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.

test(recall): fail when a recorded metadata key has no recall contract (#10220)

Alexander Eichhorn9b73dc5631ee
diff --git a/.github/workflows/frontend-checks.yml b/.github/workflows/frontend-checks.yml
index ebf7961c8b..4e37cd5863 100644
--- a/.github/workflows/frontend-checks.yml
+++ b/.github/workflows/frontend-checks.yml
@@ -64,6 +64,8 @@ jobs:
- '.nvmrc'
- '.github/actions/install-frontend-deps/**'
- 'invokeai/frontend/webv2/**'
+ # The type check reads the generated API types, the recall contract's declared-key gate included.
+ - 'invokeai/frontend/api/schema.ts'
- name: install dependencies
if: ${{ steps.changed-files.outputs.webv2_any_changed == 'true' || inputs.always_run == true }}
diff --git a/docs/src/content/docs/contributing/new-model-integration.mdx b/docs/src/content/docs/contributing/new-model-integration.mdx
index 4150fcda49..c2d542ba22 100644
--- a/docs/src/content/docs/contributing/new-model-integration.mdx
+++ b/docs/src/content/docs/contributing/new-model-integration.mdx
@@ -852,7 +852,7 @@ Paths below are relative to `invokeai/frontend/webv2/src/features/generation/cor
- A per-family setting that is not a model, such as Krea-2's rebalance or MOSS-Image's skip layers, needs its own metadata reader, a `RecalledField` member, its flag in `getImageRecallCapabilities` and its patch in `buildImageRecallSettings`.
- Add the base to `GUIDANCE_BASES` in `recallParameters.ts` if it takes the shared guidance slider.
- Nothing checks recall against what the builder writes, so test it.
+ Every metadata key the builder writes needs an entry in `IMAGE_RECALL_CONTRACT` (`imageRecallContract.test.ts`; video graphs have theirs in `videoRecallContract.test.ts`): `restores` with the settings it sets, or `consumed` or `ignored` with the reason. The contract compiles every shape of `generateGraphCases` with each recalled setting off its default (`recallTunedSettingsFor` in `graphCoverage.testing.ts`), fails for a written key without an entry, and checks that recall restores every `restores` entry and that an `ignored` key changes nothing. It sees only keys those graphs write: if the builder writes a key only under some setting, set that setting off its default in `recallTunedSettingsFor`, or add a dedicated case.
7. **Model registry and labels**
@@ -881,7 +881,7 @@ Paths below are relative to `invokeai/frontend/webv2/src/features/generation/cor
pnpm test src/features/generation/core/graphCoverage.test.ts -u
```
- This rewrites `__snapshots__/generateGraphNodeTypes.json`. Graph coverage and the remix round trip compile each base in the shapes listed in `graphCoverage.testing.ts`; a variant that changes the graph needs its own entry in `SHAPE_OVERRIDES`, and a component variant a slot filters for needs to be in `CANDIDATE_VARIANTS`, or neither test ever builds that graph. Then raise `SUPPORTED_BASE_COUNTS["generate"]` in `tests/app/invocations/test_frontend_graph_node_types.py`, and `LITERAL_FLOORS` if needed. That Python test checks every node type, edge field and literal value the builders emit against the backend's invocation registry.
+ This rewrites `__snapshots__/generateGraphNodeTypes.json`. Graph coverage and the image recall contract compile each base in the shapes listed in `graphCoverage.testing.ts`; a variant that changes the graph needs its own entry in `SHAPE_OVERRIDES`, and a component variant a slot filters for needs to be in `CANDIDATE_VARIANTS`, or neither test ever builds that graph. Then raise `SUPPORTED_BASE_COUNTS["generate"]` in `tests/app/invocations/test_frontend_graph_node_types.py`, and `LITERAL_FLOORS` if needed. That Python test checks every node type, edge field and literal value the builders emit against the backend's invocation registry.
</Steps>
:::tip[Checklist: webv2]{icon="approve-check"}
@@ -891,7 +891,7 @@ Paths below are relative to `invokeai/frontend/webv2/src/features/generation/cor
- [ ] Component slot policy (per variant where only one needs it), encoder filters, new settings keys everywhere
- [ ] `FamilyGraph` facts checked through `generateGraphCases`, with `latents` and Canvas `BASE_CASES`
- [ ] Non-null `conditioning` naming the global prompt nodes and collectors for mask-based regional guidance
-- [ ] Recall
+- [ ] Recall, with an `IMAGE_RECALL_CONTRACT` entry for every metadata key the builder writes
- [ ] Model registry, labels, `en.json`
- [ ] `SHAPE_OVERRIDES` / `CANDIDATE_VARIANTS` for variant-dependent graphs
- [ ] Graph snapshot regenerated, `SUPPORTED_BASE_COUNTS` raised
@@ -960,8 +960,8 @@ Several tests pin hand-maintained tables, so a new architecture has to extend th
| `tests/app/invocations/test_ideal_size.py` | A row in `IDEAL_SIZE_AT_NODE_DEFAULTS`: the size Ideal Size returns for the base at the node's defaults, derived by hand from the declared default size and `dimension_grid` |
| `tests/backend/model_manager/load/test_diffusers_0XX_compatibility.py` | New classes, when the dependency is bumped |
| `tests/test_package_data.py` | Nothing if `package-data` covers the vendored files; it checks them |
-| `src/features/generation/core/graphCoverage.testing.ts` (webv2) | `SHAPE_OVERRIDES` and `CANDIDATE_VARIANTS` for variant-dependent graphs |
-| `src/workbench/image-actions/imageRecall.test.ts` (webv2) | The recorded component setting in the remix round-trip list |
+| `src/features/generation/core/graphCoverage.testing.ts` (webv2) | `SHAPE_OVERRIDES` and `CANDIDATE_VARIANTS` for variant-dependent graphs; a non-default value in `recallTunedSettingsFor` for a new recalled setting |
+| `src/workbench/image-actions/imageRecallContract.test.ts` (webv2) | An `IMAGE_RECALL_CONTRACT` entry for every metadata key the builder writes |
Beyond those tables, test what can silently go wrong:
- detection of every format, including negative cases against similar architectures
diff --git a/docs/src/content/docs/development/Architecture/media-metadata.mdx b/docs/src/content/docs/development/Architecture/media-metadata.mdx
index 668f50da0c..ae5d7c6a7a 100644
--- a/docs/src/content/docs/development/Architecture/media-metadata.mdx
+++ b/docs/src/content/docs/development/Architecture/media-metadata.mdx
@@ -109,6 +109,18 @@ The current value is `CORE_METADATA_VERSION` in `invokeai/app/invocations/metada
| `vae` | `ModelIdentifier`: a standalone VAE override |
| `loras` | `LoRA[]`: the LoRAs the graph loaded, in order; absent when none ran |
+### Image profile
+
+Image records add the sampling settings (`cfg_scale`, FLUX's `guidance`, `scheduler`, `cfg_rescale_multiplier`,
+`seamless_x`/`seamless_y`, `clip_skip`, `hidiffusion_*`), each component under its family's key (`t5_encoder`,
+`qwen3_encoder`, `qwen3_source`, `pid_decoder`, ...), the reference images (`ref_images`), the SDXL refiner
+(`refiner_*`), per-family tuning (`dype_*`, `z_image_*`, `qwen_image_*`, `krea2_*`, `ideogram4_*`, `moss_image_*`,
+`pid_*`), hosted-provider options (`image_size`, `openai_*`, `gemini_*`, `seedream_*`), and, from the Canvas,
+`strength`, the control layers and `canvas_v3_metadata`. An upscale adds its own settings (`upscale_*`,
+`creativity`, `structure`, `tile_*`). The keys the coverage fixtures write and the keys the backend declares,
+with what image recall does with each, are listed in `IMAGE_RECALL_CONTRACT`
+(`invokeai/frontend/webv2/src/workbench/image-actions/imageRecallContract.test.ts`).
+
### Video profile
| Key | Type | Notes |
@@ -147,9 +159,11 @@ graph builders write only the canonical ones.
by `name` + `base` + `type`. Keys are minted per install, so a record that travelled with a file
names keys the receiving catalog has never seen; the BLAKE3 hash is the content identity and
resolves the same weights wherever they are installed. The name step is the last resort and the
- only one that can pick a different file of the same model. Image recall resolves its main model
- and components by key only; its **LoRAs** resolve by `key`, then by `hash` when one was recorded,
- otherwise by `name` + `base`, and skip any portable identifier that matches more than one install.
+ only one that can pick a different file of the same model. Image recall resolves its main model,
+ VAE, components, refiner and **LoRAs** by `key`, then by `hash` when one was recorded, otherwise
+ by `name` + `base` (and `type` when recorded). A recorded hash that matches nothing is not
+ replaced by a same-named file, and an identifier that matches more than one install is skipped.
+ Reference-image adapters fall back to `name` + `base` on a hash miss.
- **Media references** (`image_name`, `video_name`) are names in the originating gallery, exactly
as an image record's `init_image` is. Recall restores everything else and clears media it
cannot find rather than substituting.
@@ -163,6 +177,13 @@ same key names from an external process, with models given by name.
1. Add a typed `Optional` field to `CoreMetadataInvocation` under its canonical name, stamp it from
the graph builder, and read it in the recall mappers.
-2. Bump `CORE_METADATA_VERSION`'s minor component. Bump the major only for a rename, removal or
+2. Give the key an entry in the recall contract of each profile that writes it:
+ `IMAGE_RECALL_CONTRACT` (`invokeai/frontend/webv2/src/workbench/image-actions/imageRecallContract.test.ts`)
+ and its video twin, `videoRecallContract.test.ts` beside it. A contract test fails for a key without an
+ entry that the coverage fixtures' graphs write; a key written only under some setting needs that setting off
+ its default in `recallTunedSettingsFor` (`graphCoverage.testing.ts`) or in a dedicated case. A field
+ `CoreMetadataInvocation` declares without an image entry fails webv2's type check once the API types are
+ regenerated.
+3. Bump `CORE_METADATA_VERSION`'s minor component. Bump the major only for a rename, removal or
type change, and add the old spelling to the readers' alias table.
-3. Update the tables on this page.
+4. Update the tables on this page.
diff --git a/invokeai/frontend/webv2/AGENTS.md b/invokeai/frontend/webv2/AGENTS.md
index b02e4ca56d..ed73e777bb 100644
--- a/invokeai/frontend/webv2/AGENTS.md
+++ b/invokeai/frontend/webv2/AGENTS.md
@@ -57,6 +57,7 @@ No Python backend: `pnpm dev:mock` serves the app against the in-repo mock backe
- Missing engines for completion: `pnpm exec playwright install chromium firefox webkit` (`--with-deps` in Linux CI).
- Colocate tests: unit `*.test.ts`/`*.test.tsx`, browser `*.browser.test.ts`/`*.browser.test.tsx`.
- Use real IndexedDB, Web Locks, focus, pointer, rendering where mocks cannot prove correctness.
+- Every metadata key a graph builder writes needs an entry in `src/workbench/image-actions/imageRecallContract.test.ts` or `src/workbench/image-actions/videoRecallContract.test.ts`. They fail only for keys their coverage fixtures write: a key written under some setting needs that setting tuned in the fixtures (`recallTunedSettingsFor` for images).
- Droppable enabled only after drag start: drag through dnd-kit mouse sensors with `dragWithMouse` (`@platform/browser/mouseDrag.testing`). Single-jump drags such as `userEvent.dragAndDrop` miss it.
Unit tests cache transformed modules between runs in ignored `node_modules/.vitest-cache`.
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 0fa3642849..c44bc04611 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -6110,7 +6110,8 @@
"all": "Recalled video data",
"prompts": "Recalled prompts",
"remix": "Remixed video",
- "seed": "Recalled seed"
+ "seed": "Recalled seed",
+ "size": "Recalled size"
},
"beforeCanvasRecall": "Before metadata recall",
"canvasImagesTemporary": "Canvas was recalled, but some restored paint images are still temporary. Keep the project open or save it before closing to protect them from intermediate cleanup.",
diff --git a/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts b/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts
index fc701dc75e..9daa3a0e68 100644
--- a/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/architectureWorkflow.test.ts
@@ -142,6 +142,10 @@ describe('architecture workflow', () => {
for (const [workflowPath] of workflows) {
expect(patterns, path).toContain(workflowPath.replace('../../../../../', ''));
}
+ // A backend change regenerates the API types the type check reads, so it has to run the check too.
+ if (path.endsWith('/frontend-checks.yml')) {
+ expect(patterns, path).toContain('invokeai/frontend/api/schema.ts');
+ }
}
});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
index 5a1e7b47ac..d3256b187b 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
@@ -1,4 +1,4 @@
-import type { BackendGraphContract, GenerationProjectSettings } from '@features/generation/core/contracts';
+import type { BackendGraphContract } from '@features/generation/core/contracts';
import type {
ComponentModelConfig,
GenerateModelConfig,
@@ -11,17 +11,26 @@ import {
architectureCapabilitiesFixture,
seedArchitectureCapabilities,
} from '@features/generation/core/architectureCapabilities.testing';
-import { getDefaultGenerateSettings } from '@features/generation/core/baseGenerationPolicies';
import { getPidDecoderBaseForMainBase } from '@features/generation/core/pid';
import { isPidDecodeNodeType } from '@features/generation/core/pidGraph';
import { describe, expect, it, vi } from 'vitest';
import type { ControlLayerGraphInput } from './addControlLayers';
import type { RegionalGuidanceInput } from './addRegionalGuidance';
-import type { CanvasCompileMode, CanvasCompositingSettings, CanvasScalingSettings, Rect } from './types';
+import type { Rect } from './types';
import { areRegionalNegativesActive, getRegionalGuidanceSupport } from './addRegionalGuidance';
import { compileCanvasGraph } from './compileCanvasGraph';
+import {
+ bbox,
+ compile,
+ COMPONENT_OVERRIDES,
+ COMPOSITING_FIXTURE,
+ PROJECT_SETTINGS,
+ qwen3Encoder,
+ qwenImageVae,
+ settingsFor,
+} from './compileCanvasGraph.testing';
const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };
const sd2Model: MainModelConfig = { base: 'sd-2', key: 'sd2-model', name: 'SD 2', type: 'main' };
@@ -103,98 +112,6 @@ const externalModel: GenerateModelConfig = {
type: 'external_image_generator',
};
-const fluxVae: VaeModelConfig = { base: 'flux', key: 'flux-vae', name: 'FLUX VAE', type: 'vae' };
-const qwenImageVae: VaeModelConfig = { base: 'qwen-image', key: 'qwen-vae', name: 'Qwen VAE', type: 'vae' };
-const t5Encoder: ComponentModelConfig = { base: 'any', key: 't5', name: 'T5 Encoder', type: 't5_encoder' };
-const clipEmbed: ComponentModelConfig = {
- base: 'any',
- key: 'clip',
- name: 'CLIP Embed',
- type: 'clip_embed',
- variant: 'large',
-};
-const qwen3Encoder: ComponentModelConfig = {
- base: 'any',
- key: 'qwen3',
- name: 'Qwen3 Encoder',
- type: 'qwen3_encoder',
- variant: 'qwen3_06b',
-};
-
-const PROJECT_SETTINGS: GenerationProjectSettings = { useCpuNoise: true, useNsfwChecker: false, useWatermark: false };
-
-const settingsFor = (model: GenerateModelConfig, overrides: Partial<GenerateSettings> = {}): GenerateSettings => ({
- ...getDefaultGenerateSettings(model),
- seed: 1,
- seedMode: 'fixed',
- ...overrides,
-});
-
-/** Per-base overrides needed to pass component validation. */
-const COMPONENT_OVERRIDES: Partial<Record<string, Partial<GenerateSettings>>> = {
- flux: { clipEmbedModel: clipEmbed, t5EncoderModel: t5Encoder, vae: fluxVae },
- anima: { qwen3EncoderModel: qwen3Encoder, vae: qwenImageVae },
-};
-
-const bbox: Rect = { height: 1024, width: 768, x: 128, y: 64 };
-
-const COMPOSITING_FIXTURE: CanvasCompositingSettings = {
- coherenceEdgeSize: 16,
- coherenceMinDenoise: 0,
- coherenceMode: 'Gaussian Blur',
- infillColorValue: { a: 1, b: 0, g: 0, r: 0 },
- infillMethod: 'lama',
- infillPatchmatchDownscaleSize: 1,
- infillTileSize: 32,
- maskBlur: 16,
- outputOnlyMaskedRegions: false,
-};
-
-const compile = (
- model: GenerateModelConfig,
- mode: CanvasCompileMode,
- overrides: {
- settings?: Partial<GenerateSettings>;
- bbox?: Rect;
- compositeImageName?: string | null;
- maskImageName?: string | null;
- noiseMaskImageName?: string | null;
- compositing?: Partial<CanvasCompositingSettings>;
- scaling?: CanvasScalingSettings;
- strength?: number;
- destination?: 'canvas' | 'gallery';
- outputOnlyMaskedRegions?: boolean;
- controlLayers?: readonly ControlLayerGraphInput[];
- regionalGuidance?: readonly RegionalGuidanceInput[];
- projectSettings?: Partial<GenerationProjectSettings>;
- } = {}
-) =>
- compileCanvasGraph({
- bbox: overrides.bbox ?? bbox,
- compositeImageName:
- 'compositeImageName' in overrides ? (overrides.compositeImageName ?? null) : 'canvas-composite.png',
- compositing: {
- ...COMPOSITING_FIXTURE,
- outputOnlyMaskedRegions: overrides.outputOnlyMaskedRegions ?? false,
- ...overrides.compositing,
- },
- controlLayers: overrides.controlLayers,
- regionalGuidance: overrides.regionalGuidance,
- scaling: overrides.scaling,
- destination: overrides.destination ?? 'canvas',
- maskImageName:
- 'maskImageName' in overrides ? overrides.maskImageName : mode === 'inpaint' ? 'canvas-mask.png' : null,
- mode,
- model,
- noiseMaskImageName: overrides.noiseMaskImageName ?? null,
- projectSettings: { ...PROJECT_SETTINGS, ...overrides.projectSettings },
- settings: settingsFor(model, {
- ...COMPONENT_OVERRIDES[model.base],
- ...overrides.settings,
- }),
- strength: overrides.strength ?? 0.6,
- });
-
const getEdge = (graph: BackendGraphContract, targetNodeId: string, targetField: string) =>
graph.edges.find((edge) => edge.destination.node_id === targetNodeId && edge.destination.field === targetField);
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.testing.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.testing.ts
new file mode 100644
index 0000000000..917214ee2c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.testing.ts
@@ -0,0 +1,127 @@
+/** Canvas compile fixtures, shared by the compiler's tests and the image recall contract. */
+
+import type { GenerationProjectSettings } from '@features/generation/core/contracts';
+import type {
+ ComponentModelConfig,
+ GenerateModelConfig,
+ GenerateSettings,
+ MainModelConfig,
+ VaeModelConfig,
+} from '@features/generation/core/types';
+
+import { getDefaultGenerateSettings } from '@features/generation/core/baseGenerationPolicies';
+import { getFamilyGraphBuilder } from '@features/generation/core/graph';
+
+import type { ControlLayerGraphInput } from './addControlLayers';
+import type { RegionalGuidanceInput } from './addRegionalGuidance';
+import type { CanvasCompileMode, CanvasCompositingSettings, CanvasScalingSettings, Rect } from './types';
+
+import { compileCanvasGraph } from './compileCanvasGraph';
+
+const fluxVae: VaeModelConfig = { base: 'flux', key: 'flux-vae', name: 'FLUX VAE', type: 'vae' };
+export const qwenImageVae: VaeModelConfig = { base: 'qwen-image', key: 'qwen-vae', name: 'Qwen VAE', type: 'vae' };
+const t5Encoder: ComponentModelConfig = { base: 'any', key: 't5', name: 'T5 Encoder', type: 't5_encoder' };
+const clipEmbed: ComponentModelConfig = {
+ base: 'any',
+ key: 'clip',
+ name: 'CLIP Embed',
+ type: 'clip_embed',
+ variant: 'large',
+};
+export const qwen3Encoder: ComponentModelConfig = {
+ base: 'any',
+ key: 'qwen3',
+ name: 'Qwen3 Encoder',
+ type: 'qwen3_encoder',
+ variant: 'qwen3_06b',
+};
+
+export const PROJECT_SETTINGS: GenerationProjectSettings = {
+ useCpuNoise: true,
+ useNsfwChecker: false,
+ useWatermark: false,
+};
+
+export const settingsFor = (
+ model: GenerateModelConfig,
+ overrides: Partial<GenerateSettings> = {}
+): GenerateSettings => ({
+ ...getDefaultGenerateSettings(model),
+ seed: 1,
+ seedMode: 'fixed',
+ ...overrides,
+});
+
+/** Per-base overrides needed to pass component validation. */
+export const COMPONENT_OVERRIDES: Partial<Record<string, Partial<GenerateSettings>>> = {
+ flux: { clipEmbedModel: clipEmbed, t5EncoderModel: t5Encoder, vae: fluxVae },
+ anima: { qwen3EncoderModel: qwen3Encoder, vae: qwenImageVae },
+};
+
+export const bbox: Rect = { height: 1024, width: 768, x: 128, y: 64 };
+
+export const COMPOSITING_FIXTURE: CanvasCompositingSettings = {
+ coherenceEdgeSize: 16,
+ coherenceMinDenoise: 0,
+ coherenceMode: 'Gaussian Blur',
+ infillColorValue: { a: 1, b: 0, g: 0, r: 0 },
+ infillMethod: 'lama',
+ infillPatchmatchDownscaleSize: 1,
+ infillTileSize: 32,
+ maskBlur: 16,
+ outputOnlyMaskedRegions: false,
+};
+
+/** Compiles `mode` over the fixture frame; settings that name every key replace the defaults and overrides. */
+export const compile = (
+ model: GenerateModelConfig,
+ mode: CanvasCompileMode,
+ overrides: {
+ settings?: Partial<GenerateSettings>;
+ bbox?: Rect;
+ canvasMetadata?: Record<string, unknown>;
+ compositeImageName?: string | null;
+ maskImageName?: string | null;
+ noiseMaskImageName?: string | null;
+ compositing?: Partial<CanvasCompositingSettings>;
+ scaling?: CanvasScalingSettings;
+ strength?: number;
+ destination?: 'canvas' | 'gallery';
+ outputOnlyMaskedRegions?: boolean;
+ controlLayers?: readonly ControlLayerGraphInput[];
+ regionalGuidance?: readonly RegionalGuidanceInput[];
+ projectSettings?: Partial<GenerationProjectSettings>;
+ } = {}
+) =>
+ compileCanvasGraph({
+ bbox: overrides.bbox ?? bbox,
+ canvasMetadata: overrides.canvasMetadata,
+ compositeImageName:
+ 'compositeImageName' in overrides ? (overrides.compositeImageName ?? null) : 'canvas-composite.png',
+ compositing: {
+ ...COMPOSITING_FIXTURE,
+ outputOnlyMaskedRegions: overrides.outputOnlyMaskedRegions ?? false,
+ ...overrides.compositing,
+ },
+ controlLayers: overrides.controlLayers,
+ regionalGuidance: overrides.regionalGuidance,
+ scaling: overrides.scaling,
+ destination: overrides.destination ?? 'canvas',
+ maskImageName:
+ 'maskImageName' in overrides ? overrides.maskImageName : mode === 'inpaint' ? 'canvas-mask.png' : null,
+ mode,
+ model,
+ noiseMaskImageName: overrides.noiseMaskImageName ?? null,
+ projectSettings: { ...PROJECT_SETTINGS, ...overrides.projectSettings },
+ settings: settingsFor(model, {
+ ...COMPONENT_OVERRIDES[model.base],
+ ...overrides.settings,
+ }),
+ strength: overrides.strength ?? 0.6,
+ });
+
+/** The modes a local model compiles on the canvas: the image modes encode through the family's VAE, if it has one. */
+export const canvasModesFor = (model: MainModelConfig, settings: GenerateSettings): CanvasCompileMode[] =>
+ getFamilyGraphBuilder(model.base)?.(settings, model, false, PROJECT_SETTINGS).latents
+ ? ['txt2img', 'img2img', 'inpaint']
+ : ['txt2img'];
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.ts b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.ts
index f0809bdcb7..52f7c77bae 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.ts
@@ -8,6 +8,10 @@ import type {
SupportedGenerateBase,
} from './baseGenerationPolicies';
import type {
+ ComponentModelConfig,
+ ExternalImageGeneratorModelConfig,
+ ExternalImageSize,
+ GenerateModelConfig,
GenerateReferenceImage,
GenerateReferenceImageAsset,
GenerateSettings,
@@ -16,12 +20,19 @@ import type {
} from './types';
import {
+ GENERATE_COMPONENT_VALUE_KEYS,
getComponentSectionPolicy,
getDefaultGenerateSettings,
+ getGenerationDimensions,
+ getGenerationUiPolicy,
+ getSchedulerOptions,
+ isLoraSupported,
isReferenceImageSupported,
SUPPORTED_GENERATE_BASES,
+ withAddedReferenceImages,
} from './baseGenerationPolicies';
import { getIsPidSupportedBase } from './pid';
+import { clampDimension, deriveAspectRatioId } from './settings';
/** Compile both bundled and standalone component paths. */
export interface ModelShape {
@@ -314,3 +325,307 @@ export const tunedSettingsFor = (base: SupportedGenerateBase, shape: ModelShape)
},
};
};
+
+const RECALL_REFERENCE_IMAGE: GenerateReferenceImageAsset = {
+ original: { image: { height: 512, image_name: 'recall-reference.png', width: 512 } },
+};
+
+/**
+ * Every setting image recall restores, at a value the policy accepts and no default holds, so a round trip that drops
+ * one shows. Values a family does not record are harmless to carry. Seamless tiling and CFG rescale stay at their
+ * defaults where the panel hides them: recall restores them on every family.
+ */
+const withRecallTuning = (
+ model: GenerateModelConfig,
+ settings: GenerateSettings,
+ size: ExternalImageSize
+): GenerateSettings => {
+ const defaults = getDefaultGenerateSettings(model);
+ const policy = getGenerationUiPolicy(model);
+
+ return {
+ ...settings,
+ // Canvas inpainting then runs without the adapter in the filled slot, so its record shows the switch off.
+ animaInpaintAdapterEnabled: false,
+ aspectRatioId: deriveAspectRatioId(size.width, size.height),
+ aspectRatioValue: size.width / size.height,
+ cfgRescaleMultiplier: policy.cfgRescaleVisible ? 0.3 : defaults.cfgRescaleMultiplier,
+ // FLUX.3 Klein samples without CFG: validation refuses any scale but its default.
+ cfgScale:
+ model.base === 'flux3' && model.variant === 'flux3_klein'
+ ? defaults.cfgScale
+ : Math.min(policy.guidanceMax ?? Number.POSITIVE_INFINITY, defaults.cfgScale + 0.5),
+ clipSkip: policy.clipSkipMax === null ? defaults.clipSkip : 2,
+ fluxDypeExponent: 1,
+ fluxDypePreset: 'manual',
+ fluxDypeScale: 3,
+ height: size.height,
+ ...(policy.hiDiffusionVisible
+ ? {
+ hiDiffusionEnabled: true,
+ hiDiffusionRauNetEnabled: false,
+ hiDiffusionT1Ratio: 0.6,
+ hiDiffusionT2Ratio: 0.2,
+ hiDiffusionWindowAttentionEnabled: false,
+ }
+ : {}),
+ ideogram4ColorPalette: ['teal', 'amber'],
+ ideogram4GuidanceScale: 5,
+ ideogram4Mu: 1,
+ ideogram4SamplerPreset: 'V4_TURBO_12',
+ ideogram4Steps: 30,
+ krea2RebalanceEnabled: true,
+ krea2RebalanceMultiplier: 3,
+ krea2RebalanceWeights: '1.0,1.0,1.0,1.0,1.0,1.0,1.0,2.0,4.0,1.0,3.0,1.0',
+ krea2SeedVarianceEnabled: true,
+ krea2SeedVarianceRandomizePercent: 40,
+ krea2SeedVarianceStrength: 0.3,
+ loras: isLoraSupported(model)
+ ? [
+ {
+ isEnabled: true,
+ model: { base: model.base, key: `${model.base}-recall-lora`, name: `${model.base} LoRA`, type: 'lora' },
+ weight: 0.75,
+ },
+ ]
+ : [],
+ mossImageUncondSkipLayers: [10, 22],
+ negativePrompt: 'a recall-tuned negative prompt',
+ pidSteps: 6,
+ qwenImageEncoderQuantization: 'nf4',
+ qwenImageShift: 2,
+ scheduler: getSchedulerOptions(model)[1]!.value,
+ seamlessXAxis: policy.seamlessVisible,
+ seamlessYAxis: policy.seamlessVisible,
+ steps: defaults.steps + 1,
+ wanGuidanceScaleLowNoise: 3.5,
+ width: size.width,
+ zImageSeedVarianceEnabled: true,
+ zImageSeedVarianceRandomizePercent: 40,
+ zImageSeedVarianceStrength: 0.3,
+ zImageShift: 2,
+ };
+};
+
+/** The reference the family reads: an adapter where the base takes one, otherwise the base's own reference type. */
+const recallReferenceImagesFor = (model: MainModelConfig, settings: GenerateSettings): GenerateReferenceImage[] => {
+ if (model.base === 'krea-2') {
+ return [
+ {
+ config: { image: RECALL_REFERENCE_IMAGE, styleStrength: 1.5, type: 'krea2_reference_image' },
+ id: 'style',
+ isEnabled: true,
+ },
+ ];
+ }
+
+ return isReferenceImageSupported(model, settings)
+ ? withAddedReferenceImages(
+ model,
+ [{ base: model.base, key: `${model.base}-ip-adapter`, name: `${model.base} IP Adapter`, type: 'ip_adapter' }],
+ [],
+ [{ id: 'reference', image: RECALL_REFERENCE_IMAGE }]
+ )
+ : [];
+};
+
+/**
+ * A shape with every component filled and every recalled setting tuned off its default, PiD decoding included, and
+ * the family's reference where it reads one. The size is off the model's default and not square. Z-Image decodes in
+ * native PiD, which generates at a quarter of the recorded size, and the other PiD families in fit.
+ */
+export const recallTunedSettingsFor = (base: SupportedGenerateBase, shape: ModelShape) => {
+ const { model, settings: fullyFilled } = fullyFilledSettingsFor(base, shape);
+ const filled: GenerateSettings =
+ base === 'z-image' && fullyFilled.pidMode === 'fit' ? { ...fullyFilled, pidMode: 'native' } : fullyFilled;
+ const defaults = getDefaultGenerateSettings(model);
+ const { grid } = getGenerationDimensions(model, filled.pidMode);
+ const settings = withRecallTuning(model, filled, {
+ height: clampDimension(defaults.height * 0.75, grid),
+ width: clampDimension(defaults.width + grid, grid),
+ });
+
+ return {
+ label: `${base} / ${shape.label}`,
+ model,
+ settings: { ...settings, referenceImages: recallReferenceImagesFor(model, settings) },
+ };
+};
+
+/** The installed models a recall resolves the record against, the way the gallery hands them over. */
+export const recallCatalogFor = (model: GenerateModelConfig, settings: GenerateSettings) => ({
+ models: [
+ model,
+ ...GENERATE_COMPONENT_VALUE_KEYS.flatMap((key): ComponentModelConfig[] => {
+ const component = settings[key];
+
+ return component ? [component] : [];
+ }),
+ ...settings.loras.map((lora) => lora.model),
+ ...(settings.refinerModel ? [settings.refinerModel] : []),
+ ...settings.referenceImages.flatMap(({ config }): ComponentModelConfig[] =>
+ 'model' in config && config.model ? [config.model] : []
+ ),
+ ],
+ supportedModels: [model],
+ vaeModels: settings.vae ? [settings.vae] : [],
+});
+
+/** SDXL finishing with its refiner, tuned off every refiner default; PiD, which replaces the decode it feeds, is off. */
+export const sdxlRefinerRecallCase = () => {
+ const { model, settings } = recallTunedSettingsFor('sdxl', {
+ label: 'diffusers-with-refiner',
+ overrides: { format: 'diffusers' },
+ });
+ const refiner: MainModelConfig = { base: 'sdxl-refiner', key: 'sdxl-refiner', name: 'SDXL Refiner', type: 'main' };
+
+ return {
+ label: 'sdxl / diffusers-with-refiner',
+ model,
+ settings: {
+ ...settings,
+ pidMode: 'off' as const,
+ refinerCfgScale: 6,
+ refinerModel: refiner,
+ refinerNegativeAestheticScore: 2,
+ refinerPositiveAestheticScore: 7,
+ refinerScheduler: 'dpmpp_2m',
+ refinerStart: 0.7,
+ refinerSteps: 21,
+ },
+ };
+};
+
+/** FLUX with a Redux reference in place of the IP-Adapter the tuned recipe carries. */
+export const fluxReduxRecallCase = () => {
+ const { model, settings } = recallTunedSettingsFor('flux', {
+ label: 'diffusers-with-redux',
+ overrides: { format: 'diffusers' },
+ });
+ const redux: ComponentModelConfig = { base: 'flux', key: 'flux-redux', name: 'FLUX Redux', type: 'flux_redux' };
+
+ return {
+ label: 'flux / diffusers-with-redux',
+ model,
+ settings: {
+ ...settings,
+ referenceImages: [
+ {
+ config: {
+ image: RECALL_REFERENCE_IMAGE,
+ imageInfluence: 'high' as const,
+ model: redux,
+ type: 'flux_redux' as const,
+ },
+ id: 'redux',
+ isEnabled: true,
+ },
+ ],
+ },
+ };
+};
+
+/** Krea-2 edit references in place of the style reference, read by the tuned LoRA, with the reference K/V cache on. */
+export const krea2EditRecallCase = () => {
+ const { model, settings } = recallTunedSettingsFor('krea-2', {
+ label: 'diffusers-with-edit-references',
+ overrides: { format: 'diffusers' },
+ });
+
+ return {
+ label: 'krea-2 / diffusers-with-edit-references',
+ model,
+ settings: {
+ ...settings,
+ krea2ReferenceKvCache: true,
+ referenceImages: ['edit-1', 'edit-2'].map((id) => ({
+ config: { image: RECALL_REFERENCE_IMAGE, type: 'krea2_edit_reference_image' as const },
+ id,
+ isEnabled: true,
+ })),
+ },
+ };
+};
+
+const externalRecallCase = (
+ model: ExternalImageGeneratorModelConfig,
+ size: ExternalImageSize,
+ options: Partial<GenerateSettings>
+) => ({
+ label: `external / ${model.provider_id}`,
+ model,
+ settings: {
+ ...withRecallTuning(
+ model,
+ { ...getDefaultGenerateSettings(model), positivePrompt: 'a test prompt', seed: 1, seedMode: 'fixed' },
+ size
+ ),
+ ...options,
+ },
+});
+
+/**
+ * One model per hosted provider, each with its own options: GPT Image with a reference image, Gemini at one of its
+ * named sizes, Seedream.
+ */
+export const externalRecallCases = () => [
+ externalRecallCase(
+ {
+ base: 'external',
+ capabilities: { max_reference_images: 4, modes: ['txt2img', 'img2img'], supports_reference_images: true },
+ format: 'external_api',
+ key: 'openai-gpt-image-1',
+ name: 'GPT Image 1',
+ provider_id: 'openai',
+ provider_model_id: 'gpt-image-1',
+ type: 'external_image_generator',
+ },
+ { height: 1536, width: 1152 },
+ {
+ openaiBackground: 'transparent',
+ openaiInputFidelity: 'high',
+ openaiQuality: 'high',
+ referenceImages: [
+ {
+ config: { image: RECALL_REFERENCE_IMAGE, type: 'external_reference_image' },
+ id: 'reference',
+ isEnabled: true,
+ },
+ ],
+ }
+ ),
+ externalRecallCase(
+ {
+ base: 'external',
+ capabilities: {
+ modes: ['txt2img'],
+ resolution_presets: [
+ { aspect_ratio: '1:1', height: 1024, image_size: '1K', label: 'Square', width: 1024 },
+ { aspect_ratio: '16:9', height: 1152, image_size: '2K', label: 'Landscape', width: 2048 },
+ ],
+ },
+ format: 'external_api',
+ key: 'gemini-image',
+ name: 'Gemini Image',
+ provider_id: 'gemini',
+ provider_model_id: 'gemini-3-pro-image-preview',
+ type: 'external_image_generator',
+ },
+ { height: 1152, width: 2048 },
+ { externalImageSize: '2K', geminiTemperature: 0.7, geminiThinkingLevel: 'high' }
+ ),
+ externalRecallCase(
+ {
+ base: 'external',
+ capabilities: { modes: ['txt2img'], supports_seed: true },
+ format: 'external_api',
+ key: 'seedream-4-5',
+ name: 'Seedream 4.5',
+ provider_id: 'seedream',
+ provider_model_id: 'seedream-4-5-251128',
+ type: 'external_image_generator',
+ },
+ { height: 1536, width: 2048 },
+ { seedreamOptimizePrompt: true, seedreamWatermark: true }
+ ),
+];
diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.ts
index 44acb3d32d..880f28aeb5 100644
--- a/invokeai/frontend/webv2/src/features/generation/settings.ts
+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts
@@ -132,6 +132,7 @@ export {
type RebalancePreset,
} from './core/conditioningRebalance';
export { MIN_BATCH_COUNT, sanitizeBatchCount } from './core/batch';
+export { clampPidSteps, isPidMode } from './core/pid';
export {
getActiveRefiner,
isRefinerModel,
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/upscaleGraphCoverage.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/upscaleGraphCoverage.test.ts
index 4edf2717ec..d7dc01a491 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/upscaleGraphCoverage.test.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/upscaleGraphCoverage.test.ts
@@ -1,7 +1,6 @@
/** Cover every upscale builder against the backend-validated node/field/literal/connection fixture. */
import type { BackendGraphContract } from '@features/generation/contracts';
-import type { ModelConfig } from '@features/models';
import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
import { describe, expect, it } from 'vitest';
@@ -9,118 +8,15 @@ import { describe, expect, it } from 'vitest';
import type { UpscaleWidgetValues } from './types';
import { compileModelOnlyUpscaleGraph, compileUpscaleGraph } from './graph';
-import { createDefaultUpscaleWidgetValues, getUpscaleValidationReasons, UPSCALE_ARCHITECTURES } from './settings';
+import { getUpscaleValidationReasons, UPSCALE_ARCHITECTURES } from './settings';
+import { CASES, INSTALLED, valuesForCase } from './upscaleGraphCoverage.testing';
seedArchitectureCapabilities();
-const model = (key: string, type: string, base: string, extra: Record<string, unknown> = {}): ModelConfig =>
- ({
- base,
- file_size: 1,
- format: 'checkpoint',
- hash: `${key}-hash`,
- key,
- name: key,
- path: key,
- source: key,
- source_type: 'path',
- type,
- ...extra,
- }) as ModelConfig;
-
-/** What the widget picks components from, the way it does for a user. */
-const INSTALLED = [
- model('spandrel', 'spandrel_image_to_image', 'any'),
- model('t5', 't5_encoder', 'any'),
- model('clip', 'clip_embed', 'any', { variant: 'large' }),
- model('qwen3-4b', 'qwen3_encoder', 'any', { variant: 'qwen3_4b' }),
- model('qwen3-8b', 'qwen3_encoder', 'any', { variant: 'qwen3_8b' }),
- model('qwen3-06b', 'qwen3_encoder', 'any', { variant: 'qwen3_06b' }),
- model('qwen35', 'qwen3_5_encoder', 'any', { variant: 'qwen3_5_4b' }),
- model('qwen3vl-4b', 'qwen3_vl_encoder', 'any', { variant: 'qwen3_vl_4b' }),
- model('qwen-vl', 'qwen_vl_encoder', 'any'),
- model('mistral', 'mistral_encoder', 'any', { variant: 'mistral3_24b' }),
- model('flux-vae', 'vae', 'flux'),
- model('flux2-vae', 'vae', 'flux2'),
- model('qwen-vae', 'vae', 'qwen-image'),
- model('sd1-tile', 'controlnet', 'sd-1', { name: 'sd1 tile' }),
- model('sdxl-tile', 'controlnet', 'sdxl', { name: 'sdxl tile' }),
- model('z-tile', 'controlnet', 'z-image', { name: 'Z-Image ControlNet Tile' }),
-];
+const compileCase = (testCase: (typeof CASES)[number]): BackendGraphContract => {
+ const { values } = valuesForCase(testCase);
-/**
- * One case per path a builder can take: CFG above 1 where the negative branch is CFG-gated, the
- * optional Z-Image ControlNet, a bundled Z-Image, Krea-2, FLUX.2 or Qwen Image install, Anima-3.8B's
- * second encoder, and FLUX.2 Klein at either encoder size and [dev] with its own loaders.
- */
-const CASES: { label: string; main: ModelConfig; patch?: Partial<UpscaleWidgetValues> }[] = [
- { label: 'sd-1', main: model('sd1', 'main', 'sd-1') },
- { label: 'sdxl', main: model('sdxl', 'main', 'sdxl') },
- { label: 'flux', main: model('flux', 'main', 'flux') },
- {
- label: 'z-image',
- main: model('z', 'main', 'z-image'),
- patch: {
- cfgScale: 4,
- tileControlnetModel: INSTALLED.find(({ key }) => key === 'z-tile') as UpscaleWidgetValues['tileControlnetModel'],
- },
- },
- { label: 'z-image-diffusers', main: model('z-diffusers', 'main', 'z-image', { format: 'diffusers' }) },
- { label: 'anima', main: model('anima', 'main', 'anima', { variant: 'anima_qwen3' }), patch: { cfgScale: 4.5 } },
- {
- label: 'anima-3.8b',
- main: model('anima-38', 'main', 'anima', { variant: 'anima_qwen35' }),
- patch: { cfgScale: 6 },
- },
- { label: 'krea-2-turbo', main: model('krea2-turbo', 'main', 'krea-2', { variant: 'krea2_turbo' }) },
- {
- label: 'krea-2-raw',
- main: model('krea2-raw', 'main', 'krea-2', { format: 'gguf_quantized', variant: 'krea2_base' }),
- patch: { cfgScale: 5.5 },
- },
- {
- label: 'krea-2-diffusers',
- main: model('krea2-diffusers', 'main', 'krea-2', { format: 'diffusers', variant: 'krea2_turbo' }),
- },
- { label: 'flux2-klein-4b', main: model('klein-4b', 'main', 'flux2', { variant: 'klein_4b' }) },
- {
- label: 'flux2-klein-9b',
- main: model('klein-9b', 'main', 'flux2', { format: 'gguf_quantized', variant: 'klein_9b' }),
- },
- { label: 'flux2-klein-base', main: model('klein-base', 'main', 'flux2', { variant: 'klein_4b_base' }) },
- {
- label: 'flux2-dev',
- main: model('flux2-dev', 'main', 'flux2', { format: 'gguf_quantized', variant: 'dev' }),
- patch: { cfgScale: 3.5 },
- },
- {
- label: 'flux2-diffusers',
- main: model('klein-diffusers', 'main', 'flux2', { format: 'diffusers', variant: 'klein_9b' }),
- },
- {
- label: 'qwen-image',
- main: model('qwen', 'main', 'qwen-image', { format: 'gguf_quantized', variant: 'generate' }),
- patch: { cfgScale: 4 },
- },
- {
- label: 'qwen-image-diffusers',
- main: model('qwen-diffusers', 'main', 'qwen-image', { format: 'diffusers', variant: 'generate' }),
- patch: { cfgScale: 1 },
- },
-];
-
-const compileCase = ({ main, patch }: (typeof CASES)[number]): BackendGraphContract => {
- const installed = [main, ...INSTALLED, model(`${main.key}-lora`, 'lora', main.base)];
- const defaults = createDefaultUpscaleWidgetValues(installed);
- const values: UpscaleWidgetValues = {
- ...defaults,
- inputImage: { height: 101, image_name: 'input.png', width: 203 },
- // Every builder's concept loader, so its node and edges reach the contract too.
- loras: [{ isEnabled: true, model: installed.at(-1) as UpscaleWidgetValues['loras'][number]['model'], weight: 1 }],
- ...patch,
- };
-
- expect(getUpscaleValidationReasons(values), `${main.key} is not satisfiable`).toEqual([]);
+ expect(getUpscaleValidationReasons(values), `${testCase.main.key} is not satisfiable`).toEqual([]);
return compileUpscaleGraph(values, 'gallery', { useCpuNoise: true }).backendGraph;
};
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/upscaleGraphCoverage.testing.ts b/invokeai/frontend/webv2/src/features/upscale/core/upscaleGraphCoverage.testing.ts
new file mode 100644
index 0000000000..aa2f56e8d8
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/upscale/core/upscaleGraphCoverage.testing.ts
@@ -0,0 +1,118 @@
+/** Upscale coverage fixtures, shared by the graph coverage and the image recall contract. */
+
+import type { ModelConfig } from '@features/models';
+
+import type { UpscaleWidgetValues } from './types';
+
+import { createDefaultUpscaleWidgetValues } from './settings';
+
+const model = (key: string, type: string, base: string, extra: Record<string, unknown> = {}): ModelConfig =>
+ ({
+ base,
+ file_size: 1,
+ format: 'checkpoint',
+ hash: `${key}-hash`,
+ key,
+ name: key,
+ path: key,
+ source: key,
+ source_type: 'path',
+ type,
+ ...extra,
+ }) as ModelConfig;
+
+/** What the widget picks components from, the way it does for a user. */
+export const INSTALLED = [
+ model('spandrel', 'spandrel_image_to_image', 'any'),
+ model('t5', 't5_encoder', 'any'),
+ model('clip', 'clip_embed', 'any', { variant: 'large' }),
+ model('qwen3-4b', 'qwen3_encoder', 'any', { variant: 'qwen3_4b' }),
+ model('qwen3-8b', 'qwen3_encoder', 'any', { variant: 'qwen3_8b' }),
+ model('qwen3-06b', 'qwen3_encoder', 'any', { variant: 'qwen3_06b' }),
+ model('qwen35', 'qwen3_5_encoder', 'any', { variant: 'qwen3_5_4b' }),
+ model('qwen3vl-4b', 'qwen3_vl_encoder', 'any', { variant: 'qwen3_vl_4b' }),
+ model('qwen-vl', 'qwen_vl_encoder', 'any'),
+ model('mistral', 'mistral_encoder', 'any', { variant: 'mistral3_24b' }),
+ model('flux-vae', 'vae', 'flux'),
+ model('flux2-vae', 'vae', 'flux2'),
+ model('qwen-vae', 'vae', 'qwen-image'),
+ model('sd1-tile', 'controlnet', 'sd-1', { name: 'sd1 tile' }),
+ model('sdxl-tile', 'controlnet', 'sdxl', { name: 'sdxl tile' }),
+ model('z-tile', 'controlnet', 'z-image', { name: 'Z-Image ControlNet Tile' }),
+];
+
+/**
+ * One case per path a builder can take: CFG above 1 where the negative branch is CFG-gated, the
+ * optional Z-Image ControlNet, a bundled Z-Image, Krea-2, FLUX.2 or Qwen Image install, Anima-3.8B's
+ * second encoder, and FLUX.2 Klein at either encoder size and [dev] with its own loaders.
+ */
+export const CASES: { label: string; main: ModelConfig; patch?: Partial<UpscaleWidgetValues> }[] = [
+ { label: 'sd-1', main: model('sd1', 'main', 'sd-1') },
+ { label: 'sdxl', main: model('sdxl', 'main', 'sdxl') },
+ { label: 'flux', main: model('flux', 'main', 'flux') },
+ {
+ label: 'z-image',
+ main: model('z', 'main', 'z-image'),
+ patch: {
+ cfgScale: 4,
+ tileControlnetModel: INSTALLED.find(({ key }) => key === 'z-tile') as UpscaleWidgetValues['tileControlnetModel'],
+ },
+ },
+ { label: 'z-image-diffusers', main: model('z-diffusers', 'main', 'z-image', { format: 'diffusers' }) },
+ { label: 'anima', main: model('anima', 'main', 'anima', { variant: 'anima_qwen3' }), patch: { cfgScale: 4.5 } },
+ {
+ label: 'anima-3.8b',
+ main: model('anima-38', 'main', 'anima', { variant: 'anima_qwen35' }),
+ patch: { cfgScale: 6 },
+ },
+ { label: 'krea-2-turbo', main: model('krea2-turbo', 'main', 'krea-2', { variant: 'krea2_turbo' }) },
+ {
+ label: 'krea-2-raw',
+ main: model('krea2-raw', 'main', 'krea-2', { format: 'gguf_quantized', variant: 'krea2_base' }),
+ patch: { cfgScale: 5.5 },
+ },
+ {
+ label: 'krea-2-diffusers',
+ main: model('krea2-diffusers', 'main', 'krea-2', { format: 'diffusers', variant: 'krea2_turbo' }),
+ },
+ { label: 'flux2-klein-4b', main: model('klein-4b', 'main', 'flux2', { variant: 'klein_4b' }) },
+ {
+ label: 'flux2-klein-9b',
+ main: model('klein-9b', 'main', 'flux2', { format: 'gguf_quantized', variant: 'klein_9b' }),
+ },
+ { label: 'flux2-klein-base', main: model('klein-base', 'main', 'flux2', { variant: 'klein_4b_base' }) },
+ {
+ label: 'flux2-dev',
+ main: model('flux2-dev', 'main', 'flux2', { format: 'gguf_quantized', variant: 'dev' }),
+ patch: { cfgScale: 3.5 },
+ },
+ {
+ label: 'flux2-diffusers',
+ main: model('klein-diffusers', 'main', 'flux2', { format: 'diffusers', variant: 'klein_9b' }),
+ },
+ {
+ label: 'qwen-image',
+ main: model('qwen', 'main', 'qwen-image', { format: 'gguf_quantized', variant: 'generate' }),
+ patch: { cfgScale: 4 },
+ },
+ {
+ label: 'qwen-image-diffusers',
+ main: model('qwen-diffusers', 'main', 'qwen-image', { format: 'diffusers', variant: 'generate' }),
+ patch: { cfgScale: 1 },
+ },
+];
+
+/** The widget values a case compiles, picked from the installed models plus its main model and a LoRA for it. */
+export const valuesForCase = ({ main, patch }: (typeof CASES)[number]) => {
+ const installed = [main, ...INSTALLED, model(`${main.key}-lora`, 'lora', main.base)];
+ const defaults = createDefaultUpscaleWidgetValues(installed);
+ const values: UpscaleWidgetValues = {
+ ...defaults,
+ inputImage: { height: 101, image_name: 'input.png', width: 203 },
+ // Every builder's concept loader, so its node and edges reach the contract too.
+ loras: [{ isEnabled: true, model: installed.at(-1) as UpscaleWidgetValues['loras'][number]['model'], weight: 1 }],
+ ...patch,
+ };
+
+ return { installed, values };
+};
diff --git a/invokeai/frontend/webv2/src/features/video/core/videoGraphCoverage.test.ts b/invokeai/frontend/webv2/src/features/video/core/videoGraphCoverage.test.ts
index f71eea618c..5af7ec70cf 100644
--- a/invokeai/frontend/webv2/src/features/video/core/videoGraphCoverage.test.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/videoGraphCoverage.test.ts
@@ -20,251 +20,10 @@
* the formatter and this test are not both in charge of the same bytes.
*/
-import type { GenerationModelCatalogItem as ModelConfig, MainModelConfig } from '@features/generation/contracts';
-import type { BackendGraphContract } from '@features/generation/core/contracts';
-
import { describe, expect, it } from 'vitest';
-import type { VideoGenerationMode, VideoSettings, VideoSourceClip, VideoTargetResolution } from './types';
-import type { VideoComponentPolicyContext, VideoComponentSlotPolicy, VideoComponentValueKey } from './videoPolicies';
-
-import { compileVideoGraph } from './graph';
-import {
- getDefaultVideoSettings,
- getVideoComponentSectionPolicy,
- getVideoValidationReasons,
- isAutoDurationActive,
- isTwoStageSupportedForMode,
- isVideoModelSelectable,
- SUPPORTED_VIDEO_BASES,
- VIDEO_GENERATION,
-} from './videoPolicies';
-
-const IMAGE = { height: 704, image_name: 'frame.png', width: 1248 };
-const CLIP: VideoSourceClip = {
- endFrame: 47,
- fps: 24,
- height: 704,
- numFrames: 48,
- startFrame: 0,
- video_name: 'clip.mp4',
- width: 1248,
-};
-
-const { endFrame: _end, startFrame: _start, ...CLIP_REF } = CLIP;
-
-/** The conditioning each mode needs; `resolveVideoMode` infers the mode back from it. */
-const MODE_INPUTS: Record<VideoGenerationMode, Partial<VideoSettings>> = {
- 'audio-to-video': { conditioningClip: { clip: CLIP_REF, fpsKnown: true, role: 'audio' } },
- extend: { sourceVideo: CLIP },
- 'first-frame': { firstFrameImage: IMAGE },
- 'first-last': { firstFrameImage: IMAGE, lastFrameImage: IMAGE },
- 'last-frame': { lastFrameImage: IMAGE },
- reference: { references: [{ detail: 'max', image: IMAGE, kind: 'image' }] },
- txt2vid: {},
- 'video-to-audio': { conditioningClip: { clip: CLIP_REF, fpsKnown: true, role: 'video' } },
-};
-
-/**
- * Candidate components for the slot filters to choose from — a search over a pool rather than a
- * hand-written model per slot, so the test agrees with the policy rather than with itself.
- */
-const CANDIDATE_BASES = ['any', ...SUPPORTED_VIDEO_BASES] as const;
-const CANDIDATE_VARIANTS = [undefined, 'fl2va', 'ref2va', 't2v_a14b', 'i2v_a14b', 'ti2v_5b', 'ltx2_dev'] as const;
-const CANDIDATE_LATENT_CHANNELS = [undefined, 16, 48] as const;
-
-const candidatesForSlot = (slot: VideoComponentSlotPolicy): ModelConfig[] => {
- const candidates: ModelConfig[] = [];
-
- for (const type of slot.modelTypes) {
- for (const base of CANDIDATE_BASES) {
- for (const variant of CANDIDATE_VARIANTS) {
- for (const latentChannels of type === 'vae' ? CANDIDATE_LATENT_CHANNELS : [undefined]) {
- candidates.push({
- base,
- // A component source has to be a bundled install; every other slot takes a
- // single file, and the H3/LTX-2 encoder slots do not care either way.
- format: slot.valueKind === 'main' ? 'diffusers' : 'checkpoint',
- key: `${base}-${type}-${variant ?? 'novariant'}${latentChannels ? `-${latentChannels}` : ''}`,
- name: `${base} ${type} ${variant ?? ''}`.trim(),
- type,
- variant: variant ?? null,
- ...(latentChannels ? { latent_channels: latentChannels } : {}),
- } as ModelConfig);
- }
- }
- }
- }
-
- return candidates;
-};
-
-const buildContext = (
- model: MainModelConfig,
- settings: VideoSettings,
- slots: readonly VideoComponentSlotPolicy[]
-): VideoComponentPolicyContext => {
- const selectedComponents = {} as VideoComponentPolicyContext['selectedComponents'];
-
- for (const slot of slots) {
- selectedComponents[slot.key] = settings[slot.key] as never;
- }
-
- return { model, selectedComponents, settings };
-};
-
-/**
- * Fill every required slot with something its own filter accepts. Iterated to a fixpoint because
- * slots are interdependent: picking a component source can make another slot stop being required.
- */
-const satisfyRequiredComponents = (
- model: MainModelConfig,
- initial: VideoSettings
-): { settings: VideoSettings; filled: VideoComponentValueKey[] } => {
- let settings = initial;
- const filled: VideoComponentValueKey[] = [];
-
- for (let pass = 0; pass < 5; pass++) {
- const { slots } = getVideoComponentSectionPolicy(model, settings);
- const context = buildContext(model, settings, slots);
- let changed = false;
-
- for (const slot of slots) {
- if (!slot.required?.(context) || settings[slot.key]) {
- continue;
- }
-
- const candidate = candidatesForSlot(slot).find((c) => !slot.filter || slot.filter(c, context));
-
- if (candidate) {
- settings = { ...settings, [slot.key]: candidate as never };
- filled.push(slot.key);
- changed = true;
- }
- }
-
- if (!changed) {
- break;
- }
- }
-
- return { filled: filled.sort(), settings };
-};
-
-interface Case {
- base: string;
- variant: string;
- mode: VideoGenerationMode;
- format: 'diffusers' | 'checkpoint';
- /** A preset to override the variant's default with; absent runs the default. */
- targetResolution?: VideoTargetResolution;
- /** Fill the optional LTX-2 duration head slot and let it choose the length. */
- autoDuration?: true;
- label: string;
-}
-
-const createModel = (testCase: Case): MainModelConfig =>
- ({
- base: testCase.base,
- format: testCase.format,
- key: `${testCase.base}-${testCase.variant}-${testCase.format}`,
- name: `${testCase.base} ${testCase.variant} (${testCase.format})`,
- type: 'main',
- variant: testCase.variant,
- }) as MainModelConfig;
-
-/**
- * Both model shapes per variant: a bundled install supplies its own components, a single file
- * forces the component-source path, and the two produce different graphs. A shape the panel would
- * not let the user pick at all is dropped — which shapes those are is the policy's answer
- * (`isVideoModelSelectable`), not a list kept here: H3's Ref2VA folder install is supported state
- * but not runnable as the model, and hard-coding that would go stale.
- */
-const cases: Case[] = SUPPORTED_VIDEO_BASES.flatMap((base) =>
- Object.entries(VIDEO_GENERATION[base].variants).flatMap(([variant, config]) => {
- // A multi-stage preset builds a different graph -- more denoise passes, and the nodes between
- // them -- so each one is its own case. Every one of them, not just the first: the fixture
- // records the literal values written into each field as well as the node types, and the widest
- // canvas is exactly the one a future bound on those fields would reject.
- const presets: (VideoTargetResolution | undefined)[] = [
- undefined,
- ...config.targetResolutions.filter((option) => option.stages !== undefined).map((option) => option.id),
- ];
-
- return config.modes.flatMap((mode) =>
- presets
- .filter((targetResolution) => {
- // A mode the policy refuses to run two-stage is not an uncovered case, it is a
- // combination that does not exist -- asked of the policy so the two cannot drift.
- const option = config.targetResolutions.find((entry) => entry.id === targetResolution);
-
- return option?.stages !== 2 || isTwoStageSupportedForMode(mode);
- })
- .flatMap((targetResolution) =>
- (['diffusers', 'checkpoint'] as const)
- .map((format) => ({
- base,
- format,
- label: `${base} / ${variant} / ${mode} / ${format}${targetResolution ? ` / ${targetResolution}` : ''}`,
- mode,
- ...(targetResolution ? { targetResolution } : {}),
- variant,
- }))
- .filter((testCase) => isVideoModelSelectable(createModel(testCase)))
- )
- );
- })
-);
-
-/**
- * Auto duration is an optional slot plus a flag, so the matrix above -- which fills only *required*
- * slots -- never reaches the `ltx2_duration` node. Added here rather than as another dimension of
- * that matrix because it only affects one base. Every preset is kept, including the two-stage ones:
- * those build a second denoise with a `num_frames` of its own, so restricting this to the default
- * preset is exactly how a graph that dies after the base pass stays invisible.
- */
-const DURATION_HEAD = {
- base: 'ltx-2',
- key: 'ltx2-duration-head',
- name: 'LTX-2 duration head',
- type: 'ltx2_duration_head',
-} as ModelConfig;
-
-const AUTO_DURATION_CASES: Case[] = cases
- .filter((testCase) => testCase.base === 'ltx-2')
- .filter((testCase) =>
- // Asked of the policy, not of a list of modes kept here, so the two cannot drift.
- isAutoDurationActive({
- autoDuration: true,
- conditioningClip: null,
- firstFrameImage: null,
- lastFrameImage: null,
- ltx2DurationHeadModel: DURATION_HEAD,
- references: [],
- sourceVideo: null,
- ...MODE_INPUTS[testCase.mode],
- } as unknown as VideoSettings)
- )
- .map((testCase) => ({ ...testCase, autoDuration: true, label: `${testCase.label} / auto duration` }));
-
-const compileForCase = (testCase: Case): { filled: VideoComponentValueKey[]; graph: BackendGraphContract } => {
- const model = createModel(testCase);
- const { filled, settings } = satisfyRequiredComponents(model, {
- ...getDefaultVideoSettings(model),
- ...MODE_INPUTS[testCase.mode],
- positivePrompt: 'a test prompt',
- seed: 1,
- seedMode: 'fixed',
- ...(testCase.targetResolution ? { targetResolution: testCase.targetResolution } : {}),
- ...(testCase.autoDuration ? { autoDuration: true, ltx2DurationHeadModel: DURATION_HEAD as never } : {}),
- });
-
- // Compiling an invalid selection throws only the first reason; asserting here reports every
- // unmet requirement at once, and doubles as the check that the policy is satisfiable at all.
- expect(getVideoValidationReasons(model, settings), `${testCase.label} is not satisfiable`).toEqual([]);
-
- return { filled, graph: compileVideoGraph(settings, model).backendGraph };
-};
+import { AUTO_DURATION_CASES, cases, compileForCase } from './videoGraphCoverage.testing';
+import { SUPPORTED_VIDEO_BASES, VIDEO_GENERATION } from './videoPolicies';
describe('video graph coverage', () => {
it('registers a variant set for every supported base', () => {
@@ -274,7 +33,7 @@ describe('video graph coverage', () => {
});
it('compiles at least one case for every registered variant', () => {
- // The selectability filter above drops shapes the panel refuses; a variant it drops entirely
+ // The selectability filter in `cases` drops shapes the panel refuses; a variant it drops entirely
// would leave this suite silently covering nothing for it.
const covered = new Set(cases.map((testCase) => `${testCase.base}/${testCase.variant}`));
const registered = SUPPORTED_VIDEO_BASES.flatMap((base) =>
diff --git a/invokeai/frontend/webv2/src/features/video/core/videoGraphCoverage.testing.ts b/invokeai/frontend/webv2/src/features/video/core/videoGraphCoverage.testing.ts
new file mode 100644
index 0000000000..e4788f799a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/video/core/videoGraphCoverage.testing.ts
@@ -0,0 +1,252 @@
+/**
+ * The registry-driven video case matrix: every supported base, variant, generation mode, model shape and multi-stage
+ * preset, and the compile each case runs. Shared by `videoGraphCoverage.test.ts`, whose committed fixture records
+ * what these cases emit, and the recall contract in `workbench/image-actions/videoRecallContract.test.ts`, which
+ * recalls what they record.
+ */
+
+import type { GenerationModelCatalogItem as ModelConfig, MainModelConfig } from '@features/generation/contracts';
+import type { BackendGraphContract } from '@features/generation/core/contracts';
+
+import { expect } from 'vitest';
+
+import type { VideoGenerationMode, VideoSettings, VideoSourceClip, VideoTargetResolution } from './types';
+import type { VideoComponentPolicyContext, VideoComponentSlotPolicy, VideoComponentValueKey } from './videoPolicies';
+
+import { compileVideoGraph } from './graph';
+import {
+ getDefaultVideoSettings,
+ getVideoComponentSectionPolicy,
+ getVideoValidationReasons,
+ isAutoDurationActive,
+ isTwoStageSupportedForMode,
+ isVideoModelSelectable,
+ SUPPORTED_VIDEO_BASES,
+ VIDEO_GENERATION,
+} from './videoPolicies';
+
+const IMAGE = { height: 704, image_name: 'frame.png', width: 1248 };
+const CLIP: VideoSourceClip = {
+ endFrame: 47,
+ fps: 24,
+ height: 704,
+ numFrames: 48,
+ startFrame: 0,
+ video_name: 'clip.mp4',
+ width: 1248,
+};
+
+const { endFrame: _end, startFrame: _start, ...CLIP_REF } = CLIP;
+
+/** The conditioning each mode needs; `resolveVideoMode` infers the mode back from it. */
+const MODE_INPUTS: Record<VideoGenerationMode, Partial<VideoSettings>> = {
+ 'audio-to-video': { conditioningClip: { clip: CLIP_REF, fpsKnown: true, role: 'audio' } },
+ extend: { sourceVideo: CLIP },
+ 'first-frame': { firstFrameImage: IMAGE },
+ 'first-last': { firstFrameImage: IMAGE, lastFrameImage: IMAGE },
+ 'last-frame': { lastFrameImage: IMAGE },
+ reference: { references: [{ detail: 'max', image: IMAGE, kind: 'image' }] },
+ txt2vid: {},
+ 'video-to-audio': { conditioningClip: { clip: CLIP_REF, fpsKnown: true, role: 'video' } },
+};
+
+/**
+ * Candidate components for the slot filters to choose from — a search over a pool rather than a
+ * hand-written model per slot, so the test agrees with the policy rather than with itself.
+ */
+const CANDIDATE_BASES = ['any', ...SUPPORTED_VIDEO_BASES] as const;
+const CANDIDATE_VARIANTS = [undefined, 'fl2va', 'ref2va', 't2v_a14b', 'i2v_a14b', 'ti2v_5b', 'ltx2_dev'] as const;
+const CANDIDATE_LATENT_CHANNELS = [undefined, 16, 48] as const;
+
+export const candidatesForSlot = (slot: VideoComponentSlotPolicy): ModelConfig[] => {
+ const candidates: ModelConfig[] = [];
+
+ for (const type of slot.modelTypes) {
+ for (const base of CANDIDATE_BASES) {
+ for (const variant of CANDIDATE_VARIANTS) {
+ for (const latentChannels of type === 'vae' ? CANDIDATE_LATENT_CHANNELS : [undefined]) {
+ candidates.push({
+ base,
+ // A component source has to be a bundled install; every other slot takes a
+ // single file, and the H3/LTX-2 encoder slots do not care either way.
+ format: slot.valueKind === 'main' ? 'diffusers' : 'checkpoint',
+ key: `${base}-${type}-${variant ?? 'novariant'}${latentChannels ? `-${latentChannels}` : ''}`,
+ name: `${base} ${type} ${variant ?? ''}`.trim(),
+ type,
+ variant: variant ?? null,
+ ...(latentChannels ? { latent_channels: latentChannels } : {}),
+ } as ModelConfig);
+ }
+ }
+ }
+ }
+
+ return candidates;
+};
+
+const buildContext = (
+ model: MainModelConfig,
+ settings: VideoSettings,
+ slots: readonly VideoComponentSlotPolicy[]
+): VideoComponentPolicyContext => {
+ const selectedComponents = {} as VideoComponentPolicyContext['selectedComponents'];
+
+ for (const slot of slots) {
+ selectedComponents[slot.key] = settings[slot.key] as never;
+ }
+
+ return { model, selectedComponents, settings };
+};
+
+/**
+ * Fill every required slot with something its own filter accepts. Iterated to a fixpoint because
+ * slots are interdependent: picking a component source can make another slot stop being required.
+ */
+const satisfyRequiredComponents = (
+ model: MainModelConfig,
+ initial: VideoSettings
+): { settings: VideoSettings; filled: VideoComponentValueKey[] } => {
+ let settings = initial;
+ const filled: VideoComponentValueKey[] = [];
+
+ for (let pass = 0; pass < 5; pass++) {
+ const { slots } = getVideoComponentSectionPolicy(model, settings);
+ const context = buildContext(model, settings, slots);
+ let changed = false;
+
+ for (const slot of slots) {
+ if (!slot.required?.(context) || settings[slot.key]) {
+ continue;
+ }
+
+ const candidate = candidatesForSlot(slot).find((c) => !slot.filter || slot.filter(c, context));
+
+ if (candidate) {
+ settings = { ...settings, [slot.key]: candidate as never };
+ filled.push(slot.key);
+ changed = true;
+ }
+ }
+
+ if (!changed) {
+ break;
+ }
+ }
+
+ return { filled: filled.sort(), settings };
+};
+
+export interface Case {
+ base: string;
+ variant: string;
+ mode: VideoGenerationMode;
+ format: 'diffusers' | 'checkpoint';
+ /** A preset to override the variant's default with; absent runs the default. */
+ targetResolution?: VideoTargetResolution;
+ /** Fill the optional LTX-2 duration head slot and let it choose the length. */
+ autoDuration?: true;
+ label: string;
+}
+
+export const createModel = (testCase: Case): MainModelConfig =>
+ ({
+ base: testCase.base,
+ format: testCase.format,
+ key: `${testCase.base}-${testCase.variant}-${testCase.format}`,
+ name: `${testCase.base} ${testCase.variant} (${testCase.format})`,
+ type: 'main',
+ variant: testCase.variant,
+ }) as MainModelConfig;
+
+/**
+ * Both model shapes per variant: a bundled install supplies its own components, a single file
+ * forces the component-source path, and the two produce different graphs. A shape the panel would
+ * not let the user pick at all is dropped — which shapes those are is the policy's answer
+ * (`isVideoModelSelectable`), not a list kept here: H3's Ref2VA folder install is supported state
+ * but not runnable as the model, and hard-coding that would go stale.
+ */
+export const cases: Case[] = SUPPORTED_VIDEO_BASES.flatMap((base) =>
+ Object.entries(VIDEO_GENERATION[base].variants).flatMap(([variant, config]) => {
+ // A multi-stage preset builds a different graph -- more denoise passes, and the nodes between
+ // them -- so each one is its own case. Every one of them, not just the first: the fixture
+ // records the literal values written into each field as well as the node types, and the widest
+ // canvas is exactly the one a future bound on those fields would reject.
+ const presets: (VideoTargetResolution | undefined)[] = [
+ undefined,
+ ...config.targetResolutions.filter((option) => option.stages !== undefined).map((option) => option.id),
+ ];
+
+ return config.modes.flatMap((mode) =>
+ presets
+ .filter((targetResolution) => {
+ // A mode the policy refuses to run two-stage is not an uncovered case, it is a
+ // combination that does not exist -- asked of the policy so the two cannot drift.
+ const option = config.targetResolutions.find((entry) => entry.id === targetResolution);
+
+ return option?.stages !== 2 || isTwoStageSupportedForMode(mode);
+ })
+ .flatMap((targetResolution) =>
+ (['diffusers', 'checkpoint'] as const)
+ .map((format) => ({
+ base,
+ format,
+ label: `${base} / ${variant} / ${mode} / ${format}${targetResolution ? ` / ${targetResolution}` : ''}`,
+ mode,
+ ...(targetResolution ? { targetResolution } : {}),
+ variant,
+ }))
+ .filter((testCase) => isVideoModelSelectable(createModel(testCase)))
+ )
+ );
+ })
+);
+
+/**
+ * Auto duration is an optional slot plus a flag, so the matrix above -- which fills only *required*
+ * slots -- never reaches the `ltx2_duration` node. Added here rather than as another dimension of
+ * that matrix because it only affects one base. Every preset is kept, including the two-stage ones:
+ * those build a second denoise with a `num_frames` of its own, so restricting this to the default
+ * preset is exactly how a graph that dies after the base pass stays invisible.
+ */
+export const DURATION_HEAD = {
+ base: 'ltx-2',
+ key: 'ltx2-duration-head',
+ name: 'LTX-2 duration head',
+ type: 'ltx2_duration_head',
+} as ModelConfig;
+
+export const AUTO_DURATION_CASES: Case[] = cases
+ .filter((testCase) => testCase.base === 'ltx-2')
+ .filter((testCase) =>
+ // Asked of the policy, not of a list of modes kept here, so the two cannot drift.
+ isAutoDurationActive({
+ autoDuration: true,
+ conditioningClip: null,
+ firstFrameImage: null,
+ lastFrameImage: null,
+ ltx2DurationHeadModel: DURATION_HEAD,
+ references: [],
+ sourceVideo: null,
+ ...MODE_INPUTS[testCase.mode],
+ } as unknown as VideoSettings)
+ )
+ .map((testCase) => ({ ...testCase, autoDuration: true, label: `${testCase.label} / auto duration` }));
+
+export const compileForCase = (testCase: Case): { filled: VideoComponentValueKey[]; graph: BackendGraphContract } => {
+ const model = createModel(testCase);
+ const { filled, settings } = satisfyRequiredComponents(model, {
+ ...getDefaultVideoSettings(model),
+ ...MODE_INPUTS[testCase.mode],
+ positivePrompt: 'a test prompt',
+ seed: 1,
+ seedMode: 'fixed',
+ ...(testCase.targetResolution ? { targetResolution: testCase.targetResolution } : {}),
+ ...(testCase.autoDuration ? { autoDuration: true, ltx2DurationHeadModel: DURATION_HEAD as never } : {}),
+ });
+
+ // Compiling an invalid selection throws only the first reason; asserting here reports every
+ // unmet requirement at once, and doubles as the check that the policy is satisfiable at all.
+ expect(getVideoValidationReasons(model, settings), `${testCase.label} is not satisfiable`).toEqual([]);
+
+ return { filled, graph: compileVideoGraph(settings, model).backendGraph };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.ts
index 361a073071..5015ca7d67 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.ts
@@ -7,6 +7,7 @@ import type { TFunction } from 'i18next';
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { ApiError } from '@platform/transport/http';
import { QueryClient } from '@tanstack/react-query';
+import { createInstance } from 'i18next';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const galleryApi = vi.hoisted(() => ({
@@ -29,6 +30,24 @@ import { applyVideoRecallMetadata, executeVideoRecall } from './executeVideoReca
const t = ((key: string) => key) as unknown as TFunction;
+const englishCatalog = Object.values(
+ import.meta.glob('../../../public/locales/en.json', { eager: true, import: 'default' })
+)[0] as Record<string, unknown>;
+
+/** The English copy, for asserting what a notice shows rather than which key it asked for. */
+const createEnglishTranslator = async (): Promise<TFunction> => {
+ const instance = createInstance();
+
+ await instance.init({
+ initAsync: false,
+ interpolation: { escapeValue: false },
+ lng: 'en',
+ resources: { en: { translation: englishCatalog } },
+ });
+
+ return ((key: string, values?: Record<string, unknown>) => instance.t(key, values)) as TFunction;
+};
+
const wanModel = {
base: 'wan',
file_size: 1,
@@ -330,7 +349,7 @@ describe('executeVideoRecall', () => {
const didRecall = await executeVideoRecall({
queryClient,
- t,
+ t: await createEnglishTranslator(),
commands,
getVideoValues: () => videoValues as unknown as Record<string, unknown>,
item,
@@ -345,9 +364,11 @@ describe('executeVideoRecall', () => {
{ ...videoValues, aspectRatioId: '9:16', targetResolution: '720p' },
undefined
);
- expect(commands.notifications.add).toHaveBeenCalledWith(
- expect.objectContaining({ kind: 'success', title: 'widgets.gallery.itemActions.recall.videoTitles.size' })
- );
+ expect(commands.notifications.add).toHaveBeenCalledWith({
+ kind: 'success',
+ message: 'Applied size.',
+ title: 'Recalled size',
+ });
});
it('says the recorded size has no preset on the panel model, not that the metadata is missing', async () => {
@@ -523,6 +544,95 @@ describe('executeVideoRecall', () => {
});
});
+describe('the target resolution of a canvas the recorded media sized', () => {
+ const wanI2v = { ...wanModel, key: 'wan-i2v', name: 'Wan 2.2 i2v_a14b', variant: 'i2v_a14b' } as ModelConfig;
+ const h3Fl2va = { ...h3Model, key: 'h3-fl2va', name: 'MiniMax H3 FL2VA', variant: 'fl2va' } as ModelConfig;
+
+ beforeEach(() => {
+ queryClient = new QueryClient();
+ accountLifecycle.activate('test-account');
+ videoMetadata.mockReset();
+ galleryApi.galleryImages.resolveMany.mockReset();
+ });
+
+ /** Recalls a first-frame run onto a panel on the same model, the gallery holding `frames`. */
+ const recallFirstFrame = async (
+ model: ModelConfig,
+ panel: Record<string, unknown>,
+ recorded: Record<string, unknown>,
+ frames: { height: number; imageName: string; width: number }[]
+ ) => {
+ recallSeq += 1;
+ videoMetadata.mockResolvedValue({
+ first_frame_image: { image_name: 'first.png' },
+ model: { base: model.base, key: model.key, name: model.name, type: 'main' },
+ num_frames: 81,
+ positive_prompt: 'a red fox',
+ seed: 7,
+ ...recorded,
+ });
+ galleryApi.galleryImages.resolveMany.mockResolvedValue(frames);
+ const { commands, patchValues } = createCommands();
+
+ await executeVideoRecall({
+ queryClient,
+ t: await createEnglishTranslator(),
+ commands,
+ getVideoValues: () => ({ ...createDefaultVideoWidgetValues([model]), ...panel }),
+ item: { ...item, name: `media-sized-${recallSeq}.mp4` },
+ kind: 'all',
+ models: [model],
+ });
+
+ const [notice] = vi.mocked(commands.notifications.add).mock.calls.at(-1) ?? [];
+
+ return { message: notice?.message, values: patchValues.mock.calls.at(-1)?.[1] as Record<string, unknown> };
+ };
+
+ it.each([
+ // 1800x1000 at 768 highres: over the area cap, scaled to 1363.1x757.3 and snapped to 1376x768. The canvas fed
+ // back would give 1344x768, and 768 lowres gives the frame 768x416.
+ ['an area-capped H3 canvas', h3Fl2va, 'minimax_h3_i2v', 1376, 768, 1800, 1000, '768 lowres', '768 highres'],
+ // 1000x700 at 1080p: 1542.9x1080, snapped to 1536x1088. The canvas fed back would give 1520x1088.
+ ['a Wan 1080p canvas', wanI2v, 'wan_i2v', 1536, 1088, 1000, 700, '720p', '1080p'],
+ ] as const)(
+ 'restores the target resolution of %s from the frame as the gallery returns it',
+ async (_, model, generationMode, width, height, frameWidth, frameHeight, panelResolution, recalled) => {
+ const { message, values } = await recallFirstFrame(
+ model,
+ { targetResolution: panelResolution },
+ { generation_mode: generationMode, height, width },
+ [{ height: frameHeight, imageName: 'first.png', width: frameWidth }]
+ );
+
+ expect(values).toMatchObject({
+ firstFrameImage: { height: frameHeight, image_name: 'first.png', width: frameWidth },
+ targetResolution: recalled,
+ });
+ expect(message).toContain('size');
+ }
+ );
+
+ it('leaves the panel resolution, and claims no size, when the frame is gone or reaches the canvas nowhere', async () => {
+ // 688x480 is the frame's 480p canvas, which fed back would give itself: only the frame missing refuses it. A 16:9
+ // frame gives Wan 848x480, 1280x720 or 1920x1088, never 1536x1088.
+ for (const [size, frames] of [
+ [{ height: 480, width: 688 }, []],
+ [{ height: 1088, width: 1536 }, [{ height: 720, imageName: 'first.png', width: 1280 }]],
+ ] as const) {
+ const { message, values } = await recallFirstFrame(
+ wanI2v,
+ { targetResolution: '720p' },
+ { generation_mode: 'wan_i2v', ...size },
+ [...frames]
+ );
+
+ expect(values.targetResolution).toBe('720p');
+ expect(message).not.toContain('size');
+ }
+ });
+});
+
describe('the LTX-2 keyframe and extend modes on recall', () => {
beforeEach(() => {
queryClient = new QueryClient();
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts
index dd57ab42ad..5c652648be 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts
@@ -47,6 +47,7 @@ import {
getVideoRecallTitle,
parseVideoRecallRecord,
resolveVideoSizeRecall,
+ settleMediaSizedRecall,
type VideoRecallKind,
type VideoRecallMediaNames,
type VideoSizeRecallFit,
@@ -588,6 +589,9 @@ export const applyVideoRecallMetadata = async ({
}
}
+ // A canvas the recorded media sized takes its target resolution from the media as they hydrated.
+ ({ fields: result.fields, values: result.values } = settleMediaSizedRecall(result));
+
if (result.fields.length === 0) {
commands.notifications.add({ kind: 'info', ...emptyNotice });
return false;
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
index be865e8fbc..c8c4df4c88 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
@@ -1829,6 +1829,56 @@ describe('model-family tuning recall', () => {
expect(outOfRange?.values).toMatchObject({ fluxDypePreset: 'off', fluxDypeScale: 2 });
});
+ describe('PiD decoding', () => {
+ const sdxlGeneration = (extra: Record<string, unknown> = {}) => ({
+ generation_mode: 'sdxl_txt2img',
+ model: { base: 'sdxl', key: sdxlModel.key, name: sdxlModel.name, type: 'main' },
+ ...extra,
+ });
+
+ it.each(['fit', 'native'] as const)('restores %s decoding with its steps', (pidMode) => {
+ const result = recall(sdxlGeneration({ pid_mode: pidMode, pid_steps: 8 }), sdxlModel);
+
+ expect(result?.values).toMatchObject({ pidMode, pidSteps: 8 });
+ expect(result?.fields).toContain('modelTuning');
+ });
+
+ it('turns PiD off for a generation of the family that decoded without it, and keeps the steps', () => {
+ const result = recall(sdxlGeneration(), sdxlModel, 'all', { pidMode: 'fit', pidSteps: 8 });
+ const { generation_mode: _mode, ...notAGeneration } = sdxlGeneration();
+
+ expect(result?.values).toMatchObject({ pidMode: 'off', pidSteps: 8 });
+ expect(result?.fields).toContain('modelTuning');
+ // A record that is no generation says nothing about how the image was decoded.
+ expect(recall(notAGeneration, sdxlModel, 'all', { pidMode: 'fit' })?.values.pidMode).toBe('fit');
+ });
+
+ it('clamps the steps to what the decoder takes and ignores an unknown mode', () => {
+ expect(recall({ pid_mode: 'turbo', pid_steps: 40 }, sdxlModel, 'all', { pidMode: 'fit' })?.values).toMatchObject({
+ pidMode: 'fit',
+ pidSteps: 16,
+ });
+ expect(recall({ pid_steps: 0.2 }, sdxlModel)?.values.pidSteps).toBe(1);
+ });
+
+ it('leaves PiD alone for a family that cannot decode with it', () => {
+ const result = recall(
+ {
+ generation_mode: 'txt2img',
+ model: { base: 'sd-1', key: sd1Model.key, name: sd1Model.name, type: 'main' },
+ pid_mode: 'native',
+ pid_steps: 8,
+ },
+ sd1Model,
+ 'all',
+ { pidMode: 'fit' }
+ );
+
+ expect(result?.values).toMatchObject({ pidMode: 'fit', pidSteps: 4 });
+ expect(result?.fields).not.toContain('modelTuning');
+ });
+ });
+
describe('over tuning the panel has since changed', () => {
const changedTuning = {
fluxDypePreset: '4k',
@@ -1879,9 +1929,9 @@ describe('model-family tuning recall', () => {
expect(recallOverChanged(otherFamily, fluxModel)?.fluxDypePreset).toBe('4k');
});
- // What a graph records must bring the panel back to that recipe from either direction. A switch the graph stops
- // recording still passes here, since recall reads a missing key as the default; graph.test.ts pins that FLUX
- // records DyPE off.
+ // What a graph records at the defaults must bring a changed panel back to them; the recall contract covers changed
+ // tuning over the defaults. A switch the graph stops recording still passes here, since recall reads a missing key
+ // as the default; graph.test.ts pins that FLUX records DyPE off.
const tunedBases = generateGraphCases.filter(({ base }) => ['flux', 'qwen-image', 'z-image'].includes(base));
const defaultTuning = {
fluxDypePreset: 'off',
@@ -1890,15 +1940,16 @@ describe('model-family tuning recall', () => {
zImageSeedVarianceEnabled: false,
zImageShift: null,
} as const;
- const roundTrip = ({ base, shape }: (typeof generateGraphCases)[number], recorded: object, current: object) => {
+
+ it.each(tunedBases)('$label restores its default tuning over changed settings', ({ base, shape }) => {
const { model, settings } = fullyFilledSettingsFor(base, shape);
- const graph = compileGenerateGraph({ ...settings, ...recorded }, model, 'gallery', {
+ const graph = compileGenerateGraph({ ...settings, ...defaultTuning }, model, 'gallery', {
useCpuNoise: true,
useNsfwChecker: false,
useWatermark: false,
}).backendGraph;
const values = buildImageRecallSettings({
- currentValues: createValues({ ...current, model }),
+ currentValues: createValues({ ...changedTuning, model }),
image,
kind: 'all',
metadata: Object.values(graph.nodes).find((node) => node.type === 'core_metadata'),
@@ -1912,22 +1963,9 @@ describe('model-family tuning recall', () => {
'z-image': ['zImageSeedVarianceEnabled', 'zImageShift'],
}[base as 'flux' | 'qwen-image' | 'z-image'] as (keyof typeof defaultTuning)[];
- return {
- expected: Object.fromEntries(keys.map((key) => [key, (recorded as typeof defaultTuning)[key]])),
- restored: Object.fromEntries(keys.map((key) => [key, values?.[key]])),
- };
- };
-
- it.each(tunedBases)('$label restores its default tuning over changed settings', (graphCase) => {
- const { expected, restored } = roundTrip(graphCase, defaultTuning, changedTuning);
-
- expect(restored).toEqual(expected);
- });
-
- it.each(tunedBases)('$label restores its changed tuning over the defaults', (graphCase) => {
- const { expected, restored } = roundTrip(graphCase, changedTuning, defaultTuning);
-
- expect(restored).toEqual(expected);
+ expect(Object.fromEntries(keys.map((key) => [key, values?.[key]]))).toEqual(
+ Object.fromEntries(keys.map((key) => [key, defaultTuning[key]]))
+ );
});
});
@@ -2118,34 +2156,6 @@ describe('Anima IP-Adapter recall', () => {
});
});
-/** Remix from the metadata a fully filled graph records, starting from SDXL defaults. */
-const remixRoundTrip = ({ base, shape }: (typeof generateGraphCases)[number]) => {
- const { filled, model, settings } = fullyFilledSettingsFor(base, shape);
- const graph = compileGenerateGraph(settings, model, 'gallery', {
- useCpuNoise: true,
- useNsfwChecker: false,
- useWatermark: false,
- }).backendGraph;
- const recordedMetadata = Object.values(graph.nodes).find((node) => node.type === 'core_metadata');
- const serializedMetadata = JSON.stringify(recordedMetadata);
- // A slot the graph leaves unused (e.g. a bundled model's) is not recorded, so there is nothing to restore.
- const recorded = filled.filter((key) => serializedMetadata.includes(`"${settings[key]?.key}"`));
- const components = recorded.map((key) => settings[key]).filter((component) => component !== null);
- const result = buildImageRecallSettings({
- currentValues: createValues(),
- image,
- kind: 'remix',
- metadata: recordedMetadata,
- models: components.filter((component) => component.type !== 'vae'),
- supportedModels: [model],
- vaeModels: components.filter((component): component is VaeModelConfig => component.type === 'vae'),
- });
- const keysOf = (values: GenerateWidgetValues | undefined) =>
- Object.fromEntries(recorded.map((key) => [key, values?.[key]?.key ?? null]));
-
- return { expected: keysOf(settings as GenerateWidgetValues), recorded, restored: keysOf(result?.values) };
-};
-
describe('anima inpaint adapter', () => {
const inpaintAdapter: ComponentModelConfig = {
base: 'anima',
@@ -2423,36 +2433,6 @@ describe('FLUX.3 prompt upsampler recall', () => {
});
});
-describe('remix round trip', () => {
- // Every component a graph records must come back; one recorded under a key Remix does not know fails here.
- it.each(generateGraphCases)('restores the components $label records', (graphCase) => {
- const { expected, restored } = remixRoundTrip(graphCase);
-
- expect(restored).toEqual(expected);
- });
-
- it('exercises every component setting Remix restores', () => {
- const recorded = new Set(generateGraphCases.flatMap((graphCase) => remixRoundTrip(graphCase).recorded));
-
- expect([...recorded].sort()).toEqual([
- 'clipEmbedModel',
- 'componentSourceModel',
- 'gemma2EncoderModel',
- 'ideogram4UnconditionalModel',
- 'mistralEncoderModel',
- 'pidDecoderModel',
- 'qwen35EncoderModel',
- 'qwen3EncoderModel',
- 'qwen3VLEncoderModel',
- 'qwenVLEncoderModel',
- 't5EncoderModel',
- 'vae',
- 'wanLowNoiseModel',
- 'wanT5EncoderModel',
- ]);
- });
-});
-
describe('SDXL Refiner recall', () => {
const refiner: MainModelConfig = {
base: 'sdxl-refiner',
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
index 4e27d40f2d..b10847dbbd 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
@@ -13,6 +13,7 @@ import type { TFunction } from 'i18next';
import {
clampAnimaInpaintAdapterWeight,
clampDimension,
+ clampPidSteps,
cloneGenerateWidgetValues,
isIdeogram4SamplerPreset,
deriveAspectRatioId,
@@ -37,6 +38,7 @@ import {
isOpenAIImageBackground,
isOpenAIImageQuality,
isOpenAIInputFidelity,
+ isPidMode,
GEMINI_TEMPERATURE_MAX,
GEMINI_TEMPERATURE_MIN,
isRefinerModel,
@@ -554,26 +556,15 @@ const getRecordedTimestepShift = (metadata: unknown, key: string): number | null
return getBoundedNumber(metadata, key, MIN_TIMESTEP_SHIFT, MAX_TIMESTEP_SHIFT) ?? undefined;
};
-/**
- * Per-family tuning the graphs record under their own keys. Gated on the model recall settles on, since each
- * setting only reaches that family's denoise or encoder nodes.
- *
- * A generation record of that same family that leaves a switch out ran the node's default: webv2 recorded no tuning
- * before the panel offered it. Restoring the default there means a preset turned on since does not survive recall.
- * Values that only matter while a switch is on (DyPE scale, variance strength) stay as they are when missing.
- */
-const getMetadataModelTuning = (
- metadata: unknown,
- model: GenerateModelConfig | undefined
-): Partial<GenerateWidgetValues> => {
- if (!model || model.type !== 'main' || !isRecord(metadata)) {
- return {};
- }
-
- const recordsFamily = isGenerationRecord(metadata) && getRecord(metadata, 'model')?.base === model.base;
- const recordedOrDefault = <T>(key: string, recorded: T | undefined, fallback: T): T | undefined =>
- recorded !== undefined ? recorded : recordsFamily && !(key in metadata) ? fallback : undefined;
+/** The recorded value, else the fallback when a generation record of the model's own family leaves the key out. */
+type RecordedOrDefault = <T>(key: string, recorded: T | undefined, fallback: T) => T | undefined;
+/** The settings each family records under its own keys. */
+const getFamilyTuning = (
+ metadata: Record<string, unknown>,
+ model: GenerateModelConfig,
+ recordedOrDefault: RecordedOrDefault
+): Partial<GenerateWidgetValues> => {
if (model.base === 'flux') {
const preset = recordedOrDefault(
'dype_preset',
@@ -678,6 +669,56 @@ const getMetadataModelTuning = (
return {};
};
+/**
+ * PiD decoding, shared by several families. The graphs record its keys only while it decodes, so a generation record
+ * of the model's family without the mode decoded through the VAE. Out-of-range steps are clamped to what the decoder
+ * takes rather than applied.
+ */
+const getPidTuning = (
+ metadata: Record<string, unknown>,
+ model: GenerateModelConfig,
+ recordedOrDefault: RecordedOrDefault
+): Partial<Pick<GenerateWidgetValues, 'pidMode' | 'pidSteps'>> => {
+ if (!getGenerationUiPolicy(model).pidVisible) {
+ return {};
+ }
+
+ const mode = recordedOrDefault('pid_mode', isPidMode(metadata.pid_mode) ? metadata.pid_mode : undefined, 'off');
+ const steps = getNumber(metadata, 'pid_steps');
+
+ return {
+ ...(mode === undefined ? {} : { pidMode: mode }),
+ ...(steps === null ? {} : { pidSteps: clampPidSteps(steps) }),
+ };
+};
+
+/**
+ * Per-family tuning the graphs record under their own keys, and PiD. Gated on the model recall settles on, since each
+ * setting only reaches that family's denoise, encoder or decode nodes.
+ *
+ * A generation record of that same family that leaves a switch out ran the node's default: webv2 recorded no tuning
+ * before the panel offered it. Restoring the default there means a preset turned on since does not survive recall.
+ * Values that only matter while a switch is on (DyPE scale, variance strength, PiD steps) stay as they are when
+ * missing.
+ */
+const getMetadataModelTuning = (
+ metadata: unknown,
+ model: GenerateModelConfig | undefined
+): Partial<GenerateWidgetValues> => {
+ if (!model || model.type !== 'main' || !isRecord(metadata)) {
+ return {};
+ }
+
+ const recordsFamily = isGenerationRecord(metadata) && getRecord(metadata, 'model')?.base === model.base;
+ const recordedOrDefault: RecordedOrDefault = (key, recorded, fallback) =>
+ recorded !== undefined ? recorded : recordsFamily && !(key in metadata) ? fallback : undefined;
+
+ return {
+ ...getFamilyTuning(metadata, model, recordedOrDefault),
+ ...getPidTuning(metadata, model, recordedOrDefault),
+ };
+};
+
const hasModelTuning = (metadata: unknown, model: GenerateModelConfig | undefined): boolean =>
Object.keys(getMetadataModelTuning(metadata, model)).length > 0;
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecallContract.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecallContract.test.ts
new file mode 100644
index 0000000000..4be444d2ee
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecallContract.test.ts
@@ -0,0 +1,983 @@
+/**
+ * The image recall contract. Every key an image graph records, and every key the backend declares for
+ * `core_metadata`, has an entry here; the gates hold each entry to what recall does with records compiled from
+ * settings tuned off every default. A key a builder starts to write fails G1 until it has an entry, and a key the
+ * backend starts to declare fails `tsc` until it has one.
+ */
+
+import type { components } from '@api/schema';
+import type { GalleryImage } from '@features/gallery';
+import type {
+ ComponentModelConfig,
+ GenerateModelConfig,
+ GenerateSettings,
+ GenerateWidgetValues,
+ MainModelConfig,
+} from '@features/generation/contracts';
+import type { CanvasCompileMode } from '@features/generation/core/canvas/types';
+import type { SpandrelModelConfig } from '@features/upscale/core/types';
+
+import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
+import { canvasModesFor, compile as compileCanvas } from '@features/generation/core/canvas/compileCanvasGraph.testing';
+import {
+ externalRecallCases,
+ fluxReduxRecallCase,
+ generateGraphCases,
+ krea2EditRecallCase,
+ recallCatalogFor,
+ recallTunedSettingsFor,
+ sdxlRefinerRecallCase,
+} from '@features/generation/core/graphCoverage.testing';
+import { compileGenerateGraph } from '@features/generation/graph';
+import {
+ deriveAspectRatioId,
+ getDefaultGenerateSettings,
+ getExternalResolutionPresets,
+ getGenerationUiPolicy,
+ isSupportedGenerateModel,
+ isVaeModelConfig,
+} from '@features/generation/settings';
+import { compileModelOnlyUpscaleGraph, compileUpscaleGraph } from '@features/upscale/core/graph';
+import { CASES as UPSCALE_CASES, INSTALLED, valuesForCase } from '@features/upscale/core/upscaleGraphCoverage.testing';
+import { areJsonValuesStructurallyEqual } from '@platform/core/json';
+import { describe, expect, expectTypeOf, it } from 'vitest';
+
+import {
+ buildImageRecallSettings,
+ getImageRecallCapabilities,
+ type ImageRecallKind,
+ type ImageRecallResult,
+} from './imageRecall';
+import { isRuntimeValue, type KnownKeys, recordOf } from './recallContract.testing';
+
+type Written = Readonly<Record<string, unknown>>;
+type Setting = keyof GenerateWidgetValues;
+
+/** A key recall applies to the Generate settings. */
+interface Restores {
+ restores: readonly Setting[];
+ /** The recall kinds that apply it; Recall All and Remix unless listed. */
+ kinds?: readonly ImageRecallKind[];
+ /** False where recall leaves the key alone on purpose; the ablation (G3) then proves it does. */
+ when?: (model: GenerateModelConfig, written: Written) => boolean;
+ /** What the settings hold after recall, where that is not what the record was compiled from. */
+ expected?: (written: Written, tuned: GenerateWidgetValues) => Partial<GenerateWidgetValues>;
+ /** What recall sets when a generation record of the model's family lacks the key (G8); null where it sets nothing. */
+ absent?: (model: GenerateModelConfig, written: Written) => Partial<GenerateWidgetValues> | null;
+}
+
+type Entry =
+ | Restores
+ /** Read to interpret the record, or by another recall path, never into one Generate setting of its own. */
+ | { consumed: string }
+ /** Not restored, on purpose. `declaredOnly`: the backend declares it, no image graph writes it. */
+ | { ignored: string; declaredOnly?: true };
+
+type DeclaredCoreMetadataKey = Exclude<
+ KnownKeys<components['schemas']['CoreMetadataInvocation']>,
+ 'id' | 'is_intermediate' | 'type' | 'use_cache'
+>;
+
+const VIDEO_PROFILE = 'Video profile: covered by videoRecallContract.test.ts.';
+const RUNTIME_VALUE = 'A node computes it from the prompt while the graph runs; recall restores the prompt itself.';
+const UPSCALE_SETTING = 'An Upscale panel setting; image recall restores the Generate panel only.';
+
+/** A Diffusers main records itself as its own component source; having no source slot, recall skips it. */
+const unlessMainModel = (key: string) => (model: GenerateModelConfig, written: Written) =>
+ (written[key] as { key?: unknown } | null)?.key !== model.key;
+
+const ANIMA_ADAPTER_MODES: readonly unknown[] = ['anima_inpaint', 'anima_outpaint'];
+
+const IMAGE_RECALL_CONTRACT = {
+ // What the record is.
+ generation_mode: {
+ consumed:
+ 'Marks a generation record, on which a key left out ran at its default (G8); an Anima inpaint or outpaint ' +
+ 'mode without `anima_inpaint_adapter` switches the adapter off.',
+ },
+ model: { restores: ['model', 'modelKey'] },
+ rand_device: { ignored: 'Follows the project noise setting (`useCpuNoise`), which Generate does not hold.' },
+ app_version: { ignored: 'Stamped by the backend; a model-only upscale copies it from its source.' },
+ metadata_version: { ignored: 'Stamped by the backend; a model-only upscale copies it from its source.' },
+
+ // Prompts, seed and size.
+ positive_prompt: {
+ kinds: ['all', 'remix', 'prompts'],
+ restores: ['positivePrompt', 'promptTemplate', 'promptTemplateViewMode'],
+ },
+ negative_prompt: {
+ kinds: ['all', 'remix', 'prompts'],
+ restores: ['negativePrompt', 'promptTemplate', 'promptTemplateViewMode'],
+ },
+ seed: { kinds: ['all', 'seed'], restores: ['seed', 'seedMode'] },
+ // An upscale records the size of the frame it enlarged, which only exists once the graph runs.
+ width: {
+ restores: ['width', 'aspectRatioId', 'aspectRatioValue'],
+ when: (_model, written) => typeof written.width === 'number',
+ },
+ height: {
+ restores: ['height', 'aspectRatioId', 'aspectRatioValue'],
+ when: (_model, written) => typeof written.height === 'number',
+ },
+
+ // Sampling. Recall restores CFG rescale and seamless tiling on every family; the fixtures carry their defaults
+ // where the panel hides them.
+ steps: { restores: ['steps'] },
+ cfg_scale: { restores: ['cfgScale'] },
+ guidance: { restores: ['cfgScale'], when: (model) => getGenerationUiPolicy(model).guidanceLabel === 'Guidance' },
+ cfg_rescale_multiplier: {
+ restores: ['cfgRescaleMultiplier'],
+ when: (model) => getGenerationUiPolicy(model).cfgRescaleVisible,
+ },
+ // A family without a scheduler choice records its fixed one, which recall restores as recorded.
+ scheduler: { expected: (written) => ({ scheduler: String(written.scheduler) }), restores: ['scheduler'] },
+ seamless_x: { restores: ['seamlessXAxis'], when: (model) => getGenerationUiPolicy(model).seamlessVisible },
+ seamless_y: { restores: ['seamlessYAxis'], when: (model) => getGenerationUiPolicy(model).seamlessVisible },
+ clip_skip: {
+ kinds: ['all', 'remix', 'clipSkip'],
+ restores: ['clipSkip'],
+ when: (model) => getGenerationUiPolicy(model).clipSkipMax !== null,
+ },
+ hidiffusion: { restores: ['hiDiffusionEnabled'] },
+ hidiffusion_raunet: { restores: ['hiDiffusionRauNetEnabled'] },
+ hidiffusion_window_attn: { restores: ['hiDiffusionWindowAttentionEnabled'] },
+ hidiffusion_t1_ratio: { restores: ['hiDiffusionT1Ratio'] },
+ hidiffusion_t2_ratio: { restores: ['hiDiffusionT2Ratio'] },
+ hidiffusion_auto_ratios: {
+ consumed: 'Says whether the recorded ratios are automatic, which restores them as unset.',
+ },
+
+ // Components.
+ vae: { restores: ['vae'] },
+ qwen_image_vae: { consumed: "Qwen-Image's VAE alias, read only from records without `vae`; the graph writes both." },
+ clip_embed_model: { restores: ['clipEmbedModel'] },
+ t5_encoder: { restores: ['t5EncoderModel'] },
+ mistral_encoder: { restores: ['mistralEncoderModel'] },
+ qwen3_encoder: { restores: ['qwen3EncoderModel'] },
+ qwen3_5_encoder: { restores: ['qwen35EncoderModel'] },
+ qwen3_vl_encoder: { restores: ['qwen3VLEncoderModel'] },
+ qwen3_vl_vision_tower: { restores: ['qwen3VLVisionTowerModel'] },
+ qwen_image_qwen_vl_encoder: { restores: ['qwenVLEncoderModel'] },
+ wan_t5_encoder_model: { restores: ['wanT5EncoderModel'] },
+ qwen3_source: { restores: ['componentSourceModel'], when: unlessMainModel('qwen3_source') },
+ qwen_image_component_source: {
+ restores: ['componentSourceModel'],
+ when: unlessMainModel('qwen_image_component_source'),
+ },
+ wan_component_source: { restores: ['componentSourceModel'], when: unlessMainModel('wan_component_source') },
+ wan_transformer_low_noise: { restores: ['wanLowNoiseModel'] },
+ ideogram4_unconditional_model: { restores: ['ideogram4UnconditionalModel'] },
+ pid_decoder: { restores: ['pidDecoderModel'] },
+ gemma2_encoder: { restores: ['gemma2EncoderModel'] },
+ anima_inpaint_adapter: {
+ absent: (model, written) =>
+ model.base === 'anima' && ANIMA_ADAPTER_MODES.includes(written.generation_mode)
+ ? { animaInpaintAdapterEnabled: false }
+ : null,
+ restores: ['animaInpaintAdapterModel', 'animaInpaintAdapterEnabled'],
+ },
+ anima_inpaint_adapter_weight: { restores: ['animaInpaintAdapterWeight'] },
+
+ // Concepts and references.
+ loras: { absent: () => ({ loras: [] }), restores: ['loras'] },
+ ref_images: { restores: ['referenceImages'] },
+ krea2_style_strength: {
+ ignored: 'Repeats the style reference strength, which `ref_images` restores with the reference itself.',
+ },
+
+ // SDXL refiner.
+ refiner_model: {
+ absent: (model) => (getGenerationUiPolicy(model).refinerVisible ? { refinerModel: null } : null),
+ restores: ['refinerModel'],
+ },
+ refiner_steps: { restores: ['refinerSteps'] },
+ refiner_cfg_scale: { restores: ['refinerCfgScale'] },
+ refiner_scheduler: { restores: ['refinerScheduler'] },
+ refiner_start: { restores: ['refinerStart'] },
+ refiner_positive_aesthetic_score: { restores: ['refinerPositiveAestheticScore'] },
+ refiner_negative_aesthetic_score: { restores: ['refinerNegativeAestheticScore'] },
+
+ // Family tuning.
+ dype_preset: {
+ absent: (model) => (model.base === 'flux' ? { fluxDypePreset: 'off' } : null),
+ restores: ['fluxDypePreset'],
+ },
+ dype_scale: { restores: ['fluxDypeScale'] },
+ dype_exponent: { restores: ['fluxDypeExponent'] },
+ z_image_shift: {
+ absent: (model) => (model.base === 'z-image' ? { zImageShift: null } : null),
+ restores: ['zImageShift'],
+ },
+ z_image_seed_variance_enabled: {
+ absent: (model) => (model.base === 'z-image' ? { zImageSeedVarianceEnabled: false } : null),
+ restores: ['zImageSeedVarianceEnabled'],
+ },
+ z_image_seed_variance_strength: { restores: ['zImageSeedVarianceStrength'] },
+ z_image_seed_variance_randomize_percent: { restores: ['zImageSeedVarianceRandomizePercent'] },
+ qwen_image_shift: {
+ absent: (model) => (model.base === 'qwen-image' ? { qwenImageShift: null } : null),
+ restores: ['qwenImageShift'],
+ },
+ qwen_image_quantization: {
+ absent: (model) => (model.base === 'qwen-image' ? { qwenImageEncoderQuantization: 'none' } : null),
+ restores: ['qwenImageEncoderQuantization'],
+ },
+ wan_guidance_scale_low_noise: {
+ absent: (model) => (model.base === 'wan' ? { wanGuidanceScaleLowNoise: null } : null),
+ restores: ['wanGuidanceScaleLowNoise'],
+ },
+ ideogram4_sampler_preset: { restores: ['ideogram4SamplerPreset'] },
+ ideogram4_steps: {
+ absent: (model) => (model.base === 'ideogram-4' ? { ideogram4Steps: null } : null),
+ restores: ['ideogram4Steps'],
+ },
+ ideogram4_guidance_scale: {
+ absent: (model) => (model.base === 'ideogram-4' ? { ideogram4GuidanceScale: null } : null),
+ restores: ['ideogram4GuidanceScale'],
+ },
+ ideogram4_mu: {
+ absent: (model) => (model.base === 'ideogram-4' ? { ideogram4Mu: null } : null),
+ restores: ['ideogram4Mu'],
+ },
+ ideogram4_color_palette: { restores: ['ideogram4ColorPalette'] },
+ ideogram4_caption: { ignored: RUNTIME_VALUE },
+ krea2_rebalance_enabled: { restores: ['krea2RebalanceEnabled'] },
+ krea2_rebalance_multiplier: { restores: ['krea2RebalanceMultiplier'] },
+ krea2_rebalance_weights: { restores: ['krea2RebalanceWeights'] },
+ krea2_seed_variance_enabled: { restores: ['krea2SeedVarianceEnabled'] },
+ krea2_seed_variance_strength: { restores: ['krea2SeedVarianceStrength'] },
+ krea2_seed_variance_randomize_percent: { restores: ['krea2SeedVarianceRandomizePercent'] },
+ krea2_reference_kv_cache: { restores: ['krea2ReferenceKvCache'] },
+ moss_image_uncond_skip_layers: { restores: ['mossImageUncondSkipLayers'] },
+ moss_image_layout_prompt: { ignored: RUNTIME_VALUE },
+ flux3_caption: { ignored: RUNTIME_VALUE },
+ pid_mode: {
+ absent: (model) => (getGenerationUiPolicy(model).pidVisible ? { pidMode: 'off' } : null),
+ restores: ['pidMode'],
+ },
+ pid_steps: { restores: ['pidSteps'] },
+
+ // Hosted providers. A named size restores only with the size it names: a Canvas frame keeps its own size.
+ image_size: {
+ restores: ['externalImageSize', 'width', 'height', 'aspectRatioId', 'aspectRatioValue'],
+ when: (model, written) =>
+ getExternalResolutionPresets(model).some(
+ (preset) =>
+ preset.image_size === written.image_size && preset.width === written.width && preset.height === written.height
+ ),
+ },
+ openai_quality: { restores: ['openaiQuality'] },
+ openai_background: { restores: ['openaiBackground'] },
+ openai_input_fidelity: { restores: ['openaiInputFidelity'] },
+ gemini_temperature: { restores: ['geminiTemperature'] },
+ gemini_thinking_level: { restores: ['geminiThinkingLevel'] },
+ seedream_watermark: { restores: ['seedreamWatermark'] },
+ seedream_optimize_prompt: { restores: ['seedreamOptimizePrompt'] },
+
+ // Canvas.
+ strength: { consumed: 'Canvas recall restores the denoising strength; it also lets a Canvas record offer recall.' },
+ control_layers: {
+ consumed: 'Canvas recall restores the control layers; they also let a Canvas record offer recall.',
+ },
+ controlnets: {
+ consumed: 'The backend-declared view of `control_layers`; Canvas recall reads it from records without them.',
+ },
+ t2iAdapters: {
+ consumed: 'The backend-declared view of `control_layers`; Canvas recall reads it from records without them.',
+ },
+ canvas_v3_metadata: { consumed: 'Canvas recall restores the Canvas document from it.' },
+ regions: {
+ ignored:
+ 'The resolved regional prompts and masks, recorded as provenance; Canvas recall restores the regional ' +
+ 'guidance layers from `canvas_v3_metadata` instead.',
+ },
+
+ // Upscale.
+ creativity: { ignored: UPSCALE_SETTING },
+ structure: { ignored: UPSCALE_SETTING },
+ tile_overlap: { ignored: UPSCALE_SETTING },
+ tile_size: { ignored: UPSCALE_SETTING },
+ upscale_initial_image: { ignored: UPSCALE_SETTING },
+ upscale_model: { ignored: UPSCALE_SETTING },
+ upscale_scale: { ignored: UPSCALE_SETTING },
+
+ // Declared by the backend, written by no image graph.
+ ipAdapters: {
+ declaredOnly: true,
+ ignored: 'Written by the legacy web UI; recall reads it from those records as reference images.',
+ },
+ init_image: { declaredOnly: true, ignored: 'Legacy image-to-image source; the Canvas records its own.' },
+ hrf_enabled: { declaredOnly: true, ignored: 'Legacy high-resolution fix, which Generate does not offer.' },
+ hrf_method: { declaredOnly: true, ignored: 'Legacy high-resolution fix, which Generate does not offer.' },
+ hrf_strength: { declaredOnly: true, ignored: 'Legacy high-resolution fix, which Generate does not offer.' },
+ positive_style_prompt: {
+ declaredOnly: true,
+ ignored: 'Legacy SDXL style prompt; the SDXL graph sends the prompt to both encoders.',
+ },
+ negative_style_prompt: {
+ declaredOnly: true,
+ ignored: 'Legacy SDXL style prompt; the SDXL graph sends the prompt to both encoders.',
+ },
+ num_frames: { declaredOnly: true, ignored: VIDEO_PROFILE },
+ fps: { declaredOnly: true, ignored: VIDEO_PROFILE },
+ first_frame_image: { declaredOnly: true, ignored: VIDEO_PROFILE },
+ last_frame_image: { declaredOnly: true, ignored: VIDEO_PROFILE },
+ source_video: { declaredOnly: true, ignored: VIDEO_PROFILE },
+ source_video_start_frame: { declaredOnly: true, ignored: VIDEO_PROFILE },
+ source_video_end_frame: { declaredOnly: true, ignored: VIDEO_PROFILE },
+ ltx2_context_frames: { declaredOnly: true, ignored: VIDEO_PROFILE },
+ minimax_h3_transformer_model: { declaredOnly: true, ignored: VIDEO_PROFILE },
+ minimax_h3_text_encoder_model: { declaredOnly: true, ignored: VIDEO_PROFILE },
+ minimax_h3_component_source: { declaredOnly: true, ignored: VIDEO_PROFILE },
+ minimax_h3_hybrid_base_model: { declaredOnly: true, ignored: VIDEO_PROFILE },
+ minimax_h3_hybrid_start_block: { declaredOnly: true, ignored: VIDEO_PROFILE },
+ minimax_h3_references: { declaredOnly: true, ignored: VIDEO_PROFILE },
+} satisfies Record<DeclaredCoreMetadataKey, Entry> & Record<string, Entry>;
+
+const CONTRACT: Readonly<Record<string, Entry>> = IMAGE_RECALL_CONTRACT;
+
+type Contract = typeof IMAGE_RECALL_CONTRACT;
+
+/** The keys the table calls declared only, which the backend schema must still declare. */
+type DeclaredOnlyKey = {
+ [K in keyof Contract]: Contract[K] extends { declaredOnly: true } ? K : never;
+}[keyof Contract];
+
+const entryOf = (key: string): Entry | undefined => (Object.hasOwn(CONTRACT, key) ? CONTRACT[key] : undefined);
+
+/** Every label recall can report, so G5 cannot miss a new one: an unlisted member fails `tsc`. */
+const RECALLED_FIELDS = {
+ animaInpaintAdapterWeight: true,
+ cfg: true,
+ clipSkip: true,
+ components: true,
+ externalProvider: true,
+ hiDiffusion: true,
+ krea2Rebalance: true,
+ krea2SeedVariance: true,
+ loras: true,
+ model: true,
+ modelTuning: true,
+ mossImageSkipLayers: true,
+ prompts: true,
+ referenceImages: true,
+ refiner: true,
+ scheduler: true,
+ seamless: true,
+ seed: true,
+ size: true,
+ steps: true,
+ vae: true,
+} satisfies Record<ImageRecallResult['fields'][number], true>;
+
+const DEFAULT_KINDS: readonly ImageRecallKind[] = ['all', 'remix'];
+
+/** The settings choosing a model resets to its defaults before the record lands, which a vacuous round trip hides. */
+const MODEL_DEFAULT_SETTINGS: ReadonlySet<Setting> = new Set([
+ 'aspectRatioId',
+ 'aspectRatioValue',
+ 'cfgRescaleMultiplier',
+ 'cfgScale',
+ 'height',
+ 'scheduler',
+ 'steps',
+ 'width',
+]);
+
+/** Values the policy holds at the model default, so every record carries the default. */
+const isPolicyPinned = (model: GenerateModelConfig, setting: Setting): boolean =>
+ // FLUX.3 Klein samples without CFG; validation refuses any other scale.
+ (setting === 'cfgScale' && model.base === 'flux3' && model.variant === 'flux3_klein') ||
+ // A family without a scheduler choice records its fixed one.
+ (setting === 'scheduler' && !getGenerationUiPolicy(model).schedulerVisible);
+
+const BASELINE_MODEL: MainModelConfig = { base: 'sdxl', key: 'baseline-sdxl', name: 'Baseline SDXL', type: 'main' };
+const SD1_BASELINE_MODEL: MainModelConfig = {
+ base: 'sd-1',
+ key: 'baseline-sd-1',
+ name: 'Baseline SD 1.5',
+ type: 'main',
+};
+
+/** The panel recall lands on: SDXL defaults with a concept, a prompt template and a random seed. */
+const baselineValues = (): GenerateWidgetValues => ({
+ ...getDefaultGenerateSettings(BASELINE_MODEL),
+ loras: [
+ { isEnabled: true, model: { base: 'sdxl', key: 'baseline-lora', name: 'Baseline LoRA', type: 'lora' }, weight: 1 },
+ ],
+ model: BASELINE_MODEL,
+ positivePrompt: 'the baseline prompt',
+ promptTemplate: { id: 'template', name: 'Template', negativePrompt: 'lowres', positivePrompt: '{prompt}, detailed' },
+ promptTemplateViewMode: true,
+ seed: 123,
+ seedMode: 'random',
+});
+
+/** CLIP skip is judged against the panel's own model, which SDXL lacks. */
+const sd1BaselineValues = (): GenerateWidgetValues => ({
+ ...getDefaultGenerateSettings(SD1_BASELINE_MODEL),
+ clipSkip: 5,
+ model: SD1_BASELINE_MODEL,
+ seed: 123,
+});
+
+/** The baseline off the default of every setting a generation record resets when it lacks the key (G8). */
+const offDefaultBaselineValues = (): GenerateWidgetValues => ({
+ ...baselineValues(),
+ fluxDypePreset: 'manual',
+ ideogram4GuidanceScale: 5,
+ ideogram4Mu: 1,
+ ideogram4Steps: 30,
+ pidMode: 'fit',
+ qwenImageEncoderQuantization: 'nf4',
+ qwenImageShift: 2,
+ refinerModel: { base: 'sdxl-refiner', key: 'baseline-refiner', name: 'Baseline refiner', type: 'main' },
+ wanGuidanceScaleLowNoise: 3.5,
+ zImageSeedVarianceEnabled: true,
+ zImageShift: 2,
+});
+
+const imageOf = ({ height, width }: { height: number; width: number }): GalleryImage => ({
+ boardId: 'none',
+ height,
+ imageCategory: 'general',
+ imageName: 'recalled.png',
+ imageUrl: '/recalled.png',
+ queuedAt: '2026-11-09T00:00:00.000Z',
+ sourceQueueItemId: 'recall-contract',
+ starred: false,
+ thumbnailUrl: '/recalled-thumbnail.png',
+ width,
+});
+
+const PROJECT_SETTINGS = { useCpuNoise: true, useNsfwChecker: false, useWatermark: false };
+
+type RecallInput = Parameters<typeof buildImageRecallSettings>[0];
+
+interface RecallCase {
+ label: string;
+ /** The main model the record names, which recall settles on. */
+ model: GenerateModelConfig;
+ record: Written;
+ catalog: Pick<RecallInput, 'models' | 'supportedModels' | 'vaeModels'>;
+ image: GalleryImage;
+ /** The Generate settings the record was compiled from; null for a record of another panel's settings. */
+ tuned: GenerateWidgetValues | null;
+ /** The panel recall lands on. */
+ baseline: GenerateWidgetValues;
+ isCanvasFrame?: true;
+}
+
+interface SettingsFixture {
+ label: string;
+ model: GenerateModelConfig;
+ settings: GenerateSettings;
+}
+
+/** Compiles the fixture, naming it when validation refuses it. */
+const compiled = <T>(label: string, compile: () => T): T => {
+ try {
+ return compile();
+ } catch (error) {
+ throw new Error(`${label} does not compile: ${String(error)}`, { cause: error });
+ }
+};
+
+const generateCase = ({ label, model, settings }: SettingsFixture, baseline: GenerateWidgetValues): RecallCase => ({
+ baseline,
+ catalog: recallCatalogFor(model, settings),
+ image: imageOf(settings),
+ label,
+ model,
+ record: recordOf(
+ compiled(label, () => compileGenerateGraph(settings, model, 'gallery', PROJECT_SETTINGS)),
+ settings
+ ),
+ tuned: { ...settings, model },
+});
+
+const canvasCase = (
+ { label, model, settings }: SettingsFixture,
+ mode: CanvasCompileMode,
+ baseline: GenerateWidgetValues,
+ extra: Omit<NonNullable<Parameters<typeof compileCanvas>[2]>, 'bbox' | 'settings'> & {
+ frame?: { height: number; width: number };
+ isCanvasFrame?: true;
+ } = {}
+): RecallCase => {
+ const { frame = settings, isCanvasFrame, ...overrides } = extra;
+ const caseLabel = `${label} / canvas ${mode}`;
+ // PiD decodes only the modes that keep the whole frame.
+ const canvasSettings = mode === 'txt2img' || mode === 'img2img' ? settings : { ...settings, pidMode: 'off' as const };
+
+ return {
+ baseline,
+ catalog: recallCatalogFor(model, canvasSettings),
+ image: imageOf(frame),
+ ...(isCanvasFrame ? { isCanvasFrame } : {}),
+ label: caseLabel,
+ model,
+ record: recordOf(
+ compiled(caseLabel, () =>
+ compileCanvas(model, mode, {
+ ...overrides,
+ bbox: { height: frame.height, width: frame.width, x: 0, y: 0 },
+ settings: canvasSettings,
+ })
+ ),
+ canvasSettings
+ ),
+ // The record names the frame's size.
+ tuned: {
+ ...canvasSettings,
+ aspectRatioId: deriveAspectRatioId(frame.width, frame.height),
+ aspectRatioValue: frame.width / frame.height,
+ height: frame.height,
+ model,
+ width: frame.width,
+ },
+ };
+};
+
+const upscaleCase = (testCase: (typeof UPSCALE_CASES)[number], baseline: GenerateWidgetValues): RecallCase => {
+ const label = `upscale / ${testCase.label}`;
+ const { installed, values } = valuesForCase(testCase);
+ const [model] = installed.filter(isSupportedGenerateModel);
+
+ return {
+ baseline,
+ catalog: {
+ models: installed,
+ supportedModels: [model!],
+ vaeModels: installed.flatMap((entry) => (isVaeModelConfig(entry) ? [entry] : [])),
+ },
+ image: imageOf({ height: 400, width: 808 }),
+ label,
+ model: model!,
+ record: recordOf(
+ compiled(label, () => compileUpscaleGraph(values, 'gallery', { useCpuNoise: true })),
+ values
+ ),
+ tuned: null,
+ };
+};
+
+/** Model only copies the source's record, as the backend saved it, and adds what the upscale did. */
+const modelOnlyUpscaleCase = (source: RecallCase): RecallCase => {
+ const { backendGraph } = compileModelOnlyUpscaleGraph({
+ destination: 'gallery',
+ image: { height: source.image.height, image_name: source.image.imageName, width: source.image.width },
+ scale: 2,
+ sourceMetadata: { ...source.record, app_version: '7.0.0', metadata_version: '1.2.0' },
+ upscaleModel: { ...INSTALLED[0], scale: 4 } as SpandrelModelConfig,
+ });
+
+ return {
+ ...source,
+ image: imageOf({ height: source.image.height * 2, width: source.image.width * 2 }),
+ label: `upscale / model-only from ${source.label}`,
+ record: JSON.parse(JSON.stringify(backendGraph.nodes.upscale_output!.metadata)) as Written,
+ };
+};
+
+const ANIMA_INPAINT_ADAPTER: ComponentModelConfig = {
+ base: 'anima',
+ cond_in_channels: 4,
+ key: 'anima-inpaint-adapter',
+ name: 'Anima LLLite Inpainting',
+ type: 'controlnet',
+};
+
+const CANVAS_REGION = {
+ autoNegative: false,
+ id: 'region',
+ maskBounds: { height: 256, width: 192, x: 64, y: 128 },
+ maskImageName: 'region-mask.png',
+ negativePrompt: null,
+ positivePrompt: 'a cat',
+ referenceImages: [],
+};
+
+const buildCases = (): RecallCase[] => {
+ const baseline = baselineValues();
+ const tunedShapes = generateGraphCases.map(({ base, shape }) => recallTunedSettingsFor(base, shape));
+ const generate = [
+ ...tunedShapes,
+ sdxlRefinerRecallCase(),
+ fluxReduxRecallCase(),
+ krea2EditRecallCase(),
+ ...externalRecallCases(),
+ ].map((fixture) => generateCase(fixture, baseline));
+ // One shape per base: the Canvas adds the same keys to every shape's record.
+ const firstShapes = tunedShapes.filter(
+ (fixture, index) => tunedShapes.findIndex((other) => other.model.base === fixture.model.base) === index
+ );
+ const fixtureFor = (base: string) => firstShapes.find((fixture) => fixture.model.base === base)!;
+ const canvas = firstShapes.flatMap((fixture) =>
+ canvasModesFor(fixture.model, fixture.settings).map((mode) => canvasCase(fixture, mode, baseline))
+ );
+ const anima = fixtureFor('anima');
+ const sdxl = fixtureFor('sdxl');
+ const [, gemini] = externalRecallCases();
+
+ return [
+ ...generate,
+ ...canvas,
+ // The adapter switch is on by default, so only a panel that has it off shows a record turning it on.
+ canvasCase(
+ {
+ ...anima,
+ label: `${anima.label} with inpaint adapter`,
+ settings: {
+ ...anima.settings,
+ animaInpaintAdapterEnabled: true,
+ animaInpaintAdapterModel: ANIMA_INPAINT_ADAPTER,
+ animaInpaintAdapterWeight: 0.7,
+ },
+ },
+ 'inpaint',
+ { ...baseline, animaInpaintAdapterEnabled: false }
+ ),
+ canvasCase({ ...sdxl, label: `${sdxl.label} with layers` }, 'img2img', baseline, {
+ canvasMetadata: { version: 1 },
+ controlLayers: [
+ {
+ beginEndStepPct: [0.1, 0.85],
+ controlMode: 'more_control',
+ id: 'control',
+ imageName: 'control.png',
+ kind: 'controlnet',
+ model: { base: 'sdxl', key: 'sdxl-controlnet', name: 'SDXL ControlNet', type: 'controlnet' },
+ weight: 0.65,
+ },
+ {
+ beginEndStepPct: [0, 1],
+ controlMode: null,
+ id: 't2i',
+ imageName: 't2i.png',
+ kind: 't2i_adapter',
+ model: { base: 'sdxl', key: 'sdxl-t2i-adapter', name: 'SDXL T2I-Adapter', type: 't2i_adapter' },
+ weight: 0.8,
+ },
+ ],
+ regionalGuidance: [CANVAS_REGION],
+ }),
+ // A layout family places regions in its caption, which the record takes from the caption node.
+ canvasCase({ ...fixtureFor('flux3'), label: `${fixtureFor('flux3').label} with a region` }, 'txt2img', baseline, {
+ regionalGuidance: [CANVAS_REGION],
+ }),
+ // The provider was asked for its named size nearest the frame; a Canvas route keeps the frame.
+ canvasCase(gemini!, 'txt2img', baseline, { frame: { height: 800, width: 1000 }, isCanvasFrame: true }),
+ ...UPSCALE_CASES.map((testCase) => upscaleCase(testCase, baseline)),
+ modelOnlyUpscaleCase(generate.find(({ label }) => label === 'sdxl / diffusers')!),
+ ];
+};
+
+let cases: RecallCase[] | undefined;
+
+/** Built inside a test, where the architecture table is seeded. */
+const getCases = (): RecallCase[] => (cases ??= buildCases());
+
+const recall = (
+ testCase: RecallCase,
+ kind: ImageRecallKind,
+ {
+ currentValues = testCase.baseline,
+ metadata = testCase.record,
+ }: { currentValues?: GenerateWidgetValues; metadata?: Written } = {}
+) =>
+ buildImageRecallSettings({
+ ...testCase.catalog,
+ currentValues,
+ image: testCase.image,
+ isCanvasFrame: testCase.isCanvasFrame,
+ kind,
+ metadata,
+ });
+
+const equal = areJsonValuesStructurallyEqual;
+const show = (value: unknown): string => JSON.stringify(value) ?? String(value);
+
+/** The written keys whose entry restores a setting, with the entry. */
+const restoringKeys = ({ record }: RecallCase): [string, Restores][] =>
+ Object.keys(record).flatMap((key) => {
+ const entry = entryOf(key);
+
+ return entry && 'restores' in entry ? [[key, entry]] : [];
+ });
+
+/** The settings the record's restoring entries apply under `kind`. */
+const settingsUnder = (testCase: RecallCase, kind: ImageRecallKind): Setting[] => [
+ ...new Set(
+ restoringKeys(testCase).flatMap(([, entry]) =>
+ (entry.kinds ?? DEFAULT_KINDS).includes(kind) ? entry.restores : []
+ )
+ ),
+];
+
+const pick = (values: GenerateWidgetValues, settings: readonly Setting[]): Partial<GenerateWidgetValues> =>
+ Object.fromEntries(settings.map((setting) => [setting, values[setting]]));
+
+const changedSettings = (left: GenerateWidgetValues, right: GenerateWidgetValues): string[] =>
+ (Object.keys(left) as Setting[]).filter((setting) => !equal(left[setting], right[setting]));
+
+seedArchitectureCapabilities();
+
+describe('image recall contract', () => {
+ it('G1: has an entry for every key an image graph writes', () => {
+ const failures = getCases().flatMap(({ label, model, record }) =>
+ Object.entries(record).flatMap(([key, value]) => {
+ const entry = entryOf(key);
+
+ if (!entry) {
+ return [`G1: \`${key}\` written by \`${label}\` has no entry in IMAGE_RECALL_CONTRACT`];
+ }
+
+ return isRuntimeValue(value) && 'restores' in entry && entry.when?.(model, record) !== false
+ ? [`G1: \`${key}\` in \`${label}\` is computed while the graph runs (${value}); no round trip can show it`]
+ : [];
+ })
+ );
+
+ expect(failures).toEqual([]);
+ });
+
+ it('G2: restores every value it claims to, from a panel that held another', () => {
+ const failures: string[] = [];
+
+ for (const testCase of getCases()) {
+ const { baseline, label, model, record, tuned } = testCase;
+
+ if (!tuned) {
+ continue;
+ }
+
+ const values = recall(testCase, 'all')?.values;
+ const modelDefaults: GenerateWidgetValues = { ...getDefaultGenerateSettings(model), model };
+
+ for (const [key, entry] of restoringKeys(testCase)) {
+ if (entry.when?.(model, record) === false) {
+ continue;
+ }
+
+ const expected = { ...pick(tuned, entry.restores), ...entry.expected?.(record, tuned) };
+
+ for (const setting of entry.restores) {
+ if (!equal(values?.[setting], expected[setting])) {
+ failures.push(
+ `G2: \`${key}\` in \`${label}\` restores ${setting} as ${show(values?.[setting])}, expected ${show(expected[setting])}`
+ );
+ }
+
+ if (
+ equal(baseline[setting], expected[setting]) ||
+ (MODEL_DEFAULT_SETTINGS.has(setting) &&
+ equal(modelDefaults[setting], expected[setting]) &&
+ !isPolicyPinned(model, setting))
+ ) {
+ failures.push(
+ `G2 vacuous: \`${key}\` in \`${label}\` expects ${setting} ${show(expected[setting])}, which the panel ` +
+ 'or the model default already holds'
+ );
+ }
+ }
+ }
+ }
+
+ expect(failures).toEqual([]);
+ });
+
+ it('G3: leaves the settings as they are without each key it does not restore', () => {
+ const failures: string[] = [];
+
+ for (const testCase of getCases()) {
+ const { label, model, record } = testCase;
+ const full = recall(testCase, 'all')?.values ?? null;
+
+ for (const key of Object.keys(record)) {
+ const entry = entryOf(key);
+ const inert = entry && ('ignored' in entry || ('restores' in entry && entry.when?.(model, record) === false));
+
+ if (!inert) {
+ continue;
+ }
+
+ const { [key]: _ablated, ...without } = record;
+ const ablated = recall(testCase, 'all', { metadata: without })?.values ?? null;
+
+ if (!equal(full, ablated)) {
+ failures.push(
+ `G3: \`${key}\` in \`${label}\` changes ${full && ablated ? changedSettings(full, ablated).join(', ') : 'whether anything is recalled'}, so recall reads it`
+ );
+ }
+ }
+ }
+
+ expect(failures).toEqual([]);
+ });
+
+ it('G4: applies each recall kind to exactly its own settings', () => {
+ const failures: string[] = [];
+ const sd1Baseline = sd1BaselineValues();
+
+ for (const testCase of getCases()) {
+ const { baseline, image, label, record } = testCase;
+ const all = recall(testCase, 'all')?.values;
+
+ if (!all) {
+ failures.push(`G4: \`${label}\` recalls nothing`);
+ continue;
+ }
+
+ // Remix is Recall All without the settings only Recall All applies: the seed.
+ const allOnly = settingsUnder(testCase, 'all').filter(
+ (setting) => !settingsUnder(testCase, 'remix').includes(setting)
+ );
+ const expectations: [ImageRecallKind, GenerateWidgetValues | null, GenerateWidgetValues][] = [
+ ['remix', recall(testCase, 'remix')?.values ?? null, { ...all, ...pick(baseline, allOnly) }],
+ [
+ 'prompts',
+ recall(testCase, 'prompts')?.values ?? null,
+ { ...baseline, ...pick(all, settingsUnder(testCase, 'prompts')) },
+ ],
+ [
+ 'seed',
+ recall(testCase, 'seed')?.values ?? null,
+ { ...baseline, ...pick(all, settingsUnder(testCase, 'seed')) },
+ ],
+ [
+ 'dimensions',
+ recall(testCase, 'dimensions')?.values ?? null,
+ {
+ ...baseline,
+ aspectRatioId: deriveAspectRatioId(image.width, image.height),
+ aspectRatioValue: image.width / image.height,
+ height: image.height,
+ width: image.width,
+ },
+ ],
+ ];
+
+ for (const [kind, actual, expected] of expectations) {
+ if (!actual || !equal(actual, expected)) {
+ failures.push(
+ `G4: ${kind} recall of \`${label}\` ${actual ? `differs in ${changedSettings(actual, expected).join(', ')}` : 'restores nothing'}`
+ );
+ }
+ }
+
+ // SD 1.5 caps CLIP skip at 12.
+ const clipSkip = recall(testCase, 'clipSkip', { currentValues: sd1Baseline })?.values ?? null;
+ const expectedClipSkip =
+ typeof record.clip_skip === 'number' ? { ...sd1Baseline, clipSkip: Math.min(12, record.clip_skip) } : null;
+
+ if (!equal(clipSkip, expectedClipSkip)) {
+ failures.push(
+ `G4: clipSkip on \`${label}\` gives ${show(clipSkip?.clipSkip)}, expected ${show(expectedClipSkip?.clipSkip)}`
+ );
+ }
+ }
+
+ expect(failures).toEqual([]);
+ });
+
+ it('G5: reports every field label from some record', () => {
+ const reported = new Set<string>(getCases().flatMap((testCase) => recall(testCase, 'all')?.fields ?? []));
+
+ expect(
+ Object.keys(RECALLED_FIELDS).filter((field) => !reported.has(field)),
+ 'G5: no case reports these fields'
+ ).toEqual([]);
+ });
+
+ it('G6: offers every recall a record supports', () => {
+ const sd1Baseline = sd1BaselineValues();
+ const failures = getCases().flatMap((testCase) => {
+ const { baseline, catalog, image, label, record } = testCase;
+ const input = { ...catalog, image, metadata: record };
+ const capabilities = getImageRecallCapabilities({ ...input, currentValues: baseline });
+ const expected = {
+ all: true,
+ clipSkip: false,
+ dimensions: true,
+ prompts: true,
+ remix: true,
+ seed: true,
+ workflow: false,
+ };
+ const sd1ClipSkip = getImageRecallCapabilities({ ...input, currentValues: sd1Baseline }).clipSkip;
+
+ return [
+ ...(equal(capabilities, expected) ? [] : [`G6: \`${label}\` offers ${show(capabilities)}`]),
+ ...(sd1ClipSkip === 'clip_skip' in record
+ ? []
+ : [`G6: \`${label}\` offers CLIP skip ${String(sd1ClipSkip)} on SD 1.5`]),
+ ];
+ });
+
+ expect(failures).toEqual([]);
+ });
+
+ it('G7: keeps no entry no record exercises', () => {
+ // Checked by `tsc`: a key the backend stops declaring fails here until its entry goes.
+ expectTypeOf<Exclude<DeclaredOnlyKey, DeclaredCoreMetadataKey>>().toEqualTypeOf<never>();
+
+ const allCases = getCases();
+ const written = new Set(allCases.flatMap(({ record }) => Object.keys(record)));
+ const roundTripped = new Set(
+ allCases.flatMap((testCase) =>
+ testCase.tuned
+ ? restoringKeys(testCase)
+ .filter(([, entry]) => entry.when?.(testCase.model, testCase.record) !== false)
+ .map(([key]) => key)
+ : []
+ )
+ );
+ const failures = Object.entries(CONTRACT).flatMap(([key, entry]) => {
+ if ('restores' in entry) {
+ return roundTripped.has(key) ? [] : [`G7: no record round-trips \`${key}\``];
+ }
+
+ if ('ignored' in entry && entry.declaredOnly) {
+ return written.has(key) ? [`G7: \`${key}\` is written by an image graph, so it is not declared only`] : [];
+ }
+
+ return written.has(key) ? [] : [`G7: no image graph writes \`${key}\``];
+ });
+
+ expect(failures).toEqual([]);
+ });
+
+ it('G8: restores the default a generation record implies for each key it lacks', () => {
+ const offDefaults = offDefaultBaselineValues();
+ const failures: string[] = [];
+
+ for (const testCase of getCases()) {
+ const { label, model, record } = testCase;
+
+ if (typeof record.generation_mode !== 'string') {
+ continue;
+ }
+
+ const values = recall(testCase, 'all', { currentValues: offDefaults })?.values;
+
+ for (const [key, entry] of Object.entries(CONTRACT)) {
+ const defaults = !(key in record) && 'restores' in entry ? entry.absent?.(model, record) : null;
+
+ for (const [setting, value] of Object.entries(defaults ?? {}) as [Setting, unknown][]) {
+ if (!equal(values?.[setting], value)) {
+ failures.push(`G8: \`${label}\` lacks \`${key}\` but keeps ${setting} ${show(values?.[setting])}`);
+ }
+
+ if (equal(offDefaults[setting], value)) {
+ failures.push(
+ `G8 vacuous: \`${label}\` lacks \`${key}\`, but the panel already holds ${setting} ${show(value)}`
+ );
+ }
+ }
+ }
+ }
+
+ expect(failures).toEqual([]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallContract.testing.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallContract.testing.ts
new file mode 100644
index 0000000000..c9e0841951
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallContract.testing.ts
@@ -0,0 +1,61 @@
+/** Read what a compiled graph records, for the recall contracts. */
+
+import type { CompiledGenerateGraph, GenerateSettings } from '@features/generation/contracts';
+
+/** The declared keys of a generated schema type, without its index signature. */
+export type KnownKeys<T> = keyof {
+ [K in keyof T as string extends K ? never : number extends K ? never : K]: T[K];
+};
+
+const RUNTIME_PREFIX = '<runtime:';
+
+/** A value a node computes only when the graph runs, so the record cannot be known when it compiles. */
+export const isRuntimeValue = (value: unknown): value is string =>
+ typeof value === 'string' && value.startsWith(RUNTIME_PREFIX);
+
+/** The type of the node that computes a runtime value; null for a value the record carries as compiled. */
+export const runtimeSourceOf = (value: unknown): string | null =>
+ isRuntimeValue(value) ? value.slice(RUNTIME_PREFIX.length, -1) : null;
+
+/**
+ * The record a compiled graph stores: the metadata node's serialized fields without its node envelope, plus what its
+ * edges carry. The queue fills the prompts and the seed from the batch; any other source is named as a runtime value.
+ * Serializing drops fields a builder set to `undefined`, as the backend never receives them.
+ */
+export const recordOf = (
+ compiled: Pick<
+ CompiledGenerateGraph,
+ 'backendGraph' | 'negativePromptNodeId' | 'positivePromptNodeId' | 'seedNodeId'
+ >,
+ batch: Pick<GenerateSettings, 'negativePrompt' | 'positivePrompt' | 'seed'>
+): Record<string, unknown> => {
+ const { backendGraph } = compiled;
+ const node = Object.values(backendGraph.nodes).find((candidate) => candidate.type === 'core_metadata');
+
+ if (!node) {
+ throw new Error(`${backendGraph.id} records no metadata.`);
+ }
+
+ const {
+ id: _id,
+ is_intermediate: _isIntermediate,
+ type: _type,
+ use_cache: _useCache,
+ ...record
+ } = JSON.parse(JSON.stringify(node)) as Record<string, unknown>;
+ const batchValues: Record<string, unknown> = {
+ [compiled.negativePromptNodeId]: batch.negativePrompt,
+ [compiled.positivePromptNodeId]: batch.positivePrompt,
+ [compiled.seedNodeId]: batch.seed,
+ };
+
+ for (const { destination, source } of backendGraph.edges) {
+ if (destination.node_id === node.id) {
+ record[destination.field] = Object.hasOwn(batchValues, source.node_id)
+ ? batchValues[source.node_id]
+ : `${RUNTIME_PREFIX}${backendGraph.nodes[source.node_id]!.type}>`;
+ }
+ }
+
+ return record;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts
index a5dc738ee7..6d41477bd0 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts
@@ -2,12 +2,9 @@ import type { GenerationModelCatalogItem, MainModelConfig } from '@features/gene
import type { TFunction } from 'i18next';
import {
- compileVideoGraph,
createDefaultVideoWidgetValues,
- getDefaultVideoSettings,
getVideoDimensions,
getVideoValidationReasons,
- type VideoSettings,
type VideoWidgetValues,
} from '@features/video';
import { getVideoPromptPolicy } from '@features/video/core/videoPolicies';
@@ -23,6 +20,7 @@ import {
getVideoSizeRecalls,
parseVideoRecallRecord,
resolveVideoSizeRecall,
+ settleMediaSizedRecall,
} from './videoRecall';
const isVideoGenerationMetadata = (metadata: unknown): boolean =>
@@ -356,6 +354,26 @@ describe('buildVideoRecallSettings', () => {
expect(resolveVideoSizeRecall(withClip('audio'), width, height).outcome).toBe('fits');
expect(resolveVideoSizeRecall(withClip('video'), width, height).outcome).toBe('media-conflict');
});
+
+ it("applies the target resolution at which the panel's media reach the recorded size, keeping their shape", () => {
+ // A 10:7 frame, a ratio no preset has. At 480p it scales by 480 / 700 to 685.7x480, snapped to 688x480 on the
+ // 16-pixel grid; at 720p and 1080p it gives 1024x720 and 1536x1088.
+ const values = { ...wanValues, aspectRatioId: '1:1' as const, firstFrameImage: image(1000, 700) };
+
+ expect(resolveVideoSizeRecall(values, 688, 480)).toEqual({
+ outcome: 'fits',
+ sizeRecall: { targetResolution: '480p' },
+ });
+ expect(recallSize(values, 688, 480)?.values).toEqual({ ...values, targetResolution: '480p' });
+ });
+
+ it('reports no size when the media reach it at no target resolution', () => {
+ // A 16:9 frame gives 848x480, 1280x720 or 1920x1088.
+ const values = { ...wanValues, firstFrameImage: image(1280, 720) };
+
+ expect(resolveVideoSizeRecall(values, 688, 480)).toEqual({ outcome: 'unavailable' });
+ expect(recallSize(values, 688, 480)).toBeNull();
+ });
});
describe('a size recall that would change whether the panel can run', () => {
@@ -404,6 +422,103 @@ describe('buildVideoRecallSettings', () => {
expect(getVideoValidationReasons(ltx2, values)).not.toEqual([]);
expect(recall(values)?.fields).toEqual(['size']);
});
+
+ it('writes nothing when the resolution the held media need is a two-stage one the panel cannot run', () => {
+ // A 10:7 frame at 1024p: a 1024 short edge and a 1462.9 long one, snapped to 1472 on the two-stage 64-pixel
+ // grid. The other resolutions give 736x512, 992x704, 1088x768 and 2176x1536.
+ const values = { ...ltx2Values, firstFrameImage: { height: 700, image_name: 'held.png', width: 1000 }, steps: 1 };
+
+ expect(resolveVideoSizeRecall(values, 1472, 1024)).toEqual({
+ outcome: 'invalid',
+ reason: expect.stringContaining('two-stage target resolution needs at least'),
+ });
+ expect(
+ buildVideoRecallSettings({
+ currentValues: values,
+ kind: 'size',
+ metadata: wanMetadata({ height: 1024, width: 1472 }),
+ models: [ltx2],
+ })
+ ).toBeNull();
+ });
+ });
+
+ describe('a canvas the recorded media sized, settled against them once hydrated', () => {
+ const recallFirstFrame = (
+ currentValues: VideoWidgetValues,
+ record: Record<string, unknown>,
+ hydratedFrame: VideoWidgetValues['firstFrameImage']
+ ) => {
+ const result = buildVideoRecallSettings({ currentValues, kind: 'all', metadata: record, models: catalog })!;
+
+ // The pure recall restores no resolution for it: the recorded canvas lost the media's exact ratio to snapping.
+ expect(result.fields).not.toContain('size');
+
+ return settleMediaSizedRecall({ ...result, values: { ...result.values, firstFrameImage: hydratedFrame } });
+ };
+ const h3Values = { ...createDefaultVideoWidgetValues([h3Model()]), targetResolution: '768 lowres' as const };
+ // 1800x1000 at 768 highres: 1382.4x768 is over the area cap, scaled by 0.986 to 1363.1x757.3, snapped to 1376x768.
+ // Fed back, 1376x768 would give 1344x768; at 768 lowres the frame gives 768x416.
+ const h3Record = {
+ first_frame_image: { image_name: 'first.png' },
+ generation_mode: 'minimax_h3_i2v',
+ height: 768,
+ model: { key: h3Model().key },
+ width: 1376,
+ };
+ const wanValues = createDefaultVideoWidgetValues([WAN_I2V]);
+ // 1000x700 at 1080p: 1542.9x1080, snapped to 1536x1088. Fed back, 1536x1088 would give 1520x1088; 720p and 480p
+ // give the frame 1024x720 and 688x480.
+ const wanRecord = wanMetadata({
+ first_frame_image: { image_name: 'first.png' },
+ generation_mode: 'wan_i2v',
+ height: 1088,
+ model: { key: WAN_I2V.key },
+ width: 1536,
+ });
+ const frame = (width: number, height: number) => ({ height, image_name: 'first.png', width });
+
+ it.each([
+ ['an area-capped H3 canvas', h3Values, h3Record, frame(1800, 1000), '768 highres'],
+ ['a Wan 1080p canvas snapped off its short side', wanValues, wanRecord, frame(1000, 700), '1080p'],
+ ] as const)(
+ 'restores the target resolution of %s from the hydrated media, leaving the aspect ratio to them',
+ (_, currentValues, record, hydratedFrame, targetResolution) => {
+ const settled = recallFirstFrame(currentValues, record, hydratedFrame);
+
+ expect(settled.values).toMatchObject({ aspectRatioId: currentValues.aspectRatioId, targetResolution });
+ expect(settled.fields).toContain('size');
+ }
+ );
+
+ it('leaves the target resolution and reports no size when the media are gone or reach the canvas nowhere', () => {
+ // 1000x700 at 480p is 688x480, a canvas that fed back would give itself: only the missing frame refuses it. A 16:9
+ // frame gives Wan 848x480, 1280x720 or 1920x1088, never 1536x1088.
+ const wan480Record = { ...wanRecord, height: 480, width: 688 };
+
+ for (const [record, hydratedFrame] of [
+ [wan480Record, null],
+ [wanRecord, frame(1280, 720)],
+ ] as const) {
+ const settled = recallFirstFrame(wanValues, record, hydratedFrame);
+
+ expect(settled.values.targetResolution).toBe(wanValues.targetResolution);
+ expect(settled.fields).not.toContain('size');
+ }
+ });
+
+ it('settles nothing for a canvas no medium sized', () => {
+ const result = buildVideoRecallSettings({
+ currentValues: wanValues,
+ kind: 'all',
+ metadata: wanMetadata({ height: 1088, model: { key: WAN_I2V.key }, width: 1536 }),
+ models: catalog,
+ })!;
+
+ expect(
+ settleMediaSizedRecall({ ...result, values: { ...result.values, firstFrameImage: frame(1000, 700) } })
+ ).toEqual({ fields: result.fields, values: { ...result.values, firstFrameImage: frame(1000, 700) } });
+ });
});
it('tells apart no preset from media with no usable frame on the model', () => {
@@ -1553,179 +1668,6 @@ describe('LTX-2 recall', () => {
});
});
-/**
- * The record a compiled graph stores: the metadata node's literal fields plus the values its edges carry, which the
- * queue fills from the batch (prompts and seed) when it runs.
- */
-const recordedMetadata = (settings: VideoSettings, model: MainModelConfig): Record<string, unknown> => {
- const compiled = compileVideoGraph(settings, model);
- const { backendGraph } = compiled;
- const batch: Record<string, unknown> = {
- [compiled.negativePromptNodeId]: settings.negativePrompt,
- [compiled.positivePromptNodeId]: settings.positivePrompt,
- [compiled.seedNodeId]: settings.seed,
- };
- const record: Record<string, unknown> = { ...backendGraph.nodes.core_metadata };
-
- for (const edge of backendGraph.edges) {
- if (edge.destination.node_id === 'core_metadata') {
- expect(batch, `metadata field ${edge.destination.field} comes from the batch`).toHaveProperty(
- edge.source.node_id
- );
- record[edge.destination.field] = batch[edge.source.node_id];
- }
- }
-
- return record;
-};
-
-describe('recall of what the video graphs record', () => {
- it('Wan: restores prompts with the wired negative, seed, sampling, fps and size', () => {
- const model = wanModel('t2v_a14b');
- const settings: VideoSettings = {
- ...getDefaultVideoSettings(model),
- aspectRatioId: '16:9',
- cfgScale: 4,
- fps: 24,
- negativePrompt: 'blurry, low quality',
- negativePromptEnabled: true,
- numFrames: 81,
- positivePrompt: 'a red fox in the snow',
- seed: 4242,
- steps: 20,
- targetResolution: '720p',
- };
- const metadata = recordedMetadata(settings, model);
- const result = buildVideoRecallSettings({
- currentValues: createDefaultVideoWidgetValues([model]),
- kind: 'all',
- metadata,
- models: [model],
- });
-
- expect(getVideoRecallCapabilities(metadata)).toEqual({
- all: true,
- prompts: true,
- remix: true,
- seed: true,
- size: true,
- });
- expect(result?.fields).toEqual(['prompts', 'seed', 'model', 'frames', 'steps', 'cfg', 'fps', 'size']);
- expect(result?.values).toMatchObject({
- aspectRatioId: '16:9',
- cfgScale: 4,
- fps: 24,
- negativePrompt: 'blurry, low quality',
- negativePromptEnabled: true,
- numFrames: 81,
- positivePrompt: 'a red fox in the snow',
- seed: 4242,
- steps: 20,
- targetResolution: '720p',
- });
- });
-
- it('MiniMax H3: restores the ordered references with their trim and conditioning', () => {
- const componentSource = h3Model();
- const model: MainModelConfig = {
- base: 'minimax-h3',
- format: 'checkpoint',
- key: 'h3-ref2va-ckpt',
- name: 'MiniMax H3 Ref2VA Transformer',
- type: 'main',
- variant: 'ref2va',
- };
- const settings: VideoSettings = {
- ...getDefaultVideoSettings(model),
- componentSourceModel: componentSource,
- positivePrompt: 'a dancer',
- references: [
- {
- clip: { endFrame: 47, fps: 24, height: 480, numFrames: 48, startFrame: 2, video_name: 'ref.mp4', width: 832 },
- conditioning: 'video_audio',
- kind: 'video',
- },
- { detail: 'match', image: { height: 512, image_name: 'ref.png', width: 512 }, kind: 'image' },
- ],
- seed: 77,
- };
- const metadata = recordedMetadata(settings, model);
- const result = buildVideoRecallSettings({
- currentValues: createDefaultVideoWidgetValues([componentSource]),
- kind: 'all',
- metadata,
- models: [componentSource, model],
- });
-
- expect(getVideoRecallCapabilities(metadata)).toEqual({
- all: true,
- prompts: true,
- remix: true,
- seed: true,
- size: true,
- });
- expect(result?.fields).toEqual(expect.arrayContaining(['prompts', 'seed', 'model', 'components', 'media']));
- expect(result?.values).toMatchObject({
- componentSourceModel: componentSource,
- model,
- positivePrompt: 'a dancer',
- seed: 77,
- });
- expect(result?.mediaNames.references).toEqual([
- { conditioning: 'video_audio', kind: 'video', name: 'ref.mp4', trim: { endFrame: 47, startFrame: 2 } },
- { detail: 'match', kind: 'image', name: 'ref.png' },
- ]);
- });
-
- it('LTX-2 audio-to-video: restores the soundtrack in its role, the components and the fps', () => {
- const model = ltx2Model('ltx2_dev');
- const encoder: GenerationModelCatalogItem = {
- base: 'ltx-2',
- key: 'gemma4',
- name: 'LTX-2.5 Text Encoder',
- type: 'gemma4_encoder',
- };
- const componentSource = ltx2Model('ltx2_dev', 'diffusers', 'ltx2-components');
- const settings: VideoSettings = {
- ...getDefaultVideoSettings(model),
- componentSourceModel: componentSource,
- conditioningClip: {
- clip: { fps: 24, height: 704, numFrames: 96, video_name: 'song.mp4', width: 1248 },
- fpsKnown: true,
- role: 'audio',
- },
- fps: 25,
- ltx2TextEncoderModel: encoder,
- positivePrompt: 'a singer on stage',
- seed: 99,
- };
- const metadata = recordedMetadata(settings, model);
- const result = buildVideoRecallSettings({
- currentValues: createDefaultVideoWidgetValues([model]),
- kind: 'all',
- metadata,
- models: [model, componentSource, encoder],
- });
-
- expect(getVideoRecallCapabilities(metadata)).toEqual({
- all: true,
- prompts: true,
- remix: true,
- seed: true,
- size: true,
- });
- expect(result?.fields).toEqual(expect.arrayContaining(['prompts', 'seed', 'model', 'fps', 'components', 'media']));
- expect(result?.values).toMatchObject({
- componentSourceModel: componentSource,
- fps: 25,
- ltx2TextEncoderModel: encoder,
- positivePrompt: 'a singer on stage',
- seed: 99,
- });
- expect(result?.mediaNames.conditioningClip).toEqual({ name: 'song.mp4', role: 'audio' });
- });
-});
-
it('reads the legacy Wan VAE slot', () => {
const vae = { key: 'legacy-vae', base: 'wan', name: 'Wan VAE', type: 'vae' };
expect(parseVideoRecallRecord({ generation_mode: 'wan_t2v', wan_vae_model: vae })?.components).toContainEqual({
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts
index 3369ecf17d..1cc1c6a315 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts
@@ -114,6 +114,12 @@ export type VideoRecalledField =
export interface VideoRecallResult {
fields: VideoRecalledField[];
values: VideoWidgetValues;
+ /**
+ * The recorded canvas, when the run's media sized it rather than a preset. Snapping loses the media's exact ratio,
+ * so only the media themselves say which target resolution produced it: `settleMediaSizedRecall` decides once the
+ * executor has hydrated them.
+ */
+ mediaSizedCanvas?: { height: number; width: number };
}
const isRecord = (value: unknown): value is Record<string, unknown> =>
@@ -422,9 +428,15 @@ interface VideoSizePreset {
targetResolution: VideoTargetResolution;
}
+/** What a size recall writes: a preset, or only its resolution where conditioning media keep the frame's shape. */
+type VideoSizeRecall = VideoSizePreset | Pick<VideoSizePreset, 'targetResolution'>;
+
/**
- * Recall aspect/resolution presets only on exact dimension matches; other dimensions came from conditioning media
- * and remain media-controlled. Returns every match: presets that agree without media can differ under held media.
+ * The presets whose canvas is exactly the recorded size; a recall restores aspect ratio and resolution only on such a
+ * match. A canvas sized by conditioning media has the media's shape rather than a preset's: the media keep the aspect
+ * ratio, and only the target resolution at which they reproduce the canvas is recalled, judged against the media
+ * themselves (`settleMediaSizedRecall`, `resolveVideoSizeRecall`). Returns every match: presets that agree without
+ * media can differ under held media.
*/
export const getVideoSizeRecalls = (
model: MainModelConfig,
@@ -457,20 +469,47 @@ export const getVideoSizeRecalls = (
return recalls;
};
+/** The one target resolution at which `media` size the canvas to exactly `width` x `height`; null when none or several do. */
+const getMediaSizedResolution = (
+ model: MainModelConfig,
+ media: Pick<
+ VideoWidgetValues,
+ 'aspectRatioId' | 'conditioningClip' | 'firstFrameImage' | 'lastFrameImage' | 'sourceVideo'
+ >,
+ width: number,
+ height: number
+): Pick<VideoSizePreset, 'targetResolution'> | null => {
+ const [match, ...others] = getVideoTargetResolutionOptions(model).filter((option) => {
+ const canvas = getVideoDimensions(model, { ...media, targetResolution: option.id });
+
+ return canvas?.width === width && canvas.height === height;
+ });
+
+ return match && others.length === 0 ? { targetResolution: match.id } : null;
+};
+
+/** Whether a frame, the source video or a clip's picture sized the recorded canvas, rather than a preset. */
+const isCanvasFromRecordedMedia = ({ conditioningClip, media }: VideoRecallRecord): boolean =>
+ isConditioningClipExcludingFrames(conditioningClip) ||
+ media.firstFrameName !== null ||
+ media.lastFrameName !== null ||
+ media.sourceVideoName !== null;
+
export type VideoSizeRecallFit =
- /** No model, or no preset of it reproduces the size. */
+ /** No model, or neither a preset nor the panel's media at one of its target resolutions reproduces the size. */
| { outcome: 'unavailable' }
/** A preset fits, but the panel's media has no usable frame on this model. */
| { outcome: 'media-unresolvable' }
/** The panel's media owns the frame, and the run would get this size instead. */
| { outcome: 'media-conflict'; effective: { height: number; width: number } }
- /** The preset would leave the panel unable to run, for this reason it did not already have. */
+ /** The size recall would leave the panel unable to run, for this reason it did not already have. */
| { outcome: 'invalid'; reason: string }
- | { outcome: 'fits'; sizeRecall: VideoSizePreset };
+ | { outcome: 'fits'; sizeRecall: VideoSizeRecall };
/**
* Whether a recorded size can be applied to the panel as it stands, shared by the recall and its failure notice. The
- * first preset that fits wins; if none does, the first preset's failure is reported.
+ * first preset that fits wins, then the one target resolution at which the panel's own media reach the size; if
+ * neither does, the first preset's failure is reported.
*/
export const resolveVideoSizeRecall = (
values: VideoWidgetValues,
@@ -484,7 +523,7 @@ export const resolveVideoSizeRecall = (
}
const existingReasons = new Set(getVideoValidationReasons(model, values));
- const fits = getVideoSizeRecalls(model, width, height).map((sizeRecall): VideoSizeRecallFit => {
+ const fit = (sizeRecall: VideoSizeRecall): VideoSizeRecallFit => {
const next = { ...values, ...sizeRecall };
const effective = getVideoDimensions(model, next);
@@ -498,9 +537,21 @@ export const resolveVideoSizeRecall = (
const reason = getVideoValidationReasons(model, next).find((candidate) => !existingReasons.has(candidate));
return reason ? { outcome: 'invalid', reason } : { outcome: 'fits', sizeRecall };
- });
+ };
+ const presetFits = getVideoSizeRecalls(model, width, height).map(fit);
+ const presetFit = presetFits.find((candidate) => candidate.outcome === 'fits');
- return fits.find((fit) => fit.outcome === 'fits') ?? fits[0] ?? { outcome: 'unavailable' };
+ if (presetFit) {
+ return presetFit;
+ }
+
+ const panelCanvas = getVideoDimensions(model, values);
+ const mediaSized =
+ width !== null && height !== null && panelCanvas && panelCanvas.source !== 'aspect-ratio'
+ ? getMediaSizedResolution(model, values, width, height)
+ : null;
+
+ return (mediaSized ? fit(mediaSized) : presetFits[0]) ?? { outcome: 'unavailable' };
};
/**
@@ -799,7 +850,10 @@ export const buildVideoRecallSettings = ({
fields.push('fps');
}
- const [sizeRecall] = getVideoSizeRecalls(model, record.width, record.height);
+ const { height, width } = record;
+ const [sizeRecall] = getVideoSizeRecalls(model, width, height);
+ const mediaSizedCanvas =
+ !sizeRecall && width !== null && height !== null && isCanvasFromRecordedMedia(record) ? { height, width } : null;
if (sizeRecall) {
values = { ...values, ...sizeRecall };
@@ -967,7 +1021,31 @@ export const buildVideoRecallSettings = ({
fields.push('extendContext');
}
- return fields.length > 0 ? { fields, mediaNames, values: { ...values, ...promptPatch } } : null;
+ return fields.length > 0
+ ? { fields, mediaNames, ...(mediaSizedCanvas ? { mediaSizedCanvas } : {}), values: { ...values, ...promptPatch } }
+ : null;
+};
+
+/**
+ * A recall whose canvas its media sized, settled against those media as hydrated into the panel: the target
+ * resolution is restored only when they reproduce the recorded canvas at exactly one. Media that did not hydrate, or
+ * reach the canvas at no resolution, leave the panel's resolution, and the size goes unreported.
+ */
+export const settleMediaSizedRecall = ({
+ fields,
+ mediaSizedCanvas,
+ values,
+}: VideoRecallResult): Pick<VideoRecallResult, 'fields' | 'values'> => {
+ const { model } = values;
+ const panelCanvas = model ? getVideoDimensions(model, values) : null;
+ const sized =
+ model && mediaSizedCanvas && panelCanvas && panelCanvas.source !== 'aspect-ratio'
+ ? getMediaSizedResolution(model, values, mediaSizedCanvas.width, mediaSizedCanvas.height)
+ : null;
+
+ return sized
+ ? { fields: fields.includes('size') ? fields : [...fields, 'size'], values: { ...values, ...sized } }
+ : { fields, values };
};
export const getVideoRecallTitle = (kind: VideoRecallKind, t: TFunction): string =>
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallContract.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallContract.test.ts
new file mode 100644
index 0000000000..31b372d337
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallContract.test.ts
@@ -0,0 +1,820 @@
+/**
+ * Every key a video graph writes into its metadata node is accounted for here: recall restores it, or it is
+ * deliberately inert. The video twin of `imageRecallContract.test.ts`.
+ *
+ * The cases are the registry-driven matrix `videoGraphCoverage.test.ts` compiles -- every base, variant, mode, model
+ * shape and multi-stage preset, with and without auto duration -- each run with every recallable value tuned away
+ * from its default and every component slot filled, so each key a builder can write is written. A key with no entry
+ * in `VIDEO_RECALL_CONTRACT` fails G1, so a new parameter cannot reach a record untested:
+ *
+ * - `restores`: a full recall puts the value back (G2), and only through this key: recalling the record without it
+ * must land somewhere else, or the round trip proves nothing. `when` is false on runs recall deliberately leaves
+ * the value alone on, and G3 then holds the key inert there.
+ * - `media`: recall names the medium for the executor to hydrate from the gallery (G2, against `mediaNames`).
+ * - `ignored`: recall applies nothing from it; recalling the record without it changes nothing (G3).
+ * - `consumed`: read to interpret the record rather than restored, so it cannot be ablated.
+ *
+ * A value only the run produces arrives over an edge; it is recorded as `<runtime:…>` and classified in
+ * `VIDEO_RUNTIME_CONTRACT` by key and source node type.
+ */
+
+import type {
+ GenerateLora,
+ GenerationModelCatalogItem as ModelConfig,
+ LoraModelConfig,
+ MainModelConfig,
+} from '@features/generation/contracts';
+import type {
+ VideoComponentSlotPolicy,
+ VideoGenerationMode,
+ VideoModelPolicy,
+ VideoReferenceItem,
+ VideoSettings,
+ VideoSourceClip,
+ VideoWidgetValues,
+} from '@features/video';
+import type { Case } from '@features/video/core/videoGraphCoverage.testing';
+import type { TFunction } from 'i18next';
+
+import {
+ compileVideoGraph,
+ createDefaultVideoWidgetValues,
+ getDefaultVideoSettings,
+ getVideoComponentSectionPolicy,
+ getVideoDimensions,
+ getVideoModelPolicy,
+ getVideoValidationReasons,
+ resolveVideoMode,
+} from '@features/video';
+import {
+ AUTO_DURATION_CASES,
+ candidatesForSlot,
+ cases,
+ createModel,
+ DURATION_HEAD,
+} from '@features/video/core/videoGraphCoverage.testing';
+import i18n from 'i18next';
+import { beforeAll, describe, expect, it } from 'vitest';
+
+import type {
+ VideoRecalledField,
+ VideoRecallKind,
+ VideoRecallMediaNames,
+ VideoRecallReferenceName,
+} from './videoRecall';
+
+import { recordOf, runtimeSourceOf } from './recallContract.testing';
+import {
+ buildVideoRecallSettings,
+ getVideoRecallCapabilities,
+ getVideoRecallMessage,
+ getVideoRecallTitle,
+ getVideoSizeRecalls,
+ parseVideoRecallRecord,
+ settleMediaSizedRecall,
+} from './videoRecall';
+
+/** What a contract entry may consult: the recorded run, as tuned, and what its graph wrote. */
+interface RecordedRun {
+ model: MainModelConfig;
+ /** The tuned run's own policy, with its accelerator off as every tuned run has it. */
+ policy: VideoModelPolicy;
+ tuned: VideoWidgetValues;
+ written: Record<string, unknown>;
+}
+
+type WidgetValueKeys = readonly (keyof VideoWidgetValues)[];
+
+interface RestoresEntry {
+ /** The values it puts back; per run where what it restores depends on the run. */
+ restores: WidgetValueKeys | ((run: RecordedRun) => WidgetValueKeys);
+ /** The field the recall notice names for it. */
+ reports: VideoRecalledField;
+ /** The recall verbs that apply it; all and remix when absent. */
+ kinds?: readonly VideoRecallKind[];
+ /** False for a run recall deliberately leaves the value alone on; G3 then holds the key inert. */
+ when?: (run: RecordedRun) => boolean;
+ /** The restored value where it is the run's rather than the panel's (a rate or length taken from media). */
+ expected?: (run: RecordedRun) => Partial<VideoWidgetValues>;
+ /** What a full recall of a record without the key leaves on a panel holding `panel`: the run did not use one. */
+ absent?: { panel: Partial<VideoWidgetValues>; restored: Partial<VideoWidgetValues> };
+}
+
+interface MediaEntry {
+ media: (run: RecordedRun) => Partial<VideoRecallMediaNames>;
+}
+
+type ReasonEntry = { consumed: string } | { ignored: string };
+type Entry = RestoresEntry | MediaEntry | ReasonEntry;
+
+const PANEL_LORA: LoraModelConfig = { base: 'wan', key: 'panel-lora', name: 'Panel style LoRA', type: 'lora' };
+const PANEL_HYBRID_BASE: MainModelConfig = {
+ base: 'minimax-h3',
+ format: 'checkpoint',
+ key: 'panel-h3-fl2va',
+ name: 'Panel H3 FL2VA transformer',
+ type: 'main',
+ variant: 'fl2va',
+};
+
+const PROMPT_KINDS = ['all', 'remix', 'prompts'] as const;
+
+// A canvas conditioning media sized keeps their shape, so its aspect ratio stays theirs and only the target resolution
+// that sized it comes back.
+const SIZE: RestoresEntry = {
+ kinds: ['all', 'remix', 'size'],
+ reports: 'size',
+ restores: ({ model, tuned }) =>
+ getVideoDimensions(model, tuned)?.source === 'aspect-ratio'
+ ? ['aspectRatioId', 'targetResolution']
+ : ['targetResolution'],
+};
+
+const SOURCE_TRIM: MediaEntry = {
+ media: ({ tuned }) => ({
+ sourceVideoTrim: { endFrame: tuned.sourceVideo!.endFrame, startFrame: tuned.sourceVideo!.startFrame },
+ }),
+};
+
+const CONDITIONING_CLIP: MediaEntry = {
+ media: ({ tuned }) => ({
+ conditioningClip: { name: tuned.conditioningClip!.clip.video_name, role: tuned.conditioningClip!.role },
+ }),
+};
+
+const toReferenceName = (reference: VideoReferenceItem): VideoRecallReferenceName =>
+ reference.kind === 'image'
+ ? { detail: reference.detail, kind: 'image', name: reference.image.image_name }
+ : {
+ conditioning: reference.conditioning,
+ kind: 'video',
+ name: reference.clip.video_name,
+ trim: { endFrame: reference.clip.endFrame, startFrame: reference.clip.startFrame },
+ };
+
+const VIDEO_RECALL_CONTRACT: Readonly<Record<string, Entry>> = {
+ cfg_scale: { reports: 'cfg', restores: ['cfgScale'], when: ({ policy }) => policy.ui.cfgVisible },
+ first_frame_image: { media: ({ tuned }) => ({ firstFrameName: tuned.firstFrameImage!.image_name }) },
+ // The delivered rate: an extension inherits its source's, and a picture-role clip its own.
+ fps: {
+ expected: ({ written }) => ({ fps: written.fps as number }),
+ reports: 'fps',
+ restores: ['fps'],
+ when: ({ policy }) => policy.fps.editable,
+ },
+ generation_mode: {
+ consumed:
+ 'The record discriminator: only a mode the video graphs stamp makes the record recallable at all, and only an ' +
+ 'H3 one lets a legacy duration count as frames. Without it nothing is recalled, so it cannot be ablated.',
+ },
+ height: SIZE,
+ last_frame_image: { media: ({ tuned }) => ({ lastFrameName: tuned.lastFrameImage!.image_name }) },
+ loras: {
+ absent: { panel: { loras: [{ isEnabled: true, model: PANEL_LORA, weight: 1 }] }, restored: { loras: [] } },
+ reports: 'loras',
+ restores: ['loras'],
+ },
+ ltx2_audio_cfg_scale: { reports: 'cfg', restores: ['audioCfgScale'] },
+ ltx2_base_height: {
+ ignored: "Informational: a two-stage run's base pass is half its canvas, and recall recovers the preset from it.",
+ },
+ ltx2_base_width: {
+ ignored: "Informational: a two-stage run's base pass is half its canvas, and recall recovers the preset from it.",
+ },
+ ltx2_component_source: { reports: 'components', restores: ['componentSourceModel'] },
+ ltx2_conditioning_role: CONDITIONING_CLIP,
+ ltx2_conditioning_video: CONDITIONING_CLIP,
+ ltx2_context_frames: { reports: 'extendContext', restores: ['ltx2ExtendContextFrames'] },
+ ltx2_modality_scale: { reports: 'cfg', restores: ['modalityScale'] },
+ ltx2_stg_scale: { reports: 'cfg', restores: ['stgScale'] },
+ ltx2_text_encoder_model: { reports: 'components', restores: ['ltx2TextEncoderModel'] },
+ ltx2_two_stage: { ignored: 'Informational: the preset recall recovers from the canvas states its stage count.' },
+ minimax_h3_component_source: { reports: 'components', restores: ['componentSourceModel'] },
+ minimax_h3_hybrid_base_model: {
+ absent: { panel: { h3HybridBaseModel: PANEL_HYBRID_BASE }, restored: { h3HybridBaseModel: null } },
+ reports: 'components',
+ restores: ['h3HybridBaseModel'],
+ },
+ minimax_h3_hybrid_start_block: { reports: 'components', restores: ['h3HybridStartBlock'] },
+ minimax_h3_references: { media: ({ tuned }) => ({ references: tuned.references.map(toReferenceName) }) },
+ minimax_h3_text_encoder_model: { reports: 'components', restores: ['h3TextEncoderModel'] },
+ model: { reports: 'model', restores: ['model', 'modelKey'] },
+ negative_prompt: { kinds: PROMPT_KINDS, reports: 'prompts', restores: ['negativePrompt', 'negativePromptEnabled'] },
+ // The length that ran: a conditioning clip decides it rather than the panel's stored count.
+ num_frames: {
+ expected: ({ written }) => ({ numFrames: written.num_frames as number }),
+ reports: 'frames',
+ restores: ['numFrames'],
+ },
+ positive_prompt: { kinds: PROMPT_KINDS, reports: 'prompts', restores: ['positivePrompt'] },
+ seed: { kinds: ['all', 'seed'], reports: 'seed', restores: ['seed', 'seedMode'] },
+ source_video: { media: ({ tuned }) => ({ sourceVideoName: tuned.sourceVideo!.video_name }) },
+ source_video_end_frame: SOURCE_TRIM,
+ source_video_start_frame: SOURCE_TRIM,
+ steps: { reports: 'steps', restores: ['steps'], when: ({ policy }) => policy.ui.stepsEditable },
+ vae: { reports: 'components', restores: ['vae'] },
+ wan_component_source: { reports: 'components', restores: ['componentSourceModel'] },
+ wan_guidance_scale_low_noise: {
+ absent: { panel: { cfgScaleLowNoise: 2 }, restored: { cfgScaleLowNoise: null } },
+ reports: 'cfg',
+ restores: ['cfgScaleLowNoise'],
+ },
+ wan_t5_encoder_model: { reports: 'components', restores: ['wanT5EncoderModel'] },
+ wan_transformer_low_noise: { reports: 'components', restores: ['wanLowNoiseModel'] },
+ width: SIZE,
+};
+
+/** Keyed `<metadata key> <- <source node type>`. */
+const VIDEO_RUNTIME_CONTRACT: Readonly<Record<string, ReasonEntry>> = {
+ 'first_frame_image <- video_frame_extract': {
+ ignored:
+ "An extension conditions on its source's last frame, extracted when the run executes; recall restores the " +
+ 'source instead and drops a first frame recorded beside it.',
+ },
+ 'num_frames <- ltx2_duration': {
+ consumed:
+ 'The length the duration head chose, known once the run executes. A real record carries it as an integer, ' +
+ 'which recall restores like any recorded length and turns Auto duration off (videoRecall.test.ts).',
+ },
+};
+
+/**
+ * Keys only older records carry, still read so those recall; no graph writes them, and each has an old-record test
+ * in videoRecall.test.ts. With a value each reads, so a reader that stops reading one shows here as a stale entry.
+ */
+const LEGACY_READ_ONLY_KEYS: Readonly<Record<string, unknown>> = {
+ guidance_scale_low_noise: 3,
+ minimax_h3_duration_seconds: 10,
+ minimax_h3_transformer_model: { key: 'h3-transformer' },
+ transformer_low_noise: { key: 'wan-low-noise' },
+ wan_t5_encoder: { key: 'umt5' },
+ wan_vae_model: { key: 'wan-vae' },
+};
+
+/** Type-exhaustive: a new `VideoRecalledField` fails to compile until it is listed, and so has to be reported. */
+const VIDEO_RECALLED_FIELDS = Object.keys({
+ cfg: true,
+ components: true,
+ extendContext: true,
+ fps: true,
+ frames: true,
+ loras: true,
+ media: true,
+ model: true,
+ prompts: true,
+ seed: true,
+ size: true,
+ steps: true,
+} satisfies Record<VideoRecalledField, true>) as VideoRecalledField[];
+
+const VIDEO_RECALL_KINDS = Object.keys({
+ all: true,
+ prompts: true,
+ remix: true,
+ seed: true,
+ size: true,
+} satisfies Record<VideoRecallKind, true>) as VideoRecallKind[];
+
+const DEFAULT_KINDS: readonly VideoRecallKind[] = ['all', 'remix'];
+
+// Distinct names per slot so a swapped slot cannot pass; a 10:7 ratio, which no preset has and no canvas keeps once
+// snapped, so a media-sized canvas is never also a preset's and only the media say which resolution sized it; and trims
+// inside the clips, so a trim is a recorded choice and not the clip's own bounds.
+const FIRST_FRAME = { height: 700, image_name: 'first.png', width: 1000 };
+const LAST_FRAME = { height: 700, image_name: 'last.png', width: 1000 };
+const SOURCE_VIDEO: VideoSourceClip = {
+ endFrame: 43,
+ fps: 30,
+ height: 700,
+ numFrames: 120,
+ startFrame: 4,
+ video_name: 'source.mp4',
+ width: 1000,
+};
+const CONDITIONING_VIDEO = { fps: 30, height: 700, numFrames: 120, video_name: 'conditioning.mp4', width: 1000 };
+
+/** The conditioning each mode needs, as `MODE_INPUTS` in the coverage fixture gives it, with recallable choices made. */
+const TUNED_MEDIA: Record<VideoGenerationMode, Partial<VideoSettings>> = {
+ 'audio-to-video': { conditioningClip: { clip: CONDITIONING_VIDEO, fpsKnown: true, role: 'audio' } },
+ extend: { sourceVideo: SOURCE_VIDEO },
+ 'first-frame': { firstFrameImage: FIRST_FRAME },
+ 'first-last': { firstFrameImage: FIRST_FRAME, lastFrameImage: LAST_FRAME },
+ 'last-frame': { lastFrameImage: LAST_FRAME },
+ reference: {
+ references: [
+ {
+ clip: {
+ endFrame: 50,
+ fps: 24,
+ height: 480,
+ numFrames: 96,
+ startFrame: 3,
+ video_name: 'reference.mp4',
+ width: 832,
+ },
+ conditioning: 'video',
+ kind: 'video',
+ },
+ { detail: 'match', image: { height: 600, image_name: 'reference.png', width: 800 }, kind: 'image' },
+ ],
+ },
+ txt2vid: {},
+ 'video-to-audio': { conditioningClip: { clip: CONDITIONING_VIDEO, fpsKnown: true, role: 'video' } },
+};
+
+const PANEL_MODEL: MainModelConfig = {
+ base: 'wan',
+ format: 'diffusers',
+ key: 'panel-wan-i2v',
+ name: 'Panel Wan I2V',
+ type: 'main',
+ variant: 'i2v_a14b',
+};
+
+/**
+ * The panel a recall lands on: another model's, holding a first frame, a LoRA, a prompt and a switched-off negative
+ * prompt, so that replacing, clearing and switching on each of them is observable. The seed is fixed for a
+ * deterministic run; its mode stays random, so a recalled seed fixing it shows.
+ */
+const PANEL: VideoWidgetValues = {
+ ...createDefaultVideoWidgetValues([PANEL_MODEL]),
+ firstFrameImage: { height: 720, image_name: 'panel-frame.png', width: 1280 },
+ loras: [{ isEnabled: true, model: PANEL_LORA, weight: 1 }],
+ negativePrompt: 'panel negative',
+ negativePromptEnabled: false,
+ positivePrompt: 'panel prompt',
+ seed: 7,
+};
+
+/** A panel already on the recorded model, which a size recall fits itself to. */
+const panelOn = (model: MainModelConfig): VideoWidgetValues => ({
+ ...createDefaultVideoWidgetValues([model]),
+ seed: 7,
+});
+
+/**
+ * Installed alternatives the model transition takes for an empty required slot, listed first so its pick is never the
+ * recorded component: otherwise recall would land on that component without reading its key.
+ */
+const DECOYS: ModelConfig[] = [
+ { base: 'minimax-h3', format: 'diffusers', key: 'decoy-h3', name: 'Decoy H3', type: 'main', variant: 'fl2va' },
+ {
+ base: 'ltx-2',
+ format: 'diffusers',
+ key: 'decoy-ltx2-components',
+ name: 'Decoy LTX-2 components',
+ type: 'main',
+ variant: 'ltx2_dev',
+ },
+ { base: 'ltx-2', key: 'decoy-gemma4', name: 'Decoy Gemma-4 encoder', type: 'gemma4_encoder' },
+];
+
+/** A concept every family loads, at a weight other than the default; named so no accelerator claims it. */
+const tunedLora = (model: MainModelConfig): GenerateLora => ({
+ isEnabled: true,
+ model: { base: model.base, key: `tuned-lora-${model.base}`, name: 'Contract style LoRA', type: 'lora' },
+ weight: 0.75,
+});
+
+/**
+ * A main slot is offered both shapes: a component source takes a folder, but the low-noise expert and the hybrid
+ * base take a single file, which the coverage pool -- it fills only required slots -- never needs.
+ */
+const componentCandidates = (slot: VideoComponentSlotPolicy): ModelConfig[] =>
+ candidatesForSlot(slot).flatMap((candidate) =>
+ slot.valueKind === 'main'
+ ? [candidate, { ...candidate, format: 'checkpoint', key: `${candidate.key}-single-file` }]
+ : [candidate]
+ );
+
+/** Every slot the model offers, optional ones included: an empty slot leaves its metadata key unwritten. */
+const fillEveryComponentSlot = (model: MainModelConfig, settings: VideoSettings, label: string): VideoSettings => {
+ const { slots } = getVideoComponentSectionPolicy(model, settings);
+ let filled = settings;
+
+ for (const slot of slots) {
+ const context = { model, selectedComponents: filled, settings: filled };
+ const candidate =
+ filled[slot.key] ?? componentCandidates(slot).find((c) => !slot.filter || slot.filter(c, context));
+
+ filled = { ...filled, [slot.key]: (candidate ?? null) as never };
+ }
+
+ expect(
+ slots.filter((slot) => !filled[slot.key]).map((slot) => slot.key),
+ `${label}: no candidate fills these slots`
+ ).toEqual([]);
+
+ return filled;
+};
+
+const tunedValuesFor = (testCase: Case, model: MainModelConfig): VideoWidgetValues => {
+ const conditioned: VideoSettings = {
+ ...getDefaultVideoSettings(model),
+ ...TUNED_MEDIA[testCase.mode],
+ ...(testCase.autoDuration ? { autoDuration: true, ltx2DurationHeadModel: DURATION_HEAD as never } : {}),
+ };
+ const { defaults, fps, frames, targetResolutions, ui } = getVideoModelPolicy(model, conditioned);
+ const nudged = (visible: boolean, value: number | null, fallback: number | null) =>
+ visible && value !== null ? value + 0.5 : fallback;
+ const tuned: VideoSettings = {
+ ...fillEveryComponentSlot(model, conditioned, testCase.label),
+ // The panel runs 16:9.
+ aspectRatioId: '9:16',
+ audioCfgScale: nudged(ui.audioCfgVisible, defaults.audioCfgScale, conditioned.audioCfgScale),
+ cfgScale: ui.cfgVisible ? defaults.cfgScale + 0.5 : conditioned.cfgScale,
+ cfgScaleLowNoise: nudged(ui.cfgLowNoiseVisible, defaults.cfgScaleLowNoise, conditioned.cfgScaleLowNoise),
+ fps: fps.editable ? fps.defaultValue + 1 : conditioned.fps,
+ h3HybridStartBlock: conditioned.h3HybridStartBlock + 5,
+ loras: [tunedLora(model)],
+ ltx2ExtendContextFrames: ui.extendContext
+ ? ui.extendContext.value + ui.extendContext.step
+ : conditioned.ltx2ExtendContextFrames,
+ modalityScale: nudged(ui.modalityVisible, defaults.modalityScale, conditioned.modalityScale),
+ // Non-empty: an empty recorded negative prompt deliberately leaves the panel's own.
+ negativePrompt: 'tuned negative',
+ negativePromptEnabled: true,
+ numFrames:
+ frames.kind === 'grid'
+ ? frames.defaultValue + frames.step
+ : frames.choices[frames.choices.indexOf(frames.defaultValue) + 1]!,
+ positivePrompt: 'tuned prompt',
+ seed: 4242,
+ seedMode: 'fixed',
+ stgScale: nudged(ui.stgVisible, defaults.stgScale, conditioned.stgScale),
+ steps: ui.stepsEditable ? defaults.steps + 1 : conditioned.steps,
+ // The last single-stage resolution besides the default: on Wan the extrapolated 1080p, whose short side snaps off
+ // the grid, so a media-sized canvas there cannot be resolved from its own shape.
+ targetResolution:
+ testCase.targetResolution ??
+ targetResolutions
+ .filter((option) => option.id !== defaults.targetResolution && option.stages === undefined)
+ .at(-1)!.id,
+ };
+
+ expect(resolveVideoMode(tuned), `${testCase.label}: the tuned media resolve to another mode`).toBe(testCase.mode);
+ expect(getVideoValidationReasons(model, tuned), `${testCase.label}: the tuned run is not satisfiable`).toEqual([]);
+
+ return { ...tuned, model };
+};
+
+interface RecordedCase extends RecordedRun {
+ catalog: readonly ModelConfig[];
+ label: string;
+ runtimeSources: Record<string, string>;
+}
+
+const recordedCases = new Map<string, RecordedCase>();
+
+const recorded = (testCase: Case): RecordedCase => {
+ const cached = recordedCases.get(testCase.label);
+
+ if (cached) {
+ return cached;
+ }
+
+ const model = createModel(testCase);
+ const tuned = tunedValuesFor(testCase, model);
+ const record = recordOf(compileVideoGraph(tuned, model), tuned);
+ const runtimeSources = Object.fromEntries(
+ Object.entries(record).flatMap(([key, value]) => {
+ const source = runtimeSourceOf(value);
+
+ return source === null ? [] : [[key, source]];
+ })
+ );
+
+ if (getVideoDimensions(model, tuned)?.source !== 'aspect-ratio') {
+ // A media-sized canvas that is also a preset's recalls as that preset, which would hide whether recall recovers
+ // the target resolution from the media's shape.
+ expect(
+ getVideoSizeRecalls(model, record.width as number, record.height as number),
+ `${testCase.label}: the media-sized canvas is also a preset's`
+ ).toEqual([]);
+ }
+
+ const components = getVideoComponentSectionPolicy(model, tuned).slots.flatMap((slot) =>
+ tuned[slot.key] ? [tuned[slot.key] as ModelConfig] : []
+ );
+ const recordedCase: RecordedCase = {
+ catalog: [...DECOYS, PANEL_MODEL, model, ...components, ...tuned.loras.map((lora) => lora.model)],
+ label: testCase.label,
+ model,
+ policy: getVideoModelPolicy(model, tuned),
+ runtimeSources,
+ tuned,
+ written: record,
+ };
+
+ recordedCases.set(testCase.label, recordedCase);
+
+ return recordedCase;
+};
+
+const build = (
+ run: RecordedCase,
+ kind: VideoRecallKind,
+ metadata: Record<string, unknown> = run.written,
+ currentValues: VideoWidgetValues = PANEL
+) => buildVideoRecallSettings({ currentValues, kind, metadata, models: run.catalog });
+
+/**
+ * A recall as the executor applies it: a full one hydrates the media it names -- here the run's own, as the gallery
+ * returns them -- and then settles a media-sized canvas's target resolution against them.
+ */
+const recall = (...args: Parameters<typeof build>) => {
+ const [run, kind] = args;
+ const result = build(...args);
+
+ if (!result || (kind !== 'all' && kind !== 'remix')) {
+ return result;
+ }
+
+ const { mediaNames, values } = result;
+ const hydrated: VideoWidgetValues = {
+ ...values,
+ conditioningClip: mediaNames.conditioningClip ? run.tuned.conditioningClip : values.conditioningClip,
+ firstFrameImage: mediaNames.firstFrameName ? run.tuned.firstFrameImage : values.firstFrameImage,
+ lastFrameImage: mediaNames.lastFrameName ? run.tuned.lastFrameImage : values.lastFrameImage,
+ references: mediaNames.references.length > 0 ? run.tuned.references : values.references,
+ sourceVideo: mediaNames.sourceVideoName ? run.tuned.sourceVideo : values.sourceVideo,
+ };
+
+ return { ...result, ...settleMediaSizedRecall({ ...result, values: hydrated }) };
+};
+
+const without = (record: Record<string, unknown>, key: string): Record<string, unknown> => {
+ const { [key]: _removed, ...rest } = record;
+
+ return rest;
+};
+
+const pick = <T extends object, K extends keyof T>(source: T, keys: readonly K[]): Pick<T, K> =>
+ Object.fromEntries(keys.map((key) => [key, source[key]])) as Pick<T, K>;
+
+const lookup = <T>(table: Readonly<Record<string, T>>, key: string): T | undefined =>
+ Object.hasOwn(table, key) ? table[key] : undefined;
+
+/** The contract key a recorded value is classified under: a value wired in at run time is classified with its source. */
+const contractKeyOf = (run: RecordedCase, key: string): string =>
+ run.runtimeSources[key] === undefined ? key : `${key} <- ${run.runtimeSources[key]}`;
+
+const entryOf = (run: RecordedCase, key: string): Entry | undefined =>
+ run.runtimeSources[key] === undefined
+ ? lookup(VIDEO_RECALL_CONTRACT, key)
+ : lookup(VIDEO_RUNTIME_CONTRACT, contractKeyOf(run, key));
+
+/** Each recorded key with the entry governing it; G1 reports the keys without one. */
+const entriesOf = (run: RecordedCase): [string, Entry][] =>
+ Object.keys(run.written).flatMap((key): [string, Entry][] => {
+ const entry = entryOf(run, key);
+
+ return entry ? [[key, entry]] : [];
+ });
+
+const isRestoring = (entry: Entry, run: RecordedRun): entry is RestoresEntry =>
+ 'restores' in entry && (entry.when?.(run) ?? true);
+
+const restoredOn = (entry: RestoresEntry, run: RecordedRun): WidgetValueKeys =>
+ typeof entry.restores === 'function' ? entry.restores(run) : entry.restores;
+
+const expectedValues = (entry: RestoresEntry, run: RecordedRun): Partial<VideoWidgetValues> => ({
+ ...pick(run.tuned, restoredOn(entry, run)),
+ ...entry.expected?.(run),
+});
+
+/** The values the verb applies from this record: those of every entry restored on this run that the verb carries. */
+const patchFor = (run: RecordedCase, kind: VideoRecallKind): Partial<VideoWidgetValues> =>
+ Object.assign(
+ {},
+ ...entriesOf(run).flatMap(([, entry]) =>
+ isRestoring(entry, run) && (entry.kinds ?? DEFAULT_KINDS).includes(kind) ? [expectedValues(entry, run)] : []
+ )
+ );
+
+const NO_MEDIA_NAMES: VideoRecallMediaNames = {
+ conditioningClip: null,
+ firstFrameName: null,
+ lastFrameName: null,
+ references: [],
+ sourceVideoName: null,
+ sourceVideoTrim: null,
+};
+
+const ALL_CASES = [...cases, ...AUTO_DURATION_CASES];
+
+describe('video recall contract', () => {
+ it.each(ALL_CASES)('G1 gives every key $label records a contract entry', (testCase) => {
+ const run = recorded(testCase);
+ const unaccounted = Object.keys(run.written).flatMap((key) =>
+ entryOf(run, key)
+ ? []
+ : [
+ `\`${contractKeyOf(run, key)}\` has no entry in ${
+ run.runtimeSources[key] === undefined ? 'VIDEO_RECALL_CONTRACT' : 'VIDEO_RUNTIME_CONTRACT'
+ }`,
+ ]
+ );
+
+ expect(unaccounted, `G1 ${testCase.label}`).toEqual([]);
+ });
+
+ it.each(ALL_CASES)('G2 restores every recorded value of $label, each through its own key', (testCase) => {
+ const run = recorded(testCase);
+ const result = recall(run, 'all');
+ const expectedMedia = { ...NO_MEDIA_NAMES };
+
+ expect(result, `G2 ${testCase.label}: nothing recalled`).not.toBeNull();
+
+ for (const [key, entry] of entriesOf(run)) {
+ if ('media' in entry) {
+ const ablated = recall(run, 'all', without(run.written, key));
+ const media = entry.media(run);
+
+ Object.assign(expectedMedia, media);
+ for (const field of Object.keys(media) as (keyof VideoRecallMediaNames)[]) {
+ expect(result?.mediaNames[field], `G2 ${testCase.label}: \`${key}\` -> mediaNames.${field}`).toEqual(
+ media[field]
+ );
+ expect(
+ ablated?.mediaNames[field],
+ `G2 ${testCase.label}: \`${key}\` is vacuous for mediaNames.${field}; recall without it names the same`
+ ).not.toEqual(media[field]);
+ }
+ expect(result?.fields, `G2 ${testCase.label}: \`${key}\` is not reported`).toContain('media');
+ continue;
+ }
+ if (!isRestoring(entry, run)) {
+ continue;
+ }
+
+ const ablated = recall(run, 'all', without(run.written, key));
+ const expected = expectedValues(entry, run);
+
+ for (const field of restoredOn(entry, run)) {
+ expect(result?.values[field], `G2 ${testCase.label}: \`${key}\` -> ${field}`).toEqual(expected[field]);
+ expect(
+ ablated?.values[field],
+ `G2 ${testCase.label}: \`${key}\` is vacuous for ${field}; recall without it already lands there`
+ ).not.toEqual(expected[field]);
+ }
+ expect(result?.fields, `G2 ${testCase.label}: \`${key}\` is not reported as ${entry.reports}`).toContain(
+ entry.reports
+ );
+ }
+
+ expect(result?.mediaNames, `G2 ${testCase.label}: the media recall names`).toEqual(expectedMedia);
+ // A full recall clears the panel's media wholesale; the executor hydrates `mediaNames` into these slots.
+ const built = build(run, 'all');
+
+ expect(
+ built &&
+ pick(built.values, ['conditioningClip', 'firstFrameImage', 'lastFrameImage', 'references', 'sourceVideo']),
+ `G2 ${testCase.label}: the panel's media survive the recall`
+ ).toEqual({
+ conditioningClip: null,
+ firstFrameImage: null,
+ lastFrameImage: null,
+ references: [],
+ sourceVideo: null,
+ });
+ });
+
+ it.each(ALL_CASES)('G3 applies nothing from the keys of $label it leaves alone', (testCase) => {
+ const run = recorded(testCase);
+ const applied = (result: ReturnType<typeof recall>) => ({ mediaNames: result?.mediaNames, values: result?.values });
+ const full = applied(recall(run, 'all'));
+
+ for (const [key, entry] of entriesOf(run)) {
+ if ('ignored' in entry || ('restores' in entry && !isRestoring(entry, run))) {
+ expect(
+ applied(recall(run, 'all', without(run.written, key))),
+ `G3 ${testCase.label}: \`${key}\` is held inert but changes what recall applies`
+ ).toEqual(full);
+ }
+ }
+ });
+
+ it.each(ALL_CASES)('G4 offers every recall verb on $label, each applying exactly its share', (testCase) => {
+ const run = recorded(testCase);
+ const all = recall(run, 'all')!;
+ const remix = recall(run, 'remix');
+ const allOnly = entriesOf(run).flatMap(([, entry]) =>
+ isRestoring(entry, run) && !(entry.kinds ?? DEFAULT_KINDS).includes('remix') ? [entry] : []
+ );
+
+ expect(getVideoRecallCapabilities(run.written), `G4 ${testCase.label}: capabilities`).toEqual({
+ all: true,
+ prompts: true,
+ remix: true,
+ seed: true,
+ size: true,
+ });
+ expect(remix?.values, `G4 ${testCase.label}: remix`).toEqual({
+ ...all.values,
+ ...pick(
+ PANEL,
+ allOnly.flatMap((entry) => restoredOn(entry, run))
+ ),
+ });
+ expect(remix?.mediaNames, `G4 ${testCase.label}: remix media`).toEqual(all.mediaNames);
+ expect(remix?.fields, `G4 ${testCase.label}: remix fields`).toEqual(
+ all.fields.filter((field) => !allOnly.some((entry) => entry.reports === field))
+ );
+
+ for (const kind of ['prompts', 'seed'] as const) {
+ expect(recall(run, kind)?.values, `G4 ${testCase.label}: ${kind}`).toEqual({ ...PANEL, ...patchFor(run, kind) });
+ }
+
+ // Fitted to the panel's own model and media, so a panel already on the recorded model and holding its media.
+ const panel = { ...panelOn(run.model), ...TUNED_MEDIA[testCase.mode] };
+ const size = patchFor(run, 'size');
+
+ expect(recall(run, 'size', run.written, panel)?.values ?? null, `G4 ${testCase.label}: size`).toEqual(
+ Object.keys(size).length > 0 ? { ...panel, ...size } : null
+ );
+ });
+
+ it.each(ALL_CASES)('G8 restores what the absence of a key means on a full recall of $label', (testCase) => {
+ const run = recorded(testCase);
+
+ for (const [key, entry] of entriesOf(run)) {
+ if (!('restores' in entry) || !entry.absent) {
+ continue;
+ }
+
+ const { panel, restored } = entry.absent;
+ const result = recall(run, 'all', without(run.written, key), { ...panelOn(run.model), ...panel });
+
+ expect(
+ result && pick(result.values, Object.keys(restored) as (keyof VideoWidgetValues)[]),
+ `G8 ${testCase.label}: \`${key}\` absent`
+ ).toEqual(restored);
+ }
+ });
+
+ it('G7 has no entry no recorded case exercises', () => {
+ const exercised = new Set(
+ ALL_CASES.flatMap((testCase) => {
+ const run = recorded(testCase);
+
+ return Object.keys(run.written).map((key) => contractKeyOf(run, key));
+ })
+ );
+
+ expect(
+ [...Object.keys(VIDEO_RECALL_CONTRACT), ...Object.keys(VIDEO_RUNTIME_CONTRACT)].filter(
+ (key) => !exercised.has(key)
+ ),
+ 'G7: entries no case records'
+ ).toEqual([]);
+ });
+
+ it('keeps the legacy read-only keys out of every record, and still reads each', () => {
+ const recordedKeys = new Set(ALL_CASES.flatMap((testCase) => Object.keys(recorded(testCase).written)));
+ const base = { generation_mode: 'minimax_h3_t2v' };
+
+ for (const [key, value] of Object.entries(LEGACY_READ_ONLY_KEYS)) {
+ expect(recordedKeys.has(key), `\`${key}\` is written again; give it a contract entry instead`).toBe(false);
+ expect(parseVideoRecallRecord({ ...base, [key]: value }), `\`${key}\` is no longer read`).not.toEqual(
+ parseVideoRecallRecord(base)
+ );
+ }
+ });
+
+ describe('recall notice copy', () => {
+ const englishCatalog = Object.values(
+ import.meta.glob('../../../public/locales/en.json', { eager: true, import: 'default' })
+ )[0] as Record<string, unknown>;
+ const english = i18n.createInstance();
+ const t = ((key: string, values?: Record<string, unknown>) => english.t(key, values)) as TFunction;
+
+ beforeAll(async () => {
+ await english.init({
+ initAsync: false,
+ interpolation: { escapeValue: false },
+ lng: 'en',
+ resources: { en: { translation: englishCatalog } },
+ });
+ });
+
+ // The labels are looked up by a key built at run time, which the static translation-key scan cannot see.
+ it('G5 reports every recalled field on some recorded case, under an English label', () => {
+ const reported = new Set(ALL_CASES.flatMap((testCase) => recall(recorded(testCase), 'all')?.fields ?? []));
+
+ expect(
+ VIDEO_RECALLED_FIELDS.filter((field) => !reported.has(field)),
+ 'G5: fields no case reports'
+ ).toEqual([]);
+ for (const field of VIDEO_RECALLED_FIELDS) {
+ expect(getVideoRecallMessage([field], t), `G5: \`${field}\` has no label`).not.toContain('widgets.gallery');
+ }
+ });
+
+ it('titles every recall verb in English', () => {
+ for (const kind of VIDEO_RECALL_KINDS) {
+ expect(getVideoRecallTitle(kind, t), `\`${kind}\` has no title`).not.toContain('widgets.gallery');
+ }
+ });
+ });
+});