Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(webv2): video generation core — settings, capabilities matrix, canvas math

Lincoln Stein9f3fb741b2fe
diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
index 3797c0ce24..9ec8ecea3b 100644
--- a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
@@ -23,5 +23,6 @@ export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string[
nodes: [],
queue: ['contracts', 'devices', 'launchpad', 'menu', 'queries', 'react', 'reveal', 'utility', 'widget'],
upscale: ['widget'],
+ video: [],
workflow: ['contracts', 'graph', 'paletteSearch', 'preview', 'queries', 'react', 'utility', 'widget'],
};
diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.ts
index 0c09c875a9..96a73d3e5a 100644
--- a/invokeai/frontend/webv2/src/features/generation/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts
@@ -20,6 +20,7 @@ export {
isMainModelConfig,
isModelIdentifierConfig,
isVaeModelConfig,
+ isWanLoraTargetingMain,
MAX_HIDIFFUSION_RATIO,
MAX_NEGATIVE_PROMPT_HEIGHT_PX,
MAX_POSITIVE_PROMPT_HEIGHT_PX,
@@ -57,7 +58,12 @@ export {
type ResolvedGenerateWidgetValues,
type ResolveGenerateWidgetValuesInput,
} from './core/resolveGenerateWidgetValues';
-export { isVaeCompatibleWithGenerateModel } from './core/componentCompatibility';
+export {
+ getCompatibleDiffusersComponentSource,
+ isDiffusersMainForBase,
+ isVaeCompatibleWithGenerateModel,
+ isVaeForBases,
+} from './core/componentCompatibility';
export {
isValidKrea2RebalanceWeights,
normalizeRebalancePresets,
diff --git a/invokeai/frontend/webv2/src/features/video/core/dimensions.test.ts b/invokeai/frontend/webv2/src/features/video/core/dimensions.test.ts
new file mode 100644
index 0000000000..c291fb8a5a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/video/core/dimensions.test.ts
@@ -0,0 +1,160 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ getVideoAspectRatioParts,
+ getVideoDurationSeconds,
+ invertVideoAspectRatioId,
+ isValidMiniMaxH3NumFrames,
+ isValidWanNumFrames,
+ MINIMAX_H3_NUM_FRAMES_CHOICES,
+ MINIMAX_H3_NUM_FRAMES_DEFAULT,
+ resolveMiniMaxH3Canvas,
+ scaleAndSnapWanDimensions,
+ snapMiniMaxH3NumFrames,
+ snapWanNumFrames,
+ WAN_A14B_PIXEL_MULTIPLE,
+ WAN_NUM_FRAMES_DEFAULT,
+ WAN_NUM_FRAMES_MAX,
+ WAN_TI2V_PIXEL_MULTIPLE,
+} from './dimensions';
+
+describe('scaleAndSnapWanDimensions', () => {
+ it('scales the short side to the preset and snaps to the A14B grid of 16', () => {
+ // 1920x1080 at 720p is an exact fit.
+ expect(scaleAndSnapWanDimensions(1920, 1080, '720p', WAN_A14B_PIXEL_MULTIPLE)).toEqual({
+ height: 720,
+ width: 1280,
+ });
+ // 1920x1080 at 480p: 853.33 wide, snapped to the nearest multiple of 16.
+ expect(scaleAndSnapWanDimensions(1920, 1080, '480p', WAN_A14B_PIXEL_MULTIPLE)).toEqual({
+ height: 480,
+ width: 848,
+ });
+ });
+
+ it('works from pure aspect-ratio parts, matching real pixels of the same ratio', () => {
+ const fromParts = scaleAndSnapWanDimensions(16, 9, '720p', WAN_A14B_PIXEL_MULTIPLE);
+ const fromPixels = scaleAndSnapWanDimensions(3840, 2160, '720p', WAN_A14B_PIXEL_MULTIPLE);
+
+ expect(fromParts).toEqual(fromPixels);
+ expect(fromParts).toEqual({ height: 720, width: 1280 });
+ });
+
+ it('handles portrait sources (short side is the width)', () => {
+ expect(scaleAndSnapWanDimensions(1080, 1920, '480p', WAN_A14B_PIXEL_MULTIPLE)).toEqual({
+ height: 848,
+ width: 480,
+ });
+ });
+
+ it('snaps to the TI2V grid of 32 with banker’s rounding, matching the backend', () => {
+ // 720 / 32 = 22.5: Python round() gives 22 (half-to-even), not 23.
+ expect(scaleAndSnapWanDimensions(1920, 1080, '720p', WAN_TI2V_PIXEL_MULTIPLE)).toEqual({
+ height: 704,
+ width: 1280,
+ });
+ });
+
+ it('returns null for degenerate inputs', () => {
+ expect(scaleAndSnapWanDimensions(0, 1080, '720p', WAN_A14B_PIXEL_MULTIPLE)).toBeNull();
+ expect(scaleAndSnapWanDimensions(-16, 9, '720p', WAN_A14B_PIXEL_MULTIPLE)).toBeNull();
+ expect(scaleAndSnapWanDimensions(Number.NaN, 9, '720p', WAN_A14B_PIXEL_MULTIPLE)).toBeNull();
+ });
+});
+
+describe('resolveMiniMaxH3Canvas', () => {
+ it('gives the native square canvas for 1:1', () => {
+ expect(resolveMiniMaxH3Canvas(1, 1, '768 highres')).toEqual({ height: 768, width: 768 });
+ });
+
+ it('applies the 768x1344 area cap before snapping (16:9 lands on 1344x768)', () => {
+ expect(resolveMiniMaxH3Canvas(16, 9, '768 highres')).toEqual({ height: 768, width: 1344 });
+ expect(resolveMiniMaxH3Canvas(9, 16, '768 highres')).toEqual({ height: 1344, width: 768 });
+ });
+
+ it('keeps sub-cap ratios at a 768 short edge', () => {
+ expect(resolveMiniMaxH3Canvas(4, 3, '768 highres')).toEqual({ height: 768, width: 1024 });
+ expect(resolveMiniMaxH3Canvas(3, 4, '768 highres')).toEqual({ height: 1024, width: 768 });
+ });
+
+ it('pins the long edge to 768 in lowres mode', () => {
+ expect(resolveMiniMaxH3Canvas(2, 3, '768 lowres')).toEqual({ height: 768, width: 512 });
+ expect(resolveMiniMaxH3Canvas(3, 2, '768 lowres')).toEqual({ height: 512, width: 768 });
+ expect(resolveMiniMaxH3Canvas(1, 1, '768 lowres')).toEqual({ height: 768, width: 768 });
+ });
+
+ it('only the ratio matters, not the absolute pixels', () => {
+ expect(resolveMiniMaxH3Canvas(1920, 1080, '768 highres')).toEqual(resolveMiniMaxH3Canvas(16, 9, '768 highres'));
+ });
+
+ it('rejects ratios beyond 1:4 / 4:1 and degenerate inputs', () => {
+ expect(resolveMiniMaxH3Canvas(5, 1, '768 highres')).toBeNull();
+ expect(resolveMiniMaxH3Canvas(1, 5, '768 highres')).toBeNull();
+ expect(resolveMiniMaxH3Canvas(0, 1, '768 highres')).toBeNull();
+ expect(resolveMiniMaxH3Canvas(1, Number.NaN, '768 highres')).toBeNull();
+ // The bounds themselves are accepted.
+ expect(resolveMiniMaxH3Canvas(4, 1, '768 highres')).not.toBeNull();
+ expect(resolveMiniMaxH3Canvas(1, 4, '768 highres')).not.toBeNull();
+ });
+});
+
+describe('aspect ratio helpers', () => {
+ it('parses parts and inverts every offered preset onto another preset', () => {
+ expect(getVideoAspectRatioParts('16:9')).toEqual({ height: 9, width: 16 });
+ expect(invertVideoAspectRatioId('16:9')).toBe('9:16');
+ expect(invertVideoAspectRatioId('9:21')).toBe('21:9');
+ expect(invertVideoAspectRatioId('1:1')).toBe('1:1');
+ });
+});
+
+describe('Wan frame counts', () => {
+ it('accepts only 4n + 1 counts within bounds', () => {
+ expect(isValidWanNumFrames(81)).toBe(true);
+ expect(isValidWanNumFrames(5)).toBe(true);
+ expect(isValidWanNumFrames(80)).toBe(false);
+ expect(isValidWanNumFrames(4)).toBe(false);
+ expect(isValidWanNumFrames(81.5)).toBe(false);
+ });
+
+ it('snaps onto the grid and clamps to the slider bounds', () => {
+ expect(snapWanNumFrames(81)).toBe(81);
+ expect(snapWanNumFrames(80)).toBe(81);
+ expect(snapWanNumFrames(1)).toBe(5);
+ expect(snapWanNumFrames(10_000)).toBe(WAN_NUM_FRAMES_MAX);
+ expect(snapWanNumFrames(Number.NaN)).toBe(WAN_NUM_FRAMES_DEFAULT);
+ expect(isValidWanNumFrames(snapWanNumFrames(123.7))).toBe(true);
+ });
+});
+
+describe('MiniMax H3 frame counts', () => {
+ it('mirrors the backend 17n + 5 grid from 90 to 345, without the still block', () => {
+ expect(MINIMAX_H3_NUM_FRAMES_CHOICES[0]).toBe(90);
+ expect(MINIMAX_H3_NUM_FRAMES_CHOICES[MINIMAX_H3_NUM_FRAMES_CHOICES.length - 1]).toBe(345);
+ expect(MINIMAX_H3_NUM_FRAMES_CHOICES).not.toContain(5);
+
+ for (const choice of MINIMAX_H3_NUM_FRAMES_CHOICES) {
+ expect(choice % 17).toBe(5);
+ }
+
+ expect(MINIMAX_H3_NUM_FRAMES_CHOICES).toContain(MINIMAX_H3_NUM_FRAMES_DEFAULT);
+ });
+
+ it('validates and snaps onto the choice list', () => {
+ expect(isValidMiniMaxH3NumFrames(124)).toBe(true);
+ expect(isValidMiniMaxH3NumFrames(120)).toBe(false);
+ expect(snapMiniMaxH3NumFrames(124)).toBe(124);
+ expect(snapMiniMaxH3NumFrames(100)).toBe(107);
+ expect(snapMiniMaxH3NumFrames(0)).toBe(90);
+ expect(snapMiniMaxH3NumFrames(10_000)).toBe(345);
+ expect(snapMiniMaxH3NumFrames(Number.NaN)).toBe(MINIMAX_H3_NUM_FRAMES_DEFAULT);
+ });
+});
+
+describe('getVideoDurationSeconds', () => {
+ it('matches the backend n / fps labeling and guards degenerate inputs', () => {
+ expect(getVideoDurationSeconds(124, 24)).toBeCloseTo(5.17, 2);
+ expect(getVideoDurationSeconds(81, 16)).toBeCloseTo(5.0625, 4);
+ expect(getVideoDurationSeconds(81, 0)).toBeNull();
+ expect(getVideoDurationSeconds(Number.NaN, 16)).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/video/core/dimensions.ts b/invokeai/frontend/webv2/src/features/video/core/dimensions.ts
new file mode 100644
index 0000000000..294c5b6bc1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/video/core/dimensions.ts
@@ -0,0 +1,224 @@
+import type { MiniMaxH3TargetResolution, VideoAspectRatioId, WanTargetResolution } from './types';
+
+/**
+ * Client-side ports of the backend's video canvas math, so the panel can show
+ * and validate the exact dimensions a graph will run at without extra nodes:
+ *
+ * - Wan: `_scale_and_snap` in `invokeai/app/invocations/wan_ideal_dimensions.py`
+ * ("nearest" rounding — the node default; the other modes are workflow-only).
+ * - MiniMax H3: `resolve_canvas_size` in `invokeai/backend/minimax_h3/packing.py`
+ * and `resolve_lowres_canvas_size` in `invokeai/backend/minimax_h3/presets.py`.
+ *
+ * Where the backend raises, these return null: the panel falls back to defaults
+ * and reports the problem through `getVideoValidationReasons` instead of throwing.
+ */
+
+export interface VideoDimensions {
+ width: number;
+ height: number;
+}
+
+// Python's round() (used by both backend implementations) is half-to-even;
+// Math.round is half-up. The ports must agree with the backend on exact .5
+// quotients (e.g. 720 / 32 = 22.5) or panel and workflow dims would differ.
+const roundHalfToEven = (value: number): number => {
+ const floor = Math.floor(value);
+ const diff = value - floor;
+
+ if (diff > 0.5) {
+ return floor + 1;
+ }
+
+ if (diff < 0.5) {
+ return floor;
+ }
+
+ return floor % 2 === 0 ? floor : floor + 1;
+};
+
+const snapToMultiple = (value: number, multiple: number): number =>
+ Math.max(multiple, roundHalfToEven(value / multiple) * multiple);
+
+/** Pixel-grid multiple = 2 (transformer patch) × VAE spatial scale. */
+export const WAN_A14B_PIXEL_MULTIPLE = 16;
+export const WAN_TI2V_PIXEL_MULTIPLE = 32;
+
+/** Short-side pixel count for each Wan preset ("p" names the short dimension). */
+export const WAN_TARGET_RESOLUTION_PX: Record<WanTargetResolution, number> = {
+ '480p': 480,
+ '720p': 720,
+ '1080p': 1080,
+};
+
+/**
+ * Scale a source W×H so its shorter side equals the preset's pixel count, then
+ * snap each dimension to the Wan pixel grid (nearest). Only the ratio of the
+ * inputs matters, so aspect-ratio parts (16, 9) work as well as real pixels.
+ * Null when the inputs are non-positive or non-finite.
+ *
+ * Deliberate divergence from the backend node: `_scale_and_snap` rejects
+ * sources whose RAW long side is under one grid cell, which would also reject
+ * pure ratio parts like (16, 9) on the ×32 grid. Since only the ratio matters
+ * and scaling happens before snapping, tiny-but-well-formed inputs are
+ * accepted here — the scaled long side is always ≥ the target short side.
+ */
+export const scaleAndSnapWanDimensions = (
+ width: number,
+ height: number,
+ targetResolution: WanTargetResolution,
+ multiple: number
+): VideoDimensions | null => {
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
+ return null;
+ }
+
+ const targetShortSide = WAN_TARGET_RESOLUTION_PX[targetResolution];
+ const scale = targetShortSide / Math.min(width, height);
+
+ return {
+ height: snapToMultiple(height * scale, multiple),
+ width: snapToMultiple(width * scale, multiple),
+ };
+};
+
+export const MINIMAX_H3_SHORT_EDGE = 768;
+export const MINIMAX_H3_MAX_PIXELS = 768 * 1344;
+export const MINIMAX_H3_CANVAS_MULTIPLE = 32;
+export const MINIMAX_H3_MIN_ASPECT_RATIO = 1 / 4;
+export const MINIMAX_H3_MAX_ASPECT_RATIO = 4;
+
+/**
+ * The MiniMax H3 canvas for an aspect ratio. "768 highres" is the released
+ * pipeline's policy: short edge 768, soft area cap of 768×1344, both axes then
+ * rounded to the nearest multiple of 32 (so the final area may sit slightly
+ * above the pre-rounding budget). "768 lowres" pins the LONG edge to 768
+ * instead for cheaper preview renders. Only the ratio of the inputs matters.
+ * Null when the inputs are degenerate or the ratio is outside H3's supported
+ * 1:4 – 4:1 range.
+ */
+export const resolveMiniMaxH3Canvas = (
+ width: number,
+ height: number,
+ targetResolution: MiniMaxH3TargetResolution
+): VideoDimensions | null => {
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
+ return null;
+ }
+
+ const ratio = width / height;
+
+ if (ratio < MINIMAX_H3_MIN_ASPECT_RATIO || ratio > MINIMAX_H3_MAX_ASPECT_RATIO) {
+ return null;
+ }
+
+ let rawWidth: number;
+ let rawHeight: number;
+
+ if (targetResolution === '768 lowres') {
+ // Long edge pinned to 768; area always sits far below the cap.
+ if (ratio >= 1) {
+ rawWidth = MINIMAX_H3_SHORT_EDGE;
+ rawHeight = MINIMAX_H3_SHORT_EDGE / ratio;
+ } else {
+ rawWidth = MINIMAX_H3_SHORT_EDGE * ratio;
+ rawHeight = MINIMAX_H3_SHORT_EDGE;
+ }
+ } else {
+ if (ratio >= 1) {
+ rawWidth = MINIMAX_H3_SHORT_EDGE * ratio;
+ rawHeight = MINIMAX_H3_SHORT_EDGE;
+ } else {
+ rawWidth = MINIMAX_H3_SHORT_EDGE;
+ rawHeight = MINIMAX_H3_SHORT_EDGE / ratio;
+ }
+
+ const area = rawWidth * rawHeight;
+
+ if (area > MINIMAX_H3_MAX_PIXELS) {
+ const scale = Math.sqrt(MINIMAX_H3_MAX_PIXELS / area);
+ rawWidth *= scale;
+ rawHeight *= scale;
+ }
+ }
+
+ return {
+ height: snapToMultiple(rawHeight, MINIMAX_H3_CANVAS_MULTIPLE),
+ width: snapToMultiple(rawWidth, MINIMAX_H3_CANVAS_MULTIPLE),
+ };
+};
+
+/** The width/height parts of a preset ratio, for feeding the canvas resolvers. */
+export const getVideoAspectRatioParts = (id: VideoAspectRatioId): VideoDimensions => {
+ const [width = 1, height = 1] = id.split(':').map(Number);
+
+ return { height, width };
+};
+
+/** The portrait/landscape mirror of a preset; every offered ratio has one. */
+export const invertVideoAspectRatioId = (id: VideoAspectRatioId): VideoAspectRatioId => {
+ const { width, height } = getVideoAspectRatioParts(id);
+
+ return `${height}:${width}` as VideoAspectRatioId;
+};
+
+// Wan's VAE compresses 4 pixel frames into 1 latent frame, so (n - 1) % 4 == 0.
+// 81 frames (5 s at 16 fps) is the training default; the slider allows up to
+// twice that, but coherence degrades past 81 as temporal RoPE leaves its
+// training distribution — the docs recommend chaining extends instead.
+export const WAN_NUM_FRAMES_MIN = 5;
+export const WAN_NUM_FRAMES_MAX = 161;
+export const WAN_NUM_FRAMES_STEP = 4;
+export const WAN_NUM_FRAMES_DEFAULT = 81;
+
+export const WAN_FPS_MIN = 1;
+export const WAN_FPS_MAX = 120;
+export const WAN_FPS_DEFAULT = 16;
+
+export const isValidWanNumFrames = (numFrames: number): boolean =>
+ Number.isInteger(numFrames) && numFrames >= WAN_NUM_FRAMES_MIN && (numFrames - 1) % WAN_NUM_FRAMES_STEP === 0;
+
+export const snapWanNumFrames = (numFrames: number): number => {
+ if (!Number.isFinite(numFrames)) {
+ return WAN_NUM_FRAMES_DEFAULT;
+ }
+
+ const clamped = Math.min(WAN_NUM_FRAMES_MAX, Math.max(WAN_NUM_FRAMES_MIN, numFrames));
+
+ return Math.round((clamped - 1) / WAN_NUM_FRAMES_STEP) * WAN_NUM_FRAMES_STEP + 1;
+};
+
+export const MINIMAX_H3_FPS = 24;
+
+// The 17n + 5 grid points the H3 video VAE can encode, from the accepted
+// 3.75 s floor to the 15 s ceiling. Mirrors MINIMAX_H3_VIDEO_FRAME_CHOICES in
+// invokeai/backend/minimax_h3/presets.py; the 5-frame still-image block is
+// deliberately absent — the panel generates video, not stills.
+export const MINIMAX_H3_NUM_FRAMES_CHOICES: readonly number[] = Array.from({ length: 16 }, (_, i) => 90 + i * 17);
+export const MINIMAX_H3_NUM_FRAMES_DEFAULT = 124;
+
+export const isValidMiniMaxH3NumFrames = (numFrames: number): boolean =>
+ MINIMAX_H3_NUM_FRAMES_CHOICES.includes(numFrames);
+
+export const snapMiniMaxH3NumFrames = (numFrames: number): number => {
+ if (!Number.isFinite(numFrames)) {
+ return MINIMAX_H3_NUM_FRAMES_DEFAULT;
+ }
+
+ let best = MINIMAX_H3_NUM_FRAMES_DEFAULT;
+ let bestDistance = Number.POSITIVE_INFINITY;
+
+ for (const choice of MINIMAX_H3_NUM_FRAMES_CHOICES) {
+ const distance = Math.abs(choice - numFrames);
+
+ if (distance < bestDistance) {
+ best = choice;
+ bestDistance = distance;
+ }
+ }
+
+ return best;
+};
+
+/** Clip length in seconds; matches the backend's `n / fps` labeling. */
+export const getVideoDurationSeconds = (numFrames: number, fps: number): number | null =>
+ Number.isFinite(numFrames) && Number.isFinite(fps) && fps > 0 && numFrames >= 0 ? numFrames / fps : null;
diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
new file mode 100644
index 0000000000..b8e5167d13
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
@@ -0,0 +1,171 @@
+import { describe, expect, it } from 'vitest';
+
+import type { VideoSettings } from './types';
+
+import {
+ cloneVideoWidgetValues,
+ isVideoSettings,
+ isVideoSourceClip,
+ normalizeVideoSettings,
+ normalizeVideoWidgetValues,
+ resolveVideoMode,
+} from './settings';
+import { getDefaultVideoSettings } from './videoPolicies';
+
+const FIRST_FRAME = { height: 1080, image_name: 'first.png', width: 1920 };
+const LAST_FRAME = { height: 1080, image_name: 'last.png', width: 1920 };
+const SOURCE_VIDEO = {
+ endFrame: -2,
+ fps: 16,
+ height: 480,
+ numFrames: 81,
+ startFrame: 0,
+ video_name: 'clip.mp4',
+ width: 832,
+};
+
+const createSettings = (overrides: Partial<VideoSettings> = {}): VideoSettings => ({
+ ...getDefaultVideoSettings(),
+ ...overrides,
+});
+
+describe('resolveVideoMode', () => {
+ it('infers the mode from which inputs are filled', () => {
+ expect(resolveVideoMode(createSettings())).toBe('txt2vid');
+ expect(resolveVideoMode(createSettings({ firstFrameImage: FIRST_FRAME }))).toBe('first-frame');
+ expect(resolveVideoMode(createSettings({ firstFrameImage: FIRST_FRAME, lastFrameImage: LAST_FRAME }))).toBe(
+ 'first-last'
+ );
+ expect(resolveVideoMode(createSettings({ lastFrameImage: LAST_FRAME }))).toBe('last-frame');
+ expect(resolveVideoMode(createSettings({ sourceVideo: SOURCE_VIDEO }))).toBe('extend');
+ // A last frame with a source video is still extend — it is the destination anchor.
+ expect(resolveVideoMode(createSettings({ lastFrameImage: LAST_FRAME, sourceVideo: SOURCE_VIDEO }))).toBe('extend');
+ });
+});
+
+describe('normalizeVideoSettings', () => {
+ it('round-trips canonical settings', () => {
+ const settings = createSettings({ firstFrameImage: FIRST_FRAME, positivePrompt: 'a cat' });
+ const normalized = normalizeVideoSettings(settings);
+
+ expect(normalized).toEqual(settings);
+ expect(isVideoSettings(settings)).toBe(true);
+ });
+
+ it('rejects values missing the core shape', () => {
+ expect(normalizeVideoSettings(null)).toBeNull();
+ expect(normalizeVideoSettings({})).toBeNull();
+ expect(normalizeVideoSettings({ ...createSettings(), numFrames: 'many' })).toBeNull();
+ expect(normalizeVideoSettings({ ...createSettings(), positivePrompt: 7 })).toBeNull();
+ });
+
+ it('fills fields older persisted projects predate with defaults', () => {
+ const legacy: Record<string, unknown> = {
+ cfgScale: 5,
+ fps: 16,
+ modelKey: 'wan-key',
+ negativePrompt: '',
+ numFrames: 81,
+ positivePrompt: 'a dog',
+ seed: 123,
+ shouldRandomizeSeed: false,
+ steps: 40,
+ };
+ const normalized = normalizeVideoSettings(legacy);
+
+ expect(normalized).not.toBeNull();
+ expect(normalized?.aspectRatioId).toBe('16:9');
+ expect(normalized?.targetResolution).toBe('720p');
+ expect(normalized?.firstFrameImage).toBeNull();
+ expect(normalized?.sourceVideo).toBeNull();
+ expect(normalized?.loras).toEqual([]);
+ expect(normalized?.lightningEnabled).toBe(false);
+ expect(normalized?.positivePrompt).toBe('a dog');
+ });
+
+ it('drops malformed media values instead of failing wholesale', () => {
+ const normalized = normalizeVideoSettings({
+ ...createSettings(),
+ firstFrameImage: { image_name: 'x.png' },
+ sourceVideo: { video_name: 'clip.mp4' },
+ });
+
+ expect(normalized?.firstFrameImage).toBeNull();
+ expect(normalized?.sourceVideo).toBeNull();
+ });
+
+ it('clears a Lightning flag whose LoRAs are gone — the flag means the pair is active', () => {
+ const styleLora = {
+ isEnabled: true,
+ model: { base: 'wan', key: 'style', name: 'Style LoRA', type: 'lora' as const },
+ weight: 1,
+ };
+ const lightningLora = {
+ isEnabled: true,
+ model: { base: 'wan', key: 'lit', name: 'Wan Lightning High Noise', type: 'lora' as const },
+ weight: 1,
+ };
+
+ expect(normalizeVideoSettings({ ...createSettings(), lightningEnabled: true, loras: [] })?.lightningEnabled).toBe(
+ false
+ );
+ expect(
+ normalizeVideoSettings({ ...createSettings(), lightningEnabled: true, loras: [styleLora] })?.lightningEnabled
+ ).toBe(false);
+ expect(
+ normalizeVideoSettings({ ...createSettings(), lightningEnabled: true, loras: [lightningLora] })?.lightningEnabled
+ ).toBe(true);
+ expect(isVideoSettings({ ...createSettings(), lightningEnabled: true, loras: [] })).toBe(false);
+ expect(isVideoSettings({ ...createSettings(), lightningEnabled: true, loras: [lightningLora] })).toBe(true);
+ });
+
+ it('resolves an illegal first-frame + source-video combination in favor of the first frame', () => {
+ const normalized = normalizeVideoSettings({
+ ...createSettings(),
+ firstFrameImage: FIRST_FRAME,
+ sourceVideo: SOURCE_VIDEO,
+ });
+
+ expect(normalized?.firstFrameImage).toEqual(FIRST_FRAME);
+ expect(normalized?.sourceVideo).toBeNull();
+ });
+});
+
+describe('isVideoSettings', () => {
+ it('is strict over the keys normalize would invent', () => {
+ expect(isVideoSettings({ ...createSettings(), aspectRatioId: 'Free' })).toBe(false);
+ expect(isVideoSettings({ ...createSettings(), targetResolution: '4k' })).toBe(false);
+ expect(isVideoSettings({ ...createSettings(), lightningEnabled: 'yes' })).toBe(false);
+ expect(isVideoSettings({ ...createSettings(), firstFrameImage: FIRST_FRAME, sourceVideo: SOURCE_VIDEO })).toBe(
+ false
+ );
+ });
+});
+
+describe('isVideoSourceClip', () => {
+ it('requires the trim and probe fields', () => {
+ expect(isVideoSourceClip(SOURCE_VIDEO)).toBe(true);
+ expect(isVideoSourceClip({ ...SOURCE_VIDEO, fps: undefined })).toBe(false);
+ expect(isVideoSourceClip({ ...SOURCE_VIDEO, video_name: 7 })).toBe(false);
+ });
+});
+
+describe('normalizeVideoWidgetValues / cloneVideoWidgetValues', () => {
+ const model = { base: 'wan', key: 'wan-key', name: 'Wan', type: 'main' as const, variant: 't2v_a14b' };
+
+ it('requires a main model config', () => {
+ expect(normalizeVideoWidgetValues({ ...createSettings(), model })).not.toBeNull();
+ expect(normalizeVideoWidgetValues({ ...createSettings(), model: { key: 'x' } })).toBeNull();
+ });
+
+ it('clones deeply enough that mutating the clone leaves the original untouched', () => {
+ const values = { ...createSettings({ firstFrameImage: FIRST_FRAME, sourceVideo: null }), model };
+ const clone = cloneVideoWidgetValues(values);
+
+ expect(clone).toEqual(values);
+ (clone.firstFrameImage as { image_name: string }).image_name = 'mutated.png';
+ clone.model.key = 'mutated';
+ expect(values.firstFrameImage?.image_name).toBe('first.png');
+ expect(values.model.key).toBe('wan-key');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.ts
new file mode 100644
index 0000000000..7e3a5e14fa
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts
@@ -0,0 +1,252 @@
+import type { GenerateLora, ImageWithDims } from '@features/generation/contracts';
+
+import {
+ DEFAULT_NEGATIVE_PROMPT_HEIGHT_PX,
+ DEFAULT_POSITIVE_PROMPT_HEIGHT_PX,
+ isLoraModelConfig,
+ isMainModelConfig,
+ isModelIdentifierConfig,
+ isVaeModelConfig,
+ MAX_NEGATIVE_PROMPT_HEIGHT_PX,
+ MAX_POSITIVE_PROMPT_HEIGHT_PX,
+ MIN_NEGATIVE_PROMPT_HEIGHT_PX,
+ MIN_POSITIVE_PROMPT_HEIGHT_PX,
+ sanitizeBatchCount,
+} from '@features/generation/settings';
+
+import type {
+ MiniMaxH3TargetResolution,
+ VideoAspectRatioId,
+ VideoGenerationMode,
+ VideoSettings,
+ VideoSourceClip,
+ VideoTargetResolution,
+ VideoWidgetValues,
+ WanTargetResolution,
+} from './types';
+
+const isRecord = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object';
+
+const hasFiniteNumber = (record: Record<string, unknown>, key: string): boolean =>
+ typeof record[key] === 'number' && Number.isFinite(record[key]);
+
+const getClampedNumber = (record: Record<string, unknown>, key: string, min: number, max: number, fallback: number) =>
+ hasFiniteNumber(record, key) ? Math.min(Math.max(record[key] as number, min), max) : fallback;
+
+export const VIDEO_ASPECT_RATIO_IDS: readonly VideoAspectRatioId[] = [
+ '21:9',
+ '16:9',
+ '3:2',
+ '4:3',
+ '1:1',
+ '3:4',
+ '2:3',
+ '9:16',
+ '9:21',
+];
+
+export const isVideoAspectRatioId = (value: unknown): value is VideoAspectRatioId =>
+ typeof value === 'string' && (VIDEO_ASPECT_RATIO_IDS as readonly string[]).includes(value);
+
+export const WAN_TARGET_RESOLUTIONS: readonly WanTargetResolution[] = ['480p', '720p', '1080p'];
+export const MINIMAX_H3_TARGET_RESOLUTIONS: readonly MiniMaxH3TargetResolution[] = ['768 highres', '768 lowres'];
+
+export const isVideoTargetResolution = (value: unknown): value is VideoTargetResolution =>
+ typeof value === 'string' &&
+ ((WAN_TARGET_RESOLUTIONS as readonly string[]).includes(value) ||
+ (MINIMAX_H3_TARGET_RESOLUTIONS as readonly string[]).includes(value));
+
+export const isImageWithDims = (value: unknown): value is ImageWithDims =>
+ isRecord(value) &&
+ typeof value.image_name === 'string' &&
+ hasFiniteNumber(value, 'width') &&
+ hasFiniteNumber(value, 'height');
+
+export const isVideoSourceClip = (value: unknown): value is VideoSourceClip =>
+ isRecord(value) &&
+ typeof value.video_name === 'string' &&
+ hasFiniteNumber(value, 'width') &&
+ hasFiniteNumber(value, 'height') &&
+ hasFiniteNumber(value, 'numFrames') &&
+ hasFiniteNumber(value, 'fps') &&
+ hasFiniteNumber(value, 'startFrame') &&
+ hasFiniteNumber(value, 'endFrame');
+
+const isVideoLora = (value: unknown): value is GenerateLora =>
+ isRecord(value) &&
+ isLoraModelConfig(value.model) &&
+ hasFiniteNumber(value, 'weight') &&
+ typeof value.isEnabled === 'boolean';
+
+/** A Wan Lightning distillation LoRA, identified by name (they carry no dedicated taxonomy). */
+export const isWanLightningLora = (model: { base: string; name: string }): boolean =>
+ model.base === 'wan' && /lightning/i.test(model.name);
+
+const hasLightningLora = (loras: readonly GenerateLora[]): boolean =>
+ loras.some((lora) => isWanLightningLora(lora.model));
+
+/**
+ * Which inputs are filled decides the mode; there is no mode selector. A first
+ * frame and a source video never coexist (normalization and the setters both
+ * enforce it), and a last frame refines whichever mode its partner implies:
+ * with a first frame it becomes FLF2V interpolation, with a source video it is
+ * the destination the extension should land on.
+ */
+export const resolveVideoMode = (
+ settings: Pick<VideoSettings, 'firstFrameImage' | 'lastFrameImage' | 'sourceVideo'>
+): VideoGenerationMode => {
+ if (settings.sourceVideo) {
+ return 'extend';
+ }
+
+ if (settings.firstFrameImage) {
+ return settings.lastFrameImage ? 'first-last' : 'first-frame';
+ }
+
+ return settings.lastFrameImage ? 'last-frame' : 'txt2vid';
+};
+
+/**
+ * The fields of `VideoSettings` that describe how the panel is arranged rather
+ * than what will be generated. Mirrors `GENERATE_UI_STATE_KEYS`.
+ */
+export const VIDEO_UI_STATE_KEYS = {
+ batchCount: true,
+ negativePromptHeightPx: true,
+ positivePromptHeightPx: true,
+} satisfies Partial<Record<keyof VideoSettings, true>>;
+
+/**
+ * Validate stored widget values and fill in fields that older persisted
+ * projects predate. The core fields must be present and well-typed; newer
+ * fields fall back to their defaults so old projects keep their prompts and
+ * frame counts instead of being reset wholesale.
+ */
+export const normalizeVideoSettings = (values: unknown): VideoSettings | null => {
+ if (!isRecord(values)) {
+ return null;
+ }
+
+ const isCoreShapeValid =
+ typeof values.modelKey === 'string' &&
+ typeof values.positivePrompt === 'string' &&
+ typeof values.negativePrompt === 'string' &&
+ typeof values.shouldRandomizeSeed === 'boolean' &&
+ ['numFrames', 'fps', 'steps', 'cfgScale', 'seed'].every((key) => hasFiniteNumber(values, key));
+
+ if (!isCoreShapeValid) {
+ return null;
+ }
+
+ const firstFrameImage = isImageWithDims(values.firstFrameImage) ? values.firstFrameImage : null;
+ // A first frame and a source video are mutually exclusive; if a stale
+ // project somehow holds both, the first frame wins deterministically.
+ const sourceVideo = !firstFrameImage && isVideoSourceClip(values.sourceVideo) ? values.sourceVideo : null;
+ const loras = Array.isArray(values.loras) ? values.loras.filter(isVideoLora) : [];
+
+ return {
+ aspectRatioId: isVideoAspectRatioId(values.aspectRatioId) ? values.aspectRatioId : '16:9',
+ batchCount: sanitizeBatchCount(values.batchCount),
+ cfgScale: values.cfgScale as number,
+ cfgScaleLowNoise: hasFiniteNumber(values, 'cfgScaleLowNoise') ? (values.cfgScaleLowNoise as number) : null,
+ firstFrameImage,
+ fps: values.fps as number,
+ h3TextEncoderModel: isModelIdentifierConfig(values.h3TextEncoderModel) ? values.h3TextEncoderModel : null,
+ h3TransformerModel: isMainModelConfig(values.h3TransformerModel) ? values.h3TransformerModel : null,
+ lastFrameImage: isImageWithDims(values.lastFrameImage) ? values.lastFrameImage : null,
+ // The flag means "the Lightning pair is active": if the LoRAs are gone
+ // (deleted from Concepts, dropped as incompatible), the flag clears with
+ // them rather than claiming a fast path that has nothing behind it.
+ lightningEnabled: values.lightningEnabled === true && hasLightningLora(loras),
+ loras,
+ modelKey: values.modelKey as string,
+ negativePrompt: values.negativePrompt as string,
+ negativePromptEnabled: typeof values.negativePromptEnabled === 'boolean' ? values.negativePromptEnabled : true,
+ negativePromptHeightPx: getClampedNumber(
+ values,
+ 'negativePromptHeightPx',
+ MIN_NEGATIVE_PROMPT_HEIGHT_PX,
+ MAX_NEGATIVE_PROMPT_HEIGHT_PX,
+ DEFAULT_NEGATIVE_PROMPT_HEIGHT_PX
+ ),
+ numFrames: values.numFrames as number,
+ positivePrompt: values.positivePrompt as string,
+ positivePromptHeightPx: getClampedNumber(
+ values,
+ 'positivePromptHeightPx',
+ MIN_POSITIVE_PROMPT_HEIGHT_PX,
+ MAX_POSITIVE_PROMPT_HEIGHT_PX,
+ DEFAULT_POSITIVE_PROMPT_HEIGHT_PX
+ ),
+ seed: values.seed as number,
+ shouldRandomizeSeed: values.shouldRandomizeSeed as boolean,
+ sourceVideo,
+ steps: values.steps as number,
+ targetResolution: isVideoTargetResolution(values.targetResolution) ? values.targetResolution : '720p',
+ vae: isVaeModelConfig(values.vae) ? values.vae : null,
+ wanLowNoiseModel: isMainModelConfig(values.wanLowNoiseModel) ? values.wanLowNoiseModel : null,
+ wanT5EncoderModel: isModelIdentifierConfig(values.wanT5EncoderModel) ? values.wanT5EncoderModel : null,
+ componentSourceModel: isMainModelConfig(values.componentSourceModel) ? values.componentSourceModel : null,
+ };
+};
+
+export const isVideoSettings = (values: unknown): values is VideoSettings => {
+ const normalized = normalizeVideoSettings(values);
+
+ if (!normalized || !isRecord(values)) {
+ return false;
+ }
+
+ // Strict only over the keys normalize would have to invent.
+ return (
+ isVideoAspectRatioId(values.aspectRatioId) &&
+ isVideoTargetResolution(values.targetResolution) &&
+ typeof values.negativePromptEnabled === 'boolean' &&
+ typeof values.lightningEnabled === 'boolean' &&
+ (values.lightningEnabled === false ||
+ (Array.isArray(values.loras) && hasLightningLora(values.loras.filter(isVideoLora)))) &&
+ hasFiniteNumber(values, 'negativePromptHeightPx') &&
+ hasFiniteNumber(values, 'positivePromptHeightPx') &&
+ (values.cfgScaleLowNoise === null || hasFiniteNumber(values, 'cfgScaleLowNoise')) &&
+ (values.firstFrameImage === null || isImageWithDims(values.firstFrameImage)) &&
+ (values.lastFrameImage === null || isImageWithDims(values.lastFrameImage)) &&
+ (values.sourceVideo === null || isVideoSourceClip(values.sourceVideo)) &&
+ !(values.firstFrameImage !== null && values.sourceVideo !== null) &&
+ Array.isArray(values.loras) &&
+ values.loras.every(isVideoLora) &&
+ (values.vae === null || isVaeModelConfig(values.vae)) &&
+ (values.wanT5EncoderModel === null || isModelIdentifierConfig(values.wanT5EncoderModel)) &&
+ (values.wanLowNoiseModel === null || isMainModelConfig(values.wanLowNoiseModel)) &&
+ (values.componentSourceModel === null || isMainModelConfig(values.componentSourceModel)) &&
+ (values.h3TransformerModel === null || isMainModelConfig(values.h3TransformerModel)) &&
+ (values.h3TextEncoderModel === null || isModelIdentifierConfig(values.h3TextEncoderModel))
+ );
+};
+
+export const normalizeVideoWidgetValues = (values: unknown): VideoWidgetValues | null => {
+ const settings = normalizeVideoSettings(values);
+
+ if (!settings || !isRecord(values) || !isMainModelConfig(values.model)) {
+ return null;
+ }
+
+ return { ...settings, model: values.model };
+};
+
+export const isVideoWidgetValues = (values: unknown): values is VideoWidgetValues =>
+ isVideoSettings(values) && isMainModelConfig((values as unknown as Record<string, unknown>).model);
+
+export const cloneVideoWidgetValues = (values: VideoWidgetValues): VideoWidgetValues & Record<string, unknown> => ({
+ ...values,
+ componentSourceModel: values.componentSourceModel ? { ...values.componentSourceModel } : null,
+ firstFrameImage: values.firstFrameImage ? { ...values.firstFrameImage } : null,
+ h3TextEncoderModel: values.h3TextEncoderModel ? { ...values.h3TextEncoderModel } : null,
+ h3TransformerModel: values.h3TransformerModel ? { ...values.h3TransformerModel } : null,
+ lastFrameImage: values.lastFrameImage ? { ...values.lastFrameImage } : null,
+ loras: values.loras.map((lora) => ({ ...lora, model: { ...lora.model } })),
+ model: { ...values.model },
+ sourceVideo: values.sourceVideo ? { ...values.sourceVideo } : null,
+ vae: values.vae ? { ...values.vae } : null,
+ wanLowNoiseModel: values.wanLowNoiseModel ? { ...values.wanLowNoiseModel } : null,
+ wanT5EncoderModel: values.wanT5EncoderModel ? { ...values.wanT5EncoderModel } : null,
+});
diff --git a/invokeai/frontend/webv2/src/features/video/core/types.ts b/invokeai/frontend/webv2/src/features/video/core/types.ts
new file mode 100644
index 0000000000..78e4008108
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/video/core/types.ts
@@ -0,0 +1,91 @@
+import type {
+ GenerateLora,
+ ImageWithDims,
+ MainModelConfig,
+ ModelIdentifierConfig,
+ VaeModelConfig,
+} from '@features/generation/contracts';
+
+/**
+ * How a video generation is conditioned. There is no explicit mode selector:
+ * the mode is inferred from which inputs are filled — see `resolveVideoMode`.
+ */
+export type VideoGenerationMode = 'txt2vid' | 'first-frame' | 'last-frame' | 'first-last' | 'extend';
+
+/** A gallery video selected as the clip to extend, with the trim range to keep. */
+export interface VideoSourceClip {
+ video_name: string;
+ width: number;
+ height: number;
+ numFrames: number;
+ fps: number;
+ /** Inclusive trim bounds forwarded to `extract_video_range`; negative indices count from the end. */
+ startFrame: number;
+ endFrame: number;
+}
+
+export type WanTargetResolution = '480p' | '720p' | '1080p';
+export type MiniMaxH3TargetResolution = '768 highres' | '768 lowres';
+export type VideoTargetResolution = WanTargetResolution | MiniMaxH3TargetResolution;
+
+/**
+ * The preset ratios the video panel offers. No `Free` and no width/height
+ * fields: pixel dimensions are always derived — from this ratio plus the
+ * target-resolution preset in text-to-video, or from the conditioning media's
+ * own ratio once a frame or source video is set.
+ */
+export type VideoAspectRatioId = '21:9' | '16:9' | '3:2' | '4:3' | '1:1' | '3:4' | '2:3' | '9:16' | '9:21';
+
+/** Project-persisted settings owned by the Video widget. */
+export interface VideoSettings {
+ batchCount: number;
+ modelKey: string;
+ positivePrompt: string;
+ positivePromptHeightPx: number;
+ negativePromptEnabled: boolean;
+ negativePrompt: string;
+ negativePromptHeightPx: number;
+ /** Image-to-video conditioning. Mutually exclusive with `sourceVideo`. */
+ firstFrameImage: ImageWithDims | null;
+ /**
+ * The frame the clip should end on: FLF2V interpolation with a first frame,
+ * or the destination image when extending a source video. Combines with
+ * either `firstFrameImage` or `sourceVideo`.
+ */
+ lastFrameImage: ImageWithDims | null;
+ /** The clip to extend. Mutually exclusive with `firstFrameImage`. */
+ sourceVideo: VideoSourceClip | null;
+ aspectRatioId: VideoAspectRatioId;
+ targetResolution: VideoTargetResolution;
+ numFrames: number;
+ fps: number;
+ steps: number;
+ cfgScale: number;
+ /** Guidance for the low-noise half of a Wan A14B schedule; null reuses `cfgScale`. */
+ cfgScaleLowNoise: number | null;
+ /**
+ * Wan A14B fast path: the Lightning distillation LoRA pair at 4 steps and
+ * CFG 1. Toggling it patches steps/CFG and the `loras` list — see
+ * `getLightningToggleResult` — so the flag records intent, not hidden state.
+ */
+ lightningEnabled: boolean;
+ seed: number;
+ shouldRandomizeSeed: boolean;
+ loras: GenerateLora[];
+ /** Optional VAE override; null uses the VAE bundled with the main model or component source. */
+ vae: VaeModelConfig | null;
+ /** Wan 2.2's UMT5-XXL text encoder. */
+ wanT5EncoderModel: ModelIdentifierConfig | null;
+ /** The low-noise expert of a Wan 2.2 A14B mixture-of-experts pair. */
+ wanLowNoiseModel: MainModelConfig | null;
+ /** Optional Diffusers main model used as a component source for split/quantized Wan models. */
+ componentSourceModel: MainModelConfig | null;
+ /** Optional single-file MiniMax H3 transformer override (e.g. the pruned int8 repack). */
+ h3TransformerModel: MainModelConfig | null;
+ /** Optional single-file MiniMax H3 Qwen3-VL text-encoder override. */
+ h3TextEncoderModel: ModelIdentifierConfig | null;
+}
+
+export interface VideoWidgetValues extends VideoSettings {
+ model: MainModelConfig;
+}
diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts
new file mode 100644
index 0000000000..219380f480
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts
@@ -0,0 +1,656 @@
+import type { GenerationModelCatalogItem, MainModelConfig } from '@features/generation/contracts';
+
+import { describe, expect, it } from 'vitest';
+
+import type { VideoSettings } from './types';
+
+import {
+ findWanLightningLoraPair,
+ getDefaultVideoSettings,
+ getLightningToggleResult,
+ getVideoComponentSectionPolicy,
+ getVideoDimensions,
+ getVideoModelAvailabilityReasons,
+ getVideoModelPolicy,
+ getVideoModelSelectionResult,
+ getVideoModes,
+ getVideoPromptPolicy,
+ getVideoValidationReasons,
+ isSupportedVideoModel,
+ isValidVideoNumFrames,
+ snapVideoNumFrames,
+ WAN_LIGHTNING_SAMPLING,
+} from './videoPolicies';
+
+const wanModel = (variant: string, format = 'gguf_quantized', key = `wan-${variant}-${format}`): MainModelConfig => ({
+ base: 'wan',
+ format,
+ key,
+ name: `Wan 2.2 ${variant}`,
+ type: 'main',
+ variant,
+});
+
+const h3Model = (format = 'diffusers', key = `h3-${format}`): MainModelConfig => ({
+ base: 'minimax-h3',
+ format,
+ key,
+ name: 'MiniMax H3',
+ type: 'main',
+ variant: 'fl2va',
+});
+
+const lora = (name: string, variant: string | null = 'a14b', key = `lora-${name}`): GenerationModelCatalogItem => ({
+ base: 'wan',
+ key,
+ name,
+ type: 'lora',
+ variant,
+});
+
+const LIGHTNING_T2V_HIGH = lora('Wan 2.2 T2V Lightning High Noise (4-step)');
+const LIGHTNING_T2V_LOW = lora('Wan 2.2 T2V Lightning Low Noise (4-step)');
+const LIGHTNING_I2V_HIGH = lora('Wan 2.2 I2V Lightning High Noise (4-step)');
+const LIGHTNING_I2V_LOW = lora('Wan 2.2 I2V Lightning Low Noise (4-step)');
+
+const FIRST_FRAME = { height: 1080, image_name: 'first.png', width: 1920 };
+const LAST_FRAME = { height: 1080, image_name: 'last.png', width: 1920 };
+const SOURCE_VIDEO = {
+ endFrame: -2,
+ fps: 16,
+ height: 480,
+ numFrames: 81,
+ startFrame: 0,
+ video_name: 'clip.mp4',
+ width: 832,
+};
+
+const settingsFor = (model?: MainModelConfig, overrides: Partial<VideoSettings> = {}): VideoSettings => ({
+ ...getDefaultVideoSettings(model),
+ ...overrides,
+});
+
+describe('isSupportedVideoModel', () => {
+ it('accepts Wan mains in any format', () => {
+ expect(isSupportedVideoModel(wanModel('t2v_a14b', 'gguf_quantized'))).toBe(true);
+ expect(isSupportedVideoModel(wanModel('i2v_a14b', 'diffusers'))).toBe(true);
+ expect(isSupportedVideoModel(wanModel('ti2v_5b', 'checkpoint'))).toBe(true);
+ });
+
+ it('accepts MiniMax H3 mains only in Diffusers format', () => {
+ expect(isSupportedVideoModel(h3Model('diffusers'))).toBe(true);
+ // Single-file H3 checkpoints are transformer overrides, not selectable mains.
+ expect(isSupportedVideoModel(h3Model('checkpoint'))).toBe(false);
+ });
+
+ it('rejects non-video bases and non-main types', () => {
+ expect(isSupportedVideoModel({ base: 'sdxl', format: 'checkpoint', type: 'main' })).toBe(false);
+ expect(isSupportedVideoModel({ base: 'wan', format: 'checkpoint', type: 'lora' })).toBe(false);
+ });
+});
+
+describe('capabilities matrix', () => {
+ it('gates conditioning modes per Wan variant', () => {
+ expect(getVideoModes(wanModel('t2v_a14b'))).toEqual(['txt2vid']);
+ expect(getVideoModes(wanModel('i2v_a14b'))).toEqual(['first-frame', 'first-last', 'extend']);
+ expect(getVideoModes(wanModel('ti2v_5b'))).toEqual(['txt2vid', 'first-frame', 'extend']);
+ });
+
+ it('gives MiniMax H3 every mode including last-frame-only', () => {
+ expect(getVideoModes(h3Model())).toEqual(['txt2vid', 'first-frame', 'last-frame', 'first-last', 'extend']);
+ });
+
+ it('grants unknown Wan variants permissive A14B capabilities', () => {
+ const unknown = wanModel('some_future_variant');
+
+ expect(getVideoModes(unknown)).toContain('txt2vid');
+ expect(getVideoModes(unknown)).toContain('extend');
+ });
+
+ it('shapes the sampling UI per family', () => {
+ const a14b = getVideoModelPolicy(wanModel('i2v_a14b'), settingsFor(wanModel('i2v_a14b')));
+ const ti2v = getVideoModelPolicy(wanModel('ti2v_5b'), settingsFor(wanModel('ti2v_5b')));
+ const h3 = getVideoModelPolicy(h3Model(), settingsFor(h3Model()));
+
+ expect(a14b.ui).toMatchObject({ cfgLowNoiseVisible: true, cfgVisible: true, fpsVisible: true });
+ expect(a14b.ui.lightningAvailable).toBe(true);
+ expect(a14b.frames).toMatchObject({ defaultValue: 81, kind: 'grid', step: 4 });
+
+ expect(ti2v.ui).toMatchObject({ cfgLowNoiseVisible: false, cfgVisible: true, lightningAvailable: false });
+
+ expect(h3.ui).toMatchObject({
+ audioOutput: true,
+ cfgLowNoiseVisible: false,
+ cfgVisible: false,
+ fpsVisible: false,
+ lightningAvailable: false,
+ });
+ expect(h3.frames.kind).toBe('choices');
+ expect(h3.fps).toMatchObject({ defaultValue: 24, editable: false });
+ expect(h3.defaults.steps).toBe(50);
+ });
+});
+
+describe('frame snapping per model', () => {
+ it('snaps to the Wan 4n + 1 grid and the H3 choice list respectively', () => {
+ expect(snapVideoNumFrames(wanModel('t2v_a14b'), 80)).toBe(81);
+ expect(snapVideoNumFrames(h3Model(), 81)).toBe(90);
+ expect(isValidVideoNumFrames(wanModel('t2v_a14b'), 81)).toBe(true);
+ expect(isValidVideoNumFrames(h3Model(), 81)).toBe(false);
+ expect(isValidVideoNumFrames(h3Model(), 124)).toBe(true);
+ });
+});
+
+describe('getVideoDimensions', () => {
+ it('derives from the aspect-ratio preset in text-to-video', () => {
+ const model = wanModel('t2v_a14b');
+
+ expect(getVideoDimensions(model, settingsFor(model, { aspectRatioId: '16:9', targetResolution: '480p' }))).toEqual({
+ height: 480,
+ source: 'aspect-ratio',
+ width: 848,
+ });
+ });
+
+ it('derives from conditioning media once it is set, ignoring the preset ratio', () => {
+ const model = wanModel('i2v_a14b');
+ const settings = settingsFor(model, {
+ aspectRatioId: '1:1',
+ firstFrameImage: FIRST_FRAME,
+ targetResolution: '720p',
+ });
+
+ expect(getVideoDimensions(model, settings)).toEqual({ height: 720, source: 'first-frame', width: 1280 });
+ });
+
+ it('prefers the source video over frame images, and last frame over the preset', () => {
+ const model = h3Model();
+
+ expect(
+ getVideoDimensions(model, settingsFor(model, { lastFrameImage: LAST_FRAME, sourceVideo: SOURCE_VIDEO }))?.source
+ ).toBe('source-video');
+ expect(getVideoDimensions(model, settingsFor(model, { lastFrameImage: LAST_FRAME }))?.source).toBe('last-frame');
+ });
+
+ it('applies the H3 canvas policy including the area cap', () => {
+ const model = h3Model();
+
+ expect(getVideoDimensions(model, settingsFor(model, { aspectRatioId: '16:9' }))).toEqual({
+ height: 768,
+ source: 'aspect-ratio',
+ width: 1344,
+ });
+ });
+
+ it('coerces a stale target resolution from another family before resolving', () => {
+ const model = h3Model();
+ const settings = settingsFor(model, { targetResolution: '480p' });
+
+ expect(getVideoDimensions(model, settings)).toEqual({ height: 768, source: 'aspect-ratio', width: 1344 });
+ });
+
+ it('returns null for media outside the H3 aspect range', () => {
+ const model = h3Model();
+ const settings = settingsFor(model, {
+ firstFrameImage: { height: 100, image_name: 'strip.png', width: 500 },
+ });
+
+ expect(getVideoDimensions(model, settings)).toBeNull();
+ });
+});
+
+describe('getVideoPromptPolicy', () => {
+ const promptSettings = (overrides: Partial<Parameters<typeof getVideoPromptPolicy>[1]> = {}) => ({
+ cfgScale: 5,
+ cfgScaleLowNoise: null,
+ negativePromptEnabled: true,
+ wanLowNoiseModel: null,
+ ...overrides,
+ });
+
+ it('is cfg-gated for Wan', () => {
+ const model = wanModel('t2v_a14b');
+
+ const atCfg5 = getVideoPromptPolicy(model, promptSettings());
+ const atCfg1 = getVideoPromptPolicy(model, promptSettings({ cfgScale: 1 }));
+
+ expect(atCfg5).toMatchObject({ negativeUsedInGraph: true, negativeVisible: true });
+ expect(atCfg1).toMatchObject({ negativeUsedInGraph: false, negativeVisible: true });
+ expect(atCfg1.negativeHelpText).toMatch(/CFG/);
+ });
+
+ it('counts low-noise CFG > 1 as CFG in use, matching wan_video_denoise do_cfg', () => {
+ const singleFileMain = wanModel('i2v_a14b', 'gguf_quantized');
+ const lowExpert = wanModel('i2v_a14b', 'checkpoint', 'low-expert');
+ const base = promptSettings({ cfgScale: 1, cfgScaleLowNoise: 4 });
+
+ // Low expert wired → the low-noise half runs CFG and consumes the negative prompt.
+ expect(getVideoPromptPolicy(singleFileMain, { ...base, wanLowNoiseModel: lowExpert }).negativeUsedInGraph).toBe(
+ true
+ );
+ // Diffusers A14B mains bundle transformer_2, so the low half exists without a wired expert.
+ expect(getVideoPromptPolicy(wanModel('i2v_a14b', 'diffusers'), base).negativeUsedInGraph).toBe(true);
+ // No second expert at all → the low CFG value never runs.
+ expect(getVideoPromptPolicy(singleFileMain, base).negativeUsedInGraph).toBe(false);
+ // TI2V-5B has no low-noise half regardless of the stale value.
+ expect(getVideoPromptPolicy(wanModel('ti2v_5b', 'diffusers'), base).negativeUsedInGraph).toBe(false);
+ });
+
+ it('never shows a negative prompt for MiniMax H3', () => {
+ expect(getVideoPromptPolicy(h3Model(), promptSettings())).toMatchObject({
+ negativeUsedInGraph: false,
+ negativeVisible: false,
+ });
+ });
+});
+
+describe('Lightning', () => {
+ const model = wanModel('t2v_a14b');
+ const catalog = [LIGHTNING_T2V_HIGH, LIGHTNING_T2V_LOW, LIGHTNING_I2V_HIGH, LIGHTNING_I2V_LOW, lora('Style LoRA')];
+
+ it('finds the installed pair, preferring the main model’s family', () => {
+ expect(findWanLightningLoraPair(catalog, 't2v_a14b')).toMatchObject({
+ high: { key: LIGHTNING_T2V_HIGH.key },
+ low: { key: LIGHTNING_T2V_LOW.key },
+ });
+ expect(findWanLightningLoraPair(catalog, 'i2v_a14b')).toMatchObject({
+ high: { key: LIGHTNING_I2V_HIGH.key },
+ low: { key: LIGHTNING_I2V_LOW.key },
+ });
+ });
+
+ it('falls back across families and rejects incomplete pairs', () => {
+ expect(findWanLightningLoraPair([LIGHTNING_T2V_HIGH, LIGHTNING_T2V_LOW], 'i2v_a14b')).not.toBeNull();
+ expect(findWanLightningLoraPair([LIGHTNING_T2V_HIGH], 't2v_a14b')).toBeNull();
+ // 5B mains never match the A14B Lightning LoRAs.
+ expect(findWanLightningLoraPair(catalog, 'ti2v_5b')).toBeNull();
+ });
+
+ it('matches high/low only as delimited tokens, not inside ordinary words', () => {
+ // "Slow" must not read as a low-noise expert; the pair is incomplete.
+ expect(findWanLightningLoraPair([LIGHTNING_T2V_HIGH, lora('Wan Slow Motion Lightning')], 't2v_a14b')).toBeNull();
+ expect(findWanLightningLoraPair([lora('Thigh-Focus Lightning'), LIGHTNING_T2V_LOW], 't2v_a14b')).toBeNull();
+ // Underscore-delimited release filenames still match.
+ expect(
+ findWanLightningLoraPair(
+ [lora('Wan2.2-Lightning_high_noise_model'), lora('Wan2.2-Lightning_low_noise_model')],
+ 't2v_a14b'
+ )
+ ).not.toBeNull();
+ });
+
+ it("does not let 'i2v' score inside 'TI2V' when preferring a family", () => {
+ // A mistagged (variant-less) TI2V-named pair listed first must not outrank
+ // the true I2V pair for an I2V main.
+ const ti2vHigh = lora('Wan Lightning TI2V-5B High Noise', null);
+ const ti2vLow = lora('Wan Lightning TI2V-5B Low Noise', null);
+
+ expect(
+ findWanLightningLoraPair([ti2vHigh, ti2vLow, LIGHTNING_I2V_HIGH, LIGHTNING_I2V_LOW], 'i2v_a14b')
+ ).toMatchObject({
+ high: { key: LIGHTNING_I2V_HIGH.key },
+ low: { key: LIGHTNING_I2V_LOW.key },
+ });
+ });
+
+ it('toggling on patches sampling and adds the pair to the visible LoRA list', () => {
+ const base = settingsFor(model, {
+ cfgScale: 5,
+ cfgScaleLowNoise: 4,
+ lightningEnabled: false,
+ loras: [],
+ steps: 40,
+ });
+ const result = getLightningToggleResult(base, model, catalog, true);
+
+ expect(result.missingLoras).toBe(false);
+ expect(result.settings).toMatchObject({ ...WAN_LIGHTNING_SAMPLING, lightningEnabled: true });
+ expect(result.settings.loras.map((entry) => entry.model.key)).toEqual([
+ LIGHTNING_T2V_HIGH.key,
+ LIGHTNING_T2V_LOW.key,
+ ]);
+ });
+
+ it('toggling off removes only the Lightning LoRAs and restores model defaults', () => {
+ const on = getLightningToggleResult(settingsFor(model), model, catalog, true).settings;
+ const withStyle = { ...on, loras: [...on.loras, { isEnabled: true, model: lora('Style LoRA'), weight: 0.5 }] };
+ const off = getLightningToggleResult(withStyle as VideoSettings, model, catalog, false).settings;
+
+ expect(off.lightningEnabled).toBe(false);
+ expect(off).toMatchObject({ cfgScale: 5, cfgScaleLowNoise: 4, steps: 40 });
+ expect(off.loras.map((entry) => entry.model.name)).toEqual(['Style LoRA']);
+ });
+
+ it('reports a missing pair instead of enabling silently', () => {
+ const result = getLightningToggleResult(settingsFor(model), model, [], true);
+
+ expect(result.missingLoras).toBe(true);
+ expect(result.settings.lightningEnabled).toBe(false);
+ });
+
+ it('clears a stale enabled flag when the pair has vanished from the catalog', () => {
+ const stale = settingsFor(model, { lightningEnabled: true, steps: 4 });
+ const result = getLightningToggleResult(stale, model, [], true);
+
+ expect(result.missingLoras).toBe(true);
+ expect(result.settings.lightningEnabled).toBe(false);
+ });
+
+ it('defaults Lightning on for A14B when the pair is installed, off otherwise', () => {
+ const withPair = getDefaultVideoSettings(model, catalog);
+ const withoutPair = getDefaultVideoSettings(model, []);
+ const h3Defaults = getDefaultVideoSettings(h3Model(), catalog);
+
+ expect(withPair.lightningEnabled).toBe(true);
+ expect(withPair.steps).toBe(WAN_LIGHTNING_SAMPLING.steps);
+ expect(withoutPair).toMatchObject({ cfgScale: 5, lightningEnabled: false, steps: 40 });
+ expect(h3Defaults).toMatchObject({ fps: 24, lightningEnabled: false, numFrames: 124, steps: 50 });
+ });
+});
+
+describe('component section policy', () => {
+ it('requires VAE and Wan T5 for split Wan models without a component source', () => {
+ const model = wanModel('i2v_a14b', 'gguf_quantized');
+ const settings = settingsFor(model);
+ const policy = getVideoComponentSectionPolicy(model, settings);
+
+ expect(policy.defaultOpen).toBe(true);
+ expect(policy.slots.map((slot) => slot.key)).toEqual([
+ 'componentSourceModel',
+ 'vae',
+ 'wanT5EncoderModel',
+ 'wanLowNoiseModel',
+ ]);
+
+ const reasons = getVideoValidationReasons(model, { ...settings, firstFrameImage: FIRST_FRAME });
+
+ expect(reasons).toContain('Video needs a VAE for Wan models.');
+ expect(reasons).toContain('Video needs a Wan T5 Encoder for Wan models.');
+ });
+
+ it('is satisfied by a Diffusers component source or a Diffusers main', () => {
+ const gguf = wanModel('i2v_a14b', 'gguf_quantized');
+ const withSource = settingsFor(gguf, {
+ componentSourceModel: wanModel('i2v_a14b', 'diffusers'),
+ firstFrameImage: FIRST_FRAME,
+ });
+
+ expect(getVideoValidationReasons(gguf, withSource)).toEqual([]);
+
+ const diffusers = wanModel('i2v_a14b', 'diffusers');
+
+ expect(getVideoValidationReasons(diffusers, settingsFor(diffusers, { firstFrameImage: FIRST_FRAME }))).toEqual([]);
+ });
+
+ it('hides the low-noise expert slot for TI2V-5B and for Diffusers mains', () => {
+ const ti2v = wanModel('ti2v_5b', 'checkpoint');
+
+ expect(getVideoComponentSectionPolicy(ti2v, settingsFor(ti2v)).slots.map((slot) => slot.key)).not.toContain(
+ 'wanLowNoiseModel'
+ );
+
+ // A Diffusers A14B main bundles transformer_2; the loader ignores the input.
+ const diffusers = wanModel('i2v_a14b', 'diffusers');
+
+ expect(
+ getVideoComponentSectionPolicy(diffusers, settingsFor(diffusers)).slots.map((slot) => slot.key)
+ ).not.toContain('wanLowNoiseModel');
+ });
+
+ it('constrains the low-noise expert to a different single-file model of the same variant', () => {
+ const model = wanModel('i2v_a14b', 'gguf_quantized');
+ const settings = settingsFor(model);
+ const slot = getVideoComponentSectionPolicy(model, settings).slots.find((s) => s.key === 'wanLowNoiseModel');
+ const ctx = { model, selectedComponents: settings, settings };
+
+ expect(slot?.filter?.(wanModel('i2v_a14b', 'checkpoint', 'low'), ctx)).toBe(true);
+ // Same model as the main is rejected (loader raises on identical keys).
+ expect(slot?.filter?.(model, ctx)).toBe(false);
+ // Diffusers-format experts are rejected (loader requires single-file).
+ expect(slot?.filter?.(wanModel('i2v_a14b', 'diffusers'), ctx)).toBe(false);
+ // Cross-variant experts are rejected (loader requires exact variant equality).
+ expect(slot?.filter?.(wanModel('t2v_a14b', 'checkpoint'), ctx)).toBe(false);
+ // Unknown variants stay allowed — the backend probe is the authority.
+ expect(slot?.filter?.({ ...wanModel('i2v_a14b', 'checkpoint', 'untagged'), variant: null }, ctx)).toBe(true);
+ });
+
+ it('matches the standalone VAE to the main variant by latent channels', () => {
+ const a14b = wanModel('i2v_a14b', 'gguf_quantized');
+ const ti2v = wanModel('ti2v_5b', 'checkpoint');
+ const vae16 = { base: 'wan', key: 'vae16', latent_channels: 16, name: 'Wan 2.1 VAE', type: 'vae' };
+ const vae48 = { base: 'wan', key: 'vae48', latent_channels: 48, name: 'Wan 2.2 VAE', type: 'vae' };
+ const vaeUnknown = { base: 'wan', key: 'vae?', name: 'Mystery Wan VAE', type: 'vae' };
+
+ const slotFor = (model: MainModelConfig) => {
+ const settings = settingsFor(model);
+
+ return {
+ ctx: { model, selectedComponents: settings, settings },
+ slot: getVideoComponentSectionPolicy(model, settings).slots.find((s) => s.key === 'vae'),
+ };
+ };
+
+ const forA14b = slotFor(a14b);
+ const forTi2v = slotFor(ti2v);
+
+ expect(forA14b.slot?.filter?.(vae16, forA14b.ctx)).toBe(true);
+ expect(forA14b.slot?.filter?.(vae48, forA14b.ctx)).toBe(false);
+ expect(forTi2v.slot?.filter?.(vae48, forTi2v.ctx)).toBe(true);
+ expect(forTi2v.slot?.filter?.(vae16, forTi2v.ctx)).toBe(false);
+ // Configs without the field (open union) stay allowed on both.
+ expect(forA14b.slot?.filter?.(vaeUnknown, forA14b.ctx)).toBe(true);
+ expect(forTi2v.slot?.filter?.(vaeUnknown, forTi2v.ctx)).toBe(true);
+ });
+
+ it('a cross-family component source covers the encoder but not the VAE', () => {
+ // TI2V-5B main with an A14B Diffusers source: UMT5 is shared (encoder
+ // satisfied) but the VAE is family-bound, so a VAE is still required.
+ const model = wanModel('ti2v_5b', 'checkpoint');
+ const settings = settingsFor(model, { componentSourceModel: wanModel('i2v_a14b', 'diffusers') });
+ const reasons = getVideoValidationReasons(model, settings);
+
+ expect(reasons).toContain('Video needs a VAE for Wan models.');
+ expect(reasons).not.toContain('Video needs a Wan T5 Encoder for Wan models.');
+ });
+
+ it('offers only optional single-file overrides for MiniMax H3', () => {
+ const model = h3Model();
+ const policy = getVideoComponentSectionPolicy(model, settingsFor(model));
+
+ expect(policy.defaultOpen).toBe(false);
+ expect(policy.slots.map((slot) => slot.key)).toEqual(['h3TransformerModel', 'h3TextEncoderModel']);
+ expect(policy.slots.every((slot) => !slot.required)).toBe(true);
+
+ const transformerSlot = policy.slots[0];
+ const ctx = { model, selectedComponents: settingsFor(model), settings: settingsFor(model) };
+
+ expect(transformerSlot?.filter?.(h3Model('checkpoint'), ctx)).toBe(true);
+ expect(transformerSlot?.filter?.(h3Model('diffusers'), ctx)).toBe(false);
+ });
+});
+
+describe('getVideoModelSelectionResult', () => {
+ it('clears conditioning media the new model cannot consume', () => {
+ const from = settingsFor(wanModel('i2v_a14b'), {
+ firstFrameImage: FIRST_FRAME,
+ lastFrameImage: LAST_FRAME,
+ lightningEnabled: false,
+ });
+ const result = getVideoModelSelectionResult({
+ currentSettings: from,
+ model: wanModel('t2v_a14b'),
+ models: [],
+ });
+
+ expect(result.settings.firstFrameImage).toBeNull();
+ expect(result.settings.lastFrameImage).toBeNull();
+ expect(result.clearedLabels).toContain('First frame');
+ expect(result.clearedLabels).toContain('Last frame');
+ });
+
+ it('keeps a first+last pair on a model with FLF2V, but drops the last frame on TI2V-5B', () => {
+ const from = settingsFor(wanModel('i2v_a14b'), { firstFrameImage: FIRST_FRAME, lastFrameImage: LAST_FRAME });
+
+ const toH3 = getVideoModelSelectionResult({ currentSettings: from, model: h3Model(), models: [] });
+
+ expect(toH3.settings.firstFrameImage).toEqual(FIRST_FRAME);
+ expect(toH3.settings.lastFrameImage).toEqual(LAST_FRAME);
+
+ const to5b = getVideoModelSelectionResult({ currentSettings: from, model: wanModel('ti2v_5b'), models: [] });
+
+ expect(to5b.settings.firstFrameImage).toEqual(FIRST_FRAME);
+ expect(to5b.settings.lastFrameImage).toBeNull();
+ });
+
+ it('drops a destination image for extend when the model lacks the end-frame channel', () => {
+ const from = settingsFor(wanModel('i2v_a14b'), { lastFrameImage: LAST_FRAME, sourceVideo: SOURCE_VIDEO });
+ const to5b = getVideoModelSelectionResult({ currentSettings: from, model: wanModel('ti2v_5b'), models: [] });
+
+ expect(to5b.settings.sourceVideo).toEqual(SOURCE_VIDEO);
+ expect(to5b.settings.lastFrameImage).toBeNull();
+ });
+
+ it('re-fits presets, frames, fps, Lightning, and components when crossing families', () => {
+ const wan = wanModel('t2v_a14b');
+ const catalog = [LIGHTNING_T2V_HIGH, LIGHTNING_T2V_LOW];
+ const lightningOn = getLightningToggleResult(settingsFor(wan), wan, catalog, true).settings;
+ const from = settingsFor(wan, {
+ ...lightningOn,
+ loras: [...lightningOn.loras, { isEnabled: true, model: lora('Style LoRA') as never, weight: 0.5 }],
+ targetResolution: '480p',
+ vae: { base: 'wan', key: 'wan-vae', name: 'Wan VAE', type: 'vae' },
+ wanT5EncoderModel: { base: 'any', key: 'umt5', name: 'UMT5-XXL', type: 'wan_t5_encoder' },
+ });
+ const result = getVideoModelSelectionResult({ currentSettings: from, model: h3Model(), models: catalog });
+
+ expect(result.settings.targetResolution).toBe('768 highres');
+ expect(result.settings.numFrames).toBe(90); // 81 snapped onto the H3 grid
+ expect(result.settings.fps).toBe(24);
+ expect(result.settings.lightningEnabled).toBe(false);
+ expect(result.settings.steps).toBe(50);
+ expect(result.settings.loras).toEqual([]); // wan LoRAs are incompatible with H3
+ expect(result.settings.vae).toBeNull();
+ expect(result.settings.wanT5EncoderModel).toBeNull();
+ expect(result.clearedLabels).toEqual(
+ expect.arrayContaining(['Target resolution', 'Frames', 'FPS', 'Lightning', 'LoRAs', 'VAE', 'Wan T5 Encoder'])
+ );
+ });
+
+ it('returns no cleared labels when everything carries over', () => {
+ const model = wanModel('i2v_a14b');
+ const from = settingsFor(model, { firstFrameImage: FIRST_FRAME, lightningEnabled: false });
+ const result = getVideoModelSelectionResult({
+ currentSettings: from,
+ model: wanModel('i2v_a14b', 'diffusers'),
+ models: [],
+ });
+
+ expect(result.clearedLabels).toEqual([]);
+ expect(result.settings.modelKey).toBe(wanModel('i2v_a14b', 'diffusers').key);
+ });
+});
+
+describe('getVideoValidationReasons', () => {
+ it('blocks unsupported models', () => {
+ expect(getVideoValidationReasons(h3Model('checkpoint'), settingsFor())).toEqual([
+ 'Video needs a supported video model before it can be invoked.',
+ ]);
+ });
+
+ it('reports unsupported modes in plain language', () => {
+ const t2v = wanModel('t2v_a14b', 'diffusers');
+ const i2v = wanModel('i2v_a14b', 'diffusers');
+
+ expect(getVideoValidationReasons(t2v, settingsFor(t2v, { firstFrameImage: FIRST_FRAME }))).toEqual([
+ expect.stringContaining('does not support starting from a first frame'),
+ ]);
+ expect(getVideoValidationReasons(i2v, settingsFor(i2v))).toEqual([
+ expect.stringContaining('does not support text-to-video'),
+ ]);
+ });
+
+ it('rejects a destination image while extending on TI2V-5B', () => {
+ const model = wanModel('ti2v_5b', 'diffusers');
+ const settings = settingsFor(model, { lastFrameImage: LAST_FRAME, sourceVideo: SOURCE_VIDEO });
+
+ expect(getVideoValidationReasons(model, settings)).toEqual([
+ expect.stringContaining('cannot target a destination image'),
+ ]);
+ });
+
+ it('rejects the first-frame + initial-video combination', () => {
+ const model = wanModel('i2v_a14b', 'diffusers');
+ const settings = settingsFor(model, { firstFrameImage: FIRST_FRAME, sourceVideo: SOURCE_VIDEO });
+
+ expect(getVideoValidationReasons(model, settings)).toContainEqual(expect.stringContaining('cannot be combined'));
+ });
+
+ it('validates frames, fps, and steps against the matrix', () => {
+ const wan = wanModel('t2v_a14b', 'diffusers');
+ const h3 = h3Model();
+
+ expect(getVideoValidationReasons(wan, settingsFor(wan, { numFrames: 80 }))).toEqual([
+ expect.stringContaining('4·n + 1'),
+ ]);
+ expect(getVideoValidationReasons(h3, settingsFor(h3, { numFrames: 100 }))).toEqual([
+ expect.stringContaining('17·n + 5'),
+ ]);
+ expect(getVideoValidationReasons(h3, settingsFor(h3, { fps: 16 }))).toEqual([
+ expect.stringContaining('fixed 24 FPS'),
+ ]);
+ expect(getVideoValidationReasons(wan, settingsFor(wan, { fps: 0 }))).toEqual([
+ expect.stringContaining('FPS must be a whole number between'),
+ ]);
+ expect(getVideoValidationReasons(h3, settingsFor(h3, { steps: 1 }))).toEqual([
+ expect.stringContaining('at least 2'),
+ ]);
+ });
+
+ it('rejects fractional fps and steps — the backend fields are integers', () => {
+ const wan = wanModel('t2v_a14b', 'diffusers');
+
+ expect(getVideoValidationReasons(wan, settingsFor(wan, { fps: 12.5 }))).toEqual([
+ expect.stringContaining('whole number'),
+ ]);
+ expect(getVideoValidationReasons(wan, settingsFor(wan, { steps: 4.5 }))).toEqual([
+ expect.stringContaining('whole number'),
+ ]);
+ });
+
+ it('surfaces Wan LoRA family mismatches instead of silently dropping them', () => {
+ const model = wanModel('ti2v_5b', 'diffusers');
+ const settings = settingsFor(model, {
+ loras: [{ isEnabled: true, model: LIGHTNING_T2V_HIGH as never, weight: 1 }],
+ });
+
+ expect(getVideoValidationReasons(model, settings)).toEqual([
+ expect.stringContaining('targets a different Wan model family'),
+ ]);
+ });
+
+ it('accepts a fully valid H3 first-frame setup', () => {
+ const model = h3Model();
+
+ expect(getVideoValidationReasons(model, settingsFor(model, { firstFrameImage: FIRST_FRAME }))).toEqual([]);
+ });
+});
+
+describe('getVideoModelAvailabilityReasons', () => {
+ it('reports uninstalled selections by label', () => {
+ const model = wanModel('i2v_a14b');
+ const settings = settingsFor(model, {
+ loras: [{ isEnabled: true, model: LIGHTNING_T2V_HIGH as never, weight: 1 }],
+ wanT5EncoderModel: { base: 'any', key: 'umt5', name: 'UMT5-XXL', type: 'wan_t5_encoder' },
+ });
+
+ const reasons = getVideoModelAvailabilityReasons(model, settings, []);
+
+ expect(reasons).toContainEqual(expect.stringContaining('is no longer installed'));
+ expect(reasons.some((reason) => reason.includes('UMT5-XXL'))).toBe(true);
+ expect(reasons.some((reason) => reason.includes('Lightning'))).toBe(true);
+
+ const installed = getVideoModelAvailabilityReasons(model, settingsFor(model), [model]);
+
+ expect(installed).toEqual([]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts
new file mode 100644
index 0000000000..f713f98b4f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts
@@ -0,0 +1,1024 @@
+import type {
+ GenerationModelCatalogItem as ModelConfig,
+ GenerationModelTaxonomyType as ModelTaxonomyType,
+ LoraModelConfig,
+ MainModelConfig,
+} from '@features/generation/contracts';
+
+import {
+ getCompatibleDiffusersComponentSource,
+ isDiffusersMainForBase,
+ isLoraCompatibleWithModel,
+ isLoraModelConfig,
+ isVaeForBases,
+ isWanLoraTargetingMain,
+ SEED_MAX,
+} from '@features/generation/settings';
+
+import type { VideoAspectRatioId, VideoGenerationMode, VideoSettings, VideoTargetResolution } from './types';
+
+import {
+ getVideoAspectRatioParts,
+ MINIMAX_H3_FPS,
+ MINIMAX_H3_NUM_FRAMES_CHOICES,
+ MINIMAX_H3_NUM_FRAMES_DEFAULT,
+ resolveMiniMaxH3Canvas,
+ scaleAndSnapWanDimensions,
+ snapMiniMaxH3NumFrames,
+ snapWanNumFrames,
+ WAN_A14B_PIXEL_MULTIPLE,
+ WAN_FPS_DEFAULT,
+ WAN_FPS_MAX,
+ WAN_FPS_MIN,
+ WAN_NUM_FRAMES_DEFAULT,
+ WAN_NUM_FRAMES_MAX,
+ WAN_NUM_FRAMES_MIN,
+ WAN_NUM_FRAMES_STEP,
+ WAN_TI2V_PIXEL_MULTIPLE,
+ type VideoDimensions,
+} from './dimensions';
+import { isWanLightningLora, resolveVideoMode, VIDEO_ASPECT_RATIO_IDS } from './settings';
+
+// Video capabilities registry keyed by model base AND variant: unlike still-image
+// generation, Wan's variants differ structurally (which conditioning modes exist,
+// the pixel grid, whether a second expert/CFG applies), so base alone is not
+// enough. Display identity stays in @features/models; graph topology will stay
+// explicit in graph.ts.
+
+export type SupportedVideoBase = 'wan' | 'minimax-h3';
+
+export type VideoNegativePromptUsage = 'always' | 'cfg-gated' | 'never';
+
+export interface VideoTargetResolutionOption {
+ id: VideoTargetResolution;
+ label: string;
+}
+
+export interface VideoFramesGridPolicy {
+ kind: 'grid';
+ min: number;
+ max: number;
+ /** Valid counts are `min + k * step` (Wan: 4k + 1, from the VAE's temporal compression). */
+ step: number;
+ defaultValue: number;
+}
+
+export interface VideoFramesChoicesPolicy {
+ kind: 'choices';
+ choices: readonly number[];
+ defaultValue: number;
+}
+
+export type VideoFramesPolicy = VideoFramesGridPolicy | VideoFramesChoicesPolicy;
+
+export interface VideoFpsPolicy {
+ editable: boolean;
+ defaultValue: number;
+ min: number;
+ max: number;
+}
+
+interface VideoVariantConfig {
+ modes: readonly VideoGenerationMode[];
+ pixelMultiple: number;
+ targetResolutions: readonly VideoTargetResolutionOption[];
+ defaults: {
+ targetResolution: VideoTargetResolution;
+ steps: number;
+ cfgScale: number;
+ cfgScaleLowNoise: number | null;
+ };
+ minSteps: number;
+ frames: VideoFramesPolicy;
+ fps: VideoFpsPolicy;
+ cfg: { visible: boolean; lowNoiseVisible: boolean };
+ negativePrompt: { visible: boolean; usage: VideoNegativePromptUsage };
+ lightningAvailable: boolean;
+ audioOutput: boolean;
+}
+
+const WAN_TARGET_RESOLUTION_OPTIONS: readonly VideoTargetResolutionOption[] = [
+ { id: '480p', label: '480p (Wan native)' },
+ { id: '720p', label: '720p (Wan native)' },
+ { id: '1080p', label: '1080p (extrapolated)' },
+];
+
+const MINIMAX_H3_TARGET_RESOLUTION_OPTIONS: readonly VideoTargetResolutionOption[] = [
+ { id: '768 highres', label: '768 highres (H3 native)' },
+ { id: '768 lowres', label: '768 lowres (fast preview)' },
+];
+
+const WAN_FRAMES: VideoFramesGridPolicy = {
+ defaultValue: WAN_NUM_FRAMES_DEFAULT,
+ kind: 'grid',
+ max: WAN_NUM_FRAMES_MAX,
+ min: WAN_NUM_FRAMES_MIN,
+ step: WAN_NUM_FRAMES_STEP,
+};
+
+const WAN_FPS: VideoFpsPolicy = { defaultValue: WAN_FPS_DEFAULT, editable: true, max: WAN_FPS_MAX, min: WAN_FPS_MIN };
+
+// wan_video_denoise defaults: guidance_scale=5.0 (high), guidance_scale_low_noise=4.0.
+const WAN_A14B_COMMON = {
+ cfg: { lowNoiseVisible: true, visible: true },
+ defaults: { cfgScale: 5, cfgScaleLowNoise: 4, steps: 40, targetResolution: '720p' as const },
+ fps: WAN_FPS,
+ frames: WAN_FRAMES,
+ lightningAvailable: true,
+ minSteps: 1,
+ audioOutput: false,
+ negativePrompt: { usage: 'cfg-gated' as const, visible: true },
+ pixelMultiple: WAN_A14B_PIXEL_MULTIPLE,
+ targetResolutions: WAN_TARGET_RESOLUTION_OPTIONS,
+};
+
+const WAN_VARIANTS: Record<string, VideoVariantConfig> = {
+ // The T2V expert pair has no reference-image conditioning channels.
+ t2v_a14b: { ...WAN_A14B_COMMON, modes: ['txt2vid'] },
+ // The I2V expert pair conditions on a reference frame (and optionally an end
+ // frame — FLF2V); it has no text-only mode. Extend is FLF2V machinery fed by
+ // the source video's last frame.
+ i2v_a14b: { ...WAN_A14B_COMMON, modes: ['first-frame', 'first-last', 'extend'] },
+ // TI2V-5B does both text and image conditioning, but its ref encoder has no
+ // end-frame channel, and it is a single expert (no low-noise pair, no
+ // Lightning LoRAs).
+ ti2v_5b: {
+ ...WAN_A14B_COMMON,
+ cfg: { lowNoiseVisible: false, visible: true },
+ defaults: { cfgScale: 5, cfgScaleLowNoise: null, steps: 40, targetResolution: '720p' },
+ lightningAvailable: false,
+ modes: ['txt2vid', 'first-frame', 'extend'],
+ pixelMultiple: WAN_TI2V_PIXEL_MULTIPLE,
+ },
+};
+
+// An unknown Wan variant (new backend release) gets the most permissive A14B
+// capabilities rather than being blocked: the backend probe is the authority.
+const WAN_FALLBACK_VARIANT: VideoVariantConfig = {
+ ...WAN_A14B_COMMON,
+ modes: ['txt2vid', 'first-frame', 'first-last', 'extend'],
+};
+
+// Guidance-distilled: no CFG, no negative prompt, fixed 24 fps, audio included.
+const MINIMAX_H3_FL2VA: VideoVariantConfig = {
+ audioOutput: true,
+ cfg: { lowNoiseVisible: false, visible: false },
+ defaults: { cfgScale: 1, cfgScaleLowNoise: null, steps: 50, targetResolution: '768 highres' },
+ fps: { defaultValue: MINIMAX_H3_FPS, editable: false, max: MINIMAX_H3_FPS, min: MINIMAX_H3_FPS },
+ frames: { choices: MINIMAX_H3_NUM_FRAMES_CHOICES, defaultValue: MINIMAX_H3_NUM_FRAMES_DEFAULT, kind: 'choices' },
+ lightningAvailable: false,
+ minSteps: 2,
+ modes: ['txt2vid', 'first-frame', 'last-frame', 'first-last', 'extend'],
+ negativePrompt: { usage: 'never', visible: false },
+ pixelMultiple: 32,
+ targetResolutions: MINIMAX_H3_TARGET_RESOLUTION_OPTIONS,
+};
+
+export const VIDEO_GENERATION: Record<
+ SupportedVideoBase,
+ { variants: Record<string, VideoVariantConfig>; fallback: VideoVariantConfig }
+> = {
+ 'minimax-h3': { fallback: MINIMAX_H3_FL2VA, variants: { fl2va: MINIMAX_H3_FL2VA } },
+ wan: { fallback: WAN_FALLBACK_VARIANT, variants: WAN_VARIANTS },
+};
+
+export const SUPPORTED_VIDEO_BASES = Object.keys(VIDEO_GENERATION) as SupportedVideoBase[];
+
+/**
+ * MiniMax H3 mains must be the Diffusers folder install — the loader sources
+ * five of its six submodels from it; single-file H3 checkpoints are only usable
+ * as the transformer override slot.
+ */
+export const isSupportedVideoModel = <T extends { base: string; type: string; format?: string }>(
+ model: T
+): model is T & MainModelConfig =>
+ model.type === 'main' && (model.base === 'wan' || (model.base === 'minimax-h3' && model.format === 'diffusers'));
+
+export const isVideoModelSelectable = <T extends ModelConfig>(model: T): boolean => isSupportedVideoModel(model);
+
+const getVideoVariantConfig = (
+ model: Pick<MainModelConfig, 'base' | 'type' | 'variant' | 'format'> | undefined
+): VideoVariantConfig | null => {
+ if (!model || !isSupportedVideoModel(model)) {
+ return null;
+ }
+
+ const baseEntry = VIDEO_GENERATION[model.base as SupportedVideoBase];
+ const variant = typeof model.variant === 'string' ? model.variant : '';
+
+ return baseEntry.variants[variant] ?? baseEntry.fallback;
+};
+
+// Fallback keeps UI selectors crash-safe while nothing is selected;
+// isSupportedVideoModel() still blocks invocation.
+const FALLBACK_VARIANT_CONFIG = WAN_FALLBACK_VARIANT;
+
+const getVideoConfig = (
+ model: Pick<MainModelConfig, 'base' | 'type' | 'variant' | 'format'> | undefined
+): VideoVariantConfig => getVideoVariantConfig(model) ?? FALLBACK_VARIANT_CONFIG;
+
+export const getVideoModes = (model: MainModelConfig | undefined): readonly VideoGenerationMode[] =>
+ getVideoConfig(model).modes;
+
+export const isVideoModeSupported = (model: MainModelConfig | undefined, mode: VideoGenerationMode): boolean =>
+ getVideoModes(model).includes(mode);
+
+export const getVideoFramesPolicy = (model: MainModelConfig | undefined): VideoFramesPolicy =>
+ getVideoConfig(model).frames;
+
+export const getVideoFpsPolicy = (model: MainModelConfig | undefined): VideoFpsPolicy => getVideoConfig(model).fps;
+
+export const getVideoTargetResolutionOptions = (
+ model: MainModelConfig | undefined
+): readonly VideoTargetResolutionOption[] => getVideoConfig(model).targetResolutions;
+
+export const getVideoAspectRatioOptions = (_model: MainModelConfig | undefined): readonly VideoAspectRatioId[] =>
+ // Both current families accept every offered ratio (H3's 1:4–4:1 bound is
+ // wider than the preset list); the hook stays per-model for the next family.
+ VIDEO_ASPECT_RATIO_IDS;
+
+const coerceTargetResolution = (
+ config: VideoVariantConfig,
+ targetResolution: VideoTargetResolution
+): VideoTargetResolution =>
+ config.targetResolutions.some((option) => option.id === targetResolution)
+ ? targetResolution
+ : config.defaults.targetResolution;
+
+export const snapVideoNumFrames = (model: MainModelConfig | undefined, numFrames: number): number => {
+ const frames = getVideoConfig(model).frames;
+
+ return frames.kind === 'grid' ? snapWanNumFrames(numFrames) : snapMiniMaxH3NumFrames(numFrames);
+};
+
+export const isValidVideoNumFrames = (model: MainModelConfig | undefined, numFrames: number): boolean => {
+ const frames = getVideoConfig(model).frames;
+
+ if (frames.kind === 'choices') {
+ return frames.choices.includes(numFrames);
+ }
+
+ return (
+ Number.isInteger(numFrames) &&
+ numFrames >= frames.min &&
+ numFrames <= frames.max &&
+ (numFrames - frames.min) % frames.step === 0
+ );
+};
+
+export type VideoDimensionSource = 'aspect-ratio' | 'first-frame' | 'last-frame' | 'source-video';
+
+export interface ResolvedVideoDimensions extends VideoDimensions {
+ source: VideoDimensionSource;
+}
+
+/**
+ * The exact pixel dimensions a graph will run at. Text-to-video derives them
+ * from the aspect-ratio preset; once conditioning media is set, its own ratio
+ * takes over (the panel's Dimensions section locks accordingly) and only the
+ * target-resolution preset still applies. Null when the media's ratio is
+ * outside the model's supported range or the inputs are degenerate — reported
+ * via `getVideoValidationReasons`.
+ */
+export const getVideoDimensions = (
+ model: MainModelConfig | undefined,
+ settings: Pick<
+ VideoSettings,
+ 'aspectRatioId' | 'targetResolution' | 'firstFrameImage' | 'lastFrameImage' | 'sourceVideo'
+ >
+): ResolvedVideoDimensions | null => {
+ const config = getVideoConfig(model);
+ const targetResolution = coerceTargetResolution(config, settings.targetResolution);
+
+ const media = settings.sourceVideo
+ ? { ...settings.sourceVideo, source: 'source-video' as const }
+ : settings.firstFrameImage
+ ? { ...settings.firstFrameImage, source: 'first-frame' as const }
+ : settings.lastFrameImage
+ ? { ...settings.lastFrameImage, source: 'last-frame' as const }
+ : null;
+
+ const inputs = media ?? { ...getVideoAspectRatioParts(settings.aspectRatioId), source: 'aspect-ratio' as const };
+
+ const dimensions =
+ model?.base === 'minimax-h3'
+ ? resolveMiniMaxH3Canvas(inputs.width, inputs.height, targetResolution as '768 highres' | '768 lowres')
+ : scaleAndSnapWanDimensions(
+ inputs.width,
+ inputs.height,
+ targetResolution as '480p' | '720p' | '1080p',
+ config.pixelMultiple
+ );
+
+ return dimensions ? { ...dimensions, source: inputs.source } : null;
+};
+
+export const getVideoPromptPolicy = (
+ model: MainModelConfig | undefined,
+ settings: Pick<VideoSettings, 'cfgScale' | 'cfgScaleLowNoise' | 'negativePromptEnabled' | 'wanLowNoiseModel'>
+) => {
+ const config = getVideoConfig(model);
+ // Mirrors wan_video_denoise's do_cfg: negative conditioning is also consumed
+ // when the LOW-noise half runs CFG (> 1) — which needs a second expert, i.e.
+ // a Diffusers dual-expert main or a wired low-noise transformer.
+ const lowNoiseCfgActive =
+ config.cfg.lowNoiseVisible &&
+ (model?.format === 'diffusers' || settings.wanLowNoiseModel !== null) &&
+ settings.cfgScaleLowNoise !== null &&
+ settings.cfgScaleLowNoise > 1;
+ const negativeUsedInGraph =
+ settings.negativePromptEnabled &&
+ (config.negativePrompt.usage === 'always' ||
+ (config.negativePrompt.usage === 'cfg-gated' && (settings.cfgScale > 1 || lowNoiseCfgActive)));
+
+ return {
+ negativeVisible: config.negativePrompt.visible,
+ negativeUsedInGraph,
+ ...(config.negativePrompt.usage === 'cfg-gated'
+ ? { negativeHelpText: 'Used only when CFG is greater than 1.' }
+ : {}),
+ };
+};
+
+export interface VideoModelPolicy {
+ isSupported: boolean;
+ modes: readonly VideoGenerationMode[];
+ pixelMultiple: number;
+ aspectRatioOptions: readonly VideoAspectRatioId[];
+ targetResolutions: readonly VideoTargetResolutionOption[];
+ frames: VideoFramesPolicy;
+ fps: VideoFpsPolicy;
+ defaults: {
+ targetResolution: VideoTargetResolution;
+ steps: number;
+ cfgScale: number;
+ cfgScaleLowNoise: number | null;
+ };
+ prompt: {
+ negativeVisible: boolean;
+ negativeUsedInGraph: boolean;
+ negativeHelpText?: string;
+ };
+ ui: {
+ cfgVisible: boolean;
+ cfgLowNoiseVisible: boolean;
+ fpsVisible: boolean;
+ lightningAvailable: boolean;
+ audioOutput: boolean;
+ };
+}
+
+export const getVideoModelPolicy = (model: MainModelConfig | undefined, settings: VideoSettings): VideoModelPolicy => {
+ const config = getVideoConfig(model);
+
+ return {
+ aspectRatioOptions: getVideoAspectRatioOptions(model),
+ defaults: config.defaults,
+ fps: config.fps,
+ frames: config.frames,
+ isSupported: model ? isSupportedVideoModel(model) : false,
+ modes: config.modes,
+ pixelMultiple: config.pixelMultiple,
+ prompt: getVideoPromptPolicy(model, settings),
+ targetResolutions: config.targetResolutions,
+ ui: {
+ audioOutput: config.audioOutput,
+ cfgLowNoiseVisible: config.cfg.lowNoiseVisible,
+ cfgVisible: config.cfg.visible,
+ fpsVisible: config.fps.editable,
+ lightningAvailable: config.lightningAvailable,
+ },
+ };
+};
+
+// ---------------------------------------------------------------------------
+// Wan Lightning fast path
+
+/** The sampling parameters the Lightning distillation LoRAs are trained for. */
+export const WAN_LIGHTNING_SAMPLING = { cfgScale: 1, cfgScaleLowNoise: 1, steps: 4 } as const;
+
+export interface WanLightningLoraPair {
+ high: LoraModelConfig;
+ low: LoraModelConfig;
+}
+
+// "high"/"low" as standalone words. \b is useless here because release files
+// use underscores ("high_noise_model") where \w breaks no boundary, while a
+// plain word-suffix match swallows "Slow"/"Thigh" — so the token must be
+// delimited by non-alphanumerics (or the string edge) on BOTH sides.
+const HIGH_NOISE_PATTERN = /(?:^|[^a-z0-9])high(?:[^a-z0-9]|$)/i;
+const LOW_NOISE_PATTERN = /(?:^|[^a-z0-9])low(?:[^a-z0-9]|$)/i;
+
+/**
+ * The installed Lightning LoRA pair for a Wan A14B main, if any. When pairs for
+ * more than one family are installed (e.g. T2V and I2V releases), the one
+ * naming the main's family wins; noise assignment comes from the model names.
+ */
+export const findWanLightningLoraPair = (
+ models: readonly ModelConfig[],
+ mainVariant: string | null | undefined
+): WanLightningLoraPair | null => {
+ const candidates = models.filter(
+ (model): model is ModelConfig & LoraModelConfig =>
+ isLoraModelConfig(model) && isWanLightningLora(model) && isWanLoraTargetingMain(model.variant, mainVariant)
+ );
+
+ // Delimited-token match so 'i2v' cannot score inside "TI2V".
+ const familyToken = typeof mainVariant === 'string' ? mainVariant.split('_')[0] : undefined;
+ const familyPattern = familyToken ? new RegExp(`(?:^|[^a-z0-9])${familyToken}(?:[^a-z0-9]|$)`, 'i') : null;
+ const score = (model: LoraModelConfig): number => (familyPattern?.test(model.name) ? 0 : 1);
+ const pick = (pattern: RegExp): LoraModelConfig | null =>
+ candidates.filter((model) => pattern.test(model.name)).sort((a, b) => score(a) - score(b))[0] ?? null;
+
+ const high = pick(HIGH_NOISE_PATTERN);
+ const low = pick(LOW_NOISE_PATTERN);
+
+ return high && low && high.key !== low.key ? { high, low } : null;
+};
+
+export interface LightningToggleResult {
+ settings: VideoSettings;
+ /** True when enabling was requested but no installed Lightning pair was found. */
+ missingLoras: boolean;
+}
+
+/**
+ * Applies the Lightning toggle as a plain settings transition: the LoRA pair
+ * appears in (or leaves) the Concepts list and steps/CFG are patched, so the
+ * graph builder needs no hidden behavior and the user sees exactly what runs.
+ */
+export const getLightningToggleResult = (
+ settings: VideoSettings,
+ model: MainModelConfig,
+ models: readonly ModelConfig[],
+ enabled: boolean
+): LightningToggleResult => {
+ const config = getVideoConfig(model);
+ const withoutLightning = settings.loras.filter((lora) => !isWanLightningLora(lora.model));
+
+ if (!enabled || !config.lightningAvailable) {
+ return {
+ missingLoras: false,
+ settings: {
+ ...settings,
+ cfgScale: config.defaults.cfgScale,
+ cfgScaleLowNoise: config.defaults.cfgScaleLowNoise,
+ lightningEnabled: false,
+ loras: withoutLightning,
+ steps: config.defaults.steps,
+ },
+ };
+ }
+
+ const pair = findWanLightningLoraPair(models, model.variant);
+
+ if (!pair) {
+ // Never leave the flag claiming a fast path that has no LoRAs behind it.
+ return {
+ missingLoras: true,
+ settings: settings.lightningEnabled ? { ...settings, lightningEnabled: false } : settings,
+ };
+ }
+
+ return {
+ missingLoras: false,
+ settings: {
+ ...settings,
+ ...WAN_LIGHTNING_SAMPLING,
+ lightningEnabled: true,
+ loras: [
+ ...withoutLightning,
+ { isEnabled: true, model: pair.high, weight: 1 },
+ { isEnabled: true, model: pair.low, weight: 1 },
+ ],
+ },
+ };
+};
+
+// ---------------------------------------------------------------------------
+// Component slots
+
+export type VideoComponentValueKey =
+ | 'vae'
+ | 'wanT5EncoderModel'
+ | 'wanLowNoiseModel'
+ | 'componentSourceModel'
+ | 'h3TransformerModel'
+ | 'h3TextEncoderModel';
+
+export interface VideoComponentPolicyContext {
+ model: MainModelConfig;
+ settings: VideoSettings;
+ selectedComponents: Pick<VideoSettings, VideoComponentValueKey>;
+}
+
+export interface VideoComponentSlotPolicy {
+ key: VideoComponentValueKey;
+ label: string;
+ modelTypes: readonly ModelTaxonomyType[];
+ valueKind: 'component' | 'vae' | 'main';
+ helpText?: string;
+ filter?: (candidate: ModelConfig, ctx: VideoComponentPolicyContext) => boolean;
+ required?: (ctx: VideoComponentPolicyContext) => boolean;
+ missingMessage?: string;
+}
+
+export interface VideoComponentSectionPolicy {
+ defaultOpen: boolean;
+ slots: readonly VideoComponentSlotPolicy[];
+ validate: (ctx: VideoComponentPolicyContext) => string[];
+}
+
+const VIDEO_COMPONENT_SETTING_LABELS: Record<VideoComponentValueKey, string> = {
+ componentSourceModel: 'Component source',
+ h3TextEncoderModel: 'Text encoder (single file)',
+ h3TransformerModel: 'Transformer (single file)',
+ vae: 'VAE',
+ wanLowNoiseModel: 'Low-noise expert',
+ wanT5EncoderModel: 'Wan T5 Encoder',
+};
+
+const isTi2v5b = (variant: unknown): boolean => variant === 'ti2v_5b';
+
+// A Diffusers Wan main bundles its own VAE and encoder; a GGUF/checkpoint main
+// needs them from standalone models or a Diffusers component source.
+const getWanComponentSource = (ctx: VideoComponentPolicyContext) =>
+ getCompatibleDiffusersComponentSource(ctx.model, ctx.settings.componentSourceModel);
+
+// The UMT5-XXL encoder is shared across Wan families, so any Diffusers source
+// supplies it.
+const isWanEncoderSatisfied = (ctx: VideoComponentPolicyContext): boolean =>
+ ctx.model.format === 'diffusers' || Boolean(getWanComponentSource(ctx));
+
+// The VAE is family-bound (wan_model_loader's source-VAE validation): a source
+// only covers it when its TI2V-5B-ness matches the main's.
+const isWanVaeSatisfied = (ctx: VideoComponentPolicyContext): boolean => {
+ if (ctx.model.format === 'diffusers') {
+ return true;
+ }
+
+ const source = getWanComponentSource(ctx);
+
+ return Boolean(source) && isTi2v5b(source?.variant) === isTi2v5b(ctx.model.variant);
+};
+
+const validateSlots = (slots: readonly VideoComponentSlotPolicy[], ctx: VideoComponentPolicyContext): string[] =>
+ slots.flatMap((slotPolicy) => {
+ if (!slotPolicy.required?.(ctx)) {
+ return [];
+ }
+
+ const value = ctx.selectedComponents[slotPolicy.key];
+ const isValid = value && (!slotPolicy.filter || slotPolicy.filter(value as ModelConfig, ctx));
+
+ return isValid ? [] : [slotPolicy.missingMessage ?? `Video needs a ${slotPolicy.label} for this model.`];
+ });
+
+const createComponentPolicy = (
+ defaultOpen: boolean,
+ slots: readonly VideoComponentSlotPolicy[]
+): VideoComponentSectionPolicy => ({
+ defaultOpen,
+ slots,
+ validate: (ctx) => validateSlots(slots, ctx),
+});
+
+const EMPTY_VIDEO_COMPONENT_POLICY = createComponentPolicy(false, []);
+
+// wan_model_loader requires the low-noise expert to be a DIFFERENT single-file
+// model of the SAME variant as the main. Unknown variants stay allowed — the
+// backend probe is the authority.
+const isWanLowNoiseExpertCandidate = (candidate: ModelConfig, ctx: VideoComponentPolicyContext): boolean =>
+ candidate.type === 'main' &&
+ candidate.base === 'wan' &&
+ candidate.format !== 'diffusers' &&
+ candidate.key !== ctx.model.key &&
+ (typeof candidate.variant !== 'string' ||
+ typeof ctx.model.variant !== 'string' ||
+ candidate.variant === ctx.model.variant);
+
+// wan_model_loader validates the standalone VAE's latent channels against the
+// main: TI2V-5B needs the 48-channel Wan 2.2 VAE, A14B the 16-channel Wan 2.1
+// VAE. A config without the field (open union) stays allowed.
+const isWanVaeForMain = (candidate: ModelConfig, ctx: VideoComponentPolicyContext): boolean => {
+ if (!isVaeForBases(['wan'])(candidate)) {
+ return false;
+ }
+
+ const latentChannels = candidate.latent_channels;
+
+ if (typeof latentChannels !== 'number') {
+ return true;
+ }
+
+ return latentChannels === (isTi2v5b(ctx.model.variant) ? 48 : 16);
+};
+
+export const getVideoComponentSectionPolicy = (
+ model: MainModelConfig | undefined,
+ _settings: VideoSettings
+): VideoComponentSectionPolicy => {
+ if (!model || !isSupportedVideoModel(model)) {
+ return EMPTY_VIDEO_COMPONENT_POLICY;
+ }
+
+ if (model.base === 'wan') {
+ const config = getVideoConfig(model);
+ const slots: VideoComponentSlotPolicy[] = [
+ {
+ filter: (candidate) => isDiffusersMainForBase('wan')(candidate),
+ helpText: 'Select a Diffusers Wan model to provide VAE and text-encoder components.',
+ key: 'componentSourceModel',
+ label: 'Component source',
+ modelTypes: ['main'],
+ valueKind: 'main',
+ },
+ {
+ filter: isWanVaeForMain,
+ helpText: 'Required unless a Diffusers component source is available.',
+ key: 'vae',
+ label: 'VAE',
+ missingMessage: 'Video needs a VAE for Wan models.',
+ modelTypes: ['vae'],
+ required: (ctx) => !isWanVaeSatisfied(ctx),
+ valueKind: 'vae',
+ },
+ {
+ filter: (candidate) => candidate.type === 'wan_t5_encoder',
+ helpText: 'Required unless a Diffusers component source is available.',
+ key: 'wanT5EncoderModel',
+ label: 'Wan T5 Encoder',
+ missingMessage: 'Video needs a Wan T5 Encoder for Wan models.',
+ modelTypes: ['wan_t5_encoder'],
+ required: (ctx) => !isWanEncoderSatisfied(ctx),
+ valueKind: 'component',
+ },
+ ];
+
+ // TI2V-5B is a single expert, and a Diffusers A14B main bundles its own
+ // transformer_2 (the loader ignores this input for it) — so the slot is
+ // only offered for single-file A14B mains.
+ if (config.cfg.lowNoiseVisible && model.format !== 'diffusers') {
+ slots.push({
+ filter: isWanLowNoiseExpertCandidate,
+ helpText: 'Optional second A14B expert. Without it the high-noise expert runs the whole schedule.',
+ key: 'wanLowNoiseModel',
+ label: 'Transformer (Low Noise)',
+ modelTypes: ['main'],
+ valueKind: 'main',
+ });
+ }
+
+ return createComponentPolicy(model.format !== 'diffusers', slots);
+ }
+
+ // MiniMax H3: the Diffusers install bundles everything; both slots are
+ // optional single-file overrides (e.g. the int8 repacks).
+ return createComponentPolicy(false, [
+ {
+ filter: (candidate) =>
+ candidate.type === 'main' && candidate.base === 'minimax-h3' && candidate.format === 'checkpoint',
+ helpText: 'Optional single-file transformer (e.g. pruned int8) used in place of the main model’s transformer.',
+ key: 'h3TransformerModel',
+ label: 'Transformer (single file)',
+ modelTypes: ['main'],
+ valueKind: 'main',
+ },
+ {
+ filter: (candidate) => candidate.type === 'qwen3_vl_encoder' && candidate.base === 'minimax-h3',
+ helpText: 'Optional single-file Qwen3-VL encoder used in place of the main model’s text encoder.',
+ key: 'h3TextEncoderModel',
+ label: 'Text encoder (single file)',
+ modelTypes: ['qwen3_vl_encoder'],
+ valueKind: 'component',
+ },
+ ]);
+};
+
+const getVideoComponentPolicyContext = (
+ model: MainModelConfig,
+ settings: VideoSettings
+): VideoComponentPolicyContext => ({
+ model,
+ selectedComponents: {
+ componentSourceModel: settings.componentSourceModel,
+ h3TextEncoderModel: settings.h3TextEncoderModel,
+ h3TransformerModel: settings.h3TransformerModel,
+ vae: settings.vae,
+ wanLowNoiseModel: settings.wanLowNoiseModel,
+ wanT5EncoderModel: settings.wanT5EncoderModel,
+ },
+ settings,
+});
+
+// ---------------------------------------------------------------------------
+// Defaults & model-selection transitions
+
+export const getDefaultVideoSettings = (
+ model?: MainModelConfig,
+ models: readonly ModelConfig[] = []
+): VideoSettings => {
+ const config = getVideoConfig(model);
+
+ const base: VideoSettings = {
+ aspectRatioId: '16:9',
+ batchCount: 1,
+ cfgScale: config.defaults.cfgScale,
+ cfgScaleLowNoise: config.defaults.cfgScaleLowNoise,
+ componentSourceModel: null,
+ firstFrameImage: null,
+ fps: config.fps.defaultValue,
+ h3TextEncoderModel: null,
+ h3TransformerModel: null,
+ lastFrameImage: null,
+ lightningEnabled: false,
+ loras: [],
+ modelKey: model?.key ?? '',
+ negativePrompt: '',
+ negativePromptEnabled: true,
+ negativePromptHeightPx: 56,
+ numFrames: config.frames.defaultValue,
+ positivePrompt: '',
+ positivePromptHeightPx: 96,
+ seed: Math.floor(Math.random() * SEED_MAX),
+ shouldRandomizeSeed: true,
+ sourceVideo: null,
+ steps: config.defaults.steps,
+ targetResolution: config.defaults.targetResolution,
+ vae: null,
+ wanLowNoiseModel: null,
+ wanT5EncoderModel: null,
+ };
+
+ // Lightning defaults ON for Wan A14B when the LoRA pair is installed: the
+ // plain 40-step CFG-5 path is prohibitively slow as an out-of-the-box default.
+ if (model && config.lightningAvailable) {
+ const result = getLightningToggleResult(base, model, models, true);
+
+ if (!result.missingLoras) {
+ return result.settings;
+ }
+ }
+
+ return base;
+};
+
+export const getVideoSettingsWithModelDefaults = (
+ settings: VideoSettings,
+ model: MainModelConfig,
+ models: readonly ModelConfig[] = []
+): VideoSettings => {
+ const modelDefaults = getDefaultVideoSettings(model, models);
+
+ return {
+ ...settings,
+ cfgScale: modelDefaults.cfgScale,
+ cfgScaleLowNoise: modelDefaults.cfgScaleLowNoise,
+ fps: modelDefaults.fps,
+ lightningEnabled: modelDefaults.lightningEnabled,
+ loras: [...settings.loras.filter((lora) => !isWanLightningLora(lora.model)), ...modelDefaults.loras].map((lora) =>
+ isLoraCompatibleWithModel(lora.model, model) ? lora : { ...lora, isEnabled: false }
+ ),
+ modelKey: model.key,
+ numFrames: modelDefaults.numFrames,
+ steps: modelDefaults.steps,
+ targetResolution: modelDefaults.targetResolution,
+ };
+};
+
+export interface VideoModelSelectionResult {
+ settings: VideoSettings;
+ clearedLabels: readonly string[];
+}
+
+const addClearedLabel = (labels: string[], label: string) => {
+ if (!labels.includes(label)) {
+ labels.push(label);
+ }
+};
+
+/**
+ * Canonical transition for every Video model-selection entry point: reconciles
+ * conditioning media against the new model's modes, snaps frames/fps/presets
+ * onto its constraints, and drops incompatible LoRAs and components — reporting
+ * what was cleared so the UI can say so.
+ */
+export const getVideoModelSelectionResult = ({
+ currentSettings,
+ model,
+ models,
+}: {
+ currentSettings: VideoSettings;
+ model: MainModelConfig;
+ models: readonly ModelConfig[];
+}): VideoModelSelectionResult => {
+ const config = getVideoConfig(model);
+ const next: VideoSettings = { ...currentSettings, modelKey: model.key };
+ const clearedLabels: string[] = [];
+ const modes = config.modes;
+
+ if (next.sourceVideo && !modes.includes('extend')) {
+ next.sourceVideo = null;
+ addClearedLabel(clearedLabels, 'Initial video');
+ }
+
+ if (next.firstFrameImage && !modes.includes('first-frame') && !modes.includes('first-last')) {
+ next.firstFrameImage = null;
+ addClearedLabel(clearedLabels, 'First frame');
+ }
+
+ if (next.lastFrameImage) {
+ // The end-frame anchor rides the FLF2V channel whether its partner is a
+ // first frame or a source video; alone it needs a dedicated last-frame mode.
+ const lastFrameSupported =
+ next.firstFrameImage || next.sourceVideo ? modes.includes('first-last') : modes.includes('last-frame');
+
+ if (!lastFrameSupported) {
+ next.lastFrameImage = null;
+ addClearedLabel(clearedLabels, 'Last frame');
+ }
+ }
+
+ if (!config.targetResolutions.some((option) => option.id === next.targetResolution)) {
+ next.targetResolution = config.defaults.targetResolution;
+ addClearedLabel(clearedLabels, 'Target resolution');
+ }
+
+ const snappedFrames = snapVideoNumFrames(model, next.numFrames);
+
+ if (snappedFrames !== next.numFrames) {
+ next.numFrames = snappedFrames;
+ addClearedLabel(clearedLabels, 'Frames');
+ }
+
+ const clampedFps =
+ config.fps.editable && Number.isFinite(next.fps)
+ ? Math.min(config.fps.max, Math.max(config.fps.min, Math.round(next.fps)))
+ : config.fps.defaultValue;
+
+ if (clampedFps !== next.fps) {
+ next.fps = clampedFps;
+ addClearedLabel(clearedLabels, 'FPS');
+ }
+
+ if (next.lightningEnabled && !config.lightningAvailable) {
+ // Lightning wrote steps/CFG, so clearing it restores the new model's own defaults.
+ const result = getLightningToggleResult(next, model, models, false);
+ Object.assign(next, result.settings);
+ addClearedLabel(clearedLabels, 'Lightning');
+ }
+
+ if (next.cfgScaleLowNoise !== null && !config.cfg.lowNoiseVisible) {
+ next.cfgScaleLowNoise = null;
+ addClearedLabel(clearedLabels, 'CFG (Low Noise)');
+ }
+
+ const compatibleLoras = next.loras.filter((lora) => isLoraCompatibleWithModel(lora.model, model));
+
+ if (compatibleLoras.length !== next.loras.length) {
+ next.loras = compatibleLoras;
+ addClearedLabel(clearedLabels, 'LoRAs');
+ }
+
+ const policy = getVideoComponentSectionPolicy(model, next);
+ const slotsByKey = new Map(policy.slots.map((slotPolicy) => [slotPolicy.key, slotPolicy]));
+
+ for (const key of Object.keys(VIDEO_COMPONENT_SETTING_LABELS) as VideoComponentValueKey[]) {
+ const value = next[key];
+
+ if (!value) {
+ continue;
+ }
+
+ const slotPolicy = slotsByKey.get(key);
+ const isCompatible =
+ slotPolicy &&
+ (!slotPolicy.filter || slotPolicy.filter(value as ModelConfig, getVideoComponentPolicyContext(model, next)));
+
+ if (!isCompatible) {
+ next[key] = null;
+ addClearedLabel(clearedLabels, VIDEO_COMPONENT_SETTING_LABELS[key]);
+ }
+ }
+
+ return { clearedLabels, settings: next };
+};
+
+// ---------------------------------------------------------------------------
+// Validation
+
+const VIDEO_MODE_DESCRIPTIONS: Record<VideoGenerationMode, string> = {
+ extend: 'extending a video',
+ 'first-frame': 'starting from a first frame',
+ 'first-last': 'first-to-last-frame interpolation',
+ 'last-frame': 'ending on a last frame',
+ txt2vid: 'text-to-video',
+};
+
+const hasModelKey = (models: readonly ModelConfig[], key: string, type?: string): boolean =>
+ models.some((model) => model.key === key && (!type || model.type === type));
+
+export const getVideoModelAvailabilityReasons = (
+ model: MainModelConfig,
+ settings: VideoSettings,
+ models: readonly ModelConfig[]
+): string[] => {
+ const reasons: string[] = [];
+
+ if (!hasModelKey(models, model.key, model.type)) {
+ reasons.push(`Selected model "${model.name}" is no longer installed.`);
+ }
+
+ for (const key of Object.keys(VIDEO_COMPONENT_SETTING_LABELS) as VideoComponentValueKey[]) {
+ const value = settings[key];
+
+ if (value && !hasModelKey(models, value.key, value.type)) {
+ reasons.push(`${VIDEO_COMPONENT_SETTING_LABELS[key]} "${value.name}" is no longer installed.`);
+ }
+ }
+
+ for (const lora of settings.loras) {
+ if (!hasModelKey(models, lora.model.key, 'lora')) {
+ reasons.push(`LoRA "${lora.model.name}" is no longer installed.`);
+ }
+ }
+
+ return reasons;
+};
+
+export const getVideoValidationReasons = (model: MainModelConfig, settings: VideoSettings): string[] => {
+ if (!isSupportedVideoModel(model)) {
+ return ['Video needs a supported video model before it can be invoked.'];
+ }
+
+ const config = getVideoConfig(model);
+ const reasons: string[] = [];
+ const mode = resolveVideoMode(settings);
+
+ if (settings.firstFrameImage && settings.sourceVideo) {
+ reasons.push('A first frame and an initial video cannot be combined. Clear one of them.');
+ }
+
+ if (!config.modes.includes(mode)) {
+ reasons.push(`${model.name} does not support ${VIDEO_MODE_DESCRIPTIONS[mode]}.`);
+ } else if (mode === 'extend' && settings.lastFrameImage && !config.modes.includes('first-last')) {
+ reasons.push(`${model.name} cannot target a destination image while extending a video.`);
+ }
+
+ if (!isValidVideoNumFrames(model, settings.numFrames)) {
+ reasons.push(
+ config.frames.kind === 'grid'
+ ? `Frame count must be between ${config.frames.min} and ${config.frames.max} in steps of ${config.frames.step} (4·n + 1).`
+ : `Frame count must be one of the ${model.name} grid values (17·n + 5, ${config.frames.choices[0]}–${config.frames.choices[config.frames.choices.length - 1]}).`
+ );
+ }
+
+ // fps and steps are integer fields on the backend nodes; a fractional value
+ // would fail pydantic coercion at enqueue, so reject it here instead.
+ if (!Number.isInteger(settings.fps) || settings.fps < config.fps.min || settings.fps > config.fps.max) {
+ reasons.push(
+ config.fps.editable
+ ? `FPS must be a whole number between ${config.fps.min} and ${config.fps.max}.`
+ : `${model.name} generates at a fixed ${config.fps.defaultValue} FPS.`
+ );
+ }
+
+ if (!Number.isInteger(settings.steps) || settings.steps < config.minSteps) {
+ reasons.push(`Steps must be a whole number of at least ${config.minSteps}.`);
+ }
+
+ if (config.cfg.visible && (!Number.isFinite(settings.cfgScale) || settings.cfgScale < 1)) {
+ reasons.push('CFG must be at least 1.');
+ }
+
+ if (config.cfg.lowNoiseVisible && settings.cfgScaleLowNoise !== null && settings.cfgScaleLowNoise < 0) {
+ reasons.push('CFG (Low Noise) must be at least 0.');
+ }
+
+ if (settings.lightningEnabled && !config.lightningAvailable) {
+ reasons.push('Lightning is only available for Wan A14B models.');
+ }
+
+ if (!getVideoDimensions(model, settings)) {
+ reasons.push(
+ model.base === 'minimax-h3'
+ ? 'MiniMax H3 supports aspect ratios from 1:4 to 4:1. The conditioning media is outside that range.'
+ : 'The conditioning media is too small or degenerate to derive video dimensions from.'
+ );
+ }
+
+ if (model.base === 'wan') {
+ // A14B and 5B Wan LoRAs are not interchangeable — the layer patcher fails
+ // on a tensor-shape mismatch — so say so instead of silently dropping them.
+ for (const lora of settings.loras) {
+ if (lora.isEnabled && !isWanLoraTargetingMain(lora.model.variant, model.variant)) {
+ reasons.push(`${lora.model.name} targets a different Wan model family than ${model.name}.`);
+ }
+ }
+ }
+
+ const componentPolicy = getVideoComponentSectionPolicy(model, settings);
+ reasons.push(...componentPolicy.validate(getVideoComponentPolicyContext(model, settings)));
+
+ return reasons;
+};
diff --git a/invokeai/frontend/webv2/src/features/video/index.ts b/invokeai/frontend/webv2/src/features/video/index.ts
new file mode 100644
index 0000000000..61ec6ac25e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/video/index.ts
@@ -0,0 +1,78 @@
+/**
+ * Video generation's React-free values/policy surface: settings normalization,
+ * the per-base/per-variant capabilities matrix, canvas math, and model-selection
+ * transitions. Curated, caller-driven export list — add a symbol only when a
+ * consumer needs it. UI and graph compilation arrive in later modules.
+ */
+export type {
+ MiniMaxH3TargetResolution,
+ VideoAspectRatioId,
+ VideoGenerationMode,
+ VideoSettings,
+ VideoSourceClip,
+ VideoTargetResolution,
+ VideoWidgetValues,
+ WanTargetResolution,
+} from './core/types';
+export {
+ cloneVideoWidgetValues,
+ isImageWithDims,
+ isVideoAspectRatioId,
+ isVideoSettings,
+ isVideoSourceClip,
+ isVideoTargetResolution,
+ isVideoWidgetValues,
+ isWanLightningLora,
+ MINIMAX_H3_TARGET_RESOLUTIONS,
+ normalizeVideoSettings,
+ normalizeVideoWidgetValues,
+ resolveVideoMode,
+ VIDEO_ASPECT_RATIO_IDS,
+ VIDEO_UI_STATE_KEYS,
+ WAN_TARGET_RESOLUTIONS,
+} from './core/settings';
+export {
+ getVideoAspectRatioParts,
+ getVideoDurationSeconds,
+ invertVideoAspectRatioId,
+ MINIMAX_H3_FPS,
+ MINIMAX_H3_NUM_FRAMES_CHOICES,
+ resolveMiniMaxH3Canvas,
+ scaleAndSnapWanDimensions,
+ WAN_NUM_FRAMES_DEFAULT,
+ WAN_NUM_FRAMES_MAX,
+ WAN_NUM_FRAMES_MIN,
+ WAN_NUM_FRAMES_STEP,
+ type VideoDimensions,
+} from './core/dimensions';
+export {
+ findWanLightningLoraPair,
+ getDefaultVideoSettings,
+ getLightningToggleResult,
+ getVideoComponentSectionPolicy,
+ getVideoDimensions,
+ getVideoModelAvailabilityReasons,
+ getVideoModelPolicy,
+ getVideoModelSelectionResult,
+ getVideoModes,
+ getVideoPromptPolicy,
+ getVideoSettingsWithModelDefaults,
+ getVideoValidationReasons,
+ isSupportedVideoModel,
+ isValidVideoNumFrames,
+ isVideoModelSelectable,
+ isVideoModeSupported,
+ snapVideoNumFrames,
+ SUPPORTED_VIDEO_BASES,
+ VIDEO_GENERATION,
+ WAN_LIGHTNING_SAMPLING,
+ type ResolvedVideoDimensions,
+ type SupportedVideoBase,
+ type VideoComponentSectionPolicy,
+ type VideoComponentSlotPolicy,
+ type VideoComponentValueKey,
+ type VideoFramesPolicy,
+ type VideoModelPolicy,
+ type VideoModelSelectionResult,
+ type VideoTargetResolutionOption,
+} from './core/videoPolicies';