The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Runs: keep ComfyUI's own reason when a job fails, for the owner only
Adarsh809cba641cd9
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex 3537eef4..53779fab 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -245,6 +245,11 @@ async function work(saved, deps, owner) {const site = cfg.site.replace(/\/+$/, "");const f = folders(cfg.workDir);fs.mkdirSync(cfg.workDir, { recursive: true });+ /** A job's last line in the log: how it ended, and a failed one's reason in short (ComfyUI's own, when it said one). */+ const endedLine = (what, t, phase, why) => {+ const said = typeof why === "string" ? (redact ? redact(why) : why).replace(/\s+/g, " ").replace(/[\s.]+$/, "").slice(0, 600) : "";+ return `${what} ${t.id} ${phase}${said ? `: ${said}` : ""}.`;+ };emptyFolders(f);// Inputs kept by their SHA-256 while their job runs here (a job sent again reads nothing from the studio twice).const cacheDir = path.join(cfg.workDir, "cache");@@ -674,8 +679,8 @@ async function work(saved, deps, owner) {now,sleep,vet: vetJob,- ended: async (t, phase) => {- log(`Job ${t.id} ${phase}.`);+ ended: async (t, phase, why) => {+ log(endedLine("Job", t, phase, why));// Done: the studio has every result. Otherwise its kept results wait for the next claim to say whose job it is,// after a while (so a studio that won't take them now doesn't keep its ComfyUI from starting).if (phase === "done") hold.drop(t.id);@@ -820,8 +825,8 @@ async function work(saved, deps, owner) {sleep,vet: vetJob,finish: (t, inputs, o) => finish.finish(t, inputs, o),- ended: async (t, phase) => {- log(`CPU slot job ${t.id} ${phase}.`);+ ended: async (t, phase, why) => {+ log(endedLine("CPU slot job", t, phase, why));if (phase === "done") cpuHold.drop(t.id);delete crashes[t.id];saveCrashes();diff --git a/docs/admin-api.md b/docs/admin-api.mdindex 44e737dd..470487ab 100644--- a/docs/admin-api.md+++ b/docs/admin-api.md@@ -108,7 +108,7 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control| `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` (one account), else `whose` (`people`: accounts' and guests' runs, the default; `ours`: the owner's own; `everyone`); `source` (the owner's runs only: `hands-on`, or `batch` for any automated run: `batch`, `drill`, `example`, `test`, `api`); `where` (`pool`: this install's GPUs, the owner's runs on its ComfyUI too; `provider`: a cloud provider; `own`: an account's own GPU); `status` (`finished` or `done`, `failed`, `canceled`, `waiting`, `started`, and `running` for waiting and started); `kind` (`image`, `video`, `audio`, `model3d`, `text`); `model` (letters of the model id); `from` and `to` (`yyyy-mm-dd` in UTC, both days included); `q` (words of the prompt, or a run id); `ids` (a comma list of up to 100 run ids: those runs, whoever's they are); `before` (the last page's `next`); `limit` (1 to 100, default 30) | `{ items, next }`; `next` is null on the last page. Each run has `whose`: `account`, `guest` or `owner`. Each output has a `state`: `shown`, `held` (hidden, or waiting for its check) or `removed` (its file is gone). A failed run on this install's GPUs (and the owner's own failed run) also has `detail`: the technical reason, which the account never sees. `account` is `{ id, email }` (`email` null: a deleted account), `{ id, emailHidden: true }` without `accounts:read`, or `null` for the owner's own run, which has `source` too (`hands-on` from the site; `batch`, `drill`, `example`, `test` as its script said; `api` for a run sent with an API token that said none) and `sourceName` when its script gave one |-| `GET /api/admin/generations/{id}` | needs `runs:read` and `outputs:view` | One run in full, an account's, a guest's or the owner's own: `{ run, stored, fix, trouble, where, model, preset, studio, prompt, negativePrompt, asked, settings, inputs, batch, near, chain, sent, timing, jobs, workerLog, money, madeBy, surface, providerId, progress, checks }`. `stored.detail` is the technical reason for the owner. `inputs` lists each input file by slot, with its `state` (`kept` with its `url`, `removed`, `example`, `inline`, `link`). `chain` is `{ before, after }`: the steps it waits for and the steps that wait for it. Keys, tokens and GPU addresses are never part of it. 404 for an unknown run |+| `GET /api/admin/generations/{id}` | needs `runs:read` and `outputs:view` | One run in full, an account's, a guest's or the owner's own: `{ run, stored, fix, trouble, where, model, preset, studio, prompt, negativePrompt, asked, settings, inputs, batch, near, chain, sent, timing, jobs, workerLog, money, madeBy, surface, providerId, progress, checks }`. `stored.detail` is the technical reason for the owner; `comfyReason`, when there is one, is ComfyUI's own reason in one short line (a node that isn't installed, a model file not in its list, an error in a node), and each of `jobs` has it as `comfyWhy`. `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 }` |diff --git a/scripts/lib/worker-build.mjs b/scripts/lib/worker-build.mjsindex 6765b564..40442bcc 100644--- a/scripts/lib/worker-build.mjs+++ b/scripts/lib/worker-build.mjs@@ -27,7 +27,7 @@ import { unruledPathInputs } from "./catalog-checks.mjs";import { allowedNodeList, filePins, inputRules, missingRules, readCatalog } from "./worker-catalog.mjs";export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");-export const SOURCES = ["computer-runner", "engine-error", "comfy-guard", "comfy-ws", "fetch-within", "local-comfy", "relay", "lanes", "worker-hours", "finish-ticket", "camera-path", "path-splat", "scene3d"];+export const SOURCES = ["computer-runner", "engine-error", "comfy-reason", "comfy-guard", "comfy-ws", "fetch-within", "local-comfy", "relay", "lanes", "worker-hours", "finish-ticket", "camera-path", "path-splat", "scene3d"];/*** What the worker learns from the catalog: its node allowlist, its input rules and its file pins. Throws when an inputdiff --git a/src/app/api/gpu/computer/tasks/[id]/report/route.ts b/src/app/api/gpu/computer/tasks/[id]/report/route.tsindex b6178481..62c02b04 100644--- a/src/app/api/gpu/computer/tasks/[id]/report/route.ts+++ b/src/app/api/gpu/computer/tasks/[id]/report/route.ts@@ -30,11 +30,13 @@ function eventOf(b: Record<string, unknown>): ReportEvent | null {const kept = b.kept === true ? { kept: true } : {};// A worker's measured execution time and GPU name, with a finished job.const exec = { ...measured(b), ...kept };+ // ComfyUI's reason a job failed, in one short line (the server cleans it again before it keeps it).+ const why = typeof b.why === "string" && b.why.trim() ? { why: b.why.slice(0, 4_000) } : {};switch (e) {case "sent":return typeof b.promptId === "string" ? { event: e, promptId: b.promptId, number: num(b.number), ...kept } : null;case "refused":- return { event: e, status: num(b.status) ?? 400, body: b.body };+ return { event: e, status: num(b.status) ?? 400, body: b.body, ...why };case "queued":return { event: e, position: num(b.position) ?? -1 };case "running": {@@ -43,13 +45,13 @@ function eventOf(b: Record<string, unknown>): ReportEvent | null {return { event: e, value: num(b.value), max: num(b.max), nodesDone: num(b.nodesDone), ...(typeof b.node === "string" && { node: b.node }), ...(preview && { preview }) };}case "finished":- return b.entry && typeof b.entry === "object" ? { event: e, entry: b.entry as never, ...(num(b.peakVramBytes) !== undefined && { peakVramBytes: num(b.peakVramBytes) }), ...exec } : null;+ return b.entry && typeof b.entry === "object" ? { event: e, entry: b.entry as never, ...(num(b.peakVramBytes) !== undefined && { peakVramBytes: num(b.peakVramBytes) }), ...exec, ...why } : null;case "passes":- return Array.isArray(b.entries) && b.entries.length <= 64 ? { event: e, running: b.running === true, entries: b.entries as never, ...(b.running !== true && exec) } : null;+ return Array.isArray(b.entries) && b.entries.length <= 64 ? { event: e, running: b.running === true, entries: b.entries as never, ...(b.running !== true && { ...exec, ...why }) } : null;case "give-back":return typeof b.why === "string" && (GIVE_BACK as readonly string[]).includes(b.why) ? { event: e, why: b.why as never } : null;case "failed":- return typeof b.reason === "string" && (TAB_FAILURES as readonly string[]).includes(b.reason) ? { event: e, reason: b.reason as never, status: num(b.status) } : null;+ return typeof b.reason === "string" && (TAB_FAILURES as readonly string[]).includes(b.reason) ? { event: e, reason: b.reason as never, status: num(b.status), ...why } : null;case "comfy-down":return { event: e, ...(b.why === "setting" && { why: "setting" as const }) };default:diff --git a/src/components/run-details.tsx b/src/components/run-details.tsxindex 9bd7118a..b83a9e82 100644--- a/src/components/run-details.tsx+++ b/src/components/run-details.tsx@@ -178,6 +178,11 @@ export function RunDetailsView() {</Fact>)}{g.error && g.error !== d.stored.error && <Fact label="Error (as the account read it)">{g.error}</Fact>}+ {d.comfyReason && d.comfyReason !== d.stored.detail && (+ <Fact label="ComfyUI's reason">+ <span className="whitespace-pre-wrap">{d.comfyReason}</span>+ </Fact>+ )}{d.stored.detail && (<Fact label="Technical detail"><span className="whitespace-pre-wrap">{d.stored.detail}</span>diff --git a/src/lib/comfy-reason.ts b/src/lib/comfy-reason.tsnew file mode 100644index 00000000..b5e56069--- /dev/null+++ b/src/lib/comfy-reason.ts@@ -0,0 +1,232 @@+/**+ * ComfyUI's own reason a job failed, as one short line for the owner: why its /prompt refused the job (the answer's+ * `error` and `node_errors`: a node type that isn't installed, a required input missing, a model file not in the list…)+ * or why it stopped while it ran (its `execution_error`: the node, the exception and the last frames of its traceback).+ *+ * "ComfyUI refused the job: node InstantHMRPredict (id 12) isn't installed"+ * "ComfyUI refused the job: model file detection/instanthmr_medium.safetensors not in the list (model_name of InstantHMRLoader, id 12)"+ * "CUDA out of memory in KSampler (node 7)"+ *+ * The line keeps model file names and node names. It never keeps a folder (a path becomes its file's name), an address,+ * a key or a token, or the run's own words (a prompt): every text value of the job's graph that `o.graph` names is taken+ * out. It is at most REASON_MAX characters.+ *+ * Pure: the worker program (scripts/lib/worker-build.mjs) and the server share it.+ */+import { cleanEngineText } from "./engine-error";++/** The longest reason kept. */+export const REASON_MAX = 600;++type Obj = Record<string, unknown>;+const obj = (v: unknown): Obj | undefined => (v && typeof v === "object" && !Array.isArray(v) ? (v as Obj) : undefined);+const text = (v: unknown): string | undefined => (typeof v === "string" && v.trim() ? v.trim() : typeof v === "number" && Number.isFinite(v) ? String(v) : undefined);++/** A file name a model loader takes: a name (with its subfolders, never a drive or a root) and an extension. */+const MODEL_FILE = /^(?![\\/])(?![A-Za-z]:)[\w .+()[\]-]+(?:[\\/][\w .+()[\]-]+)*\.[A-Za-z0-9]{2,12}$/;+/** A short value safe to name as it is: one word, no space (an option of a list, a number). */+const WORD = /^[\w.+:-]{1,64}$/;++/** The longest run of word characters that can pass for a key: long, and mixed. */+const LONG_RUN = /[A-Za-z0-9+/=_-]{32,}/g;+const KEY_PATTERNS: [RegExp, string][] = [+ [/\b(?:hf|ghp|gho|ghu|ghs|ghr|github_pat|glpat|xox[abprs]|fuobe|rpa|r8)_[A-Za-z0-9_-]{8,}/g, "[key]"],+ [/\bsk-[A-Za-z0-9_-]{12,}/g, "[key]"],+ [/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer [key]"],+ [/\b\d{6,12}:[A-Za-z0-9_-]{30,}\b/g, "[key]"],+ [/([?&](?:token|key|api_key|apikey|access_token|sig|signature|auth|secret)=)[^&\s"']+/gi, "$1[key]"],+ [/\b((?:api[_-]?key|access[_-]?token|auth[_-]?token|token|secret|password|passwd|authorization)["']?\s*[=:]\s*["']?)[^\s"',;&)]+/gi, "$1[key]"],+];++/** A run of characters that looks like a key or a token (not a file's name, not words joined by underscores). */+function keyLike(run: string, next: string): boolean {+ if (next === ".") return false;+ if ((run.match(/[_-]/g) ?? []).length >= 3) return false;+ if (/^[a-f0-9]+$/i.test(run)) return true;+ return /[a-z]/.test(run) && /[A-Z]/.test(run) && /\d/.test(run);+}++/** Text without keys and tokens. */+export function withoutKeys(s: string): string {+ let out = s;+ for (const [re, to] of KEY_PATTERNS) out = out.replace(re, to);+ return out.replace(LONG_RUN, (m, at: number, all: string) => (keyLike(m, all[at + m.length] ?? "") ? "[key]" : m));+}++/**+ * The run's own words in its graph: each text value with a space in it (a prompt, a caption, a name typed in), longest+ * first. A value without a space is an option or a number, and a file name is a file name: the reason may name those.+ */+export function graphTexts(graph: unknown): string[] {+ const found = new Set<string>();+ const walk = (v: unknown, depth: number) => {+ if (depth > 12 || found.size > 400) return;+ if (typeof v === "string") {+ const t = v.trim();+ if (t.length >= 4 && /\s/.test(t) && !MODEL_FILE.test(t)) found.add(t);+ return;+ }+ if (Array.isArray(v)) for (const x of v) walk(x, depth + 1);+ else if (v && typeof v === "object") for (const x of Object.values(v as Obj)) walk(x, depth + 1);+ };+ walk(graph, 0);+ return [...found].sort((a, b) => b.length - a.length);+}++/**+ * A reason as it may be kept: the run's own words out (each of `o.graph`'s texts, and each of their lines), keys and+ * tokens out, then paths as file names, addresses and run ids out, one line, at most `max` characters.+ */+export function reasonText(raw: string, o: { graph?: unknown; max?: number } = {}): string {+ let s = raw;+ for (const t of graphTexts(o.graph)) {+ s = s.split(t).join("[text]");+ // ComfyUI may say a long text in part: each of its lines on its own, and its first 40 characters.+ for (const line of t.split(/\r?\n/).map((l) => l.trim())) if (line.length >= 12) s = s.split(line).join("[text]");+ if (t.length > 40) s = s.split(t.slice(0, 40)).join("[text]");+ }+ return cleanEngineText(withoutKeys(s), o.max ?? REASON_MAX);+}++/** "KSampler id 7", "id 7", "KSampler". */+const nodeName = (cls: string | undefined, id: string | undefined) => [cls, id && `id ${id}`].filter(Boolean).join(" ");++/** One of a node's validation errors, in a few words. */+function validationLine(e: Obj, cls: string | undefined, id: string | undefined): string | null {+ const type = text(e.type) ?? "";+ const info = obj(e.extra_info);+ const input = text(info?.input_name);+ const got = text(info?.received_value);+ const where = nodeName(cls, id);+ const inNode = (s: string) => (where ? `${s} (${where})` : s);+ switch (type) {+ case "value_not_in_list": {+ if (got && MODEL_FILE.test(got)) {+ const at = [input && cls ? `${input} of ${cls}` : (input ?? cls), id && `id ${id}`].filter(Boolean).join(", ");+ return `model file ${got} not in the list${at ? ` (${at})` : ""}`;+ }+ return inNode(`value ${got && WORD.test(got) ? `${got} ` : ""}${input ? `for ${input} ` : ""}not in the list`);+ }+ case "required_input_missing": {+ const name = input ?? text(e.details);+ return inNode(name ? `required input ${name} missing` : "a required input is missing");+ }+ case "value_smaller_than_min":+ case "value_bigger_than_max":+ return inNode(`${text(e.message) ?? type}${input ? ` for ${input}` : ""}`);+ default: {+ const message = text(e.message) ?? type;+ const details = text(e.details);+ if (!message && !details) return null;+ return inNode([message, details && details !== input ? details : input].filter(Boolean).join(": "));+ }+ }+}++/** The /prompt answer's error, without node errors, in a few words. */+function topLine(error: Obj): string | null {+ const type = text(error.type);+ const info = obj(error.extra_info);+ if (type === "missing_node_type") {+ const cls = text(info?.class_type);+ const id = text(info?.node_id) ?? /#(\w+)/.exec(text(error.details) ?? "")?.[1];+ return cls ? `node ${cls}${id ? ` (id ${id})` : ""} isn't installed` : (text(error.message) ?? "a node isn't installed");+ }+ const message = text(error.message);+ if (type === "prompt_outputs_failed_validation") return message ?? "the job failed validation";+ const details = text(error.details);+ return [message ?? type, details].filter(Boolean).join(": ") || null;+}++/**+ * Why ComfyUI's /prompt refused a job, from its answer (`{ error, node_errors }`), or null when the answer says nothing.+ * Each node's errors come first (at most three, then how many more), else the answer's own error.+ */+export function refusalReason(body: unknown, o: { graph?: unknown; max?: number } = {}): string | null {+ const b = obj(body);+ if (!b) return null;+ const lines: string[] = [];+ const graph = obj(o.graph);+ for (const [id, raw] of Object.entries(obj(b.node_errors) ?? {})) {+ const ne = obj(raw);+ const cls = text(ne?.class_type) ?? text(obj(graph?.[id])?.class_type);+ for (const e of Array.isArray(ne?.errors) ? ne.errors : []) {+ const line = obj(e) ? validationLine(obj(e)!, cls, id) : null;+ if (line && !lines.includes(line)) lines.push(line);+ }+ }+ const error = obj(b.error);+ if (!lines.length && error) {+ const line = topLine(error);+ if (line) lines.push(line);+ }+ if (!lines.length) {+ const said = text(b.error);+ if (!said) return null;+ lines.push(said);+ }+ const shown = lines.slice(0, 3).join("; ") + (lines.length > 3 ? ` (+${lines.length - 3} more)` : "");+ return reasonText(`ComfyUI refused the job: ${shown}`, o) || null;+}++/** "nodes.py:1234 sample": a traceback frame, by its file's name. */+function frameOf(line: string): string | null {+ const m = /File "([^"]+)", line (\d+)(?:, in ([\w<>.]+))?/.exec(line);+ if (!m) return null;+ const file = m[1].split(/[\\/]/).pop() ?? m[1];+ return `${file}:${m[2]}${m[3] ? ` ${m[3]}` : ""}`;+}++/** The last frames of a traceback (a list of strings, or one string), newest last. */+function lastFrames(tb: unknown, n = 2): string[] {+ const all = (Array.isArray(tb) ? tb : typeof tb === "string" ? [tb] : [])+ .filter((x): x is string => typeof x === "string")+ .flatMap((x) => x.split(/\r?\n/))+ .map(frameOf)+ .filter((x): x is string => !!x);+ return all.slice(-n);+}++const OUT_OF_MEMORY = /out of memory|OutOfMemoryError|Allocation on device|not enough memory|MemoryError/i;++/**+ * Why a job stopped while ComfyUI ran it: its execution error (the data of a history entry's "execution_error" message,+ * or of the websocket's), or an "execution_interrupted" one. Null when there is none.+ */+export function executionReason(data: unknown, o: { graph?: unknown; max?: number; interrupted?: boolean } = {}): string | null {+ const d = obj(data);+ if (!d) return null;+ const id = text(d.node_id);+ const cls = text(d.node_type) ?? (id ? text(obj(obj(o.graph)?.[id])?.class_type) : undefined);+ const where = cls ? ` in ${cls}${id ? ` (node ${id})` : ""}` : id ? ` in node ${id}` : "";+ if (o.interrupted) return reasonText(`ComfyUI stopped the job (interrupted)${where}`, o);+ const type = text(d.exception_type);+ const shortType = type?.split(".").pop();+ const message = (text(d.exception_message) ?? "").split(/\r?\n/).find((l) => l.trim()) ?? "";+ if (OUT_OF_MEMORY.test(`${type ?? ""} ${message}`)) {+ const cuda = /cuda|torch/i.test(`${type ?? ""} ${message}`);+ return reasonText(`${cuda ? "CUDA out of memory" : "Out of memory"}${where}`, o);+ }+ const frames = lastFrames(d.traceback);+ const head = `${shortType ?? "Error"}${where}`;+ const line = `${head}${message ? `: ${message.trim()}` : ""}${frames.length ? ` (at ${frames.join(" < ")})` : ""}`;+ return reasonText(line, o) || null;+}++/**+ * Why a finished history entry (or a meta-batch's passes) ended in an error: its execution error, else its interrupt,+ * else that its status says error. Null for an entry that finished well.+ */+export function entryReason(entries: unknown, o: { graph?: unknown; max?: number } = {}): string | null {+ for (const raw of Array.isArray(entries) ? entries : [entries]) {+ const status = obj(obj(raw)?.status);+ const messages = Array.isArray(status?.messages) ? status.messages : [];+ const msg = (name: string) => messages.find((m): m is [string, unknown] => Array.isArray(m) && m[0] === name)?.[1];+ const error = msg("execution_error");+ if (error) return executionReason(error, o);+ const interrupted = msg("execution_interrupted");+ if (interrupted) return executionReason(interrupted, { ...o, interrupted: true });+ if (status?.status_str === "error") return "ComfyUI ended the job with an error";+ }+ return null;+}diff --git a/src/lib/computer-runner.ts b/src/lib/computer-runner.tsindex c2bac8f1..9e9a25aa 100644--- a/src/lib/computer-runner.ts+++ b/src/lib/computer-runner.ts@@ -8,6 +8,7 @@* a socket and a clock, and the tests drive it from Node against a stand-in ComfyUI.*/import { isGuard } from "./comfy-guard";+import { entryReason, refusalReason } from "./comfy-reason";import { withoutLocalPaths } from "./engine-error";import { FINISH_RUN_MS, finishProblem, type FinishResult, type FinishStats } from "./finish-ticket";import { fetchWithin } from "./fetch-within";@@ -68,8 +69,11 @@ export interface RunnerDeps {* strings, verified models. The failure, or null. (A browser tab has none: graphProblem is its check.)*/vet?: (t: ClaimedTask) => TabFailure | null | Promise<TabFailure | null>;- /** A job ended here, done or not: a worker deletes its files. */- ended?: (t: ClaimedTask, phase: LocalJob["phase"]) => void | Promise<void>;+ /**+ * A job ended here, done or not: a worker deletes its files. `why`: a failed job's reason in one short line (ComfyUI's+ * own, src/lib/comfy-reason.ts, or why it stopped here), for the worker's log.+ */+ ended?: (t: ClaimedTask, phase: LocalJob["phase"], why?: string) => void | Promise<void>;/*** A worker program's composer (src/lib/ticket-compose.ts): the graph of a job ticket (src/lib/job-ticket.ts), built* from its own copy of the catalog, with the small files the graph makes itself; or why it refuses the ticket. A@@ -541,6 +545,7 @@ export class ComputerRunner {private async report(t: ClaimedTask, e: ReportEvent): Promise<{ wanted?: WantedFile[]; follow?: string; stop?: boolean; state?: RelayState }> {// A worker program never sends its own folders (a browser tab is the person's own computer: its words stay its own).if (this.deps.worker) e = withoutWorkerPaths(e);+ this.noteWhy(t, e);// A busy studio (429) is waited out, for a while; other failures are tried a few times.const until = this.now() + 2 * 60_000;for (let i = 0; ; ) {@@ -561,6 +566,15 @@ export class ComputerRunner {}}+ /** Why a job fails, as a report says it: ComfyUI's reason, or what stopped it here. */+ private noteWhy(t: ClaimedTask, e: ReportEvent) {+ const said = "why" in e && typeof e.why === "string" && e.why ? e.why : null;+ if (said && e.event !== "give-back") this.whyOf.set(t.id, said);+ else if (e.event === "failed") this.whyOf.set(t.id, `stopped here: ${e.reason}${e.status ? ` (HTTP ${e.status})` : ""}`);+ else if (e.event === "refused") this.whyOf.set(t.id, `ComfyUI refused the job (HTTP ${e.status})`);+ else if (e.event === "give-back") this.whyOf.set(t.id, `given back to the line: ${e.why}`);+ }+/** One beat: say this computer is here, keep its jobs alive, and stop what the server says to stop. */async beat(takeover = false): Promise<BeatAnswer | null> {if (!this.alive) return null;@@ -663,6 +677,8 @@ export class ComputerRunner {private stoppedDone = new Set<string>();/** The files a finishing job made, by task and name: uploaded from here, never read from ComfyUI. */private finishMade = new Map<string, Map<string, Blob>>();+ /** Why each job failed here, as its reports said (for `ended`). */+ private whyOf = new Map<string, string>();/*** Ask for a job and run it (one at a time). True when there was one. Only while ComfyUI here answers to this site: a@@ -715,8 +731,10 @@ export class ComputerRunner {} finally {this.madeOf.delete(t.id);this.finishMade.delete(t.id);+ const why = this.whyOf.get(t.id);+ this.whyOf.delete(t.id);const phase = this.view.jobs.find((j) => j.taskId === t.id)?.phase;- if (this.deps.ended && (phase === "done" || phase === "failed")) await Promise.resolve(this.deps.ended(t, phase)).catch(() => {});+ if (this.deps.ended && (phase === "done" || phase === "failed")) await Promise.resolve(this.deps.ended(t, phase, phase === "failed" ? why : undefined)).catch(() => {});}}@@ -804,6 +822,7 @@ export class ComputerRunner {if (e instanceof Stopped) {// The studio has no such job any more: a worker's kept results of it are of no use.if (e.gone) this.deps.worker?.hold.drop(t.id);+ if (!this.whyOf.has(t.id)) this.whyOf.set(t.id, e.gone ? "the studio no longer has this job" : "the studio stopped it");return this.job(t, { phase: "failed" });}throw e;@@ -1100,7 +1119,7 @@ export class ComputerRunner {return this.sendJob(t);}if (!up.ok) {- await this.report(t, { event: "failed", reason: up.status === 413 ? "input-too-big" : "comfy-error", status: up.status });+ await this.report(t, { event: "failed", reason: up.status === 413 ? "input-too-big" : "comfy-error", status: up.status, why: `ComfyUI answered HTTP ${up.status} to one of the job's files` });this.job(t, { phase: "failed" });return false;}@@ -1113,12 +1132,14 @@ export class ComputerRunner {}const answer = (await res.json().catch(() => ({}))) as { prompt_id?: string; number?: number };if (res.status === 400) {- await this.report(t, { event: "refused", status: 400, body: answer });+ const why = refusalReason(answer, { graph: t.graph });+ await this.report(t, { event: "refused", status: 400, body: answer, ...(why && { why }) });this.job(t, { phase: "failed" });return false;}if (!res.ok || typeof answer.prompt_id !== "string") {- await this.report(t, { event: "failed", reason: "comfy-error", status: res.status });+ const why = (!res.ok && refusalReason(answer, { graph: t.graph })) || `ComfyUI answered HTTP ${res.status} to the job${res.ok ? " without its id" : ""}`;+ await this.report(t, { event: "failed", reason: "comfy-error", status: res.status, why });this.job(t, { phase: "failed" });return false;}@@ -1207,7 +1228,8 @@ export class ComputerRunner {const ev = this.events.get(String(queued[0]?.[1] ?? ""));moved(JSON.stringify([queued.map((r) => r[1]), passes.length, ev?.value, ev?.node, ev?.nodesDone]));if (!running && worker) await this.keep(t, { kind: "passes", entries: passes, execMs: execOf(passes) });- const a = await this.report(t, { event: "passes", running, entries: running ? [] : passes.map(slim), ...(!running && exec(execOf(passes))) });+ const passWhy = running ? null : entryReason(passes, { graph: t.graph });+ const a = await this.report(t, { event: "passes", running, entries: running ? [] : passes.map(slim), ...(!running && exec(execOf(passes))), ...(passWhy && { why: passWhy }) });if (a.stop) throw new Stopped();if (!running) return { entries: passes, answer: a };this.job(t, { phase: "running" });@@ -1235,7 +1257,8 @@ export class ComputerRunner {const ms = execOf([w.entry]);// A worker keeps the results first: a stop from here on uploads them again instead of running the job again.if (worker && !t.metaBatch && w.entry.status?.status_str !== "error") await this.keep(t, { kind: "finished", entries: [w.entry], execMs: ms });- const a = await this.report(t, { event: "finished", entry: slim(w.entry), ...exec(ms) });+ const why = w.entry.status?.status_str === "error" ? entryReason(w.entry, { graph: t.graph }) : null;+ const a = await this.report(t, { event: "finished", entry: slim(w.entry), ...exec(ms), ...(why && { why }) });if (a.stop) throw new Stopped();if (a.follow) {following = a.follow;diff --git a/src/lib/relay.ts b/src/lib/relay.tsindex 57b301e7..475fc076 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -52,8 +52,11 @@ export type ReportEvent =* `kept`: a worker sends results it kept from an earlier try instead (nothing new runs, so it isn't another attempt).*/| { event: "sent"; promptId: string; number?: number; kept?: boolean }- /** ComfyUI's /prompt refused it (its answer, as it was). */- | { event: "refused"; status: number; body: unknown }+ /**+ * ComfyUI's /prompt refused it (its answer, as it was). `why`, on this report and on "finished", "passes" and+ * "failed": ComfyUI's reason in one short line (src/lib/comfy-reason.ts), for the owner only.+ */+ | { event: "refused"; status: number; body: unknown; why?: string }/** Waiting in ComfyUI's queue: how many prompts are before it. */| { event: "queued"; position: number }/**@@ -66,12 +69,12 @@ export type ReportEvent =* executing the job (`execMs`: execution only, no waits, no uploads), its GPU's name (`device`), and `kept` when the* results are ones it kept from an earlier try (their time doesn't count toward the lane's times).*/- | { event: "finished"; entry: HistoryEntryLike; peakVramBytes?: number; execMs?: number; device?: string; kept?: boolean }+ | { event: "finished"; entry: HistoryEntryLike; peakVramBytes?: number; execMs?: number; device?: string; kept?: boolean; why?: string }/*** A meta-batch job (VHS re-queues it pass by pass): whether a pass is still queued, and the passes' entries so far. The* last one (not running) is the job's end: a worker adds `execMs`, `device` and `kept` as for "finished".*/- | { event: "passes"; running: boolean; entries: HistoryEntryLike[]; execMs?: number; device?: string; kept?: boolean }+ | { event: "passes"; running: boolean; entries: HistoryEntryLike[]; execMs?: number; device?: string; kept?: boolean; why?: string }/** A worker gives the task back to the line (it counts as an attempt). */| { event: "give-back"; why: GiveBackWhy }/** ComfyUI has no trace of it (restarted): the server sends it again once. */@@ -81,7 +84,7 @@ export type ReportEvent =/** A stop the server asked for is done. */| { event: "stopped" }/** The tab gave up for one of its own reasons. */- | { event: "failed"; reason: TabFailure; status?: number };+ | { event: "failed"; reason: TabFailure; status?: number; why?: string };export type ReportEventName = ReportEvent["event"];diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.tsindex bddd6e4a..ad3fbf4c 100644--- a/src/server/computer/tasks.ts+++ b/src/server/computer/tasks.ts@@ -25,6 +25,7 @@ import {type WantedFile,previewOf,} from "@/lib/relay";+import { reasonText } from "@/lib/comfy-reason";import type { FinishTicket } from "@/lib/finish-ticket";import type { JobTicket } from "@/lib/job-ticket";import { DATA_DIR, db, WORKER_JOBS_KEEP_MS } from "../db";@@ -111,6 +112,11 @@ export interface TaskRow {result_json: string | null;error: string | null;refusal_json: string | null;+ /**+ * ComfyUI's own reason the job failed, in one short line, as the tab or worker reported it (src/lib/comfy-reason.ts,+ * cleaned again here): for the owner only, never part of what the run's person reads.+ */+ comfy_why?: string | null;stop: number;attempts: number;down_at: number | null;@@ -929,6 +935,15 @@ export function keptRefusal(body: unknown): { error?: Record<string, unknown>; nreturn JSON.stringify(kept).length <= RELAY_LIMITS.keptRefusalBytes ? kept : { ...(error && { error }), node_errors: {} };}+/**+ * ComfyUI's reason a job failed, as the tab or worker said it, fit to keep for the owner: the job's own words (its+ * graph's or its ticket's texts) out, keys and paths out, at most REASON_MAX characters (src/lib/comfy-reason.ts).+ */+export function ownerReason(raw: string, t: Pick<TaskRow, "graph_json" | "ticket_json">): string {+ const graph = json<unknown>(t.ticket_json ?? null, null) ?? json<unknown>(t.graph_json, null);+ return reasonText(raw.slice(0, 8_000), { graph });+}+/** What the server does with a finished prompt: the files it wants, a meta-batch to follow, or a failure. */export type FinishedPlan = { wanted: WantedFile[]; outputs: unknown[]; budget: number } | { follow: string } | { error: string };@@ -957,6 +972,8 @@ function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLikethrow new RelayError(409, `That doesn't fit this run now (${t.state})`);}const seen = { device_seen_at: now, down_at: null, down_why: null };+ const why = "why" in e && typeof e.why === "string" ? ownerReason(e.why, t) : "";+ if (why) setTask(t.id, { comfy_why: why });switch (e.event) {case "sent": {const promptId = typeof e.promptId === "string" && UUID.test(e.promptId) ? e.promptId : typeof e.promptId === "string" && /^[\w-]{1,64}$/.test(e.promptId) ? e.promptId : null;diff --git a/src/server/db.ts b/src/server/db.tsindex 291c00c1..3608f0b3 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1106,6 +1106,8 @@ const RELAY_COLUMNS: [string, string, string][] = [// picture came (the picture is a file in the task's folder): kept in the database, so every app process sees them.["relay_tasks", "progress_json", "TEXT"],["relay_tasks", "preview_at", "INTEGER"],+ // ComfyUI's own reason a job failed, in one short line (src/lib/comfy-reason.ts): the owner's only.+ ["relay_tasks", "comfy_why", "TEXT"],// A pool worker's next token (workers.ts offerNextToken) and where its token was used from (hashed networks).["relay_workers", "next_token_hash", "TEXT"],["relay_workers", "next_expires_at", "INTEGER"],diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 3309cdc6..623832eb 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -1899,9 +1899,11 @@ function poolKeeps(error: string): boolean {* stays as the owner's "Fix it".*/export function poolFailure(res: Extract<PollResult, { state: "failed" }>): PollResult {- if (poolKeeps(res.error)) return { state: "failed", error: res.error, ...(res.fix && { fix: res.fix }), ...(res.lost && { lost: true as const }) };+ // ComfyUI's own reason, when the worker reported one, is the owner's detail before the server's reading of it.+ if (poolKeeps(res.error)) return { state: "failed", error: res.error, ...(res.detail && { detail: res.detail }), ...(res.fix && { fix: res.fix }), ...(res.lost && { lost: true as const }) };const plain = plainEngineFailure(res.error, res.fix?.code);- return { state: "failed", error: plain.words, ...(plain.detail && { detail: plain.detail }), ...(res.fix && { fix: res.fix }), ...(res.lost && { lost: true as const }) };+ const detail = res.detail ?? plain.detail;+ return { state: "failed", error: plain.words, ...(detail && { detail }), ...(res.fix && { fix: res.fix }), ...(res.lost && { lost: true as const }) };}/** Where a task is (on someone's computer, or with a worker), in the words its tile shows. */@@ -1959,10 +1961,11 @@ async function pollTask(principal: Principal, t: TaskRow, meta: Record<string, u}return { state: "succeeded", outputs: await withLayerBoxes(outputs) };}+ // ComfyUI's own reason (the owner's only: `detail`), when the tab or worker reported one.case "canceled":- return { state: "failed", error: t.error === "switched" ? RELAY_WORDS.switched : t.error === "disconnected" ? RELAY_WORDS.disconnected : RELAY_WORDS.stopped };+ return { state: "failed", error: t.error === "switched" ? RELAY_WORDS.switched : t.error === "disconnected" ? RELAY_WORDS.disconnected : RELAY_WORDS.stopped, ...(t.comfy_why && { detail: t.comfy_why }) };default:- return { state: "failed", ...relayFailure(t, manifest) };+ return { state: "failed", ...relayFailure(t, manifest), ...(t.comfy_why && { detail: t.comfy_why }) };}}diff --git a/src/server/run-details.ts b/src/server/run-details.tsindex 7e3a1bb0..e0bfb5f7 100644--- a/src/server/run-details.ts+++ b/src/server/run-details.ts@@ -110,6 +110,8 @@ export interface RunDetails {/** What a failed run's GPU was missing, and what its GPU or key ran into (stored even where the account wasn't shown it). */fix: { code?: string; workflowId?: string; items?: { folder?: string; file?: string; class?: string; pack?: string }[] } | null;trouble: RunTrouble | null;+ /** ComfyUI's own reason the run failed (its last job's that has one), in one short line: the owner's "Why it failed". */+ comfyReason?: string;where: RunWhere;/** The model the account chose (Auto, or the one it named), beside the composer's default; `ranOn`: the model that made it, when another. */model: { id: string; name: string; state: "default" | "changed" | "unknown"; default?: string; defaultName?: string; ranOn?: { id: string; name: string } };@@ -193,6 +195,8 @@ export interface RunJob {finishedAt?: number;error?: string;note?: string;+ /** ComfyUI's own reason this job failed, in one short line, as its worker or tab reported it. */+ comfyWhy?: string;/** Its computer's ComfyUI didn't answer, since when (and why, when it said). */down?: { at: number; why?: string };}@@ -553,6 +557,7 @@ interface TaskFacts {down_at: number | null;down_why: string | null;progress_json: string | null;+ comfy_why: string | null;created_at: number;claimed_at: number | null;sent_at: number | null;@@ -582,7 +587,7 @@ const col = (have: Set<string>, name: string) => (have.has(name) ? name : `NULLfunction jobsOf(id: string, url?: string): { jobs: RunJob[]; log: WorkerEvent[]; tasks: TaskFacts[] } {const have = columnsOf("relay_tasks");if (!have.size) return { jobs: [], log: [], tasks: [] };- const cols = ["slot", "lane", "class", "requeues", "tried_json", "est_ms", "progress_json"].map((c) => col(have, c)).join(", ");+ const cols = ["slot", "lane", "class", "requeues", "tried_json", "est_ms", "progress_json", "comfy_why"].map((c) => col(have, c)).join(", ");const tasks = db().prepare(`SELECT id, state, workflow_id, attempts, error, note, down_at, down_why, created_at, claimed_at, sent_at, started_at, finished_at, ${cols}@@ -620,6 +625,7 @@ function jobsOf(id: string, url?: string): { jobs: RunJob[]; log: WorkerEvent[];...(t.finished_at != null && { finishedAt: t.finished_at }),...(t.error && { error: scrub(t.error) }),...(t.note && { note: scrub(t.note) }),+ ...(t.comfy_why && { comfyWhy: scrub(t.comfy_why) }),...(t.down_at != null && { down: { at: t.down_at, ...(t.down_why && { why: t.down_why }) } }),};});@@ -766,6 +772,8 @@ export function runDetails(id: string, o: { emails?: boolean } = {}): RunDetails.sort((a, b) => a.createdAt - b.createdAt).map((g) => nearOf(g, req));const chain = chainOf(id, req);+ // A run that ended without its result: ComfyUI's reason, from its last job that reported one.+ const comfyReason = run.status === "failed" || run.status === "canceled" ? jobs.findLast((j) => j.comfyWhy)?.comfyWhy : undefined;return {run: {@@ -780,6 +788,7 @@ export function runDetails(id: string, o: { emails?: boolean } = {}): RunDetailsstored: { message: scrub(raw.message), error: scrub(raw.error), ...(raw.detail && { detail: scrub(raw.detail) ?? undefined }) },fix: Object.keys(fixRest).length ? (redactValue(fixRest, { url: gpu.url }) as RunDetails["fix"]) : null,trouble,+ ...(comfyReason && { comfyReason }),where: whereOf(run, raw, gpu),model: modelChoice(run, chosen),preset: preset ? { id: preset.id, name: preset.name, type: preset.type } : run.presetId ? { id: run.presetId, name: run.presetName ?? run.presetId, type: "unknown" } : null,diff --git a/tests/comfy-reason.test.ts b/tests/comfy-reason.test.tsnew file mode 100644index 00000000..79e267ff--- /dev/null+++ b/tests/comfy-reason.test.ts@@ -0,0 +1,144 @@+import { describe, expect, it } from "vitest";+import { entryReason, executionReason, graphTexts, reasonText, REASON_MAX, refusalReason, withoutKeys } from "@/lib/comfy-reason";++/**+ * ComfyUI's own reason a job failed, as one short line for the owner: its /prompt refusal (`error` and `node_errors`) and+ * its execution error, with the run's words, keys, tokens and folders taken out.+ */++const PROMPT = "a fashion model in a red silk gown on a rooftop at golden hour";+const GRAPH = {+ "3": { class_type: "KSampler", inputs: { seed: 1, sampler_name: "euler" } },+ "6": { class_type: "CLIPTextEncode", inputs: { text: PROMPT } },+ "12": { class_type: "InstantHMRLoader", inputs: { model_name: "detection/instanthmr_medium.safetensors" } },+};++describe("refusals (/prompt answered 400)", () => {+ it("a node type that isn't installed", () => {+ const body = {+ error: {+ type: "missing_node_type",+ message: "Node 'Predict' not found. The custom node may not be installed.",+ details: "Node ID '#12'",+ extra_info: { node_id: "12", class_type: "InstantHMRPredict", node_title: "Predict" },+ },+ node_errors: {},+ };+ expect(refusalReason(body)).toBe("ComfyUI refused the job: node InstantHMRPredict (id 12) isn't installed");+ });++ it("a model file not in the list: its name, never the whole list", () => {+ const body = {+ error: { type: "prompt_outputs_failed_validation", message: "Prompt outputs failed validation", details: "", extra_info: {} },+ node_errors: {+ "12": {+ class_type: "InstantHMRLoader",+ dependent_outputs: ["40"],+ errors: [+ {+ type: "value_not_in_list",+ message: "Value not in list",+ details: "model_name: 'detection/instanthmr_medium.safetensors' not in ['other_a.safetensors', 'other_b.safetensors']",+ extra_info: { input_name: "model_name", input_config: [["other_a.safetensors", "other_b.safetensors"]], received_value: "detection/instanthmr_medium.safetensors" },+ },+ ],+ },+ },+ };+ const why = refusalReason(body)!;+ expect(why).toBe("ComfyUI refused the job: model file detection/instanthmr_medium.safetensors not in the list (model_name of InstantHMRLoader, id 12)");+ expect(why).not.toContain("other_a");+ });++ it("a required input missing, an option not in its list, a value out of range; at most three, then how many more", () => {+ const err = (type: string, extra: Record<string, unknown>, message = "x") => ({ type, message, details: String(extra.input_name ?? ""), extra_info: extra });+ const body = {+ error: { type: "prompt_outputs_failed_validation", message: "Prompt outputs failed validation" },+ node_errors: {+ "3": { class_type: "KSampler", errors: [err("required_input_missing", { input_name: "model" }, "Required input is missing"), err("value_not_in_list", { input_name: "sampler_name", received_value: "eulerx" })] },+ "4": { class_type: "EmptyLatentImage", errors: [err("value_bigger_than_max", { input_name: "width", received_value: 99999 }, "Value 99999 bigger than max of 16384")] },+ "5": { class_type: "VAEDecode", errors: [err("required_input_missing", { input_name: "vae" }, "Required input is missing")] },+ },+ };+ expect(refusalReason(body)).toBe(+ "ComfyUI refused the job: required input model missing (KSampler id 3); value eulerx for sampler_name not in the list (KSampler id 3); Value 99999 bigger than max of 16384 for width (EmptyLatentImage id 4) (+1 more)",+ );+ });++ it("a node's class from the graph when the answer leaves it out", () => {+ const body = { node_errors: { "12": { errors: [{ type: "required_input_missing", message: "Required input is missing", details: "image", extra_info: { input_name: "image" } }] } } };+ expect(refusalReason(body, { graph: GRAPH })).toBe("ComfyUI refused the job: required input image missing (InstantHMRLoader id 12)");+ });++ it("an answer that says nothing gives nothing", () => {+ expect(refusalReason({})).toBeNull();+ expect(refusalReason(null)).toBeNull();+ expect(refusalReason("nope")).toBeNull();+ });++ it("a value that holds the run's words is never named", () => {+ const body = {+ node_errors: {+ "6": { class_type: "CLIPTextEncode", errors: [{ type: "exception_during_validation", message: "Exception when validating node", details: `bad text: ${PROMPT}`, extra_info: { input_name: "text", received_value: PROMPT } }] },+ },+ };+ const why = refusalReason(body, { graph: GRAPH })!;+ expect(why).toContain("CLIPTextEncode id 6");+ expect(why).not.toContain("silk gown");+ expect(why).not.toContain("rooftop");+ });+});++describe("execution errors (/history or the websocket)", () => {+ const traceback = [+ ' File "X:\\fuobe-worker\\ComfyUI\\execution.py", line 496, in execute\n output_data, output_ui, has_subgraph = await get_output_data(...)\n',+ ' File "X:\\fuobe-worker\\ComfyUI\\nodes.py", line 1525, in sample\n return common_ksampler(model, seed, steps)\n',+ ' File "/home/runner/ComfyUI/comfy/samplers.py", line 88, in apply_model\n x = self.inner(x)\n',+ ];++ it("running out of memory: the node, in a few words", () => {+ const data = { node_id: "7", node_type: "KSampler", exception_type: "torch.OutOfMemoryError", exception_message: "CUDA out of memory. Tried to allocate 2.00 GiB. GPU 0 has a total capacity of 31.84 GiB", traceback };+ expect(executionReason(data)).toBe("CUDA out of memory in KSampler (node 7)");+ });++ it("another exception: its type, its first line, and the last frames by file name only", () => {+ const data = { node_id: "7", node_type: "KSampler", exception_type: "RuntimeError", exception_message: "mat1 and mat2 shapes cannot be multiplied (77x2048 and 4096x3072)\nmore lines", traceback };+ const why = executionReason(data)!;+ expect(why).toBe("RuntimeError in KSampler (node 7): mat1 and mat2 shapes cannot be multiplied (77x2048 and 4096x3072) (at nodes.py:1525 sample < samplers.py:88 apply_model)");+ expect(why).not.toMatch(/fuobe-worker|X:\\|\/home\//);+ });++ it("a history entry: its execution error, an interrupt, or only its status", () => {+ const entry = (messages: unknown[]) => ({ status: { status_str: "error", completed: false, messages } });+ expect(entryReason(entry([["execution_start", {}], ["execution_error", { node_id: "5", node_type: "VHS_LoadVideo", exception_type: "Exception", exception_message: "VHS failed to extract audio" }]]))).toBe(+ "Exception in VHS_LoadVideo (node 5): VHS failed to extract audio",+ );+ expect(entryReason(entry([["execution_interrupted", { node_id: "3", node_type: "KSampler" }]]))).toBe("ComfyUI stopped the job (interrupted) in KSampler (node 3)");+ expect(entryReason(entry([]))).toBe("ComfyUI ended the job with an error");+ expect(entryReason({ status: { status_str: "success", messages: [] } })).toBeNull();+ });+});++describe("what a reason never holds", () => {+ it("keys and tokens", () => {+ const raw = "failed with hf_abcdefghijklmnopqrstu and sk-abcdefghijklmnop12 Bearer eyJhbGciOi.payload.sig token=abc123secret 123456789:AAEhBP0av28aBcDeFgHiJkLmNoPqRsTuVwX https://x.test/a?key=zzz&b=1 AbCdEf0123456789AbCdEf0123456789xyz";+ const out = withoutKeys(raw);+ for (const leak of ["hf_abc", "sk-abc", "eyJhbG", "abc123secret", "AAEhBP0", "key=zzz", "AbCdEf0123456789"]) expect(out).not.toContain(leak);+ expect(out).toContain("b=1");+ });++ it("model file names stay, however long", () => {+ const name = "diffusion_models/qwen_image_2512_fp8_e4m3fn_scaled_comfyui_4steps_v1.safetensors";+ expect(withoutKeys(`missing ${name}`)).toBe(`missing ${name}`);+ });++ it("folders, addresses and the run's words; and it is cut short", () => {+ const out = reasonText(`Error loading C:\\Users\\owner\\models\\x.safetensors from http://127.0.0.1:8188/view for ${PROMPT}`, { graph: GRAPH });+ expect(out).toBe("Error loading x.safetensors from [address] for [text]");+ expect(reasonText("x".repeat(5000)).length).toBeLessThanOrEqual(REASON_MAX);+ });++ it("the run's words: each text with a space, never a file name or an option", () => {+ expect(graphTexts({ ...GRAPH, "9": { class_type: "LoadImage", inputs: { image: "my photo.png" } } })).toEqual([PROMPT]);+ });+});diff --git a/tests/pool-account-runs.test.ts b/tests/pool-account-runs.test.tsindex fb471f94..da4790ea 100644--- a/tests/pool-account-runs.test.ts+++ b/tests/pool-account-runs.test.ts@@ -63,6 +63,8 @@ const { FILE_TROUBLE_WORDS, POOL_WORDS } = await import("@/lib/relay");const { ENGINE_WORDS, isEngineWords } = await import("@/lib/engine-error");const { ACCOUNT_MESSAGES } = await import("@/server/account-files");const { catalogVersion } = await import("@/server/computer/catalog-version");+const { refusalReason } = await import("@/lib/comfy-reason");+const { runDetails } = await import("@/server/run-details");const HOST = "localhost:3000";const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };@@ -742,6 +744,112 @@ describe("an account's run that a worker can't finish", () => {// Nothing of it in the run as the account reads it.expect(JSON.stringify(getGeneration(id))).not.toMatch(/VHS|fuobe-worker|ffmpeg/);});++ describe("ComfyUI's own reason, for the owner only", () => {+ const visitorList = async () => {+ const r = await generationsRoute.GET(request("/api/generations?limit=50"));+ return JSON.stringify(await r.json());+ };+ const storedOf = (id: string) => db().prepare("SELECT error, detail FROM generations WHERE id = ?").get(id) as { error: string; detail: string | null };++ it("a refusal: the worker's short reason is the owner's detail and \"Why it failed\"; the account reads the plain sentence", async () => {+ const w = standInWorker();+ beatAs(w);+ const { id, taskId } = await accountRun();+ const api = workerApi(w.token);+ const t = (await api.claim())!;+ const body = {+ error: { type: "missing_node_type", message: "Node 'Predict' not found. The custom node may not be installed.", details: "Node ID '#12'", extra_info: { node_id: "12", class_type: "InstantHMRPredict", node_title: "Predict" } },+ node_errors: {},+ };+ const why = refusalReason(body)!;+ expect(why).toBe("ComfyUI refused the job: node InstantHMRPredict (id 12) isn't installed");+ expect((await api.report(t, { event: "refused", status: 400, body, why })).status).toBe(200);+ expect(rowOf(taskId).comfy_why).toBe(why);+ const g = await ended(id);+ expect(g.status).toBe("failed");+ expect(isEngineWords(g.error), g.error ?? "").toBe(true);+ expect(storedOf(id).detail).toBe(why);+ const owner = listAccountRuns({ account: accountId }).items.find((x) => x.id === id);+ expect(owner?.detail).toBe(why);+ const details = runDetails(id)!;+ expect(details.comfyReason).toBe(why);+ expect(details.stored.detail).toBe(why);+ expect(details.jobs.at(-1)?.comfyWhy).toBe(why);+ // Never in what the account reads: its run, its list.+ expect(JSON.stringify(getGeneration(id))).not.toMatch(/InstantHMR|isn't installed|comfyReason|comfyWhy/);+ expect(await visitorList()).not.toMatch(/InstantHMR|isn't installed|comfyReason|comfyWhy|"detail"/);+ });++ it("an execution error: cleaned again on the server (the run's words, keys and folders out)", async () => {+ const w = standInWorker();+ beatAs(w);+ const { id, taskId } = await accountRun();+ const api = workerApi(w.token);+ const t = (await api.claim())!;+ await api.report(t, { event: "sent", promptId: t.promptId });+ const entry = { prompt: [1, t.promptId], status: { status_str: "error", completed: false, messages: [["execution_error", { node_type: "KSampler", node_id: "3", exception_type: "RuntimeError", exception_message: "shapes" }]] }, outputs: {} };+ // A worker that said too much: the server keeps none of it.+ const why = "RuntimeError in KSampler (node 3): bad input a lighthouse at dusk with hf_abcdefghijklmnopqrstu from X:\\fuobe-worker\\ComfyUI\\nodes.py";+ expect((await api.report(t, { event: "finished", entry, why })).status).toBe(200);+ expect(rowOf(taskId).state).toBe("failed");+ const g = await ended(id);+ expect(isEngineWords(g.error), g.error ?? "").toBe(true);+ const detail = storedOf(id).detail!;+ expect(detail).toBe("RuntimeError in KSampler (node 3): bad input [text] with [key] from nodes.py");+ expect(runDetails(id)!.comfyReason).toBe(detail);+ expect(JSON.stringify(getGeneration(id))).not.toMatch(/RuntimeError|KSampler/);+ expect(await visitorList()).not.toMatch(/RuntimeError|KSampler/);+ });++ it("a job the studio stopped keeps the reason its worker gave before", async () => {+ const w = standInWorker();+ beatAs(w);+ const { id, taskId } = await accountRun();+ const api = workerApi(w.token);+ const t = (await api.claim())!;+ tasks.setTask(taskId, { comfy_why: "CUDA out of memory in KSampler (node 7)" });+ tasks.endTask(t.id, "canceled", { error: "Stopped" });+ const g = await ended(id);+ expect(g.error).not.toMatch(/CUDA|KSampler/);+ expect(storedOf(id).detail).toBe("CUDA out of memory in KSampler (node 7)");+ expect(listAccountRuns({ account: accountId }).items.find((x) => x.id === id)?.detail).toBe("CUDA out of memory in KSampler (node 7)");+ expect(await visitorList()).not.toMatch(/CUDA|KSampler/);+ });++ it("the worker program reads ComfyUI's refusal itself, reports it, and says it when the job ends", async () => {+ const w = standInWorker();+ beatAs(w);+ const { id, taskId } = await accountRun();+ const said: { phase: string; why?: string }[] = [];+ const api = apiAs(routes, null, { authorization: `Bearer ${w.token}` });+ const worker = new ComputerRunner(+ {+ api,+ local: (url, init) => realFetch(url, init),+ socket: (url) => new WebSocket(url) as never,+ sha256,+ origin: "http://localhost:3000",+ sleep: (ms) => new Promise((r) => setTimeout(r, Math.min(ms, 50))),+ compose: (t) => composeOnWorker(t),+ ended: (_t, phase, why) => void said.push({ phase, why }),+ beatExtra: () => ({ protocol: 3, version: "test", local: { paused: false, why: null, until: null }, gpu: { otherApps: [], tempC: null }, inventoryHash: null, warmLane: null, catalogVersion: catalogVersion() }),+ },+ { device: "worker", port: comfy.port, clientId: "worker-test" },+ );+ comfy.opts.failNext = "missing_model";+ await worker.beat();+ await worker.claimAndRun();+ expect(rowOf(taskId).state).toBe("failed");+ const why = rowOf(taskId).comfy_why ?? "";+ expect(why).toMatch(/^ComfyUI refused the job: model file \S+\.\w+ not in the list \(/);+ expect(said.at(-1)).toEqual({ phase: "failed", why });+ const g = await ended(id);+ expect(isEngineWords(g.error), g.error ?? "").toBe(true);+ expect(storedOf(id).detail).toBe(why);+ expect(await visitorList()).not.toMatch(/refused the job|not in the list/);+ });+ });});describe("graphs and results for the workers", () => {