Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: finish a video draft on its declared delivery model (#3696)

[._.]/ Adam Eivy90064e148e2e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 72f209e2f9..f52f000ebe 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,8 @@
- **Three.js Models now tells you the truth about rigging.** Every generated model was described as "animation-ready", including characters — but the spec holds a parts hierarchy and sockets, never a skeleton, a bind pose, or a deformation contract, and PortOS does no skinning at all. A character spec can now declare a bounded, optional **articulation graph**: stable joint ids, exactly one root, each joint naming a parent declared before it (so a cycle or a dangling parent is unrepresentable rather than merely unlikely), a named pivot socket per joint, and an explicit list of parts that are *carried* rather than articulated. An impossible graph is rejected outright at generation — two roots, a duplicate joint id, a joint pointed at a part or socket that does not exist, one part driven by two joints, or a part declared as both an attachment and a joint — and only a graph that passed reaches the exported factory's runtime metadata. Alongside it the record now stores a rig-readiness report, and it is honest in both directions: a model with no graph reads **static assembly** with the reason attached rather than a silent pass, and a graph that validates but rigs into nothing (a lone root, or child joints with no pivot axis) is reported the same way. The detail page shows the verdict, the joint/pivot/attachment counts and the reasons; the preview badges static versus articulation-ready and names the joint driving whichever part you click. The generation prompt asks for the contract only when the subject could be a character — a vehicle, weapon, architecture or device family, or a refinement of a spec already classified as an object, leaves the prompt exactly as it was. Models generated before this shipped have no graph and no report; they read as static and unevaluated, never as rigged. Deliberately out of scope: automatic skinning, external rigging models, and generated GLB assets.
+- Video Gen **can now finish a draft**. A fast, low-step model is the right way to find a shot, but the only way to then render it properly was Remix — which reuses the settings you had, so the delivery render came back as a *different* composition unless you noticed the seed and moved the model yourself. Video cards in Recent renders now show a **Finish** button that reloads the draft's prompt, negative prompt, size, frames, fps and — critically — the exact seed it actually rendered with, then switches the model to the full-quality sibling the registry declares for it and clears the draft's 4-step sampler so the delivery model uses its own. Nothing starts on its own: Finish only fills in the form, and you press Generate. The button appears only where it can honestly deliver the same shot — the draft model must declare a delivery pair (same weights, same runtime, differing only in step budget, not merely a similar name), that model must be installed here, and the render must be reproducible from the record alone. Image-, keyframe-, extend-, audio- and reference-conditioned drafts don't offer it, because their conditioning input isn't something PortOS keeps a durable copy of; renders made before this release don't either, since their records can't say for certain what steered them. Every render from now on records the seed it resolved to (random seeds included) and an inventory of what conditioned it — kinds only, never upload paths.
+
- Series Pipeline **Autonomous mode** gains an **"Unlock everything this series owns first"** option. A locked arc, volume, issue stage, or canon entry makes the corresponding fix path throw or silently skip, so a run would surface an editorial finding and then pause on a problem it was never allowed to resolve — leaving you to hunt down every lock toggle by hand before re-running. With the option on, the run's first step clears the arc freeze, the per-field arc locks, every volume lock and every issue stage lock, then reports exactly what it cleared and what it deliberately left frozen. Two boundaries are hard. **Shared records stay locked:** the universe's canon and world fields are only unlocked when this is the universe's *only* series — a stamp saying this series introduced a character records provenance, not exclusive use, and once a sibling series shares the universe that character may be one the sibling is built on. **Nothing is ever deleted:** the pass clears lock bits only, so characters, objects and volumes can be rewritten in full but stay in the Universe and the Catalog. Because unlocking the volume locks also removes the only thing that used to stop a regenerated arc from *dropping* a volume, all three arc-rewriting paths (arc generation, arc auto-resolve, and the foundation gate's structure fix) now re-insert any volume the rewrite omitted, and existing volumes win the per-series volume cap so a large regeneration can't push them out of the list. Consent is per run and per series: it is never saved as a default, the box clears itself once you launch, and it resets when you switch series — so a scheduled, repeat, or other-series run can't inherit lock-clearing. The dry-run plan names the step, with a count of the locks it would clear, before you commit.
- Series Pipeline **Autonomous mode gains an observing orchestrator** — the continuous, self-dispatching sibling of *Improve the pipeline itself*. With the new *Observing orchestrator* toggle on, the run watches its own telemetry step by step: when a step's fresh signals say the automation misbehaved (a retried or escalated child runner, a skipped step, an editorial check that threw, a filed gap), it spends one bounded diagnosis call asking what in PortOS should change — a missing or misordered step, an ineffective verify→resolve loop, a broken check or stage prompt, a misconfigured gate, even a missing autopilot option — and **dispatches the fix immediately** as an auto-approved CoS task that works in a worktree, opens a PR, and merges through the review loop with no human gate, so a defect noticed at step 4 is being fixed while steps 5–16 still run. Enabling the toggle is the explicit consent for those unattended changes; the guards are structural: execute-mode only, every pass billed against and gated on the daily cos budget, at most three mid-run passes plus one terminal pass per run, a higher confidence bar than the approval-gated post-mortem (which it supersedes at the run's end), and repeat diagnoses collapsing onto one open task. Live progress frames show each observation and dispatch, and the run's status banner lists everything that was filed. Off by default; scheduled runs inherit whatever you saved.
diff --git a/client/src/components/media/MediaCard.jsx b/client/src/components/media/MediaCard.jsx
index 6b6d533652..98d5256dd9 100644
--- a/client/src/components/media/MediaCard.jsx
+++ b/client/src/components/media/MediaCard.jsx
@@ -10,7 +10,10 @@ import { loraDisplayName } from './normalize';
// the Image Gen page's recent gallery, the Video Gen page's recent renders,
// and the Media History tab. Action visibility is opt-in — pass only the
// callbacks you want rendered. Image-only actions (remix, send-to-video) and
-// video-only actions (continue) are auto-hidden when the kind doesn't match.
+// video-only actions (continue, finish) are auto-hidden when the kind doesn't
+// match. `onFinish` is passed only for a draft the caller already resolved a
+// delivery model for (see client/src/lib/videoFinish.js) — an image-conditioned
+// or legacy record gets no Finish button rather than a disabled one.
export default function MediaCard({
item,
onPreview,
@@ -20,6 +23,8 @@ export default function MediaCard({
onSendToVideo,
onSendTo3d,
onContinue,
+ onFinish,
+ finishTitle = 'Re-render this draft on its delivery model',
onUpscale,
onDelete,
onToggleHidden,
@@ -200,6 +205,16 @@ export default function MediaCard({
<ImageIcon className="w-3 h-3 shrink-0" /> <span className="truncate">Continue</span>
</button>
)}
+ {isVideo && onFinish && (
+ <button
+ type="button"
+ onClick={() => onFinish(item)}
+ className="shrink-0 px-1.5 py-1 bg-port-success/20 hover:bg-port-success/40 text-port-success text-[10px] rounded flex items-center justify-center gap-1"
+ title={finishTitle}
+ >
+ <Sparkles className="w-3 h-3 shrink-0" /> <span className="truncate">Finish</span>
+ </button>
+ )}
{isVideo && onUpscale && !item.upscaledFrom && (
<button
type="button"
diff --git a/client/src/components/videoGen/VideoGenGallery.jsx b/client/src/components/videoGen/VideoGenGallery.jsx
index 4ed249cdef..6e4504f01d 100644
--- a/client/src/components/videoGen/VideoGenGallery.jsx
+++ b/client/src/components/videoGen/VideoGenGallery.jsx
@@ -11,7 +11,21 @@ export default function VideoGenGallery({
galleryVisible, galleryHidden, favoritesOnly, showHidden,
onToggleFavorites, onToggleShowHidden,
onPreview, onContinue, onUpscale, onDelete, onToggleHidden, getCardProps,
+ finishTargetFor, onFinish,
}) {
+ // Finish (#3696) is offered per-card, and only when the stored record is a
+ // fully reproducible text-to-video draft whose declared delivery model is
+ // available here — `finishTargetFor` returns null otherwise and the button
+ // is simply absent. Clicking only prefills the form; the user still presses
+ // Generate, so no render is kicked off from the gallery.
+ const finishProps = (v) => {
+ const target = finishTargetFor?.(v) || null;
+ if (!target) return {};
+ return {
+ onFinish: () => onFinish?.(v, target),
+ finishTitle: `Re-render this draft on ${target.name || target.id} (same prompt and seed, delivery quality)`,
+ };
+ };
return (
<>
{(galleryVisible.length > 0 || favoritesOnly) && (
@@ -37,6 +51,7 @@ export default function VideoGenGallery({
item={item}
onPreview={() => onPreview(item)}
onContinue={() => onContinue(v)}
+ {...finishProps(v)}
onUpscale={() => onUpscale(v)}
onDelete={() => onDelete(v)}
onToggleHidden={() => onToggleHidden(v)}
diff --git a/client/src/components/videoGen/VideoGenGallery.test.jsx b/client/src/components/videoGen/VideoGenGallery.test.jsx
new file mode 100644
index 0000000000..0b28ef5db5
--- /dev/null
+++ b/client/src/components/videoGen/VideoGenGallery.test.jsx
@@ -0,0 +1,114 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+import VideoGenGallery from './VideoGenGallery';
+import { finishTargetForRecord } from '../../lib/videoFinish';
+
+vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));
+
+const DRAFT_MODEL = { id: 'draft_model', name: 'Draft (4-step)', finishModelId: 'delivery_model' };
+const DELIVERY_MODEL = { id: 'delivery_model', name: 'Delivery (20-step)' };
+
+const videoRecord = (over = {}) => ({
+ id: 'rec-1',
+ filename: 'rec-1.mp4',
+ thumbnail: 'rec-1.jpg',
+ prompt: 'a quiet street at dusk',
+ modelId: 'draft_model',
+ seed: 424242,
+ mode: 'text',
+ renderInputsVersion: 1,
+ conditioning: [],
+ createdAt: '2026-01-01T00:00:00.000Z',
+ ...over,
+});
+
+const renderGallery = ({ records, models, onFinish = vi.fn() }) => {
+ render(
+ <MemoryRouter>
+ <VideoGenGallery
+ galleryVisible={records}
+ galleryHidden={[]}
+ favoritesOnly={false}
+ showHidden={false}
+ onToggleFavorites={vi.fn()}
+ onToggleShowHidden={vi.fn()}
+ onPreview={vi.fn()}
+ onContinue={vi.fn()}
+ onUpscale={vi.fn()}
+ onDelete={vi.fn()}
+ onToggleHidden={vi.fn()}
+ getCardProps={() => ({ showCollectionMenu: false, showMoodBoardMenu: false })}
+ finishTargetFor={(raw) => finishTargetForRecord(raw, models)}
+ onFinish={onFinish}
+ />
+ </MemoryRouter>,
+ );
+ return { onFinish };
+};
+
+describe('VideoGenGallery — Finish action (#3696)', () => {
+ it('offers Finish for a reproducible text-to-video draft with an available delivery model', () => {
+ renderGallery({ records: [videoRecord()], models: [DRAFT_MODEL, DELIVERY_MODEL] });
+ expect(screen.getByRole('button', { name: /Finish/i })).toBeInTheDocument();
+ });
+
+ it('names the delivery model in the affordance so the user knows what they are switching to', () => {
+ renderGallery({ records: [videoRecord()], models: [DRAFT_MODEL, DELIVERY_MODEL] });
+ expect(screen.getByRole('button', { name: /Finish/i })).toHaveAttribute(
+ 'title',
+ expect.stringContaining('Delivery (20-step)'),
+ );
+ });
+
+ it('hands the raw record plus the resolved target to the handler — and starts nothing itself', () => {
+ const { onFinish } = renderGallery({ records: [videoRecord()], models: [DRAFT_MODEL, DELIVERY_MODEL] });
+ fireEvent.click(screen.getByRole('button', { name: /Finish/i }));
+ expect(onFinish).toHaveBeenCalledTimes(1);
+ const [raw, target] = onFinish.mock.calls[0];
+ expect(raw.id).toBe('rec-1');
+ expect(target.id).toBe('delivery_model');
+ });
+
+ it('omits Finish for an image-conditioned draft', () => {
+ renderGallery({
+ records: [videoRecord({ mode: 'image', conditioning: ['image'] })],
+ models: [DRAFT_MODEL, DELIVERY_MODEL],
+ });
+ expect(screen.queryByRole('button', { name: /Finish/i })).toBeNull();
+ });
+
+ it('omits Finish for a legacy record with no durable re-render inputs', () => {
+ const { renderInputsVersion, conditioning, ...legacy } = videoRecord();
+ renderGallery({ records: [legacy], models: [DRAFT_MODEL, DELIVERY_MODEL] });
+ expect(screen.queryByRole('button', { name: /Finish/i })).toBeNull();
+ });
+
+ it('omits Finish when the delivery model is not installed here', () => {
+ renderGallery({ records: [videoRecord()], models: [DRAFT_MODEL] });
+ expect(screen.queryByRole('button', { name: /Finish/i })).toBeNull();
+ });
+
+ it('renders the gallery unchanged when no finish wiring is supplied at all', () => {
+ render(
+ <MemoryRouter>
+ <VideoGenGallery
+ galleryVisible={[videoRecord()]}
+ galleryHidden={[]}
+ favoritesOnly={false}
+ showHidden={false}
+ onToggleFavorites={vi.fn()}
+ onToggleShowHidden={vi.fn()}
+ onPreview={vi.fn()}
+ onContinue={vi.fn()}
+ onUpscale={vi.fn()}
+ onDelete={vi.fn()}
+ onToggleHidden={vi.fn()}
+ getCardProps={() => ({ showCollectionMenu: false, showMoodBoardMenu: false })}
+ />
+ </MemoryRouter>,
+ );
+ expect(screen.queryByRole('button', { name: /Finish/i })).toBeNull();
+ expect(screen.getByRole('button', { name: /Continue/i })).toBeInTheDocument();
+ });
+});
diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.js
index 34879b9296..869fa9470a 100644
--- a/client/src/hooks/useVideoGenForm.js
+++ b/client/src/hooks/useVideoGenForm.js
@@ -846,6 +846,24 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
}
};
+ // Finish a draft (#3696): restore the draft's provenance exactly as Remix
+ // does, then switch to its declared delivery model. Steps/guidance are reset
+ // to the empty-string sentinel ("use the model's own defaults") rather than
+ // carried over — the draft's 4-step / guidance-1.0 sampler is the whole thing
+ // Finish is meant to leave behind, and copying it to the delivery model would
+ // reproduce the draft at full cost. The seed IS carried (applyRemix restores
+ // it), which is what makes the finished render the same composition.
+ //
+ // This only fills the form. Nothing is submitted — the user still has to
+ // press Generate, so no provider call fires off a gallery click.
+ const applyFinish = (item, deliveryModelId) => {
+ if (!item || !deliveryModelId) return;
+ applyRemix(item);
+ setModelId(deliveryModelId);
+ setSteps('');
+ setGuidanceScale('');
+ };
+
// Repopulate the form from an in-flight (or queued) render restored via
// /active, so a page reload doesn't lose what the running job is rendering.
// The page owns the SSE re-attach; this only replays the params into state.
@@ -1137,7 +1155,7 @@ export function useVideoGenForm({ models, status, availableLoras, grokEnabled })
icStrength, setIcStrength,
icSkipStage2, setIcSkipStage2,
// Prefill + submit
- applyRemix, applyResumedParams, buildGeneratePayload,
+ applyRemix, applyFinish, applyResumedParams, buildGeneratePayload,
};
}
diff --git a/client/src/hooks/useVideoGenForm.test.jsx b/client/src/hooks/useVideoGenForm.test.jsx
index 65c56c1803..074ee02254 100644
--- a/client/src/hooks/useVideoGenForm.test.jsx
+++ b/client/src/hooks/useVideoGenForm.test.jsx
@@ -420,6 +420,37 @@ describe('useVideoGenForm', () => {
expect(result.current.guidanceScale).toBe('');
});
+ it('applyFinish keeps the draft seed but drops its sampler for the delivery model (#3696)', async () => {
+ const { result } = render();
+ act(() => result.current.applyFinish({
+ prompt: 'a quiet street at dusk', negativePrompt: 'blurry', modelId: MLX.id,
+ width: 768, height: 512, numFrames: 49, fps: 24, seed: 424242,
+ steps: 4, guidanceScale: 1, mode: 'text',
+ }, LTX2.id));
+
+ // The whole point: same prompt + same seed, rendered on the delivery model
+ // at ITS defaults ('' = "use the model's own steps/guidance") rather than
+ // the draft's 4-step / guidance-1.0 sampler.
+ expect(result.current.modelId).toBe(LTX2.id);
+ expect(result.current.seed).toBe('424242');
+ expect(result.current.prompt).toBe('a quiet street at dusk');
+ expect(result.current.negativePrompt).toBe('blurry');
+ expect(result.current.numFrames).toBe(49);
+ expect(result.current.steps).toBe('');
+ expect(result.current.guidanceScale).toBe('');
+ expect(result.current.mode).toBe('text');
+ });
+
+ it('applyFinish is inert without a record or a delivery model — it never starts a render', async () => {
+ const { result } = render();
+ await waitFor(() => expect(result.current.modelId).toBe(MLX.id));
+ act(() => { result.current.setPrompt('untouched'); });
+ act(() => result.current.applyFinish(null, LTX2.id));
+ act(() => result.current.applyFinish({ prompt: 'x', modelId: MLX.id }, null));
+ expect(result.current.prompt).toBe('untouched');
+ expect(result.current.modelId).toBe(MLX.id);
+ });
+
it('applyResumedParams restores an in-flight grok job to the grok backend', async () => {
const { result } = render({ grokEnabled: true });
act(() => result.current.applyResumedParams({
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 5cced3e638..73e35badf2 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -63,6 +63,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `imageTo3dReasons.js` | Client mirror of the image-to-3D unavailable-reason labels in `server/services/imageTo3d/targets.js`: `UNAVAILABLE_REASONS` (reason code → user-facing label), `UNAVAILABLE_REASON_FALLBACK`, and `unavailableReasonLabel(code, fallback?)`. Use this anywhere a target's `unavailableReason` is rendered — never re-declare the codes. Parity + code coverage enforced by `server/services/imageTo3d/unavailableReasons.parity.test.js`. |
| `importerDeepLink.js` | The Importer deep-link contract both ways: `buildImporterLink({ universeId, seriesId, seriesName })` builds the `/importer?…` URL a Series Pipeline page navigates to; `resolveImporterDeepLink(...)` reads those params back into the universe + series names the importer matches on. |
| `muscriptorModels.js` | `MUSCRIPTOR_MODELS` (audio → MIDI size tiers `small`/`medium`/`large`) + `DEFAULT_MUSCRIPTOR_MODEL`. Single source consumed by the transcribe `<select>`s in `MusicVideo.jsx` and `ReferenceAnalysis.jsx`. Mirrors the server's `MUSCRIPTOR_MODELS` in `server/services/audioMidiTranscription.js`. |
+| `videoFinish.js` | Finish-a-draft gate (#3696). `isReproducibleTextToVideo(record)` is true only for a single text-to-video render whose history record already carries everything a re-render needs — `renderInputsVersion` (the positive marker that its conditioning inventory is trustworthy, so legacy records degrade to not-finishable rather than reading as unconditioned), an empty `conditioning` array, a resolved seed, a real prompt, and no stitched/chained/upscaled provenance. `finishTargetForRecord(record, models)` additionally resolves the draft model's server-declared `finishModelId` against the models this install can actually run, returning the delivery model entry or `null`. Mirrors `finishTargetForModel` in `server/lib/videoFinishProfiles.js`; the pair table itself stays server-side. |
| `videoGenParams.js` | Pure VideoGen param helpers: `FRAME_OPTIONS`/`FPS_OPTIONS`/`VIDEO_EDGE_BOUNDS`/`MAX_CHUNKS`/`CHUNK_OPTIONS` constants, `videoModelMemoryGb()` (model memory footprint), `computeFflfSafeFrames()` (FFLF/ltx2 pixel-budget back-solve, mirrors `server/services/videoGen/local.js`), and `isModelAllowedForMode()` (a2v + IC-remix → ltx2 gate). Also mirrors the IC-LoRA remix registry (`IC_LORA_MODES`/`IC_LORA_MODE_VALUES`/`isIcLoraMode()`/`icLoraSpecForMode()`/`icResolutionIssue()`) from `server/lib/icLoraWeights.js` so the form validates a reference render pre-submit — pinned by `server/lib/icLoraWeights.parity.test.js`. |
| `videoGenResolutions.js` | Shared resolution presets for video generation (companion to image side; LTX-2 latent-friendly sizes) + `snapAspectToImage()` to pick the closest-aspect preset for an I2V source. |
| `videoTilingOptions.js` | `VIDEO_TILING_OPTIONS` (the `<select>` rows) + `VIDEO_TILING_ENUM_SET` (the value-only Set). Single source consumed by `VideoGen.jsx` and the Remix URL builder in `useMediaPreviewActions`. Mirrors the server's `z.enum` in `server/routes/videoGen.js`. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index dec15f00e4..7aed531839 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -44,6 +44,7 @@ export * from './reviewerModels.js';
export * from './reviewerPins.js';
export * from './runnerFamilies.js';
export * from './slashdoCatalog.js';
+export * from './videoFinish.js';
export * from './videoGenParams.js';
export * from './videoGenResolutions.js';
export * from './videoTilingOptions.js';
diff --git a/client/src/lib/videoFinish.js b/client/src/lib/videoFinish.js
new file mode 100644
index 0000000000..2985bb454f
--- /dev/null
+++ b/client/src/lib/videoFinish.js
@@ -0,0 +1,67 @@
+/**
+ * Finish a video draft (#3696) — decide whether one stored render can be
+ * re-rendered on its declared delivery model, and which model that is.
+ *
+ * A draft is finishable only when the record alone is enough to reproduce the
+ * same composition at higher quality. That means all of:
+ * - it was written by the finish-aware writer (`renderInputsVersion`), so its
+ * conditioning inventory can be trusted. Legacy records predate the field
+ * and degrade to "not finishable" rather than being assumed unconditioned —
+ * absent must never read as "empty" here.
+ * - it used NO conditioning inputs (`conditioning` is an empty array) and is
+ * a plain text-to-video render. Image / FFLF / extend / a2v / IC drafts
+ * have no durable reference to re-render from, so Finish is not offered for
+ * them at all (deliberate first slice — see issue #3696).
+ * - it is a single render, not a stitched/chained/upscaled derivative.
+ * - it carries the resolved seed it actually rendered with.
+ * - its model declares a `finishModelId` AND that delivery model is present
+ * in the model list this install can actually run.
+ *
+ * Mirrors `finishTargetForModel` in `server/lib/videoFinishProfiles.js`; the
+ * registry edges themselves are server-declared and ride to the client on the
+ * `/api/video-gen/status` model entries, so there is no client-side pair table
+ * to drift.
+ */
+
+// Mirror of RENDER_INPUTS_VERSION in server/services/videoGen/generateVideoHelpers.js.
+export const MIN_RENDER_INPUTS_VERSION = 1;
+
+const hasResolvedSeed = (seed) => seed != null && seed !== '' && Number.isFinite(Number(seed));
+
+const hasPrompt = (prompt) => typeof prompt === 'string' && prompt.trim() !== '' && prompt !== '(no prompt)';
+
+/**
+ * True when `record` is a fully reproducible text-to-video render — i.e. the
+ * record itself carries every input the re-render needs. Independent of model
+ * availability, so callers can explain "no compatible model" separately from
+ * "this draft isn't reproducible".
+ *
+ * @param {object|null|undefined} record - RAW video history record
+ */
+export const isReproducibleTextToVideo = (record) => {
+ if (!record || typeof record !== 'object') return false;
+ if (!(Number(record.renderInputsVersion) >= MIN_RENDER_INPUTS_VERSION)) return false;
+ if (!Array.isArray(record.conditioning) || record.conditioning.length > 0) return false;
+ if (record.mode !== 'text') return false;
+ if (!hasResolvedSeed(record.seed)) return false;
+ if (!hasPrompt(record.prompt)) return false;
+ if (record.chainedFrom || record.stitchedFrom || record.upscaledFrom) return false;
+ return true;
+};
+
+/**
+ * Resolve the delivery model a stored draft finishes into, or `null` when the
+ * draft isn't finishable on this install.
+ *
+ * @param {object|null|undefined} record - RAW video history record
+ * @param {Array<object>} models - video model entries from the status payload
+ * @returns {object|null} the delivery model entry
+ */
+export const finishTargetForRecord = (record, models) => {
+ if (!Array.isArray(models) || models.length === 0) return null;
+ if (!isReproducibleTextToVideo(record)) return null;
+ const draftModel = models.find((m) => m?.id === record.modelId);
+ const targetId = draftModel?.finishModelId;
+ if (typeof targetId !== 'string' || targetId.length === 0) return null;
+ return models.find((m) => m?.id === targetId) || null;
+};
diff --git a/client/src/lib/videoFinish.test.js b/client/src/lib/videoFinish.test.js
new file mode 100644
index 0000000000..da8d2f2e5e
--- /dev/null
+++ b/client/src/lib/videoFinish.test.js
@@ -0,0 +1,111 @@
+import { describe, it, expect } from 'vitest';
+import { isReproducibleTextToVideo, finishTargetForRecord, MIN_RENDER_INPUTS_VERSION } from './videoFinish.js';
+
+const DRAFT_MODEL = { id: 'draft_model', name: 'Draft (4-step)', finishModelId: 'delivery_model' };
+const DELIVERY_MODEL = { id: 'delivery_model', name: 'Delivery (20-step)' };
+const MODELS = [DRAFT_MODEL, DELIVERY_MODEL];
+
+// A record as the finish-aware writer stamps it for a plain text-to-video run.
+const record = (over = {}) => ({
+ id: 'rec-1',
+ prompt: 'a quiet street at dusk',
+ modelId: 'draft_model',
+ seed: 424242,
+ mode: 'text',
+ renderInputsVersion: MIN_RENDER_INPUTS_VERSION,
+ conditioning: [],
+ ...over,
+});
+
+describe('isReproducibleTextToVideo', () => {
+ it('accepts a fully reproducible text-to-video record', () => {
+ expect(isReproducibleTextToVideo(record())).toBe(true);
+ expect(isReproducibleTextToVideo(record({ seed: 0 }))).toBe(true);
+ });
+
+ it('rejects a legacy record that predates the durable-inputs fields', () => {
+ // The dangerous case: absent `conditioning` must NOT read as "no
+ // conditioning" — a legacy image-to-video render looks identical here.
+ const { renderInputsVersion, conditioning, ...legacy } = record();
+ expect(isReproducibleTextToVideo(legacy)).toBe(false);
+ });
+
+ it('rejects an incomplete record that has the marker but no inventory', () => {
+ expect(isReproducibleTextToVideo(record({ conditioning: undefined }))).toBe(false);
+ expect(isReproducibleTextToVideo(record({ conditioning: null }))).toBe(false);
+ });
+
+ it('rejects an image-conditioned draft', () => {
+ expect(isReproducibleTextToVideo(record({ mode: 'image', conditioning: ['image'] }))).toBe(false);
+ });
+
+ it('rejects a record whose mode reads text but which was audio-conditioned', () => {
+ expect(isReproducibleTextToVideo(record({ conditioning: ['audio'] }))).toBe(false);
+ });
+
+ it('rejects the non-text modes wholesale', () => {
+ for (const mode of ['image', 'fflf', 'extend', 'a2v', 'ic-control', 'grok']) {
+ expect(isReproducibleTextToVideo(record({ mode }))).toBe(false);
+ }
+ });
+
+ it('rejects a record with no resolved seed', () => {
+ expect(isReproducibleTextToVideo(record({ seed: undefined }))).toBe(false);
+ expect(isReproducibleTextToVideo(record({ seed: null }))).toBe(false);
+ expect(isReproducibleTextToVideo(record({ seed: '' }))).toBe(false);
+ expect(isReproducibleTextToVideo(record({ seed: 'random' }))).toBe(false);
+ });
+
+ it('rejects a record with no usable prompt', () => {
+ expect(isReproducibleTextToVideo(record({ prompt: '' }))).toBe(false);
+ expect(isReproducibleTextToVideo(record({ prompt: ' ' }))).toBe(false);
+ expect(isReproducibleTextToVideo(record({ prompt: '(no prompt)' }))).toBe(false);
+ expect(isReproducibleTextToVideo(record({ prompt: undefined }))).toBe(false);
+ });
+
+ it('rejects derivatives that are not a single render', () => {
+ expect(isReproducibleTextToVideo(record({ chainedFrom: ['a', 'b'] }))).toBe(false);
+ expect(isReproducibleTextToVideo(record({ stitchedFrom: ['a', 'b'] }))).toBe(false);
+ expect(isReproducibleTextToVideo(record({ upscaledFrom: 'rec-0' }))).toBe(false);
+ });
+
+ it('rejects non-records without throwing', () => {
+ expect(isReproducibleTextToVideo(null)).toBe(false);
+ expect(isReproducibleTextToVideo(undefined)).toBe(false);
+ expect(isReproducibleTextToVideo('rec-1')).toBe(false);
+ });
+});
+
+describe('finishTargetForRecord', () => {
+ it('resolves the delivery model declared by the draft model', () => {
+ expect(finishTargetForRecord(record(), MODELS)).toEqual(DELIVERY_MODEL);
+ });
+
+ it('returns null when the delivery model is unavailable on this install', () => {
+ // e.g. the user deleted the full-quality entry from their registry.
+ expect(finishTargetForRecord(record(), [DRAFT_MODEL])).toBeNull();
+ });
+
+ it('returns null when the draft model declares no delivery target', () => {
+ expect(finishTargetForRecord(record({ modelId: 'delivery_model' }), MODELS)).toBeNull();
+ });
+
+ it('returns null when the record\'s model is not in the catalog at all', () => {
+ expect(finishTargetForRecord(record({ modelId: 'some_removed_model' }), MODELS)).toBeNull();
+ });
+
+ it('returns null for an image-conditioned draft even on a pair-capable model', () => {
+ expect(finishTargetForRecord(record({ mode: 'image', conditioning: ['image'] }), MODELS)).toBeNull();
+ });
+
+ it('returns null before the model list has loaded', () => {
+ expect(finishTargetForRecord(record(), [])).toBeNull();
+ expect(finishTargetForRecord(record(), null)).toBeNull();
+ });
+
+ it('ignores a malformed finishModelId on the draft entry', () => {
+ for (const finishModelId of ['', null, 42]) {
+ expect(finishTargetForRecord(record(), [{ ...DRAFT_MODEL, finishModelId }, DELIVERY_MODEL])).toBeNull();
+ }
+ });
+});
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 9f9b4c1d9f..a03ed67cc3 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -88,6 +88,7 @@ import { VIDEO_RESOLUTIONS } from '../lib/videoGenResolutions';
import { GROK_VIDEO_DURATIONS, GROK_VIDEO_DEFAULT_DURATION } from '../lib/grokVideoClip.js';
import ResolutionField from '../components/media/ResolutionField';
import { VIDEO_EDGE_BOUNDS, IC_LORA_MODES } from '../lib/videoGenParams.js';
+import { finishTargetForRecord } from '../lib/videoFinish.js';
const MODES = [
{ id: 'text', label: 'Text', icon: Type, desc: 'Text-to-video' },
@@ -161,7 +162,7 @@ export default function VideoGen() {
pickIcReferenceFile, pickIcReferenceVideoId,
addIcReferenceImage, updateIcReferenceImage, removeIcReferenceImage,
icStrength, setIcStrength, icSkipStage2, setIcSkipStage2,
- applyRemix, applyResumedParams, buildGeneratePayload,
+ applyRemix, applyFinish, applyResumedParams, buildGeneratePayload,
} = useVideoGenForm({ models, status, availableLoras, grokEnabled });
// Image gallery — used by both the start and end frame pickers so the
@@ -266,6 +267,16 @@ export default function VideoGen() {
window.scrollTo({ top: 0, behavior: 'smooth' });
};
+ // Finish a draft (#3696): same restore as Remix, but switched to the delivery
+ // model the draft's registry entry declares. Prefill only — the user presses
+ // Generate themselves.
+ const resolveFinishTarget = useCallback((raw) => finishTargetForRecord(raw, models), [models]);
+ const handleFinishVideo = (raw, target) => {
+ if (!raw || !target) return;
+ applyFinish(raw, target.id);
+ window.scrollTo({ top: 0, behavior: 'smooth' });
+ };
+
const [generating, setGenerating] = useState(false);
const [progress, setProgress] = useState(null);
const [statusMsg, setStatusMsg] = useState('');
@@ -1165,6 +1176,8 @@ export default function VideoGen() {
onDelete={handleDeleteHistory}
onToggleHidden={handleToggleHistoryHidden}
getCardProps={getCardProps}
+ finishTargetFor={resolveFinishTarget}
+ onFinish={handleFinishVideo}
/>
<MediaPreview
diff --git a/data.reference/media-models.json b/data.reference/media-models.json
index 9c18b9ce8c..e217b8103b 100644
--- a/data.reference/media-models.json
+++ b/data.reference/media-models.json
@@ -253,7 +253,8 @@
},
"estimatedDownloadGb": 44.9,
"reviewedAt": "2026-08-09"
- }
+ },
+ "finishModelId": "wan22_t2v_a14b"
},
{
"id": "wan22_i2v_a14b_lightning",
diff --git a/scripts/migrations/238-video-finish-profiles.js b/scripts/migrations/238-video-finish-profiles.js
new file mode 100644
index 0000000000..4833bafa8f
--- /dev/null
+++ b/scripts/migrations/238-video-finish-profiles.js
@@ -0,0 +1,73 @@
+/**
+ * Attach draft → delivery `finishModelId` edges to shipped video models
+ * (issue #3696) in existing installs.
+ *
+ * `data.reference/media-models.json` ships the edge for fresh installs and
+ * `mediaModels.js` backfills it at load — but `data/media-models.json` is the
+ * gitignored, user-editable copy that is never merge-updated, so this migration
+ * makes the change durable on disk instead of relying on the in-memory backfill
+ * running every boot.
+ *
+ * Preservation contract (identical to `applyVideoFinishProfiles`):
+ * - an entry that already has a `finishModelId` key is left alone (user edit,
+ * including an explicit `null` meaning "no delivery target")
+ * - an id the user deleted is NOT recreated
+ * - a custom / user-added model is untouched (no shipped pair exists for it)
+ * - an entry whose `repo` was re-pointed at a fork is skipped — a pair
+ * established against upstream weights must not be claimed for a fork
+ * - entry order is preserved; nothing else on the entry is modified
+ *
+ * An edge whose target the user already deleted from their registry is dropped
+ * again here rather than written out — the same thing `sanitizeFinishProfiles`
+ * does at load, so disk and memory agree.
+ */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { atomicWrite } from '../../server/lib/fileUtils.js';
+import { applyVideoFinishProfiles, sanitizeFinishProfiles } from '../../server/lib/videoFinishProfiles.js';
+
+const REL_PATH = 'data/media-models.json';
+const PLATFORMS = ['macos', 'windows'];
+
+export default {
+ async up({ rootDir }) {
+ const path = join(rootDir, REL_PATH);
+ const raw = await readFile(path, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return;
+ let config;
+ try {
+ config = JSON.parse(raw);
+ } catch (err) {
+ throw new Error(`Cannot migrate ${REL_PATH}: invalid JSON (${err.message})`, { cause: err });
+ }
+ if (!config?.video || typeof config.video !== 'object') return;
+
+ // Additive only: we count (and write) entries that GAINED an edge, never
+ // entries the sanitizer merely stripped. So a draft whose delivery model
+ // the user already deleted is left exactly as it was rather than rewritten,
+ // and a hand-edited bad edge is left for the load-time sanitizer to warn
+ // about instead of being silently deleted from the user's file here.
+ let linked = 0;
+ for (const platform of PLATFORMS) {
+ const list = config.video[platform];
+ if (!Array.isArray(list)) continue;
+ const next = sanitizeFinishProfiles(applyVideoFinishProfiles(list));
+ const merged = list.map((entry, i) => {
+ const gained = next[i]?.finishModelId && !(entry && 'finishModelId' in entry);
+ if (!gained) return entry;
+ linked += 1;
+ return next[i];
+ });
+ config.video[platform] = merged;
+ }
+
+ if (linked > 0) {
+ await atomicWrite(path, `${JSON.stringify(config, null, 2)}\n`);
+ console.log(`📝 ${REL_PATH}: linked ${linked} video ${linked === 1 ? 'entry' : 'entries'} to a Finish delivery model`);
+ }
+ },
+};
diff --git a/scripts/migrations/238-video-finish-profiles.test.js b/scripts/migrations/238-video-finish-profiles.test.js
new file mode 100644
index 0000000000..8dce293cb4
--- /dev/null
+++ b/scripts/migrations/238-video-finish-profiles.test.js
@@ -0,0 +1,125 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './238-video-finish-profiles.js';
+import { VIDEO_FINISH_PROFILES } from '../../server/lib/videoFinishProfiles.js';
+
+const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+const DRAFT_ID = 'wan22_t2v_a14b_lightning';
+const DELIVERY_ID = 'wan22_t2v_a14b';
+const SHIPPED_REPO = VIDEO_FINISH_PROFILES[DRAFT_ID].shippedRepo;
+
+// The pair as an existing install stores it, pre-migration: same repo, same
+// runtime, same modes — differing only in step budget and sampler.
+const baseRegistry = (draftOverrides = {}) => ({
+ video: {
+ macos: [
+ { id: DELIVERY_ID, name: 'Wan 2.2 T2V A14B', repo: SHIPPED_REPO, runtime: 'wan22', supportedModes: ['text'], steps: 20 },
+ { id: DRAFT_ID, name: 'Wan 2.2 T2V A14B Lightning', repo: SHIPPED_REPO, runtime: 'wan22', supportedModes: ['text'], steps: 4, samplerLocked: true, ...draftOverrides },
+ { id: 'my_custom_model', name: 'My Custom Model', repo: 'example-org/example-video', source: 'user' },
+ ],
+ windows: [{ id: 'ltx_video', name: 'LTX-Video 0.9.5', runtime: 'mlx_video', steps: 25 }],
+ defaultMacos: DELIVERY_ID,
+ },
+});
+
+const findMacos = (path, id) => readJson(path).video.macos.find((e) => e.id === id);
+
+describe('migration 238 — video finish profiles', () => {
+ let rootDir;
+ let path;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-238-'));
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ path = join(rootDir, 'data', 'media-models.json');
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ vi.restoreAllMocks();
+ });
+
+ it('links the shipped draft entry to its delivery model', async () => {
+ writeJson(path, baseRegistry());
+ await migration.up({ rootDir });
+ expect(findMacos(path, DRAFT_ID).finishModelId).toBe(DELIVERY_ID);
+ });
+
+ it('preserves canonical fields and entry order', async () => {
+ writeJson(path, baseRegistry());
+ await migration.up({ rootDir });
+ const got = readJson(path);
+ expect(got.video.macos.map((e) => e.id)).toEqual([DELIVERY_ID, DRAFT_ID, 'my_custom_model']);
+ const draft = findMacos(path, DRAFT_ID);
+ expect(draft.repo).toBe(SHIPPED_REPO);
+ expect(draft.steps).toBe(4);
+ expect(draft.samplerLocked).toBe(true);
+ expect(got.video.defaultMacos).toBe(DELIVERY_ID);
+ });
+
+ it('does not link the delivery model or a custom model to anything', async () => {
+ writeJson(path, baseRegistry());
+ await migration.up({ rootDir });
+ expect('finishModelId' in findMacos(path, DELIVERY_ID)).toBe(false);
+ expect('finishModelId' in findMacos(path, 'my_custom_model')).toBe(false);
+ });
+
+ it('preserves a user override (including an intentional null)', async () => {
+ writeJson(path, baseRegistry({ finishModelId: null }));
+ await migration.up({ rootDir });
+ expect(findMacos(path, DRAFT_ID).finishModelId).toBe(null);
+ });
+
+ it('skips an entry whose repo was re-pointed at a fork', async () => {
+ writeJson(path, baseRegistry({ repo: 'example-org/wan2.2-fork' }));
+ await migration.up({ rootDir });
+ expect('finishModelId' in findMacos(path, DRAFT_ID)).toBe(false);
+ });
+
+ it('does not write an edge whose target the user already deleted', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ writeJson(path, {
+ video: {
+ macos: [{ id: DRAFT_ID, repo: SHIPPED_REPO, runtime: 'wan22', supportedModes: ['text'], steps: 4 }],
+ windows: [],
+ },
+ });
+ await migration.up({ rootDir });
+ expect('finishModelId' in findMacos(path, DRAFT_ID)).toBe(false);
+ });
+
+ it('does not recreate entries the user deleted', async () => {
+ writeJson(path, { video: { macos: [{ id: DELIVERY_ID, repo: SHIPPED_REPO }], windows: [] } });
+ await migration.up({ rootDir });
+ expect(readJson(path).video.macos.map((e) => e.id)).toEqual([DELIVERY_ID]);
+ });
+
+ it('is idempotent — a second run rewrites nothing', async () => {
+ writeJson(path, baseRegistry());
+ await migration.up({ rootDir });
+ const after = readFileSync(path, 'utf-8');
+ await migration.up({ rootDir });
+ expect(readFileSync(path, 'utf-8')).toBe(after);
+ });
+
+ it('skips silently when data/media-models.json is missing (fresh install)', async () => {
+ await migration.up({ rootDir });
+ expect(existsSync(path)).toBe(false);
+ });
+
+ it('skips when the video section is missing entirely', async () => {
+ writeJson(path, { image: [] });
+ await migration.up({ rootDir });
+ expect(readJson(path)).toEqual({ image: [] });
+ });
+
+ it('throws a clear error on invalid JSON', async () => {
+ writeFileSync(path, '{ not json');
+ await expect(migration.up({ rootDir })).rejects.toThrow(/invalid JSON/);
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index b2f80fe466..aa4cd4cb9f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -110,6 +110,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `promptPartials.js` | Mustache-style partial expansion. |
| `mediaModels.js` | Single source of truth for image/video model metadata. |
| `videoDisclosure.js` | Video Gen provenance/licensing + backend policy-scope facts (#3674). `VIDEO_MODEL_DISCLOSURES` maps each shipped video model id to `{ shippedRepo, disclosure }` (model card URL, weights license, runtime license, pinned-snapshot download size in decimal GB, review date) — every value checked against a primary upstream source, and any fact that could not be established is OMITTED so the UI renders "Unknown" instead of guessing. `applyVideoDisclosures(list)` is the load-time backfill (twin of migration 237) with the same preservation guards: an existing `disclosure` key wins, a custom id is skipped, and a `repo` pointed at a fork keeps Unknown. `VIDEO_BACKEND_DISCLOSURES` / `videoBackendDisclosure(id)` state where inference runs (`execution: local or hosted`) and whose policy applies — execution facts only, never a restrictiveness ranking. |
+| `videoFinishProfiles.js` | Draft → delivery ("Finish") relationships between video models (#3696). `VIDEO_FINISH_PROFILES` declares each fast draft entry id → `{ shippedRepo, finishModelId }`, only for pairs that share a runtime, base repo and supported modes (the same weights at a different step budget), so re-rendering the draft's seed reproduces its composition instead of re-rolling it. `applyVideoFinishProfiles(list)` is the load-time backfill (twin of migration 238) with the usual preservation guards (existing key wins, custom id skipped, forked `repo` skipped); `validateFinishProfileGraph(list)` returns the graph problems (missing / self-referencing / chained target, runtime / repo / supportedModes mismatch) and `sanitizeFinishProfiles(list)` warns + strips them at load so a typo can never surface a Finish button targeting nothing. `finishTargetForModel(model, availableModels)` resolves the delivery entry scoped to what this install can run. |
| `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`) plus reasoning-effort helpers for the claude/codex/agy CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `hasEffortFlag`, and `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`) plus codex startup-arg helpers (`CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal). |
| `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Dependency-light on purpose, mirroring those files. |
| `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier; also derives `cacheReadPer1M`/`cacheWritePer1M` from the input rate via per-family multipliers), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd(tokensIn, tokensOut, rates, cache?)` — `tokensIn` is UNCACHED input; cache tiers are priced separately via the optional 4th arg — and `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); still excludes batch/long-context tiers. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 585e00ecb8..7a1ad9756a 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -111,6 +111,7 @@ export * from './installLogger.js';
export * from './kimi.js';
export * from './mediaModels.js';
export * from './videoDisclosure.js';
+export * from './videoFinishProfiles.js';
export * from './promptPartials.js';
export * from './promptRunner.js';
export * from './promptSystemStages.js';
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index eb3af8935b..3b57802d6e 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -16,6 +16,9 @@
* rather than guessing. Canonical fields (repo/revision/runtime/memoryGb/
* supportedModes/requiredWeights) are NOT duplicated inside it. Shipped
* values live in lib/videoDisclosure.js and are backfilled at load.
+ * `finishModelId` (optional, issue #3696) names the delivery model a
+ * fast draft entry finishes into — declared in lib/videoFinishProfiles.js,
+ * backfilled at load, and validated (invalid edges are dropped, loudly).
* - video.defaultMacos / video.defaultWindows: id of the default model
* - image[]: { id, name, steps, guidance, broken? }
* - textEncoders[]: { id, label, repo, localPath? }
@@ -29,6 +32,7 @@ import { isPlainObject } from './objects.js';
import { RUNNER_FAMILIES } from './runners.js';
import { ServerError } from './errorHandler.js';
import { applyVideoDisclosures } from './videoDisclosure.js';
+import { applyVideoFinishProfiles, sanitizeFinishProfiles } from './videoFinishProfiles.js';
// fileUtils.ensureDir is async/Promise-returning; this module needs a
// synchronous version because `loadMediaModels()` is called at import-time
// from videoGen/imageGen modules, which can't await before exporting.
@@ -45,7 +49,10 @@ const DEFAULT_REGISTRY = {
// (lib/videoDisclosure.js) to each entry, so the seed written on a fresh
// install, the in-memory defaults, and data.reference/media-models.json all
// carry the same disclosure without repeating it inline here.
- macos: applyVideoDisclosures([
+ // `applyVideoFinishProfiles` attaches the shipped draft → delivery
+ // `finishModelId` edges (lib/videoFinishProfiles.js) the same way, so the
+ // Finish relationship is declared in one place instead of inline here.
+ macos: applyVideoFinishProfiles(applyVideoDisclosures([
// notapalindrome's mlx-video-with-audio runtime — single PyPI package,
// T2V/I2V only, FFLF degrades to last-frame conditioning (one --image arg).
// LTX-2 (the older 42 GB model) stays deprecated — superseded by 2.3.
@@ -183,10 +190,10 @@ const DEFAULT_REGISTRY = {
precision: 'fp32',
deprecated: true,
},
- ]),
- windows: applyVideoDisclosures([
+ ])),
+ windows: applyVideoFinishProfiles(applyVideoDisclosures([
{ id: 'ltx_video', name: 'LTX-Video 0.9.5 — T2V + I2V (~9.5 GB, auto-downloads)', runtime: 'mlx_video', steps: 25, guidance: 3.0 },
- ]),
+ ])),
defaultMacos: 'ltx23_distilled_q4',
defaultWindows: 'ltx_video',
},
@@ -660,8 +667,12 @@ const normalizeRegistry = (parsed) => {
// that persisted their registry before `disclosure` existed pick it up
// here without waiting for the migration, and both paths share the same
// preservation guards (user value wins, forked repo keeps Unknown).
- macos: applyVideoDisclosures(backfillRuntime(macosResult.entries)),
- windows: applyVideoDisclosures(backfillRuntime(windowsResult.entries)),
+ // sanitizeFinishProfiles runs LAST (after the backfill and after the
+ // user's own entries are merged in) so an edge that points at a model
+ // this install deleted — or a hand-edited typo — is dropped with a
+ // warning instead of surfacing a Finish button targeting nothing.
+ macos: sanitizeFinishProfiles(applyVideoFinishProfiles(applyVideoDisclosures(backfillRuntime(macosResult.entries)))),
+ windows: sanitizeFinishProfiles(applyVideoFinishProfiles(applyVideoDisclosures(backfillRuntime(windowsResult.entries)))),
},
_shippedDefaults: {
...(safe._shippedDefaults || {}),
diff --git a/server/lib/videoFinishProfiles.js b/server/lib/videoFinishProfiles.js
new file mode 100644
index 0000000000..bc23e8baf2
--- /dev/null
+++ b/server/lib/videoFinishProfiles.js
@@ -0,0 +1,170 @@
+/**
+ * Video draft → delivery ("Finish") profiles (issue #3696).
+ *
+ * A *draft* model is a fast, low-step variant a user composes with; a
+ * *delivery* model is the slower sibling that renders the same composition at
+ * full quality. When the two share identical base weights, re-rendering the
+ * draft's prompt + resolved seed + dials on the delivery model reproduces the
+ * same composition instead of re-rolling it — that is the entire point of the
+ * Finish action.
+ *
+ * The relationship is declared here (not inferred from names) and attached to
+ * registry entries as `finishModelId` by `applyVideoFinishProfiles`, the same
+ * load-time backfill pattern `applyVideoDisclosures` uses in
+ * `lib/videoDisclosure.js`. Migration 238 makes it durable on disk for installs
+ * that already persisted `data/media-models.json`.
+ *
+ * Rules this module exists to enforce:
+ * - Only genuinely compatible pairs are declared. "Compatible" means the
+ * same runtime, the same base `repo`, and the same `supportedModes` — the
+ * pair differs only in the step count / sampler / adaptor weights. A pair
+ * that merely sounds related (a distilled Q4 vs a bf16 build of a different
+ * checkpoint) is NOT declared: its seeds do not reproduce each other's
+ * composition, so "finishing" it would silently be a re-roll.
+ * - The graph is validated (`validateFinishProfileGraph`) so a typo fails
+ * loudly rather than surfacing as a Finish button that targets nothing.
+ * Invalid edges are stripped at load with a warning — a user-edited
+ * registry must never crash boot (`loadMediaModels` runs at import time).
+ *
+ * NOTE: the I2V lightning → full pair is deliberately NOT declared yet. Finish
+ * currently only offers itself for fully reproducible text-to-video records
+ * (image-conditioned drafts have no durable reference to re-render from), so an
+ * I2V edge would be config that can never fire.
+ */
+
+/**
+ * Shipped draft → delivery edges, keyed by the DRAFT entry id.
+ *
+ * `shippedRepo` is the fork-preservation guard (same contract as
+ * `applyVideoDisclosures` / `backfillKvRepo`): the profile is only attached
+ * while the entry still points at the repo the pair was established against. A
+ * user who re-pointed `repo` at a fork keeps no Finish target rather than
+ * inheriting a claim about weights we can no longer vouch for.
+ */
+export const VIDEO_FINISH_PROFILES = Object.freeze({
+ // Wan 2.2 T2V A14B: the Lightning entry is the SAME repo at the SAME pinned
+ // revision as the full entry — it differs only by the 4-step Seko LoRA
+ // adaptor, a locked euler sampler, and guidance 1.0. Dropping the adaptor and
+ // rendering the same seed at 20 steps is the canonical draft → delivery hop.
+ wan22_t2v_a14b_lightning: Object.freeze({
+ shippedRepo: 'AbstractFramework/wan2.2-t2v-a14b-diffusers-8bit',
+ finishModelId: 'wan22_t2v_a14b',
+ }),
+});
+
+const isEntry = (entry) => !!entry && typeof entry === 'object' && typeof entry.id === 'string';
+
+/**
+ * Attach `finishModelId` to shipped draft entries that don't already carry one.
+ * Pure; returns a new array and never mutates the input entries.
+ *
+ * Preservation contract (mirrors migration 238):
+ * - `'finishModelId' in entry` → user/existing value wins (including `null`,
+ * the explicit "this draft has no delivery target" override).
+ * - entry id not shipped → custom model, left as-is.
+ * - `repo` differs from shipped → forked weights, left as-is.
+ */
+export const applyVideoFinishProfiles = (list) => {
+ if (!Array.isArray(list)) return list;
+ return list.map((entry) => {
+ if (!isEntry(entry)) return entry;
+ if ('finishModelId' in entry) return entry;
+ const spec = VIDEO_FINISH_PROFILES[entry.id];
+ if (!spec) return entry;
+ if (spec.shippedRepo !== null && entry.repo !== spec.shippedRepo) return entry;
+ return { ...entry, finishModelId: spec.finishModelId };
+ });
+};
+
+/**
+ * Validate every `finishModelId` edge in one platform's video model list.
+ * Pure — returns an array of `{ id, finishModelId, reason }` problems (empty
+ * when the graph is sound). Callers decide whether to warn-and-strip (load
+ * path) or fail (the test that pins the shipped registry).
+ *
+ * Checked, in the order a typo is most likely to hit:
+ * - the value is a non-empty string
+ * - it is not a self-reference
+ * - the target exists in the SAME platform list (a delivery model the user
+ * deleted, or one that only exists on the other platform, is unusable)
+ * - the target is not itself a draft (no chains, and therefore no cycles —
+ * a chain would make "Finish" ambiguous about where it lands)
+ * - runtime, base `repo` and `supportedModes` match, i.e. the pair really is
+ * the same weights at a different step budget
+ */
+export const validateFinishProfileGraph = (list) => {
+ if (!Array.isArray(list)) return [];
+ const byId = new Map(list.filter(isEntry).map((e) => [e.id, e]));
+ const problems = [];
+ const fail = (id, finishModelId, reason) => problems.push({ id, finishModelId, reason });
+ for (const entry of list) {
+ if (!isEntry(entry)) continue;
+ const target = entry.finishModelId;
+ if (target === undefined || target === null) continue;
+ if (typeof target !== 'string' || target.length === 0) {
+ fail(entry.id, target, 'finishModelId must be a non-empty string');
+ continue;
+ }
+ if (target === entry.id) {
+ fail(entry.id, target, 'finishModelId points at itself');
+ continue;
+ }
+ const to = byId.get(target);
+ if (!to) {
+ fail(entry.id, target, `finishModelId "${target}" is not a video model in this platform's list`);
+ continue;
+ }
+ if (to.finishModelId !== undefined && to.finishModelId !== null) {
+ fail(entry.id, target, `finishModelId "${target}" is itself a draft (chained finish targets are not supported)`);
+ continue;
+ }
+ if (entry.runtime !== to.runtime) {
+ fail(entry.id, target, `runtime mismatch (${entry.runtime || '?'} → ${to.runtime || '?'})`);
+ continue;
+ }
+ if (entry.repo !== to.repo) {
+ fail(entry.id, target, `base repo mismatch (${entry.repo || '?'} → ${to.repo || '?'})`);
+ continue;
+ }
+ const fromModes = [...(entry.supportedModes || [])].sort().join(',');
+ const toModes = [...(to.supportedModes || [])].sort().join(',');
+ if (fromModes !== toModes) {
+ fail(entry.id, target, `supportedModes mismatch (${fromModes || '?'} → ${toModes || '?'})`);
+ }
+ }
+ return problems;
+};
+
+/**
+ * Load-time guard: strip every invalid `finishModelId` from a video model list,
+ * logging each one. A user-edited (or migration-stale) registry must not be
+ * able to surface a Finish button that targets a model this install can't run,
+ * and must not crash boot. Returns the input array unchanged when the graph is
+ * sound, so the common path allocates nothing.
+ */
+export const sanitizeFinishProfiles = (list) => {
+ const problems = validateFinishProfileGraph(list);
+ if (problems.length === 0) return list;
+ const bad = new Set(problems.map((p) => p.id));
+ for (const p of problems) {
+ console.log(`⚠️ media-models: dropping finishModelId on "${p.id}" — ${p.reason}`);
+ }
+ return list.map((entry) => {
+ if (!isEntry(entry) || !bad.has(entry.id)) return entry;
+ const { finishModelId, ...rest } = entry;
+ return rest;
+ });
+};
+
+/**
+ * Resolve the delivery model a draft entry finishes into, scoped to the models
+ * this install can actually run (`getVideoModels()` output — already filtered
+ * for platform-broken entries). Returns the target entry, or `null` when the
+ * draft declares no target or the target isn't available here.
+ */
+export const finishTargetForModel = (model, availableModels) => {
+ const targetId = model?.finishModelId;
+ if (typeof targetId !== 'string' || targetId.length === 0) return null;
+ if (!Array.isArray(availableModels)) return null;
+ return availableModels.find((m) => m?.id === targetId) || null;
+};
diff --git a/server/lib/videoFinishProfiles.test.js b/server/lib/videoFinishProfiles.test.js
new file mode 100644
index 0000000000..b0bcfd9227
--- /dev/null
+++ b/server/lib/videoFinishProfiles.test.js
@@ -0,0 +1,146 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import {
+ VIDEO_FINISH_PROFILES,
+ applyVideoFinishProfiles,
+ validateFinishProfileGraph,
+ sanitizeFinishProfiles,
+ finishTargetForModel,
+} from './videoFinishProfiles.js';
+import { readFileSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+// The shipped registry, read from the seed file rather than by importing
+// mediaModels.js (which seeds/writes data/media-models.json on import).
+// mediaModels.test.js already pins this file to the in-code DEFAULT_REGISTRY,
+// so validating it here validates the defaults.
+const SHIPPED_REGISTRY = JSON.parse(readFileSync(
+ join(dirname(fileURLToPath(import.meta.url)), '../../data.reference/media-models.json'),
+ 'utf-8',
+));
+
+// A minimal well-formed pair: same runtime, same base repo, same modes — the
+// pair differs only in step budget, which is what makes a seed re-render
+// reproduce the draft's composition.
+const draft = (over = {}) => ({
+ id: 'draft', runtime: 'wan22', repo: 'org/base', supportedModes: ['text'], steps: 4, finishModelId: 'full', ...over,
+});
+const full = (over = {}) => ({
+ id: 'full', runtime: 'wan22', repo: 'org/base', supportedModes: ['text'], steps: 20, ...over,
+});
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('applyVideoFinishProfiles', () => {
+ it('attaches the shipped finishModelId to a matching draft entry', () => {
+ const [entry] = applyVideoFinishProfiles([
+ { id: 'wan22_t2v_a14b_lightning', repo: VIDEO_FINISH_PROFILES.wan22_t2v_a14b_lightning.shippedRepo },
+ ]);
+ expect(entry.finishModelId).toBe('wan22_t2v_a14b');
+ });
+
+ it('leaves an existing finishModelId alone — including an explicit null override', () => {
+ const list = [
+ { id: 'wan22_t2v_a14b_lightning', repo: VIDEO_FINISH_PROFILES.wan22_t2v_a14b_lightning.shippedRepo, finishModelId: null },
+ ];
+ expect(applyVideoFinishProfiles(list)[0].finishModelId).toBeNull();
+ });
+
+ it('skips an entry whose repo was re-pointed at a fork', () => {
+ const [entry] = applyVideoFinishProfiles([
+ { id: 'wan22_t2v_a14b_lightning', repo: 'someone/fork-of-wan' },
+ ]);
+ expect(entry.finishModelId).toBeUndefined();
+ });
+
+ it('leaves custom / unknown ids and non-entries untouched', () => {
+ const list = [{ id: 'my-custom-model', repo: 'me/mine' }, null, 'nope'];
+ expect(applyVideoFinishProfiles(list)).toEqual(list);
+ });
+});
+
+describe('validateFinishProfileGraph', () => {
+ it('accepts a genuinely compatible pair', () => {
+ expect(validateFinishProfileGraph([draft(), full()])).toEqual([]);
+ });
+
+ it('accepts a list with no finish edges at all', () => {
+ expect(validateFinishProfileGraph([full(), { id: 'other' }])).toEqual([]);
+ });
+
+ it('rejects a target that is not in this platform list', () => {
+ const [problem] = validateFinishProfileGraph([draft({ finishModelId: 'typo_id' })]);
+ expect(problem.id).toBe('draft');
+ expect(problem.reason).toMatch(/not a video model/);
+ });
+
+ it('rejects a self-reference', () => {
+ const [problem] = validateFinishProfileGraph([draft({ finishModelId: 'draft' })]);
+ expect(problem.reason).toMatch(/itself/);
+ });
+
+ it('rejects a chained target (which is also how cycles are ruled out)', () => {
+ const problems = validateFinishProfileGraph([
+ draft(),
+ full({ finishModelId: 'draft' }), // full → draft → full would be a cycle
+ ]);
+ expect(problems.map((p) => p.reason).join(' ')).toMatch(/chained/);
+ });
+
+ it('rejects a runtime mismatch', () => {
+ const [problem] = validateFinishProfileGraph([draft(), full({ runtime: 'ltx2' })]);
+ expect(problem.reason).toMatch(/runtime mismatch/);
+ });
+
+ it('rejects a base repo mismatch — different weights do not reproduce a seed', () => {
+ const [problem] = validateFinishProfileGraph([draft(), full({ repo: 'org/other-checkpoint' })]);
+ expect(problem.reason).toMatch(/base repo mismatch/);
+ });
+
+ it('rejects a supportedModes mismatch', () => {
+ const [problem] = validateFinishProfileGraph([draft(), full({ supportedModes: ['image'] })]);
+ expect(problem.reason).toMatch(/supportedModes mismatch/);
+ });
+
+ it('rejects a non-string finishModelId', () => {
+ const [problem] = validateFinishProfileGraph([draft({ finishModelId: 7 }), full()]);
+ expect(problem.reason).toMatch(/non-empty string/);
+ });
+
+ it('passes for every shipped platform list — a typo in the registry fails here', () => {
+ for (const platform of ['macos', 'windows']) {
+ expect(validateFinishProfileGraph(SHIPPED_REGISTRY.video[platform])).toEqual([]);
+ }
+ });
+});
+
+describe('sanitizeFinishProfiles', () => {
+ it('returns the list untouched when the graph is sound', () => {
+ const list = [draft(), full()];
+ expect(sanitizeFinishProfiles(list)).toBe(list);
+ });
+
+ it('strips a bad edge and logs it, without touching the rest of the entry', () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const [entry] = sanitizeFinishProfiles([draft({ finishModelId: 'deleted_by_user' })]);
+ expect(entry.finishModelId).toBeUndefined();
+ expect(entry.id).toBe('draft');
+ expect(entry.steps).toBe(4);
+ expect(log).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('finishTargetForModel', () => {
+ it('resolves the delivery entry from the available list', () => {
+ expect(finishTargetForModel(draft(), [draft(), full()])?.id).toBe('full');
+ });
+
+ it('returns null when the target model is not available on this install', () => {
+ expect(finishTargetForModel(draft(), [draft()])).toBeNull();
+ });
+
+ it('returns null for a model with no declared target', () => {
+ expect(finishTargetForModel(full(), [draft(), full()])).toBeNull();
+ expect(finishTargetForModel(null, [full()])).toBeNull();
+ });
+});
diff --git a/server/services/videoGen/generateVideoHelpers.js b/server/services/videoGen/generateVideoHelpers.js
index 3856a1d17f..58c6113487 100644
--- a/server/services/videoGen/generateVideoHelpers.js
+++ b/server/services/videoGen/generateVideoHelpers.js
@@ -218,6 +218,50 @@ export function makeVideoGenLineHandler({ job, jobId, pythonNoiseRe }) {
};
}
+/**
+ * Version marker stamped on every history record written by this (finish-aware)
+ * writer — see `describeRenderConditioning`. It is the POSITIVE signal that the
+ * record's conditioning inventory is trustworthy: a legacy record written
+ * before #3696 carries no `renderInputsVersion` and no `conditioning`, which is
+ * indistinguishable from "this render used no conditioning" if you only look at
+ * the absence. Consumers (the client's Finish gate) must require this marker,
+ * so legacy/incomplete records degrade to "not finishable" instead of being
+ * wrongly assumed reproducible.
+ */
+export const RENDER_INPUTS_VERSION = 1;
+
+/**
+ * Inventory the conditioning inputs one render actually used, as a stable,
+ * sorted list of kind strings. An empty array means the render was driven by
+ * nothing but the prompt + seed + dials — i.e. fully reproducible from what the
+ * history record already stores, which is the precondition for Finish (#3696).
+ *
+ * Deliberately records KINDS, not paths: staging/temp upload paths are
+ * machine-specific and short-lived, and history is user-facing (the same reason
+ * IC references are stamped by basename). Recording the fact of conditioning is
+ * enough to answer "can this be re-rendered from the record alone?" — which is
+ * the only question this feeds.
+ *
+ * Pure. Tolerates missing/`null` fields (the common text-to-video call).
+ */
+export function describeRenderConditioning({
+ sourceImagePath = null,
+ lastImagePath = null,
+ keyframes = null,
+ extendFromVideoPath = null,
+ audioFilePath = null,
+ icReferencePaths = null,
+} = {}) {
+ const kinds = [];
+ if (sourceImagePath) kinds.push('image');
+ if (lastImagePath) kinds.push('lastImage');
+ if (Array.isArray(keyframes) && keyframes.length > 0) kinds.push('keyframes');
+ if (extendFromVideoPath) kinds.push('extend');
+ if (audioFilePath) kinds.push('audio');
+ if (Array.isArray(icReferencePaths) && icReferencePaths.length > 0) kinds.push('icReference');
+ return kinds.sort();
+}
+
/**
* Render a runtime fingerprint (either the `RUNTIME:` payload a helper script
* emits — `{ runtime, versions, chip, os, python }` — or the Node-side
diff --git a/server/services/videoGen/generateVideoHelpers.test.js b/server/services/videoGen/generateVideoHelpers.test.js
index 0b90db2447..5cd8ffda36 100644
--- a/server/services/videoGen/generateVideoHelpers.test.js
+++ b/server/services/videoGen/generateVideoHelpers.test.js
@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { writeFileSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
-import { makeVideoGenLineHandler, isWatchdogSuccess, finalizeGeneratedVideo, parseByteProgress, formatBytes, formatDownloadMessage, describeSignalDeath, formatRuntimeFingerprint } from './generateVideoHelpers.js';
+import { makeVideoGenLineHandler, isWatchdogSuccess, finalizeGeneratedVideo, parseByteProgress, formatBytes, formatDownloadMessage, describeSignalDeath, formatRuntimeFingerprint, describeRenderConditioning, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';
describe('parseByteProgress', () => {
it('parses single byte value (e.g., "2.5G")', () => {
@@ -244,6 +244,58 @@ describe('finalizeGeneratedVideo runtime persistence', () => {
expect(saved).toHaveLength(1);
expect('runtime' in saved[0]).toBe(false);
});
+
+ it('carries the durable re-render inputs through to the saved record (#3696)', async () => {
+ const job = { id: 'job-abcdef12', clients: [] };
+ let saved = null;
+ await finalizeGeneratedVideo({
+ ...baseCtx(job),
+ meta: {
+ ...baseCtx(job).meta,
+ seed: 424242,
+ mode: 'text',
+ renderInputsVersion: RENDER_INPUTS_VERSION,
+ conditioning: [],
+ },
+ actualSeed: 424242,
+ mutateHistory: async (fn) => { saved = await fn([]); return saved; },
+ });
+ expect(saved[0].seed).toBe(424242);
+ expect(saved[0].renderInputsVersion).toBe(RENDER_INPUTS_VERSION);
+ expect(saved[0].conditioning).toEqual([]);
+ // No staging/temp path may ride along on a user-facing history record.
+ expect(JSON.stringify(saved[0])).not.toMatch(/\/tmp\/|uploads/);
+ });
+});
+
+describe('describeRenderConditioning (#3696)', () => {
+ it('reports an empty inventory for a plain text-to-video render', () => {
+ expect(describeRenderConditioning()).toEqual([]);
+ expect(describeRenderConditioning({})).toEqual([]);
+ expect(describeRenderConditioning({ sourceImagePath: null, keyframes: [], icReferencePaths: [] })).toEqual([]);
+ });
+
+ it('names each conditioning input that steered the render', () => {
+ expect(describeRenderConditioning({ sourceImagePath: '/tmp/a.png' })).toEqual(['image']);
+ expect(describeRenderConditioning({ lastImagePath: '/tmp/z.png' })).toEqual(['lastImage']);
+ expect(describeRenderConditioning({ keyframes: [{ path: '/tmp/1.png' }] })).toEqual(['keyframes']);
+ expect(describeRenderConditioning({ extendFromVideoPath: '/data/videos/x.mp4' })).toEqual(['extend']);
+ expect(describeRenderConditioning({ audioFilePath: '/tmp/song.wav' })).toEqual(['audio']);
+ expect(describeRenderConditioning({ icReferencePaths: ['/tmp/ref.mp4'] })).toEqual(['icReference']);
+ });
+
+ it('returns a stable sorted list for a multi-input render', () => {
+ expect(describeRenderConditioning({
+ sourceImagePath: '/tmp/a.png',
+ lastImagePath: '/tmp/z.png',
+ audioFilePath: '/tmp/song.wav',
+ })).toEqual(['audio', 'image', 'lastImage']);
+ });
+
+ it('records kinds only — never the staging paths it was given', () => {
+ const kinds = describeRenderConditioning({ sourceImagePath: '/tmp/upload-9f3.png' });
+ expect(kinds.join(',')).not.toMatch(/tmp|9f3/);
+ });
});
describe('formatRuntimeFingerprint', () => {
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 2937718600..5fe1e81908 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -29,7 +29,7 @@ import { findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming, upscale
import { hfChildEnv } from '../../lib/hfToken.js';
import { inspectModelCache, findCachedRepoFile } from '../../lib/hfCache.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
-import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess, describeSignalDeath } from './generateVideoHelpers.js';
+import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess, describeSignalDeath, describeRenderConditioning, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';
import { assertSafeLoraFilename } from '../loras.js';
import { isMlxVideoLtxLoraCapable } from '../../lib/runners.js';
import {
@@ -1078,6 +1078,23 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// from `keyframes` even when caller omitted `mode`, so without this the
// history entry would say 'text' for a multi-keyframe render.
mode: mode || (hasMultiKeyframes ? 'fflf' : sourceImagePath ? 'image' : 'text'),
+ // Durable re-render provenance (#3696). `seed` above is ALWAYS the resolved
+ // seed (a caller-omitted seed was rolled into `actualSeed` before the child
+ // ever ran), so a random-seed render records the seed it actually used and
+ // a Finish re-render reproduces the same composition rather than re-rolling.
+ // `conditioning` inventories what else steered this render — empty means
+ // prompt + seed + dials are the whole input. `renderInputsVersion` is the
+ // marker that both are trustworthy; records without it are legacy and must
+ // not be assumed unconditioned. Neither field carries a staging path.
+ renderInputsVersion: RENDER_INPUTS_VERSION,
+ conditioning: describeRenderConditioning({
+ sourceImagePath: resolvedSourceImage,
+ lastImagePath: resolvedLastImage,
+ keyframes: resolvedKeyframes,
+ extendFromVideoPath,
+ audioFilePath,
+ icReferencePaths: resolvedIcReferencePaths,
+ }),
// Stamp the experimental fast-path so A/B analysis can tell a two-stage
// render apart from a user who happened to pick 8 steps — comparing it
// against the default Standard render is the whole point of the knob.
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 318b39dfbe..a19bb65703 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -1579,6 +1579,11 @@ describe('generateVideo — close-handler resilience (issue #1334)', () => {
makeVideoGenLineHandler: () => () => true,
isWatchdogSuccess: () => false,
finalizeGeneratedVideo: vi.fn(async () => { throw new Error('boom finalize'); }),
+ // Durable re-render inputs (#3696) — generateVideo reads both while
+ // building `meta`, so a partial mock has to carry them or every render
+ // in this file throws on the missing export.
+ describeRenderConditioning: () => [],
+ RENDER_INPUTS_VERSION: 1,
}));
const { generateVideo: gv } = await import('./local.js');
const { videoGenEvents: events } = await import('./events.js');
@@ -2535,3 +2540,72 @@ describe('icLoraArgs — direct validation (#3100)', () => {
})).not.toThrow();
});
});
+
+describe('generateVideo — durable re-render inputs (#3696)', () => {
+ // The `started` event spreads the same `meta` object finalizeGeneratedVideo
+ // later persists as the history record, so it's the observable surface for
+ // what a completed render would store — without having to drive the child
+ // process to a successful close.
+ const startedMetaFor = async (params) => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+ let started = null;
+ const onStarted = (e) => { started = e; };
+ videoGenEvents.on('started', onStarted);
+ await generateVideo({
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'a quiet street at dusk',
+ width: 512,
+ height: 512,
+ numFrames: 25,
+ fps: 24,
+ ...params,
+ });
+ videoGenEvents.off('started', onStarted);
+ const renderCall = spawnMock.mock.calls.find(
+ ([bin, args]) => String(bin).includes('.portos/ltx-2-mlx/.venv/bin/python3') && Array.isArray(args),
+ );
+ return { started, args: renderCall?.[1] || [] };
+ };
+
+ it('records the seed a random-seed render actually resolved to, matching the one the child got', async () => {
+ const { started, args } = await startedMetaFor({ jobId: 'finish-random-seed-test' });
+ // No seed was supplied — the record must still pin the resolved value, or
+ // a Finish re-render would roll a different composition.
+ expect(Number.isInteger(started.seed)).toBe(true);
+ expect(args[args.indexOf('--seed') + 1]).toBe(String(started.seed));
+ expect(started.renderInputsVersion).toBe(1);
+ expect(started.conditioning).toEqual([]);
+ expect(started.mode).toBe('text');
+ });
+
+ it('keeps an explicitly supplied seed verbatim', async () => {
+ const { started, args } = await startedMetaFor({ jobId: 'finish-explicit-seed-test', seed: 1234 });
+ expect(started.seed).toBe(1234);
+ expect(args[args.indexOf('--seed') + 1]).toBe('1234');
+ });
+
+ it('inventories conditioning for an image-to-video render (so Finish is not offered for it)', async () => {
+ const { started } = await startedMetaFor({
+ jobId: 'finish-i2v-conditioning-test',
+ mode: 'image',
+ sourceImagePath: '/mock/source.png',
+ });
+ expect(started.conditioning).toContain('image');
+ expect(started.mode).toBe('image');
+ });
+
+ it('inventories audio conditioning even though the mode still reads as text', async () => {
+ // The mode inference only looks at images/keyframes, so an audio-driven
+ // render with no explicit mode would otherwise be stamped `text` and look
+ // fully reproducible. The conditioning inventory is what catches it.
+ const { started } = await startedMetaFor({
+ jobId: 'finish-audio-conditioning-test',
+ audioFilePath: '/mock/song.wav',
+ });
+ expect(started.mode).toBe('text');
+ expect(started.conditioning).toEqual(['audio']);
+ });
+});