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.

Runner: timeouts from submission, restarts, cancels, live updates, faster results

Claude4bff71b1fedf
diff --git a/src/app/api/generations/stream/route.ts b/src/app/api/generations/stream/route.ts
new file mode 100644
index 00000000..ae67c849
--- /dev/null
+++ b/src/app/api/generations/stream/route.ts
@@ -0,0 +1,17 @@
+import { connection } from "next/server";
+import { ensureRunner } from "@/server/generations";
+import { generationEventStream } from "@/server/live";
+
+/**
+ * Live generation updates (server-sent events), behind the same sign-in as the REST API (proxy):
+ * event: generation data: the Generation JSON, exactly as GET /api/generations returns it
+ * event: deleted data: {"id": "…"}
+ * : ping every 15 s
+ * Sent on every insert or update of a generation row (status, progress, outputs…).
+ */
+export async function GET(request: Request) {
+ // Never prerendered, and the runner that produces the updates is running.
+ await connection();
+ ensureRunner();
+ return generationEventStream(request.signal);
+}
diff --git a/src/instrumentation.ts b/src/instrumentation.ts
new file mode 100644
index 00000000..3d2eab69
--- /dev/null
+++ b/src/instrumentation.ts
@@ -0,0 +1,9 @@
+/**
+ * Runs once when the server starts: start the generation runner right away, so jobs that were in
+ * flight before a restart keep advancing (and live updates flow) even when the UI only lists them.
+ */
+export async function register() {
+ if (process.env.NEXT_RUNTIME !== "nodejs" || process.env.NEXT_PHASE === "phase-production-build") return;
+ const { ensureRunner } = await import("./server/generations");
+ ensureRunner();
+}
diff --git a/src/server/db.ts b/src/server/db.ts
index 994f90a9..296774a4 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -101,6 +101,12 @@ const MIGRATIONS: string[] = [
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS assist_threads_updated ON assist_threads(updated_at DESC);`,
+ // When each generation reached its provider (and when the provider started it): timeouts run from here, not from creation.
+ `CREATE TABLE IF NOT EXISTS generation_runs (
+ id TEXT PRIMARY KEY,
+ submitted_at INTEGER NOT NULL,
+ started_at INTEGER
+ );`,
];
declare global {
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 02a50be6..c62dd4d0 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -23,8 +23,11 @@ import { listElements } from "./elements";
import { pollTrainings } from "./training";
import { createExtendChain, createShotFilm } from "./chains";
import { enhancePrompt } from "./enhance";
+import { setResolver, watchGenerations, type LiveEvent } from "./live";
import { provider } from "./providers";
-import type { RemoteOutput } from "./providers/types";
+import { probeComfy } from "./providers/comfyui";
+import { llmBackends, llmMissing, llmUsesClaude, probeOllama } from "./providers/llm";
+import type { PollContext, RemoteOutput } from "./providers/types";
import { convertMask } from "./png";
import { engineMode, getSetting } from "./settings";
import { contentTypeFor, readRef, saveFile } from "./storage";
@@ -163,15 +166,35 @@ export function chooseRoute(candidates: ModelRoute[]): { route: ModelRoute; demo
const routes = preferred === "auto" ? candidates : [...candidates].sort((a, b) => Number(b.provider === preferred) - Number(a.provider === preferred));
const demo = getSetting("demoMode");
if (demo === "on") return { route: routes[0], demo: true };
- const real = routes.find((r) => provider(r.provider).isConfigured());
+ const real = routes.find(routeReady);
if (real) return { route: real, demo: false };
if (demo === "off") {
+ if (routes.every((r) => r.provider === "llm")) throw new Error(llmMissing(routes[0]));
const names = [...new Set(routes.map((r) => provider(r.provider).label))].join(" or ");
throw new Error(`Connect ${names} in Settings to run this model`);
}
return { route: routes[0], demo: true };
}
+/** Text steps depend on which LLM the route may use (the open model never calls Claude). */
+const routeReady = (r: ModelRoute) => (r.provider === "llm" ? llmBackends(r).length > 0 : provider(r.provider).isConfigured());
+
+/** What a run produces: colour matching works on images and videos, so it follows the model. */
+export function outputKind(op: Generation["op"], model: { kind: MediaKind }): MediaKind {
+ return op === "color-match" ? model.kind : OPERATION_OUTPUT[op];
+}
+
+// Live updates: every write to the table becomes an event (src/server/live.ts). A trashed row
+// (soft delete, when the table has one) leaves the feeds like a deleted one.
+setResolver((ids) =>
+ ids.map((id): LiveEvent => {
+ const r = db().prepare("SELECT * FROM generations WHERE id = ?").get(id) as (Row & { deleted_at?: number | null; trashed_at?: number | null }) | undefined;
+ const g = r && (toGeneration(r) as Generation & { deletedAt?: number | null; trashedAt?: number | null });
+ if (!r || !g || r.deleted_at || r.trashed_at || g.deletedAt || g.trashedAt) return { type: "deleted", id, json: JSON.stringify({ id }) };
+ return { type: "generation", id, json: JSON.stringify(g) };
+ }),
+);
+
// ---------------------------------------------------------------------------
// Create
@@ -189,17 +212,32 @@ function prepare(original: GenerationRequest) {
: `${plan.model.name} is an open-source model, but this install is set to paid cloud APIs only (Settings → Engine mode)`,
);
}
+ // Checks planGeneration can't make without knowing the model's kind or the text ops' needs.
+ if (plan.op === "color-match" && plan.model.kind === "video" && !req.inputs?.video) throw new Error("Add the video and a reference image");
+ if (plan.op === "translate" && !plan.params.targetLanguage) throw new Error("Pick a language to translate into");
const { route, demo } = chooseRoute(routesFor(plan.model, plan.op));
const providerId: ProviderId = demo ? "mock" : route.provider;
- return { req, plan, route, demo, providerId, cost: demo ? 0 : estimateCost(plan.model, plan.params, 1) };
+ // A text step that runs on Ollama is free; only Claude costs money.
+ const free = demo || (route.provider === "llm" && !llmUsesClaude(route));
+ return { req, plan, route, demo, providerId, cost: free ? 0 : estimateCost(plan.model, plan.params, 1) };
}
+
/** What a request would run as — model, operation, job count and cost — without starting it. */
export function previewGeneration(req: GenerationRequest) {
const { plan, demo, providerId, cost } = prepare(req);
return { model: plan.model, op: plan.op, jobs: plan.jobs, outputs: plan.jobs * plan.perJobOutputs, demo, providerId, costUsd: cost === null ? null : cost * plan.jobs };
}
+/** Preview a step that will wait for `deps` earlier steps: validated with placeholders in its chain slots, as createGenerations does. */
+export function previewChained(req: GenerationRequest, deps: number) {
+ if (!deps) return previewGeneration(req);
+ // A waiting step always runs as one job (createGenerations doesn't batch dependents).
+ const p = previewGeneration(withChainInputs(req, slotsFor(req, deps).map(placeholderFor)));
+ const jobs = Math.max(1, p.jobs);
+ return { ...p, jobs: 1, outputs: p.outputs / jobs, costUsd: p.costUsd === null ? null : p.costUsd / jobs };
+}
+
export interface CreateOptions {
/** Group several requests (storyboard frames, the shots of a film) into one batch. */
batchId?: string;
@@ -241,11 +279,12 @@ export function createGenerations(original: GenerationRequest, opts: CreateOptio
engine: plan.model.engine,
provider: providerId,
op: plan.op,
- kind: OPERATION_OUTPUT[plan.op],
+ kind: outputKind(plan.op, plan.model),
status: "queued",
progress: null,
message: waits ? (original.frame ? "Waits for the previous frame" : "Waits for the earlier steps") : demo ? "Demo mode — no provider connected" : "Submitting",
- prompt: plan.prompt,
+ // A step whose prompt comes from an earlier step shows its own words (not the placeholder) until then.
+ prompt: waits && req.chain?.some((s) => s.slot === "prompt") ? original.prompt?.replaceAll("{text}", "…").trim() || null : plan.prompt,
request_json: JSON.stringify(original),
provider_input_json: null,
external_id: null,
@@ -275,8 +314,8 @@ export function createGenerations(original: GenerationRequest, opts: CreateOptio
/** Where each dependency's output goes: `chain`, or the single-image `chainFrom`. */
function slotsFor(req: GenerationRequest, n: number): ChainSlot[] {
- if (req.chain?.length) return req.chain.slice(0, n);
- return Array.from({ length: n }, () => ({ slot: "images" as const, position: req.chainFrom ?? "last" }));
+ // Dependencies beyond the listed slots are images (a chain shorter than dependsOn used to crash the launch).
+ return Array.from({ length: n }, (_, i) => req.chain?.[i] ?? { slot: "images" as const, position: req.chainFrom ?? "last" });
}
const SLOT_KIND: Record<ChainSlot["slot"], MediaKind> = {
@@ -295,9 +334,20 @@ function placeholderFor(s: ChainSlot): string {
return kind === "image" ? "/api/files/placeholder.png" : kind === "video" ? "/api/files/placeholder.mp4" : "/api/files/placeholder.wav";
}
-/** What a chained step takes from a dependency's output: the file URL, or the text for "prompt". */
-function chainValue(o: OutputFile | undefined, s: ChainSlot): string | undefined {
- return s.slot === "prompt" ? o?.text : o?.url;
+/**
+ * What a chained step takes from a dependency's output: the file URL, or the text for "prompt".
+ * A translation of timed text gets the cue list (so the timing survives); text saved only as a
+ * file is read back from it.
+ */
+async function chainValue(o: OutputFile | undefined, s: ChainSlot, op?: Generation["op"]): Promise<string | undefined> {
+ if (!o) return undefined;
+ if (s.slot !== "prompt") return o.url;
+ if (op === "translate" && Array.isArray(o.meta?.cues) && o.meta.cues.length) return JSON.stringify(o.meta.cues);
+ if (typeof o.text === "string") return o.text;
+ if (!o.url) return undefined;
+ return readRef(o.url)
+ .then((f) => f.data.toString("utf8"))
+ .catch(() => undefined);
}
/**
@@ -321,50 +371,96 @@ export function withChainInputs(req: GenerationRequest, urls: string[]): Generat
return { ...req, prompt, inputs };
}
-/** Launch dependent jobs whose inputs finished; fail the ones whose inputs failed. */
-const launching = new Set<string>();
+/** Generations this process is handing to a provider right now (shared across hot reloads and bundles). */
+declare global {
+ var __fuobeSubmitting: Set<string> | undefined;
+}
+const submitting = (): Set<string> => (globalThis.__fuobeSubmitting ??= new Set<string>());
+
+/**
+ * A chain runs all for real or all as a demo (a demo join of paid clips, or a paid step fed a demo
+ * placeholder, helps nobody). Returns the error for a step that can't match its dependencies, and
+ * whether it should run as a demo because they did.
+ */
+function chainMode(p: { demo: boolean; plan: { model: { name: string } }; route: ModelRoute }, deps: Pick<Row, "provider">[]): { error?: string; forceDemo?: boolean } {
+ const demoDeps = deps.filter((d) => d.provider === "mock").length;
+ if (p.demo && demoDeps < deps.length) {
+ const needs = p.route.provider === "llm" ? "Claude or Ollama" : provider(p.route.provider).label;
+ return { error: `${p.plan.model.name} needs ${needs} to continue what the earlier steps made for real — connect it in Settings, then retry` };
+ }
+ if (!p.demo && demoDeps > 0) {
+ if (getSetting("demoMode") === "off") return { error: "An earlier step ran as a demo — retry it with its provider connected" };
+ return { forceDemo: true };
+ }
+ return {};
+}
+
+/** Launch dependent jobs whose inputs finished; fail the ones whose inputs failed. Never waits for an upload. */
async function advanceDependents(): Promise<void> {
const rows = db()
.prepare("SELECT * FROM generations WHERE status = 'queued' AND external_id IS NULL AND depends_on IS NOT NULL ORDER BY created_at ASC LIMIT 50")
.all() as Row[];
for (const r of rows) {
- if (launching.has(r.id)) continue;
+ if (submitting().has(r.id)) continue;
const request = JSON.parse(r.request_json) as GenerationRequest;
const ids = depIds(r.depends_on);
const slots = slotsFor(request, ids.length);
- const deps = ids.map((id) => db().prepare("SELECT status, outputs_json FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "outputs_json"> | undefined);
+ const deps = ids.map((id) => db().prepare("SELECT status, provider, outputs_json FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "provider" | "outputs_json"> | undefined);
const earlier = request.frame ? "The previous frame" : "An earlier step";
if (deps.some((d) => !d || d.status === "failed" || d.status === "canceled")) {
update(r.id, { status: "failed", error: `${earlier} didn't finish`, message: null, completed_at: Date.now() });
continue;
}
if (deps.some((d) => d!.status !== "succeeded")) continue;
- const urls = deps.map((d, i) => chainValue((JSON.parse(d!.outputs_json) as OutputFile[]).find((o) => o.kind === SLOT_KIND[slots[i].slot]), slots[i]));
- if (urls.some((u) => !u)) {
- update(r.id, { status: "failed", error: `${earlier} has no ${SLOT_KIND[slots[urls.findIndex((u) => !u)].slot]} to use`, message: null, completed_at: Date.now() });
- continue;
- }
- launching.add(r.id);
+ submitting().add(r.id);
+ let handedOff = false;
try {
- const original = withChainInputs(request, urls as string[]);
- const { req, plan, route, providerId, cost, demo } = prepare(original);
+ const values = await Promise.all(
+ deps.map((d, i) => chainValue((JSON.parse(d!.outputs_json) as OutputFile[]).find((o) => o.kind === SLOT_KIND[slots[i].slot]), slots[i], request.op)),
+ );
+ const missing = values.findIndex((u) => !u);
+ if (missing >= 0) {
+ update(r.id, { status: "failed", error: `${earlier} has no ${SLOT_KIND[slots[missing].slot]} to use`, message: null, completed_at: Date.now() });
+ continue;
+ }
+ // Routing reads cached reachability: make sure it's fresh for local engines.
+ const model = getModel(request.modelId);
+ if (model?.routes.some((x) => x.provider === "comfyui")) await probeComfy();
+ if (model?.routes.some((x) => x.provider === "llm")) await probeOllama();
+ const original = withChainInputs(request, values as string[]);
+ const prepared = prepare(original);
+ const mode = chainMode(prepared, deps as Pick<Row, "provider">[]);
+ if (mode.error) throw new Error(mode.error);
+ const p = mode.forceDemo ? { ...prepared, demo: true, providerId: "mock" as const, cost: 0 } : prepared;
update(r.id, {
- provider: providerId,
- op: plan.op,
- prompt: plan.prompt,
- cost_usd: cost,
+ provider: p.providerId,
+ op: p.plan.op,
+ kind: outputKind(p.plan.op, p.plan.model),
+ prompt: p.plan.prompt,
+ cost_usd: p.cost,
request_json: JSON.stringify(original),
- message: demo ? "Demo mode — no provider connected" : "Submitting",
+ message: mode.forceDemo ? "Demo — an earlier step ran as a demo" : p.demo ? "Demo mode — no provider connected" : "Submitting",
});
- await submit(r.id, route, providerId, plan, req, 0);
+ // In the background: an upload must not hold up the runner's other polls.
+ handedOff = true;
+ void submit(r.id, p.route, p.providerId, p.plan, p.req, 0);
} catch (e) {
update(r.id, { status: "failed", error: (e as Error).message, message: null, completed_at: Date.now() });
} finally {
- launching.delete(r.id);
+ if (!handedOff) submitting().delete(r.id);
}
}
}
+const statusOf = (id: string) => (db().prepare("SELECT status FROM generations WHERE id = ?").get(id) as Pick<Row, "status"> | undefined)?.status;
+
+/** Start the timeout clock: the job has reached its provider. */
+function recordSubmission(id: string, at: number): void {
+ db()
+ .prepare("INSERT INTO generation_runs (id, submitted_at, started_at) VALUES (?, ?, NULL) ON CONFLICT(id) DO UPDATE SET submitted_at = excluded.submitted_at, started_at = NULL")
+ .run(id, at);
+}
+
async function submit(
id: string,
route: ModelRoute,
@@ -374,6 +470,7 @@ async function submit(
index: number,
): Promise<void> {
const adapter = provider(providerId);
+ submitting().add(id);
try {
const prep = async (ref?: string) => {
if (!ref) return undefined;
@@ -410,14 +507,28 @@ async function submit(
seed: plan.params.seed !== undefined && plan.params.seed >= 0 ? plan.params.seed + index : undefined,
};
const res = await adapter.submit({ generationId: id, model: plan.model, route, input });
- update(id, {
- external_id: res.externalId,
- external_meta_json: JSON.stringify(res.meta ?? {}),
- provider_input_json: res.payload ? JSON.stringify(res.payload).slice(0, 200_000) : null,
- message: "Queued",
- });
+ const now = Date.now();
+ const status = statusOf(id);
+ if (!status || status === "canceled") {
+ // Canceled (or deleted) while it was being handed over: stop the provider's job too.
+ await adapter.cancel?.({ externalId: res.externalId, meta: res.meta ?? {}, route, model: plan.model, createdAt: now }).catch(() => {});
+ if (status) update(id, { external_id: res.externalId, external_meta_json: JSON.stringify(res.meta ?? {}), message: null });
+ return;
+ }
+ db().transaction(() => {
+ update(id, {
+ external_id: res.externalId,
+ external_meta_json: JSON.stringify(res.meta ?? {}),
+ provider_input_json: res.payload ? JSON.stringify(res.payload).slice(0, 200_000) : null,
+ message: "Queued",
+ });
+ recordSubmission(id, now);
+ })();
} catch (e) {
- update(id, { status: "failed", error: (e as Error).message, completed_at: Date.now(), message: null });
+ // A cancel during the hand-over stays a cancel.
+ if (statusOf(id) !== "canceled") update(id, { status: "failed", error: (e as Error).message, completed_at: Date.now(), message: null });
+ } finally {
+ submitting().delete(id);
}
}
@@ -425,27 +536,87 @@ async function submit(
// Polling loop
const POLL_MS = 1500;
+/** Jobs about to finish (progress ≥ 0.9) are polled this often, so results land sooner. */
+const FAST_POLL_MS = 500;
+/** How long a job may run once its provider has started it… */
const TIMEOUT_MS = 45 * 60 * 1000;
+/** …and how long it may wait in the provider's queue first (a busy local GPU works through jobs one by one). */
+const QUEUE_TIMEOUT_MS = 4 * 60 * 60 * 1000;
+/** A row this old with no external id, that no submit in this process is working on, was cut off by a restart. */
+const STALE_SUBMIT_MS = 2 * 60 * 1000;
+
+interface RunnerState {
+ timer: NodeJS.Timeout;
+ busy: boolean;
+ tick: () => Promise<void>;
+ fastTimer?: NodeJS.Timeout;
+ fastBusy?: boolean;
+ fast?: () => Promise<void>;
+ /** Rows being polled right now (the fast lane and the tick never poll one row twice at once). */
+ polling?: Set<string>;
+}
declare global {
- var __fuobeRunner: { timer: NodeJS.Timeout; busy: boolean; tick: () => Promise<void> } | undefined;
+ var __fuobeRunner: RunnerState | undefined;
}
+/**
+ * Start the background runner (once per process; started at boot by src/instrumentation.ts).
+ * Also installs the live-update hooks and primes the reachability probes routing reads.
+ */
export function ensureRunner(): void {
- if (globalThis.__fuobeRunner) {
- // After a dev hot-reload, point the existing timer at this module's (fresh) code.
- globalThis.__fuobeRunner.tick = tick;
+ watchGenerations(db());
+ const cur = globalThis.__fuobeRunner;
+ if (cur) {
+ // After a dev hot-reload, point the existing timers at this module's (fresh) code.
+ cur.tick = tick;
+ cur.fast = fastTick;
+ cur.polling ??= new Set();
+ if (!cur.fastTimer) {
+ cur.fastTimer = setInterval(() => void globalThis.__fuobeRunner?.fast?.(), FAST_POLL_MS);
+ cur.fastTimer.unref?.();
+ }
return;
}
- const state = { busy: false, tick, timer: setInterval(() => void globalThis.__fuobeRunner?.tick(), POLL_MS) };
+ const state: RunnerState = {
+ busy: false,
+ tick,
+ fast: fastTick,
+ polling: new Set(),
+ timer: setInterval(() => void globalThis.__fuobeRunner?.tick(), POLL_MS),
+ fastTimer: setInterval(() => void globalThis.__fuobeRunner?.fast?.(), FAST_POLL_MS),
+ };
state.timer.unref?.();
+ state.fastTimer?.unref?.();
globalThis.__fuobeRunner = state;
- // Jobs that never got an external id (server died mid-submit) can't be recovered.
- db()
- .prepare(
- "UPDATE generations SET status = 'failed', error = 'Interrupted before it reached the provider', completed_at = ? WHERE status IN ('queued','running') AND external_id IS NULL AND depends_on IS NULL AND created_at < ?",
- )
- .run(Date.now(), Date.now() - 2 * 60 * 1000);
+ void probeComfy().catch(() => false);
+ void probeOllama().catch(() => false);
+ sweepInterrupted();
+}
+
+/** Jobs that never got an external id (the server died mid-submit) can't be recovered. Runs every tick. */
+function sweepInterrupted(): void {
+ const rows = db()
+ .prepare("SELECT id FROM generations WHERE status IN ('queued','running') AND external_id IS NULL AND depends_on IS NULL AND created_at < ?")
+ .all(Date.now() - STALE_SUBMIT_MS) as Pick<Row, "id">[];
+ const busy = submitting();
+ for (const r of rows) {
+ if (busy.has(r.id)) continue;
+ update(r.id, { status: "failed", error: "Interrupted before it reached the provider", completed_at: Date.now(), message: null });
+ }
+}
+
+async function pollGuarded(r: Row): Promise<void> {
+ const polling = (globalThis.__fuobeRunner!.polling ??= new Set());
+ if (polling.has(r.id)) return;
+ polling.add(r.id);
+ try {
+ await pollOne(r);
+ } catch (e) {
+ update(r.id, { message: `Poll error: ${(e as Error).message}` });
+ } finally {
+ polling.delete(r.id);
+ }
}
async function tick(): Promise<void> {
@@ -453,38 +624,81 @@ async function tick(): Promise<void> {
if (!state || state.busy) return;
state.busy = true;
try {
+ sweepInterrupted();
const active = db()
.prepare("SELECT * FROM generations WHERE status IN ('queued','running') AND external_id IS NOT NULL ORDER BY created_at ASC LIMIT 50")
.all() as Row[];
- await Promise.all([
- ...active.map((r) => pollOne(r).catch((e) => update(r.id, { message: `Poll error: ${(e as Error).message}` }))),
- pollTrainings().catch(() => {}),
- advanceDependents().catch(() => {}),
- ]);
+ await Promise.all([...active.map(pollGuarded), pollTrainings().catch(() => {}), advanceDependents().catch(() => {})]);
} finally {
state.busy = false;
}
}
+async function fastTick(): Promise<void> {
+ const state = globalThis.__fuobeRunner;
+ if (!state || state.fastBusy) return;
+ state.fastBusy = true;
+ try {
+ const rows = db()
+ .prepare(
+ "SELECT g.*, r.started_at AS run_started_at FROM generations g LEFT JOIN generation_runs r ON r.id = g.id WHERE g.status = 'running' AND g.external_id IS NOT NULL AND g.progress IS NOT NULL ORDER BY g.created_at ASC LIMIT 50",
+ )
+ .all() as (Row & { run_started_at: number | null })[];
+ const now = Date.now();
+ // At 90% (or on course to be there by now, at the pace it has reported since it started).
+ const nearlyDone = rows.filter((r) => {
+ const p = r.progress ?? 0;
+ if (p >= 0.9) return true;
+ const ran = r.run_started_at ? r.updated_at - r.run_started_at : 0;
+ return ran > 0 && p > 0 && (p * (now - r.run_started_at!)) / ran >= 0.9;
+ });
+ await Promise.all(nearlyDone.slice(0, 20).map(pollGuarded));
+ } finally {
+ state.fastBusy = false;
+ }
+}
+
+function runRoute(model: NonNullable<ReturnType<typeof getModel>>, r: Pick<Row, "op" | "provider">): ModelRoute {
+ return model.routes.find((x) => x.op === r.op && (x.provider === r.provider || r.provider === "mock")) ?? model.routes[0];
+}
+
+function pollContext(r: Row, model: NonNullable<ReturnType<typeof getModel>>): PollContext {
+ return { externalId: r.external_id!, meta: JSON.parse(r.external_meta_json ?? "{}") as Record<string, unknown>, route: runRoute(model, r), model, createdAt: r.created_at };
+}
+
async function pollOne(r: Row): Promise<void> {
const model = getModel(r.model_id);
if (!model) {
update(r.id, { status: "failed", error: `Model ${r.model_id} no longer exists`, completed_at: Date.now() });
return;
}
- if (Date.now() - r.created_at > TIMEOUT_MS) {
- update(r.id, { status: "failed", error: "Timed out", completed_at: Date.now() });
+ // The clock runs from when the provider got the job (and from when it started it), not from creation:
+ // a chained step created at the start of a long pipeline gets its full time once it's submitted.
+ const now = Date.now();
+ let run = db().prepare("SELECT submitted_at, started_at FROM generation_runs WHERE id = ?").get(r.id) as { submitted_at: number; started_at: number | null } | undefined;
+ if (!run) {
+ // Submitted before this was recorded (an upgrade mid-job): start counting now.
+ recordSubmission(r.id, now);
+ run = { submitted_at: now, started_at: null };
+ }
+ const overdue = run.started_at ? now - run.started_at > TIMEOUT_MS : now - run.submitted_at > QUEUE_TIMEOUT_MS;
+ const ctx = pollContext(r, model);
+ if (overdue) {
+ // Stop the provider's job too, so it doesn't keep rendering (or billing) for nothing.
+ await provider(r.provider)
+ .cancel?.(ctx)
+ .catch(() => {});
+ update(r.id, {
+ status: "failed",
+ error: run.started_at ? `Timed out after ${TIMEOUT_MS / 60_000} minutes` : `Timed out waiting ${QUEUE_TIMEOUT_MS / 3_600_000} hours in the provider's queue`,
+ completed_at: now,
+ message: null,
+ });
return;
}
- const route = model.routes.find((x) => x.op === r.op && (x.provider === r.provider || r.provider === "mock")) ?? model.routes[0];
- const res = await provider(r.provider).poll({
- externalId: r.external_id!,
- meta: JSON.parse(r.external_meta_json ?? "{}") as Record<string, unknown>,
- route,
- model,
- createdAt: r.created_at,
- });
+ const res = await provider(r.provider).poll(ctx);
if (res.state === "queued" || res.state === "running") {
+ if (res.state === "running" && !run.started_at) db().prepare("UPDATE generation_runs SET started_at = ? WHERE id = ?").run(Date.now(), r.id);
update(r.id, { status: res.state, progress: res.progress ?? r.progress, message: res.message ?? null });
return;
}
@@ -495,11 +709,11 @@ async function pollOne(r: Row): Promise<void> {
// Mark first so a slow download isn't polled twice.
update(r.id, { status: "running", progress: 0.99, message: "Saving results" });
const outputs: OutputFile[] = [];
- for (const o of res.outputs) {
+ for (const o of res.outputs as RichOutput[]) {
try {
outputs.push(await persistOutput(o, r.id));
} catch (e) {
- outputs.push({ url: o.url, kind: o.kind ?? r.kind, ...(o.draftId ? { draftId: o.draftId } : {}) });
+ outputs.push({ url: o.url, kind: o.kind ?? r.kind, ...(o.text !== undefined && { text: o.text }), ...(o.meta && { meta: o.meta }), ...(o.draftId ? { draftId: o.draftId } : {}) });
console.warn(`[fuobe] could not save output for ${r.id}: ${(e as Error).message}`);
}
}
@@ -512,10 +726,19 @@ async function pollOne(r: Row): Promise<void> {
});
}
-async function persistOutput(o: RemoteOutput, generationId: string): Promise<OutputFile> {
+/** Outputs may carry text (transcripts, translations, scripts) and structured extras (layer boxes, cues, stems). */
+type RichOutput = RemoteOutput & { text?: string; meta?: Record<string, unknown> };
+
+/** Text kept inline on the generation; longer text stays in its file. */
+const MAX_INLINE_TEXT = 1_000_000;
+
+async function persistOutput(o: RichOutput, generationId: string): Promise<OutputFile> {
let data: Buffer;
let contentType = o.contentType;
- if (o.url.startsWith("sample:")) {
+ if (!o.url && o.text !== undefined) {
+ data = Buffer.from(o.text);
+ contentType ??= "text/plain";
+ } else if (o.url.startsWith("sample:")) {
const file = path.join(process.cwd(), "public", "samples", path.basename(o.url.slice(7)));
data = fs.readFileSync(file);
contentType ??= contentTypeFor(file);
@@ -531,22 +754,27 @@ async function persistOutput(o: RemoteOutput, generationId: string): Promise<Out
contentType ??= header && header !== "application/octet-stream" ? header : contentTypeFor(new URL(o.url).searchParams.get("filename") ?? o.url);
}
const asset = saveFile({ data, contentType: contentType!, source: "generation", generationId });
- return { url: asset.url, kind: asset.kind, contentType: asset.contentType, assetId: asset.id, ...(o.draftId ? { draftId: o.draftId } : {}) };
+ // A text file's words travel with the generation, so feeds and the next chained step can use them.
+ const text = o.text ?? (asset.kind === "text" && data.length <= MAX_INLINE_TEXT ? data.toString("utf8") : undefined);
+ return {
+ url: asset.url,
+ kind: asset.kind,
+ contentType: asset.contentType,
+ assetId: asset.id,
+ ...(text !== undefined && { text }),
+ ...(o.meta && { meta: o.meta }),
+ ...(o.draftId ? { draftId: o.draftId } : {}),
+ };
}
export async function cancelGeneration(id: string): Promise<void> {
const r = db().prepare("SELECT * FROM generations WHERE id = ?").get(id) as Row | undefined;
if (!r || (r.status !== "queued" && r.status !== "running")) return;
const model = getModel(r.model_id);
+ // Without an external id the job is still being handed over: submit() cancels it as soon as it lands.
if (r.external_id && model) {
await provider(r.provider)
- .cancel?.({
- externalId: r.external_id,
- meta: JSON.parse(r.external_meta_json ?? "{}") as Record<string, unknown>,
- route: model.routes[0],
- model,
- createdAt: r.created_at,
- })
+ .cancel?.(pollContext(r, model))
.catch(() => {});
}
update(id, { status: "canceled", completed_at: Date.now(), message: null });
diff --git a/src/server/live.ts b/src/server/live.ts
new file mode 100644
index 00000000..0b3399b7
--- /dev/null
+++ b/src/server/live.ts
@@ -0,0 +1,153 @@
+import "server-only";
+import type Database from "better-sqlite3";
+
+/**
+ * Live updates for the feed (GET /api/generations/stream). Every write to the generations
+ * table, from any code path, reaches here through temporary SQLite triggers that call into JS
+ * (so there is exactly one hook, and new writers are covered without remembering to emit).
+ * Changes are batched per event-loop turn and turned into events by the generations module.
+ * State lives on globalThis so it survives dev hot reloads.
+ */
+
+export type LiveEventType = "generation" | "deleted";
+
+export interface LiveEvent {
+ type: LiveEventType;
+ id: string;
+ /** Serialized once per change, shared by every open stream. */
+ json: string;
+}
+
+type Listener = (e: LiveEvent) => void;
+
+interface LiveState {
+ listeners: Set<Listener>;
+ pending: Set<string>;
+ scheduled: boolean;
+ /** Turns changed ids into events: set (and re-set after hot reloads) by src/server/generations.ts. */
+ resolve?: (ids: string[]) => LiveEvent[];
+ hooked: WeakSet<object>;
+}
+
+declare global {
+ var __fuobeLive: LiveState | undefined;
+}
+
+const state = (): LiveState => (globalThis.__fuobeLive ??= { listeners: new Set(), pending: new Set(), scheduled: false, hooked: new WeakSet() });
+
+export function subscribe(listener: Listener): () => void {
+ const s = state();
+ s.listeners.add(listener);
+ return () => void s.listeners.delete(listener);
+}
+
+export const listenerCount = () => state().listeners.size;
+
+export function setResolver(resolve: (ids: string[]) => LiveEvent[]): void {
+ state().resolve = resolve;
+}
+
+function changed(id: string): void {
+ const s = state();
+ if (!s.listeners.size) return;
+ s.pending.add(id);
+ if (s.scheduled) return;
+ s.scheduled = true;
+ // After the current statement/transaction: a trigger can't read the database itself.
+ setImmediate(flush);
+}
+
+function flush(): void {
+ const s = state();
+ s.scheduled = false;
+ const ids = [...s.pending];
+ s.pending.clear();
+ if (!ids.length || !s.listeners.size || !s.resolve) return;
+ let events: LiveEvent[];
+ try {
+ events = s.resolve(ids);
+ } catch (e) {
+ console.warn(`[fuobe] live update failed: ${(e as Error).message}`);
+ return;
+ }
+ for (const e of events) {
+ for (const l of [...s.listeners]) {
+ try {
+ l(e);
+ } catch {
+ // A broken stream removes itself on its next write.
+ }
+ }
+ }
+}
+
+/** Install the change hooks on a connection (once). TEMP triggers live only as long as the connection. */
+export function watchGenerations(d: Database.Database): void {
+ const s = state();
+ if (s.hooked.has(d)) return;
+ d.function("fuobe_generation_changed", { deterministic: false }, (id: unknown) => {
+ changed(String(id));
+ return null;
+ });
+ d.exec(`
+ CREATE TEMP TRIGGER IF NOT EXISTS fuobe_generations_insert AFTER INSERT ON main.generations BEGIN SELECT fuobe_generation_changed(NEW.id); END;
+ CREATE TEMP TRIGGER IF NOT EXISTS fuobe_generations_update AFTER UPDATE ON main.generations BEGIN SELECT fuobe_generation_changed(NEW.id); END;
+ CREATE TEMP TRIGGER IF NOT EXISTS fuobe_generations_delete AFTER DELETE ON main.generations BEGIN SELECT fuobe_generation_changed(OLD.id); END;
+ `);
+ s.hooked.add(d);
+}
+
+const encoder = new TextEncoder();
+const PING_MS = 15_000;
+
+/**
+ * A server-sent events stream of generation changes: `event: generation` (the Generation JSON,
+ * exactly as GET /api/generations returns it), `event: deleted` ({"id"}), `: ping` every 15 s.
+ * The listener and the ping are removed as soon as the client goes away.
+ */
+export function generationEventStream(signal: AbortSignal, opts: { pingMs?: number } = {}): Response {
+ let stop = () => {};
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ let open = true;
+ const send = (chunk: string) => {
+ if (!open) return;
+ try {
+ controller.enqueue(encoder.encode(chunk));
+ } catch {
+ stop();
+ }
+ };
+ const off = subscribe((e) => send(`event: ${e.type}\ndata: ${e.json}\n\n`));
+ const ping = setInterval(() => send(": ping\n\n"), opts.pingMs ?? PING_MS);
+ stop = () => {
+ if (!open) return;
+ open = false;
+ off();
+ clearInterval(ping);
+ signal.removeEventListener("abort", stop);
+ try {
+ controller.close();
+ } catch {
+ // Already closed by the client.
+ }
+ };
+ signal.addEventListener("abort", stop);
+ if (signal.aborted) return stop();
+ // Reconnect quickly after a restart; the first comment flushes the headers through proxies.
+ send("retry: 2000\n: connected\n\n");
+ },
+ cancel() {
+ stop();
+ },
+ });
+ return new Response(body, {
+ headers: {
+ "Content-Type": "text/event-stream; charset=utf-8",
+ // no-transform keeps compression (and its buffering) off; X-Accel-Buffering does the same for nginx.
+ "Cache-Control": "no-cache, no-transform",
+ Connection: "keep-alive",
+ "X-Accel-Buffering": "no",
+ },
+ });
+}
diff --git a/src/server/training.ts b/src/server/training.ts
index 9f34ac8f..f30be353 100644
--- a/src/server/training.ts
+++ b/src/server/training.ts
@@ -8,6 +8,7 @@ import { DATA_DIR, db } from "./db";
import { getElement, updateElement } from "./elements";
import { falFetch, falProvider } from "./providers/fal";
import { hfFetch, hfUpload, higgsfieldKey } from "./providers/higgsfield";
+import { ProviderError } from "./providers/types";
import { getSetting } from "./settings";
import { readRef } from "./storage";
import { zip } from "./zip";
@@ -120,10 +121,24 @@ export function startTraining(elementId: string, targetId: string): Training {
.prepare(`INSERT INTO trainings (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
.run(row);
updateElement(elementId, { status: "training" });
- void submit(row.id, el, target, row.trigger_word ?? "", images).catch((e) => fail(row.id, el.id, (e as Error).message));
+ submittingTrainings().add(row.id);
+ void submit(row.id, el, target, row.trigger_word ?? "", images)
+ .catch((e) => fail(row.id, el.id, (e as Error).message))
+ .finally(() => submittingTrainings().delete(row.id));
return toTraining(row);
}
+/** Trainings this process is still uploading (shared across hot reloads). */
+declare global {
+ var __fuobeTrainingSubmits: Set<string> | undefined;
+}
+const submittingTrainings = (): Set<string> => (globalThis.__fuobeTrainingSubmits ??= new Set<string>());
+
+/** The longest a training may run before it's given up on. */
+const MAX_TRAINING_MS = 8 * 3_600_000;
+/** A queued training this old that nothing is uploading was cut off by a restart. */
+const STALE_TRAINING_MS = 2 * 60 * 1000;
+
function fail(id: string, elementId: string, error: string) {
update(id, { status: "failed", error, message: null, completed_at: Date.now() });
settleElement(elementId);
@@ -164,7 +179,7 @@ async function aitk(pathname: string, init: RequestInit = {}) {
headers: { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}), ...(init.headers ?? {}) },
});
const body = await res.json().catch(() => null);
- if (!res.ok) throw new Error(`AI-Toolkit ${res.status}: ${JSON.stringify(body).slice(0, 300)}`);
+ if (!res.ok) throw new ProviderError(`AI-Toolkit ${res.status}: ${JSON.stringify(body).slice(0, 300)}`, res.status);
return body as Record<string, unknown>;
}
@@ -223,13 +238,30 @@ async function submit(id: string, el: StudioElement, t: TrainingTarget, trigger:
// ---------------------------------------------------------------------------
// Polling (called from the generation runner's tick)
+/** A provider answer that won't change by asking again: the job failed or is gone (not auth, timeouts or rate limits). */
+const permanent = (e: unknown) => e instanceof ProviderError && e.status !== undefined && e.status >= 400 && e.status < 500 && ![401, 403, 408, 429].includes(e.status);
+
export async function pollTrainings(): Promise<void> {
+ // Trainings a restart cut off mid-upload never reach the trainer: fail them so the element can retrain.
+ const stale = db()
+ .prepare("SELECT * FROM trainings WHERE status = 'queued' AND external_id IS NULL AND created_at < ?")
+ .all(Date.now() - STALE_TRAINING_MS) as Row[];
+ for (const r of stale) if (!submittingTrainings().has(r.id)) fail(r.id, r.element_id, "Interrupted before it reached the trainer — start it again");
const rows = db().prepare("SELECT * FROM trainings WHERE status = 'running' AND external_id IS NOT NULL").all() as Row[];
- await Promise.all(rows.map((r) => pollOne(r).catch((e) => update(r.id, { message: `Checking status failed: ${(e as Error).message}` }))));
+ await Promise.all(
+ rows.map((r) =>
+ pollOne(r).catch((e) => {
+ if (permanent(e)) return fail(r.id, r.element_id, (e as Error).message);
+ update(r.id, { message: `Checking status failed: ${(e as Error).message}` });
+ }),
+ ),
+ );
}
async function pollOne(r: Row) {
- const t = getTrainingTarget(r.target)!;
+ const t = getTrainingTarget(r.target);
+ if (!t) return fail(r.id, r.element_id, `Unknown training target ${r.target}`);
+ if (Date.now() - r.created_at > MAX_TRAINING_MS) return fail(r.id, r.element_id, `Training didn't finish within ${MAX_TRAINING_MS / 3_600_000} hours`);
const meta = JSON.parse(r.meta_json ?? "{}") as Record<string, string>;
if (r.provider === "higgsfield") {
const ref = (await hfFetch(`v1/custom-references/${r.external_id}`)) as { status: string; fail_reason?: string };
@@ -242,7 +274,9 @@ async function pollOne(r: Row) {
return;
}
if (r.provider === "fal") {
- const s = (await falFetch(`${meta.statusUrl}?logs=1`)) as { status: string; logs?: { message: string }[] };
+ const s = (await falFetch(`${meta.statusUrl}?logs=1`)) as { status: string; logs?: { message: string }[]; error?: string };
+ if (s.error) return fail(r.id, r.element_id, `fal couldn't train this: ${s.error}`);
+ if (s.status === "FAILED" || s.status === "ERROR" || s.status === "CANCELLED") return fail(r.id, r.element_id, `fal training ${s.status.toLowerCase()}`);
if (s.status !== "COMPLETED") {
const last = s.logs?.at(-1)?.message;
const step = last && /(\d+)\s*\/\s*(\d+)/.exec(last);
diff --git a/tests/demo-ops.test.ts b/tests/demo-ops.test.ts
new file mode 100644
index 00000000..30754c14
--- /dev/null
+++ b/tests/demo-ops.test.ts
@@ -0,0 +1,145 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import type { Generation, GenerationRequest } from "@/lib/catalog/types";
+
+vi.mock("@/lib/catalog", async (importOriginal) => {
+ const mod = await importOriginal<typeof import("@/lib/catalog")>();
+ const { ROUND3_FIXTURES } = await import("./fixtures/round3-models");
+ return { ...mod, MODELS: [...mod.MODELS, ...ROUND3_FIXTURES], getModel: (id: string) => ROUND3_FIXTURES.find((m) => m.id === id) ?? mod.getModel(id) };
+});
+vi.setConfig({ testTimeout: 60_000 });
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-demo-ops-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const gens = await import("@/server/generations");
+const { contentTypeFor, kindFor, saveFile } = await import("@/server/storage");
+const files = await import("@/app/api/files/[...path]/route");
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+async function settle(id: string, ms = 40_000): Promise<Generation> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const g = gens.getGeneration(id)!;
+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;
+ if (Date.now() > end) throw new Error(`timed out: ${g.status} ${g.message}`);
+ await new Promise((r) => setTimeout(r, 200));
+ }
+}
+
+const png = Buffer.from("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d49444154789c63f8cfc0f01f0005000201a2e2b6a40000000049454e44ae426082", "hex");
+
+async function serve(url: string, download?: string) {
+ const parts = url.replace(/^\/api\/files\//, "").split("/");
+ return files.GET(new Request(`http://localhost${url}${download ? `?download=${download}` : ""}`), { params: Promise.resolve({ path: parts }) } as never);
+}
+
+/** Reads a GLB and checks it against the glTF 2.0 binary layout. */
+function checkGlb(buf: Buffer) {
+ expect(buf.readUInt32LE(0)).toBe(0x46546c67);
+ expect(buf.readUInt32LE(4)).toBe(2);
+ expect(buf.readUInt32LE(8)).toBe(buf.length);
+ const jsonLen = buf.readUInt32LE(12);
+ expect(buf.readUInt32LE(16)).toBe(0x4e4f534a);
+ expect(jsonLen % 4).toBe(0);
+ const gltf = JSON.parse(buf.subarray(20, 20 + jsonLen).toString("utf8").trimEnd());
+ const binAt = 20 + jsonLen;
+ const binLen = buf.readUInt32LE(binAt);
+ expect(buf.readUInt32LE(binAt + 4)).toBe(0x004e4942);
+ expect(gltf.asset.version).toBe("2.0");
+ expect(gltf.buffers[0].byteLength).toBe(binLen);
+ const size = { SCALAR: 1, VEC3: 3, VEC4: 4 } as Record<string, number>;
+ const bytes = { 5126: 4, 5123: 2 } as Record<number, number>;
+ for (const a of gltf.accessors) {
+ const v = gltf.bufferViews[a.bufferView];
+ expect(v.byteOffset + v.byteLength).toBeLessThanOrEqual(binLen);
+ expect(a.count * size[a.type] * bytes[a.componentType]).toBe(v.byteLength);
+ expect(v.byteOffset % bytes[a.componentType]).toBe(0);
+ }
+ const prim = gltf.meshes[0].primitives[0];
+ expect(gltf.accessors[prim.attributes.POSITION].min).toHaveLength(3);
+ expect(gltf.accessors[prim.indices].count % 3).toBe(0);
+}
+
+describe("storage", () => {
+ it("knows text and 3D files", () => {
+ expect(kindFor("text/plain")).toBe("text");
+ expect(kindFor("application/json")).toBe("text");
+ expect(kindFor("application/x-subrip")).toBe("text");
+ expect(kindFor("text/plain; charset=utf-8")).toBe("text");
+ expect(kindFor("model/gltf-binary")).toBe("model3d");
+ expect(kindFor("image/png")).toBe("image");
+ expect(contentTypeFor("a.srt")).toBe("application/x-subrip");
+ expect(contentTypeFor("a.glb")).toBe("model/gltf-binary");
+ expect(saveFile({ data: Buffer.from("hi"), contentType: "text/plain", source: "generation" }).url).toMatch(/\.txt$/);
+ expect(saveFile({ data: Buffer.from("[]"), contentType: "application/json", source: "generation" }).kind).toBe("text");
+ });
+
+ it("ships a valid demo .glb", () => {
+ checkGlb(fs.readFileSync(path.join(process.cwd(), "public/samples/demo-model.glb")));
+ });
+});
+
+describe("demo outputs for every new operation", () => {
+ it("gives layers, text, stems, clips and 3D the extras real providers return", async () => {
+ const image = saveFile({ data: png, contentType: "image/png", source: "upload" }).url;
+ const video = saveFile({ data: fs.readFileSync(path.join(process.cwd(), "public/samples/demo-square.mp4")), contentType: "video/mp4", source: "upload" }).url;
+ const audio = saveFile({ data: Buffer.from("RIFF0000WAVEfmt "), contentType: "audio/wav", source: "upload" }).url;
+ const reqs: Record<string, GenerationRequest> = {
+ layers: { feature: "layers", modelId: "test-layers", prompt: "Summer sale poster", inputs: { images: [image] }, params: { numLayers: 4 } },
+ textLayers: { feature: "layers", modelId: "test-text-layers", prompt: "Big summer sale", inputs: { images: [image] } },
+ trim: { feature: "shorts", modelId: "test-trim", prompt: "trim", inputs: { video: video }, params: { startTime: 1, endTime: 3, aspectRatio: "9:16" } },
+ captions: { feature: "captions", modelId: "test-captions", prompt: "captions", inputs: { video: video } },
+ mux: { feature: "dub", modelId: "test-mux", prompt: "mux", inputs: { video: video, audio: audio } },
+ transcribe: { feature: "dub", modelId: "test-transcribe", prompt: "transcribe", inputs: { video: video } },
+ separate: { feature: "dub", modelId: "test-separate", prompt: "separate", inputs: { video: video } },
+ model: { feature: "3d", modelId: "test-3d", prompt: "a ceramic vase", inputs: { images: [image] } },
+ };
+ const started = Object.fromEntries(Object.entries(reqs).map(([k, r]) => [k, gens.createGenerations(r)[0]]));
+ expect(started.transcribe.kind).toBe("text");
+ expect(started.model.kind).toBe("model3d");
+ const done = Object.fromEntries(await Promise.all(Object.entries(started).map(async ([k, g]) => [k, await settle(g.id)] as const)));
+ for (const [k, g] of Object.entries(done)) expect(g.status, `${k}: ${g.error}`).toBe("succeeded");
+
+ const layers = done.layers.outputs;
+ expect(layers.length).toBeGreaterThanOrEqual(3);
+ expect(layers.length).toBeLessThanOrEqual(4);
+ expect(layers.map((l) => l.meta?.z)).toEqual(layers.map((_, i) => i));
+ for (const l of layers) {
+ expect(l).toMatchObject({ kind: "image", contentType: "image/svg+xml" });
+ expect(l.meta).toMatchObject({ name: expect.any(String), bbox: [expect.any(Number), expect.any(Number), expect.any(Number), expect.any(Number)] });
+ }
+ expect(done.textLayers.outputs[0].meta?.textBlocks).toEqual(expect.arrayContaining([expect.objectContaining({ text: "BIG SUMMER SALE", bbox: expect.any(Array) })]));
+
+ for (const k of ["trim", "captions", "mux"]) expect(done[k].outputs[0]).toMatchObject({ kind: "video", contentType: "video/mp4", meta: { demo: true } });
+
+ const t = done.transcribe.outputs[0];
+ expect(t).toMatchObject({ kind: "text", contentType: "application/x-subrip" });
+ expect((t.meta?.cues as unknown[]).length).toBeGreaterThan(2);
+ expect(t.text).toContain("This is a demo transcript.");
+ const served = await serve(t.url, "transcript.srt");
+ expect(served.headers.get("content-type")).toBe("application/x-subrip; charset=utf-8");
+ expect(served.headers.get("content-disposition")).toBe('attachment; filename="transcript.srt"');
+ expect(await served.text()).toMatch(/^1\n00:00:00,000 --> 00:00:02,300\nThis is a demo transcript\./);
+
+ expect(done.separate.outputs.map((o) => [o.kind, o.meta?.stem])).toEqual([
+ ["audio", "voice"],
+ ["audio", "background"],
+ ]);
+
+ const [glb, turntable] = done.model.outputs;
+ expect(glb).toMatchObject({ kind: "model3d", contentType: "model/gltf-binary" });
+ expect(glb.url).toMatch(/\.glb$/);
+ expect(turntable).toMatchObject({ kind: "video", meta: { turntable: true } });
+ const res = await serve(glb.url, "vase.glb");
+ expect(res.headers.get("content-type")).toBe("model/gltf-binary");
+ checkGlb(Buffer.from(await res.arrayBuffer()));
+ });
+});
diff --git a/tests/fixtures/round3-models.ts b/tests/fixtures/round3-models.ts
new file mode 100644
index 00000000..553eeb0d
--- /dev/null
+++ b/tests/fixtures/round3-models.ts
@@ -0,0 +1,29 @@
+import type { ModelDef, Operation } from "@/lib/catalog/types";
+
+/**
+ * Stand-in cloud models for the round-3 operations (the real ones come from the catalog
+ * packages). They route to fal, which tests never configure, so they run on the demo provider.
+ */
+const fixture = (id: string, op: Operation, kind: ModelDef["kind"]): ModelDef => ({
+ id,
+ name: `Test ${op}`,
+ vendor: "Test",
+ family: "test",
+ engine: "cloud",
+ kind,
+ tagline: `Fixture for ${op}`,
+ routes: [{ op, provider: "fal", endpoint: `test/${op}` }],
+ options: { aspectRatios: ["1:1", "16:9", "9:16"] },
+ pricing: { unit: "request", usd: 0.01 },
+});
+
+export const ROUND3_FIXTURES: ModelDef[] = [
+ fixture("test-layers", "layers", "image"),
+ fixture("test-text-layers", "text-layers", "image"),
+ fixture("test-trim", "trim", "video"),
+ fixture("test-captions", "captions", "video"),
+ fixture("test-mux", "mux", "video"),
+ fixture("test-transcribe", "transcribe", "text"),
+ fixture("test-separate", "separate-audio", "audio"),
+ fixture("test-3d", "image-to-3d", "model3d"),
+];
diff --git a/tests/llm.test.ts b/tests/llm.test.ts
new file mode 100644
index 00000000..edfdcfdc
--- /dev/null
+++ b/tests/llm.test.ts
@@ -0,0 +1,198 @@
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import type { Generation } from "@/lib/catalog/types";
+
+vi.setConfig({ testTimeout: 40_000 });
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-llm-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const gens = await import("@/server/generations");
+const llm = await import("@/server/providers/llm");
+const { getModel, modelsFor } = await import("@/lib/catalog");
+
+// A stand-in Ollama: answers numbered subtitle lines line by line, anything else with a prefix.
+const seen: { system: string; user: string; model: string }[] = [];
+const server = http.createServer((req, res) => {
+ if (req.url === "/api/tags") return res.end(JSON.stringify({ models: [{ name: "qwen3:8b" }] }));
+ let body = "";
+ req.on("data", (c) => (body += c));
+ req.on("end", () => {
+ const j = JSON.parse(body) as { model: string; messages: { role: string; content: string }[] };
+ const system = j.messages[0].content;
+ const user = j.messages[1].content;
+ seen.push({ system, user, model: j.model });
+ const lang = /into (\w+)/.exec(system)?.[1] ?? "??";
+ const content = /^\[\d+\]/.test(user)
+ ? user
+ .split("\n")
+ .map((l) => l.replace(/^\[(\d+)\]\s*/, (_, n) => `[${n}] (${lang}) `))
+ .join("\n")
+ : `<think>hmm</think>(${lang}) ${user}`;
+ res.setHeader("content-type", "application/json");
+ res.end(JSON.stringify({ message: { role: "assistant", content } }));
+ });
+});
+let ollama = "";
+
+beforeAll(async () => {
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ ollama = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
+ setSetting("demoMode", "auto");
+});
+afterAll(() => {
+ server.close();
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+beforeEach(() => {
+ seen.length = 0;
+ setSetting("anthropicKey", "");
+ setSetting("engineMode", "");
+ setSetting("enhanceProvider", "");
+ setSetting("demoMode", "auto");
+});
+
+async function settle(id: string, ms = 20_000): Promise<Generation> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const g = gens.getGeneration(id)!;
+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;
+ if (Date.now() > end) throw new Error(`timed out: ${g.status} ${g.message}`);
+ await new Promise((r) => setTimeout(r, 150));
+ }
+}
+
+const useOllama = async (up: boolean) => {
+ setSetting("ollamaUrl", up ? ollama : "http://127.0.0.1:9");
+ await llm.probeOllama(true);
+};
+
+const CUES = JSON.stringify([
+ { start: 0, end: 1.8, text: "Hello there." },
+ { start: 2, end: 4.25, text: "This is a test\nwith two lines." },
+]);
+
+describe("text models", () => {
+ it("are registered as text models with a cloud and an open route", () => {
+ expect(getModel("text-llm")).toMatchObject({ kind: "text", engine: "cloud" });
+ expect(getModel("oss-text-llm")).toMatchObject({ kind: "text", engine: "open" });
+ // Only pickers that ask for text see them.
+ expect(modelsFor({ kind: "image" }).some((m) => m.kind === "text")).toBe(false);
+ expect(modelsFor({ kind: "text", ops: ["translate"] }).map((m) => m.id)).toEqual(expect.arrayContaining(["text-llm", "oss-text-llm"]));
+ });
+});
+
+describe("LLM provider", () => {
+ it("translates subtitles cue by cue on Ollama and keeps the timing", async () => {
+ await useOllama(true);
+ const [g] = gens.createGenerations({ feature: "dub", modelId: "oss-text-llm", op: "translate", prompt: CUES, params: { targetLanguage: "Spanish" } });
+ expect(g.provider).toBe("llm");
+ expect(g.kind).toBe("text");
+ expect(g.costUsd).toBe(0);
+ const done = await settle(g.id);
+ expect(done.status, done.error ?? "").toBe("succeeded");
+ const out = done.outputs[0];
+ expect(out).toMatchObject({ kind: "text", contentType: "application/x-subrip" });
+ expect(out.url).toMatch(/\.srt$/);
+ expect(out.meta?.cues).toEqual([
+ { start: 0, end: 1.8, text: "(Spanish) Hello there." },
+ { start: 2, end: 4.25, text: "(Spanish) This is a test\nwith two lines." },
+ ]);
+ expect(out.text).toBe("(Spanish) Hello there.\n(Spanish) This is a test\nwith two lines.");
+ // One call for the batch, multi-line cues kept together.
+ expect(seen).toHaveLength(1);
+ expect(seen[0].user).toBe("[1] Hello there.\n[2] This is a test <br> with two lines.");
+ expect(seen[0].model).toBe("qwen3:8b");
+ });
+
+ it("translates SRT and plain text too", async () => {
+ await useOllama(true);
+ const srt = "1\n00:00:01,000 --> 00:00:02,500\nBonjour\n\n2\n00:00:03,000 --> 00:00:04,000\nÇa va ?\n";
+ const [a] = gens.createGenerations({ feature: "dub", modelId: "oss-text-llm", op: "translate", prompt: srt, params: { targetLanguage: "English" } });
+ const [b] = gens.createGenerations({ feature: "dub", modelId: "oss-text-llm", op: "translate", prompt: "Good morning, friends.", params: { targetLanguage: "German" } });
+ const [da, db] = [await settle(a.id), await settle(b.id)];
+ expect(da.outputs[0].meta?.cues).toEqual([
+ { start: 1, end: 2.5, text: "(English) Bonjour" },
+ { start: 3, end: 4, text: "(English) Ça va ?" },
+ ]);
+ expect(db.outputs[0]).toMatchObject({ kind: "text", contentType: "text/plain", text: "(German) Good morning, friends." });
+ expect(db.outputs[0].url).toMatch(/\.txt$/);
+ });
+
+ it("writes from a brief with an optional system prompt", async () => {
+ await useOllama(true);
+ const [g] = gens.createGenerations({ feature: "ads", modelId: "text-llm", op: "write", prompt: "Three hooks for a perfume ad", params: { extra: { system: "You write punchy hooks into French." } } });
+ const done = await settle(g.id);
+ expect(done.status).toBe("succeeded");
+ expect(seen[0].system).toBe("You write punchy hooks into French.");
+ expect(done.outputs[0].text).toBe("(French) Three hooks for a perfume ad");
+ });
+
+ it("uses Claude when a key is set (falling back to Ollama), never on the open model", async () => {
+ await useOllama(true);
+ setSetting("anthropicKey", "sk-ant-test");
+ expect(llm.llmBackends({ endpoint: "auto" })).toEqual(["claude", "ollama"]);
+ expect(llm.llmBackends({ endpoint: "ollama" })).toEqual(["ollama"]);
+ setSetting("engineMode", "open");
+ expect(llm.llmBackends({ endpoint: "auto" })).toEqual(["ollama"]);
+ expect(() => gens.createGenerations({ feature: "dub", modelId: "text-llm", op: "translate", prompt: "x", params: { targetLanguage: "Spanish" } })).toThrow(/open source only/);
+ setSetting("engineMode", "");
+ setSetting("enhanceProvider", "none");
+ expect(llm.llmBackends({ endpoint: "auto" })).toEqual([]);
+ setSetting("enhanceProvider", "");
+
+ const sent: { url: string; body: Record<string, unknown> }[] = [];
+ const realFetch = globalThis.fetch;
+ let status = 200;
+ globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {
+ if (!String(url).includes("api.anthropic.com")) return realFetch(url, init);
+ sent.push({ url: String(url), body: JSON.parse(String(init!.body)) });
+ const body =
+ status === 200
+ ? { id: "msg_1", type: "message", role: "assistant", model: "claude-opus-5-5", content: [{ type: "text", text: "Hola, amigos." }], stop_reason: "end_turn", stop_sequence: null, stop_details: null, usage: { input_tokens: 1, output_tokens: 1 } }
+ : { type: "error", error: { type: "invalid_request_error", message: "nope" } };
+ return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
+ }) as typeof fetch;
+ try {
+ const [g] = gens.createGenerations({ feature: "dub", modelId: "text-llm", op: "translate", prompt: "Hello, friends.", params: { targetLanguage: "Spanish" } });
+ expect(g.costUsd).toBe(0.02);
+ const done = await settle(g.id);
+ expect(done.outputs[0].text).toBe("Hola, amigos.");
+ expect(sent[0].body).toMatchObject({ model: "claude-opus-5-5", output_config: { effort: "low" }, fallbacks: "default" });
+ expect(String(sent[0].body.system)).toMatch(/into Spanish/);
+ expect(seen).toHaveLength(0);
+ // Claude fails: Ollama takes over.
+ status = 400;
+ const [h] = gens.createGenerations({ feature: "dub", modelId: "text-llm", op: "translate", prompt: "Bye.", params: { targetLanguage: "Spanish" } });
+ expect((await settle(h.id)).outputs[0].text).toBe("(Spanish) Bye.");
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ });
+
+ it("with no LLM: demo text in demo mode (timing kept), a clear error otherwise", async () => {
+ await useOllama(false);
+ const [g] = gens.createGenerations({ feature: "dub", modelId: "text-llm", op: "translate", prompt: CUES, params: { targetLanguage: "Italian" } });
+ expect(g.provider).toBe("mock");
+ const done = await settle(g.id);
+ expect(done.outputs[0].meta).toMatchObject({ demo: true, cues: [{ start: 0, end: 1.8, text: "[Italian] Hello there." }, { start: 2, end: 4.25 }] });
+ const [w] = gens.createGenerations({ feature: "ads", modelId: "oss-text-llm", op: "write", prompt: "A tagline for a bakery" });
+ expect((await settle(w.id)).outputs[0].text).toMatch(/Demo script for: A tagline for a bakery/);
+ setSetting("demoMode", "off");
+ expect(() => gens.createGenerations({ feature: "dub", modelId: "text-llm", op: "translate", prompt: "x", params: { targetLanguage: "Italian" } })).toThrow(/Connect Claude or Ollama in Settings/);
+ expect(() => gens.createGenerations({ feature: "dub", modelId: "oss-text-llm", op: "write", prompt: "x" })).toThrow(/Connect Ollama in Settings/);
+ });
+
+ it("asks for a language before translating", () => {
+ expect(() => gens.createGenerations({ feature: "dub", modelId: "text-llm", op: "translate", prompt: "x" })).toThrow(/Pick a language/);
+ });
+
+ it("fails a job that a restart interrupted", async () => {
+ const res = await llm.llmProvider.poll({ externalId: "llm_gone", meta: {}, route: getModel("text-llm")!.routes[0], model: getModel("text-llm")!, createdAt: Date.now() });
+ expect(res).toMatchObject({ state: "failed", error: expect.stringMatching(/Interrupted/) });
+ });
+});
diff --git a/tests/runtime-runner.test.ts b/tests/runtime-runner.test.ts
new file mode 100644
index 00000000..afc1ba86
--- /dev/null
+++ b/tests/runtime-runner.test.ts
@@ -0,0 +1,237 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import type { Generation } from "@/lib/catalog/types";
+
+vi.setConfig({ testTimeout: 40_000 });
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-runner-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const gens = await import("@/server/generations");
+const { db } = await import("@/server/db");
+const { mockProvider } = await import("@/server/providers/mock");
+const live = await import("@/server/live");
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+async function until<T>(f: () => T | undefined | null | false, ms = 20_000): Promise<T> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const v = f();
+ if (v) return v;
+ if (Date.now() > end) throw new Error("timed out waiting");
+ await sleep(100);
+ }
+}
+
+const row = (id: string) => db().prepare("SELECT * FROM generations WHERE id = ?").get(id) as { status: string; external_id: string | null; error: string | null; created_at: number };
+const settle = (id: string, ms = 20_000) => until(() => {
+ const g = gens.getGeneration(id)!;
+ return ["succeeded", "failed", "canceled"].includes(g.status) ? g : undefined;
+}, ms);
+
+const image = (prompt = "a red fox") => gens.createGenerations({ feature: "image", modelId: "nano-banana-pro", prompt })[0];
+
+describe("timeouts (S3)", () => {
+ it("measure from submission, not creation: a step created long ago still gets its full time", async () => {
+ const g = image("created two hours ago");
+ await until(() => row(g.id).external_id);
+ // As if the chain that made it had been waiting for two hours.
+ db().prepare("UPDATE generations SET created_at = ? WHERE id = ?").run(Date.now() - 2 * 3_600_000, g.id);
+ const done = await settle(g.id);
+ expect(done.status).toBe("succeeded");
+ });
+
+ it("time out a job that has run too long, and stop it at the provider", async () => {
+ const cancel = vi.fn(async () => {});
+ mockProvider.cancel = cancel;
+ try {
+ const g = image("runs forever");
+ await until(() => row(g.id).external_id);
+ db().prepare("UPDATE generation_runs SET started_at = ? WHERE id = ?").run(Date.now() - 46 * 60_000, g.id);
+ const done = await settle(g.id);
+ expect(done.status).toBe("failed");
+ expect(done.error).toMatch(/Timed out after 45 minutes/);
+ expect(cancel).toHaveBeenCalledWith(expect.objectContaining({ externalId: row(g.id).external_id }));
+ } finally {
+ delete mockProvider.cancel;
+ }
+ });
+
+ it("give a job that never left the queue a longer, separate limit", async () => {
+ const g = image("stuck in the queue");
+ await until(() => row(g.id).external_id);
+ db().prepare("UPDATE generation_runs SET submitted_at = ?, started_at = NULL WHERE id = ?").run(Date.now() - 5 * 3_600_000, g.id);
+ const done = await settle(g.id);
+ expect(done.error).toMatch(/waiting 4 hours in the provider's queue/);
+ });
+});
+
+describe("restarts (S7)", () => {
+ it("instrumentation starts the runner at boot", async () => {
+ const { register } = await import("@/instrumentation");
+ process.env.NEXT_RUNTIME = "nodejs";
+ await register();
+ expect(globalThis.__fuobeRunner).toBeDefined();
+ expect(globalThis.__fuobeRunner?.fastTimer).toBeDefined();
+ });
+
+ it("fails jobs a restart cut off mid-submit on any tick, but not ones still being submitted here", async () => {
+ gens.ensureRunner();
+ const insert = (id: string) =>
+ db()
+ .prepare(
+ `INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at)
+ VALUES (?, 'image', 'nano-banana-pro', 'cloud', 'fal', 't2i', 'image', 'queued', '{"feature":"image","modelId":"nano-banana-pro"}', '[]', ?, ?)`,
+ )
+ .run(id, Date.now() - 5 * 60_000, Date.now() - 5 * 60_000);
+ insert("cut-off-1");
+ insert("uploading-1");
+ globalThis.__fuobeSubmitting!.add("uploading-1");
+ try {
+ await until(() => row("cut-off-1").status === "failed", 5000);
+ expect(row("cut-off-1").error).toBe("Interrupted before it reached the provider");
+ await sleep(1700);
+ expect(row("uploading-1").status).toBe("queued");
+ } finally {
+ globalThis.__fuobeSubmitting!.delete("uploading-1");
+ }
+ });
+});
+
+describe("cancel while submitting (S13)", () => {
+ it("cancels the provider's job when it lands, and keeps the row canceled", async () => {
+ const real = mockProvider.submit;
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ const cancel = vi.fn(async () => {});
+ mockProvider.submit = async (ctx) => {
+ await gate;
+ return real(ctx);
+ };
+ mockProvider.cancel = cancel;
+ try {
+ const g = image("slow upload");
+ await sleep(50);
+ await gens.cancelGeneration(g.id);
+ expect(row(g.id).status).toBe("canceled");
+ release();
+ await until(() => cancel.mock.calls.length > 0, 3000);
+ expect(cancel).toHaveBeenCalledWith(expect.objectContaining({ externalId: expect.stringMatching(/^demo_/) }));
+ await sleep(1700);
+ expect(row(g.id).status).toBe("canceled");
+ } finally {
+ mockProvider.submit = real;
+ delete mockProvider.cancel;
+ }
+ });
+
+ it("doesn't turn a canceled job into a failed one when the submit then fails", async () => {
+ const real = mockProvider.submit;
+ let fail!: () => void;
+ const gate = new Promise<void>((_, rej) => (fail = () => rej(new Error("upload failed"))));
+ mockProvider.submit = async () => gate.then(() => ({ externalId: "never" }));
+ try {
+ const g = image("doomed upload");
+ await sleep(50);
+ await gens.cancelGeneration(g.id);
+ fail();
+ await sleep(100);
+ expect(row(g.id).status).toBe("canceled");
+ } finally {
+ mockProvider.submit = real;
+ }
+ });
+});
+
+describe("colour match on video (S17)", () => {
+ it("stores the result as a video and needs the video", () => {
+ expect(() => gens.createGenerations({ feature: "video-color", modelId: "oss-palette-video", op: "color-match", inputs: { images: ["/api/files/x.png"] } })).toThrow(/Add the video/);
+ const [g] = gens.createGenerations({ feature: "video-color", modelId: "oss-palette-video", op: "color-match", inputs: { video: "/api/files/placeholder.mp4", images: ["/api/files/placeholder.png"] } });
+ expect(g.kind).toBe("video");
+ expect(gens.outputKind("color-match", { kind: "image" })).toBe("image");
+ });
+});
+
+describe("result latency (U19)", () => {
+ it("polls a nearly finished job every 500 ms, without waiting for the 1.5 s tick", async () => {
+ gens.ensureRunner();
+ const runner = globalThis.__fuobeRunner!;
+ const near = image("almost there");
+ const far = image("just started");
+ await until(() => row(near.id).external_id && row(far.id).external_id);
+ // Hold the regular tick; only the fast lane may poll now.
+ await until(() => !runner.busy, 5000);
+ runner.busy = true;
+ try {
+ const done = (meta: string, ms: number) => JSON.stringify({ ...JSON.parse(meta), startedAt: Date.now() - ms });
+ const m = (id: string) => (db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").get(id) as { external_meta_json: string }).external_meta_json;
+ db().prepare("UPDATE generations SET status = 'running', progress = 0.95, external_meta_json = ? WHERE id = ?").run(done(m(near.id), 10_000), near.id);
+ db().prepare("UPDATE generations SET status = 'running', progress = 0.2, external_meta_json = ? WHERE id = ?").run(done(m(far.id), 10_000), far.id);
+ db().prepare("UPDATE generation_runs SET started_at = ? WHERE id = ?").run(Date.now() - 1000, far.id);
+ const t0 = Date.now();
+ await until(() => row(near.id).status === "succeeded", 3000);
+ expect(Date.now() - t0).toBeLessThan(1500);
+ expect(row(far.id).status).toBe("running");
+ } finally {
+ runner.busy = false;
+ }
+ });
+});
+
+describe("live updates", () => {
+ it("emits every insert and update as the Generation JSON, and deletes as {id}", async () => {
+ gens.ensureRunner();
+ const events: { type: string; data: unknown }[] = [];
+ const off = live.subscribe((e) => events.push({ type: e.type, data: JSON.parse(e.json) }));
+ try {
+ const g = image("live fox");
+ await settle(g.id);
+ await sleep(50);
+ const mine = events.filter((e) => (e.data as { id: string }).id === g.id);
+ expect(mine[0]).toMatchObject({ type: "generation", data: { id: g.id, status: "queued" } });
+ expect(mine.some((e) => (e.data as Generation).status === "running")).toBe(true);
+ const last = mine.at(-1)!.data as Generation;
+ expect(last.status).toBe("succeeded");
+ // Exactly what the REST list returns for it.
+ expect(last).toEqual(JSON.parse(JSON.stringify(gens.listGenerations({ limit: 200 }).find((x) => x.id === g.id))));
+ gens.deleteGeneration(g.id);
+ await sleep(50);
+ expect(events.at(-1)).toEqual({ type: "deleted", data: { id: g.id } });
+ } finally {
+ off();
+ }
+ expect(live.listenerCount()).toBe(0);
+ });
+
+ it("streams server-sent events with pings, and drops the listener when the client goes away", async () => {
+ const before = live.listenerCount();
+ const ac = new AbortController();
+ const res = live.generationEventStream(ac.signal, { pingMs: 100 });
+ expect(res.headers.get("content-type")).toBe("text/event-stream; charset=utf-8");
+ expect(res.headers.get("cache-control")).toContain("no-transform");
+ expect(live.listenerCount()).toBe(before + 1);
+ const reader = res.body!.getReader();
+ const dec = new TextDecoder();
+ let text = "";
+ const g = image("streamed fox");
+ const until2 = Date.now() + 8000;
+ while (!(text.includes(": ping") && text.includes(`"id":"${g.id}"`)) && Date.now() < until2) {
+ const { value } = await reader.read();
+ text += dec.decode(value);
+ }
+ expect(text).toMatch(/^retry: 2000\n/);
+ expect(text).toContain("event: generation\ndata: {");
+ expect(text).toContain(": ping\n\n");
+ ac.abort();
+ expect(live.listenerCount()).toBe(before);
+ await gens.cancelGeneration(g.id);
+ });
+});
diff --git a/tests/training-runtime.test.ts b/tests/training-runtime.test.ts
new file mode 100644
index 00000000..63c007a0
--- /dev/null
+++ b/tests/training-runtime.test.ts
@@ -0,0 +1,92 @@
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-train-rt-"));
+process.env.FUOBE_DATA_DIR = dir;
+
+const { db } = await import("@/server/db");
+const { createElement, getElement, updateElement } = await import("@/server/elements");
+const { pollTrainings, listTrainings } = await import("@/server/training");
+const { setSetting } = await import("@/server/settings");
+
+// A stand-in fal queue and AI-Toolkit.
+const routes: Record<string, { status: number; body: unknown }> = {};
+const server = http.createServer((req, res) => {
+ const r = routes[req.url!.split("?")[0]] ?? { status: 404, body: { detail: "not found" } };
+ res.writeHead(r.status, { "content-type": "application/json" });
+ res.end(JSON.stringify(r.body));
+});
+let base = "";
+beforeAll(async () => {
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ base = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
+ setSetting("falKey", "test-key");
+ setSetting("aiToolkitUrl", base);
+});
+afterAll(() => {
+ server.close();
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+function training(o: { target: string; provider: string; status: string; externalId?: string | null; meta?: unknown; age?: number }) {
+ const el = createElement({ name: `Maya ${Math.random().toString(36).slice(2, 6)}`, kind: "character", references: [] });
+ updateElement(el.id, { status: "training" });
+ const id = `t_${Math.random().toString(36).slice(2, 10)}`;
+ const at = Date.now() - (o.age ?? 0);
+ db()
+ .prepare(
+ `INSERT INTO trainings (id, element_id, target, provider, status, external_id, meta_json, trigger_word, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'mayafz', ?, ?)`,
+ )
+ .run(id, el.id, o.target, o.provider, o.status, o.externalId ?? null, o.meta ? JSON.stringify(o.meta) : null, at, at);
+ return { id, elementId: el.id };
+}
+
+const state = (id: string) => listTrainings().find((t) => t.id === id)!;
+
+describe("training jobs reach an end (S6)", () => {
+ it("fails a fal training whose result URL answers 4xx, and frees the element", async () => {
+ routes["/fal/status"] = { status: 200, body: { status: "COMPLETED" } };
+ routes["/fal/response"] = { status: 422, body: { detail: "Training failed: not enough faces" } };
+ const t = training({ target: "fal-z-image", provider: "fal", status: "running", externalId: "req1", meta: { statusUrl: `${base}/fal/status`, responseUrl: `${base}/fal/response` } });
+ await pollTrainings();
+ expect(state(t.id)).toMatchObject({ status: "failed", error: expect.stringMatching(/422.*not enough faces/) });
+ expect(getElement(t.elementId)?.status).toBe("ready");
+ });
+
+ it("fails on a reported error, keeps polling through a transient one", async () => {
+ routes["/fal/err"] = { status: 200, body: { status: "COMPLETED", error: "Out of memory" } };
+ routes["/fal/busy"] = { status: 503, body: { detail: "try later" } };
+ const bad = training({ target: "fal-z-image", provider: "fal", status: "running", externalId: "r2", meta: { statusUrl: `${base}/fal/err`, responseUrl: `${base}/x` } });
+ const busy = training({ target: "fal-z-image", provider: "fal", status: "running", externalId: "r3", meta: { statusUrl: `${base}/fal/busy`, responseUrl: `${base}/x` } });
+ await pollTrainings();
+ expect(state(bad.id)).toMatchObject({ status: "failed", error: expect.stringMatching(/Out of memory/) });
+ expect(state(busy.id)).toMatchObject({ status: "running", message: expect.stringMatching(/Checking status failed/) });
+ db().prepare("UPDATE trainings SET status = 'failed' WHERE id = ?").run(busy.id);
+ });
+
+ it("fails an AI-Toolkit job that was deleted (404)", async () => {
+ const t = training({ target: "aitk-z-image", provider: "ai-toolkit", status: "running", externalId: "job-gone" });
+ await pollTrainings();
+ expect(state(t.id)).toMatchObject({ status: "failed", error: expect.stringMatching(/AI-Toolkit 404/) });
+ });
+
+ it("gives up after 8 hours", async () => {
+ routes["/fal/slow"] = { status: 200, body: { status: "IN_PROGRESS", logs: [] } };
+ const t = training({ target: "fal-z-image", provider: "fal", status: "running", externalId: "r4", meta: { statusUrl: `${base}/fal/slow` }, age: 9 * 3_600_000 });
+ await pollTrainings();
+ expect(state(t.id)).toMatchObject({ status: "failed", error: expect.stringMatching(/8 hours/) });
+ });
+
+ it("fails a training a restart cut off before it reached the trainer, so it can be started again", async () => {
+ const t = training({ target: "fal-z-image", provider: "fal", status: "queued", age: 5 * 60_000 });
+ const fresh = training({ target: "fal-z-image", provider: "fal", status: "queued" });
+ await pollTrainings();
+ expect(state(t.id)).toMatchObject({ status: "failed", error: expect.stringMatching(/Interrupted/) });
+ expect(getElement(t.elementId)?.status).toBe("ready");
+ expect(state(fresh.id).status).toBe("queued");
+ });
+});