The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Settings: show people the cleaned reason a run failed, or the plain sentence only
Adarsh2ee9df752405
diff --git a/docs/SELF-HOSTING.md b/docs/SELF-HOSTING.mdindex ac1ed698..35145a96 100644--- a/docs/SELF-HOSTING.md+++ b/docs/SELF-HOSTING.md@@ -129,6 +129,7 @@ A file that looks like the note but was changed (it has a password or a sign-in| `FUOBE_DATA_DIR` | Where the database (with the sign-in data) and files live (default `./data`). Back up `secrets.key` there with `fuobe.db`: it opens the fal.ai and Replicate keys accounts saved ([Your keys](public-signup.md#your-keys)), which must be added again without it || `FUOBE_AUTH_REIMPORT=1` | For one start only: an `auth.json` in the data folder when the server starts, after sign-in data moved into the database, replaces the database's sign-in data, instead of being set aside unread ([Sign-in data](#sign-in-data)). It counts only for the server's first look after it starts. Remove it after that start || `FUOBE_DEMO_MODE` | `off` (default: a run with nothing connected asks you to connect one) or `on` (placeholder results, for a tour: every run makes a labelled placeholder). The old `auto` reads as `off`, and a saved `auto` is cleared on start |+| `FUOBE_RUN_FAILURE_DETAIL` | What a person reads when a run of theirs on this install's GPUs fails: `full` (the plain sentence and the cleaned technical reason under it) or `friendly` (the plain sentence only). Settings → Failed runs wins over it. A new install starts with `full`; an install that already had runs or settings when this choice came keeps `friendly` (saved in its database) || `FUOBE_SKILLS_DIR` | Where Assist's built-in skills are read from (default `./skills`) || `FUOBE_ENGINE_MODE`, `FUOBE_CLOUD_PROVIDER`, `FUOBE_ENHANCE_PROVIDER`, `FUOBE_LLM_PROVIDER` | The Settings choices above || `FUOBE_LLM_CONTEXT` | Tokens of context for the local model (default `16384`): Ollama's `num_ctx`, and the context LM Studio loads a model with. `0` leaves it to the server |diff --git a/docs/admin-api.md b/docs/admin-api.mdindex 470487ab..24f08952 100644--- a/docs/admin-api.md+++ b/docs/admin-api.md@@ -50,8 +50,8 @@ Keep the token out of URLs, logs and shared files. Send it only in the `Authoriz| `queue:read` | `GET /api/admin/queue`, `GET /api/admin/queue/settings`, `GET /api/admin/queue/overrides` || `queue:write` | `PATCH /api/admin/queue/settings`: the run ceiling, the owner's wait limit, fair share, the pick allowance and the paused budget (`pausedBudgetS`: how long a run that has started may spend back in line) || `queue:control` | `POST /api/admin/queue/mode`, `POST /api/admin/queue/overrides`, `DELETE /api/admin/queue/overrides/{id}`, `POST /api/admin/queue/cancel`: who the GPUs serve first, runs and people sent first or held, and cancelling a run ([gpu-workers.md](gpu-workers.md#who-goes-first)) |-| `site:read` | `GET /api/admin/site/uploads` |-| `site:write` | `PATCH /api/admin/site/uploads`: the upload switches |+| `site:read` | `GET /api/admin/site/uploads`, `GET /api/admin/site/runs` |+| `site:write` | `PATCH /api/admin/site/uploads`: the upload switches; `PATCH /api/admin/site/runs`: what people read when a run fails || `audit:read` | `GET /api/admin/audit` |The read-only preset in Settings ticks `runs:read`, `reports:read`, `workers:read`, `queue:read` and `audit:read`:@@ -125,6 +125,8 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control| `PATCH /api/admin/queue/settings` | any of `runCeilingS: { default, lanes? }` (seconds, 60 to 86400; a given `runCeilingS` replaces the default and every lane's value), `ownerWaitLimitS` (seconds, 60 to 604800, or `null` for no limit), `fairShare` (boolean), `pickAllowanceMs` (0 to 3600000), `pausedBudgetS` (seconds, 0 to 604800) | `{ settings }`; 400 with the reason for a value out of bounds, an unknown setting or an unknown lane || `GET /api/admin/site/uploads` | | `{ switches: { soundConvert, soundTrim, videoTrim, photoConvert, photoCrop } }`: what a browser may do to a file that doesn't fit a tool before it is uploaded (convert a sound to MP3, offer a part of a sound or clip, convert or shrink a photo, offer a crop). All `true` by default. Every visitor reads the same values at `GET /api/site/uploads` || `PATCH /api/admin/site/uploads` | any of the five, each `true` or `false` | `{ switches }`; 400 with the reason for an unknown switch or a value that isn't a boolean. A switch that is off leaves that kind of file as it is: the tool says why it can't take it, and the server's checks apply. Browsers pick it up when they next load a page |+| `GET /api/admin/site/runs` | | `{ failureDetail }`: what a person reads when a run of theirs on this install's GPUs fails. `full`: the plain sentence and, under it, the cleaned technical reason (ComfyUI's own: no folders, addresses, keys or prompt text); `friendly`: the plain sentence only. Settings → Failed runs is the same choice. A new install starts with `full`; an install that had runs or settings before this choice existed keeps `friendly` |+| `PATCH /api/admin/site/runs` | `{ "failureDetail": "full" \| "friendly" }` | `{ failureDetail }`; 400 for any other body. Runs read it the next time they are shown. A person only ever sees the details of their own runs || `GET /api/admin/workers` | | `{ workers, lanes }`. Each worker adds `asked: { at, words }` or null, `jobs` (each job it holds: `{ taskId, generationId, slot, lane, laneLabel, stage, state, claimedAt, startedAt, progress, progressAt, typicalMs, etaS, owners, feature?, modelName? }`) and `lastEvent: { at, kind, event, words }` or null || `POST /api/admin/workers` | `{ name, pool? }` | 201 `{ id, token }`: the worker's token, once || `POST /api/admin/workers/{id}/update` | none | `{ worker }`: its next beat answer asks it to update now. It looks for new code at once and restarts on it after the job in hand (a person's job is never cut off). Each worker in `GET /api/admin/workers` has `update`: `state` (`current`, `updating` while behind the site's version for under 3 minutes, `behind` after), `since`, `behindMs`, `site`, `worker`, `commit` (first 12 hex), `peopleHeld`, `peopleWaiting`, `askedAt`, `words` and `needsOwner` |@@ -139,8 +141,8 @@ A log row is `{ id, at, actor: "owner" | "token" | "system", token: { id, name }`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` (withthe values before and after), `queue.mode`, `queue.override`, `queue.override.end`, `queue.cancel`, `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), `token.create`, `token.revoke`,-`token.revoke_all`, `settings.comfy_where` (where ComfyUI runs, with the values before and after); a token's reads+(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 actionevery 10 minutes); reads of accounts' content by a token or the owner: `runs.content` (one row per reader and accountevery 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); refusalsdiff --git a/src/app/api/admin/site/runs/route.ts b/src/app/api/admin/site/runs/route.tsnew file mode 100644index 00000000..677ae09f--- /dev/null+++ b/src/app/api/admin/site/runs/route.ts@@ -0,0 +1,38 @@+import { connection } from "next/server";+import { adminAccess, audit } from "@/server/admin-tokens";+import { runFailureDetail, setSetting } from "@/server/settings";++const NO_STORE = { "Cache-Control": "no-store" };+const VALUES = ["full", "friendly"] as const;++/**+ * What people read when a run of theirs fails (owner only, or an admin token with site:read): `failureDetail` is "full"+ * (the plain sentence and, under it, the cleaned technical reason) or "friendly" (the plain sentence only). The same+ * choice as Settings → Failed runs (src/server/settings.ts runFailureDetail).+ */+export async function GET(request: Request) {+ await connection();+ const access = adminAccess(request, "site:read", "Only the studio's owner sees the site's switches");+ if (access instanceof Response) return access;+ return Response.json({ failureDetail: runFailureDetail() }, { headers: NO_STORE });+}++/**+ * Change it (owner only, or an admin token with site:write): `{ failureDetail: "full" | "friendly" }`. Each change is+ * written to the admin log with the value before and after. Runs read it the next time they are shown.+ */+export async function PATCH(request: Request) {+ const access = adminAccess(request, "site:write", "Only the studio's owner changes the site's switches");+ if (access instanceof Response) return access;+ const body = (await request.json().catch(() => null)) as { failureDetail?: unknown } | null;+ const value = body && typeof body === "object" ? body.failureDetail : undefined;+ if (typeof value !== "string" || !(VALUES as readonly string[]).includes(value) || Object.keys(body ?? {}).length !== 1) {+ audit(access.actor, "site.runs", null, { keys: body && typeof body === "object" ? Object.keys(body).slice(0, 8) : [] }, 400);+ return Response.json({ error: `Send { "failureDetail": "full" } or { "failureDetail": "friendly" }` }, { status: 400, headers: NO_STORE });+ }+ const before = runFailureDetail();+ setSetting("runFailureDetail", value, { audited: true });+ const after = runFailureDetail();+ audit(access.actor, "site.runs", null, { before, after }, 200);+ return Response.json({ failureDetail: after }, { headers: NO_STORE });+}diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsxindex e238b510..dc16b4ce 100644--- a/src/components/settings-form.tsx+++ b/src/components/settings-form.tsx@@ -782,6 +782,23 @@ export function SettingsForm({ prices }: { prices?: string }) {</label></Section>+ <Section+ id="failed-runs"+ title="Failed runs"+ description="What a person reads when a run of theirs on this studio's GPUs can't finish. The details are cleaned first: no folders, addresses, keys or prompt text, and nobody sees another person's."+ >+ <ChoiceField+ id="setting-run-failure-detail"+ label="Show people"+ value={get("runFailureDetail")?.value ?? "full"}+ onChange={set("runFailureDetail")}+ options={[+ { value: "full", label: "Full details", hint: "The plain sentence, and under it what went wrong: ComfyUI's own reason, such as a node that isn't installed or a model file it doesn't have." },+ { value: "friendly", label: "Friendly only", hint: "The plain sentence only. You still read the full reason in each run's details." },+ ]}+ />+ </Section>+<Sectionid="auto-image"title="Auto image model"diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsxindex 0b49e3c6..9e39f594 100644--- a/src/components/studio/feed.tsx+++ b/src/components/studio/feed.tsx@@ -293,7 +293,11 @@ export function FailedTile({ g, ratio, onRetry, onReuse }: { g: Generation; rati<div className="flex h-full max-w-full flex-col justify-between overflow-hidden rounded-xl border bg-muted/40 p-3" style={{ aspectRatio: shape }} data-stage={g.status}><div className="flex min-h-0 flex-col gap-1 overflow-hidden">{poolFailed ? (- <p className={cn("shrink-0 text-[13px] leading-snug font-medium break-words", narrow ? "line-clamp-4" : "line-clamp-5")}>{g.error || POOL_WORDS.failed}</p>+ <>+ <p className={cn("shrink-0 text-[13px] leading-snug font-medium break-words", narrow ? "line-clamp-4" : "line-clamp-5")}>{g.error || POOL_WORDS.failed}</p>+ {/* The cleaned technical reason, when this studio shows it (Settings → Failed runs). */}+ <TroubleDetails details={g.errorDetail ? `Details: ${g.errorDetail}` : undefined} className="min-h-0" />+ </>) : (<><p className="shrink-0 text-[13px] font-medium">{g.status === "canceled" ? "Canceled" : "Couldn't generate this one"}</p>diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex d8a922cd..61218e28 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -1557,6 +1557,12 @@ export interface Generation {* help (Start your pod, Check my GPU, Replace key…; src/lib/diagnose.ts). The plain sentence is `error`.*/trouble?: RunTrouble;+ /**+ * A failed run's technical reason, cleaned (ComfyUI's own words, or the engine's: no folders, addresses, keys or+ * prompt text), shown under the plain sentence in `error`. Only while the install shows failure details to people+ * (Settings → Failed runs: "full"), and only in the run as its own person reads it.+ */+ errorDetail?: string;/*** An account's run waiting for its own GPU or key to come back (it goes on by itself): why, the buttons that help* (Start your pod, Run with your key…), and when it stops waiting.diff --git a/src/server/db.ts b/src/server/db.tsindex 3608f0b3..86ef2a55 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1173,6 +1173,24 @@ function forgetDroppedBranchMigrations(db: Database.Database): void {if (done(24) && !hasColumn("assets", "account_id") && has("trigger", "audit_log_no_delete")) forget(24);}+/** The settings row that says the choice below was made for this data folder (once, whatever it was). */+export const FAILURE_DETAIL_CHOSEN = "runs.failureDetail.chosen";++/**+ * What people read when a run fails (settings.ts runFailureDetail): a new install starts with "full", the default. An+ * install whose data folder already had migrations when this build first opened it read the plain sentence only until+ * now, and keeps it: "friendly" is saved for it, before any request is served. Done once per data folder (its marker+ * row), so the owner's later choice, either way, stays across restarts and updates.+ */+function keepFriendlyFailures(db: Database.Database, fresh: boolean): void {+ if (db.prepare("SELECT 1 FROM settings WHERE key = ?").get(FAILURE_DETAIL_CHOSEN)) return;+ db.transaction(() => {+ if (db.prepare("SELECT 1 FROM settings WHERE key = ?").get(FAILURE_DETAIL_CHOSEN)) return;+ if (!fresh) db.prepare("INSERT OR IGNORE INTO settings (key, value) VALUES ('runs.failureDetail', 'friendly')").run();+ db.prepare("INSERT INTO settings (key, value) VALUES (?, '1')").run(FAILURE_DETAIL_CHOSEN);+ }).immediate();+}+/** Add a column found missing: another server starting at the same moment may have just added it. */function addColumn(db: Database.Database, alter: string): void {try {@@ -1213,6 +1231,7 @@ function open(): Database.Database {db.prepare("INSERT INTO _migrations (id) VALUES (?)").run(i);}).immediate();});+ keepFriendlyFailures(db, done.size === 0);// Placeholder results are opt-in (settings.ts, demoMode): a saved "auto", which made a placeholder whenever the model// wasn't connected, is cleared, so the install runs with the default "off". A saved "on" stays. Safe on every start.db.exec("DELETE FROM settings WHERE key = 'demo.mode' AND value NOT IN ('on', 'off')");diff --git a/src/server/generations.ts b/src/server/generations.tsindex 23b137bc..728ba76a 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -145,7 +145,7 @@ import { finishTask, pathOnWorker, poolFinishes3d, startWorkerModelFinish, stopWimport { PATH_FPS, PATH_FRAMES } from "@/lib/camera-path";import { cropPicture, isCropWindow } from "./crop-picture";import { convertMask, decodePng, encodePng } from "./png";-import { engineMode, getSetting, withCandidates, withoutCandidates } from "./settings";+import { engineMode, getSetting, runFailureDetail, withCandidates, withoutCandidates } from "./settings";import { blockedForAccounts, discardBody, fetchRemoteToFile, RemoteFetchError } from "./remote-fetch";import { accountSend } from "./account-send";import { stamped, stampOf, withoutStamp, withRunStamp, type RunStamp } from "./run-stamp";@@ -203,7 +203,8 @@ interface Row {stage?: string | null;/*** A failed run's technical detail, for the owner only (the engine's own words, cleaned: src/lib/engine-error.ts), when- * the person read a plain sentence in `error` instead. Never part of a Generation.+ * the person read a plain sentence in `error` instead. Part of a Generation only as `errorDetail`, while the install+ * shows failure details to people (settings.ts runFailureDetail).*/detail?: string | null;}@@ -280,6 +281,8 @@ export function toGeneration(r: Row): Generation {pinnedAt: r.pinned_at ?? null,review: isReviewStatus(r.review) ? r.review : null,...(made && { made }),+ // On this install's GPUs, the cleaned technical reason under the plain sentence, while the install shows it.+ ...(pool && (r.status === "failed" || r.status === "canceled") && failureDetailOf(r)),...(r.status === "failed" && r.fix_json && !pool && { fix: parseFix(r.fix_json) }),...(r.status === "failed" && r.fix_json && !pool && parseTrouble(r.fix_json)),// Waiting for its own GPU or key to come back: why, the buttons that help, and until when (never the owner's note).@@ -306,6 +309,14 @@ export function toGeneration(r: Row): Generation {};}+/**+ * A failed run's technical reason for its own person (Generation.errorDetail): the stored detail, already cleaned+ * (storedFields), while Settings → Failed runs is "full". Nothing when the install shows the plain sentence only.+ */+function failureDetailOf(r: Pick<Row, "detail">): { errorDetail: string } | Record<string, never> {+ return r.detail && runFailureDetail() === "full" ? { errorDetail: r.detail } : {};+}+/** What Ideogram 4 returned in place of a picture, kept with the run for the owner (Generation.declinedCards). */export function declinedCardsOf(meta: { declined?: unknown } | undefined): { declinedCards: DeclinedCard[] } | Record<string, never> {const cards = (meta?.declined as DeclinedMeta | undefined)?.cards;diff --git a/src/server/settings.ts b/src/server/settings.tsindex 2398bafe..cf508c51 100644--- a/src/server/settings.ts+++ b/src/server/settings.ts@@ -141,6 +141,14 @@ export const SETTINGS = {* to Krea 2 Realism straight away (src/lib/auto-image.ts). Empty: the built-in list.*/autoImagePatterns: { key: "auto.imagePatterns", default: DEFAULT_AUTO_PATTERNS.join("\n") },+ /**+ * Settings → Failed runs: what a person reads when a run of theirs on this install's GPUs fails. "full": the plain+ * sentence, and under it the cleaned technical reason (ComfyUI's own, src/lib/comfy-reason.ts: no folders, addresses,+ * keys or prompt text), for people who run their own install and want to see what went wrong. "friendly": the plain+ * sentence only. A new install starts with "full"; an install that already had runs or settings when this build first+ * opened its data keeps "friendly", as before (db.ts keepFriendlyFailures).+ */+ runFailureDetail: { key: "runs.failureDetail", env: "FUOBE_RUN_FAILURE_DETAIL", default: "full", options: ["full", "friendly"] },/** "1" once the first-run guide was put away, or /api/status first saw something the engine mode generates with connected: Home stops offering it. */onboarded: { key: "onboarding.done", default: "0", options: ["0", "1"] },} satisfies Record<string, SettingDef>;@@ -247,19 +255,29 @@ export function validateSetting(name: SettingName, value: string, from: "api" |}}-export function setSetting(name: SettingName, value: string): void {+/**+ * Settings whose every change is in the admin log, with the value before and after: where ComfyUI runs (it decides whose+ * GPUs run every job), and what people read when a run fails.+ */+const AUDITED: Partial<Record<SettingName, string>> = { comfyWhere: "settings.comfy_where", runFailureDetail: "settings.run_failure_detail" };++/** Save a setting. `o.audited`: the caller writes its own admin log row (the admin API, with its actor). */+export function setSetting(name: SettingName, value: string, o: { audited?: boolean } = {}): void {validateSetting(name, value);const def = SETTINGS[name];- // Where ComfyUI runs decides whose GPUs run every job: each change is in the admin log, with the value before and after.- const before = name === "comfyWhere" ? getSetting("comfyWhere") : null;+ const action = o.audited ? undefined : AUDITED[name];+ const before = action ? getSetting(name) : null;if (value === "") db().prepare("DELETE FROM settings WHERE key = ?").run(def.key);else db().prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(def.key, value);- if (name === "comfyWhere") {- const after = getSetting("comfyWhere");- if (after !== before) auditSettingChange("settings.comfy_where", { before, after });+ if (action) {+ const after = getSetting(name);+ if (after !== before) auditSettingChange(action, { before, after });}}+/** What a person reads when a run of theirs on this install's GPUs fails: the cleaned reason too ("full"), or not. */+export const runFailureDetail = (): "full" | "friendly" => (getSetting("runFailureDetail") === "friendly" ? "friendly" : "full");+/** A row in the admin log (admin_audit) for a setting the owner changed. Never fails the change. */function auditSettingChange(action: string, detail: Record<string, unknown>): void {try {diff --git a/tests/pool-account-runs.test.ts b/tests/pool-account-runs.test.tsindex da4790ea..a7639a08 100644--- a/tests/pool-account-runs.test.ts+++ b/tests/pool-account-runs.test.ts@@ -111,6 +111,8 @@ beforeEach(() => {setSetting("comfyUrl", "");setSetting("engineMode", "open");setSetting("demoMode", "off");+ // People read the plain sentence only, unless a test says otherwise (Settings → Failed runs).+ setSetting("runFailureDetail", "friendly");db().prepare("DELETE FROM relay_workers").run();db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();@@ -802,6 +804,39 @@ describe("an account's run that a worker can't finish", () => {expect(await visitorList()).not.toMatch(/RuntimeError|KSampler/);});+ it("with full details on, the person reads the cleaned reason under the plain sentence; nobody else does", async () => {+ setSetting("runFailureDetail", "full");+ const w = standInWorker();+ beatAs(w);+ const { id } = await accountRun();+ const api = workerApi(w.token);+ const t = (await api.claim())!;+ const body = { error: { type: "missing_node_type", message: "x", details: "Node ID '#12'", extra_info: { node_id: "12", class_type: "InstantHMRPredict" } }, node_errors: {} };+ await api.report(t, { event: "refused", status: 400, body, why: `${refusalReason(body)} from X:\\fuobe-worker\\ComfyUI with hf_abcdefghijklmnopqrstu` });+ const g = await ended(id);+ const why = "ComfyUI refused the job: node InstantHMRPredict (id 12) isn't installed from [folder] with [key]";+ // The plain sentence stays; the cleaned reason comes with it, in the run and the person's own list.+ expect(isEngineWords(g.error), g.error ?? "").toBe(true);+ expect(g.errorDetail).toBe(why);+ const mine = JSON.parse(await visitorList()) as { items: { id: string; errorDetail?: string }[] };+ expect(mine.items.find((x) => x.id === id)?.errorDetail).toBe(why);+ expect(JSON.stringify(mine)).not.toMatch(/fuobe-worker|hf_abc|X:\\\\/);+ // Another account: not in its list, and its look at the run is refused.+ const theirs = await generationsRoute.GET(request("/api/generations?limit=50", { cookie: computerCookie }));+ expect(JSON.stringify(await theirs.json())).not.toMatch(/InstantHMR/);+ const { proxy } = await import("@/proxy");+ const { NextRequest } = await import("next/server");+ const look = proxy(new NextRequest(`http://${HOST}/api/generations/${id}`, { headers: { ...SITE_HEADERS, cookie: computerCookie } }));+ expect([403, 404]).toContain(look.status);+ // A guest is asked to sign in.+ const guest = proxy(new NextRequest(`http://${HOST}/api/generations/${id}`, { headers: SITE_HEADERS }));+ expect(guest.headers.get("x-middleware-next")).not.toBe("1");+ // Friendly only: the same run reads the plain sentence alone.+ setSetting("runFailureDetail", "friendly");+ expect(getGeneration(id)!.errorDetail).toBeUndefined();+ expect(await visitorList()).not.toMatch(/InstantHMR|errorDetail/);+ });+it("a job the studio stopped keeps the reason its worker gave before", async () => {const w = standInWorker();beatAs(w);diff --git a/tests/run-failure-detail-install.test.ts b/tests/run-failure-detail-install.test.tsnew file mode 100644index 00000000..4b0a618a--- /dev/null+++ b/tests/run-failure-detail-install.test.ts@@ -0,0 +1,91 @@+import fs from "node:fs";+import path from "node:path";+import Database from "better-sqlite3";+import { afterEach, describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";++/**+ * What people read when a run fails (settings.ts runFailureDetail) on each kind of data folder: a new install starts+ * with the full details; a data folder an earlier build made keeps the friendly sentence only, saved before anything+ * reads it, and that choice (or the owner's later one) stays through every restart and update.+ */++const dir = tempDir("fuobe-failure-detail-install-");+process.env.FUOBE_DATA_DIR = dir;+delete process.env.FUOBE_RUN_FAILURE_DETAIL;+const file = path.join(dir, "fuobe.db");++const { db, MIGRATIONS, FAILURE_DETAIL_CHOSEN } = await import("@/server/db");+const { getSetting, runFailureDetail, setSetting } = await import("@/server/settings");++/** The server stops and starts again on the same data folder (a restart, or a deploy of a newer build). */+function restart() {+ globalThis.__fuobeDb?.close();+ globalThis.__fuobeDb = undefined;+}+const saved = () => (db().prepare("SELECT value FROM settings WHERE key = 'runs.failureDetail'").get() as { value: string } | undefined)?.value;++afterEach(() => {+ restart();+ for (const f of [file, `${file}-wal`, `${file}-shm`]) fs.rmSync(f, { force: true });+ delete process.env.FUOBE_RUN_FAILURE_DETAIL;+});++/** A data folder an earlier build made and used: its migrations, a run and a setting, and no choice made yet. */+function earlierInstall() {+ const d = new Database(file);+ d.exec("CREATE TABLE IF NOT EXISTS _migrations (id INTEGER PRIMARY KEY)");+ MIGRATIONS.forEach((sql, i) => {+ d.exec(sql);+ d.prepare("INSERT INTO _migrations (id) VALUES (?)").run(i);+ });+ d.prepare("INSERT INTO settings (key, value) VALUES ('comfyui.where', 'workers')").run();+ d.close();+}++describe("what people read when a run fails, by data folder", () => {+ it("a new install shows the full details, and keeps them through restarts", () => {+ expect(runFailureDetail()).toBe("full");+ expect(saved()).toBeUndefined();+ expect(db().prepare("SELECT value FROM settings WHERE key = ?").get(FAILURE_DETAIL_CHOSEN)).toEqual({ value: "1" });+ for (let i = 0; i < 3; i++) {+ restart();+ expect(runFailureDetail()).toBe("full");+ }+ });++ it("an install an earlier build made keeps the friendly sentence, saved at its first start on this build", () => {+ earlierInstall();+ // Its first read already finds it saved: no request is ever served with the details on.+ expect(runFailureDetail()).toBe("friendly");+ expect(saved()).toBe("friendly");+ // Deploy after deploy, and with the environment saying otherwise, it stays.+ process.env.FUOBE_RUN_FAILURE_DETAIL = "full";+ for (let i = 0; i < 3; i++) {+ restart();+ expect(runFailureDetail()).toBe("friendly");+ }+ expect(getSetting("comfyWhere")).toBe("workers");+ });++ it("the owner's choice stays through restarts, either way: the first start's choice is made once only", () => {+ earlierInstall();+ expect(runFailureDetail()).toBe("friendly");+ setSetting("runFailureDetail", "full");+ restart();+ expect(runFailureDetail()).toBe("full");+ setSetting("runFailureDetail", "friendly");+ restart();+ expect(runFailureDetail()).toBe("friendly");+ // Even a cleared value isn't set again by a later start: the default (full) is then the owner's to have.+ setSetting("runFailureDetail", "");+ restart();+ expect(runFailureDetail()).toBe("full");+ });++ it("a value that isn't one of the two reads as the default, and can't be saved", () => {+ db().prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('runs.failureDetail', 'everything')").run();+ expect(runFailureDetail()).toBe("full");+ expect(() => setSetting("runFailureDetail", "raw")).toThrow(/full, friendly/);+ });+});diff --git a/tests/run-failure-detail.test.ts b/tests/run-failure-detail.test.tsnew file mode 100644index 00000000..c886aa8f--- /dev/null+++ b/tests/run-failure-detail.test.ts@@ -0,0 +1,115 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";++/**+ * What people read when a run fails (settings.ts runFailureDetail), as the owner changes it: GET and PATCH+ * /api/admin/site/runs (the owner, or a token with site:read or site:write), each change in the admin log, and the same+ * setting in Settings.+ */++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++const dir = tempDir("fuobe-failure-detail-");+process.env.FUOBE_DATA_DIR = dir;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_TRUST_PROXY;+delete process.env.FUOBE_RUN_FAILURE_DETAIL;+const auth = await import("@/server/auth");+const admin = await import("@/server/admin-tokens");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { proxy } = await import("@/proxy");+const { runFailureDetail, setSetting } = await import("@/server/settings");+const route = await import("@/app/api/admin/site/runs/route");+afterAll(() => {+ delete process.env.FUOBE_PUBLIC_SIGNUP;+});++const req = (url: string, o: { method?: string; token?: string; cookie?: string; body?: unknown } = {}) =>+ new NextRequest(`http://localhost:3000${url}`, {+ method: o.method ?? "GET",+ headers: {+ ...(o.token && { authorization: `Bearer ${o.token}` }),+ ...(o.cookie && { cookie: `${auth.SESSION_COOKIE}=${o.cookie}` }),+ ...(o.body !== undefined && { "content-type": "application/json" }),+ },+ ...(o.body !== undefined && { body: JSON.stringify(o.body) }),+ });+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";+let n = 0;+const make = (scopes: (typeof admin.SCOPES)[number][]) => admin.createAdminToken({ name: `failures ${++n}`, scopes, expiresInDays: null });+const audits = (action: string) => db().prepare("SELECT * FROM admin_audit WHERE action = ? ORDER BY id").all(action) as { actor: string; detail_json: string | null; status: number }[];+const URL_ = "/api/admin/site/runs";++let owner = "";+let account = "";+beforeAll(() => {+ auth.setPassword("install password");+ owner = auth.createSession().value;+ account = auth.createSession(auth.createAccount("[email protected]", "long enough").id).value;+});+beforeEach(() => {+ resetRates();+ admin.revokeAllAdminTokens();+});++describe("what people read when a run fails: who may read and change it", () => {+ it("is the full details on a new install", async () => {+ expect(runFailureDetail()).toBe("full");+ expect(await (await route.GET(req(URL_, { cookie: owner }))).json()).toEqual({ failureDetail: "full" });+ });++ it("answers a guest 401 and an account 403 at the proxy, and lets the owner through", () => {+ for (const method of ["GET", "PATCH"]) {+ expect(proxy(req(URL_, { method })).status, method).toBe(401);+ expect(proxy(req(URL_, { method, cookie: account })).status, method).toBe(403);+ expect(passed(proxy(req(URL_, { method, cookie: owner }))), method).toBe(true);+ }+ });++ it("refuses anyone but the owner or a token with the scope", async () => {+ expect((await route.GET(req(URL_))).status).toBe(403);+ expect((await route.PATCH(req(URL_, { method: "PATCH", body: { failureDetail: "full" } }))).status).toBe(403);+ expect((await route.PATCH(req(URL_, { method: "PATCH", cookie: account, body: { failureDetail: "full" } }))).status).toBe(403);+ const other = make(admin.SCOPES.filter((s) => s !== "site:read" && s !== "site:write"));+ expect(await (await route.GET(req(URL_, { token: other.token }))).json()).toMatchObject({ code: "scope", scope: "site:read" });+ const reader = make(["site:read"]);+ expect((await route.GET(req(URL_, { token: reader.token }))).status).toBe(200);+ const no = await route.PATCH(req(URL_, { token: reader.token, method: "PATCH", body: { failureDetail: "friendly" } }));+ expect(no.status).toBe(403);+ expect(await no.json()).toMatchObject({ code: "scope", scope: "site:write" });+ expect(runFailureDetail()).toBe("full");+ });++ it("the owner and a site:write token change it, each change logged with before and after; anything else is a 400", async () => {+ const off = await route.PATCH(req(URL_, { cookie: owner, method: "PATCH", body: { failureDetail: "friendly" } }));+ expect(off.status).toBe(200);+ expect(off.headers.get("cache-control")).toBe("no-store");+ expect(await off.json()).toEqual({ failureDetail: "friendly" });+ expect(runFailureDetail()).toBe("friendly");+ expect(audits("site.runs").at(-1)).toMatchObject({ actor: "owner", status: 200 });+ expect(JSON.parse(audits("site.runs").at(-1)!.detail_json!)).toEqual({ before: "full", after: "friendly" });++ const writer = make(["site:write"]);+ const on = await route.PATCH(req(URL_, { token: writer.token, method: "PATCH", body: { failureDetail: "full" } }));+ expect(await on.json()).toEqual({ failureDetail: "full" });+ expect(audits("site.runs").at(-1)).toMatchObject({ actor: "token", status: 200 });++ for (const body of [{ failureDetail: "raw" }, { failureDetail: true }, {}, { failureDetail: "full", more: 1 }, null]) {+ const bad = await route.PATCH(req(URL_, { cookie: owner, method: "PATCH", body }));+ expect(bad.status, JSON.stringify(body)).toBe(400);+ }+ expect(audits("site.runs").at(-1)).toMatchObject({ status: 400 });+ expect(runFailureDetail()).toBe("full");+ // The admin API's change isn't logged twice.+ expect(audits("settings.run_failure_detail")).toHaveLength(0);+ });++ it("a change in Settings (the owner's browser) is in the admin log too", () => {+ setSetting("runFailureDetail", "friendly");+ expect(JSON.parse(audits("settings.run_failure_detail").at(-1)!.detail_json!)).toEqual({ before: "full", after: "friendly" });+ setSetting("runFailureDetail", "full");+ });+});