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.

74.4 KB
Raw Blame
import "server-only";
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { nanoid } from "nanoid";
import {
  ACTIVE_STATES,
  DEVICE_ID,
  FACT_LIMITS,
  INPUT_NAME,
  PREVIEW_LIMITS,
  RELAY_LIMITS,
  RELAY_TIMES,
  reportAllowed,
  SENT_STATES,
  UUID,
  type BeatAnswer,
  type ClaimedTask,
  type ComputerFacts,
  type GiveBackWhy,
  type HistoryEntryLike,
  type RelayState,
  type ReportEvent,
  type TaskInput,
  type WantedFile,
  previewOf,
  cleanNodeClass,
  cleanNodeTitle,
} from "@/lib/relay";
import { OUT_OF_MEMORY, reasonText } from "@/lib/comfy-reason";
import { cleanPriority } from "@/lib/run-priority";
import { cleanNodeTimes } from "@/lib/node-times";
import { trackReport, type LiveProgress } from "@/lib/run-progress";
import type { FinishTicket } from "@/lib/finish-ticket";
import type { JobTicket } from "@/lib/job-ticket";
import { DATA_DIR, db, WORKER_JOBS_KEEP_MS } from "../db";
import { runCeilingMs } from "../queue-settings";
import { hostedRunsOn } from "../hosted-switch";
import { jobWords, lastStage, logWorkerEvent, type JobStage } from "./worker-events";

/**
 * "Use the ComfyUI on this computer" (DESIGN.md): the server keeps each ComfyUI job of a run on someone's computer as a
 * task, and that person's Fuobe tab does it. A task holds the graph exactly as the server built it, the inputs it
 * staged (under names it chose), the prompt id it minted, and later the files it asks for. Tasks belong to a principal
 * ("owner", or "acct:<id>"), which every route takes from the session cookie, never from the request: one principal
 * can't see, take, read or fill another's task (an unknown or foreign task is a 404). A task is taken by one tab at a
 * time: each claim hands out a new lease, and every call about the task carries it. One computer at a time runs a
 * principal's waiting tasks (the runner, renewed by its beats); a task a computer took stays with that computer.
 */

/**
 * Whose tasks: the owner's, an account's, or (for a worker, docs/gpu-workers.md) a pool of the owner's GPUs. A task
 * always belongs to the owner or an account (its `principal`); a task for workers also names the pools that may take it
 * (`pools`), and a worker reaches it only through those.
 */
export type Principal = "owner" | `acct:${string}` | `pool:${string}`;

export const isPool = (p: Principal): p is `pool:${string}` => p.startsWith("pool:");

/** The relay's own folder: staged inputs and received outputs. Never served as it is. */
export const relayDir = () => path.join(DATA_DIR, "relay");
const inputFile = (name: string) => path.join(relayDir(), "in", name);
const taskDir = (id: string) => path.join(relayDir(), "tasks", id);
export const outputFile = (id: string, n: number) => path.join(taskDir(id), `out-${n}`);

/** A task's latest preview picture (a worker's JPEG while the job renders), in the task's folder. */
const previewFile = (id: string) => path.join(taskDir(id), "preview.jpg");

export interface Progress extends LiveProgress {
  value?: number;
  max?: number;
  node?: string;
  nodesDone?: number;
  position?: number;
  /** Taken by a worker with another model loaded (or none): loading its model, until its first step reports. */
  cold?: boolean;
  /**
   * When the worker's watchdog last saw the job move (this server's clock: the worker says how long ago, JobMotion).
   * Absent: an older worker, or a tab, which doesn't say.
   */
  movedAt?: number;
  /** How busy the worker's GPU was at its last word (0-100); null when it couldn't say. Absent: it doesn't say. */
  gpuBusy?: number | null;
  /** The running node's class and title (the owner's view only, NodeFacts), as its last report named the node. */
  nodeClass?: string;
  nodeTitle?: string;
  /** A meta-batch job's pass now, of all its passes. */
  pass?: { n: number; of: number };
  at: number;
}

/** A report's NodeFacts, checked: kept only with the node they describe (a report that names another node clears them). */
export function nodeFactsOf(r: Record<string, unknown>): Pick<Progress, "nodeClass" | "nodeTitle" | "pass"> {
  const nodeClass = cleanNodeClass(r.nodeClass);
  const nodeTitle = cleanNodeTitle(r.nodeTitle);
  const p = r.pass && typeof r.pass === "object" ? (r.pass as Record<string, unknown>) : null;
  const n = Number(p?.n);
  const of = Number(p?.of);
  const pass = Number.isInteger(n) && Number.isInteger(of) && n >= 1 && of >= n && of <= 1e5 ? { n, of } : undefined;
  return { ...(nodeClass && { nodeClass }), ...(nodeTitle && { nodeTitle }), ...(pass && { pass }) };
}

/** What a running job's ComfyUI does now, for the owner's views (never a person's): its node, its step or pass. */
export interface JobNow {
  node: string | null;
  nodeClass: string | null;
  nodeTitle: string | null;
  value?: number;
  max?: number;
  pass?: { n: number; of: number };
}

/** A task's JobNow from its kept progress (null: nothing said yet). */
export function jobNowOf(p: Progress | undefined): JobNow | null {
  if (!p || (p.node === undefined && p.nodeClass === undefined && p.max === undefined)) return null;
  return {
    node: p.node ?? null,
    nodeClass: p.nodeClass ?? null,
    nodeTitle: p.nodeTitle ?? null,
    ...(p.max && p.value !== undefined && { value: Math.min(p.value, p.max), max: p.max }),
    ...(p.pass && { pass: p.pass }),
  };
}

/** A "moved ago" longer than this is read as this (a day): no stored time is ever before the job could have moved. */
const MAX_MOVED_AGO_MS = 24 * 3_600_000;

/** A report's or a beat's JobMotion, checked: when it last moved (on `now`'s clock) and how busy its GPU is (0-100, or null). */
export function motionOf(r: Record<string, unknown>, now: number): Pick<Progress, "movedAt" | "gpuBusy"> {
  const ago = typeof r.movedAgoMs === "number" && Number.isFinite(r.movedAgoMs) && r.movedAgoMs >= 0 ? Math.min(r.movedAgoMs, MAX_MOVED_AGO_MS) : undefined;
  const busy = typeof r.gpuBusy === "number" && Number.isFinite(r.gpuBusy) ? Math.round(Math.max(0, Math.min(100, r.gpuBusy))) : r.gpuBusy === null ? null : undefined;
  return { ...(ago !== undefined && { movedAt: Math.round(now - ago) }), ...(busy !== undefined && { gpuBusy: busy }) };
}

/**
 * A task's live progress, as its last report or beat said it. Kept in the database (relay_tasks.progress_json), not in
 * one process's memory: a refresh, a second device and the other app process during a deploy all see the same step.
 */
export const taskProgress = (t: Pick<TaskRow, "progress_json">): Progress | undefined => json<Progress | undefined>(t.progress_json, undefined);

/**
 * A preview picture that comes a little before PREVIEW_LIMITS.everyMs is kept all the same (a worker's timer and the
 * network's delay).
 */
const PREVIEW_SLACK_MS = 300;

/** The relay's tables are made with the database (db.ts RELAY_TABLES). */
const rdb = () => db();

export interface TaskRow {
  id: string;
  principal: Principal;
  generation_id: string;
  state: RelayState;
  device: string | null;
  lease_hash: string | null;
  graph_json: string | null;
  /** An account's task for workers: its job ticket (src/lib/job-ticket.ts), in place of a graph (graph_json is NULL). */
  ticket_json?: string | null;
  /** A finishing job for a worker's CPU slot (src/lib/finish-ticket.ts), in place of a graph (graph_json is NULL). */
  finish_json?: string | null;
  /** The worker slot that takes it: "cpu" (light CPU work, a finishing job), or NULL (its GPU's). */
  slot?: string | null;
  prompt_id: string;
  prefix: string | null;
  meta_batch: number;
  preview: number;
  workflow_id: string | null;
  extra_json: string | null;
  wanted_json: string | null;
  received_json: string | null;
  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;
  /** A worker's slowest nodes for the job, as JSON (src/lib/node-times.ts): for the owner only, like comfy_why. */
  exec_nodes?: string | null;
  stop: number;
  attempts: number;
  down_at: number | null;
  /** Why the computer's ComfyUI can't take it: "setting" (it answers, without Fuobe's setting), else it doesn't answer. */
  down_why: string | null;
  note: string | null;
  /** Workers only (all null for a browser computer's task): see pool.ts. */
  account: string | null;
  pools: string | null;
  rank_at: number | null;
  lane: string | null;
  needs_json: string | null;
  est_ms: number | null;
  tried_json: string | null;
  requeues: number;
  not_after: number | null;
  only_worker: string | null;
  worker_id: string | null;
  /** Its class in the line: "paid", "free" (people's runs) or "owner" (the owner's own jobs, served last). NULL: from before classes, read as "owner" with no account and "free" with one. */
  class: string | null;
  /** The run's priority within its class, from an external service (0 or absent: none; higher first, at most 9). */
  priority?: number | null;
  /** 1: one attempt of it failed (it stalled, or ran past its run limit), and it waits at the back for its last try. */
  failed_once?: number | null;
  /** Its live progress as JSON (taskProgress), and when its latest preview picture came (null: none kept). */
  progress_json: string | null;
  preview_at: number | null;
  created_at: number;
  updated_at: number;
  claimed_at: number | null;
  /** A worker's task sending its files again on the same claim (its ComfyUI lost it): since when. NULL: since its claim. */
  sending_since: number | null;
  sent_at: number | null;
  started_at: number | null;
  finished_at: number | null;
  device_seen_at: number | null;
}

interface InputRow {
  name: string;
  principal: string;
  task_id: string | null;
  n: number | null;
  content_type: string;
  size: number;
  sha256: string;
  reads: number;
  created_at: number;
}

export interface Received {
  n: number;
  bytes: number;
  total: number;
  done: boolean;
  contentType?: string;
}

export const hash = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
export const json = <T,>(s: string | null, fallback: T): T => {
  if (!s) return fallback;
  try {
    return JSON.parse(s) as T;
  } catch {
    return fallback;
  }
};

export function setTask(id: string, fields: Partial<TaskRow>): void {
  const keys = Object.keys(fields);
  if (!keys.length) return;
  rdb()
    .prepare(`UPDATE relay_tasks SET ${keys.map((k) => `${k} = @${k}`).join(", ")}, updated_at = @updated_at WHERE id = @id`)
    .run({ ...fields, updated_at: Date.now(), id });
}

/**
 * A task as a caller of the computer routes reaches it, or null (another principal's task is no task at all). A pool's:
 * a task for workers that this pool may take. The owner's or an account's: a task for its own computer only, never a
 * task for workers, even one of its own runs (only a worker of its pool takes that, and only the server reads it).
 */
export function getTask(principal: Principal, id: string): TaskRow | null {
  if (typeof id !== "string" || !/^[A-Za-z0-9_-]{16}$/.test(id)) return null;
  if (isPool(principal)) {
    const t = rdb().prepare("SELECT * FROM relay_tasks WHERE id = ? AND pools IS NOT NULL").get(id) as TaskRow | undefined;
    return t && poolsOf(t).includes(principal.slice(5)) ? t : null;
  }
  return (rdb().prepare("SELECT * FROM relay_tasks WHERE id = ? AND principal = ? AND pools IS NULL").get(id, principal) as TaskRow | undefined) ?? null;
}

/**
 * A task of one of this principal's runs, wherever it runs (its own computer, or the workers): the server's own reads as
 * the run's principal (a poll, a cancel, a result). Never what a route's caller reaches (that is getTask).
 */
export function ownTask(principal: Principal, id: string): TaskRow | null {
  if (isPool(principal) || typeof id !== "string" || !/^[A-Za-z0-9_-]{16}$/.test(id)) return null;
  return (rdb().prepare("SELECT * FROM relay_tasks WHERE id = ? AND principal = ?").get(id, principal) as TaskRow | undefined) ?? null;
}

/** A task as it is now, by its id: the server's own read of a task it already holds. */
export const taskById = (id: string): TaskRow | null => (rdb().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as TaskRow | undefined) ?? null;

/** What the workers' log says happened to a task. */
export type WorkerJobEvent = "claimed" | "finished" | "requeued" | "done" | "failed" | "canceled";

declare global {
  var __fuobeWorkerJobsPruned: number | undefined;
}

/**
 * Add a row to the workers' log (worker_jobs): which worker took which task, when, and what became of it, with the run's
 * measured time and device when the worker said them. Only ids, times and those facts: never a prompt, a file or an
 * account's details. Rows are never changed; each is kept a year, as the admin API's log is, then removed.
 */
export function logWorkerJob(
  event: WorkerJobEvent,
  t: Pick<TaskRow, "id" | "generation_id" | "principal" | "lane"> & Partial<Pick<TaskRow, "claimed_at" | "finish_json">>,
  workerId: string | null,
  now = Date.now(),
  run: { execMs?: number; device?: string } = {},
  info: { why?: string; tries?: number; variant?: string } = {},
): void {
  try {
    const name = workerId ? ((rdb().prepare("SELECT name FROM relay_workers WHERE id = ?").get(workerId) as { name: string } | undefined)?.name ?? null) : null;
    rdb()
      .prepare("INSERT INTO worker_jobs (at, event, worker_id, worker_name, task_id, generation_id, principal, lane, exec_ms, device) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
      .run(now, event, workerId, name, t.id, t.generation_id, t.principal, t.lane ?? null, run.execMs ?? null, run.device ?? null);
    if (now - (globalThis.__fuobeWorkerJobsPruned ?? 0) > 24 * 60 * 60_000) {
      globalThis.__fuobeWorkerJobsPruned = now;
      rdb().prepare("DELETE FROM worker_jobs WHERE at < ?").run(Date.now() - WORKER_JOBS_KEEP_MS - 60_000);
    }
  } catch (e) {
    console.warn(`[fuobe] Couldn't write the workers' log: ${(e as Error).message}`);
  }
  // The same handoff in the worker's timeline, in words (best-effort, as above).
  const detail = { ...(run.execMs !== undefined && { execMs: run.execMs }), ...(run.device && { device: run.device }), ...(info.why && { why: info.why }), ...(info.tries !== undefined && { tries: info.tries }), ...(info.variant && { variant: info.variant }) };
  logWorkerEvent(
    { kind: "job", event, workerId, words: jobWords(event, t, { execMs: run.execMs, why: info.why, now }), taskId: t.id, generationId: t.generation_id, lane: t.lane ?? null, detail },
    now,
  );
}

/** The stage of a worker's job, from its state and progress (null: it isn't with a worker now). */
export function stageOf(t: Pick<TaskRow, "state" | "progress_json">): JobStage | null {
  switch (t.state) {
    case "sending":
      return "sending";
    case "queued":
      return "queued";
    case "running":
      return taskCold(t) ? "loading" : "running";
    case "collecting":
      return "saving";
    default:
      return null;
  }
}

/**
 * A worker's task may have moved to another stage (a report, its first step): a stage row when it differs from the
 * task's last one on this attempt (`fresh`: a new attempt, always a row). Called at state changes only, never on every
 * progress report. Best-effort.
 */
export function noteStage(id: string, now = Date.now(), detail: Record<string, unknown> = {}, fresh = false): void {
  try {
    const t = rdb().prepare("SELECT id, generation_id, lane, state, progress_json, pools, worker_id, claimed_at FROM relay_tasks WHERE id = ?").get(id) as
      | Pick<TaskRow, "id" | "generation_id" | "lane" | "state" | "progress_json" | "pools" | "worker_id" | "claimed_at">
      | undefined;
    if (!t?.pools || !t.worker_id) return;
    const stage = stageOf(t);
    if (!stage) return;
    const last = fresh ? null : lastStage(t.id);
    if (last && last.event === stage && last.workerId === t.worker_id && last.at >= (t.claimed_at ?? 0)) return;
    const p = taskProgress(t);
    logWorkerEvent(
      {
        kind: "stage",
        event: stage,
        workerId: t.worker_id,
        words: STAGE_WORDS[stage],
        taskId: t.id,
        generationId: t.generation_id,
        lane: t.lane,
        detail: { ...detail, ...(stage === "queued" && p?.position !== undefined && { position: p.position }) },
      },
      now,
    );
  } catch {}
}

const STAGE_WORDS: Record<JobStage, string> = {
  sending: "Sending its files to its ComfyUI",
  queued: "In its ComfyUI's queue",
  loading: "Loading the model",
  running: "Running",
  saving: "Saving the results",
};

/** A row of the workers' log as the owner reads it. */
export interface WorkerJobRow {
  id: number;
  at: number;
  event: WorkerJobEvent;
  workerId: string | null;
  workerName: string | null;
  taskId: string;
  generationId: string;
  principal: string;
  lane: string | null;
  execMs: number | null;
  device: string | null;
}

export interface WorkerJobQuery {
  limit: number;
  before?: number;
  worker?: string;
  generation?: string;
}

/** The workers' log query from a URL: `before` (a row id), `limit` (1 to 200, 50), `worker`, `generation`. */
export function workerJobsQueryFrom(sp: URLSearchParams): WorkerJobQuery | { error: string } {
  const before = sp.get("before");
  if (before !== null && !/^\d{1,15}$/.test(before)) return { error: "before is a row id" };
  const raw = sp.get("limit");
  const limit = raw === null ? 50 : Math.trunc(Number(raw));
  if (!Number.isFinite(limit) || limit < 1 || limit > 200) return { error: "limit is 1 to 200" };
  const worker = sp.get("worker");
  if (worker !== null && !/^[A-Za-z0-9_-]{1,64}$/.test(worker)) return { error: "worker is a worker id" };
  const generation = sp.get("generation");
  if (generation !== null && !/^[A-Za-z0-9_-]{1,64}$/.test(generation)) return { error: "generation is a run id" };
  return { limit, ...(before !== null && { before: Number(before) }), ...(worker !== null && { worker }), ...(generation !== null && { generation }) };
}

/** The workers' log, newest first; `next` is the last row's id (pass it as `before`), null on the last page. */
export function listWorkerJobs(q: WorkerJobQuery): { items: WorkerJobRow[]; next: string | null } {
  const filters: [string, string | number | undefined][] = [
    ["id < ?", q.before],
    ["worker_id = ?", q.worker],
    ["generation_id = ?", q.generation],
  ];
  const used = filters.filter((f): f is [string, string | number] => f[1] !== undefined);
  const where = used.length ? `WHERE ${used.map((f) => f[0]).join(" AND ")}` : "";
  const rows = rdb()
    .prepare(`SELECT * FROM worker_jobs ${where} ORDER BY id DESC LIMIT ?`)
    .all(...used.map((f) => f[1]), q.limit) as { id: number; at: number; event: WorkerJobEvent; worker_id: string | null; worker_name: string | null; task_id: string; generation_id: string; principal: string; lane: string | null; exec_ms: number | null; device: string | null }[];
  return {
    items: rows.map((r) => ({ id: r.id, at: r.at, event: r.event, workerId: r.worker_id, workerName: r.worker_name, taskId: r.task_id, generationId: r.generation_id, principal: r.principal, lane: r.lane, execMs: r.exec_ms, device: r.device })),
    next: rows.length === q.limit ? String(rows[rows.length - 1].id) : null,
  };
}

/** The pools that may take a task (none: a browser computer's). */
export const poolsOf = (t: Pick<TaskRow, "pools">): string[] => (t.pools ? t.pools.split(",").filter(Boolean) : []);

// ---------------------------------------------------------------------------
// Inputs: staged by the server when it plans the run (comfyui.ts prepareFile, ctx.upload)

const extOf = (name: string, contentType: string) => {
  const fromName = name.includes(".") ? name.split(".").pop()!.toLowerCase() : "";
  const ext = /^[a-z0-9]{1,5}$/.test(fromName) ? fromName : (contentType.split("/")[1] ?? "bin").replace(/[^a-z0-9]/g, "").slice(0, 5);
  return ext || "bin";
};

/** Keep an input for a principal's next task: returns the name its graph uses (and ComfyUI will get). */
export function stageInput(principal: Principal, data: Buffer, contentType: string, name: string): string {
  const staged = `fuobe_${nanoid(12).replace(/[^A-Za-z0-9_-]/g, "_")}.${extOf(name, contentType)}`;
  if (!INPUT_NAME.test(staged)) throw new Error("Couldn't name that file");
  fs.mkdirSync(path.dirname(inputFile(staged)), { recursive: true });
  fs.writeFileSync(inputFile(staged), data, { mode: 0o600 });
  rdb()
    .prepare("INSERT INTO relay_inputs (name, principal, task_id, n, content_type, size, sha256, reads, created_at) VALUES (?, ?, NULL, NULL, ?, ?, ?, 0, ?)")
    .run(staged, principal, contentType.split(";")[0].trim().toLowerCase() || "application/octet-stream", data.length, crypto.createHash("sha256").update(data).digest("hex"), Date.now());
  return staged;
}

/** An input a principal staged and no task has taken yet: its SHA-256 and content type (a job ticket names both). */
export function stagedInput(principal: Principal, name: string): { sha256: string; contentType: string } | null {
  const r = rdb().prepare("SELECT sha256, content_type FROM relay_inputs WHERE principal = ? AND name = ? AND task_id IS NULL").get(principal, name) as { sha256: string; content_type: string } | undefined;
  return r ? { sha256: r.sha256, contentType: r.content_type } : null;
}

/** Every string a graph's nodes take (the names of the inputs it loads are among them). */
function graphStrings(graph: Record<string, { inputs?: Record<string, unknown> }>): Set<string> {
  const out = new Set<string>();
  for (const n of Object.values(graph)) for (const v of Object.values(n?.inputs ?? {})) if (typeof v === "string") out.add(v.replace(/ \[input\]$/, ""));
  return out;
}

export interface NewTask {
  principal: Principal;
  generationId: string;
  graph: Record<string, { class_type: string; inputs: Record<string, unknown> }>;
  /**
   * An account's run on the workers: its job ticket. The task then keeps no graph (the worker composes it), and takes the
   * inputs the ticket names.
   */
  ticket?: JobTicket;
  /** A finishing job (src/lib/finish-ticket.ts): no graph and no ticket; the worker's CPU slot runs it with its own code. */
  finish?: FinishTicket;
  prefix?: string;
  metaBatch?: boolean;
  preview?: boolean;
  workflowId?: string;
  /** What the run makes ("image", "video", "audio"…), for the tile's words. */
  made?: string;
  /** The run's LoRAs (for the words of a refusal). */
  loras?: { file: string; url?: string }[];
  /** How many results its workflow says one job makes (an owner's job keeps no more than that, and at least 16). */
  outputs?: number;
  /** More to keep with it (a finishing job's step). */
  extra?: Record<string, unknown>;
  /** For workers (pool.ts): the pools that may take it, and what they need to. */
  pool?: { pools: string[]; account?: string; class?: "paid" | "free" | "owner"; priority?: number; rankAt: number; lane: string; needs: unknown; estMs?: number; notAfter?: number; onlyWorker?: string; slot?: "cpu" };
}

/** A ComfyUI job for a computer: the graph, the inputs it names, and a prompt id minted here. */
export function createTask(t: NewTask): { id: string; promptId: string } {
  const id = nanoid(16).replace(/[^A-Za-z0-9_-]/g, "_");
  const promptId = crypto.randomUUID();
  const now = Date.now();
  const d = rdb();
  const named = t.finish ? new Set(t.finish.inputs.map((i) => i.name)) : t.ticket ? new Set(t.ticket.inputs.map((i) => i.name)) : graphStrings(t.graph);
  d.transaction(() => {
    const pool = t.pool;
    d.prepare(
      `INSERT INTO relay_tasks (id, principal, generation_id, state, graph_json, prompt_id, prefix, meta_batch, preview, workflow_id, extra_json, created_at, updated_at,
         account, pools, rank_at, lane, needs_json, est_ms, not_after, only_worker, class, ticket_json, finish_json, slot, priority)
       VALUES (?, ?, ?, 'waiting', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
    ).run(
      id,
      t.principal,
      t.generationId,
      t.ticket || t.finish ? null : JSON.stringify(t.graph),
      promptId,
      t.prefix ?? null,
      t.metaBatch ? 1 : 0,
      t.preview ? 1 : 0,
      t.workflowId ?? null,
      JSON.stringify({ ...t.extra, made: t.made, loras: t.loras ?? [], ...(t.outputs && { outputs: t.outputs }) }),
      now,
      now,
      pool?.account ?? null,
      pool ? pool.pools.join(",") : null,
      pool ? pool.rankAt : null,
      pool?.lane ?? null,
      pool ? JSON.stringify(pool.needs) : null,
      pool?.estMs ?? null,
      pool?.notAfter ?? null,
      pool?.onlyWorker ?? null,
      pool ? (pool.class ?? (pool.account ? "free" : "owner")) : null,
      t.ticket ? JSON.stringify(t.ticket) : null,
      t.finish ? JSON.stringify(t.finish) : null,
      pool?.slot ?? null,
      cleanPriority(pool?.priority),
    );
    const free = d.prepare("SELECT name FROM relay_inputs WHERE principal = ? AND task_id IS NULL ORDER BY created_at").all(t.principal) as { name: string }[];
    let n = 0;
    for (const f of free) if (named.has(f.name)) d.prepare("UPDATE relay_inputs SET task_id = ?, n = ? WHERE name = ?").run(id, n++, f.name);
  })();
  return { id, promptId };
}

/**
 * One of a task's inputs put in place of another (a job ticket made again, whose graph's own file came out new): `next`
 * is staged as the task's, after its other inputs, and `old` (when given) goes with its file. `next` null: `old` only
 * goes. Returns the new input's name and SHA-256.
 */
export function swapTaskInput(t: Pick<TaskRow, "id" | "principal">, old: string | null, next: { data: Buffer; contentType: string; name: string } | null): { name: string; sha256: string } | null {
  const d = rdb();
  let made: { name: string; sha256: string } | null = null;
  if (next) {
    const name = stageInput(t.principal as Principal, next.data, next.contentType, next.name);
    const n = (d.prepare("SELECT COALESCE(MAX(n), -1) + 1 AS n FROM relay_inputs WHERE task_id = ?").get(t.id) as { n: number }).n;
    d.prepare("UPDATE relay_inputs SET task_id = ?, n = ? WHERE name = ?").run(t.id, n, name);
    made = { name, sha256: crypto.createHash("sha256").update(next.data).digest("hex") };
  }
  if (old) {
    fs.rmSync(inputFile(old), { force: true });
    d.prepare("DELETE FROM relay_inputs WHERE name = ? AND task_id = ?").run(old, t.id);
  }
  return made;
}

/** The names of the inputs a principal staged that no task has taken yet (its next task's files). */
export const freeInputs = (principal: Principal): string[] =>
  (rdb().prepare("SELECT name FROM relay_inputs WHERE principal = ? AND task_id IS NULL").all(principal) as { name: string }[]).map((r) => r.name);

export const inputsOf = (taskId: string) => rdb().prepare("SELECT * FROM relay_inputs WHERE task_id = ? ORDER BY n").all(taskId) as InputRow[];

// ---------------------------------------------------------------------------
// The runner: one computer at a time runs a principal's waiting tasks

interface RunnerRow {
  principal: string;
  device: string;
  lease_until: number;
  seen_at: number;
  port: number | null;
  facts_json: string | null;
  /** Its ComfyUI at the last beat: answering ("ok"), not ("down"), or answering without Fuobe's setting. */
  comfy: "ok" | "down" | "no-setting";
}

const runnerOf = (principal: Principal) => rdb().prepare("SELECT * FROM relay_runners WHERE principal = ?").get(principal) as RunnerRow | undefined;

/**
 * The principal's runner is a ComfyUI paired with a code (Fuobe Connect runs inside ComfyUI, device "connect-…"), not
 * a Fuobe tab: a run waiting for it needs that ComfyUI started, not a tab opened.
 */
export function pairedRunner(principal: Principal): boolean {
  return !!runnerOf(principal)?.device.startsWith("connect-");
}

/** Is a computer of this principal's online: it beat in the last 30 s, and its ComfyUI answered? */
export function runnerOnline(principal: Principal, now = Date.now()): boolean {
  const r = runnerOf(principal);
  return !!r && r.comfy === "ok" && now - r.seen_at < RELAY_TIMES.onlineMs;
}

/**
 * What the computer said about its ComfyUI (the last report), and its port. Online: it beat in the last 30 s and its
 * ComfyUI answered then (a tab whose ComfyUI is closed, or runs without Fuobe's setting, keeps beating: not online).
 */
export function runnerFacts(principal: Principal): (ComputerFacts & { port?: number; seenAt: number; online: boolean; comfy?: "down" | "no-setting" }) | null {
  const r = runnerOf(principal);
  if (!r) return null;
  const here = Date.now() - r.seen_at < RELAY_TIMES.onlineMs;
  return { ...json<ComputerFacts>(r.facts_json, {}), ...(r.port && { port: r.port }), seenAt: r.seen_at, online: here && r.comfy === "ok", ...(here && r.comfy !== "ok" && { comfy: r.comfy }) };
}

/**
 * Forget a principal's computer (it disconnected: `disconnected` when the owner pressed Disconnect, its runs moved
 * elsewhere: `switched`, or the account went).
 */
export function forgetComputer(principal: Principal, why: "Stopped" | "switched" | "disconnected" = "Stopped"): void {
  rdb().prepare("DELETE FROM relay_runners WHERE principal = ?").run(principal);
  for (const t of rdb().prepare(`SELECT id FROM relay_tasks WHERE principal = ? AND pools IS NULL AND state IN (${ACTIVE_STATES.map(() => "?").join(",")})`).all(principal, ...ACTIVE_STATES) as { id: string }[]) {
    endTask(t.id, "canceled", { error: why });
  }
}

const str = (v: unknown, max: number) => (typeof v === "string" && v ? v.slice(0, max) : undefined);
const nonNeg = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined);

/** Facts as kept: known keys, capped lengths, at most 20,000 LoRA names. */
export function cleanFacts(f: unknown, keep?: ComputerFacts): ComputerFacts {
  const o = (f && typeof f === "object" ? f : {}) as Record<string, unknown>;
  const loras = Array.isArray(o.loras)
    ? o.loras.filter((x): x is string => typeof x === "string" && x.length > 0 && x.length <= FACT_LIMITS.loraName).slice(0, FACT_LIMITS.loras)
    : keep?.loras;
  return {
    ...(str(o.device, FACT_LIMITS.text) && { device: str(o.device, FACT_LIMITS.text) }),
    ...(nonNeg(o.vramBytes) !== undefined && { vramBytes: nonNeg(o.vramBytes) }),
    ...(nonNeg(o.ramBytes) !== undefined && { ramBytes: nonNeg(o.ramBytes) }),
    ...(str(o.version, 40) && { version: str(o.version, 40) }),
    ...(str(o.os, 40) && { os: str(o.os, 40) }),
    ...(typeof o.portable === "boolean" && { portable: o.portable }),
    ...((o.cors === "exact" || o.cors === "any" || o.cors === "other") && { cors: o.cors }),
    ...(typeof o.guard === "boolean" && { guard: o.guard }),
    ...(typeof o.gpuGen === "string" && /^\d{1,2}\.\d{1,2}$/.test(o.gpuGen) && { gpuGen: o.gpuGen }),
    ...(o.dynamicVramOff === true && { dynamicVramOff: true as const }),
    ...(loras && { loras }),
  };
}

export interface BeatInput {
  device: string;
  port?: number;
  facts?: unknown;
  /** Tasks this tab is working on, with where each is. */
  running?: { task: string; position?: number; value?: number; max?: number; node?: string; nodesDone?: number }[];
  takeover?: boolean;
  /** Tasks whose prompts this computer took off its ComfyUI, as the server asked. */
  stopped?: string[];
  /** False: this computer's ComfyUI doesn't answer (a phone, a laptop without one, or ComfyUI restarting). */
  ready?: boolean;
  /** Not ready because ComfyUI answers without Fuobe's setting. */
  why?: "setting";
  /** A browser that may not reach this computer's apps yet (it hasn't been allowed): it hears how many wait, never runs them. */
  listen?: boolean;
}

/**
 * A computer's beat: it takes or renews the runner's place when that is free, lapsed, its own, or taken over; it keeps
 * the tasks it works on alive; and it hears which of its prompts to stop. A computer whose ComfyUI doesn't answer only
 * keeps a place it has (its ComfyUI restarting), so a phone or a laptop without ComfyUI never takes the jobs.
 */
export function beat(principal: Principal, b: BeatInput, now = Date.now()): BeatAnswer {
  if (!DEVICE_ID.test(b.device)) throw new RelayError(400, "Bad device");
  const d = rdb();
  sweepPrincipal(principal);
  const cur = runnerOf(principal);
  const elsewhere = !!cur && cur.device !== b.device && cur.lease_until >= now;
  const free = b.listen ? false : b.ready === false ? cur?.device === b.device : !elsewhere || b.takeover === true;
  const port = Number.isInteger(b.port) && b.port! > 0 && b.port! < 65536 ? b.port! : null;
  if (free) {
    const facts = b.facts !== undefined ? cleanFacts(b.facts, json<ComputerFacts>(cur?.facts_json ?? null, {})) : json<ComputerFacts>(cur?.device === b.device ? cur.facts_json : null, {});
    d.prepare(
      `INSERT INTO relay_runners (principal, device, lease_until, seen_at, port, facts_json, comfy) VALUES (?, ?, ?, ?, ?, ?, ?)
       ON CONFLICT(principal) DO UPDATE SET device = excluded.device, lease_until = excluded.lease_until, seen_at = excluded.seen_at, port = excluded.port, facts_json = excluded.facts_json, comfy = excluded.comfy`,
    ).run(principal, b.device, now + RELAY_TIMES.leaseMs, now, port ?? (cur?.device === b.device ? cur.port : null), JSON.stringify(facts), b.ready === false ? (b.why === "setting" ? "no-setting" : "down") : "ok");
  }
  // The tasks this computer works on stay alive, and their live progress is kept.
  for (const r of (b.running ?? []).slice(0, 32)) {
    const t = typeof r?.task === "string" ? getTask(principal, r.task) : null;
    if (!t || t.device !== b.device || !(SENT_STATES as readonly string[]).includes(t.state)) continue;
    setTask(t.id, { device_seen_at: now });
    noteProgress(t.id, r, now, t.lease_hash);
  }
  for (const id of (b.stopped ?? []).slice(0, 64)) {
    const t = typeof id === "string" ? getTask(principal, id) : null;
    if (t?.device === b.device) setTask(t.id, { stop: 0 });
  }
  const stops = (
    d.prepare("SELECT id, prompt_id, prefix FROM relay_tasks WHERE principal = ? AND pools IS NULL AND device = ? AND stop = 1").all(principal, b.device) as { id: string; prompt_id: string; prefix: string | null }[]
  ).map((s) => ({ task: s.id, promptId: s.prompt_id, ...(s.prefix && { prefix: s.prefix }) }));
  const waiting = (d.prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE principal = ? AND pools IS NULL AND state = 'waiting'").get(principal) as { n: number }).n;
  return { runner: free, heldElsewhere: !free && elsewhere, waiting, stops };
}

/**
 * Does a worker's task show live previews: a task on the workers whose run asked for previews, that isn't a finishing
 * job, and whose results aren't checked before anyone sees them (the task's stamp, and its run's: previewShown).
 */
export function showsPreview(t: Pick<TaskRow, "pools" | "preview" | "finish_json" | "extra_json" | "generation_id">): boolean {
  return !!t.pools && !!t.preview && !t.finish_json && !json<{ checkOutputs?: boolean }>(t.extra_json, {}).checkOutputs && previewShown(t.generation_id);
}

/**
 * Note a task's live progress (a report or a beat; never a preview: notePreview), over what it said before. Only while the task is still with the
 * computer or worker that said it (`lease`: the lease it held then, as read with the task): a late report from an attempt
 * another app process sent back in line, ended or gave to another worker meanwhile leaves nothing behind.
 */
export function noteProgress(id: string, r: Record<string, unknown>, now: number, lease: string | null) {
  const p: Omit<Progress, "at"> = {};
  for (const k of ["value", "max", "nodesDone", "position"] as const) {
    const v = nonNeg(r[k]);
    if (v !== undefined) p[k] = Math.min(v, 1e6);
  }
  const node = str(r.node, 64);
  if (node) p.node = node;
  const d = rdb();
  const warmed = d.transaction((): boolean => {
    const cur = d.prepare(`SELECT progress_json, state FROM relay_tasks WHERE id = ? AND ${STILL_HELD}`).get(id, lease) as Pick<TaskRow, "progress_json" | "state"> | undefined;
    if (!cur) return false;
    // Its steps as passes (src/lib/run-progress.ts): a node started since clears the step of the node before.
    // Its motion (a worker's watchdog, JobMotion) over what it said before; a word without it keeps the last.
    const next: Progress = { ...trackReport(taskProgress(cur), p, now), ...(p.position !== undefined && { position: p.position }), ...motionOf(r, now), at: now };
    // The node's class and title go with the node a report names: a report naming a node says them anew.
    if (node) {
      delete next.nodeClass;
      delete next.nodeTitle;
      delete next.pass;
      Object.assign(next, nodeFactsOf(r));
    }
    // Its first step reported: its model is loaded (noteCold), so it is no longer getting ready.
    const wasCold = next.cold === true;
    if (p.value !== undefined) delete next.cold;
    d.prepare(`UPDATE relay_tasks SET progress_json = ? WHERE id = ? AND ${STILL_HELD}`).run(JSON.stringify(next), id, lease);
    return wasCold && next.cold !== true && cur.state === "running";
  }).immediate();
  // Loading the model → running: a stage row.
  if (warmed) noteStage(id, now);
}

/**
 * Note that a task a worker just took starts with its model to load (the worker had another lane's model loaded, or
 * none): it is "getting ready" until its first step reports (noteProgress). Over a fresh attempt's empty progress only.
 */
export function noteCold(id: string, now: number): void {
  rdb().prepare("UPDATE relay_tasks SET progress_json = ? WHERE id = ? AND progress_json IS NULL").run(JSON.stringify({ cold: true, at: now } satisfies Progress), id);
}

/**
 * Keep the highest share a task's run showed in this try (src/lib/run-progress.ts), so a later poll never shows less.
 * Only over the try's own progress, and only higher.
 */
export function noteShown(id: string, share: number): void {
  if (!Number.isFinite(share) || share <= 0) return;
  const v = Math.round(share * 10_000) / 10_000;
  rdb()
    .prepare(
      `UPDATE relay_tasks SET progress_json = json_set(progress_json, '$.shown', ?) WHERE id = ? AND state IN ('running','collecting')
         AND progress_json IS NOT NULL AND json_valid(progress_json) AND COALESCE(json_extract(progress_json, '$.shown'), 0) < ?`,
    )
    .run(v, id, v);
}

/** Is a task still getting ready: taken cold (noteCold), with no step reported since? */
export const taskCold = (t: Pick<TaskRow, "progress_json">): boolean => {
  const p = taskProgress(t);
  return p?.cold === true && p.value === undefined && !p.passes?.length;
};

/** A task still sent to the computer or worker that holds the lease given (the query's last parameter). */
const STILL_HELD = `state IN (${SENT_STATES.map((x) => `'${x}'`).join(",")}) AND lease_hash IS ?`;

/**
 * Does this run show a preview picture while it works? Only with hosted runs on (an install without them shows what it
 * showed before), and not when the moderation service asked to see its outputs before they show (its stamp's
 * `checkOutputs`): a preview would show what the check holds back.
 */
export function previewShown(generationId: string): boolean {
  if (!hostedRunsOn()) return false;
  const g = rdb().prepare("SELECT request_json FROM generations WHERE id = ?").get(generationId) as { request_json: string } | undefined;
  if (!g) return false;
  try {
    return !(JSON.parse(g.request_json) as { checkOutputs?: boolean }).checkOutputs;
  } catch {
    return false;
  }
}


/** A preview picture that couldn't be kept is logged once per app process. */
let previewWarned = false;

/**
 * Keep a worker's preview picture of its job (a JPEG of at most 64 KB, sent as base64 with a "running" report), in
 * place of the one before. One every 2 s at most: one that comes sooner is dropped, as is anything that isn't a JPEG
 * or is too big. Only a worker's task keeps one, and only for a run that shows previews (previewShown); a person's own
 * computer shows its own previews in its tab. Kept only while the attempt that sent it still holds the task: a picture
 * that comes after another app process sent it back in line or ended it is dropped, and no file is left behind.
 */
export function notePreview(
  t: Pick<TaskRow, "id" | "pools" | "preview" | "preview_at" | "lease_hash" | "generation_id" | "finish_json" | "extra_json">,
  base64: unknown,
  now = Date.now(),
): boolean {
  if (t.preview_at && now - t.preview_at < PREVIEW_LIMITS.everyMs - PREVIEW_SLACK_MS) return false;
  // A JPEG of at most PREVIEW_LIMITS.maxBytes (previewOf); a larger one, or anything else, is dropped.
  const jpeg = previewOf(base64);
  if (!jpeg || !showsPreview(t)) return false;
  const data = Buffer.from(jpeg, "base64");
  const file = previewFile(t.id);
  const part = `${file}.${process.pid}.part`;
  const d = rdb();
  let kept = false;
  try {
    fs.mkdirSync(path.dirname(file), { recursive: true });
    fs.writeFileSync(part, data, { mode: 0o600 });
    // The row and the file change together: dropProgress in another process waits for this, then removes both.
    kept = d
      .transaction((): boolean => {
        const changed = d.prepare("UPDATE relay_tasks SET preview_at = ? WHERE id = ? AND state IN ('queued','running') AND lease_hash IS ?").run(now, t.id, t.lease_hash).changes > 0;
        if (changed) fs.renameSync(part, file);
        return changed;
      })
      .immediate();
  } catch (e) {
    // A picture that can't be kept (a full disk, a file a reader has open) is only a picture: the report it came with
    // is taken all the same, and the next picture tries again.
    if (!previewWarned) console.warn(`[fuobe] a preview picture couldn't be kept: ${(e as Error).message}`);
    previewWarned = true;
    kept = false;
  } finally {
    if (!kept) {
      try {
        fs.rmSync(part, { force: true });
      } catch {}
    }
  }
  return kept;
}

/** Forget a task's progress and its preview picture (it ended, or went back in line, or its ComfyUI starts it again). */
export function dropProgress(id: string): void {
  rdb().prepare("UPDATE relay_tasks SET progress_json = NULL, preview_at = NULL WHERE id = ?").run(id);
  // (A picture a reader has open stays until the task's folder goes; nothing serves it once preview_at is gone.)
  try {
    fs.rmSync(previewFile(id), { force: true });
  } catch {}
}

/**
 * The latest preview picture of a run's job on the workers while it works, and when it came; null when there is none.
 * The caller has checked that the run is the viewer's own.
 */
export function runPreview(generationId: string): { path: string; at: number } | null {
  const t = previewTask(generationId);
  if (!t) return null;
  const file = previewFile(t.id);
  return fs.existsSync(file) ? { path: file, at: t.preview_at } : null;
}

const previewTask = (generationId: string) =>
  rdb()
    .prepare("SELECT id, preview_at FROM relay_tasks WHERE generation_id = ? AND pools IS NOT NULL AND state IN ('queued','running') AND preview_at IS NOT NULL ORDER BY created_at DESC LIMIT 1")
    .get(generationId) as { id: string; preview_at: number } | undefined;

/** When a run's latest preview picture came (null: it has none now), for the address its tile loads it from. */
export const runPreviewAt = (generationId: string): number | null => previewTask(generationId)?.preview_at ?? null;

/**
 * A run's own job was made here (a task for it, in any state; a finishing job's, such as a camera path drawn for it,
 * isn't one). On this install's GPUs the job is a row of this database, so a send that was cut off either made it or not.
 */
export const hasJobFor = (generationId: string): boolean => !!rdb().prepare("SELECT 1 FROM relay_tasks WHERE generation_id = ? AND finish_json IS NULL LIMIT 1").get(generationId);

/** A run that ended before it noted its job (a send cut off): that job stops too, in line or on a worker. */
export function stopJobsOf(generationId: string): void {
  const rows = rdb()
    .prepare(`SELECT id FROM relay_tasks WHERE generation_id = ? AND finish_json IS NULL AND state IN (${ACTIVE_STATES.map(() => "?").join(",")})`)
    .all(generationId, ...ACTIVE_STATES) as { id: string }[];
  for (const r of rows) endTask(r.id, "canceled", { error: "Stopped" });
}

/**
 * A computer asks for work: first a task it took before and lost track of (a reload: not in `running`), then, when it is
 * the runner, the oldest waiting task. Null when there is none. The claim gets a new lease each time.
 */
export function claim(principal: Principal, device: string, running: string[], now = Date.now()): ClaimedTask | null {
  if (!DEVICE_ID.test(device)) throw new RelayError(400, "Bad device");
  const d = rdb();
  return d.transaction((): ClaimedTask | null => {
    const mine = d
      .prepare(`SELECT * FROM relay_tasks WHERE principal = ? AND pools IS NULL AND device = ? AND state IN ('sending','queued','running','collecting') AND stop = 0 ORDER BY created_at LIMIT 40`)
      .all(principal, device) as TaskRow[];
    let t: TaskRow | undefined = mine.find((x) => !running.includes(x.id));
    if (!t) {
      const r = runnerOf(principal);
      if (!r || r.device !== device || r.lease_until < now) return null;
      // The oldest waiting task, or one another computer took but never sent and went quiet on.
      t = d
        .prepare(
          `SELECT * FROM relay_tasks WHERE principal = ? AND pools IS NULL AND stop = 0 AND (state = 'waiting' OR (state = 'sending' AND sent_at IS NULL AND device != ? AND device_seen_at < ?))
           ORDER BY created_at LIMIT 1`,
        )
        .get(principal, device, now - RELAY_TIMES.leaseMs) as TaskRow | undefined;
      if (!t) return null;
    }
    return takeTask(t, device, now);
  })();
}

/**
 * Hand a task to a computer or worker (inside the caller's transaction): a new lease, and the task as it is sent. A task
 * this device had already resumes where it was; anything else starts by sending its inputs again.
 */
export function takeTask(t: TaskRow, device: string, now: number, fields: Partial<TaskRow> = {}): ClaimedTask {
  const lease = crypto.randomBytes(32).toString("hex");
  const resume = t.state === "waiting" || t.device !== device ? undefined : (t.state as ClaimedTask["resume"]);
  const fresh = t.state === "waiting" || t.device !== device;
  // A worker's task taken afresh starts its own count of sends: its ComfyUI may lose it once and get it again on this
  // claim (the report "gone"). Across claims, only its requeues count (pool.ts MAX_ATTEMPTS). Its sending clock starts at
  // the claim.
  setTask(t.id, { device, lease_hash: hash(lease), state: t.state === "waiting" ? "sending" : t.state, claimed_at: now, device_seen_at: now, ...(fresh && t.pools && { attempts: 0, sending_since: null }), ...fields });
  if (fresh) {
    rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);
    // A new attempt: nothing of an earlier one shows (no step, no preview picture).
    dropProgress(t.id);
  }
  const inputs: TaskInput[] = inputsOf(t.id).map((i) => ({ n: i.n!, name: i.name, size: i.size, sha256: i.sha256, contentType: i.content_type }));
  // An account's task for workers hands out its job ticket, never a graph (src/lib/job-ticket.ts).
  const ticket = t.ticket_json ? json<JobTicket | null>(t.ticket_json, null) : null;
  // A finishing job hands out its finish ticket (src/lib/finish-ticket.ts): no graph and no job ticket.
  const finish = t.finish_json ? json<FinishTicket | null>(t.finish_json, null) : null;
  return {
    id: t.id,
    generationId: t.generation_id,
    lease,
    ...(finish ? { finish } : ticket ? { ticket } : { graph: json(t.graph_json, {}) }),
    ...(t.slot === "cpu" && { slot: "cpu" as const }),
    // The worker reads "owner" as the owner's job, the only kind that comes as a graph: the owner's hands-on run (no
    // account, in a person's class in the line) is "owner" to it too.
    ...(t.pools && { class: (!t.account || t.class === "owner" ? "owner" : t.class === "paid" ? "paid" : "free") as "paid" | "free" | "owner", ...(t.workflow_id && { workflowId: t.workflow_id }) }),
    promptId: t.prompt_id,
    preview: !!t.preview,
    // A worker sends live previews only of a run that shows them: never of one whose results are checked first.
    ...(showsPreview(t) && { reportPreview: true as const }),
    ...(t.prefix && { prefix: t.prefix }),
    ...(t.meta_batch && { metaBatch: true }),
    inputs,
    ...(resume && { resume }),
    ...(t.state === "collecting" && { wanted: json<WantedFile[]>(t.wanted_json, []), received: json<Received[]>(t.received_json, []).map((r) => ({ n: r.n, bytes: r.bytes, done: r.done })) }),
  };
}

export class RelayError extends Error {
  constructor(
    readonly status: number,
    message: string,
    readonly extra: Record<string, unknown> = {},
  ) {
    super(message);
  }
}

/** A task call: the principal's task, taken with this lease. Unknown or foreign: 404. Another tab took it since: 409. */
export function leased(principal: Principal, id: string, lease: unknown): TaskRow {
  const t = getTask(principal, id);
  if (!t) throw new RelayError(404, "Not found");
  if (typeof lease !== "string" || !/^[0-9a-f]{64}$/.test(lease) || !t.lease_hash || !crypto.timingSafeEqual(Buffer.from(hash(lease)), Buffer.from(t.lease_hash))) {
    throw new RelayError(409, "Another tab is running this now", { code: "lease" });
  }
  return t;
}

/** An input's file for its task's tab, while it sends (a few reads each). */
export function inputFor(t: TaskRow, n: number): { path: string; size: number; contentType: string; sha256: string } {
  if (t.state !== "sending") throw new RelayError(409, "This run isn't sending files now");
  const row = rdb().prepare("SELECT * FROM relay_inputs WHERE task_id = ? AND n = ?").get(t.id, n) as InputRow | undefined;
  if (!row) throw new RelayError(404, "Not found");
  if (row.reads >= RELAY_LIMITS.inputReads) throw new RelayError(429, "That file was sent enough times. Press Retry on the run.");
  rdb().prepare("UPDATE relay_inputs SET reads = reads + 1 WHERE name = ?").run(row.name);
  setTask(t.id, { device_seen_at: Date.now() });
  return { path: inputFile(row.name), size: row.size, contentType: row.content_type, sha256: row.sha256 };
}

/**
 * Ends a task (its inputs go; its outputs stay until the run has kept them). `takeOff`: a prompt already on the
 * computer's ComfyUI is taken off it there (the computer hears it at its next beat): a cancel, or a timeout.
 */
export function endTask(id: string, state: "done" | "failed" | "canceled", fields: Partial<TaskRow> = {}, takeOff = state === "canceled") {
  const t = taskById(id);
  const stop = takeOff && t && t.device && (SENT_STATES as readonly string[]).includes(t.state) ? 1 : 0;
  setTask(id, { state, finished_at: Date.now(), down_at: null, down_why: null, ...(stop && { stop }), ...fields });
  // A task a worker held ends: the workers' log says how.
  if (t?.pools && t.worker_id && (ACTIVE_STATES as readonly string[]).includes(t.state)) logWorkerJob(state, t, t.worker_id, Date.now(), {}, typeof fields.error === "string" ? { why: fields.error } : {});
  dropProgress(id);
  for (const i of rdb().prepare("SELECT name FROM relay_inputs WHERE task_id = ?").all(id) as { name: string }[]) fs.rmSync(inputFile(i.name), { force: true });
  rdb().prepare("DELETE FROM relay_inputs WHERE task_id = ?").run(id);
}

/**
 * What is kept of ComfyUI's /prompt refusal, as the tab reported it: the parts the run's words and "Fix it" read (the
 * error, and each node's errors with the value it got), each cut short, at most 16 KB in all.
 */
export function keptRefusal(body: unknown): { error?: Record<string, unknown>; node_errors?: Record<string, unknown> } | null {
  if (!body || typeof body !== "object") return null;
  const b = body as { error?: unknown; node_errors?: unknown };
  const cut = (v: unknown, n: number) => (typeof v === "string" ? v.slice(0, n) : undefined);
  const obj = (v: unknown) => (v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : undefined);
  const err = obj(b.error);
  const info = obj(err?.extra_info);
  const error = err && { type: cut(err.type, 64), message: cut(err.message, 1024), ...(info && { extra_info: { class_type: cut(info.class_type, 128) } }) };
  const nodes: Record<string, unknown> = {};
  for (const [id, raw] of Object.entries(obj(b.node_errors) ?? {}).slice(0, 24)) {
    const ne = obj(raw);
    const errors = (Array.isArray(ne?.errors) ? ne.errors : []).slice(0, 6).map((x) => {
      const e = obj(x);
      const ei = obj(e?.extra_info);
      return { type: cut(e?.type, 64), message: cut(e?.message, 300), details: cut(e?.details, 300), extra_info: { input_name: cut(ei?.input_name, 64), received_value: cut(ei?.received_value, 256) } };
    });
    nodes[id.slice(0, 32)] = { class_type: cut(ne?.class_type, 128), errors };
  }
  const kept = { ...(error && { error }), node_errors: nodes };
  return 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 };

export interface ReportAnswer {
  ok: true;
  /** Where the task is now (the tab stops when it has ended). */
  state?: RelayState;
  wanted?: WantedFile[];
  follow?: string;
  stop?: boolean;
}

/**
 * A tab's report about its task (each taken only in its state: lib/relay.ts). `plan` turns a finished entry into the
 * files to collect (comfyui.ts, which knows the workflow's outputs).
 */
export function report(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike[], last: boolean) => FinishedPlan, now = Date.now()): ReportAnswer {
  const a = reportOnce(t, e, plan, now);
  return { ...a, state: taskById(t.id)?.state ?? t.state };
}

function reportOnce(t: TaskRow, e: ReportEvent, plan: (entries: HistoryEntryLike[], last: boolean) => FinishedPlan, now: number): ReportAnswer {
  if (t.stop && e.event !== "stopped") return { ok: true, stop: true };
  if (!reportAllowed(e.event, t.state)) {
    if (t.state === "canceled") return { ok: true, stop: true };
    throw 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;
      if (!promptId) throw new RelayError(400, "Bad prompt id");
      // Results a worker kept from an earlier try go up instead of a new render. Each send counts toward this claim's
      // sends all the same, so a ComfyUI that "loses" a job twice on one claim (a resend after each) sends it back in line.
      setTask(t.id, { ...seen, state: "queued", prompt_id: promptId, sent_at: now, attempts: t.attempts + 1 });
      if (t.pools) noteStage(t.id, now);
      return { ok: true };
    }
    case "refused":
      setTask(t.id, { refusal_json: JSON.stringify({ status: Number(e.status) || 400, body: keptRefusal(e.body) }) });
      endTask(t.id, "failed");
      return { ok: true };
    case "queued":
      setTask(t.id, seen);
      noteProgress(t.id, { position: e.position }, now, t.lease_hash);
      return { ok: true };
    case "running":
      setTask(t.id, { ...seen, state: "running", ...(!t.started_at && { started_at: now }), note: null });
      noteProgress(t.id, { ...e, position: undefined }, now, t.lease_hash);
      // A worker's live preview of the job: the tile shows the latest one while the run works. Kept only from a progress
      // report of the attempt that holds the lease, for a run that shows them (notePreview, showsPreview).
      if (e.preview) notePreview({ ...(taskById(t.id) ?? t), lease_hash: t.lease_hash }, e.preview, now);
      // Its ComfyUI started it: loading its model (taken cold) or running. Later reports change no stage here.
      if (t.pools && t.state !== "running") noteStage(t.id, now);
      return { ok: true };
    case "finished":
    case "passes": {
      if (e.event === "passes" && e.running) {
        setTask(t.id, { ...seen, state: "running" });
        if (t.pools && t.state !== "running") noteStage(t.id, now);
        return { ok: true };
      }
      const entries = e.event === "finished" ? [e.entry] : e.entries;
      if (!Array.isArray(entries) || entries.some((x) => !x || typeof x !== "object")) throw new RelayError(400, "Bad history entry");
      // A worker's job that ran out of memory: one it took by streaming its weights from RAM goes to another worker when
      // one can run it, instead of failing (pool.ts sets this).
      if (t.pools && t.worker_id && poolOutOfMemory && ranOutOfMemory(entries, e.why) && poolOutOfMemory(t, now)) return { ok: true };
      const p = plan(entries, e.event === "passes");
      // A worker's job ended on its ComfyUI: the workers' log keeps its measured run (the billing service settles with it,
      // and a lane's typical run is read from it). CPU work (light CPU work, a finishing job) uses no GPU: its time and
      // device are never kept as the run's GPU time.
      const cpuWork = t.slot === "cpu" || !!t.finish_json;
      if (t.pools && t.worker_id && (!("follow" in p) || !t.meta_batch)) logWorkerJob("finished", t, t.worker_id, now, cpuWork ? {} : (execFields(e, t, now) ?? {}));
      // Its slowest nodes, as its worker timed them (the owner's run details show where a slow run's time went).
      const nodes = t.pools && t.worker_id && e.event === "finished" && !e.kept ? cleanNodeTimes(e.nodes, runCeilingMs(t.lane)) : undefined;
      if (nodes) setTask(t.id, { exec_nodes: JSON.stringify(nodes) });
      if ("follow" in p) {
        if (!t.meta_batch) {
          endTask(t.id, "failed", { error: "This run finished without a result. Press Retry." });
          return { ok: true };
        }
        setTask(t.id, { ...seen, state: "running" });
        return { ok: true, follow: p.follow };
      }
      if ("error" in p) {
        endTask(t.id, "failed", { error: p.error });
        return { ok: true };
      }
      const received: Received[] = p.wanted.map((w) => ({ n: w.n, bytes: 0, total: 0, done: false }));
      if (!p.wanted.length) {
        endTask(t.id, "done", { result_json: JSON.stringify(p.outputs), wanted_json: "[]", received_json: "[]" });
        return { ok: true, wanted: [] };
      }
      setTask(t.id, {
        ...seen,
        state: "collecting",
        result_json: JSON.stringify(p.outputs),
        wanted_json: JSON.stringify(p.wanted),
        received_json: JSON.stringify(received),
        extra_json: JSON.stringify({ ...extraOf(t), budget: p.budget }),
      });
      if (t.pools) noteStage(t.id, now, { files: p.wanted.length });
      return { ok: true, wanted: p.wanted };
    }
    case "give-back":
      // Only a worker's task goes back to the line (a person's own computer keeps its jobs).
      if (!t.pools || !poolGiveBack) throw new RelayError(409, "That doesn't fit this run now");
      poolGiveBack(t, e.why);
      return { ok: true };
    case "gone":
      if (t.attempts < 2 && t.state !== "sending") {
        // A worker's task sends its files again: its sending clock (pool.ts SENDING_MS) starts again from now. The
        // attempt's own deadline stays where its claim put it (pool.ts attemptDeadline).
        setTask(t.id, { ...seen, state: "sending", note: "resent", started_at: null, ...(t.pools && { sending_since: now }) });
        dropProgress(t.id);
        rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);
        if (t.pools) noteStage(t.id, now, { resent: true });
        return { ok: true };
      }
      if (t.state === "sending") return { ok: true };
      // A worker's ComfyUI lost it a second time on this claim: back in line as a lost attempt, with its place kept (the
      // line's one budget: pool.ts MAX_ATTEMPTS).
      if (t.pools && poolLost) {
        poolLost(t);
        return { ok: true };
      }
      endTask(t.id, "failed", { error: "lost" });
      return { ok: true };
    case "comfy-down":
      setTask(t.id, { device_seen_at: now, down_why: e.why ?? null, ...(t.down_at ? {} : { down_at: now }) });
      return { ok: true };
    case "stopped":
      setTask(t.id, { stop: 0 });
      return { ok: true };
    case "failed":
      endTask(t.id, "failed", { error: `tab:${e.reason}${e.status ? `:${Number(e.status) | 0}` : ""}` });
      return { ok: true };
  }
}

/** Where an upload of an output stands. */
export function outputStatus(t: TaskRow, n: number): Received {
  const r = json<Received[]>(t.received_json, []).find((x) => x.n === n);
  if (!r) throw new RelayError(404, "Not found");
  return r;
}

/** Bytes in the first part of a file: enough to say what it is. */
export const SNIFF_BYTES = 64;

/**
 * Take part of a wanted output: only while collecting, only a file the server asked for, at exactly the offset already
 * received, never past its size limit, and only once (a finished file can't be sent again). `check` reads the first part
 * and says what the file is (or throws); `whole` reads the whole file once it has arrived, before it counts as saved
 * (or throws); `write` appends the part.
 */
export async function receivePart(
  t: TaskRow,
  n: number,
  o: { offset: number; total: number; length: number },
  write: (file: string, append: boolean) => Promise<{ bytes: number; head: Buffer }>,
  check: (head: Buffer, w: WantedFile, total: number) => string,
  whole?: (file: string, w: WantedFile, contentType: string | undefined) => void,
): Promise<Received> {
  if (t.state !== "collecting") throw new RelayError(409, "This run isn't saving results now");
  const wanted = json<WantedFile[]>(t.wanted_json, []).find((w) => w.n === n);
  if (!wanted) throw new RelayError(404, "Not found");
  const all = json<Received[]>(t.received_json, []);
  const cur = all.find((r) => r.n === n)!;
  if (cur.done) throw new RelayError(409, "That file was saved already");
  if (!Number.isInteger(o.total) || o.total < 1 || o.total > wanted.maxBytes) {
    throw new RelayError(413, wanted.maxBytes >= 2 ** 30 ? "tooBig" : "Your ComfyUI made a file bigger than this run can keep", { fail: true });
  }
  if (cur.total && cur.total !== o.total) throw new RelayError(409, "The file's size changed");
  // All the files together fit the room the run had when it finished.
  const others = all.filter((r) => r.n !== n).reduce((s, r) => s + r.total, 0);
  const budget = extraOf(t).budget ?? Infinity;
  if (others + o.total > budget) throw new RelayError(413, "full", { fail: true });
  if (o.offset !== cur.bytes) throw new RelayError(409, "Wrong place in the file", { received: cur.bytes });
  if (o.offset + o.length > o.total || o.length > RELAY_LIMITS.partBytes) throw new RelayError(413, "Too much at once");
  const file = outputFile(t.id, n);
  fs.mkdirSync(path.dirname(file), { recursive: true });
  const part = `${file}.part`;
  if (o.offset === 0) fs.rmSync(part, { force: true });
  const got = await write(part, o.offset > 0);
  if (got.bytes !== o.length) {
    // Cut short: what arrived is dropped, so the next try starts where this part did.
    fs.truncateSync(part, o.offset);
    throw new RelayError(400, "The part didn't arrive whole");
  }
  let contentType = cur.contentType;
  if (o.offset === 0) {
    try {
      contentType = check(got.head, wanted, o.total);
    } catch (e) {
      fs.rmSync(part, { force: true });
      throw new RelayError(415, (e as Error).message, { fail: true });
    }
  }
  const bytes = o.offset + got.bytes;
  const done = bytes === o.total;
  if (done) {
    try {
      whole?.(part, wanted, contentType);
    } catch (e) {
      fs.rmSync(part, { force: true });
      throw new RelayError(415, (e as Error).message, { fail: true });
    }
    fs.renameSync(part, file);
  }
  const fresh = taskById(t.id);
  const list = json<Received[]>(fresh?.received_json ?? null, all).map((r) => (r.n === n ? { n, bytes, total: o.total, done, ...(contentType && { contentType }) } : r));
  setTask(t.id, { received_json: JSON.stringify(list), device_seen_at: Date.now() });
  if (list.every((r) => r.done)) endTask(t.id, "done");
  return list.find((r) => r.n === n)!;
}

/** A task failed while saving a result (a file that isn't what it should be, or too big). */
export function failTask(t: TaskRow, error: string): void {
  if ((ACTIVE_STATES as readonly string[]).includes(t.state)) endTask(t.id, "failed", { error });
}

/** The tab let go of a task it hadn't sent yet (the tab closes): another tab or computer may take it at once. */
export function release(t: TaskRow): void {
  if (t.state === "sending" && !t.sent_at) {
    setTask(t.id, { state: "waiting", device: null, lease_hash: null, ...(t.pools && { worker_id: null }) });
    rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);
  } else setTask(t.id, { lease_hash: null });
}

/**
 * Stop a task (the run was canceled or timed out): a waiting one ends at once; one a computer took is taken off its
 * ComfyUI at the computer's next beat.
 */
export function requestStop(principal: Principal, id: string): void {
  const t = ownTask(principal, id);
  if (!t || !(ACTIVE_STATES as readonly string[]).includes(t.state)) return;
  endTask(t.id, "canceled", { error: "Stopped" });
}

/** The tasks whose run is no longer going (deleted, canceled from elsewhere) stop: a principal's, or everyone's. */
function sweepPrincipal(principal?: Principal) {
  const orphans = rdb()
    .prepare(
      `SELECT t.id FROM relay_tasks t LEFT JOIN generations g ON g.id = t.generation_id
       WHERE ${principal ? "t.principal = ? AND " : ""}t.state IN (${ACTIVE_STATES.map(() => "?").join(",")}) AND (g.id IS NULL OR g.status NOT IN ('queued','running'))`,
    )
    .all(...(principal ? [principal] : []), ...ACTIVE_STATES) as { id: string }[];
  for (const o of orphans) endTask(o.id, "canceled", { error: "Stopped" });
}

/** A deleted account's computer: its place as runner, its tasks and every file the relay kept for it go. */
export function purgeComputer(principal: Principal): void {
  const d = rdb();
  for (const t of d.prepare("SELECT id FROM relay_tasks WHERE principal = ?").all(principal) as { id: string }[]) {
    fs.rmSync(taskDir(t.id), { recursive: true, force: true });
  }
  for (const i of d.prepare("SELECT name FROM relay_inputs WHERE principal = ?").all(principal) as { name: string }[]) fs.rmSync(inputFile(i.name), { force: true });
  d.transaction(() => {
    d.prepare("DELETE FROM relay_inputs WHERE principal = ?").run(principal);
    d.prepare("DELETE FROM relay_tasks WHERE principal = ?").run(principal);
    d.prepare("DELETE FROM relay_runners WHERE principal = ?").run(principal);
    // Its paired ComfyUIs (Fuobe Connect) stop with it.
    d.prepare("DELETE FROM relay_workers WHERE kind = 'personal' AND principal = ?").run(principal);
    d.prepare("DELETE FROM relay_pairings WHERE principal = ?").run(principal);
  })();
}

declare global {
  var __fuobeRelaySweep: NodeJS.Timeout | undefined;
}

/** Sweep the relay every 15 minutes (once per process), and forget a deleted account's computer with its account. */
export function ensureRelaySweep(onDeleted: (hook: (id: string) => void) => void): void {
  if (globalThis.__fuobeRelaySweep) return;
  const run = () => {
    try {
      sweepRelay();
    } catch (e) {
      console.warn(`[fuobe] relay sweep failed: ${(e as Error).message}`);
    }
  };
  globalThis.__fuobeRelaySweep = setInterval(run, 15 * 60_000);
  globalThis.__fuobeRelaySweep.unref?.();
  onDeleted((id) => purgeComputer(`acct:${id}`));
  run();
}

/**
 * Files and rows nobody needs: tasks whose run stopped going, inputs staged for a task that never came (an hour), and
 * ended tasks (their folders once the run is no longer going, their rows after a day). Every 15 minutes
 * (ensureRelaySweep); a beat sweeps its own principal's.
 */
export function sweepRelay(now = Date.now()): { inputs: number; tasks: number } {
  const d = rdb();
  sweepPrincipal();
  const stale = d.prepare("SELECT name FROM relay_inputs WHERE task_id IS NULL AND created_at < ?").all(now - RELAY_TIMES.stagedMs) as { name: string }[];
  for (const s of stale) fs.rmSync(inputFile(s.name), { force: true });
  d.prepare("DELETE FROM relay_inputs WHERE task_id IS NULL AND created_at < ?").run(now - RELAY_TIMES.stagedMs);
  const ended = d
    .prepare(
      `SELECT t.id, t.finished_at FROM relay_tasks t LEFT JOIN generations g ON g.id = t.generation_id
       WHERE t.state IN ('done','failed','canceled') AND (g.id IS NULL OR g.status NOT IN ('queued','running') OR t.finished_at < ?)`,
    )
    .all(now - RELAY_TIMES.keepMs) as { id: string; finished_at: number | null }[];
  for (const t of ended) {
    fs.rmSync(taskDir(t.id), { recursive: true, force: true });
    d.prepare("UPDATE relay_tasks SET graph_json = NULL, ticket_json = NULL, finish_json = NULL WHERE id = ?").run(t.id);
  }
  const old = d.prepare("DELETE FROM relay_tasks WHERE state IN ('done','failed','canceled') AND finished_at < ?").run(now - RELAY_TIMES.keepMs);
  return { inputs: stale.length, tasks: old.changes };
}

/**
 * The clocks a task's own computer runs on (the run's queue and running clocks are the runner's, generations.ts): a
 * computer that took it and went quiet for 30 minutes, or a ComfyUI that stopped answering for 30 minutes, fails it.
 * Returns the task as it is now.
 */
export function checkClocks(t: TaskRow, now = Date.now()): TaskRow {
  if (t.pools) return poolClocks ? poolClocks(t, now) : t;
  if (!(SENT_STATES as readonly string[]).includes(t.state)) return t;
  if (t.device_seen_at && now - t.device_seen_at > RELAY_TIMES.silentMs) endTask(t.id, "failed", { error: "silent" }, true);
  else if (t.down_at && now - t.down_at > RELAY_TIMES.comfyDownMs) endTask(t.id, "failed", { error: "down" }, true);
  else return t;
  return taskById(t.id) ?? t;
}

/** A task for workers keeps the workers' clocks (pool.ts sets this, so this file needn't import it). */
let poolClocks: ((t: TaskRow, now: number) => TaskRow) | null = null;
export const setPoolClocks = (fn: (t: TaskRow, now: number) => TaskRow) => (poolClocks = fn);

/** A worker gives its task back to the line (pool.ts sets this too). */
let poolGiveBack: ((t: TaskRow, why: GiveBackWhy) => void) | null = null;
export const setPoolGiveBack = (fn: (t: TaskRow, why: GiveBackWhy) => void) => (poolGiveBack = fn);

/** A worker's ComfyUI lost its task again: it goes back in line as a lost attempt (pool.ts sets this too). */
let poolLost: ((t: TaskRow) => void) | null = null;
export const setPoolLost = (fn: (t: TaskRow) => void) => (poolLost = fn);

/**
 * A worker's job ran out of memory (pool.ts sets this too): true when it went back in line for another worker, false
 * when it fails as any failed job does.
 */
let poolOutOfMemory: ((t: TaskRow, now: number) => boolean) | null = null;
export const setPoolOutOfMemory = (fn: (t: TaskRow, now: number) => boolean) => (poolOutOfMemory = fn);

/**
 * Did a finished job end by running out of memory: one of its entries failed with an execution error in those words, or
 * the worker's reason for its failure (`why`) says so.
 */
export function ranOutOfMemory(entries: readonly HistoryEntryLike[], why?: string): boolean {
  const failed = entries.filter((x) => x?.status?.status_str === "error");
  if (!failed.length) return false;
  if (typeof why === "string" && OUT_OF_MEMORY.test(why)) return true;
  return failed.some((x) => (x.status?.messages ?? []).some((m) => Array.isArray(m) && m[0] === "execution_error" && OUT_OF_MEMORY.test(`${m[1]?.exception_type ?? ""} ${m[1]?.exception_message ?? ""}`)));
}

/** The execution time (ms) and GPU name a worker reported with a finished job, as the workers' log keeps them. */
export interface ExecFacts {
  ms: number;
  device?: string;
}

/** ComfyUI starts a job as soon as it takes it, a little before the studio hears "sent": the time allowed for that. */
const SENT_SLACK_MS = 60_000;

/**
 * The execution time a worker reports, held to what is possible: at most a day, at most the run ceiling of the task's
 * lane (queue-settings.ts), and at most the time since it sent the job to its ComfyUI (or, with no send noted, since the
 * task was made). Results kept from an earlier try ran before their "sent" (it notes only the upload): for them, the
 * time since the task was made. With its GPU's name, as the workers' log keeps them (none reported: empty).
 */
function execFields(e: ReportEvent, t: TaskRow, now = Date.now()): { execMs?: number; device?: string } | null {
  if (e.event !== "finished" && e.event !== "passes") return null;
  const since = e.kept ? t.created_at : (t.sent_at ?? t.created_at);
  const most = Math.max(0, Math.min(24 * 3_600_000, runCeilingMs(t.lane), now - since + SENT_SLACK_MS));
  const ms = typeof e.execMs === "number" && Number.isFinite(e.execMs) && e.execMs >= 0 ? Math.min(Math.round(e.execMs), most) : null;
  const device = typeof e.device === "string" && e.device.trim() ? e.device.trim().slice(0, FACT_LIMITS.text) : undefined;
  return { ...(ms !== null && { execMs: ms }), ...(ms !== null && device && { device }) };
}

/** What a worker measured for a task's last finished run (the workers' log): its execution time and its GPU, or null. */
export function execOf(t: Pick<TaskRow, "id">): ExecFacts | null {
  const r = rdb().prepare("SELECT exec_ms, device FROM worker_jobs WHERE task_id = ? AND event = 'finished' ORDER BY id DESC LIMIT 1").get(t.id) as { exec_ms: number | null; device: string | null } | undefined;
  return r && r.exec_ms !== null ? { ms: r.exec_ms, ...(r.device && { device: r.device }) } : null;
}

/** The file of a received output, for the principal whose task it is (anyone else: null). */
export function receivedFile(principal: Principal, taskId: string, n: number): { path: string; contentType?: string } | null {
  const t = ownTask(principal, taskId);
  if (!t) return null;
  const r = json<Received[]>(t.received_json, []).find((x) => x.n === n);
  if (!r?.done) return null;
  const p = outputFile(t.id, n);
  return fs.existsSync(p) ? { path: p, contentType: r.contentType } : null;
}

export const wantedOf = (t: TaskRow) => json<WantedFile[]>(t.wanted_json, []);
export const receivedOf = (t: TaskRow) => json<Received[]>(t.received_json, []);
export const resultOf = <T,>(t: TaskRow) => json<T[]>(t.result_json, []);
export const extraOf = (t: { extra_json?: string | null }) => json<{ made?: string; loras?: { file: string; url?: string }[]; budget?: number; outputs?: number }>(t.extra_json ?? null, {});
export const refusalOf = (t: TaskRow) => json<{ status: number; body: unknown } | null>(t.refusal_json, null);
export const inputKinds = (t: TaskRow) => (rdb().prepare("SELECT content_type FROM relay_inputs WHERE task_id = ?").all(t.id) as { content_type: string }[]).map((r) => r.content_type);