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 runs: everyone's runs with filters, one run's chain, the owner's files

Adarsh6d994149c760
diff --git a/docs/admin-api.md b/docs/admin-api.md
index 8f5c9ea6..3626b93c 100644
--- a/docs/admin-api.md
+++ b/docs/admin-api.md
@@ -37,9 +37,9 @@ Keep the token out of URLs, logs and shared files. Send it only in the `Authoriz
| `accounts:read` | `GET /api/admin/accounts` (JSON or CSV), `GET /api/admin/accounts/{id}` |
| `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`: accounts' runs, each one's facts only (when, which model and app, how it ended, how many results). Never the owner's own runs |
+| `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:delete` | `DELETE /api/admin/generations/{id}`: a run still going is canceled first |
-| `outputs:view` | `GET /api/admin/files/{path}`: an account's stored file, held ones too (never the owner's own). Each view is logged. With `runs:read`, the runs' prompts, inputs and results too |
+| `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` |
| `outputs:moderate` | `POST /api/admin/outputs/hide`, `/unhide` and `/remove` |
| `reports:read` | `GET /api/admin/reports` (reporters' emails only with `accounts:read`) |
@@ -106,12 +106,13 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control
| `GET /api/admin/accounts/{id}` | | one account with its numbers; 404 `No such account` |
| `PATCH /api/admin/accounts/{id}` | exactly one of `{ disabled: boolean }` or `{ signOut: true }` | the account (no numbers) |
| `DELETE /api/admin/accounts/{id}` | | 204 |
-| `GET /api/admin/generations` | `account`, `status` (`finished`, `running`, `failed`), `kind` (`image`, `video`, `audio`, `model3d`, `text`), `before` (the last page's `next`), `limit` (1 to 100, default 30) | `{ items, next }`; `next` is null on the last page. 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 also has `detail`: the technical reason, which the account never sees. `account` is `{ id, email }` (`email` null: a deleted account), or `{ id, emailHidden: true }` without `accounts:read` |
+| `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 run a script said it made: `batch`, `drill`, `example`, `test`); `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); `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 |
+| `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. `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/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 }` |
-| `GET /api/admin/files/{path}` | `Range` works | the file; 404 for the owner's own files (held or not) and unknown paths |
+| `GET /api/admin/files/{path}` | `Range` works | the file, an account's or the owner's own (held ones too); 404 for unknown paths |
| `GET /api/admin/reports` | `limit` (1 to 500, default 100) | `{ items }`, newest first |
| `GET /api/admin/queue` | | `{ held, lanes, running, holding, queued, next, nextTotal, text, controls, now }`. `queued` is in the order the workers serve it, each with `rank` (null while no worker takes it), `why`, `code` (`class`, `next`, `boost`, `held`, `pinned`, `paused`), `override` and `person` (a key, never an account id). `controls`: `{ pools, workers, overrides, ended, modes }` ([gpu-workers.md](gpu-workers.md#the-queue)) |
| `POST /api/admin/queue/mode` | `{ pool?, worker?, mode, forMin? }`: `mode` is `people-first`, `people-only`, `ours-first`, `balanced`, or `null` (back to normal); `forMin` is 1 to 10080, or `null` (until switched back) | `{ mode, before }`; 400 for a value out of bounds, 404 for no such worker |
@@ -140,7 +141,7 @@ the values before and after), `queue.mode`, `queue.override`, `queue.override.en
`token.revoke_all`, `settings.comfy_where` (where ComfyUI runs, 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
every 10 minutes); reads of accounts' content by a token or the owner: `runs.content` (one row per reader and account
-every 10 minutes, the account as its target) and `file.view` (one row per reader and file every hour); refusals
+every 10 minutes, the account as its target, or `owner` for the owner's own runs) and `file.view` (one row per reader and file every hour); refusals
`scope.denied` and `rate.limited`; and the studio's own alerts `worker.alert` (actor `system`: a worker's token used
from a new country, a new network, or two networks at once; [gpu-workers.md](gpu-workers.md#the-protocol)) and
`runs.waiting` (actor `system`, at most once every 5 minutes: runs on this install's GPUs that have waited longer than
diff --git a/docs/cli.md b/docs/cli.md
index 4bb22912..9b17e73b 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -351,7 +351,9 @@ server too (`fuobe mcp`).
For script writers who'd rather call the API directly: `GET /api/models` (`kind`, `engine`, `op`,
`q`, `hidden=1`; it answers with the studios' `defaults` per engine, `demoMode`, and per model
`connected` and `runs`), `POST /api/generations` (with `?preview=1` to price; a model id Fuobe has
-retired runs on the model that replaced it, and the answer gives that `modelId` with `notes` saying so),
+retired runs on the model that replaced it, and the answer gives that `modelId` with `notes` saying so;
+a script can say what made the run with `source`: `batch`, `drill`, `example` or `test`, which the admin runs
+list tells apart from `hands-on` runs),
`GET /api/generations[/<id>]`,
`POST /api/generations/<id>/cancel`, `POST /api/uploads` (multipart `file`), `GET /api/files/…`,
`GET /api/status`, `GET|PATCH /api/assist/skills[/<name>]`, `POST /api/assist/skills/upload`
diff --git a/src/app/api/admin/files/[...path]/route.ts b/src/app/api/admin/files/[...path]/route.ts
index 20dfcb78..4be4c854 100644
--- a/src/app/api/admin/files/[...path]/route.ts
+++ b/src/app/api/admin/files/[...path]/route.ts
@@ -6,9 +6,10 @@ import { fileResponse } from "@/server/file-response";
const NO_STORE = { "Cache-Control": "no-store" };
/**
- * An account's stored file, for an admin token with outputs:view (or the owner): the path as in an output's url after
- * /api/files/. Accounts' files only, held ones too (waiting for their check, or hidden: what moderation has to see);
- * the owner's own files, held or not, and unknown paths are a 404. Every view by a token is logged. Byte ranges work.
+ * A stored file, for an admin token with outputs:view (or the owner): the path as in an output's url after /api/files/.
+ * Accounts' files, held ones too (waiting for their check, or hidden: what moderation has to see), and the owner's own
+ * (the admin list's Ours: its runs' inputs and results). Unknown paths are a 404. Every view by a token is logged, with
+ * the account (or "owner"). Byte ranges work.
*/
export async function GET(request: Request, ctx: RouteContext<"/api/admin/files/[...path]">) {
await connection();
@@ -18,7 +19,7 @@ export async function GET(request: Request, ctx: RouteContext<"/api/admin/files/
// Next has decoded each segment once already: decoding again would turn %252e into "." (stored names never need it).
const rel = parts.join("/");
const file = fileRecord(rel);
- if (!file?.account) return Response.json({ error: "Not found" }, { status: 404, headers: NO_STORE });
- auditFileView(access.actor, rel, file.account, file.held);
+ if (!file) return Response.json({ error: "Not found" }, { status: 404, headers: NO_STORE });
+ auditFileView(access.actor, rel, file.account ?? "owner", file.held);
return fileResponse(request, rel, { cache: "no-store" });
}
diff --git a/src/app/api/admin/generations/[id]/route.ts b/src/app/api/admin/generations/[id]/route.ts
index db07f5ed..9f3a1af2 100644
--- a/src/app/api/admin/generations/[id]/route.ts
+++ b/src/app/api/admin/generations/[id]/route.ts
@@ -7,11 +7,11 @@ import { runDetails } from "@/server/run-details";
const NO_STORE = { "Cache-Control": "no-store" };
/**
- * One account's run in full, for the owner's Run details (owner 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, and its batch and the account's 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. The owner's own runs aren't here
- * (404): they are in the Library. Each read is in the admin log with the account as its target.
+ * One run in full, an account's, a guest's or the owner's own, for the owner's Run details and the admin panel (owner
+ * 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.
*/
export async function GET(request: Request, ctx: RouteContext<"/api/admin/generations/[id]">) {
await connection();
@@ -22,7 +22,7 @@ export async function GET(request: Request, ctx: RouteContext<"/api/admin/genera
const { id } = await ctx.params;
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], { run: id });
+ auditContentRead(access.actor, "runs.content", [details.run.account?.id ?? "owner"], { run: id });
return Response.json(details, { headers: NO_STORE });
}
diff --git a/src/app/api/admin/generations/route.ts b/src/app/api/admin/generations/route.ts
index a26d1f5f..70e4ccf2 100644
--- a/src/app/api/admin/generations/route.ts
+++ b/src/app/api/admin/generations/route.ts
@@ -1,17 +1,21 @@
import { connection } from "next/server";
-import { accountRunOptions, listAccountRuns } from "@/server/account-admin";
+import { accountRunOptions, listAdminRuns } from "@/server/account-admin";
import { actorHas, adminAccess, auditContentRead, auditRead } from "@/server/admin-tokens";
const NO_STORE = { "Cache-Control": "no-store" };
/**
- * Accounts' runs (owner only, or an admin token with runs:read), newest first: `?account=<id>` (else every account's),
- * `status` (finished, running, failed), `kind` (image, video, audio, model3d, text), `before=<createdAt>:<id>` (the
- * `next` of the last page) and `limit` (≤ 100). Never the owner's own runs: those are in the Library.
+ * Runs (owner only, or an admin token with runs:read), newest first: `?account=<id>`, else `whose` (`people`: every
+ * account's and guest's, the default; `ours`: the owner's own; `everyone`), `source` (the owner's runs: `hands-on` or
+ * `batch`), `where` (`pool`, `provider`, `own`), `status` (`finished` or `done`, `failed`, `canceled`, `waiting`,
+ * `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`.
*
* 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
- * the admin log, once per account every 10 minutes, with the account as its target.
+ * the admin log, once per account every 10 minutes, with the account (or "owner") as its target.
*/
export async function GET(request: Request) {
await connection();
@@ -21,9 +25,20 @@ export async function GET(request: Request) {
const o = accountRunOptions(sp);
if ("error" in o) return Response.json({ error: o.error }, { status: 400, headers: NO_STORE });
const show = { content: actorHas(access.actor, "outputs:view"), emails: actorHas(access.actor, "accounts:read") };
- const page = listAccountRuns(o, show);
- const filters = { ...(o.account && { account: o.account }), ...(sp.get("status") && { status: sp.get("status") }), ...(o.kind && { kind: o.kind }) };
+ const page = listAdminRuns(o, show);
+ const filters = {
+ ...(o.account && { account: o.account }),
+ ...(o.whose !== "people" && { whose: o.whose }),
+ ...(o.source && { source: o.source }),
+ ...(o.where && { where: o.where }),
+ ...(sp.get("status") && { status: sp.get("status") }),
+ ...(o.kind && { kind: o.kind }),
+ ...(o.modelLike && { model: o.modelLike }),
+ ...(o.q && { q: true }),
+ ...(sp.get("from") && { from: sp.get("from") }),
+ ...(sp.get("to") && { to: sp.get("to") }),
+ };
auditRead(access.actor, "runs.list", filters);
- if (show.content) auditContentRead(access.actor, "runs.content", page.items.map((r) => r.account.id), 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 });
}
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index 36c22314..66374708 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -180,7 +180,7 @@ export async function POST(request: Request) {
// or key only (src/lib/own-setup.ts), as on the Genjutsu page: an account's run goes there (accountRun answers Connect
// your GPU or Add your key when it has neither), a run on this install's GPUs is refused with the setup's label
// (hosted-run.ts poolGate), and a guest signs up first. Never this studio's own GPU for a visitor.
- let req = account ? { ...asked, account: account.id, engine: accountEngineMode(account.id) === "open" ? ("open" as const) : asked.engine } : { ...asked, account: undefined };
+ let req = account ? { ...asked, account: account.id, source: undefined, engine: accountEngineMode(account.id) === "open" ? ("open" as const) : asked.engine } : { ...asked, account: undefined };
const onOwn = <T,>(fn: () => T): T => (account ? asAccount(account.id, fn) : fn());
// A visitor's price check: priced as it would run, as that visitor (an account: its own GPU and keys; a guest: the open
// engine, no demo).
diff --git a/src/components/run-details.tsx b/src/components/run-details.tsx
index 97d5c4fa..9bd7118a 100644
--- a/src/components/run-details.tsx
+++ b/src/components/run-details.tsx
@@ -18,7 +18,7 @@ import { OPERATION_LABELS, type Generation } from "@/lib/catalog/types";
import { elapsed, formatCost, timeAgo } from "@/lib/format";
import type { SettingRow, SettingState } from "@/lib/run-settings";
import { cn } from "@/lib/utils";
-import type { AccountRun } from "@/server/account-admin";
+import type { AccountRun, AdminRun } from "@/server/account-admin";
import type { NearRun, RunDetails, RunInput, RunJob, RunMadeBy, RunMoney, RunTiming, WorkerEvent } from "@/server/run-details";
/** The address of a run's details page. */
@@ -112,15 +112,17 @@ export function RunDetailsView() {
const d = q.data;
const g = d.run;
- const email = g.account.email;
+ const email = g.account ? g.account.email : undefined;
return (
<>
<PageHeader
title={d.preset?.name ?? g.presetName ?? d.studio?.title ?? featureName(g.feature)}
description={
<>
- {email ? (
- <Link href={runsHref({ account: g.account.id })} className="underline-offset-2 hover:underline">
+ {g.whose === "owner" ? (
+ "Your own run"
+ ) : email ? (
+ <Link href={runsHref({ account: g.account!.id })} className="underline-offset-2 hover:underline">
{email}
</Link>
) : email === null ? (
@@ -460,7 +462,7 @@ function Inputs({ inputs }: { inputs: RunInput[] }) {
* What the account was shown for this run: its studio feed's tile and its Library card, made by the same components
* its own pages use (inert: nothing here runs anything). A finished run shows its results.
*/
-function Seen({ g }: { g: AccountRun }) {
+function Seen({ g }: { g: AdminRun }) {
const run = g as unknown as Generation;
if (g.status === "succeeded") {
const outs = g.outputs.filter((o) => o.state === "shown");
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index d7f10a69..7c570d33 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -1353,6 +1353,11 @@ export interface GenerationRequest {
title?: string;
/** Server-set: the name of the batch it belongs to (an Assist plan's summary): the Library stack's title. */
batchTitle?: string;
+ /**
+ * Where an owner's run came from, as the script or runner that made it said (POST /api/generations): "hands-on" (none
+ * said), or a batch, drill, example or test run. The admin runs list tells them apart. An account's run never has one.
+ */
+ source?: RunSource;
/**
* Server-set: made by a run of a skill's recipe (src/lib/recipe.ts): the skill's name and the run's id (its batch), so
* a run's history can be read back. Stripped from API input, like chainFilled.
@@ -1786,3 +1791,7 @@ export interface PrestepRoute {
/** Route endpoint for models without an extend API: last frame → image-to-video → join (src/server/chains.ts). */
export const LAST_FRAME_CHAIN = "chain:last-frame";
+
+/** Where an owner's run came from (GenerationRequest.source). */
+export const RUN_SOURCES = ["hands-on", "batch", "drill", "example", "test"] as const;
+export type RunSource = (typeof RUN_SOURCES)[number];
diff --git a/src/server/account-admin.ts b/src/server/account-admin.ts
index 3b063c77..2c745b3b 100644
--- a/src/server/account-admin.ts
+++ b/src/server/account-admin.ts
@@ -1,6 +1,6 @@
import "server-only";
import path from "node:path";
-import type { Generation, OutputFile } from "@/lib/catalog/types";
+import type { Generation, OutputFile, RunSource } from "@/lib/catalog/types";
import { accountsMaxBytes, accountTotalBytes } from "./account-files";
import { listAccounts, type AccountInfo } from "./auth";
import { db } from "./db";
@@ -94,30 +94,66 @@ export function accountsWithStats(items: AccountInfo[] = listAccounts(), now = D
};
}
-/** The status filter's choices: a canceled run shows under "any status" only. */
+/**
+ * The status filter's choices: `finished` (or `done`), `failed`, `canceled`, `waiting` (in line, not started),
+ * `started` (working now) and `running` (both of those, as before).
+ */
const STATUSES = new Map<string, Generation["status"][]>([
["finished", ["succeeded"]],
+ ["done", ["succeeded"]],
["running", ["queued", "running"]],
+ ["waiting", ["queued"]],
+ ["started", ["running"]],
["failed", ["failed"]],
+ ["canceled", ["canceled"]],
]);
export const RUNS_PAGE = 30;
const MAX_RUNS_PAGE = 100;
+const DATE = /^\d{4}-\d{2}-\d{2}$/;
+
+/** Whose runs a list holds: `people` (accounts' and guests'), `ours` (the owner's own) or `everyone` (both). */
+export type RunsWhose = "people" | "ours" | "everyone";
+
+/** A yyyy-mm-dd day's start in UTC (ms), or undefined for anything else. */
+function dayStart(v: string | null): number | undefined {
+ if (!v || !DATE.test(v)) return undefined;
+ const t = Date.parse(`${v}T00:00:00Z`);
+ return Number.isFinite(t) ? t : undefined;
+}
/**
- * GET /api/admin/generations query → listGenerations options: `account` (one account, else every account's), `status`
- * (finished, running, failed), `kind`, `before=<createdAt>:<id>` and `limit` (≤ 100). Unknown statuses and kinds are
- * ignored, as the Library's list ignores them.
+ * GET /api/admin/generations query → listGenerations options: `account` (one account), else `whose` (`people`: every
+ * account's and guest's, the default; `ours`: the owner's own; `everyone`), `source` (the owner's runs only: `hands-on`
+ * or `batch`), `where` (`pool`, `provider`, `own`), `status` (STATUSES), `kind`, `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), `before=<createdAt>:<id>` and
+ * `limit` (≤ 100). Unknown values are ignored, as the Library's list ignores them.
*/
-export function accountRunOptions(sp: URLSearchParams): ListOptions | { error: string } {
+export function accountRunOptions(sp: URLSearchParams): (ListOptions & { whose: RunsWhose }) | { error: string } {
const account = sp.get("account")?.trim();
if (account && !/^[\w-]{1,40}$/.test(account)) return { error: "Pick an account" };
const kind = sp.get("kind") ?? "";
const asked = Math.trunc(Number(sp.get("limit")));
+ const source = sp.get("source");
+ const askedWhose = sp.get("whose");
+ // A source names the owner's runs, so it means Ours.
+ const whose: RunsWhose = account ? "people" : source === "hands-on" || source === "batch" ? "ours" : askedWhose === "ours" || askedWhose === "everyone" ? askedWhose : "people";
+ const where = sp.get("where");
+ const model = sp.get("model")?.trim().slice(0, 80);
+ const q = sp.get("q")?.trim().slice(0, 200);
+ const from = dayStart(sp.get("from"));
+ const to = dayStart(sp.get("to"));
return {
- ...(account ? { account } : { accounts: true }),
+ ...(account ? { account } : whose === "people" ? { accounts: true } : whose === "everyone" ? { everyone: true } : {}),
+ whose,
+ ...((source === "hands-on" || source === "batch") && { source }),
+ ...((where === "pool" || where === "provider" || where === "own") && { where }),
statuses: STATUSES.get(sp.get("status") ?? ""),
kind: KINDS.has(kind) ? kind : undefined,
+ ...(model && { modelLike: model }),
+ ...(q && { q }),
+ ...(from !== undefined && { since: from }),
+ ...(to !== undefined && { until: to + DAY }),
...cursorFrom(sp.get("before")),
limit: sp.get("limit") && Number.isFinite(asked) ? Math.max(1, Math.min(asked, MAX_RUNS_PAGE)) : RUNS_PAGE,
};
@@ -133,8 +169,18 @@ export type OutputState = "shown" | "held" | "removed";
* An account's run as the owner sees it: whose it is (null email: the account was deleted; no `email` and
* `emailHidden: true`: a reader that may not see emails), and each result's state. A run on this install's GPUs also
* carries `detail`: the technical reason it failed, which the account never sees (its own page shows one plain sentence).
+ * `whose`: an account's, a guest's (an account id that starts with "guest") or, in AdminRun, the owner's own.
+ */
+export type AccountRun = Omit<Generation, "outputs"> & { outputs: (OutputFile & { state: OutputState })[]; account: AccountOfRun; whose: RunWhose; detail?: string };
+
+/** Whose a run is. */
+export type RunWhose = "account" | "guest" | "owner";
+
+/**
+ * A run in the owner's admin list: an account's or a guest's (as AccountRun), or the owner's own (`account` null, `whose`
+ * "owner", and `source`: what made it, "hands-on" when its runner said nothing).
*/
-export type AccountRun = Omit<Generation, "outputs"> & { outputs: (OutputFile & { state: OutputState })[]; account: AccountOfRun; detail?: string };
+export type AdminRun = Omit<AccountRun, "account"> & { account: AccountOfRun | null; source?: RunSource };
/** Whose a run is: its email (null: the account was deleted), or no email and `emailHidden` for a reader that may not see emails. */
export type AccountOfRun = { id: string; email?: string | null; emailHidden?: true };
@@ -156,11 +202,11 @@ function withStates(outputs: OutputFile[]): (OutputFile & { state: OutputState }
* how many results, never its prompt, its inputs, its results' files or words, or its technical reason.
*/
export type AccountRunFacts = Pick<
- AccountRun,
- "id" | "batchId" | "feature" | "presetId" | "presetName" | "modelId" | "modelName" | "engine" | "provider" | "op" | "kind" | "status" | "progress" | "costUsd" | "createdAt" | "updatedAt" | "completedAt" | "place" | "account"
+ AdminRun,
+ "id" | "batchId" | "feature" | "presetId" | "presetName" | "modelId" | "modelName" | "engine" | "provider" | "op" | "kind" | "status" | "progress" | "costUsd" | "createdAt" | "updatedAt" | "completedAt" | "place" | "account" | "whose" | "source"
> & { outputs: { kind: OutputFile["kind"]; state: OutputState }[] };
-function factsOnly(r: AccountRun): AccountRunFacts {
+function factsOnly(r: AdminRun): AccountRunFacts {
return {
id: r.id,
batchId: r.batchId,
@@ -181,6 +227,8 @@ function factsOnly(r: AccountRun): AccountRunFacts {
completedAt: r.completedAt,
...(r.place && { place: r.place }),
account: r.account,
+ whose: r.whose,
+ ...(r.source && { source: r.source }),
outputs: r.outputs.map((x) => ({ kind: x.kind, state: x.state })),
};
}
@@ -189,29 +237,58 @@ function factsOnly(r: AccountRun): AccountRunFacts {
* One page of accounts' runs, newest first, and the cursor of the next (null on the last page). Never the owner's.
* `show.content` false: each run's facts only (factsOnly); `show.emails` false: no account's email.
*/
-export function listAccountRuns(o: ListOptions): { items: AccountRun[]; next: string | null };
-export function listAccountRuns(o: ListOptions, show: { content: boolean; emails: boolean }): { items: (AccountRun | AccountRunFacts)[]; next: string | null };
-export function listAccountRuns(o: ListOptions, show: { content: boolean; emails: boolean } = { content: true, emails: true }): { items: (AccountRun | AccountRunFacts)[]; next: string | null } {
+export function listAccountRuns(o: ListOptions): { items: AccountRun[]; next: string | null } {
const limit = o.limit ?? RUNS_PAGE;
- const opts: ListOptions = o.account ? { ...o, accounts: undefined, limit } : { ...o, account: undefined, accounts: true, limit };
+ const opts: ListOptions = o.account ? { ...o, accounts: undefined, everyone: undefined, source: undefined, limit } : { ...o, account: undefined, accounts: true, everyone: undefined, source: undefined, limit };
const emails = new Map(listAccounts().map((a) => [a.id, a.email]));
// The WHERE already leaves the owner's runs out; this keeps them out whatever a caller passes.
const found = listGenerations(opts).filter((g) => g.request.account);
const last = found.at(-1);
+ return { items: found.map((g) => asAccountRun(g, emails, true)), next: last && found.length === limit ? `${last.createdAt}:${last.id}` : null };
+}
+
+/**
+ * One page of the owner's admin list of runs (GET /api/admin/generations), newest first, and the cursor of the next:
+ * accounts' and guests' runs, the owner's own, or both (`whose`). `show.content` false: each run's facts only
+ * (factsOnly); `show.emails` false: no account's email.
+ */
+export function listAdminRuns(o: ListOptions & { whose?: RunsWhose }, show: { content: boolean; emails: boolean } = { content: true, emails: true }): { items: (AdminRun | AccountRunFacts)[]; next: string | null } {
+ const limit = o.limit ?? RUNS_PAGE;
+ const whose = o.account ? "people" : (o.whose ?? "people");
+ const rest: ListOptions = { ...o };
+ delete (rest as { whose?: RunsWhose }).whose;
+ const opts: ListOptions =
+ whose === "people"
+ ? { ...rest, ...(o.account ? { accounts: undefined } : { accounts: true }), everyone: undefined, source: undefined, limit }
+ : whose === "ours"
+ ? { ...rest, account: undefined, accounts: undefined, everyone: undefined, limit }
+ : { ...rest, account: undefined, accounts: undefined, everyone: true, source: undefined, limit };
+ const emails = new Map(listAccounts().map((a) => [a.id, a.email]));
+ const found = listGenerations(opts).filter((g) => (whose === "people" ? !!g.request.account : whose === "ours" ? !g.request.account : true));
+ const last = found.at(-1);
return {
items: found.map((g) => {
- const run = asAccountRun(g, emails, show.emails);
+ const run = asAdminRun(g, emails, show.emails);
return show.content ? run : factsOnly(run);
}),
next: last && found.length === limit ? `${last.createdAt}:${last.id}` : null,
};
}
+/** Whose a run is, from its stamped account (none: the owner's own; a "guest…" id: a guest's). */
+export const runWhose = (account: string | null | undefined): RunWhose => (!account ? "owner" : account.startsWith("guest") ? "guest" : "account");
+
/** An account's run (`g.request.account` set) as the owner sees it: whose, each result's state, and a hosted run's technical reason. */
function asAccountRun(g: Generation, emails: Map<string, string>, showEmails: boolean): AccountRun {
const id = g.request.account!;
const account: AccountOfRun = showEmails ? { id, email: emails.get(id) ?? null } : { id, emailHidden: true };
- return { ...g, outputs: withStates(g.outputs), account, ...poolDetail(g), ...declinedCardsIn(g.id) };
+ return { ...g, outputs: withStates(g.outputs), account, whose: runWhose(id), ...poolDetail(g), ...declinedCardsIn(g.id) };
+}
+
+/** Any run as the owner's admin list has it: an account's (asAccountRun), or the owner's own with its source. */
+function asAdminRun(g: Generation, emails: Map<string, string>, showEmails: boolean): AdminRun {
+ if (g.request.account) return asAccountRun(g, emails, showEmails);
+ return { ...g, outputs: withStates(g.outputs), account: null, whose: "owner", source: g.request.source ?? "hands-on", ...ownDetail(g), ...declinedCardsIn(g.id) };
}
/**
@@ -225,9 +302,23 @@ function poolDetail(g: Generation): { detail?: string } {
return row?.error && row.error !== g.error ? { detail: row.error } : {};
}
+/** The owner's own failed run: its stored technical detail, when it has one. */
+function ownDetail(g: Generation): { detail?: string } {
+ if (!g.error) return {};
+ const row = db().prepare("SELECT detail FROM generations WHERE id = ?").get(g.id) as { detail: string | null } | undefined;
+ return row?.detail ? { detail: row.detail } : {};
+}
+
/** One account's run as the list gives it (null: no such run, or it is the owner's own). */
export function accountRunById(id: string, showEmails = true): AccountRun | null {
const g = getGeneration(id, { includeDeleted: true });
if (!g?.request.account) return null;
return asAccountRun(g, new Map(listAccounts().map((a) => [a.id, a.email])), showEmails);
}
+
+/** Any run as the owner's admin list gives it, the owner's own too (null: no such run). */
+export function adminRunById(id: string, showEmails = true): AdminRun | null {
+ const g = getGeneration(id, { includeDeleted: true });
+ if (!g) return null;
+ return asAdminRun(g, new Map(listAccounts().map((a) => [a.id, a.email])), showEmails);
+}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index d3310d54..920f1d43 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -727,6 +727,17 @@ export interface ListOptions {
account?: string;
/** Every account's runs, never the owner's: the owner's view of what accounts make (src/server/account-admin.ts). */
accounts?: boolean;
+ /** Everyone's runs, the owner's and every account's (the owner's admin view); `account` and `accounts` win over it. */
+ everyone?: boolean;
+ /**
+ * Where it ran: "pool" (this install's GPUs: hosted runs, and the owner's runs on the install's ComfyUI), "provider" (a
+ * cloud provider: fal, Replicate…), "own" (an account's own GPU).
+ */
+ where?: "pool" | "provider" | "own";
+ /** A model id that holds these letters. */
+ modelLike?: string;
+ /** The owner's runs only, by `request.source`: "hands-on" (none set, or "hands-on") or "batch" (any other source). */
+ source?: "hands-on" | "batch";
/** Date range on createdAt: since ≤ t < until. */
since?: number;
until?: number;
@@ -746,7 +757,16 @@ export function listGenerations(o: ListOptions = {}): Generation[] {
if (o.account) add("json_extract(g.request_json, '$.account') = ?", o.account);
// A range rather than IS NOT NULL: SQLite can search the generations_account index for a range (it scans it whole for IS NOT NULL).
else if (o.accounts) add("json_extract(g.request_json, '$.account') > ''");
- else add("json_extract(g.request_json, '$.account') IS NULL");
+ else if (!o.everyone) add("json_extract(g.request_json, '$.account') IS NULL");
+ if (o.source) {
+ add("json_extract(g.request_json, '$.account') IS NULL");
+ add(`COALESCE(json_extract(g.request_json, '$.source'), 'hands-on') ${o.source === "hands-on" ? "=" : "<>"} 'hands-on'`);
+ }
+ const place = "COALESCE(json_extract(g.request_json, '$.place'), '')";
+ if (o.where === "pool") add(`(${place} = 'pool' OR (json_extract(g.request_json, '$.account') IS NULL AND g.provider = 'comfyui'))`);
+ else if (o.where === "provider") add(`${place} <> 'pool' AND g.provider NOT IN ('comfyui', 'mock')`);
+ else if (o.where === "own") add(`${place} <> 'pool' AND g.provider = 'comfyui' AND json_extract(g.request_json, '$.account') > ''`);
+ if (o.modelLike) add("g.model_id LIKE ? ESCAPE '!'", `%${o.modelLike.replace(/[!%_]/g, (c) => `!${c}`)}%`);
if (o.batchId) add("g.batch_id = ?", o.batchId);
if (o.feature) add("g.feature = ?", o.feature);
if (o.features?.length) add(`(${o.features.map(() => "g.feature LIKE ?").join(" OR ")})`, ...o.features.map(featureLike));
@@ -778,7 +798,8 @@ export function listGenerations(o: ListOptions = {}): Generation[] {
if (o.until) add("g.created_at < ?", o.until);
const q = o.q?.trim();
// The user's own words (request.prompt) and what the model got (prompt, with suffixes and templates).
- if (q) add("(g.prompt LIKE ? OR json_extract(g.request_json, '$.prompt') LIKE ?)", `%${q}%`, `%${q}%`);
+ // A run's own id finds it too.
+ if (q) add("(g.id = ? OR g.prompt LIKE ? OR json_extract(g.request_json, '$.prompt') LIKE ?)", q, `%${q}%`, `%${q}%`);
// Every account's runs: from the accounts' entries in generations_account, then sorted (they go after 30 days, so they
// stay few). Left to its own plan, SQLite walks every run newest first (or every run of a status), the owner's too,
// until the page is full: the whole table when accounts' runs are few or none match. Without the index (db.ts goes
diff --git a/src/server/request-schema.ts b/src/server/request-schema.ts
index 80e63eb6..5ebdb2fd 100644
--- a/src/server/request-schema.ts
+++ b/src/server/request-schema.ts
@@ -1,7 +1,7 @@
import "server-only";
import { z } from "zod";
import { FORMAT_INFO } from "@/lib/av/formats";
-import type { VideoFormat } from "@/lib/catalog/types";
+import { RUN_SOURCES, type VideoFormat } from "@/lib/catalog/types";
import { LATENT_EXTRA } from "@/lib/catalog/regenerate";
import { SignatureSchema } from "./palettes";
@@ -162,4 +162,6 @@ export const GenerationRequestSchema = z.object({
// What a tool calls its result (Trim · 0:01.0–0:02.5, Captions · Karaoke), shown instead of the prompt.
title: z.string().max(200).optional(),
batchTitle: z.string().max(200).optional(),
+ // An owner's script or runner says what made the run (a batch, a drill…); an account's run drops it.
+ source: z.enum(RUN_SOURCES).optional(),
});
diff --git a/src/server/run-details.ts b/src/server/run-details.ts
index abc2a2e3..7e3a1bb0 100644
--- a/src/server/run-details.ts
+++ b/src/server/run-details.ts
@@ -10,12 +10,12 @@ import type { RunTrouble } from "@/lib/diagnose";
import { compareSettings, LINK_WORDS, SECRET_KEY, linkKind, redactText, redactValue, runMatch, type LinkKind, type RunMatch, type SettingRow } from "@/lib/run-settings";
import * as STUDIOS from "@/lib/studios";
import { viewerDefaults } from "@/lib/composer";
-import { accountRunById, type AccountRun } from "./account-admin";
+import { adminRunById, type AdminRun } from "./account-admin";
import { fileAccount } from "./account-library";
import { accountGpu } from "./auth";
import { db } from "./db";
import { exampleRel } from "./example-files";
-import { listGenerations } from "./generations";
+import { getGeneration, listGenerations } from "./generations";
import type { OwnRunNote } from "./run-events";
import { absolutePath, contentTypeFor, filesRel } from "./storage";
@@ -101,7 +101,7 @@ export interface NearRun {
export interface RunDetails {
/** The run as the account's own feed has it (its words, trouble, buttons), with whose it is and each result's state. */
- run: AccountRun;
+ run: AdminRun;
/**
* The stored status words and error (the account may have read a plainer sentence: a hosted run's), without addresses
* or credentials. `detail`: the engine's own words (cleaned) behind a plain sentence, for the owner only.
@@ -125,6 +125,8 @@ export interface RunDetails {
batch: NearRun[];
/** The account's other runs from 2 hours before to 6 hours after it, oldest first (helper steps left out). */
near: NearRun[];
+ /** Its chain: the earlier steps it waits for or took inputs from (`before`), and the later steps that wait for it (`after`), oldest first. */
+ chain: { before: NearRun[]; after: NearRun[] };
/** What was sent to the GPU or provider (the graph or the request), redacted; null when nothing was sent. */
sent: unknown;
/** When it was pressed, sent, started and ended, and how long it waited and ran. */
@@ -281,15 +283,17 @@ function gpuNow(account: string): { kind: GpuHostKind | "none"; url?: string } {
return { kind: linkKind(gpu.url), url: gpu.url };
}
-function whereOf(run: AccountRun, raw: RawRow, gpu: ReturnType<typeof gpuNow>): RunWhere {
+function whereOf(run: AdminRun, raw: RawRow, gpu: ReturnType<typeof gpuNow>): RunWhere {
const meta = obj(parse(raw.external_meta_json));
const note = obj(meta.ownRun) as Partial<OwnRunNote>;
const heal = obj(meta.heal);
- const pool = run.place === "pool";
+ // The owner's own run on ComfyUI ran on this install's GPUs.
+ const pool = run.place === "pool" || (run.whose === "owner" && run.provider === "comfyui");
const own = !pool && run.provider === "comfyui";
const key = !pool && (run.provider === "fal" || run.provider === "replicate");
const kind: RunPlaceKind = pool ? "site-gpus" : own ? "own-gpu" : key ? "own-key" : "unknown";
- const label = pool ? "This site's GPUs" : own ? "Its own GPU" : key ? `Its own ${run.provider === "fal" ? "fal.ai key" : "Replicate token"}` : run.provider;
+ const ownerKey = run.whose === "owner" ? (run.provider === "fal" ? "fal.ai" : run.provider === "replicate" ? "Replicate" : run.provider) : null;
+ const label = pool ? "This site's GPUs" : ownerKey ? ownerKey : own ? "Its own GPU" : key ? `Its own ${run.provider === "fal" ? "fal.ai key" : "Replicate token"}` : run.provider;
const hostKind = typeof note.hostKind === "string" && HOST_KINDS.has(note.hostKind as GpuHostKind) ? (note.hostKind as GpuHostKind) : undefined;
const said = str(note.said);
return {
@@ -389,12 +393,12 @@ function studioOf(feature: string): { title: string; feature: string; defaultMod
* The model the composer would have opened on for this run: an app's or a camera motion's first route on its engine,
* else its studio's default (or the stand-in it names where the server writes no caption). Unknown otherwise.
*/
-function modelChoice(run: AccountRun, chosen: string = run.modelId): RunDetails["model"] {
+function modelChoice(run: AdminRun, chosen: string = run.modelId): RunDetails["model"] {
const picked = modelPicked(run, chosen);
return { ...picked, ...(chosen !== run.modelId && { ranOn: { id: run.modelId, name: run.modelName ?? run.modelId } }) };
}
-function modelPicked(run: AccountRun, chosen: string): RunDetails["model"] {
+function modelPicked(run: AdminRun, chosen: string): RunDetails["model"] {
const name = chosen === run.modelId ? (run.modelName ?? run.modelId) : (getModel(chosen)?.name ?? chosen);
const preset = run.presetId ? getPreset(run.presetId) : undefined;
const has = (id: string) => !!getModel(id);
@@ -503,7 +507,7 @@ const DECLINED_STAGE_WORDS: Record<string, string> = {
};
/** How a run was made: Auto's pick, Ideogram 4's declines and the model after them, and the notices it carries. */
-export function madeByOf(run: AccountRun, meta: Record<string, unknown>): RunMadeBy {
+export function madeByOf(run: AdminRun, meta: Record<string, unknown>): RunMadeBy {
const req = run.request;
const pick = req.modelId === AUTO_IMAGE && req.auto ? req.auto : undefined;
const d = obj(meta.declined);
@@ -633,10 +637,29 @@ function jobsOf(id: string, url?: string): { jobs: RunJob[]; log: WorkerEvent[];
};
}
+/** A run's chain: the steps its depends_on names, and the runs whose depends_on names it (made after it). */
+export function chainOf(id: string, req: GenerationRequest): RunDetails["chain"] {
+ const row = db().prepare("SELECT depends_on, created_at FROM generations WHERE id = ?").get(id) as { depends_on: string | null; created_at: number } | undefined;
+ if (!row) return { before: [], after: [] };
+ const deps = !row.depends_on ? [] : row.depends_on.startsWith("[") ? (() => { const v = parse(row.depends_on); return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []; })() : [row.depends_on];
+ const near = (ids: string[]) =>
+ ids
+ .map((g) => getGeneration(g, { includeDeleted: true }))
+ .filter((g): g is NonNullable<typeof g> => !!g)
+ .sort((a, b) => a.createdAt - b.createdAt || a.id.localeCompare(b.id))
+ .map((g) => nearOf(g, req));
+ // Later steps are made with or after it: the range keeps the search on the created_at index.
+ const later = db()
+ .prepare("SELECT id FROM generations WHERE created_at >= ? AND (depends_on = ? OR (depends_on LIKE '[%' AND depends_on LIKE ?)) ORDER BY created_at, id LIMIT 50")
+ .pluck()
+ .all(row.created_at - 60_000, id, `%"${id}"%`) as string[];
+ return { before: near(deps.slice(0, 50)), after: near(later) };
+}
+
const earliest = (xs: (number | null | undefined)[]) => xs.filter((x): x is number => typeof x === "number").sort((a, b) => a - b)[0];
/** When the run was pressed, sent, started and ended, and the waits between. */
-function timingOf(run: AccountRun, tasks: TaskFacts[], log: WorkerEvent[]): RunTiming {
+function timingOf(run: AdminRun, tasks: TaskFacts[], log: WorkerEvent[]): RunTiming {
const times = columnsOf("generation_runs").size
? (db().prepare("SELECT submitted_at, started_at FROM generation_runs WHERE id = ?").get(run.id) as { submitted_at: number | null; started_at: number | null } | undefined)
: undefined;
@@ -659,7 +682,7 @@ function timingOf(run: AccountRun, tasks: TaskFacts[], log: WorkerEvent[]): RunT
}
/** What a run cost, whether an amount was set aside and charged, and where its report stands. */
-function moneyOf(run: AccountRun, stamp: GenerationRequest): RunMoney {
+function moneyOf(run: AdminRun, stamp: GenerationRequest): RunMoney {
const report = columnsOf("billing_outbox").size
? (db().prepare("SELECT kind, done_at, gave_up, tries FROM billing_outbox WHERE key = ?").get(run.id) as { kind: string; done_at: number | null; gave_up: number; tries: number } | undefined)
: undefined;
@@ -690,7 +713,7 @@ function checksOf(id: string): RunDetails["checks"] {
}
/** A run still going: the share done, and the step its GPU last said. */
-function progressOf(run: AccountRun, tasks: TaskFacts[]): RunDetails["progress"] {
+function progressOf(run: AdminRun, tasks: TaskFacts[]): RunDetails["progress"] {
if (run.status !== "queued" && run.status !== "running") return null;
const live = [...tasks].reverse().find((t) => t.progress_json);
const p = obj(parse(live?.progress_json));
@@ -704,14 +727,15 @@ function progressOf(run: AccountRun, tasks: TaskFacts[]): RunDetails["progress"]
return { share: run.progress, ...(Object.keys(step).length > 0 && { step }) };
}
-/** The owner's view of one account's run, or null: no such run, or it is the owner's own (the Library has those). */
+/** The owner's view of one run, an account's, a guest's or the owner's own, or null: no such run. */
export function runDetails(id: string, o: { emails?: boolean } = {}): RunDetails | null {
- const run = accountRunById(id, o.emails ?? true);
+ const run = adminRunById(id, o.emails ?? true);
if (!run) return null;
- const account = run.account.id;
+ // undefined: the owner's own run (the lists below then read the owner's runs).
+ const account = run.account?.id;
const raw = db().prepare("SELECT request_json, message, error, external_id, external_meta_json, provider_input_json, fix_json, detail FROM generations WHERE id = ?").get(id) as RawRow | undefined;
if (!raw) return null;
- const gpu = gpuNow(account);
+ const gpu: ReturnType<typeof gpuNow> = account ? gpuNow(account) : { kind: "none" };
const scrub = (t: string | null) => (t ? redactText(t, { url: gpu.url }) : t);
const req = run.request;
const asked = req.asked ?? req;
@@ -741,6 +765,7 @@ export function runDetails(id: string, o: { emails?: boolean } = {}): RunDetails
.filter((g) => g.id !== run.id && !inBatch.has(g.id))
.sort((a, b) => a.createdAt - b.createdAt)
.map((g) => nearOf(g, req));
+ const chain = chainOf(id, req);
return {
run: {
@@ -772,6 +797,7 @@ export function runDetails(id: string, o: { emails?: boolean } = {}): RunDetails
inputs: inputsOf(asked),
batch,
near,
+ chain,
sent: redactValue(parse(raw.provider_input_json), { url: gpu.url }),
timing: timingOf(run, tasks, log),
jobs,
diff --git a/tests/account-runs-admin.test.ts b/tests/account-runs-admin.test.ts
index c823fe8f..ab65a3cb 100644
--- a/tests/account-runs-admin.test.ts
+++ b/tests/account-runs-admin.test.ts
@@ -3,7 +3,7 @@ import fs from "node:fs";
import path from "node:path";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { NextRequest } from "next/server";
-import type { AccountListing, AccountRun, AccountTotals } from "@/server/account-admin";
+import type { AccountListing, AdminRun, AccountTotals } from "@/server/account-admin";
import type { ListOptions } from "@/server/generations";
import { TINY_PNG } from "./helpers/fake-comfy-runner";
import { tempDir } from "./helpers/temp-dir";
@@ -95,7 +95,7 @@ const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";
const direct = (url: string, method = "GET", headers: Record<string, string> = {}) => new Request(`http://localhost:3000${url}`, { method, headers });
const ctx = (id: string) => ({ params: Promise.resolve({ id }) }) as never;
-type Listed = { items: AccountRun[]; next: string | null };
+type Listed = { items: AdminRun[]; next: string | null };
async function listed(qs = "", cookie = cookies.owner): Promise<Listed> {
const res = await runsRoute.GET(direct(`/api/admin/generations${qs ? `?${qs}` : ""}`, "GET", { cookie }));
expect(res.status).toBe(200);
@@ -245,9 +245,9 @@ describe("Settings → Accounts: what accounts make", () => {
const waiting = run(B, { status: "queued" });
const ofA = await listed(`account=${A}`);
expect(ofA.items.length).toBe(5);
- expect(ofA.items.every((g) => g.account.id === A && g.account.email === "[email protected]")).toBe(true);
+ expect(ofA.items.every((g) => g.account?.id === A && g.account.email === "[email protected]")).toBe(true);
const ofB = await listed(`account=${B}`);
- expect(ofB.items.every((g) => g.account.id === B)).toBe(true);
+ expect(ofB.items.every((g) => g.account?.id === B)).toBe(true);
expect(ids(ofB)).toEqual(expect.arrayContaining([clip, waiting]));
const statuses = async (qs: string) => new Set((await listed(qs)).items.map((g) => g.status));
@@ -265,7 +265,50 @@ describe("Settings → Accounts: what accounts make", () => {
expect(((await bad.json()) as { error: string }).error).toBe("Pick an account");
});
- it("never lists the owner's runs, and never deletes them", async () => {
+ it("lists the owner's own runs only when asked (Ours, Everyone), with their source, and filters on the server", async () => {
+ const mineHands = run(undefined, { status: "succeeded" });
+ const mineDrill = run(undefined, { status: "failed" });
+ db().prepare("UPDATE generations SET request_json = json_set(request_json, '$.source', 'drill') WHERE id = ?").run(mineDrill);
+ const guest = run("guest-abc123", { status: "canceled" });
+ const ofB = run(B, { status: "queued" });
+ db().prepare("UPDATE generations SET request_json = json_set(request_json, '$.place', 'pool'), provider = 'comfyui', prompt = 'a red velvet chair', model_id = 'oss-wan-22' WHERE id = ?").run(ofB);
+
+ const ours = await listed("whose=ours&limit=100");
+ expect(ids(ours)).toEqual(expect.arrayContaining([mineHands, mineDrill]));
+ expect(ours.items.every((g) => g.account === null && g.whose === "owner")).toBe(true);
+ const bySource = new Map(ours.items.map((g) => [g.id, (g as unknown as { source: string }).source]));
+ expect(bySource.get(mineHands)).toBe("hands-on");
+ expect(bySource.get(mineDrill)).toBe("drill");
+ expect(ids(await listed("source=hands-on&limit=100"))).toContain(mineHands);
+ expect(ids(await listed("source=hands-on&limit=100"))).not.toContain(mineDrill);
+ expect(ids(await listed("source=batch&limit=100"))).toEqual([mineDrill]);
+
+ const people = await listed("limit=100");
+ expect(ids(people)).toEqual(expect.arrayContaining([guest, ofB]));
+ expect(people.items.find((g) => g.id === guest)?.whose).toBe("guest");
+ expect(people.items.some((g) => g.whose === "owner")).toBe(false);
+ const everyone = ids(await listed("whose=everyone&limit=100"));
+ expect(everyone).toEqual(expect.arrayContaining([mineHands, mineDrill, guest, ofB]));
+
+ const canceled = await listed("status=canceled&limit=100");
+ expect(ids(canceled)).toContain(guest);
+ expect(canceled.items.every((g) => g.status === "canceled")).toBe(true);
+ expect(ids(await listed("status=waiting&limit=100"))).toContain(ofB);
+ expect(ids(await listed("status=done&whose=ours&limit=100"))).toContain(mineHands);
+ expect(ids(await listed("where=pool&limit=100"))).toContain(ofB);
+ expect(ids(await listed("where=pool&limit=100"))).not.toContain(guest);
+ expect(ids(await listed("where=own&limit=100"))).not.toContain(ofB);
+ // The owner's run on ComfyUI ran on this install's GPUs.
+ expect(ids(await listed("where=pool&whose=ours&limit=100"))).toContain(mineHands);
+ expect(ids(await listed("model=wan-2&limit=100"))).toEqual([ofB]);
+ expect(ids(await listed("q=velvet&limit=100"))).toEqual([ofB]);
+ expect(ids(await listed(`q=${mineDrill}&whose=everyone&limit=100`))).toEqual([mineDrill]);
+ const day = new Date().toISOString().slice(0, 10);
+ expect(ids(await listed(`from=${day}&to=${day}&limit=100`))).toContain(ofB);
+ expect(ids(await listed("from=2001-01-01&to=2001-01-02&limit=100"))).toEqual([]);
+ });
+
+ it("never lists the owner's runs unless asked, and never deletes them", async () => {
const mine = run(undefined, { status: "failed" });
const owners = new Set((db().prepare("SELECT id FROM generations WHERE json_extract(request_json, '$.account') IS NULL").all() as { id: string }[]).map((r) => r.id));
expect(owners.size).toBeGreaterThan(1);
@@ -273,7 +316,7 @@ describe("Settings → Accounts: what accounts make", () => {
const page = await listed(qs);
expect(page.items.length, qs).toBeGreaterThan(0);
expect(page.items.some((g) => owners.has(g.id)), qs).toBe(false);
- expect(page.items.every((g) => g.account.id && g.request.account === g.account.id), qs).toBe(true);
+ expect(page.items.every((g) => g.account?.id && g.request.account === g.account.id), qs).toBe(true);
}
const res = await remove(mine);
expect(res.status).toBe(404);
diff --git a/tests/admin-tokens.test.ts b/tests/admin-tokens.test.ts
index a23f11b6..737ceb4b 100644
--- a/tests/admin-tokens.test.ts
+++ b/tests/admin-tokens.test.ts
@@ -438,7 +438,7 @@ describe("admin tokens: accounts and files", () => {
expect((await routes.account.PATCH(req("/api/admin/accounts/nope", { token, method: "PATCH", body: { signOut: true } }), ctx({ id: "nope" }))).status).toBe(404);
});
- it("serves accounts' and held files to outputs:view, never the owner's, and logs each view", async () => {
+ it("serves accounts', held and the owner's own files to outputs:view, and logs each view", async () => {
const { token, info } = make(["outputs:view"]);
const a = auth.createAccount(`files-${++n}@example.com`, "long enough");
const mine = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload" });
@@ -455,14 +455,15 @@ describe("admin tokens: accounts and files", () => {
expect(ok.headers.get("cache-control")).toBe("no-store");
expect(Buffer.from(await ok.arrayBuffer()).equals(TINY_PNG)).toBe(true);
expect((await get(held.url)).status).toBe(200);
- expect((await get(mine.url)).status).toBe(404);
- expect((await get(mineHeld.url)).status).toBe(404);
+ // The owner's own (the panel's Ours), logged as the owner's.
+ expect((await get(mine.url)).status).toBe(200);
+ expect((await get(mineHeld.url)).status).toBe(200);
expect((await get("/api/files/outputs/none.png")).status).toBe(404);
const views = auditRows().filter((r) => r.action === "file.view" && r.token_id === info.id);
- expect(views.map((v) => JSON.parse(v.detail_json!))).toEqual([{ account: a.id }, { account: a.id, held: true }]);
+ expect(views.map((v) => JSON.parse(v.detail_json!))).toEqual([{ account: a.id }, { account: a.id, held: true }, { account: "owner" }, { account: "owner", held: true }]);
// One row per file an hour.
await get(theirs.url);
- expect(auditRows().filter((r) => r.action === "file.view" && r.token_id === info.id)).toHaveLength(2);
+ expect(auditRows().filter((r) => r.action === "file.view" && r.token_id === info.id)).toHaveLength(4);
});
it("Sign everyone out with every API token revokes admin tokens too", async () => {
diff --git a/tests/run-details.test.ts b/tests/run-details.test.ts
index 64b19f43..a6c74938 100644
--- a/tests/run-details.test.ts
+++ b/tests/run-details.test.ts
@@ -103,9 +103,32 @@ describe("Run details: the owner's view of one account's run", () => {
expect(res.headers.get("cache-control")).toBe("no-store");
});
- it("answers 404 for a run that doesn't exist and for the owner's own run", async () => {
+ it("answers 404 for a run that doesn't exist, and gives the owner's own run with no account", async () => {
expect((await get("nope")).status).toBe(404);
- expect((await get(run(undefined))).status).toBe(404);
+ const res = await get(run(undefined, { request: { source: "drill" } }));
+ expect(res.status).toBe(200);
+ const d = (await res.json()) as RunDetails;
+ expect(d.run.account).toBeNull();
+ expect(d.run.whose).toBe("owner");
+ expect(d.run.source).toBe("drill");
+ // The owner's run on the install's ComfyUI ran on this site's GPUs.
+ expect(d.where.kind).toBe("site-gpus");
+ });
+
+ it("names its chain: the earlier steps it waits for and the later steps that wait for it", async () => {
+ const first = run(A, { status: "succeeded", at: 1_000_000 });
+ const second = run(A, { status: "succeeded", at: 1_000_100 });
+ const last = run(A, { status: "queued", at: 1_000_200 });
+ db().prepare("UPDATE generations SET depends_on = ? WHERE id = ?").run(first, second);
+ db().prepare("UPDATE generations SET depends_on = ? WHERE id = ?").run(JSON.stringify([first, second]), last);
+ const d = (await (await get(second)).json()) as RunDetails;
+ expect(d.chain.before.map((r) => r.id)).toEqual([first]);
+ expect(d.chain.after.map((r) => r.id)).toEqual([last]);
+ const end = (await (await get(last)).json()) as RunDetails;
+ expect(end.chain.before.map((r) => r.id)).toEqual([first, second]);
+ expect(end.chain.after).toEqual([]);
+ const start = (await (await get(first)).json()) as RunDetails;
+ expect(start.chain.after.map((r) => r.id)).toEqual([second, last]);
});
it("needs outputs:view as well as runs:read for an admin token, and accounts:read for the email", async () => {
@@ -118,7 +141,7 @@ describe("Run details: the owner's view of one account's run", () => {
const d = (await res.json()) as RunDetails;
expect(d.run.account).toEqual({ id: A, emailHidden: true });
const owner = (await (await get(id)).json()) as RunDetails;
- expect(owner.run.account.email).toBe("[email protected]");
+ expect(owner.run.account?.email).toBe("[email protected]");
});
it("never carries a key, a token or a GPU's address", async () => {