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
Mixed Media: a failed frame stops the waiting lanes, Try again redraws only what didn't finish
Claude9771500e9afe
diff --git a/src/app/api/mixed-media/progress/route.ts b/src/app/api/mixed-media/progress/route.tsindex 4cdfcddd..4a11a714 100644--- a/src/app/api/mixed-media/progress/route.ts+++ b/src/app/api/mixed-media/progress/route.ts@@ -1,11 +1,12 @@import { framesProgress } from "@/server/mixed-media";import { handle } from "@/server/shorts-schemas";-/** How far a per-frame render's frame edits are (?batch=<the render's batch id>): counts, and the first frame that failed. */+/** How far a per-frame render's frame edits are (?id=<the render's finished video>): counts, and the first frame that failed. */export async function GET(request: Request) {return handle(() => {- const batch = new URL(request.url).searchParams.get("batch")?.trim() ?? "";- if (!batch || batch.length > 64) return Response.json({ error: "Which render?" }, { status: 400 });- return Response.json(framesProgress(batch));+ const id = new URL(request.url).searchParams.get("id")?.trim() ?? "";+ if (!id || id.length > 64) return Response.json({ error: "Which render?" }, { status: 400 });+ const progress = framesProgress(id);+ return progress ? Response.json(progress) : Response.json({ error: "This render no longer exists" }, { status: 404 });});}diff --git a/src/components/mixed-media/history.tsx b/src/components/mixed-media/history.tsxindex 6997e370..a07b12f4 100644--- a/src/components/mixed-media/history.tsx+++ b/src/components/mixed-media/history.tsx@@ -85,8 +85,8 @@ export function MixedHistory({ onStart }: { onStart: () => void }) {<PendingTile g={state.status === "working" ? (chain.find((x) => x.status !== "succeeded") ?? g) : g} ratio={1} />) : (<div className="flex size-full flex-col justify-center gap-1 border border-dashed p-3">- {g.status !== "canceled" && isFrameRender(chain) && g.batchId ? (- <FrameFailure batchId={g.batchId} heading={heading} reason={reason} />+ {g.status !== "canceled" && isFrameRender(chain) ? (+ <FrameFailure id={g.id} heading={heading} reason={reason} />) : (<><p className="text-[13px] font-medium">{heading}</p>@@ -124,9 +124,12 @@ export function MixedHistory({ onStart }: { onStart: () => void }) {);}-/** A per-frame render that failed: the frame that failed and why (the steps after it only say an earlier step didn't finish). */-function FrameFailure({ batchId, heading, reason }: { batchId: string; heading: string; reason?: string | null }) {- const failed = useFramesProgress(batchId, false).data?.failed;+/**+ * A per-frame render that failed: the frame that failed and why (the steps after it only say an earlier step didn't+ * finish). When no frame failed on its own (the cut or the extraction did), the failing step's error stands.+ */+function FrameFailure({ id, heading, reason }: { id: string; heading: string; reason?: string | null }) {+ const failed = useFramesProgress(id, "once").data?.failed;const title = failed ? `${failed.label} failed` : heading;const why = failed?.error ?? reason;return (diff --git a/src/components/mixed-media/hooks.ts b/src/components/mixed-media/hooks.tsindex 528f9040..15736532 100644--- a/src/components/mixed-media/hooks.ts+++ b/src/components/mixed-media/hooks.ts@@ -46,13 +46,18 @@ export interface FramesProgress {failed?: { label: string; error: string };}-/** A per-frame render's frame edits (counts and the first failure), polled while `live`; read once otherwise. */-export function useFramesProgress(batchId: string | null | undefined, live: boolean) {+/**+ * A per-frame render's frame edits (counts and the first failure), by its finished video's id: polled while "live"+ * (the frames are being redrawn), read once when "once" (a render that failed: its counts no longer change), not at all when null.+ */+export function useFramesProgress(finalId: string | null | undefined, mode: "live" | "once" | null) {return useQuery({- queryKey: ["mixed-media", "frames", batchId],- queryFn: async () => send<FramesProgress>(`/api/mixed-media/progress?batch=${encodeURIComponent(batchId!)}`, "GET"),- enabled: !!batchId,- refetchInterval: live ? 2000 : false,+ // The mode is in the key: a render that just failed is read once more, after its last poll.+ queryKey: ["mixed-media", "frames", finalId, mode],+ queryFn: async () => send<FramesProgress>(`/api/mixed-media/progress?id=${encodeURIComponent(finalId!)}`, "GET"),+ enabled: !!finalId && !!mode,+ refetchInterval: mode === "live" ? 2000 : false,+ staleTime: mode === "once" ? Infinity : 0,});}@@ -123,8 +128,8 @@ export function renderSteps(chain: (Generation | undefined)[]): { g?: Generationreturn chain.map((g) => ({ g, label: g ? stepLabel(g) : "A step" }));}-/** A per-frame render (its frames were taken by an extract step). */-export const isFrameRender = (chain: (Generation | undefined)[]) => chain.some((g) => g?.op === "extract-frames");+/** A per-frame render (its frames go back together in an images-to-video step; a retry may keep the extraction from before). */+export const isFrameRender = (chain: (Generation | undefined)[]) => chain.some((g) => g?.op === "extract-frames" || g?.op === "images-to-video");export function useMixedActions() {const qc = useQueryClient();diff --git a/src/components/mixed-media/mixed-studio.tsx b/src/components/mixed-media/mixed-studio.tsxindex 8fb0c3da..5133d707 100644--- a/src/components/mixed-media/mixed-studio.tsx+++ b/src/components/mixed-media/mixed-studio.tsx@@ -17,6 +17,7 @@ import {clampFps,defaultValues,fpsChoices,+ FRAME_LIMITS,MIXED,MIXED_PRESETS,mixedFrames,@@ -134,6 +135,11 @@ function How({ onStart }: { onStart: () => void }) {cloud each frame is redrawn by an image model and priced per frame (Nano Banana 2 or Seedream 5.0 Flash). Fast restyles the clip in one video-to-video pass,priced by the model. The estimate shows before you generate.</p>+ <p className="mt-2">+ To keep a render quick, the cloud redraws frames in runs of {FRAME_LIMITS.lane} side by side: each frame matches the one before it, and each run starts from+ your preview frame, so the look can shift slightly every {FRAME_LIMITS.lane} frames. If a frame fails, the frames still waiting stop, and Try again redraws only+ the frames that didn’t finish.+ </p></div><div className="mt-6 text-center"><button type="button" onClick={onStart} className="h-10 rounded-full bg-primary px-5 text-[14px] font-medium text-primary-foreground hover:bg-primary/90">@@ -663,7 +669,7 @@ function LatestRender({ chain, frames }: { chain: (Generation | undefined)[]; frconst steps = chain.some((x) => !x) ? null : chainState(renderSteps(chain));const perFrame = frames > 0 && isFrameRender(chain);const redrawing = perFrame && steps?.status === "working" && steps.label === "Redrawing the frames";- const progress = useFramesProgress(perFrame ? g?.batchId : null, redrawing || steps?.status === "failed").data;+ const progress = useFramesProgress(perFrame ? g?.id : null, redrawing ? "live" : steps?.status === "failed" ? "once" : null).data;let state = steps ?? ({ status: "working", label: "Rendering", progress: 0 } as const);if (perFrame && state.status === "working") {// The frames are most of the work: the cut and the extraction fill the first tenth of the bar, redrawing the@@ -672,7 +678,8 @@ function LatestRender({ chain, frames }: { chain: (Generation | undefined)[]; frconst p = redrawing ? 0.1 + 0.8 * (progress?.total ? progress.done / progress.total : 0) : state.progress < at ? (state.progress / at) * 0.1 : 0.9 + ((state.progress - at) / (1 - at)) * 0.1;state = { ...state, progress: p, ...(redrawing && progress?.total ? { label: `Redrawing frames · ${progress.done} of ${progress.total}` } : {}) };}- // A frame that failed: say which and why (the steps after it only say an earlier step didn't finish).+ // A frame that failed on its own: say which and why (the steps after it only say an earlier step didn't finish).+ // When the cut or the extraction failed, no frame did: that step's own error stands.if (state.status === "failed" && progress?.failed) state = { ...state, label: `${progress.failed.label} failed`, error: progress.failed.error };const out = g?.status === "succeeded" ? g.outputs.find((o) => o.kind === "video") : undefined;return (diff --git a/src/lib/catalog/mixed-media.ts b/src/lib/catalog/mixed-media.tsindex 3f3dec9f..5cceab76 100644--- a/src/lib/catalog/mixed-media.ts+++ b/src/lib/catalog/mixed-media.ts@@ -55,9 +55,12 @@ export const MIXED_FRAME_MODELS = ["nano-banana-2", "seedream-5-flash"] as const* Cloud per-frame limits: fal's extract-nth-frame returns up to 500 frames a call and images-to-video* takes up to 200 images. Frames are styled in lanes of `lane`: each frame looks at the one styled before* it, and each lane's first frame at the approved preview (else the first styled frame), so lanes run side- * by side and a 240-frame clip takes the time of about 13 edits, not 240.+ * by side and a 240-frame clip takes the time of about 13 edits, not 240. The price of that: a lane's first+ * frame matches the preview, not the frame before it, so a look that drifts within a lane can step back+ * every `lane` frames (the page's How it works says so). merge-videos sizes its output 512–2048 px+ * (`joinMaxPx`): clips of more than 200 frames are joined at that size.*/-export const FRAME_LIMITS = { perExtract: 500, perClip: 200, lane: 12, maxInterval: 300 } as const;+export const FRAME_LIMITS = { perExtract: 500, perClip: 200, lane: 12, maxInterval: 300, joinMaxPx: 2048, joinMinPx: 512 } as const;/** The seed every frame is redrawn with when the request names none (the same seed keeps frames alike). */export const FRAME_SEED = 424242;@@ -521,10 +524,33 @@ export function frameChunks(frames: number, size: number): { from: number; countreturn Array.from({ length: Math.ceil(frames / size) }, (_, i) => ({ from: i * size, count: Math.min(size, frames - i * size) }));}-/** What the cloud frame editor is asked for: Nano Banana 2 keeps the frame's shape at 1K/2K/4K, Seedream 5.0 Flash at auto 1K/2K. */+/**+ * What the cloud frame editor is asked for: Nano Banana 2 keeps the frame's shape at 1K/2K/4K, Seedream 5.0 Flash+ * at auto 1K/2K. Frames come back as JPEG (Seedream's default): every one is downloaded, sent on as the next+ * frame's reference and into images-to-video, and a 4K PNG is ten times the bytes for a frame that is re-encoded anyway.+ */export function frameEditParams(modelId: string, resolution: MixedResolution, seed: number): { aspectRatio?: string; resolution?: string; seed?: number; extra?: Record<string, unknown> } {if (modelId === "seedream-5-flash") return { extra: { image_size: resolution === "1K" ? "auto_1K" : "auto_2K" } };- return { aspectRatio: "auto", resolution, seed };+ return { aspectRatio: "auto", resolution, seed, extra: { output_format: "jpeg" } };+}++/**+ * The size clips of styled frames are joined at (merge-videos takes 512–2048 px a side): the source's shape with+ * its long side at 2048, its short side at least 512. Undefined without the source's size (fal then picks the+ * smallest of the clips).+ */+export function frameJoinSize(source?: { width?: number; height?: number }): { width: number; height: number } | undefined {+ const w = source?.width;+ const h = source?.height;+ if (!w || !h) return undefined;+ const even = (v: number) => Math.max(FRAME_LIMITS.joinMinPx, Math.min(FRAME_LIMITS.joinMaxPx, 2 * Math.round(v / 2)));+ const k = FRAME_LIMITS.joinMaxPx / Math.max(w, h);+ return { width: even(w * k), height: even(h * k) };+}++/** Per frame at 4K with more than one clip: joined at up to 2048 px, so frames are drawn at 2K (same picture, less money). */+export function frameResolution(frames: number, resolution: MixedResolution): MixedResolution {+ return frames > FRAME_LIMITS.perClip && resolution === "4K" ? "2K" : resolution;}// ---------------------------------------------------------------------------@@ -545,6 +571,8 @@ export interface MixedPlanInput {mode?: MixedMode;/** Cloud Per frame: the clip's own frame rate (frames are every Nth one of it). */sourceFps?: number;+ /** Cloud Per frame: the clip's own size (the clips of styled frames are joined at its shape). */+ sourceSize?: { width?: number; height?: number };/** Cloud: the approved preview still, sent when the model takes an image (LTX: the first frame; Kling, Happy Horse: a style reference). */anchor?: string;/** Cloud: what to ask the model for (its nearest resolution). */@@ -656,7 +684,9 @@ export function planMixedFrames(input: MixedPlanInput): { steps: PlanStep[]; finconst base = { batchTitle: input.title };const helper = { ...base, feature: MIXED_STEP_FEATURE };const seed = input.seed ?? FRAME_SEED;- const edit = frameEditParams(input.modelId, input.resolution, seed);+ const edit = frameEditParams(input.modelId, frameResolution(n, input.resolution), seed);+ // Only worth making for the steps after them: dropped before they're paid for once the render can't finish.+ const feeds = { dropWhenUnused: true };// The whole selection: its sound goes back under the result, and with one window its frames come from it.add("Cut", { key: "cut", request: { ...helper, modelId: t.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: input.range.start, endTime: input.range.end } } });const secondsPerWindow = (FRAME_LIMITS.perExtract * sampling.interval) / input.sourceFps;@@ -674,7 +704,8 @@ export function planMixedFrames(input: MixedPlanInput): { steps: PlanStep[]; fin...helper,modelId: t.frames,op: "extract-frames",- params: { frameInterval: sampling.interval, extra: { max_frames: w.count } },+ // JPEG frames: a tenth of the bytes of PNG, and every frame is downloaded and sent on.+ params: { frameInterval: sampling.interval, extra: { max_frames: w.count, output_format: "jpg", quality: 95 } },},after: [source],chain: [{ slot: "video" }],@@ -683,13 +714,14 @@ export function planMixedFrames(input: MixedPlanInput): { steps: PlanStep[]; finconst lane = FRAME_LIMITS.lane;for (let i = 0; i < n; i++) {const w = Math.floor(i / FRAME_LIMITS.perExtract);- const frame = { slot: "images" as const, index: i - w * FRAME_LIMITS.perExtract, position: "first" as const };+ const frame = { slot: "images" as const, index: i - w * FRAME_LIMITS.perExtract, of: windows[w].count, position: "first" as const };// The styled picture it matches: the frame before it in its lane, else the approved preview, else the first styled frame.const ref = i % lane ? `f${i - 1}` : input.anchor ? null : i ? "f0" : null;add(`Frame ${i + 1} of ${n}`, {key: `f${i}`,request: {...base,+ ...feeds,feature: MIXED_FRAME_FEATURE,modelId: input.modelId,op: "edit",@@ -707,7 +739,7 @@ export function planMixedFrames(input: MixedPlanInput): { steps: PlanStep[]; finadd(joined ? `Clip ${i + 1} of ${clips.length}` : "Frames to video", {key: `clip${i + 1}`,request: {- ...(last ? { ...base, feature: MIXED_FEATURE, title: input.title } : helper),+ ...(last ? { ...base, feature: MIXED_FEATURE, title: input.title } : { ...helper, ...feeds }),modelId: t.assemble,op: "images-to-video",params: { fps: sampling.fps },@@ -719,9 +751,17 @@ export function planMixedFrames(input: MixedPlanInput): { steps: PlanStep[]; finlet picture = "clip1";if (joined) {picture = "film";+ const size = frameJoinSize(input.sourceSize);add("Joining the clips", {key: "film",- request: { ...(sound ? helper : { ...base, feature: MIXED_FEATURE, title: input.title }), modelId: t.join, op: "concat", prompt: input.title },+ request: {+ ...(sound ? { ...helper, ...feeds } : { ...base, feature: MIXED_FEATURE, title: input.title }),+ modelId: t.join,+ op: "concat",+ prompt: input.title,+ // merge-videos sizes its output 512–2048 px: the frames' shape at that size.+ ...(size && { params: { extra: { resolution: size } } }),+ },after: clips.map((_, i) => `clip${i + 1}`),chain: clips.map(() => ({ slot: "videos" as const })),});@@ -757,6 +797,7 @@ export function planMixedPreview(input: MixedPlanInput & { frameUrl?: string }):}// Per frame: the frame editor itself with the render's settings, so the approved preview is what the first frame looks like.const frames = (input.mode ?? "frames") === "frames" && (MIXED_FRAME_MODELS as readonly string[]).includes(input.modelId);+ const count = frames && input.sourceFps ? frameSampling(input.range.end - input.range.start, input.fps, input.sourceFps).frames : 0;return {key: "preview",request: {@@ -767,7 +808,7 @@ export function planMixedPreview(input: MixedPlanInput & { frameUrl?: string }):prompt: prompts.still,inputs: { images: input.frameUrl ? [input.frameUrl] : [] },...(frames- ? { params: { ...frameEditParams(input.modelId, input.resolution, input.seed ?? FRAME_SEED), numOutputs: 1 } }+ ? { params: { ...frameEditParams(input.modelId, frameResolution(count, input.resolution), input.seed ?? FRAME_SEED), numOutputs: 1 } }: input.seed !== undefined? { params: { seed: input.seed } }: {}),diff --git a/src/server/mixed-media.ts b/src/server/mixed-media.tsindex 8e927647..bc9e643a 100644--- a/src/server/mixed-media.ts+++ b/src/server/mixed-media.ts@@ -3,13 +3,14 @@ import { getModel } from "@/lib/catalog";import {clampFps,cleanValues,+ FRAME_LIMITS,+ frameResolution,frameSampling,getMixedPreset,MIXED_FEATURE,MIXED_FRAME_FEATURE,MIXED_FRAME_MODELS,MIXED_MODELS,- MIXED_STEP_FEATURE,mixedFrames,mixedRangeProblem,nearestResolution,@@ -24,7 +25,7 @@ import { sourceSeconds, takesImage } from "@/lib/catalog/shorts-models";import type { Engine, Generation } from "@/lib/catalog/types";import { createPipeline } from "./chains";import { db } from "./db";-import { getGeneration, previewChained, unfilledRequest } from "./generations";+import { DROPPED_UNUSED, getGeneration, previewChained, unfilledRequest, waitedOnFailure } from "./generations";import { engineMode } from "./settings";import { probeSource, ShortsError } from "./shorts";@@ -46,7 +47,7 @@ export interface MixedBody {resolution: MixedResolution;/** Cloud Fast: the restyle model; cloud Per frame: the frame editor (MIXED_FRAME_MODELS). */modelId?: string;- /** Cloud: frame by frame (default) or Fast (one video-to-video pass). */+ /** Cloud: frame by frame or Fast (one video-to-video pass). Without it, Fast for a Fast restyle model, else Per frame. */mode?: MixedMode;/** Cloud: the approved preview still (anchors the render: Per frame always, Fast when the model takes an image). */anchor?: string;@@ -55,6 +56,23 @@ export interface MixedBody {seed?: number;}+/**+ * How a cloud render restyles: the mode asked for, else Fast when the model named is a Fast restyle model (an API+ * caller from before Per frame), else Per frame. A model that belongs to the other mode is refused, not swapped.+ */+function cloudMode(body: Pick<MixedBody, "engine" | "mode" | "modelId">): MixedMode | undefined {+ if (body.engine !== "cloud") return undefined;+ const fastModel = !!body.modelId && MIXED_MODELS.cloud.includes(body.modelId);+ const frameModel = !!body.modelId && (MIXED_FRAME_MODELS as readonly string[]).includes(body.modelId);+ const mode = body.mode ?? (fastModel ? "fast" : "frames");+ const name = (id: string) => getModel(id)?.name ?? id;+ if (mode === "frames" && fastModel) {+ throw new ShortsError(`${name(body.modelId!)} restyles the clip as video — pick Fast for it, or ${MIXED_FRAME_MODELS.map(name).join(" or ")} to redraw each frame`, 422);+ }+ if (mode === "fast" && frameModel) throw new ShortsError(`${name(body.modelId!)} redraws single frames — pick Per frame for it, or a Fast restyle model`, 422);+ return mode;+}+const ordinal = (n: number) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : (["th", "st", "nd", "rd"][n % 10] ?? "th")}`;async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ input: MixedPlanInput; frames: number; fps: number; notes: string[] }> {@@ -70,7 +88,7 @@ async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ iconst problem = mixedRangeProblem(body.range, duration, sourceFps);if (problem) throw new ShortsError(problem);const fps = clampFps(body.fps, sourceFps);- const mode: MixedMode | undefined = body.engine === "cloud" ? (body.mode ?? "frames") : undefined;+ const mode = cloudMode(body);const choices: readonly string[] = mode === "frames" ? MIXED_FRAME_MODELS : MIXED_MODELS[body.engine];const modelId = body.modelId && choices.includes(body.modelId) ? body.modelId : choices[0];const model = getModel(modelId);@@ -86,6 +104,10 @@ async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ irate = s.fps;if (Math.abs(s.fps - fps) > 0.01) notes.push(`Frames are every ${s.interval === 1 ? "" : `${ordinal(s.interval)} `}frame of this ${+sourceFps.toFixed(2)} FPS clip: ${+s.fps.toFixed(2)} FPS, ${frames} frames`);if (modelId === "seedream-5-flash") notes.push(`Seedream 5.0 Flash takes no seed, so frames vary a little more than with Nano Banana 2${body.resolution === "4K" ? "; it draws up to 2K" : ""}`);+ else if (frames > FRAME_LIMITS.perClip && body.resolution !== "1K") {+ // merge-videos sizes the joined clips 512–2048 px a side.+ notes.push(`Over ${FRAME_LIMITS.perClip} frames are made as clips and joined at up to ${FRAME_LIMITS.joinMaxPx} px${frameResolution(frames, body.resolution) !== body.resolution ? ", so frames are drawn at 2K" : ""}`);+ }} else if (mode === "fast") {// A cut the model won't take is paid for, then refused: say so before anything runs.const fits = (id: string) => clipLengthProblem({ name: getModel(id)?.name ?? id, minSeconds: sourceSeconds(id).min, maxSeconds: sourceSeconds(id).max }, len);@@ -119,6 +141,7 @@ async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ imodelId,mode,sourceFps,+ ...(info.width && info.height ? { sourceSize: { width: info.width, height: info.height } } : {}),anchor,modelResolution: mode === "fast" ? nearestResolution(model?.options.resolutions, body.resolution) : undefined,// LTX follows the clip's outlines, like the open engine's canny ControlNet.@@ -170,9 +193,9 @@ export async function estimateMixed(body: MixedBody): Promise<MixedEstimate> {return { ...full, previewUsd: preview.costUsd, frames, fps, notes, ...(input.mode && { mode: input.mode }), ...(perFrameUsd !== undefined && { perFrameUsd }) };}-function run(steps: PlanStep[]): { batchId: string; items: Generation[]; byKey: Record<string, Generation> } {+function run(steps: PlanStep[], opts: { existing?: Record<string, string> } = {}): { batchId: string; items: Generation[]; byKey: Record<string, Generation> } {try {- return createPipeline(steps);+ return createPipeline(steps, opts);} catch (e) {throw new ShortsError((e as Error).message, 422);}@@ -189,57 +212,111 @@ export async function createMixed(body: MixedBody): Promise<{ final: Generation;return { final: p.byKey[plan.final], ...followed(p) };}+interface StepRow {+ id: string;+ feature: string;+ status: Generation["status"];+ error: string | null;+ depends_on: string | null;+}++const depList = (v: string | null): string[] => (!v ? [] : v.startsWith("[") ? (JSON.parse(v) as string[]) : [v]);+/**- * Run a render again with the same settings (History's "Try again" after a failed step): its steps- * are made anew from their stored requests, waiting on each other as before.+ * A render's steps: its finished video and every step it waits for, across earlier tries (a retry's new steps+ * wait for the ones that had finished), inputs before the steps that take them. Null when one is gone.+ */+function renderSteps(finalId: string): StepRow[] | null {+ const get = db().prepare("SELECT id, feature, status, error, depends_on FROM generations WHERE id = ?");+ const rows = new Map<string, StepRow>();+ const order: StepRow[] = [];+ let gone = false;+ // Depth-first: a lane of frames is a dozen deep, so the recursion stays shallow.+ const visit = (id: string) => {+ if (rows.has(id) || gone) return;+ const r = get.get(id) as StepRow | undefined;+ if (!r) {+ gone = true;+ return;+ }+ rows.set(id, r);+ for (const d of depList(r.depends_on)) visit(d);+ order.push(r);+ };+ visit(finalId);+ return gone ? null : order;+}++/**+ * Try a render again (History's "Try again"): the steps that failed or were canceled, and every step after them,+ * are made anew (in a new batch) from their stored requests; they wait for the steps that finished, or are still+ * running, which aren't made or paid for again. A render with nothing failed is made again from its first step.*/export function retryMixed(id: string): { final: Generation; items: Generation[]; frames: number } {const final = getGeneration(id);- if (!final || final.feature !== MIXED_FEATURE || !final.batchId) throw new ShortsError("This render no longer exists", 404);+ if (!final || final.feature !== MIXED_FEATURE) throw new ShortsError("This render no longer exists", 404);const mode = engineMode();if (mode !== "both" && mode !== final.engine) {throw new ShortsError(mode === "open" ? "This install runs open-source models only (Settings → Engine mode)" : "This install runs cloud models only (Settings → Engine mode)", 422);}- const rows = db()- .prepare("SELECT id, depends_on FROM generations WHERE batch_id = ? AND feature IN (?, ?, ?) ORDER BY created_at ASC, id ASC")- .all(final.batchId, MIXED_FEATURE, MIXED_STEP_FEATURE, MIXED_FRAME_FEATURE) as { id: string; depends_on: string | null }[];- const deps = (v: string | null): string[] => (!v ? [] : v.startsWith("[") ? (JSON.parse(v) as string[]) : [v]);- const steps: PlanStep[] = rows.map((r) => {+ const rows = renderSteps(id);+ if (!rows) throw new ShortsError("Part of this render was deleted — make it again from the editor", 409);+ // In input order, so a step is redone when it failed or any step it waits for is redone.+ const redo = new Set<string>();+ for (const r of rows) if (r.status === "failed" || r.status === "canceled" || depList(r.depends_on).some((d) => redo.has(d))) redo.add(r.id);+ const again = redo.size ? rows.filter((r) => redo.has(r.id)) : rows;+ const existing = Object.fromEntries(rows.filter((r) => redo.size && !redo.has(r.id)).map((r) => [r.id, r.id]));+ const steps: PlanStep[] = again.map((r) => {const g = getGeneration(r.id);if (!g) throw new ShortsError("Part of this render was deleted — make it again from the editor", 409);- const after = deps(r.depends_on);- // Chained inputs were filled in when the step ran: the new run fills them from the new steps.+ const after = depList(r.depends_on);+ // Chained inputs were filled in when the step ran: the new run fills them from the new (or kept) steps.const { chain, ...request } = unfilledRequest(g.request, after.length);const inputs = { ...request.inputs };for (const c of chain ?? []) if (c.slot !== "images" && c.slot !== "videos" && c.slot !== "audios" && c.slot !== "prompt") delete inputs[c.slot];return { key: r.id, request: { ...request, inputs: Object.keys(inputs).length ? inputs : undefined }, ...(after.length ? { after, chain } : {}) };});- const p = run(steps);+ const p = run(steps, { existing });+ // Old steps that would only fail after the ones they wait for: stop them (nothing was spent on them yet).+ for (const r of again) if (r.status === "queued" && r.depends_on) cancelWaiting(r.id);return { final: p.byKey[id], ...followed(p) };}+/** Stop a step still waiting for its inputs (nothing spent yet). */+function cancelWaiting(id: string): void {+ db()+ .prepare("UPDATE generations SET status = 'canceled', message = NULL, completed_at = ?, updated_at = ? WHERE id = ? AND status = 'queued' AND external_id IS NULL AND depends_on IS NOT NULL")+ .run(Date.now(), Date.now(), id);+}+export interface FramesProgress {/** Frame edits in the render. */total: number;done: number;running: number;- /** The first frame that failed or was canceled, with its own error (the steps after it only say an earlier step didn't finish). */+ /**+ * The first frame that failed with its own error, or that someone canceled. Unset when the frames only failed+ * because an earlier step did (the cut, the extraction): that step's own error says why.+ */failed?: { label: string; error: string };}-/** A per-frame render's frame edits at a glance (the page follows the main steps, not hundreds of frames). */-export function framesProgress(batchId: string): FramesProgress {- const rows = db().prepare("SELECT status, COUNT(*) AS n FROM generations WHERE batch_id = ? AND feature = ? GROUP BY status").all(batchId, MIXED_FRAME_FEATURE) as { status: string; n: number }[];- const count = (...s: string[]) => rows.filter((r) => s.includes(r.status)).reduce((a, r) => a + r.n, 0);- const out: FramesProgress = { total: count("queued", "running", "succeeded", "failed", "canceled"), done: count("succeeded"), running: count("running") };- if (count("failed", "canceled")) {- // The first one to fail, not the frames after it that only waited for it.- const bad = db()- .prepare("SELECT status, error, request_json FROM generations WHERE batch_id = ? AND feature = ? AND status IN ('failed', 'canceled') ORDER BY (error LIKE '%earlier step%') ASC, created_at ASC LIMIT 1")- .get(batchId, MIXED_FRAME_FEATURE) as { status: string; error: string | null; request_json: string };- const label = (JSON.parse(bad.request_json) as { step?: { label?: string } }).step?.label ?? "A frame";- out.failed = { label, error: bad.status === "canceled" ? "Canceled" : (bad.error ?? "Something went wrong") };- }+/** A per-frame render's frame edits at a glance (the page follows the main steps, not hundreds of frames), by its finished video's id. */+export function framesProgress(finalId: string): FramesProgress | null {+ const rows = renderSteps(finalId);+ if (!rows) return getGeneration(finalId) ? { total: 0, done: 0, running: 0 } : null;+ const frames = rows.filter((r) => r.feature === MIXED_FRAME_FEATURE);+ const out: FramesProgress = { total: frames.length, done: frames.filter((r) => r.status === "succeeded").length, running: frames.filter((r) => r.status === "running").length };+ const waited = new Set([waitedOnFailure(false), waitedOnFailure(true)]);+ const own = frames.filter((r) => r.status === "failed" && !waited.has(r.error ?? ""));+ const stopped = frames.filter((r) => r.status === "canceled" && r.error !== DROPPED_UNUSED);+ const at = (r: StepRow) => {+ const req = (db().prepare("SELECT request_json FROM generations WHERE id = ?").get(r.id) as { request_json: string }).request_json;+ return (JSON.parse(req) as Generation["request"]).step;+ };+ const first = (list: StepRow[]) => list.map((r) => ({ r, step: at(r) })).sort((a, b) => (a.step?.index ?? 0) - (b.step?.index ?? 0))[0];+ const bad = first(own) ?? first(stopped);+ if (bad) out.failed = { label: bad.step?.label ?? "A frame", error: bad.r.status === "canceled" ? "Canceled" : (bad.r.error ?? "Something went wrong") };return out;}diff --git a/tests/mixed-media.test.ts b/tests/mixed-media.test.tsindex fa98d796..56b103b0 100644--- a/tests/mixed-media.test.ts+++ b/tests/mixed-media.test.ts@@ -10,6 +10,8 @@ import {FRAME_SEED,frameChunks,frameEditParams,+ frameJoinSize,+ frameResolution,frameSampling,fpsChoices,framesCost,@@ -226,7 +228,8 @@ describe("Mixed Media per frame on the cloud", () => {});it("asks each editor for the frame's own shape, with a fixed seed where it takes one", () => {- expect(frameEditParams("nano-banana-2", "2K", 9)).toEqual({ aspectRatio: "auto", resolution: "2K", seed: 9 });+ // JPEG back: every frame is downloaded and sent on twice (a 4K PNG is ten times the bytes).+ expect(frameEditParams("nano-banana-2", "2K", 9)).toEqual({ aspectRatio: "auto", resolution: "2K", seed: 9, extra: { output_format: "jpeg" } });expect(frameEditParams("seedream-5-flash", "1K", 9)).toEqual({ extra: { image_size: "auto_1K" } });expect(frameEditParams("seedream-5-flash", "4K", 9)).toEqual({ extra: { image_size: "auto_2K" } });});@@ -239,9 +242,11 @@ describe("Mixed Media per frame on the cloud", () => {expect(keys).toEqual(["cut", "frames1", ...Array.from({ length: 40 }, (_, i) => `f${i}`), "clip1", "final"]);const by = Object.fromEntries(plan.steps.map((s) => [s.key, s]));expect(by.cut.request).toMatchObject({ feature: "mixed-media-step", modelId: "trim-video", op: "trim", params: { startTime: 2, endTime: 7 } });- expect(by.frames1).toMatchObject({ after: ["cut"], chain: [{ slot: "video" }], request: { modelId: "extract-frames", op: "extract-frames", params: { frameInterval: 3, extra: { max_frames: 40 } } } });+ expect(by.frames1).toMatchObject({ after: ["cut"], chain: [{ slot: "video" }], request: { modelId: "extract-frames", op: "extract-frames", params: { frameInterval: 3, extra: { max_frames: 40, output_format: "jpg", quality: 95 } } } });// Frame 0 alone; then each frame with the one styled before it (lanes of 12: frame 12 looks at frame 0).- expect(by.f0).toMatchObject({ after: ["frames1"], chain: [{ slot: "images", index: 0, position: "first" }] });+ // Each knows how many frames were planned (a list far short of it fails before anything is paid).+ expect(by.f0.chain).toEqual([{ slot: "images", index: 0, of: 40, position: "first" }]);+ expect(by.f0).toMatchObject({ after: ["frames1"] });expect(by.f0.request).toMatchObject({ feature: "mixed-media-frame-step", modelId: "nano-banana-2", op: "edit", params: { aspectRatio: "auto", resolution: "1K", seed: FRAME_SEED, numOutputs: 1 } });expect(by.f0.request.prompt).toMatch(/^Redraw this image as hand-drawn/);expect(by.f1).toMatchObject({ after: ["frames1", "f0"], chain: [{ slot: "images", index: 1, position: "first" }, { slot: "images" }] });@@ -252,6 +257,9 @@ describe("Mixed Media per frame on the cloud", () => {expect(by.clip1).toMatchObject({ after: keys.filter((k) => /^f\d/.test(k)), request: { modelId: "images-to-video", op: "images-to-video", params: { fps: 8 } } });expect(by.clip1.chain).toHaveLength(40);expect(by.final).toMatchObject({ after: ["clip1", "cut"], chain: [{ slot: "video" }, { slot: "audio" }], request: { feature: "mixed-media", title: "Sketch · skate", modelId: "merge-audio-video", op: "mux" } });+ // The frame edits and the clip only feed what comes after: dropped while waiting once that can't be made.+ expect(plan.steps.filter((s) => s.request.dropWhenUnused).map((s) => s.key)).toEqual([...keys.filter((k) => /^f\d/.test(k)), "clip1"]);+ expect(by.final.request.dropWhenUnused).toBeUndefined();// Every step knows its place.expect(plan.steps.map((s) => s.request.step?.index)).toEqual(plan.steps.map((_, i) => i));expect(new Set(plan.steps.map((s) => s.request.step?.of))).toEqual(new Set([plan.steps.length]));@@ -276,6 +284,29 @@ describe("Mixed Media per frame on the cloud", () => {expect(by.film).toMatchObject({ after: ["clip1", "clip2"], chain: [{ slot: "videos" }, { slot: "videos" }], request: { feature: "mixed-media", title: "Sketch · skate", modelId: "join-clips", op: "concat" } });expect(plan.final).toBe("film");expect(by.final).toBeUndefined();+ // The result itself is never dropped; the clips are.+ expect([by.clip1.request.dropWhenUnused, by.clip2.request.dropWhenUnused, by.film.request.dropWhenUnused]).toEqual([true, true, undefined]);+ });++ it("joins clips of more than 200 frames at merge-videos' 2048 px, and draws 4K frames at 2K then", () => {+ expect(frameJoinSize({ width: 3840, height: 2160 })).toEqual({ width: 2048, height: 1152 });+ expect(frameJoinSize({ width: 1080, height: 1920 })).toEqual({ width: 1152, height: 2048 });+ // A very wide clip keeps its short side at merge-videos' 512.+ expect(frameJoinSize({ width: 4000, height: 500 })).toEqual({ width: 2048, height: 512 });+ expect(frameJoinSize({})).toBeUndefined();+ expect(frameResolution(240, "4K")).toBe("2K");+ expect(frameResolution(240, "2K")).toBe("2K");+ expect(frameResolution(200, "4K")).toBe("4K");++ const long = frames({ range: { start: 0, end: 10 }, fps: 24, resolution: "4K", sourceSize: { width: 1920, height: 1080 } });+ const by = Object.fromEntries(planMixed(long).steps.map((s) => [s.key, s]));+ expect(by.film.request.params).toEqual({ extra: { resolution: { width: 2048, height: 1152 } } });+ expect(by.f0.request.params).toMatchObject({ resolution: "2K" });+ expect(planMixedPreview({ ...long, frameUrl: "/api/files/uploads/frame.png" }).request.params).toMatchObject({ resolution: "2K" });+ // One clip: 4K as asked, nothing to join.+ const short = Object.fromEntries(planMixed(frames({ resolution: "4K", sourceSize: { width: 1920, height: 1080 } })).steps.map((s) => [s.key, s]));+ expect(short.f0.request.params).toMatchObject({ resolution: "4K" });+ expect(short.film).toBeUndefined();});it("cuts a run of more than 500 frames into windows for the extractor", () => {@@ -286,7 +317,8 @@ describe("Mixed Media per frame on the cloud", () => {expect(by.cut2.request.params).toEqual({ startTime: 21.833, endTime: 26 });expect(by.frames2).toMatchObject({ after: ["cut2"], request: { params: { frameInterval: 1, extra: { max_frames: 100 } } } });// Frame 503 is the 4th of the second window.- expect(by.f503).toMatchObject({ after: ["frames2", "f502"], chain: [{ slot: "images", index: 3, position: "first" }, { slot: "images" }] });+ expect(by.f503).toMatchObject({ after: ["frames2", "f502"], chain: [{ slot: "images", index: 3, of: 100, position: "first" }, { slot: "images" }] });+ expect(by.f499.chain?.[0]).toMatchObject({ index: 499, of: 500 });expect(by.final.after).toEqual(["film", "cut"]);});diff --git a/tests/shorts-api.test.ts b/tests/shorts-api.test.tsindex ed2e1003..cd5dbd27 100644--- a/tests/shorts-api.test.ts+++ b/tests/shorts-api.test.ts@@ -368,21 +368,24 @@ describe("Mixed Media renders", () => {expect(await settle(final.id)).toMatchObject({ status: "succeeded", feature: "mixed-media" });});- it("tries a failed render again with the same settings, from its first step", async () => {+ it("tries a failed render again with the same settings, from the step that failed (the cut is kept)", async () => {const { final, items } = await mixed.createMixed(mm({ engine: "cloud", mode: "fast", range: { start: 1, end: 4 } }) as never);// The restyle stops: the soundtrack step then fails with the generic "An earlier step didn't finish".+ await settle(items[0].id);await gens.cancelGeneration(items[1].id);expect(await settle(final.id)).toMatchObject({ status: "failed", error: "An earlier step didn't finish" });const res = await mixedRetryRoute.POST(json("POST", { id: final.id, requestId: "mm-retry-0001" }));expect(res.status).toBe(201);const again = await res.json();- expect(again.items.map((g: Generation) => g.modelId)).toEqual(["trim-video", "ltx-2-3-restyle", "merge-audio-video"]);+ // The cut finished: it isn't made (or paid for) again.+ expect(again.items.map((g: Generation) => g.modelId)).toEqual(["ltx-2-3-restyle", "merge-audio-video"]);expect(again.final.id).not.toBe(final.id);expect(again.final.batchId).not.toBe(final.batchId);- // Same settings; the chained inputs are filled again by the new steps.- expect(again.items[1].request).toMatchObject({ prompt: items[1].request.prompt, params: items[1].request.params });- expect(again.items[1].request.inputs?.video).toBeUndefined();- expect(dependsOn(again.final.id)).toEqual([again.items[1].id, again.items[0].id]);+ // Same settings; the chained inputs are filled again, from the kept cut.+ expect(again.items[0].request).toMatchObject({ prompt: items[1].request.prompt, params: items[1].request.params });+ expect(again.items[0].request.inputs?.video).toBeUndefined();+ expect(dependsOn(again.items[0].id)).toEqual([items[0].id]);+ expect(dependsOn(again.final.id)).toEqual([again.items[0].id, items[0].id]);expect(await settle(again.final.id)).toMatchObject({ status: "succeeded" });const gone = await mixedRetryRoute.POST(json("POST", { id: "nope" }));expect(gone.status).toBe(404);@@ -420,9 +423,15 @@ describe("Mixed Media renders", () => {// 75 frames × $0.08, plus the cut, the extraction and the assembly (fal compute, about free).expect(est.costUsd).toBeGreaterThanOrEqual(6);expect(est.costUsd).toBeLessThan(6.01);- const big = await mixed.estimateMixed(mm({ engine: "cloud", source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 24 }, range: { start: 0, end: 10 }, fps: 24, resolution: "4K" }) as never);- expect(big).toMatchObject({ frames: 240, fps: 24, perFrameUsd: 0.16 });- expect(big.costUsd).toBeGreaterThanOrEqual(38.4);+ const big = await mixed.estimateMixed(mm({ engine: "cloud", source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 24 }, range: { start: 0, end: 5 }, fps: 24, resolution: "4K" }) as never);+ expect(big).toMatchObject({ frames: 120, fps: 24, perFrameUsd: 0.16 });+ expect(big.costUsd).toBeGreaterThanOrEqual(19.2);+ // Over 200 frames the clips are joined at up to 2048 px: 4K frames would be paid for and shrunk, so they are drawn at 2K.+ const joined = await mixed.estimateMixed(mm({ engine: "cloud", source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 24 }, range: { start: 0, end: 10 }, fps: 24, resolution: "4K" }) as never);+ expect(joined).toMatchObject({ frames: 240, perFrameUsd: 0.12 });+ expect(joined.costUsd).toBeGreaterThanOrEqual(28.8);+ expect(joined.costUsd).toBeLessThan(28.9);+ expect(joined.notes).toContain("Over 200 frames are made as clips and joined at up to 2048 px, so frames are drawn at 2K");const flash = await mixed.estimateMixed(mm({ engine: "cloud", modelId: "seedream-5-flash", source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 24 }, range: { start: 0, end: 5 }, fps: 8 }) as never);expect(flash).toMatchObject({ frames: 40, perFrameUsd: 0.027 });expect(flash.notes.join(" ")).toMatch(/Seedream 5\.0 Flash takes no seed/);@@ -435,6 +444,16 @@ describe("Mixed Media renders", () => {const res = await mixedEstimateRoute.POST(json("POST", mm({ engine: "cloud", source: { url: "/api/files/placeholder.mp4", duration: 12 } })));expect(res.status).toBe(422);expect((await res.json()).error).toMatch(/pick Fast/);+ // A caller from before Per frame that names a Fast model gets Fast, as before; a model of the other mode is refused, not swapped.+ const legacy = await mixed.estimateMixed(mm({ engine: "cloud", modelId: "ltx-2-3-restyle", source: { url: "/api/files/placeholder.mp4", duration: 12 }, range: { start: 0, end: 5 } }) as never);+ expect(legacy.mode).toBe("fast");+ expect(legacy.perFrameUsd).toBeUndefined();+ const wrong = await mixedEstimateRoute.POST(json("POST", mm({ engine: "cloud", mode: "frames", modelId: "ltx-2-3-restyle", source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 24 } })));+ expect(wrong.status).toBe(422);+ expect((await wrong.json()).error).toBe("LTX 2.3 Reference Restyle restyles the clip as video — pick Fast for it, or Nano Banana 2 or Seedream 5.0 Flash to redraw each frame");+ const still = await mixedEstimateRoute.POST(json("POST", mm({ engine: "cloud", mode: "fast", modelId: "nano-banana-2", source: { url: "/api/files/placeholder.mp4", duration: 12, fps: 24 } })));+ expect(still.status).toBe(422);+ expect((await still.json()).error).toMatch(/^Nano Banana 2 redraws single frames — pick Per frame/);} finally {setSetting("falKey", "");}@@ -464,7 +483,32 @@ describe("Mixed Media renders", () => {expect(redo.map((g) => g.request.chainFilled)).toEqual([undefined, undefined, undefined, undefined]);expect(await settle(again.final.id)).toMatchObject({ status: "succeeded" });expect(gens.getGeneration(redo[3].id)!.request.inputs?.images).toHaveLength(2);- expect(mixed.framesProgress(again.final.batchId)).toEqual({ total: 4, done: 4, running: 0 });+ expect(mixed.framesProgress(again.final.id)).toEqual({ total: 4, done: 4, running: 0 });++ // A frame failed after the others were paid for: Try again redraws that frame and the ones after it in its+ // lane (they matched it), keeping the rest, the cut and the extraction.+ const old = gens.listGenerations({ batchId: again.final.batchId, features: ["mixed-media-frame-step"], limit: 50 }).sort((a, b) => a.request.step!.index - b.request.step!.index);+ const steps = gens.listGenerations({ batchId: again.final.batchId, features: ["mixed-media-step"], limit: 50 });+ const clipStep = steps.find((g) => g.op === "images-to-video")!;+ const fail = (id: string, error: string) => db().prepare("UPDATE generations SET status = 'failed', error = ? WHERE id = ?").run(error, id);+ fail(old[2].id, "Refused by the safety filter");+ fail(old[3].id, "An earlier step didn't finish");+ fail(clipStep.id, "An earlier step didn't finish");+ fail(again.final.id, "An earlier step didn't finish");+ expect(mixed.framesProgress(again.final.id)).toMatchObject({ total: 4, done: 2, failed: { label: "Frame 3 of 4", error: "Refused by the safety filter" } });+ const third = await (await mixedRetryRoute.POST(json("POST", { id: again.final.id, requestId: "mm-frames-retry2" }))).json();+ expect(third.frames).toBe(2);+ expect(third.items.map((g: Generation) => g.op)).toEqual(["images-to-video", "mux"]);+ const redrawn = gens.listGenerations({ batchId: third.final.batchId, features: ["mixed-media-frame-step"], limit: 50 }).sort((a, b) => a.request.step!.index - b.request.step!.index);+ expect(redrawn.map((g) => g.request.step?.label)).toEqual(["Frame 3 of 4", "Frame 4 of 4"]);+ // Frame 3 waits on the kept extraction and the kept frame 2.+ expect(dependsOn(redrawn[0].id)).toEqual([...dependsOn(old[2].id).slice(0, 1), old[1].id]);+ expect(await settle(third.final.id)).toMatchObject({ status: "succeeded" });+ const rebuilt = gens.getGeneration(third.items[0].id)!.request.inputs?.images;+ expect(rebuilt?.slice(0, 2)).toEqual([old[0].outputs[0].url, old[1].outputs[0].url]);+ expect(rebuilt?.slice(2)).toEqual(redrawn.map((g) => gens.getGeneration(g.id)!.outputs[0].url));+ // Progress follows the render across tries: all four frames.+ expect(mixed.framesProgress(third.final.id)).toEqual({ total: 4, done: 4, running: 0 });});it("says which frame failed and why, not just that an earlier step didn't finish", async () => {@@ -472,9 +516,36 @@ describe("Mixed Media renders", () => {const edits = gens.listGenerations({ batchId: final.batchId!, features: ["mixed-media-frame-step"], limit: 50 }).sort((a, b) => a.request.step!.index - b.request.step!.index);await gens.cancelGeneration(edits[1].id);expect(await settle(final.id)).toMatchObject({ status: "failed" });- const res = await mixedProgressRoute.GET(new Request(`http://x/api/mixed-media/progress?batch=${final.batchId}`));+ const res = await mixedProgressRoute.GET(new Request(`http://x/api/mixed-media/progress?id=${final.id}`));const progress = await res.json();expect(progress).toMatchObject({ total: 4, failed: { label: "Frame 2 of 4", error: "Canceled" } });expect((await mixedProgressRoute.GET(new Request("http://x/api/mixed-media/progress"))).status).toBe(400);+ expect((await mixedProgressRoute.GET(new Request("http://x/api/mixed-media/progress?id=nope"))).status).toBe(404);+ });++ it("stops the frames still waiting when one fails, so the other lanes aren't paid for", async () => {+ // 4 s at 4 FPS: 16 frames in two lanes (frames 1–12 and 13–16).+ const { final, frames } = await mixed.createMixed(mm({ engine: "cloud", range: { start: 1, end: 5 }, fps: 4 }) as never);+ expect(frames).toBe(16);+ const edits = gens.listGenerations({ batchId: final.batchId!, features: ["mixed-media-frame-step"], limit: 50 }).sort((a, b) => a.request.step!.index - b.request.step!.index);+ db().prepare("UPDATE generations SET status = 'failed', error = 'Refused by the safety filter', completed_at = ? WHERE id = ?").run(Date.now(), edits[13].id);+ expect(await settle(final.id)).toMatchObject({ status: "failed" });+ for (const g of edits) await settle(g.id);+ const rows = edits.map((g) => db().prepare("SELECT status, error, external_id FROM generations WHERE id = ?").get(g.id) as { status: string; error: string | null; external_id: string | null });+ // None of the other frames reached a provider: they were waiting for the cut and the extraction.+ expect(rows.filter((r) => r.external_id)).toEqual([]);+ expect(rows.filter((r) => r.status === "canceled").every((r) => r.error === gens.DROPPED_UNUSED)).toBe(true);+ expect(rows.filter((r) => r.status === "canceled")).toHaveLength(14);+ expect(mixed.framesProgress(final.id)).toMatchObject({ total: 16, done: 0, failed: { label: "Frame 14 of 16", error: "Refused by the safety filter" } });+ });++ it("names the step that failed when no frame did (the extraction), not frame 1", async () => {+ const { final, items } = await mixed.createMixed(mm({ engine: "cloud", range: { start: 1, end: 2 }, fps: 4 }) as never);+ const extract = items.find((g) => g.op === "extract-frames")!;+ await gens.cancelGeneration(extract.id);+ expect(await settle(final.id)).toMatchObject({ status: "failed" });+ const progress = mixed.framesProgress(final.id)!;+ expect(progress.total).toBe(4);+ expect(progress.failed).toBeUndefined();});});