The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Runner and chains: poll before timing out, second audio track and stems, planned op for chained translates
Claude634f3cfa151b
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex 855a61ac..d1eafb6a 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -18,6 +18,7 @@ const RequestSchema = z.object({sketch: z.string().optional(),video: z.string().optional(),audio: z.string().optional(),+ audio2: z.string().optional(),voiceAudio: z.string().optional(),voiceAudio2: z.string().optional(),videos: z.array(z.string()).max(24).optional(),diff --git a/src/lib/catalog/canvas.ts b/src/lib/catalog/canvas.tsindex ad22ff15..ea279585 100644--- a/src/lib/catalog/canvas.ts+++ b/src/lib/catalog/canvas.ts@@ -592,6 +592,7 @@ const SLOT_KIND: Record<ChainSlot["slot"], MediaKind> = {videos: "video",audio: "audio",voiceAudio: "audio",+ audio2: "audio",prompt: "text",};diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex b29cf871..ec543c0c 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -378,6 +378,8 @@ export interface GenerationRequest {sketch?: string;video?: string;audio?: string;+ /** Second audio track: the background stem (or a music bed) mixed under `audio` (mux). */+ audio2?: string;/** Reference recording of the voice to speak with / convert into. */voiceAudio?: string;/** Second speaker's reference voice (open-source dialogue). */@@ -409,10 +411,17 @@ export interface ChainSlot {* "prompt" takes the dependency's text output (OutputFile.text): it replaces "{text}" in the* request's prompt, or becomes the prompt when there is no placeholder.* "voiceAudio" clones the voice of the dependency's audio output.+ * "audio2" is the second audio track (the background stem mixed under the new voice, mux).*/- slot: "images" | "endImage" | "video" | "videos" | "audio" | "voiceAudio" | "prompt";+ slot: "images" | "endImage" | "video" | "videos" | "audio" | "voiceAudio" | "audio2" | "prompt";/** For list slots: put it before or after the request's own items (default last). */position?: "first" | "last";+ /**+ * Audio slots: take the dependency's output whose `meta.stem` is this (separate-audio makes+ * "voice" and "background"; "voice" also matches vocals/speech/target, "background" also+ * accompaniment/instrumental/residual/no_vocals). Without it, the first output of the slot's kind.+ */+ stem?: string;}/** Canonical, provider-ready input (asset refs already resolved to provider URLs/filenames). */@@ -424,6 +433,8 @@ export interface GenInput extends GenParams {mask?: string;video?: string;audio?: string;+ /** Second audio track (mux: the background mixed under `audio`). */+ audio2?: string;voiceAudio?: string;voiceAudio2?: string;videos?: string[];diff --git a/src/server/chains.ts b/src/server/chains.tsindex a4f23248..9f9ede96 100644--- a/src/server/chains.ts+++ b/src/server/chains.ts@@ -216,7 +216,7 @@ export interface PipelineStep {/** Unique name of the step within the pipeline (used by `after` and in `byKey`). */key: string;request: GenerationRequest;- /** Steps whose first output this one takes, in the order of its chain slots. */+ /** Steps whose output this one takes (the first of the slot's kind, or the slot's stem), in the order of its chain slots. */after?: string | string[];/** Where each `after` step's output goes (defaults to `request.chain`, else the images). */chain?: ChainSlot[];@@ -237,6 +237,9 @@ export interface Pipeline {const asList = (a: string | string[] | undefined) => (a === undefined ? [] : Array.isArray(a) ? a : [a]);+/** Chain slots that take an audio output (and so may pick a stem). */+const AUDIO_SLOTS = new Set<ChainSlot["slot"]>(["audio", "voiceAudio", "audio2"]);+/** Kahn's algorithm: steps in an order where every `after` comes first; throws on a cycle. */function topoOrder(steps: PipelineStep[]): PipelineStep[] {const byKey = new Map(steps.map((s) => [s.key, s]));@@ -266,20 +269,28 @@ function topoOrder(steps: PipelineStep[]): PipelineStep[] {* demo and real steps — before a single row is created; then the rows are created in* dependency order and the runner launches each step when the steps it waits for succeed.*- * @example Dub a clip into Spanish with the speaker's own voice+ * A chain slot takes the first output of its kind from the step it names, or with `stem` the+ * audio output whose `meta.stem` matches — that's how one separate-audio step feeds both the voice+ * to clone and the background to mix back in.+ *+ * @example Dub a clip into Spanish in the speaker's own voice, over the original music and effects* ```ts* const video = "/api/files/uploads/2026-10-17/clip.mp4";* const { batchId, byKey } = createPipeline([- * // Voice and background stems; the voice stem (the first audio output) is what we clone.- * { key: "stems", request: { feature: "dub", modelId: "…separate-audio model", op: "separate-audio", inputs: { video } } },- * { key: "words", request: { feature: "dub", modelId: "…transcribe model", op: "transcribe" }, after: "stems", chain: [{ slot: "audio" }] },+ * // Two stems: meta.stem "voice" and "background".+ * { key: "stems", request: { feature: "dub", modelId: "oss-voice-separate", op: "separate-audio", inputs: { video } } },+ * { key: "words", request: { feature: "dub", modelId: "oss-qwen3-asr", op: "transcribe" }, after: "stems", chain: [{ slot: "audio", stem: "voice" }] },* // A transcript's cues go in as a cue list, so the translation keeps the timing.- * { key: "spanish", request: { feature: "dub", modelId: "text-llm", op: "translate", params: { targetLanguage: "Spanish" } }, after: "words", chain: [{ slot: "prompt" }] },- * { key: "voice", request: { feature: "dub", modelId: "chatterbox-cloud", op: "tts" }, after: ["spanish", "stems"], chain: [{ slot: "prompt" }, { slot: "voiceAudio" }] },- * { key: "lips", request: { feature: "dub", modelId: "sync-lipsync-3", op: "lipsync", inputs: { video } }, after: "voice", chain: [{ slot: "audio" }] },- * { key: "film", request: { feature: "dub", modelId: "…mux model", op: "mux" }, after: ["lips", "voice"], chain: [{ slot: "video" }, { slot: "audio" }] },+ * { key: "spanish", request: { feature: "dub", modelId: "oss-text-llm", op: "translate", params: { targetLanguage: "Spanish" } }, after: "words", chain: [{ slot: "prompt" }] },+ * // Speak the translation, cloning the voice stem.+ * { key: "voice", request: { feature: "dub", modelId: "oss-chatterbox", op: "tts" }, after: ["spanish", "stems"], chain: [{ slot: "prompt" }, { slot: "voiceAudio", stem: "voice" }] },+ * { key: "lips", request: { feature: "dub", modelId: "oss-infinitetalk-v2v", op: "lipsync", inputs: { video } }, after: "voice", chain: [{ slot: "audio" }] },+ * // The new voice over the background stem (inputs.audio2).+ * { key: "film", request: { feature: "dub", modelId: "oss-mux", op: "mux" }, after: ["lips", "voice", "stems"], chain: [{ slot: "video" }, { slot: "audio" }, { slot: "audio2", stem: "background" }] },* ]);* // byKey.film is the finished video; every step shares batchId and shows "Step n of 6".+ * // Paid route: demucs ("vocals" counts as "voice"), scribe-v2, text-llm, chatterbox-cloud, sync-lipsync-3;+ * // its soundtrack model (merge-audio-video) takes one track, so it ends at "lips" or muxes the voice alone.* ```*/export function createPipeline(steps: PipelineStep[], opts: PipelineOptions = {}): Pipeline {@@ -299,6 +310,8 @@ export function createPipeline(steps: PipelineStep[], opts: PipelineOptions = {}if (new Set(after).size !== after.length) throw new Error(`Step “${s.key}” lists the same step twice`);const chain = s.chain ?? s.request.chain;if (chain && chain.length !== after.length) throw new Error(`Step “${s.key}” has ${chain.length} chain slot${chain.length === 1 ? "" : "s"} for ${after.length} earlier step${after.length === 1 ? "" : "s"}`);+ const stray = chain?.find((c) => c.stem && !AUDIO_SLOTS.has(c.slot));+ if (stray) throw new Error(`Step “${s.key}”: a stem (“${stray.stem}”) only goes into an audio slot, not “${stray.slot}”`);}const ordered = topoOrder(steps);const n = steps.length;diff --git a/src/server/generations.ts b/src/server/generations.tsindex f76c9e33..44853f22 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -5,6 +5,7 @@ import { nanoid } from "nanoid";import { getModel, getPreset } from "@/lib/catalog";import { applyMentions } from "@/lib/catalog/elements";import { applySketch, stripMotionPaths } from "@/lib/catalog/sketch";+import { cueText, type Cue } from "@/lib/cues";import { estimateCost, planGeneration, routesFor } from "@/lib/catalog/plan";import {LAST_FRAME_CHAIN,@@ -27,7 +28,7 @@ import { setResolver, watchGenerations, type LiveEvent } from "./live";import { provider } from "./providers";import { probeComfy } from "./providers/comfyui";import { llmBackends, llmMissing, llmUsesClaude, probeOllama } from "./providers/llm";-import type { PollContext, RemoteOutput } from "./providers/types";+import type { PollContext, PollResult, RemoteOutput } from "./providers/types";import { convertMask } from "./png";import { engineMode, getSetting } from "./settings";import { contentTypeFor, deleteAsset, readRef, saveFile } from "./storage";@@ -373,9 +374,26 @@ const SLOT_KIND: Record<ChainSlot["slot"], MediaKind> = {videos: "video",audio: "audio",voiceAudio: "audio",+ audio2: "audio",prompt: "text",};+/** Names providers give the same stem (ComfyUI: voice/background; Demucs: vocals…; SAM Audio: target/residual). */+const STEM_ALIASES: Record<string, string[]> = {+ voice: ["voice", "vocals", "speech", "target"],+ background: ["background", "accompaniment", "instrumental", "residual", "no_vocals"],+};++/** The dependency output a slot takes: the first of the slot's kind, or the one with the slot's `stem`. */+export function pickOutput(outputs: OutputFile[], s: ChainSlot): OutputFile | undefined {+ const ofKind = outputs.filter((o) => o.kind === SLOT_KIND[s.slot]);+ if (!s.stem) return ofKind[0];+ const want = STEM_ALIASES[s.stem.toLowerCase()] ?? [s.stem.toLowerCase()];+ return ofKind.find((o) => typeof o.meta?.stem === "string" && want.includes(o.meta.stem.toLowerCase()));+}++const slotNoun = (s: ChainSlot) => (s.stem ? `${s.stem} stem` : SLOT_KIND[s.slot]);+function placeholderFor(s: ChainSlot): string {const kind = SLOT_KIND[s.slot];if (kind === "text") return "Placeholder text from an earlier step";@@ -385,13 +403,16 @@ function placeholderFor(s: ChainSlot): string {/*** 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.+ * file, or cut short inline (meta.truncated), 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;+ const cues = Array.isArray(o.meta?.cues) && o.meta.cues.length ? (o.meta.cues as Cue[]) : null;+ if (op === "translate" && cues) return JSON.stringify(cues);+ if (typeof o.text === "string" && !o.meta?.truncated) return o.text;+ // Timed text is saved as subtitles: its words come from the cues, not the .srt file.+ if (cues) return cueText(cues);if (!o.url) return undefined;return readRef(o.url).then((f) => f.data.toString("utf8"))@@ -463,12 +484,11 @@ async function advanceDependents(): Promise<void> {submitting().add(r.id);let handedOff = false;try {- 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)),- );+ // The planned op (r.op), not request.op: a translate whose op was inferred still gets the cue list.+ const values = await Promise.all(deps.map((d, i) => chainValue(pickOutput(JSON.parse(d!.outputs_json) as OutputFile[], slots[i]), slots[i], r.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() });+ update(r.id, { status: "failed", error: `${earlier} has no ${slotNoun(slots[missing])} to use`, message: null, completed_at: Date.now() });continue;}// Routing reads cached reachability: make sure it's fresh for local engines.@@ -547,6 +567,7 @@ async function submit(mask: await prepMask(req.inputs?.mask),video: await prep(req.inputs?.video),audio: await prep(req.inputs?.audio),+ audio2: await prep(req.inputs?.audio2),voiceAudio: await prep(req.inputs?.voiceAudio),voiceAudio2: await prep(req.inputs?.voiceAudio2),videos: (await Promise.all((req.inputs?.videos ?? []).map(prep))).filter(Boolean) as string[],@@ -729,24 +750,34 @@ async function pollOne(r: Row): Promise<void> {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;+ // Poll first: a job that finished while the server was asleep or down is collected, not timed out.+ let res: PollResult | undefined;+ let pollError: unknown;+ try {+ res = await provider(r.provider).poll(ctx);+ } catch (e) {+ pollError = e;}- 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);+ if (!res || res.state === "queued" || res.state === "running") {+ // A job that has just left the queue gets its full running time from now.+ const startsNow = res?.state === "running" && !run.started_at;+ const overdue = run.started_at ? now - run.started_at > TIMEOUT_MS : !startsNow && now - run.submitted_at > QUEUE_TIMEOUT_MS;+ 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;+ }+ if (!res) throw pollError;+ if (startsNow) 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;}@@ -761,7 +792,7 @@ async function pollOne(r: Row): Promise<void> {try {outputs.push(await persistOutput(o, r.id));} catch (e) {- 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 } : {}) });+ outputs.push({ url: o.url, kind: o.kind ?? r.kind, ...inlineText(o.text, o.meta), ...(o.draftId ? { draftId: o.draftId } : {}) });console.warn(`[fuobe] could not save output for ${r.id}: ${(e as Error).message}`);}}@@ -777,8 +808,17 @@ async function pollOne(r: Row): Promise<void> {/** 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;+/**+ * Text kept inline on the generation. Every list page and live event carries it, so longer text+ * (long transcripts, scripts) is cut there, marked `meta.truncated`, and read in full from its file.+ */+export const MAX_INLINE_TEXT = 64_000;++function inlineText(text: string | undefined, meta: Record<string, unknown> | undefined): Pick<OutputFile, "text" | "meta"> {+ if (text === undefined) return meta ? { meta } : {};+ if (text.length <= MAX_INLINE_TEXT) return { text, ...(meta && { meta }) };+ return { text: text.slice(0, MAX_INLINE_TEXT), meta: { ...meta, truncated: true } };+}async function persistOutput(o: RichOutput, generationId: string): Promise<OutputFile> {let data: Buffer;@@ -803,14 +843,13 @@ async function persistOutput(o: RichOutput, generationId: string): Promise<Outpu}const asset = saveFile({ data, contentType: contentType!, source: "generation", generationId });// 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);+ const text = o.text ?? (asset.kind === "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 }),+ ...inlineText(text, o.meta),...(o.draftId ? { draftId: o.draftId } : {}),};}diff --git a/tests/pipeline.test.ts b/tests/pipeline.test.tsindex ee62fb15..41c0e260 100644--- a/tests/pipeline.test.ts+++ b/tests/pipeline.test.ts@@ -115,6 +115,94 @@ describe("createPipeline on the demo provider", () => {});});+describe("stems and the second audio track", () => {+ const clip = () => saveFile({ data: fs.readFileSync(path.join(process.cwd(), "public/samples/demo-landscape.mp4")), contentType: "video/mp4", source: "upload" }).url;+ const providerInput = (id: string) => JSON.parse((db().prepare("SELECT provider_input_json FROM generations WHERE id = ?").get(id) as { provider_input_json: string }).provider_input_json) as Record<string, unknown>;++ it("separates once, clones the voice stem and mixes the new voice over the background stem", async () => {+ const video = clip();+ const p = createPipeline([+ { key: "stems", request: { feature: "dub", modelId: "oss-voice-separate", op: "separate-audio", inputs: { video } } },+ { key: "voice", request: { feature: "dub", modelId: "oss-chatterbox", op: "tts", prompt: "Hola a todos, bienvenidos." }, after: "stems", chain: [{ slot: "voiceAudio", stem: "voice" }] },+ {+ key: "film",+ request: { feature: "dub", modelId: "oss-mux", op: "mux", inputs: { video } },+ after: ["voice", "stems"],+ chain: [{ slot: "audio" }, { slot: "audio2", stem: "background" }],+ },+ ]);+ expect(p.items.map((g) => g.op)).toEqual(["separate-audio", "tts", "mux"]);+ expect(dependsOn(p.byKey.film.id)).toEqual([p.byKey.voice.id, p.byKey.stems.id]);++ const film = await settle(p.byKey.film.id);+ expect(film.status, film.error ?? "").toBe("succeeded");+ const stems = gens.getGeneration(p.byKey.stems.id)!;+ const voice = gens.getGeneration(p.byKey.voice.id)!;+ const stem = (name: string) => stems.outputs.find((o) => o.meta?.stem === name)!.url;+ expect(stems.outputs.map((o) => o.meta?.stem)).toEqual(["voice", "background"]);+ // The voice stem is cloned; the background stem (not the first audio output) goes under the new voice.+ expect(voice.request.inputs?.voiceAudio).toBe(stem("voice"));+ expect(film.request.inputs).toEqual({ video, audio: voice.outputs[0].url, audio2: stem("background") });+ // …and reaches the provider as the canonical second track.+ const sent = providerInput(film.id);+ expect(sent.audio).toEqual(expect.stringMatching(/^data:audio\/wav/));+ expect(sent.audio2).toEqual(expect.stringMatching(/^data:audio\/wav/));+ });++ it("accepts audio2 on POST /api/generations", async () => {+ const { POST } = await import("@/app/api/generations/route");+ const res = await POST(+ new Request("http://localhost/api/generations", {+ method: "POST",+ body: JSON.stringify({ feature: "edit", modelId: "oss-mux", op: "mux", inputs: { video: "/api/files/a.mp4", audio: "/api/files/v.wav", audio2: "/api/files/bg.wav" } }),+ }),+ );+ expect(res.status).toBe(201);+ const { items } = (await res.json()) as { items: Generation[] };+ expect(items[0].request.inputs?.audio2).toBe("/api/files/bg.wav");+ await gens.cancelGeneration(items[0].id);+ });++ it("fails a step whose stem the earlier step didn't make, and refuses a stem on a non-audio slot", async () => {+ expect(() =>+ createPipeline([step("a", "oss-voice-separate", { op: "separate-audio", inputs: { video: "/api/files/a.mp4" } }), { ...step("b", "oss-mux", { op: "mux", inputs: { audio: "/api/files/v.wav" } }), after: "a", chain: [{ slot: "video", stem: "voice" }] }]),+ ).toThrow(/Step “b”: a stem \(“voice”\) only goes into an audio slot, not “video”/);+ const p = createPipeline([+ step("a", "oss-voice-separate", { op: "separate-audio", inputs: { video: clip() } }),+ { ...step("b", "oss-chatterbox", { op: "tts" }), after: "a", chain: [{ slot: "voiceAudio", stem: "drums" }] },+ ]);+ const b = await settle(p.byKey.b.id);+ expect(b.status).toBe("failed");+ expect(b.error).toBe("An earlier step has no drums stem to use");+ });++ it("picks stems by the names other providers use (Demucs: vocals)", () => {+ const outs = [+ { url: "/api/files/drums.wav", kind: "audio" as const, meta: { stem: "drums" } },+ { url: "/api/files/vocals.wav", kind: "audio" as const, meta: { stem: "vocals" } },+ { url: "/api/files/rest.wav", kind: "audio" as const, meta: { stem: "accompaniment" } },+ ];+ expect(gens.pickOutput(outs, { slot: "voiceAudio", stem: "voice" })?.url).toBe("/api/files/vocals.wav");+ expect(gens.pickOutput(outs, { slot: "audio2", stem: "Background" })?.url).toBe("/api/files/rest.wav");+ expect(gens.pickOutput(outs, { slot: "audio", stem: "drums" })?.url).toBe("/api/files/drums.wav");+ expect(gens.pickOutput(outs, { slot: "audio" })?.url).toBe("/api/files/drums.wav");+ });++ it("gives a translate step the cue list even when its op was left to be inferred", async () => {+ const p = createPipeline([+ step("words", "test-transcribe", { op: "transcribe", inputs: { video: clip() } }),+ // No op: text-llm's first route (translate) is planned, and the cues must still go in.+ { key: "es", request: { feature: "dub", modelId: "text-llm", params: { targetLanguage: "Spanish" } }, after: "words", chain: [{ slot: "prompt" }] },+ ]);+ expect(p.byKey.es.op).toBe("translate");+ const es = await settle(p.byKey.es.id);+ expect(es.status, es.error ?? "").toBe("succeeded");+ const words = gens.getGeneration(p.byKey.words.id)!;+ expect(JSON.parse(es.request.prompt!)).toEqual(words.outputs[0].meta!.cues);+ expect((es.outputs[0].meta!.cues as unknown[]).length).toBe((words.outputs[0].meta!.cues as unknown[]).length);+ });+});+describe("one mode per chain at launch (S9)", () => {const insertDone = (id: string, providerId: string, outputs: unknown[]) =>db()diff --git a/tests/runtime-runner.test.ts b/tests/runtime-runner.test.tsindex afc1ba86..1dc8e383 100644--- a/tests/runtime-runner.test.ts+++ b/tests/runtime-runner.test.ts@@ -49,17 +49,48 @@ describe("timeouts (S3)", () => {expect(done.status).toBe("succeeded");});+ /** Make the demo provider report `state` for one job (by its external id) until restored. */+ const holdAt = (externalId: () => string | null, state: "queued" | "running") => {+ const poll = mockProvider.poll;+ mockProvider.poll = async (ctx) => (ctx.externalId === externalId() ? { state, message: `held ${state}` } : poll(ctx));+ return () => {+ mockProvider.poll = poll;+ };+ };+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;+ const g = image("runs forever");+ const restore = holdAt(() => row(g.id).external_id, "running");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 {+ restore();+ delete mockProvider.cancel;+ }+ });++ it("collect a job that finished at the provider while the server was away, however late", async () => {+ const cancel = vi.fn(async () => {});+ mockProvider.cancel = cancel;+ try {+ const g = image("finished while the laptop slept");+ await until(() => row(g.id).external_id);+ // An hour later: the provider has long finished it (the demo job "started" an hour ago too).+ const hourAgo = Date.now() - 60 * 60_000;+ const meta = JSON.parse((db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").get(g.id) as { external_meta_json: string }).external_meta_json);+ db().prepare("UPDATE generations SET external_meta_json = ? WHERE id = ?").run(JSON.stringify({ ...meta, startedAt: hourAgo }), g.id);+ db().prepare("UPDATE generation_runs SET submitted_at = ?, started_at = ? WHERE id = ?").run(hourAgo, hourAgo, g.id);+ const done = await settle(g.id);+ expect(done.status, done.error ?? "").toBe("succeeded");+ expect(done.outputs[0]).toMatchObject({ kind: "image", url: expect.stringMatching(/^\/api\/files\//) });+ expect(cancel).not.toHaveBeenCalled();} finally {delete mockProvider.cancel;}@@ -67,10 +98,30 @@ describe("timeouts (S3)", () => {it("give a job that never left the queue a longer, separate limit", async () => {const g = image("stuck in the queue");+ const restore = holdAt(() => row(g.id).external_id, "queued");+ try {+ 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/);+ } finally {+ restore();+ }+ });++ it("give a job that leaves the queue late its full running time", async () => {+ const g = image("finally on the GPU");await until(() => row(g.id).external_id);+ // Waited 5 hours in the queue, but the provider has just started it: it runs to the end.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/);+ const restore = holdAt(() => row(g.id).external_id, "running");+ try {+ await until(() => (db().prepare("SELECT started_at FROM generation_runs WHERE id = ?").get(g.id) as { started_at: number | null }).started_at);+ expect(gens.getGeneration(g.id)!.status).toBe("running");+ } finally {+ restore();+ }+ expect((await settle(g.id)).status).toBe("succeeded");});});