Skip to content

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

feat(webv2): video generation parameter recall

Lincoln Steinbef9035fad52
diff --git a/invokeai/frontend/webv2/src/features/video/index.ts b/invokeai/frontend/webv2/src/features/video/index.ts
index ffcebf28e0..2fed5e8124 100644
--- a/invokeai/frontend/webv2/src/features/video/index.ts
+++ b/invokeai/frontend/webv2/src/features/video/index.ts
@@ -52,10 +52,12 @@ export {
getAcceleratorToggleResult,
getDefaultVideoSettings,
getVideoComponentSectionPolicy,
+ getVideoAspectRatioOptions,
getVideoDimensions,
getVideoModelAvailabilityReasons,
getVideoModelPolicy,
getVideoModelSelectionResult,
+ getVideoTargetResolutionOptions,
getVideoModes,
getVideoPromptPolicy,
getVideoSettingsWithModelDefaults,
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx
index e84bbae3fa..12e5699ef4 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx
@@ -54,6 +54,8 @@ const createActions = (deleteItems: ImageActions['deleteItems']): ImageActions =
openItemInPreview: vi.fn(),
openImageInPreview: vi.fn(),
recallImageData: vi.fn(() => Promise.resolve()),
+ getVideoRecallCapabilities: vi.fn(() => Promise.resolve({ all: false, prompts: false, remix: false, seed: false })),
+ recallVideoData: vi.fn(() => Promise.resolve()),
selectForCompare: vi.fn(),
sendToCanvas: vi.fn(() => Promise.resolve()),
setItemsStarred: vi.fn(() => Promise.resolve()),
@@ -249,7 +251,8 @@ describe('ImageContextMenu mixed-media action visibility', () => {
expect(document.body.textContent).toContain('Delete Video');
expect(document.body.textContent).not.toContain('Copy to clipboard');
expect(document.body.textContent).not.toContain('widgets.preview.copyCurrentFrame');
- expect(document.body.textContent).not.toContain('Recall Metadata');
+ // Videos carry their own Recall Metadata submenu (parameter recall).
+ expect(document.body.textContent).toContain('Recall Metadata');
expect(document.body.textContent).not.toContain('Send to Upscale');
expect(document.body.textContent).not.toContain('Select for Compare');
expect(document.body.textContent).not.toContain('New from Image');
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
index 9e7b50fb35..3cb36e7c27 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
@@ -47,6 +47,7 @@ import { useTranslation } from 'react-i18next';
import type { ImageActions } from './useImageActions';
import { EMPTY_IMAGE_RECALL_CAPABILITIES, type ImageRecallCapabilities } from './imageRecall';
+import { EMPTY_VIDEO_RECALL_CAPABILITIES, type VideoRecallCapabilities, type VideoRecallKind } from './videoRecall';
export interface LegacyImageContextMenuTarget {
/** Right-clicked image first; more entries switch the menu into bulk mode. */
@@ -320,6 +321,60 @@ const SingleItemMenuItems = ({
const handleDelete = useCallback(() => onRequestDeletion([itemRef]), [itemRef, onRequestDeletion]);
const { generation, widgets } = useWorkbenchCommands();
const openWidget = useOpenWorkbenchWidget();
+ // Video recall availability, fetched from the item's recorded core_metadata
+ // when the menu opens on a video — the video twin of the image menu's flow.
+ const [videoRecallCapabilities, setVideoRecallCapabilities] = useState<VideoRecallCapabilities>(
+ EMPTY_VIDEO_RECALL_CAPABILITIES
+ );
+ const [isLoadingVideoRecall, setIsLoadingVideoRecall] = useState(false);
+ const videoItemName = item.kind === 'video' ? item.name : null;
+ const getVideoRecallCapabilities = actions.getVideoRecallCapabilities;
+
+ useEffect(() => {
+ if (!videoItemName || item.kind !== 'video') {
+ return;
+ }
+
+ let isCancelled = false;
+ const videoItem = item;
+
+ setVideoRecallCapabilities(EMPTY_VIDEO_RECALL_CAPABILITIES);
+ setIsLoadingVideoRecall(true);
+ getVideoRecallCapabilities(videoItem)
+ .then((capabilities) => {
+ if (!isCancelled) {
+ setVideoRecallCapabilities(capabilities);
+ }
+ })
+ .catch(() => {
+ if (!isCancelled) {
+ setVideoRecallCapabilities(EMPTY_VIDEO_RECALL_CAPABILITIES);
+ }
+ })
+ .finally(() => {
+ if (!isCancelled) {
+ setIsLoadingVideoRecall(false);
+ }
+ });
+
+ return () => {
+ isCancelled = true;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed by name; the item identity churns per render
+ }, [getVideoRecallCapabilities, videoItemName]);
+
+ const makeVideoRecallHandler = useCallback(
+ (kind: VideoRecallKind) => () => {
+ if (item.kind === 'video') {
+ void actions.recallVideoData(item, kind);
+ }
+ },
+ [actions, item]
+ );
+ const handleVideoRecallAll = useMemo(() => makeVideoRecallHandler('all'), [makeVideoRecallHandler]);
+ const handleVideoRecallRemix = useMemo(() => makeVideoRecallHandler('remix'), [makeVideoRecallHandler]);
+ const handleVideoRecallPrompts = useMemo(() => makeVideoRecallHandler('prompts'), [makeVideoRecallHandler]);
+ const handleVideoRecallSeed = useMemo(() => makeVideoRecallHandler('seed'), [makeVideoRecallHandler]);
const handleExtendInVideo = useCallback(() => {
if (item.kind !== 'video') {
return;
@@ -366,12 +421,44 @@ const SingleItemMenuItems = ({
</HStack>
<Menu.Separator borderColor="border.subtle" />
{item.kind === 'video' ? (
- <ContextMenuItem
- icon={ClapperboardIcon}
- label="Extend in Video"
- value="extend-in-video"
- onClick={handleExtendInVideo}
- />
+ <>
+ <ContextSubMenu icon={AsteriskIcon} label="Recall Metadata">
+ <ContextMenuItem
+ disabled={isLoadingVideoRecall || !videoRecallCapabilities.all}
+ icon={AsteriskIcon}
+ label="Recall All"
+ value="video-recall-all"
+ onClick={handleVideoRecallAll}
+ />
+ <ContextMenuItem
+ disabled={isLoadingVideoRecall || !videoRecallCapabilities.remix}
+ icon={ShuffleIcon}
+ label="Remix Video"
+ value="video-remix"
+ onClick={handleVideoRecallRemix}
+ />
+ <ContextMenuItem
+ disabled={isLoadingVideoRecall || !videoRecallCapabilities.prompts}
+ icon={QuoteIcon}
+ label="Use Prompt"
+ value="video-use-prompt"
+ onClick={handleVideoRecallPrompts}
+ />
+ <ContextMenuItem
+ disabled={isLoadingVideoRecall || !videoRecallCapabilities.seed}
+ icon={SproutIcon}
+ label="Use Seed"
+ value="video-use-seed"
+ onClick={handleVideoRecallSeed}
+ />
+ </ContextSubMenu>
+ <ContextMenuItem
+ icon={ClapperboardIcon}
+ label="Extend in Video"
+ value="extend-in-video"
+ onClick={handleExtendInVideo}
+ />
+ </>
) : null}
{item.kind === 'video' && previewVideoActions && previewVideoActions.itemKey === toGalleryItemKey(item) ? (
<>
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts
new file mode 100644
index 0000000000..1609df6eb9
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts
@@ -0,0 +1,215 @@
+import type { GalleryVideoItem } from '@features/gallery';
+import type { ModelConfig } from '@features/models';
+import type { AccountScope } from '@platform/state/accountLifecycle';
+import type { WorkbenchCommands } from '@workbench/workbenchStore';
+
+import { galleryImages, galleryItems, galleryVideos } from '@features/gallery';
+import {
+ createDefaultVideoWidgetValues,
+ createVideoSourceClip,
+ normalizeVideoWidgetValues,
+ syncVideoWidgetValuesWithModels,
+} from '@features/video';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+} from '@platform/state/accountLifecycle';
+
+import {
+ buildVideoRecallSettings,
+ getVideoRecallMessage,
+ getVideoRecallTitle,
+ type VideoRecallKind,
+} from './videoRecall';
+
+const videoMetadataRequests = new Map<string, { owner: AccountScope; promise: Promise<unknown> }>();
+
+registerAccountOwnedResource({
+ clear: () => {
+ videoMetadataRequests.clear();
+ },
+ name: 'video-recall-metadata',
+});
+
+const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
+
+const loadVideoMetadata = (videoName: string, owner: AccountScope): Promise<unknown> => {
+ const cachedRequest = videoMetadataRequests.get(videoName);
+
+ if (cachedRequest?.owner === owner) {
+ return cachedRequest.promise;
+ }
+
+ const request = galleryVideos
+ .metadata(videoName, owner.signal)
+ .then((metadata) => {
+ assertAccountScopeCurrent(owner);
+
+ return metadata;
+ })
+ .catch((error: unknown) => {
+ if (videoMetadataRequests.get(videoName)?.promise === request) {
+ videoMetadataRequests.delete(videoName);
+ }
+ throw error;
+ });
+
+ videoMetadataRequests.set(videoName, { owner, promise: request });
+ return request;
+};
+
+export const getCurrentVideoValues = ({
+ models,
+ videoValues,
+}: {
+ models: readonly ModelConfig[];
+ videoValues: Record<string, unknown>;
+}) => {
+ const normalized = normalizeVideoWidgetValues(videoValues) ?? createDefaultVideoWidgetValues(models);
+
+ return syncVideoWidgetValuesWithModels(normalized, models);
+};
+
+export const executeVideoRecall = async ({
+ commands,
+ getVideoValues,
+ item,
+ kind,
+ models,
+ owner: callerOwner,
+ projectId,
+}: {
+ commands: Pick<WorkbenchCommands, 'generation' | 'notifications' | 'widgets'>;
+ getVideoValues: () => Record<string, unknown>;
+ item: GalleryVideoItem;
+ kind: VideoRecallKind;
+ models: ModelConfig[];
+ /** Caller-captured identity lifetime; direct synchronous callers may omit it. */
+ owner?: AccountScope;
+ projectId?: string;
+}): Promise<boolean> => {
+ const owner = callerOwner ?? captureAccountScope();
+
+ if (!isAccountScopeCurrent(owner)) {
+ return false;
+ }
+
+ try {
+ const metadata = await loadVideoMetadata(item.name, owner);
+
+ assertAccountScopeCurrent(owner);
+ // Snapshot the panel AFTER the fetch: an edit made while the metadata
+ // loaded must survive into the base the recall applies on top of.
+ const currentValues = getCurrentVideoValues({ models, videoValues: getVideoValues() });
+ const result = buildVideoRecallSettings({ currentValues, kind, metadata, models });
+
+ if (!result) {
+ commands.notifications.add({
+ kind: 'info',
+ message: 'This video does not include supported Video metadata.',
+ title: 'No recallable video data',
+ });
+ return false;
+ }
+
+ // Conditioning media re-hydrates against the gallery: the metadata records
+ // only names, and the panel needs dimensions/probe data — plus deleted
+ // media must drop rather than resurrect as broken references.
+ if (result.fields.includes('media')) {
+ let recalledMedia = false;
+ const { firstFrameName, lastFrameName, sourceVideoName } = result.mediaNames;
+ const frameNames = [firstFrameName, lastFrameName].filter((name): name is string => name !== null);
+ const resolvedFrames =
+ frameNames.length > 0 ? await galleryImages.resolveMany([...new Set(frameNames)], owner.signal) : [];
+
+ assertAccountScopeCurrent(owner);
+ const framesByName = new Map(resolvedFrames.map((frame) => [frame.imageName, frame]));
+ const firstFrame = firstFrameName ? framesByName.get(firstFrameName) : undefined;
+ const lastFrame = lastFrameName ? framesByName.get(lastFrameName) : undefined;
+
+ if (firstFrame) {
+ result.values = {
+ ...result.values,
+ firstFrameImage: { height: firstFrame.height, image_name: firstFrame.imageName, width: firstFrame.width },
+ sourceVideo: null,
+ };
+ recalledMedia = true;
+ }
+ if (lastFrame) {
+ result.values = {
+ ...result.values,
+ lastFrameImage: { height: lastFrame.height, image_name: lastFrame.imageName, width: lastFrame.width },
+ };
+ recalledMedia = true;
+ }
+
+ if (sourceVideoName) {
+ try {
+ const sourceItem = await galleryItems.resolve({ kind: 'video', name: sourceVideoName }, owner.signal);
+
+ assertAccountScopeCurrent(owner);
+ if (sourceItem?.kind === 'video') {
+ result.values = {
+ ...result.values,
+ firstFrameImage: null,
+ sourceVideo: createVideoSourceClip({
+ durationSeconds: sourceItem.durationSeconds,
+ fps: sourceItem.fps,
+ height: sourceItem.height,
+ name: sourceItem.name,
+ width: sourceItem.width,
+ }),
+ };
+ recalledMedia = true;
+ }
+ } catch {
+ assertAccountScopeCurrent(owner);
+ // The source clip is gone; the rest of the recall still applies.
+ }
+ }
+
+ if (!recalledMedia) {
+ result.fields = result.fields.filter((field) => field !== 'media');
+ }
+ }
+
+ if (result.fields.length === 0) {
+ commands.notifications.add({
+ kind: 'info',
+ message: 'This video does not include supported Video metadata.',
+ title: 'No recallable video data',
+ });
+ return false;
+ }
+
+ // Prompts live in the shared project draft; everything else is widget values.
+ if (result.promptPatch) {
+ commands.generation.patchPromptDraft(result.promptPatch, 'video', projectId);
+ }
+ // A prompts-only recall changes no widget values — skip the whole-values
+ // write (and the lost-update window it would widen).
+ if (result.values !== currentValues || result.fields.some((field) => field !== 'prompts')) {
+ commands.widgets.patchValues('video', { ...result.values }, projectId);
+ }
+ commands.notifications.add({
+ kind: 'success',
+ message: getVideoRecallMessage(result.fields),
+ title: getVideoRecallTitle(kind),
+ });
+ return true;
+ } catch (error: unknown) {
+ if (!isAccountScopeCurrent(owner)) {
+ return false;
+ }
+
+ commands.notifications.reportError({
+ area: 'video-recall',
+ message: toErrorMessage(error),
+ namespace: 'generation',
+ projectId,
+ });
+ return false;
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
index 68de586526..ae6ef2d7e2 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
@@ -15,6 +15,8 @@ import {
type GalleryItemKey,
type GalleryItemMutationResult,
type GalleryItemRef,
+ galleryVideos,
+ type GalleryVideoItem,
} from '@features/gallery';
import { getGalleryBoardLabel } from '@features/gallery/contracts';
import {
@@ -52,6 +54,7 @@ import type { RequestDeletionConfirmation } from './useDeletionConfirmation';
import { appendReferenceImage } from './appendReferenceImage';
import { recordCanvasImportError } from './canvasImportError';
import { executeImageRecall, getCurrentGenerateValues } from './executeImageRecall';
+import { executeVideoRecall } from './executeVideoRecall';
import {
captureGalleryWidgetKeyValues,
collectGalleryStoreKnownItemFields,
@@ -67,6 +70,12 @@ import {
type ImageRecallCapabilities,
type ImageRecallKind,
} from './imageRecall';
+import {
+ EMPTY_VIDEO_RECALL_CAPABILITIES,
+ getVideoRecallCapabilities as deriveVideoRecallCapabilitiesFromMetadata,
+ type VideoRecallCapabilities,
+ type VideoRecallKind,
+} from './videoRecall';
/**
* Image operations shared by every surface that shows backend images (gallery
@@ -86,9 +95,13 @@ export interface ImageActions extends GalleryItemActions {
downloadImage: (image: GalleryImage) => Promise<void>;
downloadImages: (imageNames: string[]) => Promise<void>;
getImageRecallCapabilities: (image: GalleryImage, signal?: AbortSignal) => Promise<ImageRecallCapabilities>;
+ /** Recall availability for a gallery video, from its recorded core_metadata. */
+ getVideoRecallCapabilities: (item: GalleryVideoItem, signal?: AbortSignal) => Promise<VideoRecallCapabilities>;
moveImagesToBoard: (imageNames: string[], boardId: string) => Promise<void>;
openImageInPreview: (image: GalleryImage) => void;
recallImageData: (image: GalleryImage, kind: ImageRecallKind) => Promise<void>;
+ /** Applies a gallery video's recorded parameters to the Video panel. */
+ recallVideoData: (item: GalleryVideoItem, kind: VideoRecallKind) => Promise<void>;
/** Opens the generate widget's template editor prefilled from this image's prompts. */
savePromptAsTemplate: (image: GalleryImage) => Promise<void>;
selectForCompare: (image: GalleryImage) => void;
@@ -171,6 +184,14 @@ export const useImageActions = ({
return project ? getProjectWidgetValues(project, 'generate') : {};
};
+ const getLatestVideoValues = () => {
+ const snapshot = queries.getSnapshot();
+ const project = projectId
+ ? snapshot.projects.find((candidate) => candidate.id === projectId)
+ : snapshot.activeProject;
+
+ return project ? getProjectWidgetValues(project, 'video') : {};
+ };
// A deleted item can be visible only through widget values — the
// `recentImages` overlay, or upscale's locked input — which the cache patch
// cannot restore. Snapshot those fields across every open project (images
@@ -816,6 +837,36 @@ export const useImageActions = ({
};
}
},
+ getVideoRecallCapabilities: async (item, signal) => {
+ const owner = captureAccountScope();
+
+ try {
+ const requestSignal = signal ? AbortSignal.any([signal, owner.signal]) : owner.signal;
+ const metadata = await galleryVideos.metadata(item.name, requestSignal);
+
+ assertAccountScopeCurrent(owner);
+ return deriveVideoRecallCapabilitiesFromMetadata(metadata);
+ } catch {
+ return EMPTY_VIDEO_RECALL_CAPABILITIES;
+ }
+ },
+ recallVideoData: async (item, kind) => {
+ const owner = captureAccountScope();
+ const didRecall = await executeVideoRecall({
+ commands,
+ getVideoValues: getLatestVideoValues,
+ item,
+ kind,
+ models,
+ projectId,
+ });
+
+ // The value patch auto-routes the invoke source (media/settings are
+ // intent-bearing keys); surfacing the widget is the caller-side touch.
+ if (isAccountScopeCurrent(owner) && didRecall && (!projectId || queries.isActiveProject(projectId))) {
+ openWorkbenchWidget('video', { preferredRegions: ['left'] });
+ }
+ },
savePromptAsTemplate: async (image) => {
const owner = captureAccountScope();
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts
new file mode 100644
index 0000000000..c967e21f82
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts
@@ -0,0 +1,348 @@
+import type { GenerationModelCatalogItem, MainModelConfig } from '@features/generation/contracts';
+
+import { createDefaultVideoWidgetValues } from '@features/video';
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildVideoRecallSettings,
+ deriveAcceleratorRecallState,
+ EMPTY_VIDEO_RECALL_CAPABILITIES,
+ getRecallableMediaNames,
+ getVideoRecallCapabilities,
+ getVideoSizeRecall,
+ isVideoGenerationMetadata,
+} from './videoRecall';
+
+const wanModel = (variant: string, format = 'diffusers', key = `wan-${variant}-${format}`): MainModelConfig => ({
+ base: 'wan',
+ format,
+ key,
+ name: `Wan 2.2 ${variant}`,
+ type: 'main',
+ variant,
+});
+
+const h3Model = (key = 'h3-main'): MainModelConfig => ({
+ base: 'minimax-h3',
+ format: 'diffusers',
+ key,
+ name: 'MiniMax H3',
+ type: 'main',
+ variant: 'fl2va',
+});
+
+const lora = (name: string, base = 'wan', variant: string | null = 'a14b'): GenerationModelCatalogItem => ({
+ base,
+ key: `lora-${name}`,
+ name,
+ type: 'lora',
+ variant,
+});
+
+const LIGHTNING_HIGH = lora('Wan 2.2 T2V Lightning High Noise (4-step)');
+const LIGHTNING_LOW = lora('Wan 2.2 T2V Lightning Low Noise (4-step)');
+
+const WAN_T2V = wanModel('t2v_a14b');
+const WAN_I2V = wanModel('i2v_a14b');
+
+const wanMetadata = (extra: Record<string, unknown> = {}): Record<string, unknown> => ({
+ cfg_scale: 1,
+ generation_mode: 'wan_t2v',
+ height: 720,
+ model: { base: 'wan', key: WAN_T2V.key, name: WAN_T2V.name, type: 'main' },
+ negative_prompt: 'blurry',
+ num_frames: 81,
+ positive_prompt: 'a red fox running',
+ seed: 1234,
+ steps: 4,
+ width: 1280,
+ ...extra,
+});
+
+describe('isVideoGenerationMetadata', () => {
+ it('accepts only the video generation modes', () => {
+ expect(isVideoGenerationMetadata(wanMetadata())).toBe(true);
+ expect(isVideoGenerationMetadata({ generation_mode: 'minimax_h3_flf2v' })).toBe(true);
+ // Image metadata — including Wan still-image modes — is not video metadata.
+ expect(isVideoGenerationMetadata({ generation_mode: 'wan_txt2img' })).toBe(false);
+ expect(isVideoGenerationMetadata({ generation_mode: 'sdxl_txt2img' })).toBe(false);
+ expect(isVideoGenerationMetadata({})).toBe(false);
+ expect(isVideoGenerationMetadata(null)).toBe(false);
+ });
+});
+
+describe('getVideoRecallCapabilities', () => {
+ it('is empty for non-video metadata', () => {
+ expect(getVideoRecallCapabilities({ generation_mode: 'sdxl_txt2img', seed: 5 })).toEqual(
+ EMPTY_VIDEO_RECALL_CAPABILITIES
+ );
+ });
+
+ it('derives per-verb availability from what the metadata contains', () => {
+ expect(getVideoRecallCapabilities(wanMetadata())).toEqual({ all: true, prompts: true, remix: true, seed: true });
+ expect(getVideoRecallCapabilities({ generation_mode: 'wan_t2v', seed: 7 })).toEqual({
+ all: true,
+ prompts: false,
+ remix: false,
+ seed: true,
+ });
+ });
+});
+
+describe('getRecallableMediaNames', () => {
+ it('suppresses the extracted first frame in extend mode', () => {
+ const names = getRecallableMediaNames({
+ first_frame_image: { image_name: 'extracted.png' },
+ generation_mode: 'wan_extend_video',
+ last_frame_image: { image_name: 'destination.png' },
+ source_video: { video_name: 'clip.mp4' },
+ });
+
+ expect(names).toEqual({ firstFrameName: null, lastFrameName: 'destination.png', sourceVideoName: 'clip.mp4' });
+ });
+
+ it('keeps user keyframes when no source video was recorded', () => {
+ expect(
+ getRecallableMediaNames({ first_frame_image: { image_name: 'first.png' }, generation_mode: 'wan_i2v' })
+ ).toEqual({ firstFrameName: 'first.png', lastFrameName: null, sourceVideoName: null });
+ });
+});
+
+describe('getVideoSizeRecall', () => {
+ it('inverts a preset-derived canvas exactly', () => {
+ expect(getVideoSizeRecall(WAN_T2V, 1280, 720)).toEqual({ aspectRatioId: '16:9', targetResolution: '720p' });
+ expect(getVideoSizeRecall(h3Model(), 1344, 768)).toEqual({
+ aspectRatioId: '16:9',
+ targetResolution: '768 highres',
+ });
+ });
+
+ it('rejects sizes that came from conditioning media rather than a preset', () => {
+ // 1920x1080-shaped media at some odd snap no preset reproduces.
+ expect(getVideoSizeRecall(WAN_T2V, 848, 464)).toBeNull();
+ });
+});
+
+describe('deriveAcceleratorRecallState', () => {
+ const catalog = [WAN_T2V, LIGHTNING_HIGH, LIGHTNING_LOW];
+ const settings = createDefaultVideoWidgetValues([WAN_T2V]);
+ const pairEntries = [
+ { isEnabled: true, model: LIGHTNING_HIGH as never, weight: 1 },
+ { isEnabled: true, model: LIGHTNING_LOW as never, weight: 1 },
+ ];
+
+ it('re-enables the fast path when the recalled LoRAs are exactly the accelerator set at its steps', () => {
+ expect(deriveAcceleratorRecallState(WAN_T2V, catalog, pairEntries, 4, settings)).toEqual({
+ acceleratorEnabled: true,
+ acceleratorLoraKeys: [LIGHTNING_HIGH.key, LIGHTNING_LOW.key],
+ });
+ });
+
+ it('stays off at non-accelerator steps or with a partial pair', () => {
+ expect(deriveAcceleratorRecallState(WAN_T2V, catalog, pairEntries, 40, settings)).toEqual({
+ acceleratorEnabled: false,
+ acceleratorLoraKeys: [],
+ });
+ expect(deriveAcceleratorRecallState(WAN_T2V, catalog, [pairEntries[0]!], 4, settings)).toEqual({
+ acceleratorEnabled: false,
+ acceleratorLoraKeys: [],
+ });
+ });
+});
+
+describe('buildVideoRecallSettings', () => {
+ const catalog = [WAN_T2V, WAN_I2V, h3Model(), LIGHTNING_HIGH, LIGHTNING_LOW];
+ const currentValues = { ...createDefaultVideoWidgetValues([h3Model()]) };
+
+ it('routes prompts into the shared draft patch, not the widget values', () => {
+ const result = buildVideoRecallSettings({
+ currentValues,
+ kind: 'prompts',
+ metadata: wanMetadata(),
+ models: catalog,
+ });
+
+ expect(result?.fields).toEqual(['prompts']);
+ expect(result?.promptPatch).toEqual({
+ negativePrompt: 'blurry',
+ negativePromptEnabled: true,
+ positivePrompt: 'a red fox running',
+ });
+ expect(result?.values).toEqual(currentValues);
+ });
+
+ it('recalls only the seed for the seed verb', () => {
+ const result = buildVideoRecallSettings({ currentValues, kind: 'seed', metadata: wanMetadata(), models: catalog });
+
+ expect(result?.fields).toEqual(['seed']);
+ expect(result?.values).toMatchObject({ seed: 1234, shouldRandomizeSeed: false });
+ });
+
+ it('remix recalls everything except the seed', () => {
+ const result = buildVideoRecallSettings({ currentValues, kind: 'remix', metadata: wanMetadata(), models: catalog });
+
+ expect(result?.fields).not.toContain('seed');
+ expect(result?.values.shouldRandomizeSeed).toBe(currentValues.shouldRandomizeSeed);
+ expect(result?.fields).toEqual(expect.arrayContaining(['model', 'frames', 'steps', 'cfg', 'size']));
+ });
+
+ it('resolves the model by key and snaps cross-family constraints before applying values', () => {
+ // Current panel is H3 (frames 124, fps 24); metadata is a Wan t2v run.
+ const result = buildVideoRecallSettings({ currentValues, kind: 'all', metadata: wanMetadata(), models: catalog });
+
+ expect(result?.values.model?.key).toBe(WAN_T2V.key);
+ expect(result?.values).toMatchObject({
+ aspectRatioId: '16:9',
+ cfgScale: 1,
+ numFrames: 81,
+ seed: 1234,
+ steps: 4,
+ targetResolution: '720p',
+ });
+ });
+
+ it('skips the model (and validates against the current one) when it is not installed', () => {
+ const result = buildVideoRecallSettings({
+ currentValues,
+ kind: 'all',
+ metadata: wanMetadata({ model: { key: 'gone' }, num_frames: 81 }),
+ models: [h3Model()],
+ });
+
+ expect(result?.fields).not.toContain('model');
+ expect(result?.values.model?.base).toBe('minimax-h3');
+ // 81 is off the H3 grid; it snaps rather than landing invalid.
+ expect(result?.values.numFrames).toBe(90);
+ });
+
+ it('recalls LoRAs by key and restores the accelerator state that produced the video', () => {
+ const metadata = wanMetadata({
+ loras: [
+ { model: { key: LIGHTNING_HIGH.key }, weight: 1 },
+ { model: { key: LIGHTNING_LOW.key }, weight: 1 },
+ ],
+ });
+ const result = buildVideoRecallSettings({ currentValues, kind: 'all', metadata, models: catalog });
+
+ expect(result?.fields).toContain('loras');
+ expect(result?.values.loras.map((entry) => entry.model.key)).toEqual([LIGHTNING_HIGH.key, LIGHTNING_LOW.key]);
+ expect(result?.values).toMatchObject({ acceleratorEnabled: true });
+ });
+
+ it('clears existing LoRAs when the video ran without any', () => {
+ const withLora = {
+ ...currentValues,
+ loras: [{ isEnabled: true, model: LIGHTNING_HIGH as never, weight: 1 }],
+ };
+ const result = buildVideoRecallSettings({
+ currentValues: withLora,
+ kind: 'all',
+ metadata: wanMetadata(),
+ models: catalog,
+ });
+
+ expect(result?.fields).toContain('loras');
+ expect(result?.values.loras).toEqual([]);
+ expect(result?.values.acceleratorEnabled).toBe(false);
+ });
+
+ it('reports recallable media names but leaves hydration to the executor', () => {
+ const metadata = wanMetadata({
+ first_frame_image: { image_name: 'first.png' },
+ generation_mode: 'wan_i2v',
+ model: { key: WAN_I2V.key },
+ });
+ const result = buildVideoRecallSettings({ currentValues, kind: 'all', metadata, models: catalog });
+
+ expect(result?.fields).toContain('media');
+ expect(result?.mediaNames).toEqual({ firstFrameName: 'first.png', lastFrameName: null, sourceVideoName: null });
+ expect(result?.values.firstFrameImage).toBeNull();
+ });
+
+ it('restores reuse-primary semantics when the low-noise CFG key is absent', () => {
+ const withLow = { ...createDefaultVideoWidgetValues([WAN_T2V]), cfgScaleLowNoise: 2 };
+ // wan_t2v metadata without guidance_scale_low_noise: the run reused the
+ // primary CFG, so the recalled state must too.
+ const result = buildVideoRecallSettings({
+ currentValues: withLow,
+ kind: 'all',
+ metadata: wanMetadata(),
+ models: catalog,
+ });
+
+ expect(result?.values.cfgScaleLowNoise).toBeNull();
+
+ const withKey = buildVideoRecallSettings({
+ currentValues: withLow,
+ kind: 'all',
+ metadata: wanMetadata({ guidance_scale_low_noise: 3 }),
+ models: catalog,
+ });
+
+ expect(withKey?.values.cfgScaleLowNoise).toBe(3);
+ });
+
+ it('clears held conditioning media when the recorded run had none — mode is part of the recall', () => {
+ const withFrame = {
+ ...createDefaultVideoWidgetValues([WAN_I2V]),
+ firstFrameImage: { height: 720, image_name: 'held.png', width: 1280 },
+ };
+ const result = buildVideoRecallSettings({
+ currentValues: withFrame,
+ kind: 'all',
+ metadata: wanMetadata(),
+ models: catalog,
+ });
+
+ expect(result?.fields).toContain('media');
+ expect(result?.values.firstFrameImage).toBeNull();
+ expect(result?.values.sourceVideo).toBeNull();
+ });
+
+ it('does not flip the negative toggle on for an empty recorded negative', () => {
+ const empty = buildVideoRecallSettings({
+ currentValues,
+ kind: 'prompts',
+ metadata: wanMetadata({ negative_prompt: '' }),
+ models: catalog,
+ });
+
+ expect(empty?.promptPatch).toEqual({ positivePrompt: 'a red fox running' });
+
+ const explicitNull = buildVideoRecallSettings({
+ currentValues,
+ kind: 'prompts',
+ metadata: wanMetadata({ negative_prompt: null }),
+ models: catalog,
+ });
+
+ expect(explicitNull?.promptPatch).toMatchObject({ negativePrompt: '', negativePromptEnabled: false });
+ });
+
+ it('clears current LoRAs when the recorded ones are no longer installed', () => {
+ const withLora = {
+ ...currentValues,
+ loras: [{ isEnabled: true, model: LIGHTNING_HIGH as never, weight: 1 }],
+ };
+ const result = buildVideoRecallSettings({
+ currentValues: withLora,
+ kind: 'all',
+ metadata: wanMetadata({ loras: [{ model: { key: 'uninstalled' }, weight: 1 }] }),
+ models: [WAN_T2V, LIGHTNING_HIGH],
+ });
+
+ expect(result?.values.loras).toEqual([]);
+ expect(result?.fields).toContain('loras');
+ });
+
+ it('returns null for non-video metadata', () => {
+ expect(
+ buildVideoRecallSettings({
+ currentValues,
+ kind: 'all',
+ metadata: { generation_mode: 'sdxl_txt2img', seed: 3 },
+ models: catalog,
+ })
+ ).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts
new file mode 100644
index 0000000000..146d67b46e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts
@@ -0,0 +1,550 @@
+import type {
+ GenerateLora,
+ GenerationModelCatalogItem as ModelConfig,
+ LoraModelConfig,
+ MainModelConfig,
+} from '@features/generation/contracts';
+import type { ProjectPromptDraftPatch } from '@features/generation/settings';
+import type { VideoAspectRatioId, VideoTargetResolution, VideoWidgetValues } from '@features/video';
+
+import { isLoraCompatibleWithModel, isLoraModelConfig, SEED_MAX } from '@features/generation/settings';
+import {
+ findMiniMaxH3TurboLora,
+ findWanLightningLoraPair,
+ getVideoAspectRatioOptions,
+ getVideoDimensions,
+ getVideoModelPolicy,
+ getVideoModelSelectionResult,
+ getVideoTargetResolutionOptions,
+ isSupportedVideoModel,
+ isValidVideoNumFrames,
+ snapVideoNumFrames,
+} from '@features/video';
+
+/**
+ * Pure mapping from a video's recorded `core_metadata` to a Video-panel
+ * patch — the sibling of `imageRecall.ts`. Model resolution is by KEY against
+ * the installed catalog; an uninstalled model skips the model field and
+ * everything downstream validates against the current model instead. The
+ * conditioning mode is never recalled directly: the panel derives it from
+ * which media fields are filled, so recall restores the media and lets the
+ * mode fall out.
+ */
+
+/** The generation_mode strings the video graphs stamp; anything else is not video metadata. */
+const VIDEO_GENERATION_MODE_IDS: ReadonlySet<string> = new Set([
+ 'wan_t2v',
+ 'wan_i2v',
+ 'wan_interpolate',
+ 'wan_extend_video',
+ 'minimax_h3_t2v',
+ 'minimax_h3_i2v',
+ 'minimax_h3_lf2v',
+ 'minimax_h3_flf2v',
+ 'minimax_h3_extend_video',
+]);
+
+export type VideoRecallKind = 'all' | 'remix' | 'prompts' | 'seed';
+
+export interface VideoRecallCapabilities {
+ all: boolean;
+ remix: boolean;
+ prompts: boolean;
+ seed: boolean;
+}
+
+export const EMPTY_VIDEO_RECALL_CAPABILITIES: VideoRecallCapabilities = {
+ all: false,
+ prompts: false,
+ remix: false,
+ seed: false,
+};
+
+export type VideoRecalledField =
+ | 'model'
+ | 'prompts'
+ | 'seed'
+ | 'size'
+ | 'frames'
+ | 'steps'
+ | 'cfg'
+ | 'loras'
+ | 'components'
+ | 'media';
+
+export interface VideoRecallResult {
+ fields: VideoRecalledField[];
+ /** Prompt fields live in the shared project draft, not the widget values. */
+ promptPatch: ProjectPromptDraftPatch | null;
+ values: VideoWidgetValues;
+}
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ Boolean(value) && typeof value === 'object' && !Array.isArray(value);
+
+const getRecord = (value: unknown, key: string): Record<string, unknown> | null => {
+ if (!isRecord(value)) {
+ return null;
+ }
+
+ const child = value[key];
+
+ return isRecord(child) ? child : null;
+};
+
+const getString = (metadata: unknown, key: string): string | null => {
+ if (!isRecord(metadata)) {
+ return null;
+ }
+
+ const value = metadata[key];
+
+ return typeof value === 'string' ? value : null;
+};
+
+const getNullableString = (metadata: unknown, key: string): string | null | undefined => {
+ if (!isRecord(metadata)) {
+ return undefined;
+ }
+
+ const value = metadata[key];
+
+ if (value === null) {
+ return null;
+ }
+
+ return typeof value === 'string' ? value : undefined;
+};
+
+const getNumber = (metadata: unknown, key: string): number | null => {
+ if (!isRecord(metadata)) {
+ return null;
+ }
+
+ const value = metadata[key];
+
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
+};
+
+const getInteger = (metadata: unknown, key: string): number | null => {
+ const value = getNumber(metadata, key);
+
+ return value !== null && Number.isInteger(value) ? value : null;
+};
+
+const getSeed = (metadata: unknown): number | null => {
+ const seed = getInteger(metadata, 'seed');
+
+ return seed !== null && seed >= 0 && seed <= SEED_MAX ? seed : null;
+};
+
+export const isVideoGenerationMetadata = (metadata: unknown): boolean => {
+ const mode = getString(metadata, 'generation_mode');
+
+ return mode !== null && VIDEO_GENERATION_MODE_IDS.has(mode);
+};
+
+const getMetadataModelKey = (metadata: unknown, key: string): string | null => {
+ const model = getRecord(metadata, key);
+
+ return typeof model?.key === 'string' ? model.key : null;
+};
+
+const getSupportedVideoMetadataModel = (metadata: unknown, models: readonly ModelConfig[]): MainModelConfig | null => {
+ const modelKey = getMetadataModelKey(metadata, 'model');
+
+ if (!modelKey) {
+ return null;
+ }
+
+ const installed = models.find((model) => model.key === modelKey);
+
+ return installed && isSupportedVideoModel(installed) ? (installed as MainModelConfig) : null;
+};
+
+const getMetadataPrompts = (
+ metadata: unknown
+): { positivePrompt: string | null; negativePrompt: string | null | undefined } => ({
+ negativePrompt: getNullableString(metadata, 'negative_prompt'),
+ positivePrompt: getString(metadata, 'positive_prompt'),
+});
+
+const hasPrompt = (metadata: unknown): boolean => {
+ const { negativePrompt, positivePrompt } = getMetadataPrompts(metadata);
+
+ return positivePrompt !== null || typeof negativePrompt === 'string';
+};
+
+const getImageName = (metadata: unknown, key: string): string | null => {
+ const field = getRecord(metadata, key);
+
+ return typeof field?.image_name === 'string' ? field.image_name : null;
+};
+
+const getSourceVideoName = (metadata: unknown): string | null => {
+ const field = getRecord(metadata, 'source_video');
+
+ return typeof field?.video_name === 'string' ? field.video_name : null;
+};
+
+/**
+ * The keyframe names the recall should restore, per the recorded mode. In
+ * extend mode `first_frame_image` is the frame the graph EXTRACTED from the
+ * source clip — derived conditioning, not user input — so restoring it would
+ * both misrepresent the session and collide with the panel's first-frame ⊻
+ * initial-video exclusion.
+ */
+export const getRecallableMediaNames = (
+ metadata: unknown
+): { firstFrameName: string | null; lastFrameName: string | null; sourceVideoName: string | null } => {
+ const sourceVideoName = getSourceVideoName(metadata);
+
+ return {
+ firstFrameName: sourceVideoName ? null : getImageName(metadata, 'first_frame_image'),
+ lastFrameName: getImageName(metadata, 'last_frame_image'),
+ sourceVideoName,
+ };
+};
+
+const getMetadataLoras = (metadata: unknown): { key: string; weight: number }[] => {
+ if (!isRecord(metadata) || !Array.isArray(metadata.loras)) {
+ return [];
+ }
+
+ return metadata.loras.flatMap((entry) => {
+ if (!isRecord(entry) || !isRecord(entry.model) || typeof entry.model.key !== 'string') {
+ return [];
+ }
+
+ const weight = typeof entry.weight === 'number' && Number.isFinite(entry.weight) ? entry.weight : 1;
+
+ return [{ key: entry.model.key, weight }];
+ });
+};
+
+/** Metadata component slot → widget-values key, with the recorded value's key resolved against the catalog. */
+const VIDEO_COMPONENT_METADATA_KEYS = [
+ ['vae', 'vae'],
+ ['wan_t5_encoder', 'wanT5EncoderModel'],
+ ['wan_component_source', 'componentSourceModel'],
+ ['transformer_low_noise', 'wanLowNoiseModel'],
+ ['minimax_h3_transformer_model', 'h3TransformerModel'],
+ ['minimax_h3_text_encoder_model', 'h3TextEncoderModel'],
+] as const;
+
+/**
+ * The recorded W×H inverted back into the panel's aspect-ratio preset +
+ * target-resolution pair — exact matches only. A near-miss would silently
+ * recall a preset the run never used: a non-matching size means the dims came
+ * from conditioning media, and recalling that media locks the size anyway.
+ */
+export const getVideoSizeRecall = (
+ model: MainModelConfig,
+ width: number | null,
+ height: number | null
+): { aspectRatioId: VideoAspectRatioId; targetResolution: VideoTargetResolution } | null => {
+ if (width === null || height === null || width <= 0 || height <= 0) {
+ return null;
+ }
+
+ for (const aspectRatioId of getVideoAspectRatioOptions(model)) {
+ for (const option of getVideoTargetResolutionOptions(model)) {
+ const derived = getVideoDimensions(model, {
+ aspectRatioId,
+ firstFrameImage: null,
+ lastFrameImage: null,
+ sourceVideo: null,
+ targetResolution: option.id,
+ });
+
+ if (derived && derived.width === width && derived.height === height) {
+ return { aspectRatioId, targetResolution: option.id };
+ }
+ }
+ }
+
+ return null;
+};
+
+/**
+ * Whether the recalled LoRA list is exactly what the accelerator toggle would
+ * install for this model — if so the flag (and its recorded keys) come back
+ * on, so the panel shows the same fast-path state that produced the video.
+ */
+export const deriveAcceleratorRecallState = (
+ model: MainModelConfig,
+ models: readonly ModelConfig[],
+ loras: readonly GenerateLora[],
+ steps: number,
+ settings: VideoWidgetValues
+): Pick<VideoWidgetValues, 'acceleratorEnabled' | 'acceleratorLoraKeys'> => {
+ const accelerator = getVideoModelPolicy(model, settings).ui.accelerator;
+
+ if (!accelerator || steps !== accelerator.steps) {
+ return { acceleratorEnabled: false, acceleratorLoraKeys: [] };
+ }
+
+ const expected =
+ model.base === 'minimax-h3'
+ ? [findMiniMaxH3TurboLora(models)].flatMap((lora) => (lora ? [lora.key] : []))
+ : (() => {
+ const pair = findWanLightningLoraPair(models, model.variant);
+
+ return pair ? [pair.high.key, pair.low.key] : [];
+ })();
+ const present = expected.length > 0 && expected.every((key) => loras.some((lora) => lora.model.key === key));
+
+ return present
+ ? { acceleratorEnabled: true, acceleratorLoraKeys: expected }
+ : { acceleratorEnabled: false, acceleratorLoraKeys: [] };
+};
+
+export const getVideoRecallCapabilities = (metadata: unknown): VideoRecallCapabilities => {
+ if (!isVideoGenerationMetadata(metadata)) {
+ return EMPTY_VIDEO_RECALL_CAPABILITIES;
+ }
+
+ const prompts = hasPrompt(metadata);
+ const seed = getSeed(metadata) !== null;
+ const media = getRecallableMediaNames(metadata);
+ const hasNonSeed =
+ prompts ||
+ getMetadataModelKey(metadata, 'model') !== null ||
+ getInteger(metadata, 'num_frames') !== null ||
+ getInteger(metadata, 'steps') !== null ||
+ getNumber(metadata, 'cfg_scale') !== null ||
+ getMetadataLoras(metadata).length > 0 ||
+ media.firstFrameName !== null ||
+ media.lastFrameName !== null ||
+ media.sourceVideoName !== null;
+
+ return {
+ all: hasNonSeed || seed,
+ prompts,
+ remix: hasNonSeed,
+ seed,
+ };
+};
+
+/**
+ * Media names survive as a separate result field: the executor resolves them
+ * against the gallery (existence + dimensions/probe data the metadata does not
+ * carry) before they become widget values.
+ */
+export interface VideoRecallMediaNames {
+ firstFrameName: string | null;
+ lastFrameName: string | null;
+ sourceVideoName: string | null;
+}
+
+export const buildVideoRecallSettings = ({
+ currentValues,
+ kind,
+ metadata,
+ models,
+}: {
+ currentValues: VideoWidgetValues;
+ kind: VideoRecallKind;
+ metadata: unknown;
+ models: readonly ModelConfig[];
+}): (VideoRecallResult & { mediaNames: VideoRecallMediaNames }) | null => {
+ if (!isVideoGenerationMetadata(metadata)) {
+ return null;
+ }
+
+ const fields: VideoRecalledField[] = [];
+ let values: VideoWidgetValues = { ...currentValues };
+ let promptPatch: ProjectPromptDraftPatch | null = null;
+ const mediaNames: VideoRecallMediaNames = { firstFrameName: null, lastFrameName: null, sourceVideoName: null };
+
+ if (kind === 'all' || kind === 'prompts' || kind === 'remix') {
+ const { negativePrompt, positivePrompt } = getMetadataPrompts(metadata);
+
+ if (positivePrompt !== null || negativePrompt !== undefined) {
+ // A disabled negative submits as '' — an empty recorded negative is
+ // indistinguishable from disabled, so it must not flip the toggle on
+ // (or erase a saved-but-disabled draft's enabled state).
+ promptPatch = {
+ ...(positivePrompt !== null ? { positivePrompt } : {}),
+ ...(typeof negativePrompt === 'string' && negativePrompt.length > 0
+ ? { negativePrompt, negativePromptEnabled: true }
+ : negativePrompt === null
+ ? { negativePrompt: '', negativePromptEnabled: false }
+ : {}),
+ };
+ fields.push('prompts');
+ }
+ }
+
+ if (kind === 'prompts') {
+ return fields.length > 0 ? { fields, mediaNames, promptPatch, values } : null;
+ }
+
+ if (kind === 'all' || kind === 'seed') {
+ const seed = getSeed(metadata);
+
+ if (seed !== null) {
+ values = { ...values, seed, shouldRandomizeSeed: false };
+ fields.push('seed');
+ }
+ }
+
+ if (kind === 'seed') {
+ return fields.length > 0 ? { fields, mediaNames, promptPatch, values } : null;
+ }
+
+ // all / remix from here on.
+ const recalledModel = getSupportedVideoMetadataModel(metadata, models);
+ const model = recalledModel ?? values.model;
+
+ if (recalledModel && recalledModel.key !== values.model?.key) {
+ // The canonical family transition first, so frames/fps/resolution snap to
+ // the recalled model before its recorded values land on top.
+ values = {
+ ...getVideoModelSelectionResult({ currentSettings: values, model: recalledModel, models }).settings,
+ model: recalledModel,
+ };
+ fields.push('model');
+ } else if (recalledModel) {
+ fields.push('model');
+ }
+
+ if (!model) {
+ // Without any model, nothing below can validate; prompts/seed may still
+ // have been recalled.
+ return fields.length > 0 ? { fields, mediaNames, promptPatch, values } : null;
+ }
+
+ const numFrames = getInteger(metadata, 'num_frames');
+
+ if (numFrames !== null && numFrames > 0) {
+ const snapped = isValidVideoNumFrames(model, numFrames) ? numFrames : snapVideoNumFrames(model, numFrames);
+
+ if (snapped !== values.numFrames) {
+ values = { ...values, numFrames: snapped };
+ }
+ fields.push('frames');
+ }
+
+ const steps = getInteger(metadata, 'steps');
+
+ if (steps !== null && steps >= 1) {
+ values = { ...values, steps };
+ fields.push('steps');
+ }
+
+ const cfgScale = getNumber(metadata, 'cfg_scale');
+ const cfgScaleLowNoise = getNumber(metadata, 'guidance_scale_low_noise');
+ const policy = getVideoModelPolicy(model, values);
+
+ if (policy.ui.cfgVisible && cfgScale !== null && cfgScale >= 1) {
+ values = {
+ ...values,
+ cfgScale,
+ // The graph records the key only when the setting was non-null; absence
+ // means "reuse the primary CFG", so restore that exact semantics.
+ ...(policy.ui.cfgLowNoiseVisible
+ ? { cfgScaleLowNoise: cfgScaleLowNoise !== null && cfgScaleLowNoise >= 0 ? cfgScaleLowNoise : null }
+ : {}),
+ };
+ fields.push('cfg');
+ }
+
+ const sizeRecall = getVideoSizeRecall(model, getInteger(metadata, 'width'), getInteger(metadata, 'height'));
+
+ if (sizeRecall) {
+ values = { ...values, ...sizeRecall };
+ fields.push('size');
+ }
+
+ const recordedLoras = getMetadataLoras(metadata);
+ const resolvedLoras = recordedLoras.flatMap((entry) => {
+ const installed = models.find((candidate) => candidate.key === entry.key);
+
+ return installed && isLoraModelConfig(installed) && isLoraCompatibleWithModel(installed, model)
+ ? [{ isEnabled: true, model: installed as LoraModelConfig, weight: entry.weight }]
+ : [];
+ });
+
+ // The recall reproduces the recorded LoRA set: empty when the video ran
+ // without LoRAs, and also when the recorded ones are no longer installed —
+ // keeping the panel's current LoRAs would misrepresent the run either way.
+ if (resolvedLoras.length > 0 || values.loras.length > 0) {
+ values = {
+ ...values,
+ loras: resolvedLoras,
+ ...deriveAcceleratorRecallState(model, models, resolvedLoras, values.steps, values),
+ };
+ fields.push('loras');
+ }
+
+ let componentsRecalled = false;
+
+ for (const [metadataKey, valuesKey] of VIDEO_COMPONENT_METADATA_KEYS) {
+ const recordedKey = getMetadataModelKey(metadata, metadataKey);
+
+ if (!recordedKey) {
+ continue;
+ }
+
+ const installed = models.find((candidate) => candidate.key === recordedKey);
+
+ if (installed) {
+ values = { ...values, [valuesKey]: installed };
+ componentsRecalled = true;
+ }
+ }
+
+ if (componentsRecalled) {
+ fields.push('components');
+ }
+
+ const media = getRecallableMediaNames(metadata);
+ // Judged against the ORIGINAL panel state: the model transition above may
+ // already have cleared media the new family cannot consume, and that change
+ // is still part of what this recall did.
+ const hadMedia = Boolean(currentValues.firstFrameImage || currentValues.lastFrameImage || currentValues.sourceVideo);
+
+ // Media selects the graph family (t2v vs i2v vs extend), so an all/remix
+ // recall must reproduce the recorded media EXACTLY: whatever the panel held
+ // is cleared, and the executor re-hydrates the recorded names on top.
+ if (hadMedia) {
+ values = { ...values, firstFrameImage: null, lastFrameImage: null, sourceVideo: null };
+ }
+
+ if (media.firstFrameName || media.lastFrameName || media.sourceVideoName) {
+ mediaNames.firstFrameName = media.firstFrameName;
+ mediaNames.lastFrameName = media.lastFrameName;
+ mediaNames.sourceVideoName = media.sourceVideoName;
+ fields.push('media');
+ } else if (hadMedia) {
+ fields.push('media');
+ }
+
+ return fields.length > 0 ? { fields, mediaNames, promptPatch, values } : null;
+};
+
+const VIDEO_RECALL_TITLES: Record<VideoRecallKind, string> = {
+ all: 'Recalled video data',
+ prompts: 'Recalled prompts',
+ remix: 'Remixed video',
+ seed: 'Recalled seed',
+};
+
+export const getVideoRecallTitle = (kind: VideoRecallKind): string => VIDEO_RECALL_TITLES[kind];
+
+const VIDEO_FIELD_LABELS: Record<VideoRecalledField, string> = {
+ cfg: 'CFG',
+ steps: 'steps',
+ components: 'components',
+ frames: 'frames',
+ loras: 'concepts',
+ media: 'conditioning media',
+ model: 'model',
+ prompts: 'prompts',
+ seed: 'seed',
+ size: 'size',
+};
+
+export const getVideoRecallMessage = (fields: readonly VideoRecalledField[]): string =>
+ `Applied ${fields.map((field) => VIDEO_FIELD_LABELS[field]).join(', ')}.`;