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.

fix(preview): Use menu and recall shortcuts for videos (#10114)

Lincoln Stein417f917b728c
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index b601d501ff..e14b254d3a 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -3366,6 +3366,8 @@
"searchPromptTriggers": "Search prompt triggers",
"selectComponent": "Select a component model…",
"selectImageFirst": "Select an image in Gallery or Preview first.",
+ "nothingSelected": "Nothing selected",
+ "selectImageOrVideoFirst": "Select an image or video in Gallery or Preview first.",
"selectMainModelBeforeConcepts": "Select a main model before adding concepts.",
"selectModel": "Select a model…",
"selectModelFirst": "Select a model first",
@@ -3799,6 +3801,7 @@
"unstarVideo": "Unstar video",
"use": "Use",
"useInGenerate": "Use this image in Generate",
+ "useThisVideo": "Use this video",
"showGallery": "Show Gallery"
},
"queue": {
@@ -5752,16 +5755,22 @@
"recall": {
"appliedFields": "Applied {{fields, list}}.",
"cannotRecallImage": "Cannot recall image data",
+ "cannotRecallVideo": "Cannot recall video data",
"conceptsNotRestored": "Concepts not restored: {{concepts}}.",
"fieldsApplied_one": "{{count}} field applied to Generate.",
"fieldsApplied_other": "{{count}} fields applied to Generate.",
"imageMetadataUnsupported": "This image does not include supported Generate metadata.",
+ "modelsUnavailableForVideoRecall": "The model library has not loaded. Try again once it has.",
"nothingRecalled": "No recallable image data",
"nothingRecalledVideo": "No recallable video data",
+ "nothingRecalledVideoSize": "Size not recalled",
"partiallyRecalled": "Some image data was not recalled",
"unnamedConcept": "unnamed concept",
"unnamedRefiner": "unnamed refiner",
"videoMetadataUnsupported": "This video does not include supported Video metadata.",
+ "videoSizeMediaConflict": "Media in the Video panel sets the output to {{effectiveWidth}}×{{effectiveHeight}}, so this video's {{width}}×{{height}} can't be applied. Remove that media to use this size.",
+ "videoSizeMediaUnresolvable": "Media in the Video panel has a shape this model can't use, so this video's {{width}}×{{height}} can't be applied. Remove that media to use this size.",
+ "videoSizeUnavailable": "This video's size ({{width}}×{{height}}) isn't available for the current Video model, or no model is selected.",
"fields": {
"cfg": "CFG",
"components": "components",
@@ -5782,7 +5791,8 @@
"dimensions": "Recalled image size",
"prompts": "Recalled prompts",
"remix": "Recalled remix settings",
- "seed": "Recalled seed"
+ "seed": "Recalled seed",
+ "size": "Recalled size"
},
"parameters": {
"applied": "Recalled parameters",
@@ -6077,7 +6087,8 @@
"useAsReferenceImage": "Use as reference image",
"useAsReferenceImageHint": "Adds it to Generate's references",
"useAsReferenceVideo": "Use as reference video",
- "useImageAs": "Use image as"
+ "useImageAs": "Use image as",
+ "useVideoAs": "Use video as"
},
"mediaCountsTwo": "{{first}} and {{second}}",
"mediaCountsThree": "{{first}}, {{second}}, and {{third}}",
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.browser.test.tsx
index 7c6bc59905..14c671c1db 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.browser.test.tsx
@@ -1,9 +1,13 @@
-import type { GalleryImage } from '@features/gallery';
+import type { GalleryImage, GalleryVideoItem } from '@features/gallery';
import type * as GalleryBackendModule from '@features/gallery/data/backend';
import type { ModelConfig } from '@features/models';
import type { ControlLayerRejection } from '@workbench/widgets/canvas/invoke/prepareCanvasInvocation';
-import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
+import { setArchitectureCapabilities } from '@features/generation/core/architectureCapabilities';
+import {
+ architectureCapabilitiesFixture,
+ seedArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities.testing';
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { QueryClient } from '@tanstack/react-query';
import { FocusRegionProvider } from '@workbench/focusRegions';
@@ -12,7 +16,7 @@ import { createInstance } from 'i18next';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider, initReactI18next } from 'react-i18next';
-import { afterEach, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { useRegisterFirstPartyCommands } from './firstPartyCommands';
@@ -31,19 +35,25 @@ const workbench = vi.hoisted(() => ({
}));
const recallFixtures = vi.hoisted(() => ({
image: null as unknown,
+ item: null as unknown,
metadata: vi.fn(),
models: [] as unknown[],
+ videoMetadata: vi.fn(),
}));
vi.mock('@workbench/activeInvocationSubmission', () => ({ submitActiveInvocation }));
-vi.mock('@workbench/image-actions/selectedImage', () => ({
+vi.mock('@workbench/image-actions/selectedImage', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
getSelectedGalleryImage: () => recallFixtures.image,
+ getSelectedGalleryItem: () => recallFixtures.item,
}));
vi.mock('@features/gallery/data/backend', async (importOriginal) => ({
...(await importOriginal<typeof GalleryBackendModule>()),
getGalleryImageMetadata: recallFixtures.metadata,
+ getGalleryVideoMetadata: recallFixtures.videoMetadata,
}));
-vi.mock('@workbench/WorkbenchContext', () => {
+// Partial: the video recall loads through the image-actions entry, whose menus import the rest of this module.
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => {
const getProject = () => ({
id: 'project-1',
invocation: { sourceId: 'generate' },
@@ -53,6 +63,7 @@ vi.mock('@workbench/WorkbenchContext', () => {
});
return {
+ ...(await importOriginal<Record<string, unknown>>()),
useWorkbenchCommands: () => workbench.commands,
useWorkbenchExtensions: () => ({
commands: {
@@ -117,6 +128,9 @@ afterEach(async () => {
handlers.clear();
submitActiveInvocation.mockClear();
recallFixtures.metadata.mockReset();
+ recallFixtures.videoMetadata.mockReset();
+ recallFixtures.image = null;
+ recallFixtures.item = null;
workbench.commands = { layout: {}, notifications: {}, queue: {}, widgets: {} };
workbench.generateValues = {};
});
@@ -192,6 +206,140 @@ it('recalls from hotkeys on top of recalls and edits committed while the image r
expect(workbench.generateValues).toMatchObject({ positivePrompt: 'recalled prompt', seed: 7, steps: 42 });
});
+describe('viewer recall keys on a selected video', () => {
+ const wanModel = {
+ base: 'wan',
+ file_size: 1,
+ format: 'diffusers',
+ hash: 'wan-hash',
+ key: 'wan-t2v',
+ name: 'Wan 2.2 t2v_a14b',
+ path: '/models/wan',
+ source: 'local',
+ source_type: 'path',
+ type: 'main',
+ variant: 't2v_a14b',
+ } as ModelConfig;
+ const video: GalleryVideoItem = {
+ boardId: 'none',
+ category: 'general',
+ createdAt: '2026-08-26T00:00:00.000Z',
+ durationSeconds: 5,
+ fullUrl: '/clip.mp4',
+ height: 1280,
+ isIntermediate: false,
+ kind: 'video',
+ name: 'clip.mp4',
+ starred: false,
+ thumbnailUrl: '/clip-thumb.jpg',
+ width: 720,
+ };
+
+ const pressOnVideo = async (commandId: string) => {
+ const patchValues = vi.fn();
+ const open = vi.fn();
+
+ accountLifecycle.activate('hotkey-video-recall-account');
+ // Activation clears the seeded capabilities; seed them again for this account.
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+ recallFixtures.item = video;
+ recallFixtures.models = [wanModel];
+ recallFixtures.videoMetadata.mockResolvedValue({
+ generation_mode: 'wan_t2v',
+ height: 1280,
+ model: { base: 'wan', key: wanModel.key, name: wanModel.name, type: 'main' },
+ positive_prompt: 'a fox running',
+ seed: 4321,
+ width: 720,
+ });
+ workbench.queryClient = new QueryClient();
+ workbench.commands = {
+ layout: {},
+ notifications: { add: vi.fn() },
+ queue: {},
+ widgets: { open, patchValues },
+ };
+ await renderCommands();
+ await act(async () => {
+ await handlers.get(commandId)?.();
+ });
+
+ return { open, patchValues };
+ };
+
+ it('remixes the video into the Video panel and opens it, not Generate', async () => {
+ const { open, patchValues } = await pressOnVideo('viewer.remix');
+
+ expect(recallFixtures.metadata).not.toHaveBeenCalled();
+ expect(patchValues).toHaveBeenCalledExactlyOnceWith(
+ 'video',
+ expect.objectContaining({ positivePrompt: 'a fox running' }),
+ 'project-1'
+ );
+ // Remix keeps the panel's seed.
+ expect(patchValues.mock.calls[0]?.[1]).not.toMatchObject({ seed: 4321 });
+ expect(open).toHaveBeenCalledWith(expect.objectContaining({ widgetId: 'video' }));
+ });
+
+ it('recalls the size alone for Use Size', async () => {
+ const { open, patchValues } = await pressOnVideo('viewer.useSize');
+
+ const [widget, values] = patchValues.mock.calls[0] ?? [];
+ expect(widget).toBe('video');
+ expect(values).toMatchObject({ aspectRatioId: '9:16', targetResolution: '720p' });
+ expect(values).not.toMatchObject({ positivePrompt: 'a fox running' });
+ expect(open).toHaveBeenCalledWith(expect.objectContaining({ widgetId: 'video' }));
+ });
+
+ it('keeps a selected image on the image recall', async () => {
+ const sdxl = { ...wanModel, base: 'sdxl', format: 'checkpoint', key: 'sdxl-model', name: 'SDXL' } as ModelConfig;
+
+ accountLifecycle.activate('hotkey-video-recall-account');
+ // Activation clears the seeded capabilities; seed them again for this account.
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+ // A video item is selected too; the image answer wins, exactly as before videos were recalled.
+ recallFixtures.item = video;
+ recallFixtures.image = {
+ boardId: 'none',
+ height: 768,
+ imageCategory: 'general',
+ imageName: 'selected.png',
+ imageUrl: '/selected.png',
+ queuedAt: '2026-06-19T00:00:00.000Z',
+ sourceQueueItemId: 'backend-gallery',
+ starred: false,
+ thumbnailUrl: '/selected-thumb.png',
+ width: 512,
+ } satisfies GalleryImage;
+ recallFixtures.models = [sdxl];
+ recallFixtures.metadata.mockResolvedValue({ seed: 7 });
+ workbench.queryClient = new QueryClient();
+ workbench.generateValues = { modelKey: sdxl.key, steps: 20 };
+ const patchValues = vi.fn();
+ const open = vi.fn();
+ workbench.commands = {
+ generation: {
+ setSettings: (values: Record<string, unknown>) => {
+ workbench.generateValues = values;
+ },
+ },
+ layout: {},
+ notifications: { add: vi.fn() },
+ queue: {},
+ widgets: { open, patchValues },
+ };
+ await renderCommands();
+ await act(async () => {
+ await handlers.get('viewer.recallSeed')?.();
+ });
+
+ expect(workbench.generateValues).toMatchObject({ seed: 7 });
+ expect(recallFixtures.videoMetadata).not.toHaveBeenCalled();
+ expect(patchValues).not.toHaveBeenCalled();
+ expect(open).toHaveBeenCalledWith(expect.objectContaining({ widgetId: 'generate' }));
+ });
+});
+
it('words a blocked control layer from the locale when Invoke runs from its hotkey', async () => {
await renderCommands();
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
index bd1ddb127c..a867c1f5f7 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts
@@ -1,4 +1,7 @@
+import type { GalleryVideoItem } from '@features/gallery';
+import type { AccountScope } from '@platform/state/accountLifecycle';
import type { ImageRecallKind } from '@workbench/image-actions/imageRecall';
+import type { VideoRecallKind } from '@workbench/image-actions/videoRecall';
import type { ResultDestination } from '@workbench/invocationContracts';
import {
@@ -51,6 +54,15 @@ const imageRecallCommands: Record<string, ImageRecallKind> = {
'viewer.useSize': 'dimensions',
};
+/** The same keys on a selected video; it has no CLIP skip, and its size verb is `size`. */
+const videoRecallKinds: Partial<Record<ImageRecallKind, VideoRecallKind>> = {
+ all: 'all',
+ dimensions: 'size',
+ prompts: 'prompts',
+ remix: 'remix',
+ seed: 'seed',
+};
+
export const FIRST_PARTY_APP_COMMAND_IDS = [
...regionFocusHotkeys.map(({ commandId }) => commandId),
...widgetCycleHotkeys.map(({ commandId }) => commandId),
@@ -137,8 +149,8 @@ export const useRegisterFirstPartyCommands = () => {
notifications.add({
actions: [{ kind: 'open-widget', widgetId: 'gallery' }],
kind: 'info',
- message: 'Select an image in Gallery or Preview first.',
- title: 'No image selected',
+ message: t('widgets.generate.selectImageOrVideoFirst'),
+ title: t('widgets.generate.nothingSelected'),
});
const loadSelectedItemWorkflow = async () => {
@@ -179,7 +191,7 @@ export const useRegisterFirstPartyCommands = () => {
const owner = captureAccountScope();
try {
- const [{ executeImageRecall }, { getSelectedGalleryImage }] = await Promise.all([
+ const [{ executeImageRecall }, { getSelectedGalleryImage, getSelectedGalleryItem }] = await Promise.all([
import('@workbench/image-actions/executeImageRecall'),
import('@workbench/image-actions/selectedImage'),
]);
@@ -189,7 +201,14 @@ export const useRegisterFirstPartyCommands = () => {
const image = getSelectedGalleryImage(activeProject);
if (!image) {
- notifyNoImageSelected();
+ const item = getSelectedGalleryItem(activeProject);
+ const videoKind = videoRecallKinds[kind];
+
+ if (item?.kind === 'video' && videoKind) {
+ await recallSelectedVideo(item, videoKind, owner, activeProject.id);
+ } else {
+ notifyNoImageSelected();
+ }
return;
}
@@ -230,6 +249,40 @@ export const useRegisterFirstPartyCommands = () => {
}
};
+ const recallSelectedVideo = async (
+ item: GalleryVideoItem,
+ kind: VideoRecallKind,
+ owner: AccountScope,
+ projectId: string
+ ) => {
+ // Through the entry the gallery's actions already load on every editor route: naming the module itself would split
+ // it out of their chunk, at two more boot requests.
+ const { executeVideoRecall } = await import('@workbench/image-actions');
+
+ assertAccountScopeCurrent(owner);
+ const didRecall = await executeVideoRecall({
+ commands,
+ // Re-read on every call, as for images: recall awaits the video's metadata.
+ getVideoValues: () => {
+ const project = queries.getProject(projectId);
+
+ return project ? getProjectWidgetValues(project, 'video') : {};
+ },
+ item,
+ kind,
+ models: getAvailableModels() ?? [],
+ owner,
+ projectId,
+ queryClient,
+ t,
+ });
+
+ assertAccountScopeCurrent(owner);
+ if (didRecall && queries.isActiveProject(projectId)) {
+ openWidgetPlacement({ getWidgetsForRegion, options: { preferredRegions: ['left'] }, typeId: 'video', widgets });
+ }
+ };
+
useMountEffect(() =>
commandApi.register({
handler: toggleCommandPalette,
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 411e3e5ec0..9ec994ae59 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
@@ -21,7 +21,7 @@ import { userEvent } from 'vitest/browser';
import type * as ModelOnlyUpscaleModule from './modelOnlyUpscale';
import type { ImageActions } from './useImageActions';
-import { ImageContextMenu, type ImageContextMenuTarget } from './ImageContextMenu';
+import { ImageContextMenu, type ImageContextMenuTarget, type ImageContextMenuVariant } from './ImageContextMenu';
import { EMPTY_IMAGE_RECALL_CAPABILITIES } from './imageRecall';
const NO_BOARDS: [] = [];
@@ -278,7 +278,8 @@ const renderItemMenu = async (
onCopyCurrentFrame: () => void;
onOpenDetails: () => void;
},
- queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }),
+ variant?: ImageContextMenuVariant
) => {
host = document.createElement('div');
document.body.append(host);
@@ -293,6 +294,7 @@ const renderItemMenu = async (
boards={NO_BOARDS}
previewVideoActions={previewVideoActions}
target={target as unknown as ImageContextMenuTarget}
+ variant={variant}
onClose={vi.fn()}
/>
</ChakraProvider>
@@ -681,10 +683,10 @@ describe('ImageContextMenu video placement', () => {
const actions = { ...createActions(vi.fn()), canUseAsReferenceVideo: true };
await renderVideoMenu(actions, video);
- await interact(() => getMenuItem('widgets.gallery.itemMenu.extendInVideo').click());
+ await pickItem('widgets.gallery.itemMenu.extendInVideo');
expect(actions.sendToInitialVideo).toHaveBeenCalledExactlyOnceWith(video);
- await interact(() => getMenuItem('widgets.gallery.itemMenu.useAsReferenceVideo').click());
+ await pickItem('widgets.gallery.itemMenu.useAsReferenceVideo');
expect(actions.useAsReferenceVideo).toHaveBeenCalledExactlyOnceWith(video);
});
@@ -771,6 +773,30 @@ describe('ImageContextMenu video placement', () => {
await vi.waitFor(() => expect(isDisabled('widgets.gallery.itemActions.recall.verbs.prompts')).toBe(false));
expect(isDisabled('widgets.gallery.itemActions.recall.verbs.seed')).toBe(false);
+ // The record names no size, so Use Size stays off.
+ expect(isDisabled('widgets.gallery.itemActions.recall.verbs.dimensions')).toBe(true);
+ });
+
+ it('lists the reuse verbs remix first, Use Size last, and recalls the size the record names', async () => {
+ galleryMock.videoMetadata.mockResolvedValueOnce({ generation_mode: 'wan_t2v', height: 720, width: 1280 });
+ const video = item('video', 'sized.mp4');
+ const actions = createActions(vi.fn());
+ await renderVideoMenu(actions, video);
+ await openReuseSubmenu();
+
+ const reuseLabels = [
+ 'widgets.gallery.itemMenu.remixVideo',
+ 'widgets.gallery.itemMenu.allSettings',
+ 'widgets.gallery.itemActions.recall.verbs.prompts',
+ 'widgets.gallery.itemActions.recall.verbs.seed',
+ 'widgets.gallery.itemActions.recall.verbs.dimensions',
+ ];
+ const menuLabels = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]')).map(itemLabel);
+ expect(menuLabels.filter((label) => label && reuseLabels.includes(label))).toEqual(reuseLabels);
+
+ await vi.waitFor(() => expect(isDisabled('widgets.gallery.itemActions.recall.verbs.dimensions')).toBe(false));
+ await pickItem('widgets.gallery.itemActions.recall.verbs.dimensions');
+ expect(actions.recallVideoData).toHaveBeenCalledExactlyOnceWith(video, 'size');
});
it("reads a video's metadata once across opens, and reads a failed one again on the next open", async () => {
@@ -838,7 +864,7 @@ describe('ImageContextMenu video placement', () => {
await renderVideoMenu(actions, video);
await openConditioningSubmenu();
- await interact(() => getMenuItem('widgets.video.conditioningRoleAudio').click());
+ await pickItem('widgets.video.conditioningRoleAudio');
expect(actions.useAsConditioningClip).toHaveBeenCalledExactlyOnceWith(video, 'audio');
});
@@ -850,7 +876,7 @@ describe('ImageContextMenu video placement', () => {
await openConditioningSubmenu();
expect(getMenuItem('widgets.video.conditioningRoleAudio').getAttribute('aria-disabled')).toBe('true');
- await interact(() => getMenuItem('widgets.video.conditioningRoleVideo').click());
+ await pickItem('widgets.video.conditioningRoleVideo');
expect(actions.useAsConditioningClip).toHaveBeenCalledExactlyOnceWith(video, 'video');
});
@@ -923,6 +949,44 @@ describe('ImageContextMenu mixed-media action visibility', () => {
expect(onCopyCurrentFrame).not.toHaveBeenCalled();
});
+ it("keeps only housekeeping in a Preview video's housekeeping menu, leaving use and reuse to the Use menu", async () => {
+ const video = item('video', 'preview.mp4');
+ await renderItemMenu(
+ createActions(vi.fn()),
+ { itemRefs: [{ kind: 'video', name: video.name }], items: [video], x: 20, y: 20 },
+ {
+ isCopyCurrentFrameAvailable: true,
+ itemKey: 'video:preview.mp4',
+ onCopyCurrentFrame: vi.fn(),
+ onOpenDetails: vi.fn(),
+ },
+ undefined,
+ 'housekeeping'
+ );
+
+ // The quick row stays, as for an image's housekeeping menu.
+ for (const label of [
+ 'widgets.gallery.itemMenu.openInNewTab',
+ 'widgets.gallery.itemMenu.downloadVideo',
+ 'widgets.gallery.itemMenu.openInPreview',
+ 'widgets.preview.starVideo',
+ ]) {
+ expect(document.querySelector(`[aria-label="${label}"]`)).not.toBeNull();
+ }
+ const rowLabels = Array.from(document.querySelectorAll<HTMLElement>('[role="menuitem"]'))
+ .filter((candidate) => !candidate.hasAttribute('aria-label'))
+ .map(itemLabel);
+ expect(rowLabels).toEqual([
+ 'widgets.gallery.itemActions.loadWorkflow.label',
+ 'widgets.preview.copyCurrentFrame',
+ 'widgets.preview.videoDetails',
+ 'widgets.gallery.findInGallery',
+ 'widgets.gallery.changeBoard',
+ 'widgets.gallery.itemMenu.deleteVideo',
+ ]);
+ expect(galleryMock.videoMetadata).not.toHaveBeenCalledWith('preview.mp4', expect.anything());
+ });
+
it('hides Preview video extras when the captured menu target is no longer the selected video', async () => {
const video = item('video', 'stale-menu.mp4');
await renderItemMenu(
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
index 66ee7d989e..90eaeb7172 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
@@ -1,6 +1,5 @@
import type { GalleryBoard, GalleryImage, GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery';
import type { GalleryItemContextMenuTarget } from '@features/gallery/react';
-import type { VideoConditioningRole } from '@features/video';
import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';
import {
@@ -11,7 +10,7 @@ import {
toGalleryItemKey,
} from '@features/gallery';
import { getGalleryMoveTargets } from '@features/gallery/contracts';
-import { galleryKeys, galleryVideoMetadataOptions } from '@features/gallery/queries';
+import { galleryKeys } from '@features/gallery/queries';
import { canCopyImage } from '@platform/browser/clipboard';
import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
import { ApiError } from '@platform/transport/http';
@@ -21,9 +20,6 @@ import { useQuery } from '@tanstack/react-query';
import { formatHotkeyPartLabel } from '@workbench/hotkeys/keys';
import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';
import {
- ClapperboardIcon,
- AsteriskIcon,
- AudioLinesIcon,
BoxIcon,
CopyIcon,
CrosshairIcon,
@@ -31,13 +27,8 @@ import {
ExternalLinkIcon,
EyeIcon,
FileJsonIcon,
- FilmIcon,
FolderIcon,
- ImagePlayIcon,
ImagesIcon,
- QuoteIcon,
- ShuffleIcon,
- SproutIcon,
StarIcon,
Trash2Icon,
WorkflowIcon,
@@ -51,9 +42,8 @@ import type { ImageActions } from './useImageActions';
import { ContextSubMenu, IMAGE_MENU_CONTENT_PROPS } from './ContextSubMenu';
import { GalleryBoardDestinationGroups } from './GalleryBoardDestinationGroups';
-import { ImageContinueGroup, ImageUseGroups } from './ImageItemMenuGroups';
+import { ImageContinueGroup, ImageUseGroups, VideoUseGroups } from './ImageItemMenuGroups';
import { useImageRecallCapabilities } from './useImageRecallCapabilities';
-import { EMPTY_VIDEO_RECALL_CAPABILITIES, getVideoRecallCapabilities, type VideoRecallKind } from './videoRecall';
export interface LegacyImageContextMenuTarget {
/** Right-clicked image first; more entries switch the menu into bulk mode. */
@@ -66,7 +56,8 @@ export type ImageContextMenuTarget = LegacyImageContextMenuTarget | GalleryItemC
/**
* `housekeeping` leaves out the groups a host already offers beside the menu (Preview's Edit and Use menus): what to
- * continue working on with the image and what to take from it. Single images only; videos and selections stay full.
+ * continue working on with the image, and what to take from the image or video. Single items only; selections stay
+ * full.
*/
export type ImageContextMenuVariant = 'full' | 'housekeeping';
@@ -181,6 +172,7 @@ export const ImageContextMenu = ({
boards={boards}
previewVideoActions={previewVideoActions}
target={itemTarget}
+ variant={variant}
onClose={onClose}
onRequestDeletion={requestDeletion}
/>
@@ -192,6 +184,7 @@ const GalleryItemContextMenuContent = ({
boards,
previewVideoActions,
target,
+ variant,
onClose,
onRequestDeletion,
}: {
@@ -199,6 +192,7 @@ const GalleryItemContextMenuContent = ({
boards: GalleryBoard[];
previewVideoActions?: PreviewVideoContextActions;
target: GalleryItemContextMenuTarget;
+ variant: ImageContextMenuVariant;
onClose: () => void;
onRequestDeletion: (itemRefs: GalleryItemRef[]) => void;
}) => {
@@ -262,6 +256,7 @@ const GalleryItemContextMenuContent = ({
item={item}
itemRef={itemRef}
previewVideoActions={previewVideoActions}
+ variant={variant}
onRequestDeletion={onRequestDeletion}
/>
)}
@@ -278,6 +273,7 @@ const SingleItemMenuItems = ({
item,
itemRef,
previewVideoActions,
+ variant,
onRequestDeletion,
}: {
actions: ImageActions;
@@ -285,6 +281,7 @@ const SingleItemMenuItems = ({
item: GalleryItem;
itemRef: GalleryItemRef;
previewVideoActions?: PreviewVideoContextActions;
+ variant: ImageContextMenuVariant;
onRequestDeletion: (itemRefs: GalleryItemRef[]) => void;
}) => {
const { t } = useTranslation();
@@ -305,12 +302,6 @@ const SingleItemMenuItems = ({
const owner = captureAccountScope();
const videoItem = item.kind === 'video' ? item : null;
const videoName = videoItem?.name ?? '';
- // The gallery's shared entry, which Preview Details and recall commands also read; a failed read holds no answer, so
- // the next open reads it again.
- const videoMetadataQuery = useQuery({
- ...galleryVideoMetadataOptions(owner, videoName),
- enabled: videoItem !== null,
- });
// The record answers whether a workflow is embedded only when the listing did not say.
const readsVideoRecord = videoItem !== null && videoItem.hasWorkflow === undefined;
const videoHasWorkflowQuery = useQuery({
@@ -340,10 +331,6 @@ const SingleItemMenuItems = ({
retry: false,
staleTime: Infinity,
});
- const isLoadingVideoRecall = videoMetadataQuery.isPending;
- const videoRecallCapabilities = videoMetadataQuery.isSuccess
- ? getVideoRecallCapabilities(videoMetadataQuery.data)
- : EMPTY_VIDEO_RECALL_CAPABILITIES;
const isLoadingVideoWorkflow = readsVideoRecord && videoHasWorkflowQuery.isPending;
const hasVideoWorkflow = readsVideoRecord ? videoHasWorkflowQuery.data === true : videoItem?.hasWorkflow === true;
const handleLoadVideoWorkflow = useCallback(() => {
@@ -352,41 +339,6 @@ const SingleItemMenuItems = ({
}
}, [actions, item]);
- 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') {
- actions.sendToInitialVideo(item);
- }
- }, [actions, item]);
- const handleUseAsReferenceVideo = useCallback(() => {
- if (item.kind === 'video') {
- // eslint-disable-next-line react/hooks -- `useAsReferenceVideo` is a plain action method; the compiler reads its name as a hook.
- actions.useAsReferenceVideo(item);
- }
- }, [actions, item]);
- const makeConditioningClipHandler = useCallback(
- (role: VideoConditioningRole) => () => {
- if (item.kind === 'video') {
- // eslint-disable-next-line react/hooks -- `useAsConditioningClip` is a plain action method; the compiler reads its name as a hook.
- actions.useAsConditioningClip(item, role);
- }
- },
- [actions, item]
- );
- const handleUseSoundtrack = useMemo(() => makeConditioningClipHandler('audio'), [makeConditioningClipHandler]);
- const handleUsePicture = useMemo(() => makeConditioningClipHandler('video'), [makeConditioningClipHandler]);
-
return (
<>
<HStack gap="1">
@@ -434,66 +386,13 @@ const SingleItemMenuItems = ({
value="load-video-workflow"
onClick={handleLoadVideoWorkflow}
/>
- <ContextSubMenu icon={AsteriskIcon} label={t('widgets.gallery.itemMenu.reuseFromVideo')}>
- <ContextMenuItem
- disabled={isLoadingVideoRecall || !videoRecallCapabilities.all}
- icon={AsteriskIcon}
- label={t('widgets.gallery.itemMenu.allSettings')}
- value="video-recall-all"
- onClick={handleVideoRecallAll}
- />
- <ContextMenuItem
- disabled={isLoadingVideoRecall || !videoRecallCapabilities.remix}
- icon={ShuffleIcon}
- label={t('widgets.gallery.itemMenu.remixVideo')}
- value="video-remix"
- onClick={handleVideoRecallRemix}
- />
- <ContextMenuItem
- disabled={isLoadingVideoRecall || !videoRecallCapabilities.prompts}
- icon={QuoteIcon}
- label={t('widgets.gallery.itemActions.recall.verbs.prompts')}
- value="video-use-prompt"
- onClick={handleVideoRecallPrompts}
- />
- <ContextMenuItem
- disabled={isLoadingVideoRecall || !videoRecallCapabilities.seed}
- icon={SproutIcon}
- label={t('widgets.gallery.itemActions.recall.verbs.seed')}
- value="video-use-seed"
- onClick={handleVideoRecallSeed}
- />
- </ContextSubMenu>
- <ContextMenuItem
- icon={ClapperboardIcon}
- label={t('widgets.gallery.itemMenu.extendInVideo')}
- value="extend-in-video"
- onClick={handleExtendInVideo}
- />
- <ContextMenuItem
- disabled={!actions.canUseAsReferenceVideo}
- icon={FilmIcon}
- label={t('widgets.gallery.itemMenu.useAsReferenceVideo')}
- value="use-as-reference-video"
- onClick={handleUseAsReferenceVideo}
- />
- <ContextSubMenu icon={AudioLinesIcon} label={t('widgets.gallery.itemMenu.useAsConditioningClip')}>
- <ContextMenuItem
- disabled={!actions.canUseAsConditioningClip.audio}
- icon={AudioLinesIcon}
- label={t('widgets.video.conditioningRoleAudio')}
- value="use-as-conditioning-audio"
- onClick={handleUseSoundtrack}
- />
- {/* A wrapped audio upload's picture is a placeholder, so it has nothing to lend. */}
- <ContextMenuItem
- disabled={!actions.canUseAsConditioningClip.video || item.mediaOrigin === 'audio_upload'}
- icon={ImagePlayIcon}
- label={t('widgets.video.conditioningRoleVideo')}
- value="use-as-conditioning-video"
- onClick={handleUsePicture}
- />
- </ContextSubMenu>
+ {variant === 'full' ? (
+ <>
+ <Menu.Separator borderColor="border.subtle" />
+ <VideoUseGroups actions={actions} item={item} presentation="compact" />
+ <Menu.Separator borderColor="border.subtle" />
+ </>
+ ) : null}
</>
) : null}
{item.kind === 'video' && previewVideoActions && previewVideoActions.itemKey === toGalleryItemKey(item) ? (
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageItemMenuGroups.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageItemMenuGroups.tsx
index 80df7adcee..0857c8f5b7 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageItemMenuGroups.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageItemMenuGroups.tsx
@@ -1,14 +1,17 @@
-import type { GalleryImage } from '@features/gallery';
+import type { GalleryImage, GalleryVideoItem } from '@features/gallery';
import type { ModelsSnapshot } from '@features/models';
import type { SpandrelModelConfig } from '@features/upscale';
+import type { VideoConditioningRole } from '@features/video';
import type { GalleryCanvasImportDestination } from '@workbench/canvas-operations/api';
import { Menu, Text } from '@chakra-ui/react';
+import { galleryVideoMetadataOptions } from '@features/gallery/queries';
import { ensureModelsLoaded, useModelsSelector } from '@features/models';
import { getModelOnlyUpscaleFactors, getSpandrelNativeScale } from '@features/upscale';
import { useMountEffect } from '@platform/react/useMountEffect';
import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { MenuActionItem, MenuItem } from '@platform/ui/Menu';
+import { useQuery } from '@tanstack/react-query';
import { ShortcutKeycaps } from '@workbench/hotkeys/keyGlyphs';
import { useShortcutBinding } from '@workbench/hotkeys/useShortcutBinding';
import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
@@ -16,9 +19,12 @@ import { LAYER_KIND_ICONS } from '@workbench/widgets/layers/layerTypeIcon';
import { useActiveProjectId, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import {
AsteriskIcon,
+ AudioLinesIcon,
ClapperboardIcon,
FileImageIcon,
+ FilmIcon,
ImageIcon,
+ ImagePlayIcon,
LayersIcon,
PencilIcon,
QuoteIcon,
@@ -39,6 +45,12 @@ import type { ImageRecallCapabilities, ImageRecallKind } from './imageRecall';
import type { ImageActions } from './useImageActions';
import { ContextSubMenu } from './ContextSubMenu';
+import {
+ EMPTY_VIDEO_RECALL_CAPABILITIES,
+ getVideoRecallCapabilities,
+ type VideoRecallCapabilities,
+ type VideoRecallKind,
+} from './videoRecall';
/*
* The image menus' shared groups, by intent: what to continue working on with the image, and what to take from it.
@@ -394,6 +406,193 @@ const ReuseMenuItem = ({
);
};
+interface VideoReuseItem {
+ capability: keyof VideoRecallCapabilities;
+ /** The viewer command that recalls the same from the selected video, for its keycaps. */
+ commandId: string;
+ icon: LucideIcon;
+ kind: VideoRecallKind;
+ label: string;
+ value: string;
+}
+
+/** In the image list's order: remix leads, the full recall follows, then the single settings. */
+const VIDEO_REUSE_ITEMS: readonly VideoReuseItem[] = [
+ {
+ capability: 'remix',
+ commandId: 'viewer.remix',
+ icon: ShuffleIcon,
+ kind: 'remix',
+ label: 'widgets.gallery.itemMenu.remixVideo',
+ value: 'video-remix',
+ },
+ {
+ capability: 'all',
+ commandId: 'viewer.recallAll',
+ icon: AsteriskIcon,
+ kind: 'all',
+ label: 'widgets.gallery.itemMenu.allSettings',
+ value: 'video-recall-all',
+ },
+ {
+ capability: 'prompts',
+ commandId: 'viewer.recallPrompts',
+ icon: QuoteIcon,
+ kind: 'prompts',
+ label: 'widgets.gallery.itemActions.recall.verbs.prompts',
+ value: 'video-use-prompt',
+ },
+ {
+ capability: 'seed',
+ commandId: 'viewer.recallSeed',
+ icon: SproutIcon,
+ kind: 'seed',
+ label: 'widgets.gallery.itemActions.recall.verbs.seed',
+ value: 'video-use-seed',
+ },
+ {
+ capability: 'size',
+ commandId: 'viewer.useSize',
+ icon: RulerIcon,
+ kind: 'size',
+ label: 'widgets.gallery.itemActions.recall.verbs.dimensions',
+ value: 'video-use-size',
+ },
+];
+
+/**
+ * "Use video as" and "Reuse from video": the video as a Video panel input, then its recorded settings. Reads the
+ * video's metadata when it mounts, so hosts mount it with their open menu. The entry is the gallery's shared one,
+ * which Preview Details and recall commands also read; a failed read holds no answer, so the next open reads it again.
+ */
+export const VideoUseGroups = ({
+ actions,
+ item,
+ presentation,
+}: {
+ actions: ImageActions;
+ item: GalleryVideoItem;
+ presentation: ImageMenuPresentation;
+}) => {
+ const { t } = useTranslation();
+ const metadataQuery = useQuery(galleryVideoMetadataOptions(captureAccountScope(), item.name));
+ const capabilities = metadataQuery.isSuccess
+ ? getVideoRecallCapabilities(metadataQuery.data)
+ : EMPTY_VIDEO_RECALL_CAPABILITIES;
+ const handleExtendInVideo = useCallback(() => actions.sendToInitialVideo(item), [actions, item]);
+ // eslint-disable-next-line react/hooks -- `useAsReferenceVideo` is a plain action method; the compiler reads its name as a hook.
+ const handleUseAsReferenceVideo = useCallback(() => actions.useAsReferenceVideo(item), [actions, item]);
+ const reuseItems = VIDEO_REUSE_ITEMS.map((reuseItem) => (
+ <VideoReuseMenuItem
+ key={reuseItem.kind}
+ actions={actions}
+ disabled={metadataQuery.isPending || !capabilities[reuseItem.capability]}
+ guided={presentation === 'guided'}
+ item={item}
+ reuseItem={reuseItem}
+ />
+ ));
+
+ return (
+ <>
+ <Menu.ItemGroup>
+ <Menu.ItemGroupLabel>{t('widgets.gallery.itemMenu.useVideoAs')}</Menu.ItemGroupLabel>
+ <MenuActionItem
+ icon={ClapperboardIcon}
+ label={t('widgets.gallery.itemMenu.extendInVideo')}
+ value="extend-in-video"
+ onSelect={handleExtendInVideo}
+ />
+ <MenuActionItem
+ disabled={!actions.canUseAsReferenceVideo}
+ icon={FilmIcon}
+ label={t('widgets.gallery.itemMenu.useAsReferenceVideo')}
+ value="use-as-reference-video"
+ onSelect={handleUseAsReferenceVideo}
+ />
+ <ContextSubMenu icon={AudioLinesIcon} label={t('widgets.gallery.itemMenu.useAsConditioningClip')}>
+ <ConditioningClipMenuItem actions={actions} conditioningRole="audio" item={item} />
+ <ConditioningClipMenuItem actions={actions} conditioningRole="video" item={item} />
+ </ContextSubMenu>
+ </Menu.ItemGroup>
+ {/* As for images: outside the "Use video as" group, so it is not announced under that heading. */}
+ {presentation === 'guided' ? (
+ <>
+ <Menu.Separator borderColor="border.subtle" />
+ <Menu.ItemGroup>
+ <Menu.ItemGroupLabel>{t('widgets.gallery.itemMenu.reuseFromVideo')}</Menu.ItemGroupLabel>
+ {reuseItems}
+ </Menu.ItemGroup>
+ </>
+ ) : (
+ <ContextSubMenu icon={AsteriskIcon} label={t('widgets.gallery.itemMenu.reuseFromVideo')}>
+ {reuseItems}
+ </ContextSubMenu>
+ )}
+ </>
+ );
+};
+
+const ConditioningClipMenuItem = ({
+ actions,
+ conditioningRole: role,
+ item,
+}: {
+ actions: ImageActions;
+ conditioningRole: VideoConditioningRole;
+ item: GalleryVideoItem;
+}) => {
+ const { t } = useTranslation();
+ // eslint-disable-next-line react/hooks -- `useAsConditioningClip` is a plain action method; the compiler reads its name as a hook.
+ const handleSelect = useCallback(() => actions.useAsConditioningClip(item, role), [actions, item, role]);
+
+ return (
+ <MenuActionItem
+ // A wrapped audio upload's picture is a placeholder, so it has nothing to lend.
+ disabled={!actions.canUseAsConditioningClip[role] || (role === 'video' && item.mediaOrigin === 'audio_upload')}
+ icon={role === 'audio' ? AudioLinesIcon : ImagePlayIcon}
+ label={t(role === 'audio' ? 'widgets.video.conditioningRoleAudio' : 'widgets.video.conditioningRoleVideo')}
+ value={`use-as-conditioning-${role}`}
+ onSelect={handleSelect}
+ />
+ );
+};
+
+const VideoReuseMenuItem = ({
+ actions,
+ disabled,
+ guided,
+ item,
+ reuseItem,
+}: {
+ actions: ImageActions;
+ disabled: boolean;
+ guided: boolean;
+ item: GalleryVideoItem;
+ reuseItem: VideoReuseItem;
+}) => {
+ const { t } = useTranslation();
+ const handleSelect = useCallback(
+ () => void actions.recallVideoData(item, reuseItem.kind),
+ [actions, item, reuseItem.kind]
+ );
+ const shortcut = useMemo(
+ () => (guided ? <CommandKeycaps commandId={reuseItem.commandId} /> : undefined),
+ [guided, reuseItem.commandId]
+ );
+
+ return (
+ <MenuActionItem
+ disabled={disabled}
+ icon={reuseItem.icon}
+ label={t(reuseItem.label)}
+ shortcut={shortcut}
+ value={reuseItem.value}
+ onSelect={handleSelect}
+ />
+ );
+};
+
/** The command's effective first binding, remaps included, as keycaps; nothing when it is unbound. */
const CommandKeycaps = ({ commandId }: { commandId: string }) => {
const binding = useShortcutBinding(commandId);
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 59c2b37948..361a073071 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.ts
@@ -231,7 +231,8 @@ describe('executeVideoRecall', () => {
getVideoValues: () => videoValues as unknown as Record<string, unknown>,
item,
kind: 'prompts',
- models: [],
+ // The panel's Wan main is not installed; only H3 is.
+ models: [h3Model],
});
expect(didRecall).toBe(true);
@@ -243,6 +244,54 @@ describe('executeVideoRecall', () => {
);
});
+ it('commits only the prompt keys of a prompts recall while the model catalog is empty', async () => {
+ videoMetadata.mockResolvedValue(metadata);
+ const { commands, patchValues } = createCommands();
+
+ const didRecall = await executeVideoRecall({
+ queryClient,
+ t,
+ commands,
+ getVideoValues: () => createDefaultVideoWidgetValues([wanModel]) as unknown as Record<string, unknown>,
+ item,
+ kind: 'prompts',
+ models: [],
+ });
+
+ expect(didRecall).toBe(true);
+ expect(patchValues).toHaveBeenCalledExactlyOnceWith(
+ 'video',
+ { negativePrompt: 'blurry', negativePromptEnabled: true, positivePrompt: 'a fox running' },
+ undefined
+ );
+ });
+
+ it.each(['all', 'remix', 'seed', 'size'] as const)(
+ 'writes nothing for %s while the model catalog is empty',
+ async (kind) => {
+ videoMetadata.mockResolvedValue(metadata);
+ const { commands, patchValues } = createCommands();
+
+ const didRecall = await executeVideoRecall({
+ queryClient,
+ t,
+ commands,
+ getVideoValues: () => createDefaultVideoWidgetValues([wanModel]) as unknown as Record<string, unknown>,
+ item,
+ kind,
+ models: [],
+ });
+
+ expect(didRecall).toBe(false);
+ expect(patchValues).not.toHaveBeenCalled();
+ expect(commands.notifications.add).toHaveBeenCalledExactlyOnceWith({
+ kind: 'info',
+ message: 'widgets.gallery.itemActions.recall.modelsUnavailableForVideoRecall',
+ title: 'widgets.gallery.itemActions.recall.cannotRecallVideo',
+ });
+ }
+ );
+
it('writes the whole values object when the recall carries more than prompts', async () => {
videoMetadata.mockResolvedValue(metadata);
const { commands, patchValues } = createCommands();
@@ -268,6 +317,161 @@ describe('executeVideoRecall', () => {
});
});
+ it('recalls only the size onto the panel model, reading none of the media the record names', async () => {
+ videoMetadata.mockResolvedValue({
+ ...metadata,
+ first_frame_image: { image_name: 'frame.png' },
+ height: 1280,
+ model: { base: 'minimax-h3', key: 'h3-main', name: 'MiniMax H3', type: 'main' },
+ width: 720,
+ });
+ const { commands, patchValues } = createCommands();
+ const videoValues = createDefaultVideoWidgetValues([wanModel]);
+
+ const didRecall = await executeVideoRecall({
+ queryClient,
+ t,
+ commands,
+ getVideoValues: () => videoValues as unknown as Record<string, unknown>,
+ item,
+ kind: 'size',
+ models: [wanModel, h3Model],
+ });
+
+ expect(didRecall).toBe(true);
+ expect(galleryApi.galleryImages.resolveMany).not.toHaveBeenCalled();
+ expect(patchValues).toHaveBeenCalledWith(
+ 'video',
+ { ...videoValues, aspectRatioId: '9:16', targetResolution: '720p' },
+ undefined
+ );
+ expect(commands.notifications.add).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: 'success', title: 'widgets.gallery.itemActions.recall.videoTitles.size' })
+ );
+ });
+
+ it('says the recorded size has no preset on the panel model, not that the metadata is missing', async () => {
+ videoMetadata.mockResolvedValue({ ...metadata, height: 464, width: 848 });
+ const { commands, patchValues } = createCommands();
+
+ const didRecall = await executeVideoRecall({
+ queryClient,
+ t,
+ commands,
+ getVideoValues: () => createDefaultVideoWidgetValues([wanModel]) as unknown as Record<string, unknown>,
+ item,
+ kind: 'size',
+ models: [wanModel],
+ });
+
+ expect(didRecall).toBe(false);
+ expect(patchValues).not.toHaveBeenCalled();
+ expect(commands.notifications.add).toHaveBeenCalledExactlyOnceWith({
+ kind: 'info',
+ message: 'widgets.gallery.itemActions.recall.videoSizeUnavailable',
+ title: 'widgets.gallery.itemActions.recall.nothingRecalledVideoSize',
+ });
+ });
+
+ it('names the panel media when it has no usable frame on the model, and shows a refused run its reason', async () => {
+ const recallSize = async (model: ModelConfig, values: Record<string, unknown>, width: number, height: number) => {
+ videoMetadata.mockResolvedValue({ ...metadata, height, width });
+ queryClient.clear();
+ const { commands, patchValues } = createCommands();
+
+ await executeVideoRecall({
+ queryClient,
+ t,
+ commands,
+ getVideoValues: () => ({ ...createDefaultVideoWidgetValues([model]), ...values }),
+ item,
+ kind: 'size',
+ models: [model],
+ });
+ expect(patchValues).not.toHaveBeenCalled();
+
+ return commands.notifications.add;
+ };
+
+ const narrowFrame = { firstFrameImage: { height: 500, image_name: 'held.png', width: 100 } };
+ const h3Checkpoint = { ...h3Model, format: 'checkpoint' } as ModelConfig;
+ expect(await recallSize(h3Checkpoint, narrowFrame, 1344, 768)).toHaveBeenCalledExactlyOnceWith({
+ kind: 'info',
+ message: 'widgets.gallery.itemActions.recall.videoSizeMediaUnresolvable',
+ title: 'widgets.gallery.itemActions.recall.nothingRecalledVideoSize',
+ });
+
+ const audioClip = {
+ conditioningClip: {
+ clip: { fps: 24, height: 1024, numFrames: 96, video_name: 'song.mp4', width: 1792 },
+ fpsKnown: true,
+ role: 'audio',
+ },
+ };
+ expect(
+ await recallSize(ltx2Model, { ...audioClip, targetResolution: '720p' }, 1792, 1024)
+ ).toHaveBeenCalledExactlyOnceWith({
+ kind: 'info',
+ message: expect.stringContaining('does not run a two-stage target resolution'),
+ title: 'widgets.gallery.itemActions.recall.nothingRecalledVideoSize',
+ });
+ });
+
+ it('keeps the unsupported-metadata notice for a size key on a record that is not video generation', async () => {
+ videoMetadata.mockResolvedValue({ generation_mode: 'sdxl_txt2img', height: 720, width: 1280 });
+ const { commands } = createCommands();
+
+ await executeVideoRecall({
+ queryClient,
+ t,
+ commands,
+ getVideoValues: () => createDefaultVideoWidgetValues([wanModel]) as unknown as Record<string, unknown>,
+ item,
+ kind: 'size',
+ models: [wanModel],
+ });
+
+ expect(commands.notifications.add).toHaveBeenCalledExactlyOnceWith({
+ kind: 'info',
+ message: 'widgets.gallery.itemActions.recall.videoMetadataUnsupported',
+ title: 'widgets.gallery.itemActions.recall.nothingRecalledVideo',
+ });
+ });
+
+ it('says media in the panel overrules the recorded size, and leaves the panel alone', async () => {
+ videoMetadata.mockResolvedValue({ ...metadata, height: 1280, width: 720 });
+ const { commands, patchValues } = createCommands();
+ const message = vi.fn((key: string) => key);
+ const videoValues = {
+ ...createDefaultVideoWidgetValues([wanModel]),
+ firstFrameImage: { height: 720, image_name: 'held.png', width: 1280 },
+ };
+
+ const didRecall = await executeVideoRecall({
+ queryClient,
+ t: message as unknown as TFunction,
+ commands,
+ getVideoValues: () => videoValues as unknown as Record<string, unknown>,
+ item,
+ kind: 'size',
+ models: [wanModel],
+ });
+
+ expect(didRecall).toBe(false);
+ expect(patchValues).not.toHaveBeenCalled();
+ expect(message).toHaveBeenCalledWith('widgets.gallery.itemActions.recall.videoSizeMediaConflict', {
+ effectiveHeight: 720,
+ effectiveWidth: 1280,
+ height: 1280,
+ width: 720,
+ });
+ expect(commands.notifications.add).toHaveBeenCalledExactlyOnceWith({
+ kind: 'info',
+ message: 'widgets.gallery.itemActions.recall.videoSizeMediaConflict',
+ title: 'widgets.gallery.itemActions.recall.nothingRecalledVideoSize',
+ });
+ });
+
it('recalls from the metadata the menu already read, without reading it again', async () => {
videoMetadata.mockResolvedValue(metadata);
const { commands, patchValues } = createCommands();
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts
index b4556bba21..dd57ab42ad 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts
@@ -45,8 +45,11 @@ import {
buildVideoRecallSettings,
getVideoRecallMessage,
getVideoRecallTitle,
+ parseVideoRecallRecord,
+ resolveVideoSizeRecall,
type VideoRecallKind,
type VideoRecallMediaNames,
+ type VideoSizeRecallFit,
} from './videoRecall';
const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
@@ -187,6 +190,27 @@ const reportVideoRecallError = (
return false;
};
+const getSizeRecallFailureMessage = (
+ fit: VideoSizeRecallFit,
+ size: { height: number; width: number },
+ t: TFunction
+): string => {
+ switch (fit.outcome) {
+ case 'invalid':
+ return fit.reason;
+ case 'media-conflict':
+ return t('widgets.gallery.itemActions.recall.videoSizeMediaConflict', {
+ ...size,
+ effectiveHeight: fit.effective.height,
+ effectiveWidth: fit.effective.width,
+ });
+ case 'media-unresolvable':
+ return t('widgets.gallery.itemActions.recall.videoSizeMediaUnresolvable', size);
+ default:
+ return t('widgets.gallery.itemActions.recall.videoSizeUnavailable', size);
+ }
+};
+
export const executeVideoRecall = async ({
commands,
getVideoValues,
@@ -215,6 +239,17 @@ export const executeVideoRecall = async ({
return false;
}
+ // Values are synced against the catalog: an empty one (not loaded yet, or failed) would drop the panel's model,
+ // LoRAs and components on commit. A prompts recall commits only the prompt keys, so it needs no catalog.
+ if (models.length === 0 && kind !== 'prompts') {
+ commands.notifications.add({
+ kind: 'info',
+ message: t('widgets.gallery.itemActions.recall.modelsUnavailableForVideoRecall'),
+ title: t('widgets.gallery.itemActions.recall.cannotRecallVideo'),
+ });
+ return false;
+ }
+
let metadata: unknown;
try {
@@ -223,12 +258,32 @@ export const executeVideoRecall = async ({
return reportVideoRecallError(commands, owner, error, projectId);
}
+ // A recorded size the panel cannot take is not missing metadata: say which size and why. A size recall reads no
+ // media, so this sees the snapshot the recall below applies to.
+ const record = kind === 'size' ? parseVideoRecallRecord(metadata) : null;
+ const size =
+ record?.isVideoGeneration && record.width && record.height ? { height: record.height, width: record.width } : null;
+ const emptyNotice = size
+ ? {
+ message: getSizeRecallFailureMessage(
+ resolveVideoSizeRecall(
+ getCurrentVideoValues({ models, videoValues: getVideoValues() }),
+ size.width,
+ size.height
+ ),
+ size,
+ t
+ ),
+ title: t('widgets.gallery.itemActions.recall.nothingRecalledVideoSize'),
+ }
+ : {
+ message: t('widgets.gallery.itemActions.recall.videoMetadataUnsupported'),
+ title: t('widgets.gallery.itemActions.recall.nothingRecalledVideo'),
+ };
+
return applyVideoRecallMetadata({
commands,
- emptyNotice: {
- message: t('widgets.gallery.itemActions.recall.videoMetadataUnsupported'),
- title: t('widgets.gallery.itemActions.recall.nothingRecalledVideo'),
- },
+ emptyNotice,
getVideoValues,
kind,
metadata,
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts b/invokeai/frontend/webv2/src/workbench/image-actions/index.ts
index 6d0be916e6..e3aae2fb3e 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/index.ts
@@ -4,7 +4,12 @@ export {
type ImageContextMenuTarget,
type ImageContextMenuVariant,
} from './ImageContextMenu';
-export { GALLERY_CANVAS_IMPORT_DESTINATIONS, ImageContinueGroup, ImageUseGroups } from './ImageItemMenuGroups';
+export {
+ GALLERY_CANVAS_IMPORT_DESTINATIONS,
+ ImageContinueGroup,
+ ImageUseGroups,
+ VideoUseGroups,
+} from './ImageItemMenuGroups';
export { useImageRecallCapabilities } from './useImageRecallCapabilities';
export {
buildImageRecallSettings,
@@ -20,6 +25,7 @@ export { readRecordedModelRef } from './recordedModel';
export {
appendReferenceVideo,
applyVideoRecallMetadata,
+ executeVideoRecall,
getCurrentVideoValues,
placeConditioningClip,
placeInitialVideo,
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 678feee6a4..e8e6318d68 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts
@@ -5,7 +5,10 @@ import {
compileVideoGraph,
createDefaultVideoWidgetValues,
getDefaultVideoSettings,
+ getVideoDimensions,
+ getVideoValidationReasons,
type VideoSettings,
+ type VideoWidgetValues,
} from '@features/video';
import { getVideoPromptPolicy } from '@features/video/core/videoPolicies';
import i18n from 'i18next';
@@ -17,8 +20,9 @@ import {
EMPTY_VIDEO_RECALL_CAPABILITIES,
getVideoRecallCapabilities,
getVideoRecallMessage,
- getVideoSizeRecall,
+ getVideoSizeRecalls,
parseVideoRecallRecord,
+ resolveVideoSizeRecall,
} from './videoRecall';
const isVideoGenerationMetadata = (metadata: unknown): boolean =>
@@ -90,13 +94,23 @@ describe('getVideoRecallCapabilities', () => {
});
it('derives per-verb availability from what the metadata contains', () => {
- expect(getVideoRecallCapabilities(wanMetadata())).toEqual({ all: true, prompts: true, remix: true, seed: true });
+ expect(getVideoRecallCapabilities(wanMetadata())).toEqual({
+ all: true,
+ prompts: true,
+ remix: true,
+ seed: true,
+ size: true,
+ });
expect(getVideoRecallCapabilities({ generation_mode: 'wan_t2v', seed: 7 })).toEqual({
all: true,
prompts: false,
remix: false,
seed: true,
+ size: false,
});
+ // A dimension alone, or a non-positive one, is no size to recall.
+ expect(getVideoRecallCapabilities({ generation_mode: 'wan_t2v', width: 1280 }).size).toBe(false);
+ expect(getVideoRecallCapabilities({ generation_mode: 'wan_t2v', height: 720, width: 0 }).size).toBe(false);
});
// Each record names one thing recall writes; the verbs it offers must be the ones that do something.
@@ -182,18 +196,17 @@ describe('getVideoRecallMessage', () => {
});
});
-describe('getVideoSizeRecall', () => {
+describe('getVideoSizeRecalls', () => {
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',
- });
+ expect(getVideoSizeRecalls(WAN_T2V, 1280, 720)).toEqual([{ aspectRatioId: '16:9', targetResolution: '720p' }]);
+ expect(getVideoSizeRecalls(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();
+ expect(getVideoSizeRecalls(WAN_T2V, 848, 464)).toEqual([]);
});
});
@@ -277,6 +290,169 @@ describe('buildVideoRecallSettings', () => {
expect(result?.values).toMatchObject({ seed: 1234, seedMode: 'fixed' });
});
+ it('recalls only the size for the size verb, fitted to the panel model', () => {
+ const wanValues = createDefaultVideoWidgetValues([WAN_T2V]);
+ const metadata = wanMetadata({ height: 1280, model: { key: h3Model().key }, width: 720 });
+ const result = buildVideoRecallSettings({ currentValues: wanValues, kind: 'size', metadata, models: catalog });
+
+ expect(result?.fields).toEqual(['size']);
+ // The recorded model, prompts and seed stay out; only the preset pair changes.
+ expect(result?.values).toEqual({ ...wanValues, aspectRatioId: '9:16', targetResolution: '720p' });
+ });
+
+ it('recalls no size the panel model cannot reproduce, or without a model', () => {
+ const wanValues = createDefaultVideoWidgetValues([WAN_T2V]);
+ const recall = (values: typeof wanValues, width: number, height: number) =>
+ buildVideoRecallSettings({
+ currentValues: values,
+ kind: 'size',
+ metadata: wanMetadata({ height, width }),
+ models: catalog,
+ });
+
+ expect(recall(wanValues, 848, 464)).toBeNull();
+ expect(recall({ ...wanValues, model: null }, 1280, 720)).toBeNull();
+ });
+
+ describe('a size recall with media in the panel', () => {
+ const image = (width: number, height: number) => ({ height, image_name: 'held.png', width });
+ const recallSize = (values: VideoWidgetValues, width: number, height: number) =>
+ buildVideoRecallSettings({
+ currentValues: values,
+ kind: 'size',
+ metadata: wanMetadata({ height, width }),
+ models: catalog,
+ });
+ const wanValues = createDefaultVideoWidgetValues([WAN_T2V]);
+
+ it('writes nothing when the media would keep the frame from reaching the recorded size', () => {
+ const values = { ...wanValues, firstFrameImage: image(1280, 720) };
+
+ expect(recallSize(values, 720, 1280)).toBeNull();
+ expect(resolveVideoSizeRecall(values, 720, 1280)).toMatchObject({
+ effective: { height: 720, width: 1280 },
+ outcome: 'media-conflict',
+ });
+ });
+
+ it('applies when the media resolves to the recorded size, keeping the media', () => {
+ const values = { ...wanValues, firstFrameImage: image(1920, 1080), targetResolution: '480p' as const };
+
+ expect(recallSize(values, 1280, 720)?.values).toEqual({
+ ...values,
+ aspectRatioId: '16:9',
+ targetResolution: '720p',
+ });
+ });
+
+ it('lets only a video-role conditioning clip own the frame, not an audio-role one', () => {
+ const ltx2 = ltx2Model('ltx2_dev');
+ const ltx2Values = createDefaultVideoWidgetValues([ltx2]);
+ const { height, width } = getVideoDimensions(ltx2, { ...ltx2Values, aspectRatioId: '16:9' })!;
+ const portrait = { duration: 4, fps: 24, height: 1920, video_name: 'held.mp4', width: 1080 };
+ const withClip = (role: 'audio' | 'video') =>
+ ({ ...ltx2Values, conditioningClip: { clip: portrait, role } }) as unknown as VideoWidgetValues;
+
+ expect(resolveVideoSizeRecall(withClip('audio'), width, height).outcome).toBe('fits');
+ expect(resolveVideoSizeRecall(withClip('video'), width, height).outcome).toBe('media-conflict');
+ });
+ });
+
+ describe('a size recall that would change whether the panel can run', () => {
+ const ltx2 = ltx2Model('ltx2_dev');
+ const ltx2Values = createDefaultVideoWidgetValues([ltx2]);
+ const audioClip = {
+ clip: { duration: 4, fps: 24, height: 1024, video_name: 'song.mp4', width: 1792 },
+ role: 'audio',
+ };
+ const metadata = wanMetadata({ height: 1024, width: 1792 });
+ const recall = (values: VideoWidgetValues) =>
+ buildVideoRecallSettings({ currentValues: values, kind: 'size', metadata, models: [ltx2] });
+
+ it('writes nothing when a two-stage preset would be refused alongside the conditioning clip', () => {
+ const values = {
+ ...ltx2Values,
+ conditioningClip: audioClip,
+ targetResolution: '720p',
+ } as unknown as VideoWidgetValues;
+
+ expect(recall(values)).toBeNull();
+ expect(resolveVideoSizeRecall(values, 1792, 1024)).toEqual({
+ outcome: 'invalid',
+ reason: expect.stringContaining('does not run a two-stage target resolution'),
+ });
+ });
+
+ it('writes nothing when a two-stage preset needs more steps than the panel has', () => {
+ const values = { ...ltx2Values, steps: 1, targetResolution: '720p' } as unknown as VideoWidgetValues;
+
+ expect(recall(values)).toBeNull();
+ expect(resolveVideoSizeRecall(values, 1792, 1024)).toEqual({
+ outcome: 'invalid',
+ reason: expect.stringContaining('two-stage target resolution needs at least'),
+ });
+ });
+
+ it('does not hold a reason the panel already had against the recall', () => {
+ const values = {
+ ...ltx2Values,
+ conditioningClip: audioClip,
+ steps: 0,
+ targetResolution: '1024p',
+ } as unknown as VideoWidgetValues;
+
+ expect(getVideoValidationReasons(ltx2, values)).not.toEqual([]);
+ expect(recall(values)?.fields).toEqual(['size']);
+ });
+ });
+
+ it('tells apart no preset from media with no usable frame on the model', () => {
+ const h3 = h3Model();
+ const h3Values = createDefaultVideoWidgetValues([h3]);
+ const narrowFrame = { height: 500, image_name: 'held.png', width: 100 };
+
+ expect(resolveVideoSizeRecall(h3Values, 1000, 1000).outcome).toBe('unavailable');
+ expect(resolveVideoSizeRecall({ ...h3Values, model: null }, 1344, 768).outcome).toBe('unavailable');
+ expect(resolveVideoSizeRecall({ ...h3Values, firstFrameImage: narrowFrame }, 1344, 768).outcome).toBe(
+ 'media-unresolvable'
+ );
+ });
+
+ describe('a size more than one preset reproduces', () => {
+ const h3 = h3Model();
+ const h3Values = createDefaultVideoWidgetValues([h3]);
+ const withFrame = (width: number, height: number): VideoWidgetValues => ({
+ ...h3Values,
+ firstFrameImage: { height, image_name: 'held.png', width },
+ });
+
+ it('takes the preset that fits the held frame, not just the first match', () => {
+ const values = withFrame(1003, 1024);
+ const lowres = { aspectRatioId: '1:1', targetResolution: '768 lowres' };
+
+ expect(resolveVideoSizeRecall(values, 768, 768)).toEqual({ outcome: 'fits', sizeRecall: lowres });
+
+ const result = buildVideoRecallSettings({
+ currentValues: values,
+ kind: 'size',
+ metadata: wanMetadata({ height: 768, width: 768 }),
+ models: [h3],
+ });
+
+ expect(result?.values).toEqual({ ...values, ...lowres });
+ expect(getVideoDimensions(h3, result!.values)).toMatchObject({ height: 768, width: 768 });
+ });
+
+ it('reports the first preset when none fits the held frame', () => {
+ // 1920x1080 at 768 highres: 1365.3x768 exceeds the pixel cap, scales to 1354.6x762, snaps to 1344x768.
+ // 768 lowres would report 768x448.
+ expect(resolveVideoSizeRecall(withFrame(1920, 1080), 768, 768)).toMatchObject({
+ effective: { height: 768, width: 1344 },
+ outcome: 'media-conflict',
+ });
+ });
+ });
+
it('remix recalls everything except the seed', () => {
const result = buildVideoRecallSettings({ currentValues, kind: 'remix', metadata: wanMetadata(), models: catalog });
@@ -1262,6 +1438,7 @@ describe('LTX-2 recall', () => {
prompts: true,
remix: true,
seed: true,
+ size: true,
});
}
});
@@ -1426,7 +1603,13 @@ describe('recall of what the video graphs record', () => {
models: [model],
});
- expect(getVideoRecallCapabilities(metadata)).toEqual({ all: true, prompts: true, remix: true, seed: true });
+ 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',
@@ -1474,7 +1657,13 @@ describe('recall of what the video graphs record', () => {
models: [componentSource, model],
});
- expect(getVideoRecallCapabilities(metadata)).toEqual({ all: true, prompts: true, remix: true, seed: true });
+ 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,
@@ -1518,7 +1707,13 @@ describe('recall of what the video graphs record', () => {
models: [model, componentSource, encoder],
});
- expect(getVideoRecallCapabilities(metadata)).toEqual({ all: true, prompts: true, remix: true, seed: true });
+ 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,
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts
index c2fd4de9b1..9d2a4fe236 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts
@@ -22,6 +22,7 @@ import {
getVideoModelPolicy,
getVideoModelSelectionResult,
getVideoTargetResolutionOptions,
+ getVideoValidationReasons,
isConditioningClipExcludingFrames,
isSupportedVideoModel,
isValidVideoNumFrames,
@@ -76,13 +77,14 @@ const VIDEO_GENERATION_MODE_IDS: ReadonlySet<string> = new Set([
'ltx2_extend_video',
]);
-export type VideoRecallKind = 'all' | 'remix' | 'prompts' | 'seed';
+export type VideoRecallKind = 'all' | 'remix' | 'prompts' | 'seed' | 'size';
export interface VideoRecallCapabilities {
all: boolean;
remix: boolean;
prompts: boolean;
seed: boolean;
+ size: boolean;
}
export const EMPTY_VIDEO_RECALL_CAPABILITIES: VideoRecallCapabilities = {
@@ -90,6 +92,7 @@ export const EMPTY_VIDEO_RECALL_CAPABILITIES: VideoRecallCapabilities = {
prompts: false,
remix: false,
seed: false,
+ size: false,
};
export type VideoRecalledField =
@@ -401,19 +404,26 @@ export const parseVideoRecallRecord = (metadata: unknown): VideoRecallRecord | n
};
};
+interface VideoSizePreset {
+ aspectRatioId: VideoAspectRatioId;
+ targetResolution: VideoTargetResolution;
+}
+
/**
* Recall aspect/resolution presets only on exact dimension matches; other dimensions came from conditioning media
- * and remain media-controlled.
+ * and remain media-controlled. Returns every match: presets that agree without media can differ under held media.
*/
-export const getVideoSizeRecall = (
+export const getVideoSizeRecalls = (
model: MainModelConfig,
width: number | null,
height: number | null
-): { aspectRatioId: VideoAspectRatioId; targetResolution: VideoTargetResolution } | null => {
+): VideoSizePreset[] => {
if (width === null || height === null || width <= 0 || height <= 0) {
- return null;
+ return [];
}
+ const recalls: VideoSizePreset[] = [];
+
for (const aspectRatioId of getVideoAspectRatioOptions(model)) {
for (const option of getVideoTargetResolutionOptions(model)) {
const derived = getVideoDimensions(model, {
@@ -426,12 +436,58 @@ export const getVideoSizeRecall = (
});
if (derived && derived.width === width && derived.height === height) {
- return { aspectRatioId, targetResolution: option.id };
+ recalls.push({ aspectRatioId, targetResolution: option.id });
}
}
}
- return null;
+ return recalls;
+};
+
+export type VideoSizeRecallFit =
+ /** No model, or no preset of it 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. */
+ | { outcome: 'invalid'; reason: string }
+ | { outcome: 'fits'; sizeRecall: VideoSizePreset };
+
+/**
+ * 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.
+ */
+export const resolveVideoSizeRecall = (
+ values: VideoWidgetValues,
+ width: number | null,
+ height: number | null
+): VideoSizeRecallFit => {
+ const { model } = values;
+
+ if (!model) {
+ return { outcome: 'unavailable' };
+ }
+
+ const existingReasons = new Set(getVideoValidationReasons(model, values));
+ const fits = getVideoSizeRecalls(model, width, height).map((sizeRecall): VideoSizeRecallFit => {
+ const next = { ...values, ...sizeRecall };
+ const effective = getVideoDimensions(model, next);
+
+ if (!effective) {
+ return { outcome: 'media-unresolvable' };
+ }
+ if (effective.width !== width || effective.height !== height) {
+ return { effective, outcome: 'media-conflict' };
+ }
+
+ const reason = getVideoValidationReasons(model, next).find((candidate) => !existingReasons.has(candidate));
+
+ return reason ? { outcome: 'invalid', reason } : { outcome: 'fits', sizeRecall };
+ });
+
+ return fits.find((fit) => fit.outcome === 'fits') ?? fits[0] ?? { outcome: 'unavailable' };
};
/**
@@ -475,6 +531,7 @@ export const getVideoRecallCapabilities = (metadata: unknown): VideoRecallCapabi
// A recorded null negative prompt is applied too: it switches the negative prompt off.
const prompts = record.positivePrompt !== null || record.negativePrompt !== undefined;
const seed = record.seed !== null;
+ const size = record.width !== null && record.height !== null;
const { media } = record;
const remix =
prompts ||
@@ -486,7 +543,7 @@ export const getVideoRecallCapabilities = (metadata: unknown): VideoRecallCapabi
record.stgScale !== null ||
record.modalityScale !== null ||
record.fps !== null ||
- (record.width !== null && record.height !== null) ||
+ size ||
record.components.length > 0 ||
record.loras.length > 0 ||
record.hybridStartBlock !== null ||
@@ -497,7 +554,7 @@ export const getVideoRecallCapabilities = (metadata: unknown): VideoRecallCapabi
record.conditioningClip !== null ||
record.references.length > 0;
- return { all: remix || seed, prompts, remix, seed };
+ return { all: remix || seed, prompts, remix, seed, size };
};
const createEmptyMediaNames = (): VideoRecallMediaNames => ({
@@ -613,6 +670,13 @@ export const buildVideoRecallSettings = ({
return fields.length > 0 ? { fields, mediaNames, values: { ...values, ...promptPatch } } : null;
}
+ if (kind === 'size') {
+ // Fitted to the panel's own model and media: a size recall leaves both alone, so a size they refuse writes nothing.
+ const fit = resolveVideoSizeRecall(values, record.width, record.height);
+
+ return fit.outcome === 'fits' ? { fields: ['size'], mediaNames, values: { ...values, ...fit.sizeRecall } } : null;
+ }
+
// all / remix from here on.
const installedModel = resolveVideoModel(record.model, models);
const recalledModel =
@@ -722,7 +786,7 @@ export const buildVideoRecallSettings = ({
fields.push('fps');
}
- const sizeRecall = getVideoSizeRecall(model, record.width, record.height);
+ const [sizeRecall] = getVideoSizeRecalls(model, record.width, record.height);
if (sizeRecall) {
values = { ...values, ...sizeRecall };
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx
index 5a019b2b24..deb8b55bf3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx
@@ -7,7 +7,12 @@ import { canCopyImage } from '@platform/browser/clipboard';
import { Button, IconButton } from '@platform/ui/Button';
import { MenuContent } from '@platform/ui/Menu';
import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';
-import { ImageContinueGroup, ImageUseGroups, useImageRecallCapabilities } from '@workbench/image-actions';
+import {
+ ImageContinueGroup,
+ ImageUseGroups,
+ useImageRecallCapabilities,
+ VideoUseGroups,
+} from '@workbench/image-actions';
import {
ChevronDownIcon,
CopyIcon,
@@ -31,9 +36,8 @@ const STAR_LABEL_KEYS = {
/**
* The selection's actions in the Preview header. An image gets Edit (every way to continue working with it) and Use
- * (it as an input, or its settings), so ⋮ keeps only housekeeping: labelled at full density, icon-only at compact,
- * where compare moves into ⋮ too. Minimal density keeps star and the full ⋮ alone; videos have neither menu and keep
- * the full ⋮ at every density.
+ * (it as an input, or its settings); a video gets Use alone. ⋮ then keeps only housekeeping: labelled at full density,
+ * icon-only at compact, where compare moves into ⋮ too. Minimal density keeps star and the full ⋮ alone.
*/
export const PreviewActionStrip = ({
actions,
@@ -59,7 +63,7 @@ export const PreviewActionStrip = ({
);
const selectForCompare = useCallback(() => image && actions.selectForCompare(image), [actions, image]);
const copyCurrentFrame = useCallback(() => onCopyCurrentFrame?.(), [onCopyCurrentFrame]);
- const hasItemMenus = density !== 'minimal' && image !== null;
+ const hasItemMenus = density !== 'minimal';
const openMenu = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
const rect = event.currentTarget.getBoundingClientRect();
@@ -80,11 +84,11 @@ export const PreviewActionStrip = ({
<StripIconButton icon={EllipsisVerticalIcon} label={t('widgets.preview.imageActions')} onClick={openMenu} />
) : null;
- if (density === 'compact' && image) {
+ if (density === 'compact') {
return (
<HStack flexShrink={0} gap="0.5">
- <EditMenu actions={actions} image={image} isIconOnly />
- <UseMenu actions={actions} image={image} isIconOnly />
+ {image ? <EditMenu actions={actions} image={image} isIconOnly /> : null}
+ <UseMenu actions={actions} isIconOnly item={item} />
{starButton}
{menuButton}
</HStack>
@@ -102,13 +106,11 @@ export const PreviewActionStrip = ({
return (
<HStack flexShrink={0} gap="0.5">
- {/* Lead with the labelled next steps; omit them for videos, matching context-menu eligibility. */}
+ {/* Lead with the labelled next steps; videos have no Edit or compare, matching context-menu eligibility. */}
+ {image ? <EditMenu actions={actions} image={image} /> : null}
+ <UseMenu actions={actions} item={item} />
{image ? (
- <>
- <EditMenu actions={actions} image={image} />
- <UseMenu actions={actions} image={image} />
- <StripIconButton icon={ImagesIcon} label={t('widgets.preview.selectForCompare')} onClick={selectForCompare} />
- </>
+ <StripIconButton icon={ImagesIcon} label={t('widgets.preview.selectForCompare')} onClick={selectForCompare} />
) : null}
{starButton}
{item.kind === 'video' && onCopyCurrentFrame ? (
@@ -127,14 +129,14 @@ export const PreviewActionStrip = ({
};
/**
- * The image an open menu acts on, held from the moment it opens, as the ⋮ menu holds its target: a result that
+ * The item an open menu acts on, held from the moment it opens, as the ⋮ menu holds its target: a result that
* Auto-switch brings in meanwhile must not take over the items, nor reload what they offer.
*/
-const useImageHeldWhileOpen = (image: GalleryImage) => {
- const [heldImage, setHeldImage] = useState<GalleryImage | null>(null);
- const handleOpenChange = useCallback(({ open }: { open: boolean }) => setHeldImage(open ? image : null), [image]);
+const useHeldWhileOpen = <T,>(item: T) => {
+ const [heldItem, setHeldItem] = useState<T | null>(null);
+ const handleOpenChange = useCallback(({ open }: { open: boolean }) => setHeldItem(open ? item : null), [item]);
- return { handleOpenChange, menuImage: heldImage ?? image };
+ return { handleOpenChange, menuItem: heldItem ?? item };
};
interface ItemMenuProps {
@@ -179,7 +181,7 @@ const EditMenu = ({ actions, image, isIconOnly = false }: ItemMenuProps) => {
const { t } = useTranslation();
const label = t('widgets.preview.editThisImage');
const ids = useTooltipTriggerIds();
- const { handleOpenChange, menuImage } = useImageHeldWhileOpen(image);
+ const { handleOpenChange, menuItem: menuImage } = useHeldWhileOpen(image);
const images = useMemo(() => [menuImage], [menuImage]);
return (
@@ -205,12 +207,22 @@ const EditMenu = ({ actions, image, isIconOnly = false }: ItemMenuProps) => {
);
};
-/** What to take from the image: it as an input, or its recorded settings, with the viewer keys that do the same. */
-const UseMenu = ({ actions, image, isIconOnly = false }: ItemMenuProps) => {
+/**
+ * What to take from the item: it as an input, or its recorded settings; for an image, with the viewer keys that do
+ * the same.
+ */
+const UseMenu = ({
+ actions,
+ isIconOnly = false,
+ item,
+}: Omit<ItemMenuProps, 'image'> & {
+ item: GalleryItem;
+}) => {
const { t } = useTranslation();
const ids = useTooltipTriggerIds();
- const label = t('widgets.preview.useInGenerate');
- const { handleOpenChange, menuImage } = useImageHeldWhileOpen(image);
+ const { handleOpenChange, menuItem } = useHeldWhileOpen(item);
+ // Named for the held item, so an open menu keeps its name when Auto-switch brings in the other kind.
+ const label = t(menuItem.kind === 'video' ? 'widgets.preview.useThisVideo' : 'widgets.preview.useInGenerate');
return (
<Menu.Root ids={ids} lazyMount positioning={MENU_POSITIONING} unmountOnExit onOpenChange={handleOpenChange}>
@@ -227,7 +239,11 @@ const UseMenu = ({ actions, image, isIconOnly = false }: ItemMenuProps) => {
<Portal>
<Menu.Positioner>
<MenuContent minW="16rem">
- <UseMenuItems actions={actions} image={menuImage} />
+ {isGalleryImageItem(menuItem) ? (
+ <UseMenuItems actions={actions} image={galleryImageItemToGalleryImage(menuItem)} />
+ ) : (
+ <VideoUseGroups actions={actions} item={menuItem} presentation="guided" />
+ )}
</MenuContent>
</Menu.Positioner>
</Portal>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsx
index 3296beb364..04b5c51747 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsx
@@ -58,11 +58,17 @@ void i18n.use(initReactI18next).init({
continueWorking: 'Continue working',
editOnCanvasHint: 'Adds an image layer and opens Canvas',
remixHint: 'Same settings, new seed',
+ extendInVideo: 'Extend in Video',
+ remixVideo: 'Remix video',
reuseFromImage: 'Reuse from image',
+ reuseFromVideo: 'Reuse from video',
sendToVideo: 'Send to Video',
useAsPromptTemplate: 'Use as prompt template',
useAsReferenceImage: 'Use as reference image',
+ useAsConditioningClip: 'Use as conditioning clip',
+ useAsReferenceVideo: 'Use as reference video',
useImageAs: 'Use image as',
+ useVideoAs: 'Use video as',
},
},
preview: {
@@ -72,8 +78,10 @@ void i18n.use(initReactI18next).init({
imageActions: 'Image actions',
selectForCompare: 'Select for Compare',
starImage: 'Star image',
+ starVideo: 'Star video',
use: 'Use',
useInGenerate: 'Use this image in Generate',
+ useThisVideo: 'Use this video',
zoom: 'Zoom',
zoomFit: 'Fit to view',
zoomLevel: 'Zoom {{percent}}%',
@@ -100,9 +108,12 @@ const state = vi.hoisted(() => ({
const patchValues = vi.hoisted(() => vi.fn());
const openItemMenu = vi.hoisted(() => vi.fn());
const itemActions = vi.hoisted(() => ({
+ canUseAsConditioningClip: { audio: true, video: true },
canUseAsReferenceImage: false,
+ canUseAsReferenceVideo: true,
deriveImageRecallCapabilities: vi.fn(),
recallImageData: vi.fn(() => Promise.resolve()),
+ recallVideoData: vi.fn(() => Promise.resolve()),
selectForCompare: vi.fn(),
sendImageAsControl: vi.fn(() => Promise.resolve()),
sendToCanvas: vi.fn(() => Promise.resolve()),
@@ -111,12 +122,14 @@ const itemActions = vi.hoisted(() => ({
const updateProjectPreferences = vi.hoisted(() => vi.fn());
const showAll = vi.hoisted(() => vi.fn());
const imageMetadata = vi.hoisted(() => vi.fn());
+const videoMetadata = vi.hoisted(() => vi.fn());
vi.mock('@features/queue/react', () => ({ useProgressImage: () => null }));
// The transport, under both the gallery's shared metadata query and its public image port.
vi.mock('@features/gallery/data/backend', async (importOriginal) => ({
...(await importOriginal<typeof GalleryBackendModule>()),
getGalleryImageByName: () => Promise.resolve({ hasWorkflow: false }),
getGalleryImageMetadata: imageMetadata,
+ getGalleryVideoMetadata: videoMetadata,
}));
vi.mock('@features/identity', async (importOriginal) => ({
...(await importOriginal<typeof IdentityModule>()),
@@ -232,6 +245,8 @@ beforeEach(() => {
itemActions.canUseAsReferenceImage = false;
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
imageMetadata.mockReset().mockResolvedValue({ seed: 1 });
+ videoMetadata.mockReset().mockResolvedValue({ generation_mode: 'wan_t2v', positive_prompt: 'a fox', seed: 7 });
+ itemActions.recallVideoData.mockClear();
itemActions.deriveImageRecallCapabilities.mockReset();
itemActions.deriveImageRecallCapabilities.mockReturnValue({
all: true,
@@ -626,13 +641,96 @@ describe('preview header Edit and Use', () => {
);
});
- it('keeps a video to star and the full ⋮ menu', async () => {
+ it('keeps an open Use menu, and its name, on the image when a video takes the selection', async () => {
+ state.actionItem = STILL_IMAGE;
+ await render();
+ await settle(() => button('Use this image in Generate').click());
+ const menu = page.getByRole('menu').element();
+ await vi.waitFor(() => expect(menuRows(menu)[0]).toBe('# Use image as'));
+
state.actionItem = VIDEO;
+ await settle(() => {
+ root?.render(
+ <QueryClientProvider client={queryClient}>
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <PreviewHeaderActions {...({ region: 'center', runtime: {} } as unknown as WidgetViewProps)} />
+ </ChakraProvider>
+ </I18nextProvider>
+ </QueryClientProvider>
+ );
+ });
+
+ expect(button('Use this image in Generate')?.getAttribute('aria-expanded')).toBe('true');
+ expect(button('Use this video')).toBeNull();
+ expect(menuRows(page.getByRole('menu').element())).toContain('# Reuse from image');
+ expect(videoMetadata).not.toHaveBeenCalled();
+ });
+
+ it('gives a video the Use menu and a housekeeping ⋮ down to compact, and minimal star and the full ⋮', async () => {
+ const strip = () =>
+ [...host!.querySelectorAll<HTMLButtonElement>('button')]
+ .map((entry) => entry.getAttribute('aria-label'))
+ .filter((label) => label !== null && !label.startsWith('Auto-switch') && label !== 'Details');
+ state.actionItem = VIDEO;
+
+ await render();
+ expect(strip()).toEqual(['Use this video', 'Star video', 'Image actions']);
+ expect(button('Use this video').textContent).toContain('Use');
+ await settle(() => button('Image actions').click());
+ expect(openItemMenu).toHaveBeenLastCalledWith(expect.any(Number), expect.any(Number), 'housekeeping');
+
+ state.density = 'compact';
await render();
+ expect(strip()).toEqual(['Use this video', 'Star video', 'Image actions']);
+ expect(button('Use this video').textContent).toBe('');
+ expect(button('Use this video').getAttribute('aria-haspopup')).toBe('menu');
+ await settle(() => button('Image actions').click());
+ expect(openItemMenu).toHaveBeenLastCalledWith(expect.any(Number), expect.any(Number), 'housekeeping');
- expect(button('Edit')).toBeNull();
- expect(button('Use this image in Generate')).toBeNull();
+ state.density = 'minimal';
+ await render();
+ expect(strip()).toEqual(['Star video', 'Image actions']);
await settle(() => button('Image actions').click());
expect(openItemMenu).toHaveBeenLastCalledWith(expect.any(Number), expect.any(Number), 'full');
});
+
+ it('loads what the video can lend only when Use opens, then lists both groups', async () => {
+ state.actionItem = VIDEO;
+ await render();
+ expect(videoMetadata).not.toHaveBeenCalled();
+
+ await settle(() => button('Use this video').click());
+ const menu = page.getByRole('menu').element();
+
+ expect(videoMetadata).toHaveBeenCalledExactlyOnceWith('clip.mp4', expect.any(AbortSignal));
+ await vi.waitFor(() =>
+ expect(menuRows(menu)).toEqual([
+ '# Use video as',
+ 'Extend in Video',
+ 'Use as reference video',
+ 'Use as conditioning clip',
+ '# Reuse from video',
+ 'Remix video',
+ 'All settings',
+ 'Use prompt',
+ 'Use seed',
+ // The record names no size.
+ 'Use size (disabled)',
+ ])
+ );
+ // The viewer keys recall the same from the selected video.
+ const keycaps = [...menu.querySelectorAll<HTMLElement>('[role="menuitem"]')].map(
+ (row) => [...row.querySelectorAll('kbd')].map((key) => key.textContent).join('+') || null
+ );
+ expect(keycaps.slice(3)).toEqual(['r', 'a', 'p', 's', 'd']);
+
+ const seed = page.getByRole('menuitem', { name: /^Use seed/ });
+ await seed.hover();
+ await seed.click();
+ expect(itemActions.recallVideoData).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ name: 'clip.mp4' }),
+ 'seed'
+ );
+ });
});