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): apply external video recall events to the Video panel

Lincoln Stein1bf47dee72a8
diff --git a/docs/src/content/docs/development/Guides/video-recall-api.mdx b/docs/src/content/docs/development/Guides/video-recall-api.mdx
index a821f6820f..96f0ea5b60 100644
--- a/docs/src/content/docs/development/Guides/video-recall-api.mdx
+++ b/docs/src/content/docs/development/Guides/video-recall-api.mdx
@@ -29,13 +29,9 @@ gallery or a video file, which is uploaded into the gallery first.
3. **Event** — the backend emits one `video_recall_requested` socket event to the
calling user's own room. Other users, including administrators, do not receive
it.
-4. **Frontend** — the user's open frontends apply the event to the Video panel.
-
-:::note
-The webv2 handler for `video_recall_requested` ships separately from these
-endpoints. Until it is present, the endpoints validate, upload and emit, but no
-client acts on the event.
-:::
+4. **Frontend** — the user's open webv2 sessions apply the event to the Video
+ panel of the project that was active when it arrived. See
+ [Frontend behavior](#frontend-behavior). The legacy frontend ignores it.
## Endpoints
@@ -56,7 +52,7 @@ client acts on the event.
| Query parameter | Default | Meaning |
|---|---|---|
| `mode` | `recall` | `recall` sends every field; `remix` never sends `seed`, so the panel's own seed stands |
-| `strict` | `false` | Forwarded to the frontend. `false` asks it to change only the fields you send; `true` asks it to treat the body as a whole generation record, clearing LoRAs and media you do not send. |
+| `strict` | `false` | `false` changes only the fields you send. `true` treats the body as a whole generation record: LoRAs, media and a MiniMax H3 hybrid base you do not send are cleared, as the gallery's *Recall All* does with a video's own metadata. |
Fields naming a model or medium that cannot be used are dropped and listed in the
response's `skipped`; the rest are sent. So are trim bounds or a conditioning role
@@ -79,9 +75,47 @@ Uncategorized); uploading to a board requires permission to add media to it. The
share the upload route's size limit and concurrency slots, so a busy server can
answer `429` with a `Retry-After` header.
-Whether the video is usable depends on the model selected in the panel: an
-initial video needs a model that can extend a clip, and a reference video needs
-a model that takes reference videos.
+Whether the video is usable depends on the model selected in the panel, which is
+never switched on the caller's behalf: an initial video needs a model that can
+extend a clip, and a reference video needs a model that takes reference videos,
+with room for another.
+
+## Frontend behavior
+
+webv2 applies each event, in arrival order, to the Video panel of the project that
+was active when the event arrived. Video recall events are ordered among themselves;
+image recall events (`POST /api/v1/recall`) are ordered separately. A notification
+reports each change applied or declined. An event whose project was closed before it
+could be applied is dropped. When something was applied and the project is on screen
+without a Video widget anywhere in its layout, the widget is opened; a Video widget
+that is already there, docked or floating, is left where it is.
+
+- **Recall / Remix** runs the same mapping as the gallery's *Recall All* and
+ *Remix Video*: the model is resolved against the installed catalog (switching
+ family resets frames, fps and resolution to the new model's grid before the
+ sent values land), frames snap to the model's grid, `width`/`height` are applied
+ only when they match one of the model's resolution presets, and media names are
+ looked up in the gallery for their dimensions, with missing ones dropped. Without
+ `strict`, the panel keeps the media you do not send. A medium you send fills its
+ slot and displaces only the slots it conflicts with (an initial video and a first
+ frame are exclusive; references displace the frame slots), and a
+ `minimax_h3_references` list replaces the panel's references. Media the panel's
+ model cannot use is ignored rather than displacing anything. On a Ref2VA panel that
+ extends from its references, the initial video keeps its continuity reference
+ through either change, as the *Initial Video* field keeps it, or is removed when a
+ sent reference list leaves no video slot for it.
+- **Send Video** does what dropping the clip on the panel's *Initial Video* field
+ does. On a MiniMax H3 Ref2VA panel that extends from its references, the clip's
+ continuity reference is linked into the references, and the request is declined
+ when all three video reference slots are taken. On a model that cannot extend a
+ clip, the video is still set and the notification says it will go unused.
+- **Use as Ref Video** appends the video with the defaults the *References* field
+ gives a new video: soundtrack-only conditioning for an uploaded audio file,
+ otherwise video and audio from a short sample of the clip. It is declined when
+ the panel's model takes no reference videos or all its video slots are taken.
+
+The gallery's context menu offers the same *Extend in Video* and *Use as Reference
+Video* actions for any video in the gallery.
## Request schema
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 2f0a2281f5..6e3507ee0a 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -4024,6 +4024,19 @@
"referenceDetailMax": "Max detail (2048px, slower)",
"referenceExtendCapFull": "Initial video not set",
"referenceExtendCapFullDescription": "All 3 video reference slots are in use, so there is no room for the continuity reference this clip needs. Remove a video reference, then drop the clip again.",
+ "placement": {
+ "initialVideoFull": "All video reference slots are in use, so there is no room for the continuity reference this clip needs. Remove a video reference and try again.",
+ "initialVideoSet": "Initial video set",
+ "initialVideoUnused": "The selected video model can't extend a clip, so it won't use this initial video until you choose one that can.",
+ "referenceAdded": "Reference video added",
+ "referenceFull": "All video reference slots are in use. Remove a video reference and try again.",
+ "referenceNotAdded": "Reference video not added",
+ "referenceUnsupported": "The selected video model doesn't take reference videos. Choose one that does, such as MiniMax H3 Ref2VA."
+ },
+ "externalRecall": {
+ "nothingApplied": "Nothing recalled",
+ "nothingAppliedDescription": "None of the recalled settings apply to the Video panel's model."
+ },
"referenceExtendHelp": "The generated video is appended to this clip at its End Frame, and samples the last ~5 seconds before the cutpoint to achieve video continuity.",
"referenceImageCapRace": "All {{max}} image reference slots filled while this one was loading, so it was not added.",
"referenceImageCost": "{{width}}×{{height}} · {{rows}} rows per step",
diff --git a/invokeai/frontend/webv2/src/app/RecallParametersRuntime.tsx b/invokeai/frontend/webv2/src/app/RecallParametersRuntime.tsx
index 7c1e3d23df..5608f9fb24 100644
--- a/invokeai/frontend/webv2/src/app/RecallParametersRuntime.tsx
+++ b/invokeai/frontend/webv2/src/app/RecallParametersRuntime.tsx
@@ -1,8 +1,13 @@
import { getAuthSession } from '@features/identity';
import { useMountEffect } from '@platform/react/useMountEffect';
import { socketHub } from '@platform/transport/socketHub';
-import { attachRecallParametersRuntime } from '@workbench/image-actions/recallParametersBridge';
+import {
+ attachRecallParametersRuntime,
+ attachVideoRecallRuntime,
+} from '@workbench/image-actions/recallParametersBridge';
+import { openWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
import { useWorkbenchInternalStore } from '@workbench/WorkbenchContext';
+import { useWorkbenchWidgetRegistry } from '@workbench/WorkbenchWidgetRegistryContext';
import { useTranslation } from 'react-i18next';
/** Single-user servers tag events with a system user id, so only multi-user sessions can be fenced. */
@@ -11,22 +16,40 @@ const getSessionUserId = (): string | null => {
return session.multiuserEnabled ? (session.user?.user_id ?? null) : null;
};
-/** App-owned composition: external `POST /api/v1/recall` updates land in the active project's Generate panel. */
+/**
+ * App-owned composition: external `POST /api/v1/recall` updates land in the active project's Generate panel, and
+ * `POST /api/v1/recall/video` updates in its Video panel.
+ */
export const RecallParametersRuntime = () => {
const store = useWorkbenchInternalStore();
+ const { getWidgetsForRegion } = useWorkbenchWidgetRegistry();
// Captured once at mount; i18next resolves it against the current language at each call.
const { t } = useTranslation();
- useMountEffect(
- () =>
- attachRecallParametersRuntime({
- commands: store.commands,
- getSessionUserId,
- hub: socketHub,
- queries: store.queries,
- t,
- }).dispose
- );
+ useMountEffect(() => {
+ const recall = attachRecallParametersRuntime({
+ commands: store.commands,
+ getSessionUserId,
+ hub: socketHub,
+ queries: store.queries,
+ t,
+ });
+ const videoRecall = attachVideoRecallRuntime({
+ commands: store.commands,
+ getSessionUserId,
+ hub: socketHub,
+ openVideoWidget: () => {
+ openWorkbenchWidget(store.commands.widgets, getWidgetsForRegion, 'video', { preferredRegions: ['left'] });
+ },
+ queries: store.queries,
+ t,
+ });
+
+ return () => {
+ recall.dispose();
+ videoRecall.dispose();
+ };
+ });
return null;
};
diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
index 43fb9592d8..d9384275ec 100644
--- a/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/settings.test.ts
@@ -22,6 +22,8 @@ import {
getDefaultReferenceClip,
getDefaultReferenceConditioning,
getDefaultReferenceImageDetail,
+ getInitialVideoPatch,
+ getReferencesPatch,
isVideoSettings,
createVideoConditioningClip,
isVideoSourceClip,
@@ -1488,3 +1490,38 @@ describe('reference sample window', () => {
});
});
});
+
+describe('panel patches shared by the Video panel and gallery/API placement', () => {
+ const clip = createVideoSourceClip({ durationSeconds: 5, fps: 16, height: 480, name: 'clip.mp4', width: 832 });
+ const imageReference: VideoReferenceItem = {
+ detail: 'max',
+ image: { height: 512, image_name: 'ref.png', width: 512 },
+ kind: 'image',
+ };
+
+ it('sets an initial video on a plain panel without touching the references', () => {
+ expect(
+ getInitialVideoPatch({ maxVideos: 0, numFrames: 81, referenceExtend: false, references: [], sourceVideo: clip })
+ ).toEqual({ conditioningClip: null, firstFrameImage: null, sourceVideo: clip });
+ });
+
+ it('clears an initial video without displacing anything', () => {
+ expect(
+ getInitialVideoPatch({ maxVideos: 3, numFrames: 81, referenceExtend: true, references: [], sourceVideo: null })
+ ).toEqual({ references: [], sourceVideo: null });
+ });
+
+ it('lets references displace the initial video only on a panel that does not extend from it', () => {
+ expect(getReferencesPatch({ referenceExtend: false, references: [imageReference] })).toEqual({
+ conditioningClip: null,
+ firstFrameImage: null,
+ lastFrameImage: null,
+ references: [imageReference],
+ sourceVideo: null,
+ });
+ expect(getReferencesPatch({ referenceExtend: true, references: [imageReference] })).not.toHaveProperty(
+ 'sourceVideo'
+ );
+ expect(getReferencesPatch({ referenceExtend: false, references: [] })).toEqual({ references: [] });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.ts
index 85be7ace13..6ea3a77f10 100644
--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts
@@ -674,6 +674,24 @@ export const getDefaultReferenceClip = (
startFrame: 0,
});
+/**
+ * A gallery video as a new Ref2VA reference, with the add-path defaults: soundtrack-only conditioning for wrapped
+ * audio, and the default sample of the clip. Do not persist mediaOrigin on the clip: project import reuploads under a
+ * new name without rederiving it.
+ */
+export const createVideoReferenceEntry = (item: {
+ durationSeconds: number;
+ fps?: number;
+ height: number;
+ mediaOrigin?: string | null;
+ name: string;
+ width: number;
+}): Extract<VideoReferenceItem, { kind: 'video' }> => {
+ const conditioning = getDefaultReferenceConditioning(item.mediaOrigin);
+
+ return { clip: getDefaultReferenceClip(createVideoSourceClip(item), conditioning), conditioning, kind: 'video' };
+};
+
/**
* Default the first image to max detail and later images to generation-matched detail to limit repeatedly attended
* reference rows; users may override each.
@@ -895,6 +913,64 @@ export const applyReferenceExtendSourceVideo = (
return videoCount >= maxVideos ? references : [...references, linked];
};
+/**
+ * The panel patch that makes `sourceVideo` the Initial Video, or clears it. An initial video displaces the first
+ * frame and a conditioning clip; on a reference-extend panel it also links its continuity anchor into the
+ * references. Returns null when that panel has no reference slot left for the anchor: the clip must not be set
+ * without it.
+ */
+export const getInitialVideoPatch = ({
+ maxVideos,
+ numFrames,
+ referenceExtend,
+ references,
+ sourceVideo,
+}: {
+ maxVideos: number;
+ numFrames: number;
+ referenceExtend: boolean;
+ references: VideoReferenceItem[];
+ sourceVideo: VideoSourceClip | null;
+}): Partial<VideoWidgetValues> | null => {
+ const displaced = sourceVideo ? { conditioningClip: null, firstFrameImage: null } : {};
+
+ if (!referenceExtend) {
+ return { sourceVideo, ...displaced };
+ }
+
+ const linked = applyReferenceExtendSourceVideo(references, sourceVideo, maxVideos, numFrames);
+
+ // Unchanged identity is the capacity refusal; clearing cannot overflow.
+ return sourceVideo && linked === references ? null : { references: linked, sourceVideo, ...displaced };
+};
+
+/**
+ * The panel patch for a new reference list. References displace the frame slots and a conditioning clip, and the
+ * initial video too unless the panel extends from it; generation continues from the last reference, so a
+ * reference-extend panel keeps its continuity anchor pinned last.
+ */
+export const getReferencesPatch = ({
+ referenceExtend,
+ references,
+}: {
+ referenceExtend: boolean;
+ references: VideoReferenceItem[];
+}): Partial<VideoWidgetValues> => {
+ const next = referenceExtend ? pinReferenceExtendAnchor(references) : references;
+
+ return {
+ references: next,
+ ...(next.length > 0
+ ? {
+ conditioningClip: null,
+ firstFrameImage: null,
+ lastFrameImage: null,
+ ...(referenceExtend ? {} : { sourceVideo: null }),
+ }
+ : {}),
+ };
+};
+
/**
* Clear deleted media from raw values before normalization can mask conflicting slots; preserve identity when
* unchanged.
diff --git a/invokeai/frontend/webv2/src/features/video/index.ts b/invokeai/frontend/webv2/src/features/video/index.ts
index 6f535aedb8..304b8a74eb 100644
--- a/invokeai/frontend/webv2/src/features/video/index.ts
+++ b/invokeai/frontend/webv2/src/features/video/index.ts
@@ -18,9 +18,12 @@ export {
clearDeletedVideoMedia,
cloneVideoWidgetValues,
createVideoConditioningClip,
+ createVideoReferenceEntry,
createVideoSourceClip,
getDefaultConditioningRole,
getDefaultReferenceConditioning,
+ getInitialVideoPatch,
+ getReferencesPatch,
isImageWithDims,
isVideoAspectRatioId,
isVideoReferenceConditioning,
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
index bc0e1668b4..510c78060b 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoReferenceListField.tsx
@@ -17,10 +17,8 @@ import { galleryImageUrls, galleryVideoUrls, isGalleryItemDragData } from '@feat
import { resolveMiniMaxH3ReferenceImage } from '@features/video/core/dimensions';
import {
clampReferenceSampleFrames,
- createVideoSourceClip,
+ createVideoReferenceEntry,
formatReferencePromptLabels,
- getDefaultReferenceClip,
- getDefaultReferenceConditioning,
getDefaultReferenceImageDetail,
referencePromptLabels,
referenceSampleFrames,
@@ -496,17 +494,8 @@ export const VideoReferenceListField = memo(function VideoReferenceListField({
const addVideoItem = useCallback(
(item: GalleryVideoItem) => {
- // Do not persist mediaOrigin on the clip: project import reuploads under a new name without rederiving it.
- const conditioning = getDefaultReferenceConditioning(item.mediaOrigin);
- const clip = createVideoSourceClip(item);
// Construct once so the caller retains the same entry identity through reorders.
- const entry: Extract<VideoReferenceItem, { kind: 'video' }> = {
- // Footage defaults to a short sample; audio uses the whole clip. References are truncated, not
- // crossfade-joined.
- clip: getDefaultReferenceClip(clip, conditioning),
- conditioning,
- kind: 'video',
- };
+ const entry = createVideoReferenceEntry(item);
let declined = false;
setErrorMessage(null);
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx
index 418bc282e9..92f51d4735 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx
@@ -20,11 +20,11 @@ import {
snapLtx2FramesDown,
} from '@features/video/core/dimensions';
import {
- applyReferenceExtendSourceVideo,
applyReferenceExtendNumFrames,
canPlaceReferenceExtendAnchor,
+ getInitialVideoPatch,
+ getReferencesPatch,
isVideoTargetResolution,
- pinReferenceExtendAnchor,
normalizeVideoWidgetValues,
resolveVideoMode,
VIDEO_ASPECT_RATIO_IDS,
@@ -295,32 +295,29 @@ export const VideoWidgetView = () => {
);
const setSourceVideo = useCallback(
(sourceVideo: VideoSourceClip | null) => {
- if (referenceExtend) {
- if (!referencesRef.current.live || referencesRef.current.projectId !== projectId) {
- return;
- }
- const current = referencesRef.current.references;
- const references = applyReferenceExtendSourceVideo(current, sourceVideo, maxVideoReferences, values.numFrames);
-
- // Unchanged identity means no tail-reference slot is available: refuse the whole drop so the clip cannot
- // be set without its continuity anchor. Clearing cannot overflow.
- if (sourceVideo && references === current) {
- toaster.create({
- description: t('widgets.video.referenceExtendCapFullDescription'),
- title: t('widgets.video.referenceExtendCapFull'),
- type: 'warning',
- });
-
- return;
- }
- patch({
- references,
- sourceVideo,
- ...(sourceVideo ? { conditioningClip: null, firstFrameImage: null } : {}),
+ if (referenceExtend && (!referencesRef.current.live || referencesRef.current.projectId !== projectId)) {
+ return;
+ }
+ const placement = getInitialVideoPatch({
+ maxVideos: maxVideoReferences,
+ numFrames: values.numFrames,
+ referenceExtend,
+ references: referencesRef.current.references,
+ sourceVideo,
+ });
+
+ // No tail-reference slot is available: refuse the whole drop so the clip cannot be set without its
+ // continuity anchor.
+ if (!placement) {
+ toaster.create({
+ description: t('widgets.video.referenceExtendCapFullDescription'),
+ title: t('widgets.video.referenceExtendCapFull'),
+ type: 'warning',
});
+
return;
}
- patch({ sourceVideo, ...(sourceVideo ? { conditioningClip: null, firstFrameImage: null } : {}) });
+ patch(placement);
},
[maxVideoReferences, patch, projectId, referenceExtend, t, values.numFrames]
);
@@ -336,19 +333,7 @@ export const VideoWidgetView = () => {
if (updated === referencesRef.current.references) {
return;
}
- const next = referenceExtend ? pinReferenceExtendAnchor(updated) : updated;
-
- patch({
- references: next,
- ...(next.length > 0
- ? {
- conditioningClip: null,
- firstFrameImage: null,
- lastFrameImage: null,
- ...(referenceExtend ? {} : { sourceVideo: null }),
- }
- : {}),
- });
+ patch(getReferencesPatch({ referenceExtend, references: updated }));
},
[patch, projectId, referenceExtend]
);
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 73dd737192..06277289f7 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
@@ -39,6 +39,7 @@ const image = (imageName: string): GalleryImage => ({
const createActions = (deleteItems: ImageActions['deleteItems']): ImageActions => ({
canUseAsReferenceImage: false,
+ canUseAsReferenceVideo: false,
copyImage: vi.fn(() => Promise.resolve()),
createCanvasFromImages: vi.fn(() => Promise.resolve()),
deleteItems,
@@ -63,7 +64,9 @@ const createActions = (deleteItems: ImageActions['deleteItems']): ImageActions =
setItemsStarred: vi.fn(() => Promise.resolve()),
setImagesStarred: vi.fn(() => Promise.resolve()),
savePromptAsTemplate: vi.fn(),
+ sendToInitialVideo: vi.fn(),
useAsReferenceImage: vi.fn(),
+ useAsReferenceVideo: vi.fn(),
});
let host: HTMLDivElement | null = null;
@@ -329,6 +332,31 @@ describe('ImageContextMenu new canvas from image', () => {
});
});
+describe('ImageContextMenu video placement', () => {
+ const renderVideoMenu = (actions: ImageActions, video: GalleryItem) =>
+ renderItemMenu(actions, { itemRefs: [{ kind: 'video', name: video.name }], items: [video], x: 20, y: 20 });
+
+ it('hands the video to the Initial Video and reference actions', async () => {
+ const video = item('video', 'clip.mp4');
+ const actions = { ...createActions(vi.fn()), canUseAsReferenceVideo: true };
+ await renderVideoMenu(actions, video);
+
+ await interact(() => getMenuItem('Extend in Video').click());
+ expect(actions.sendToInitialVideo).toHaveBeenCalledExactlyOnceWith(video);
+
+ await interact(() => getMenuItem('Use as Reference Video').click());
+ expect(actions.useAsReferenceVideo).toHaveBeenCalledExactlyOnceWith(video);
+ });
+
+ it('disables Use as Reference Video when the Video panel cannot take another', async () => {
+ const actions = createActions(vi.fn());
+ await renderVideoMenu(actions, item('video', 'clip.mp4'));
+
+ expect(getMenuItem('Use as Reference Video').getAttribute('aria-disabled')).toBe('true');
+ expect(getMenuItem('Extend in Video').getAttribute('aria-disabled')).not.toBe('true');
+ });
+});
+
describe('ImageContextMenu mixed-media action visibility', () => {
it('shows common actions for a single video and hides every image-only action', async () => {
const video = item('video', 'clip.mp4');
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
index 8f382bf269..dcf29f3d74 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx
@@ -9,7 +9,6 @@ import {
legacyGeneratedImageToGalleryItem,
toGalleryItemKey,
} from '@features/gallery';
-import { createVideoSourceClip } from '@features/video';
import { MenuContent, MenuIconItem } from '@platform/ui';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
@@ -24,6 +23,7 @@ import {
EyeIcon,
FileImageIcon,
FileJsonIcon,
+ FilmIcon,
FolderIcon,
ImageIcon,
ImagesIcon,
@@ -313,8 +313,6 @@ const SingleItemMenuItems = ({
[actions, itemRef]
);
const handleDelete = useCallback(() => onRequestDeletion([itemRef]), [itemRef, onRequestDeletion]);
- const { generation, widgets } = useWorkbenchCommands();
- const openWidget = useOpenWorkbenchWidget();
const [videoRecallCapabilities, setVideoRecallCapabilities] = useState<VideoRecallCapabilities>(
EMPTY_VIDEO_RECALL_CAPABILITIES
);
@@ -368,26 +366,15 @@ const SingleItemMenuItems = ({
const handleVideoRecallPrompts = useMemo(() => makeVideoRecallHandler('prompts'), [makeVideoRecallHandler]);
const handleVideoRecallSeed = useMemo(() => makeVideoRecallHandler('seed'), [makeVideoRecallHandler]);
const handleExtendInVideo = useCallback(() => {
- if (item.kind !== 'video') {
- return;
+ if (item.kind === 'video') {
+ actions.sendToInitialVideo(item);
}
-
- openWidget('video', { preferredRegions: ['left'] });
- // An initial video, a first frame, and Ref2VA references all claim the same
- // conditioning slot: extending clears the rivals.
- widgets.patchValues('video', {
- firstFrameImage: null,
- references: [],
- sourceVideo: createVideoSourceClip({
- durationSeconds: item.durationSeconds,
- fps: item.fps,
- height: item.height,
- name: item.name,
- width: item.width,
- }),
- });
- generation.setSource('video');
- }, [generation, item, openWidget, widgets]);
+ }, [actions, item]);
+ const handleUseAsReferenceVideo = useCallback(() => {
+ if (item.kind === 'video') {
+ actions.useAsReferenceVideo(item);
+ }
+ }, [actions, item]);
return (
<>
@@ -452,6 +439,13 @@ const SingleItemMenuItems = ({
value="extend-in-video"
onClick={handleExtendInVideo}
/>
+ <ContextMenuItem
+ disabled={!actions.canUseAsReferenceVideo}
+ icon={FilmIcon}
+ label="Use as Reference Video"
+ value="use-as-reference-video"
+ onClick={handleUseAsReferenceVideo}
+ />
</>
) : null}
{item.kind === 'video' && previewVideoActions && previewVideoActions.itemKey === toGalleryItemKey(item) ? (
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.placement.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.placement.test.ts
new file mode 100644
index 0000000000..8657edf200
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.placement.test.ts
@@ -0,0 +1,155 @@
+import type { ModelConfig } from '@features/models';
+import type { VideoReferenceItem } from '@features/video';
+
+import { createDefaultVideoWidgetValues, createVideoReferenceEntry } from '@features/video';
+import { describe, expect, it } from 'vitest';
+
+import { appendReferenceVideo, canAppendReferenceVideo, placeInitialVideo } from './executeVideoRecall';
+
+const model = (fields: Record<string, unknown>) =>
+ ({
+ file_size: 1,
+ hash: 'h',
+ path: '/m',
+ source: 'local',
+ source_type: 'path',
+ type: 'main',
+ ...fields,
+ }) as ModelConfig;
+
+const WAN_I2V = model({ base: 'wan', format: 'diffusers', key: 'wan-i2v', name: 'Wan I2V', variant: 'i2v_a14b' });
+const WAN_T2V = model({ base: 'wan', format: 'diffusers', key: 'wan-t2v', name: 'Wan T2V', variant: 't2v_a14b' });
+// A Ref2VA Diffusers folder is only a component source; the selectable main is a checkpoint.
+const REF2VA = model({
+ base: 'minimax-h3',
+ format: 'checkpoint',
+ key: 'h3-ref2va',
+ name: 'H3 Ref2VA',
+ variant: 'ref2va',
+});
+
+const clip = { durationSeconds: 5, fps: 16, height: 480, name: 'clip.mp4', width: 832 };
+const videoReference = (name: string): Extract<VideoReferenceItem, { kind: 'video' }> =>
+ createVideoReferenceEntry({ ...clip, name });
+
+const panel = (selected: ModelConfig, overrides: Record<string, unknown> = {}) => ({
+ ...(createDefaultVideoWidgetValues([selected]) as unknown as Record<string, unknown>),
+ ...overrides,
+});
+
+describe('placeInitialVideo', () => {
+ it('sets the initial video and displaces the first frame on a model that extends clips', () => {
+ const placement = placeInitialVideo({
+ models: [WAN_I2V],
+ video: clip,
+ videoValues: panel(WAN_I2V, { firstFrameImage: { height: 480, image_name: 'first.png', width: 832 } }),
+ });
+
+ expect(placement).toMatchObject({
+ patch: { conditioningClip: null, firstFrameImage: null, sourceVideo: { video_name: 'clip.mp4' } },
+ status: 'placed',
+ usable: true,
+ });
+ expect(placement.status === 'placed' && 'references' in placement.patch).toBe(false);
+ });
+
+ it('still fills the slot on a model that cannot extend, but says it will go unused', () => {
+ expect(placeInitialVideo({ models: [WAN_T2V], video: clip, videoValues: panel(WAN_T2V) })).toMatchObject({
+ status: 'placed',
+ usable: false,
+ });
+ });
+
+ it('links the continuity anchor on a reference-extend panel, pinned after the existing references', () => {
+ const placement = placeInitialVideo({
+ models: [REF2VA],
+ video: clip,
+ videoValues: panel(REF2VA, { references: [videoReference('dance.mp4')] }),
+ });
+
+ // Ref2VA has no extend mode of its own; it extends through the linked reference.
+ expect(placement).toMatchObject({ status: 'placed', usable: true });
+ const references = placement.status === 'placed' ? (placement.patch.references ?? []) : [];
+ expect(
+ references.map((entry) => (entry.kind === 'video' ? [entry.clip.video_name, entry.fromSourceVideo] : []))
+ ).toEqual([
+ ['dance.mp4', undefined],
+ ['clip.mp4', true],
+ ]);
+ });
+
+ it('refuses a reference-extend panel with no video reference slot left for the anchor', () => {
+ const full = ['a.mp4', 'b.mp4', 'c.mp4'].map(videoReference);
+
+ expect(
+ placeInitialVideo({ models: [REF2VA], video: clip, videoValues: panel(REF2VA, { references: full }) })
+ ).toEqual({
+ status: 'full',
+ });
+ });
+});
+
+describe('appendReferenceVideo', () => {
+ it('appends footage as a short video-and-audio sample, and wrapped audio whole as a soundtrack', () => {
+ // 20 s at 16 fps = 320 frames: longer than the 200-frame default sample.
+ const long = { ...clip, durationSeconds: 20, name: 'long.mp4' };
+ const append = (video: typeof long & { mediaOrigin?: string }) => {
+ const placement = appendReferenceVideo({ models: [REF2VA], video, videoValues: panel(REF2VA) });
+ return placement.status === 'appended' ? placement.patch.references?.[0] : undefined;
+ };
+
+ expect(append(long)).toMatchObject({
+ clip: { endFrame: 199, numFrames: 320, startFrame: 0, video_name: 'long.mp4' },
+ conditioning: 'video_audio',
+ kind: 'video',
+ });
+ expect(append({ ...long, mediaOrigin: 'audio_upload' })).toMatchObject({
+ clip: { endFrame: 319, startFrame: 0 },
+ conditioning: 'audio',
+ });
+ });
+
+ it('counts only video references against the video cap', () => {
+ const image: VideoReferenceItem = {
+ detail: 'max',
+ image: { height: 512, image_name: 'ref.png', width: 512 },
+ kind: 'image',
+ };
+ const videoValues = panel(REF2VA, { references: [videoReference('a.mp4'), videoReference('b.mp4'), image, image] });
+
+ expect(canAppendReferenceVideo({ models: [REF2VA], videoValues })).toBe(true);
+ expect(appendReferenceVideo({ models: [REF2VA], video: clip, videoValues }).status).toBe('appended');
+ });
+
+ it('keeps a reference-extend panel continuity anchor last', () => {
+ const anchor: VideoReferenceItem = { ...videoReference('source.mp4'), fromSourceVideo: true };
+ const placement = appendReferenceVideo({
+ models: [REF2VA],
+ video: clip,
+ videoValues: panel(REF2VA, { references: [anchor] }),
+ });
+
+ const references = placement.status === 'appended' ? (placement.patch.references ?? []) : [];
+ expect(references.map((entry) => (entry.kind === 'video' ? entry.clip.video_name : null))).toEqual([
+ 'clip.mp4',
+ 'source.mp4',
+ ]);
+ });
+
+ it('declines when every video reference slot is taken', () => {
+ const videoValues = panel(REF2VA, { references: ['a.mp4', 'b.mp4', 'c.mp4'].map(videoReference) });
+
+ expect(appendReferenceVideo({ models: [REF2VA], video: clip, videoValues })).toEqual({ status: 'full' });
+ expect(canAppendReferenceVideo({ models: [REF2VA], videoValues })).toBe(false);
+ });
+
+ it('declines, rather than switching models, when the panel model takes no reference videos', () => {
+ const videoValues = panel(WAN_I2V);
+
+ expect(appendReferenceVideo({ models: [WAN_I2V, REF2VA], video: clip, videoValues })).toEqual({
+ status: 'unsupported',
+ });
+ expect(canAppendReferenceVideo({ models: [WAN_I2V, REF2VA], videoValues })).toBe(false);
+ expect(canAppendReferenceVideo({ models: [REF2VA], videoValues: panel(REF2VA) })).toBe(true);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts
index abd92da2de..dfb36c9a78 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts
@@ -1,6 +1,6 @@
import type { GalleryVideoItem } from '@features/gallery';
import type { ModelConfig } from '@features/models';
-import type { VideoReferenceItem } from '@features/video';
+import type { VideoReferenceItem, VideoWidgetValues } from '@features/video';
import type { AccountScope } from '@platform/state/accountLifecycle';
import type { WorkbenchCommands } from '@workbench/workbenchStore';
@@ -8,8 +8,11 @@ import { galleryImages, galleryItems, galleryVideos } from '@features/gallery';
import {
createDefaultVideoWidgetValues,
createVideoConditioningClip,
+ createVideoReferenceEntry,
createVideoSourceClip,
getDefaultReferenceConditioning,
+ getInitialVideoPatch,
+ getReferencesPatch,
getVideoModelPolicy,
isVideoReferenceConditioning,
normalizeVideoWidgetValues,
@@ -77,6 +80,28 @@ export const getCurrentVideoValues = ({
return syncVideoWidgetValuesWithModels(normalized, models);
};
+interface VideoRecallNotice {
+ message: string;
+ title: string;
+}
+
+const reportVideoRecallError = (
+ commands: Pick<WorkbenchCommands, 'notifications'>,
+ owner: AccountScope,
+ error: unknown,
+ projectId: string | undefined
+): false => {
+ if (isAccountScopeCurrent(owner)) {
+ commands.notifications.reportError({
+ area: 'video-recall',
+ message: toErrorMessage(error),
+ namespace: 'generation',
+ projectId,
+ });
+ }
+ return false;
+};
+
export const executeVideoRecall = async ({
commands,
getVideoValues,
@@ -101,26 +126,113 @@ export const executeVideoRecall = async ({
return false;
}
+ let metadata: unknown;
+
try {
- const metadata = await loadVideoMetadata(item.name, owner);
+ metadata = await loadVideoMetadata(item.name, owner);
+ } catch (error: unknown) {
+ return reportVideoRecallError(commands, owner, error, projectId);
+ }
+ return applyVideoRecallMetadata({
+ commands,
+ emptyNotice: {
+ message: 'This video does not include supported Video metadata.',
+ title: 'No recallable video data',
+ },
+ getVideoValues,
+ kind,
+ metadata,
+ models,
+ owner,
+ projectId,
+ });
+};
+
+/**
+ * Apply a video metadata record — read from a gallery video, or sent by the external recall API — to the Video
+ * panel: build the values, hydrate the media it names from the gallery, drop media the resulting model cannot use,
+ * and commit. Resolves whether anything was applied.
+ */
+export const applyVideoRecallMetadata = async ({
+ commands,
+ emptyNotice,
+ getVideoValues,
+ kind,
+ metadata,
+ models,
+ owner,
+ partial = false,
+ projectId,
+ requireGenerationMode = true,
+}: {
+ commands: Pick<WorkbenchCommands, 'notifications' | 'widgets'>;
+ /** Shown when nothing in the record applies. */
+ emptyNotice: VideoRecallNotice;
+ getVideoValues: () => Record<string, unknown>;
+ kind: VideoRecallKind;
+ metadata: unknown;
+ models: readonly ModelConfig[];
+ owner: AccountScope;
+ /** See `buildVideoRecallSettings`. */
+ partial?: boolean;
+ projectId?: string;
+ /** See `buildVideoRecallSettings`. */
+ requireGenerationMode?: boolean;
+}): Promise<boolean> => {
+ try {
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 });
+ const result = buildVideoRecallSettings({
+ currentValues,
+ kind,
+ metadata,
+ models,
+ partial,
+ requireGenerationMode,
+ });
if (!result) {
- commands.notifications.add({
- kind: 'info',
- message: 'This video does not include supported Video metadata.',
- title: 'No recallable video data',
- });
+ commands.notifications.add({ kind: 'info', ...emptyNotice });
return false;
}
+ // A partial recall names media on top of the panel's own. One the panel's model cannot use would still displace
+ // the held media it conflicts with before the mode check below dropped it, so it is dropped up front instead.
+ if (partial && result.values.model) {
+ const policy = getVideoModelPolicy(result.values.model, result.values);
+ const modes = policy.modes;
+ const names = result.mediaNames;
+
+ if (!modes.includes('reference')) {
+ names.references = [];
+ }
+ if (!modes.includes('first-frame') && !modes.includes('first-last')) {
+ names.firstFrameName = null;
+ }
+ if (!modes.includes('last-frame') && !modes.includes('first-last')) {
+ names.lastFrameName = null;
+ }
+ if (!modes.includes('extend') && !policy.references?.extend) {
+ names.sourceVideoName = null;
+ names.sourceVideoTrim = null;
+ }
+ if (
+ names.conditioningClip &&
+ !modes.includes(names.conditioningClip.role === 'audio' ? 'audio-to-video' : 'video-to-audio')
+ ) {
+ names.conditioningClip = null;
+ }
+ }
+
// Resolve media names against the gallery for dimensions/probe data and drop deleted references.
if (result.fields.includes('media')) {
+ // A full recall that cleared held media changed the panel even if nothing named below hydrates.
+ const clearedMedia = (
+ ['conditioningClip', 'firstFrameImage', 'lastFrameImage', 'references', 'sourceVideo'] as const
+ ).some((slot) => result.values[slot] !== currentValues[slot]);
let recalledMedia = false;
const { firstFrameName, lastFrameName, sourceVideoName } = result.mediaNames;
const frameNames = [firstFrameName, lastFrameName].filter((name): name is string => name !== null);
@@ -282,14 +394,15 @@ export const executeVideoRecall = async ({
lastFrameImage: null,
references,
// A source video recorded alongside references is reference-extend
- // state (hydrated above) — keep it; clear only a leftover.
- sourceVideo: result.mediaNames.sourceVideoName ? result.values.sourceVideo : null,
+ // state (hydrated above) — keep it; clear only a leftover. A partial
+ // recall keeps the panel's own, subject to the mode check below.
+ sourceVideo: result.mediaNames.sourceVideoName || partial ? result.values.sourceVideo : null,
};
recalledMedia = true;
}
}
- if (!recalledMedia) {
+ if (!recalledMedia && !clearedMedia) {
result.fields = result.fields.filter((field) => field !== 'media');
}
@@ -301,6 +414,22 @@ export const executeVideoRecall = async ({
const policy = getVideoModelPolicy(effectiveModel, result.values);
const modes = policy.modes;
const referenceExtend = Boolean(policy.references?.extend);
+
+ // A partial recall can replace the references or the initial video alone, which on a reference-extend panel
+ // would orphan the clip's continuity reference or leave it pointing at the previous clip. Relink it the way
+ // the panel's Initial Video field does, dropping the clip when no reference slot is left for it.
+ if (partial && referenceExtend && result.values.sourceVideo) {
+ const linked = getInitialVideoPatch({
+ maxVideos: policy.references?.maxVideos ?? 0,
+ numFrames: result.values.numFrames,
+ referenceExtend,
+ references: result.values.references,
+ sourceVideo: result.values.sourceVideo,
+ });
+
+ result.values = linked ? { ...result.values, ...linked } : { ...result.values, sourceVideo: null };
+ }
+
let { firstFrameImage, lastFrameImage, sourceVideo } = result.values;
let references = result.values.references;
@@ -345,11 +474,7 @@ export const executeVideoRecall = async ({
}
if (result.fields.length === 0) {
- commands.notifications.add({
- kind: 'info',
- message: 'This video does not include supported Video metadata.',
- title: 'No recallable video data',
- });
+ commands.notifications.add({ kind: 'info', ...emptyNotice });
return false;
}
@@ -375,16 +500,107 @@ export const executeVideoRecall = async ({
});
return true;
} catch (error: unknown) {
- if (!isAccountScopeCurrent(owner)) {
- return false;
+ return reportVideoRecallError(commands, owner, error, projectId);
+ }
+};
+
+// Placing a gallery video in the Video panel. Kept in this module rather than a file of its own: the gallery's actions
+// load it on every editor route, and a new module there is a new entry in the routes' pinned source-owner sets.
+
+/** What placing a video needs to know about it; gallery items and the external recall event both carry it. */
+export interface PlaceableVideo {
+ durationSeconds: number;
+ fps?: number;
+ height: number;
+ mediaOrigin?: string;
+ name: string;
+ width: number;
+}
+
+export type InitialVideoPlacement =
+ | {
+ patch: Partial<VideoWidgetValues>;
+ status: 'placed';
+ /** Whether the panel's model can generate from an initial video; the slot is filled either way. */
+ usable: boolean;
}
+ | { status: 'full' };
- commands.notifications.reportError({
- area: 'video-recall',
- message: toErrorMessage(error),
- namespace: 'generation',
- projectId,
- });
- return false;
+/** Set the video as the Video panel's Initial Video, exactly as the panel's own Initial Video field would. */
+export const placeInitialVideo = ({
+ models,
+ video,
+ videoValues,
+}: {
+ models: readonly ModelConfig[];
+ video: PlaceableVideo;
+ videoValues: Record<string, unknown>;
+}): InitialVideoPlacement => {
+ const values = getCurrentVideoValues({ models, videoValues });
+ const policy = values.model ? getVideoModelPolicy(values.model, values) : null;
+ const referenceExtend = Boolean(policy?.references?.extend);
+ const patch = getInitialVideoPatch({
+ maxVideos: policy?.references?.maxVideos ?? 0,
+ numFrames: values.numFrames,
+ referenceExtend,
+ references: values.references,
+ sourceVideo: createVideoSourceClip(video),
+ });
+
+ return patch
+ ? { patch, status: 'placed', usable: Boolean(policy && (policy.modes.includes('extend') || referenceExtend)) }
+ : { status: 'full' };
+};
+
+export type ReferenceVideoPlacement =
+ | { patch: Partial<VideoWidgetValues>; status: 'appended' }
+ | { status: 'full' | 'unsupported' };
+
+const getReferenceVideoRoom = (values: VideoWidgetValues): 'available' | 'full' | 'unsupported' => {
+ const policy = values.model ? getVideoModelPolicy(values.model, values) : null;
+
+ if (!policy?.references || !policy.modes.includes('reference')) {
+ return 'unsupported';
}
+
+ return values.references.filter((entry) => entry.kind === 'video').length < policy.references.maxVideos
+ ? 'available'
+ : 'full';
+};
+
+/** Whether the Video panel's model takes reference videos and has room for another. */
+export const canAppendReferenceVideo = ({
+ models,
+ videoValues,
+}: {
+ models: readonly ModelConfig[];
+ videoValues: Record<string, unknown>;
+}): boolean => getReferenceVideoRoom(getCurrentVideoValues({ models, videoValues })) === 'available';
+
+/** Append the video to the Video panel's references with the defaults the References field gives a new video. */
+export const appendReferenceVideo = ({
+ models,
+ video,
+ videoValues,
+}: {
+ models: readonly ModelConfig[];
+ video: PlaceableVideo;
+ videoValues: Record<string, unknown>;
+}): ReferenceVideoPlacement => {
+ const values = getCurrentVideoValues({ models, videoValues });
+ const room = getReferenceVideoRoom(values);
+
+ if (room !== 'available') {
+ return { status: room };
+ }
+
+ const referenceExtend = Boolean(values.model && getVideoModelPolicy(values.model, values).references?.extend);
+
+ return {
+ patch: getReferencesPatch({
+ referenceExtend,
+ references: [...values.references, createVideoReferenceEntry(video)],
+ }),
+ status: 'appended',
+ };
};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts b/invokeai/frontend/webv2/src/workbench/image-actions/index.ts
index 64148040c0..856bc36ffa 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/index.ts
@@ -16,6 +16,12 @@ export {
type ImageRecallResult,
} from './imageRecall';
export { executeImageRecall, getCurrentGenerateValues } from './executeImageRecall';
+export {
+ appendReferenceVideo,
+ applyVideoRecallMetadata,
+ placeInitialVideo,
+ type PlaceableVideo,
+} from './executeVideoRecall';
export { getImageRecallVerb, IMAGE_RECALL_KINDS } from './RecallActionButtons';
export { getSelectedGalleryImage, getSelectedGalleryImageFromValues } from './selectedImage';
export { useImageActions, type ImageActions } from './useImageActions';
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallEventRuntime.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallEventRuntime.ts
new file mode 100644
index 0000000000..cd330408ba
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallEventRuntime.ts
@@ -0,0 +1,119 @@
+import type { ModelConfig } from '@features/models';
+import type { AccountScope } from '@platform/state/accountLifecycle';
+import type { SocketHub } from '@platform/transport/socketHub';
+import type { WorkbenchCommands, WorkbenchQueries } from '@workbench/workbenchStore';
+
+import { ensureModelsLoaded, getModelsSnapshot } from '@features/models';
+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
+
+export interface RecallRuntime {
+ dispose(): void;
+}
+
+/** A raw socket payload with the project that was active when it arrived. */
+export interface PendingRecallEvent {
+ payload: unknown;
+ projectId: string;
+}
+
+const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
+
+/**
+ * Apply one kind of external recall event to its arrival-time project, strictly in arrival order so a later event
+ * observes an earlier one's changes (an append after a replace). Buffered replay events run first. Each event waits
+ * for the model catalog and is dropped when it belongs to another user or outlives the account it arrived under.
+ */
+export const createRecallEventRuntime = <Event extends { user_id: string }>({
+ apply,
+ area,
+ commands,
+ eventName,
+ getSessionUserId = () => null,
+ hub,
+ isEvent,
+ queries,
+ replay = [],
+}: {
+ apply: (event: Event, context: { models: ModelConfig[]; owner: AccountScope; projectId: string }) => Promise<unknown>;
+ /** The notification area failures are reported under. */
+ area: string;
+ commands: Pick<WorkbenchCommands, 'notifications'>;
+ eventName: string;
+ /**
+ * The signed-in user in multi-user mode, or `null` to accept every event. Admin sockets also receive other users'
+ * image recall events, which must not rewrite the admin's own panels.
+ */
+ getSessionUserId?: () => string | null;
+ hub: Pick<SocketHub, 'on'>;
+ isEvent: (payload: unknown) => payload is Event;
+ queries: Pick<WorkbenchQueries, 'getSnapshot'>;
+ replay?: readonly PendingRecallEvent[];
+}): RecallRuntime => {
+ let disposed = false;
+ let chain: Promise<void> = Promise.resolve();
+
+ const enqueue = ({ payload, projectId }: PendingRecallEvent) => {
+ if (disposed || !isEvent(payload)) {
+ return;
+ }
+
+ const sessionUserId = getSessionUserId();
+ if (sessionUserId !== null && payload.user_id !== sessionUserId) {
+ return;
+ }
+
+ const owner = captureAccountScope();
+ const reportError = (error: unknown) => {
+ if (!disposed && isAccountScopeCurrent(owner)) {
+ commands.notifications.reportError({
+ area,
+ message: toErrorMessage(error),
+ namespace: 'generation',
+ projectId,
+ });
+ }
+ };
+
+ chain = chain
+ .then(async () => {
+ if (disposed || !isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ // The models store never rejects; a failed catalog fetch is recorded as
+ // its error status, which would otherwise read as "no model selected".
+ await ensureModelsLoaded();
+ if (disposed || !isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ const snapshot = getModelsSnapshot();
+ if (snapshot.status === 'error') {
+ reportError(snapshot.error ?? 'Failed to load models.');
+ return;
+ }
+
+ await apply(payload, { models: snapshot.models, owner, projectId });
+ })
+ // One failing event must not wedge the chain for every later one.
+ .catch(reportError);
+ };
+
+ for (const pending of replay) {
+ enqueue(pending);
+ }
+
+ const detach = hub.on(eventName, (payload: unknown) => {
+ enqueue({ payload, projectId: queries.getSnapshot().activeProject.id });
+ });
+
+ return {
+ dispose: () => {
+ if (disposed) {
+ return;
+ }
+ disposed = true;
+ detach();
+ },
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.test.ts
index 8d8d9dd207..6c291cb78d 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.test.ts
@@ -4,7 +4,7 @@ import type { TFunction } from 'i18next';
import { describe, expect, it, vi } from 'vitest';
-import { attachRecallParametersRuntime } from './recallParametersBridge';
+import { attachRecallParametersRuntime, attachVideoRecallRuntime } from './recallParametersBridge';
type SocketHandler = (payload: never) => void;
@@ -85,7 +85,8 @@ describe('attachRecallParametersRuntime', () => {
release = resolve;
})
);
- const bridge = attachRecallParametersRuntime({ ...deps, hub: socket.hub, load });
+ const getSessionUserId = () => 'owner';
+ const bridge = attachRecallParametersRuntime({ ...deps, getSessionUserId, hub: socket.hub, load });
expect(load).not.toHaveBeenCalled();
@@ -96,6 +97,8 @@ describe('attachRecallParametersRuntime', () => {
release({ createRecallParametersRuntime: deps.createRecallParametersRuntime });
await flush();
+ // The multi-user fence must survive the lazy hand-over: admins receive other users' recall events.
+ expect(deps.createRecallParametersRuntime).toHaveBeenCalledWith(expect.objectContaining({ getSessionUserId }));
socket.emit('recall_parameters_updated', event({ steps: 3 }));
expect(deps.received.map((entry) => [stepsOf(entry), entry.projectId])).toEqual([
@@ -152,3 +155,40 @@ describe('attachRecallParametersRuntime', () => {
bridge.dispose();
});
});
+
+describe('attachVideoRecallRuntime', () => {
+ it('loads the video runtime on its own event only, handing over the arrival project', async () => {
+ const socket = createFakeSocketHub();
+ const deps = createDeps();
+ const createVideoRecallRuntime = vi.fn(({ replay = [] }: RuntimeOptions) => {
+ deps.received.push(...replay);
+ return { dispose: deps.dispose };
+ });
+ const load = vi.fn(() => Promise.resolve({ createVideoRecallRuntime }));
+ const getSessionUserId = () => 'owner';
+ const openVideoWidget = vi.fn();
+ const bridge = attachVideoRecallRuntime({
+ ...deps,
+ commands: { ...deps.commands, widgets: {} as WorkbenchCommands['widgets'] },
+ getSessionUserId,
+ hub: socket.hub,
+ load,
+ openVideoWidget,
+ });
+
+ socket.emit('recall_parameters_updated', event({ steps: 1 }));
+ expect(load).not.toHaveBeenCalled();
+
+ socket.emit('video_recall_requested', { action: 'initial_video', user_id: 'owner' });
+ await flush();
+
+ expect(load).toHaveBeenCalledTimes(1);
+ expect(createVideoRecallRuntime).toHaveBeenCalledWith(
+ expect.objectContaining({ getSessionUserId, openVideoWidget })
+ );
+ expect(deps.received).toEqual([{ payload: { action: 'initial_video', user_id: 'owner' }, projectId: 'project-1' }]);
+
+ bridge.dispose();
+ expect(deps.dispose).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.ts
index d5052698e8..51daa7fb0c 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersBridge.ts
@@ -2,41 +2,38 @@ import type { SocketHub } from '@platform/transport/socketHub';
import type { WorkbenchCommands, WorkbenchQueries } from '@workbench/workbenchStore';
import type { TFunction } from 'i18next';
-import type {
- createRecallParametersRuntime,
- PendingRecallEvent,
- RecallParametersRuntime,
-} from './recallParametersRuntime';
-
-interface RecallParametersRuntimeModule {
- createRecallParametersRuntime: typeof createRecallParametersRuntime;
-}
+import type { PendingRecallEvent, RecallRuntime } from './recallEventRuntime';
+import type { createRecallParametersRuntime } from './recallParametersRuntime';
+import type { createVideoRecallRuntime } from './videoRecallRuntime';
/**
- * Lazy-load recall on its first event; buffer events in arrival order with their original project. Report load
- * failures and retry on the next event.
+ * Lazy-load a recall runtime on its first event; buffer events in arrival order with their original project. Report
+ * load failures and retry on the next event. This module stays in the editor boot graph, so it imports the runtimes
+ * by type only.
*/
-export const attachRecallParametersRuntime = ({
+const attachLazyRecallRuntime = <Module>({
+ area,
commands,
- getSessionUserId,
+ create,
+ eventName,
hub,
- load = () => import('./recallParametersRuntime'),
+ load,
queries,
- t,
}: {
- commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;
- getSessionUserId?: () => string | null;
+ area: string;
+ commands: Pick<WorkbenchCommands, 'notifications'>;
+ create: (module: Module, replay: PendingRecallEvent[]) => RecallRuntime;
+ eventName: string;
hub: Pick<SocketHub, 'on'>;
- load?: () => Promise<RecallParametersRuntimeModule>;
- queries: Pick<WorkbenchQueries, 'getProject' | 'getSnapshot'>;
- t: TFunction;
-}): RecallParametersRuntime => {
+ load: () => Promise<Module>;
+ queries: Pick<WorkbenchQueries, 'getSnapshot'>;
+}): RecallRuntime => {
let disposed = false;
let loading: Promise<void> | null = null;
- let runtime: RecallParametersRuntime | null = null;
+ let runtime: RecallRuntime | null = null;
const pending: PendingRecallEvent[] = [];
- let detachBuffer: (() => void) | null = hub.on('recall_parameters_updated', (payload: unknown) => {
+ let detachBuffer: (() => void) | null = hub.on(eventName, (payload: unknown) => {
pending.push({ payload, projectId: queries.getSnapshot().activeProject.id });
loading ??= load()
.then((module) => {
@@ -48,14 +45,7 @@ export const attachRecallParametersRuntime = ({
// slip between the buffered ones and the runtime's own listener.
detachBuffer?.();
detachBuffer = null;
- runtime = module.createRecallParametersRuntime({
- commands,
- getSessionUserId,
- hub,
- queries,
- replay: pending.splice(0),
- t,
- });
+ runtime = create(module, pending.splice(0));
})
.catch((error: unknown) => {
loading = null;
@@ -63,7 +53,7 @@ export const attachRecallParametersRuntime = ({
if (!disposed) {
commands.notifications.reportError({
- area: 'recall-parameters',
+ area,
message: error instanceof Error ? error.message : String(error),
namespace: 'generation',
projectId: queries.getSnapshot().activeProject.id,
@@ -86,3 +76,67 @@ export const attachRecallParametersRuntime = ({
},
};
};
+
+interface RecallParametersRuntimeModule {
+ createRecallParametersRuntime: typeof createRecallParametersRuntime;
+}
+
+/** `recall_parameters_updated` → the Generate panel. */
+export const attachRecallParametersRuntime = ({
+ commands,
+ getSessionUserId,
+ hub,
+ load = () => import('./recallParametersRuntime'),
+ queries,
+ t,
+}: {
+ commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;
+ getSessionUserId?: () => string | null;
+ hub: Pick<SocketHub, 'on'>;
+ load?: () => Promise<RecallParametersRuntimeModule>;
+ queries: Pick<WorkbenchQueries, 'getProject' | 'getSnapshot'>;
+ t: TFunction;
+}): RecallRuntime =>
+ attachLazyRecallRuntime({
+ area: 'recall-parameters',
+ commands,
+ create: (module, replay) =>
+ module.createRecallParametersRuntime({ commands, getSessionUserId, hub, queries, replay, t }),
+ eventName: 'recall_parameters_updated',
+ hub,
+ load,
+ queries,
+ });
+
+interface VideoRecallRuntimeModule {
+ createVideoRecallRuntime: typeof createVideoRecallRuntime;
+}
+
+/** `video_recall_requested` → the Video panel. */
+export const attachVideoRecallRuntime = ({
+ commands,
+ getSessionUserId,
+ hub,
+ load = () => import('./videoRecallRuntime'),
+ openVideoWidget,
+ queries,
+ t,
+}: {
+ commands: Pick<WorkbenchCommands, 'notifications' | 'widgets'>;
+ getSessionUserId?: () => string | null;
+ hub: Pick<SocketHub, 'on'>;
+ load?: () => Promise<VideoRecallRuntimeModule>;
+ openVideoWidget: () => void;
+ queries: Pick<WorkbenchQueries, 'getProject' | 'getSnapshot'>;
+ t: TFunction;
+}): RecallRuntime =>
+ attachLazyRecallRuntime({
+ area: 'video-recall',
+ commands,
+ create: (module, replay) =>
+ module.createVideoRecallRuntime({ commands, getSessionUserId, hub, openVideoWidget, queries, replay, t }),
+ eventName: 'video_recall_requested',
+ hub,
+ load,
+ queries,
+ });
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.ts
index 5a9fe4f0db..bb33a758a1 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.ts
@@ -2,127 +2,51 @@ import type { SocketHub } from '@platform/transport/socketHub';
import type { WorkbenchCommands, WorkbenchQueries } from '@workbench/workbenchStore';
import type { TFunction } from 'i18next';
-import { ensureModelsLoaded, getModelsSnapshot } from '@features/models';
-import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
import { getProjectWidgetValues } from '@workbench/widgetState';
+import type { PendingRecallEvent, RecallRuntime } from './recallEventRuntime';
+
import { executeRecallParameters } from './executeRecallParameters';
+import { createRecallEventRuntime } from './recallEventRuntime';
import { isRecallParametersUpdatedEvent } from './recallParameters';
-export interface RecallParametersRuntime {
- dispose(): void;
-}
-
-/** A raw socket payload with the project that was active when it arrived. */
-export interface PendingRecallEvent {
- payload: unknown;
- projectId: string;
-}
-
-const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
-
-/**
- * Apply socket recall events to their arrival-time project, strictly in order so append observes preceding
- * replace. Buffered replay events run first.
- */
+/** Apply `recall_parameters_updated` events to their arrival-time project's Generate panel. */
export const createRecallParametersRuntime = ({
commands,
- getSessionUserId = () => null,
+ getSessionUserId,
hub,
queries,
- replay = [],
+ replay,
t,
}: {
commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;
- /**
- * The signed-in user in multi-user mode, or `null` to accept every event.
- * Admin sockets also receive other users' recall events, which must not
- * rewrite the admin's own panel.
- */
getSessionUserId?: () => string | null;
hub: Pick<SocketHub, 'on'>;
queries: Pick<WorkbenchQueries, 'getProject' | 'getSnapshot'>;
replay?: readonly PendingRecallEvent[];
/** Resolves against the current language at call time; captured once, at attach. */
t: TFunction;
-}): RecallParametersRuntime => {
- let disposed = false;
- let chain: Promise<void> = Promise.resolve();
-
- const enqueue = ({ payload, projectId }: PendingRecallEvent) => {
- if (disposed || !isRecallParametersUpdatedEvent(payload)) {
- return;
- }
-
- const sessionUserId = getSessionUserId();
- if (sessionUserId !== null && payload.user_id !== sessionUserId) {
- return;
- }
-
- const owner = captureAccountScope();
- const { parameters } = payload;
- const reportError = (error: unknown) => {
- if (!disposed && isAccountScopeCurrent(owner)) {
- commands.notifications.reportError({
- area: 'recall-parameters',
- message: toErrorMessage(error),
- namespace: 'generation',
- projectId,
- });
- }
- };
-
- chain = chain
- .then(async () => {
- if (disposed || !isAccountScopeCurrent(owner)) {
- return;
- }
-
- // The models store never rejects; a failed catalog fetch is recorded as
- // its error status, which would otherwise read as "no model selected".
- await ensureModelsLoaded();
- if (disposed || !isAccountScopeCurrent(owner)) {
- return;
- }
-
- const snapshot = getModelsSnapshot();
- if (snapshot.status === 'error') {
- reportError(snapshot.error ?? 'Failed to load models.');
- return;
- }
-
- await executeRecallParameters({
- commands,
- t,
- getGenerateValues: () => {
- const project = queries.getProject(projectId);
- return project ? getProjectWidgetValues(project, 'generate') : null;
- },
- models: snapshot.models,
- owner,
- parameters,
- projectId,
- });
- })
- // One failing event must not wedge the chain for every later one.
- .catch(reportError);
- };
-
- for (const pending of replay) {
- enqueue(pending);
- }
-
- const detach = hub.on('recall_parameters_updated', (payload: unknown) => {
- enqueue({ payload, projectId: queries.getSnapshot().activeProject.id });
+}): RecallRuntime =>
+ createRecallEventRuntime({
+ apply: ({ parameters }, { models, owner, projectId }) =>
+ executeRecallParameters({
+ commands,
+ t,
+ getGenerateValues: () => {
+ const project = queries.getProject(projectId);
+ return project ? getProjectWidgetValues(project, 'generate') : null;
+ },
+ models,
+ owner,
+ parameters,
+ projectId,
+ }),
+ area: 'recall-parameters',
+ commands,
+ eventName: 'recall_parameters_updated',
+ getSessionUserId,
+ hub,
+ isEvent: isRecallParametersUpdatedEvent,
+ queries,
+ replay,
});
-
- return {
- dispose: () => {
- if (disposed) {
- return;
- }
- disposed = true;
- detach();
- },
- };
-};
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
index 678624f7f2..5f73fe9e93 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx
@@ -177,6 +177,8 @@ vi.mock('@workbench/WorkbenchContext', () => ({
getSnapshot: (...args: unknown[]) => mocks.getSnapshot(...args),
isActiveProject: vi.fn(() => true),
}),
+ // Only the Video panel's reference capacity is selected; no test here exercises it.
+ useWorkbenchSelector: () => false,
}));
vi.mock('react-i18next', () => ({
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
index 221ee8379b..2bdd278788 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts
@@ -1,5 +1,7 @@
import type { GalleryItemActionContext, GalleryItemActions } from '@features/gallery/react';
import type { VaeModelConfig } from '@features/generation/contracts';
+import type { ModelConfig } from '@features/models';
+import type { WorkbenchSnapshot } from '@workbench/workbenchStore';
import {
galleryImages,
@@ -47,8 +49,8 @@ import {
} from '@workbench/canvas-operations/api';
import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';
-import { getProjectWidgetValues } from '@workbench/widgetState';
-import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';
+import { getProjectWidgetInstance, getProjectWidgetValues } from '@workbench/widgetState';
+import { useWorkbenchCommands, useWorkbenchQueries, useWorkbenchSelector } from '@workbench/WorkbenchContext';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -57,7 +59,12 @@ import type { RequestDeletionConfirmation } from './useDeletionConfirmation';
import { appendReferenceImage } from './appendReferenceImage';
import { recordCanvasImportError } from './canvasImportError';
import { executeImageRecall, executeLoadImageWorkflow, getCurrentGenerateValues } from './executeImageRecall';
-import { executeVideoRecall } from './executeVideoRecall';
+import {
+ appendReferenceVideo,
+ canAppendReferenceVideo,
+ executeVideoRecall,
+ placeInitialVideo,
+} from './executeVideoRecall';
import {
captureGalleryWidgetKeyValues,
collectGalleryStoreKnownItemFields,
@@ -87,6 +94,8 @@ import {
export interface ImageActions extends GalleryItemActions {
/** Whether the generate widget's current model can accept another reference image. */
canUseAsReferenceImage: boolean;
+ /** Whether the video widget's current model takes reference videos and has room for another. */
+ canUseAsReferenceVideo: boolean;
copyImage: (image: GalleryImage) => Promise<void>;
/** Opens a new project whose canvas holds these images as raster layers. */
createCanvasFromImages: (images: readonly GalleryImage[]) => Promise<void>;
@@ -108,14 +117,42 @@ export interface ImageActions extends GalleryItemActions {
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>;
+ /** Sets a gallery video as the Video panel's Initial Video, as that field would. */
+ sendToInitialVideo: (item: GalleryVideoItem) => void;
/** Opens the generate widget's template editor prefilled from this image's prompts. */
savePromptAsTemplate: (image: GalleryImage) => Promise<void>;
selectForCompare: (image: GalleryImage) => void;
sendToCanvas: (images: readonly GalleryImage[], destination: GalleryCanvasImportDestination) => Promise<void>;
setImagesStarred: (imageNames: string[], starred: boolean) => Promise<void>;
useAsReferenceImage: (image: GalleryImage) => void;
+ useAsReferenceVideo: (item: GalleryVideoItem) => void;
}
+const EMPTY_WIDGET_VALUES: Record<string, unknown> = {};
+
+/**
+ * Selected as a boolean so Video panel edits re-render action consumers only when the answer flips. The cache skips
+ * re-normalizing video values that have not changed since the last store update.
+ */
+const createCanUseAsReferenceVideoSelector = (models: readonly ModelConfig[], projectId: string | undefined) => {
+ let lastValues: Record<string, unknown> | null = null;
+ let lastResult = false;
+
+ return (snapshot: WorkbenchSnapshot): boolean => {
+ const project = projectId
+ ? snapshot.projects.find((candidate) => candidate.id === projectId)
+ : snapshot.activeProject;
+ const videoValues = (project && getProjectWidgetInstance(project, 'video')?.state.values) ?? EMPTY_WIDGET_VALUES;
+
+ if (videoValues !== lastValues) {
+ lastValues = videoValues;
+ lastResult = canAppendReferenceVideo({ models, videoValues });
+ }
+
+ return lastResult;
+ };
+};
+
const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));
const toPngBlob = async (blob: Blob): Promise<Blob> => {
@@ -175,6 +212,12 @@ export const useImageActions = ({
}, [generateValues, supportedModels])
);
+ const selectCanUseAsReferenceVideo = useMemo(
+ () => createCanUseAsReferenceVideoSelector(models, projectId),
+ [models, projectId]
+ );
+ const canUseAsReferenceVideo = useWorkbenchSelector(selectCanUseAsReferenceVideo, Object.is);
+
useMountEffect(() => {
void ensureModelsLoaded();
});
@@ -1004,6 +1047,50 @@ export const useImageActions = ({
starred
),
canUseAsReferenceImage,
+ canUseAsReferenceVideo,
+ sendToInitialVideo: (item) => {
+ const placement = placeInitialVideo({ models, video: item, videoValues: getLatestVideoValues() });
+
+ if (placement.status === 'full') {
+ notifications.add({
+ kind: 'info',
+ message: t('widgets.video.placement.initialVideoFull'),
+ title: t('widgets.video.referenceExtendCapFull'),
+ });
+ return;
+ }
+
+ openWorkbenchWidget('video', { preferredRegions: ['left'] });
+ commands.widgets.patchValues('video', placement.patch, projectId);
+ generation.setSource('video');
+ if (!placement.usable) {
+ notifications.add({
+ kind: 'info',
+ message: t('widgets.video.placement.initialVideoUnused'),
+ title: t('widgets.video.placement.initialVideoSet'),
+ });
+ }
+ },
+ useAsReferenceVideo: (item) => {
+ const placement = appendReferenceVideo({ models, video: item, videoValues: getLatestVideoValues() });
+
+ // The menu offers this only when there is room; a race can still fill the last slot first.
+ if (placement.status !== 'appended') {
+ notifications.add({
+ kind: 'info',
+ message: t(
+ placement.status === 'full'
+ ? 'widgets.video.placement.referenceFull'
+ : 'widgets.video.placement.referenceUnsupported'
+ ),
+ title: t('widgets.video.placement.referenceNotAdded'),
+ });
+ return;
+ }
+
+ commands.widgets.patchValues('video', placement.patch, projectId);
+ openWorkbenchWidget('video', { preferredRegions: ['left'] });
+ },
useAsReferenceImage: (image) => {
const result = appendReferenceImage({ generateValues: getLatestGenerateValues(), image, models });
@@ -1018,6 +1105,7 @@ export const useImageActions = ({
}, [
boards,
canUseAsReferenceImage,
+ canUseAsReferenceVideo,
confirmImageDeletion,
currentGenerateValues,
commands,
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 66c2ec931e..45cdc1a816 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.test.ts
@@ -418,6 +418,169 @@ describe('buildVideoRecallSettings', () => {
});
});
+describe('buildVideoRecallSettings — partial records from the external recall API', () => {
+ const catalog = [WAN_T2V, WAN_I2V, h3Model(), LIGHTNING_HIGH, LIGHTNING_LOW];
+ const heldLora = { isEnabled: true, model: LIGHTNING_HIGH as never, weight: 0.5 };
+ const holding = {
+ ...createDefaultVideoWidgetValues([WAN_I2V]),
+ firstFrameImage: { height: 720, image_name: 'held.png', width: 1280 },
+ loras: [heldLora],
+ };
+
+ it('accepts a request without generation_mode only when told it is one', () => {
+ const request = { positive_prompt: 'a heron' };
+
+ expect(buildVideoRecallSettings({ currentValues: holding, kind: 'all', metadata: request, models: catalog })).toBe(
+ null
+ );
+ expect(
+ buildVideoRecallSettings({
+ currentValues: holding,
+ kind: 'all',
+ metadata: request,
+ models: catalog,
+ requireGenerationMode: false,
+ })?.values.positivePrompt
+ ).toBe('a heron');
+ });
+
+ it('leaves the LoRAs, media and model a request does not name exactly as the panel has them', () => {
+ const result = buildVideoRecallSettings({
+ currentValues: holding,
+ kind: 'all',
+ metadata: { positive_prompt: 'a heron', steps: 30 },
+ models: catalog,
+ partial: true,
+ requireGenerationMode: false,
+ });
+
+ expect(result?.fields).toEqual(['prompts', 'steps']);
+ expect(result?.values).toEqual({ ...holding, positivePrompt: 'a heron', steps: 30 });
+ });
+
+ it('replaces the LoRA set only when the request names one, an empty list included', () => {
+ const cleared = buildVideoRecallSettings({
+ currentValues: holding,
+ kind: 'all',
+ metadata: { loras: [] },
+ models: catalog,
+ partial: true,
+ requireGenerationMode: false,
+ });
+
+ expect(cleared?.fields).toEqual(['loras']);
+ expect(cleared?.values.loras).toEqual([]);
+ });
+
+ it('names a media slot without clearing the others; hydration displaces only its rivals', () => {
+ const result = buildVideoRecallSettings({
+ currentValues: holding,
+ kind: 'all',
+ metadata: { last_frame_image: { image_name: 'last.png' } },
+ models: catalog,
+ partial: true,
+ requireGenerationMode: false,
+ });
+
+ expect(result?.mediaNames).toMatchObject({ firstFrameName: null, lastFrameName: 'last.png' });
+ expect(result?.values.firstFrameImage).toEqual(holding.firstFrameImage);
+ });
+
+ it('clears the references for an explicitly empty list, and only then', () => {
+ const panel = {
+ ...createDefaultVideoWidgetValues([h3Model()]),
+ references: [
+ { detail: 'max' as const, image: { height: 512, image_name: 'ref.png', width: 512 }, kind: 'image' as const },
+ ],
+ };
+ const build = (metadata: Record<string, unknown>) =>
+ buildVideoRecallSettings({
+ currentValues: panel,
+ kind: 'all',
+ metadata,
+ models: catalog,
+ partial: true,
+ requireGenerationMode: false,
+ });
+
+ expect(build({ minimax_h3_references: [] })).toMatchObject({ fields: ['media'], values: { references: [] } });
+ expect(build({ positive_prompt: 'p' })?.values.references).toEqual(panel.references);
+ });
+
+ it('keeps the panel hybrid base and may set its start block', () => {
+ const fl2vaBase: MainModelConfig = { ...h3Model('h3-fl2va-base'), format: 'checkpoint' };
+ const panel = {
+ ...createDefaultVideoWidgetValues([h3Model()]),
+ h3HybridBaseModel: fl2vaBase,
+ h3HybridStartBlock: 25,
+ };
+ const result = buildVideoRecallSettings({
+ currentValues: panel,
+ kind: 'all',
+ metadata: { minimax_h3_hybrid_start_block: 30 },
+ models: [...catalog, fl2vaBase],
+ partial: true,
+ requireGenerationMode: false,
+ });
+
+ expect(result?.values.h3HybridBaseModel).toBe(fl2vaBase);
+ expect(result?.values.h3HybridStartBlock).toBe(30);
+ });
+
+ it('reads an explicit null negative prompt as turning it off', () => {
+ const result = buildVideoRecallSettings({
+ currentValues: { ...holding, negativePrompt: 'blurry', negativePromptEnabled: true },
+ kind: 'all',
+ metadata: { negative_prompt: null },
+ models: catalog,
+ partial: true,
+ requireGenerationMode: false,
+ });
+
+ expect(result?.values).toMatchObject({ negativePrompt: '', negativePromptEnabled: false });
+ });
+});
+
+describe('buildVideoRecallSettings — leaving the accelerator', () => {
+ const catalog = [WAN_T2V, LIGHTNING_HIGH, LIGHTNING_LOW];
+ const defaults = createDefaultVideoWidgetValues([WAN_T2V]);
+ const accelerated = {
+ ...defaults,
+ acceleratorEnabled: true,
+ acceleratorLoraKeys: [LIGHTNING_HIGH.key, LIGHTNING_LOW.key],
+ cfgScale: 1,
+ loras: [LIGHTNING_HIGH, LIGHTNING_LOW].map((model) => ({ isEnabled: true, model: model as never, weight: 1 })),
+ steps: 4,
+ };
+ const recall = (metadata: Record<string, unknown>, partial: boolean) =>
+ buildVideoRecallSettings({
+ currentValues: accelerated,
+ kind: 'all',
+ metadata,
+ models: catalog,
+ partial,
+ requireGenerationMode: false,
+ });
+
+ it('restores the model sampling defaults when a whole record drops the accelerator LoRAs', () => {
+ expect(recall({ positive_prompt: 'p' }, false)?.values).toMatchObject({
+ acceleratorEnabled: false,
+ cfgScale: defaults.cfgScale,
+ loras: [],
+ steps: defaults.steps,
+ });
+ expect(defaults.steps).not.toBe(4);
+ });
+
+ it('keeps the sampling values the record names', () => {
+ expect(recall({ loras: [], steps: 12 }, true)?.values).toMatchObject({
+ acceleratorEnabled: false,
+ cfgScale: defaults.cfgScale,
+ steps: 12,
+ });
+ });
+});
+
describe('ref2va reference recall', () => {
const catalog = [WAN_T2V, WAN_I2V, h3Model(), LIGHTNING_HIGH, LIGHTNING_LOW];
const currentValues = { ...createDefaultVideoWidgetValues([h3Model()]) };
@@ -937,6 +1100,27 @@ describe('LTX-2 recall', () => {
expect(result?.fields).toEqual(expect.arrayContaining(['steps', 'cfg']));
});
+ it('writes no control a partial recall leaves hidden behind the panel accelerator', () => {
+ const accelerated = {
+ ...createDefaultVideoWidgetValues([LTX2_DEV]),
+ acceleratorEnabled: true,
+ acceleratorLoraKeys: ['ltx2-distilled'],
+ cfgScale: 1,
+ steps: 8,
+ };
+ const result = buildVideoRecallSettings({
+ currentValues: accelerated,
+ kind: 'all',
+ metadata: { positive_prompt: 'p', steps: 30, cfg_scale: 4 },
+ models: catalog,
+ partial: true,
+ requireGenerationMode: false,
+ });
+
+ expect(result?.fields).toEqual(['prompts']);
+ expect(result?.values).toMatchObject({ acceleratorEnabled: true, cfgScale: 1, steps: 8 });
+ });
+
it('treats both LTX-2 modes as recallable video metadata', () => {
// The mode id is the gate for every Recall button; a string the set does not know silently
// hides them all, with nothing failing.
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts
index 468fef117a..36cfe683c1 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecall.ts
@@ -14,6 +14,7 @@ import type {
import { isLoraCompatibleWithModel, isLoraModelConfig } from '@features/generation/settings';
import {
findAcceleratorLorasIn,
+ getAcceleratorToggleResult,
getAcceleratorSteps,
getVideoAspectRatioOptions,
getVideoDimensions,
@@ -471,13 +472,26 @@ export const buildVideoRecallSettings = ({
kind,
metadata,
models,
+ partial = false,
+ requireGenerationMode = true,
}: {
currentValues: VideoWidgetValues;
kind: VideoRecallKind;
metadata: unknown;
models: readonly ModelConfig[];
+ /**
+ * Apply only what the record carries, leaving everything it omits as the panel has it — the external recall
+ * API's default. A full recall instead reproduces the run: it clears LoRAs, media and the hybrid base the record
+ * does not name.
+ */
+ partial?: boolean;
+ /**
+ * Whether the record must be video generation metadata. A video's own record always is; the external recall API
+ * sends the same keys without a `generation_mode`.
+ */
+ requireGenerationMode?: boolean;
}): (VideoRecallResult & { mediaNames: VideoRecallMediaNames }) | null => {
- if (!isVideoGenerationMetadata(metadata)) {
+ if (requireGenerationMode ? !isVideoGenerationMetadata(metadata) : !isRecord(metadata)) {
return null;
}
@@ -574,7 +588,10 @@ export const buildVideoRecallSettings = ({
// the accelerator on would drop them all and silently leave the accelerator's values in place,
// showing numbers the recalled clip never used. The accelerator's own state is derived further
// down from the recalled LoRA set, which overwrites this anyway.
- const policy = getVideoModelPolicy(model, { ...values, acceleratorEnabled: false });
+ // A partial record without `loras` leaves the accelerator as the panel has it, so it may write only the controls
+ // that panel shows; everything else re-derives the accelerator from the recalled LoRAs further down.
+ const lorasRecalled = !partial || (isRecord(metadata) && Array.isArray(metadata.loras));
+ const policy = getVideoModelPolicy(model, lorasRecalled ? { ...values, acceleratorEnabled: false } : values);
const steps = getInteger(metadata, 'steps');
// A fixed-schedule checkpoint ignores whatever step count reaches it, so recalling one would
@@ -653,24 +670,25 @@ export const buildVideoRecallSettings = ({
// Restore only an installed recorded hybrid base; otherwise clear it and report against the original panel.
// Required source/text components retain current picks when absent.
- if (!hybridBaseRecalled) {
+ if (!hybridBaseRecalled && !partial) {
if (values.h3HybridBaseModel) {
values = { ...values, h3HybridBaseModel: null };
}
componentsRecalled ||= currentValues.h3HybridBaseModel !== null;
}
- // The hybrid's start block belongs to the recorded base: it only comes back
- // with it, never onto a base the panel happened to hold already.
+ // The hybrid's start block belongs to the recorded base: a full recall restores it only with that base, never
+ // onto one the panel happened to hold already. A partial recall may set it on the panel's own base.
const hybridStartBlock = getInteger(metadata, 'minimax_h3_hybrid_start_block');
if (
- hybridBaseRecalled &&
+ (hybridBaseRecalled || (partial && values.h3HybridBaseModel !== null)) &&
hybridStartBlock !== null &&
hybridStartBlock >= MINIMAX_H3_HYBRID_BLOCK_RANGE.min &&
hybridStartBlock <= MINIMAX_H3_HYBRID_BLOCK_RANGE.max
) {
values = { ...values, h3HybridStartBlock: hybridStartBlock };
+ componentsRecalled = true;
}
if (componentsRecalled) {
@@ -714,13 +732,26 @@ export const buildVideoRecallSettings = ({
});
// Reproduce the recorded LoRA set, including empty or entirely uninstalled sets; never retain unrelated panel
- // LoRAs.
- if (resolvedLoras.length > 0 || values.loras.length > 0) {
- values = {
- ...values,
- loras: resolvedLoras,
- ...deriveAcceleratorRecallState(model, resolvedLoras, values.steps, values),
- };
+ // LoRAs. A partial record without `loras` leaves the panel's set alone.
+ if (lorasRecalled && (resolvedLoras.length > 0 || values.loras.length > 0)) {
+ const accelerator = deriveAcceleratorRecallState(model, resolvedLoras, values.steps, values);
+
+ if (values.acceleratorEnabled && !accelerator.acceleratorEnabled) {
+ // Leaving the fast path restores the model's sampling defaults, as switching it off in the panel does; a
+ // value the record names stays. Otherwise the accelerator's few-step, guidance-free recipe would outlive it.
+ const defaults = getAcceleratorToggleResult(values, model, models, false).settings;
+ const recorded = (key: string) => getNumber(metadata, key) !== null;
+
+ values = {
+ ...values,
+ ...(recorded('steps') ? {} : { steps: defaults.steps }),
+ ...(recorded('cfg_scale') ? {} : { cfgScale: defaults.cfgScale, cfgScaleLowNoise: defaults.cfgScaleLowNoise }),
+ ...(recorded('ltx2_audio_cfg_scale') ? {} : { audioCfgScale: defaults.audioCfgScale }),
+ ...(recorded('ltx2_stg_scale') ? {} : { stgScale: defaults.stgScale }),
+ ...(recorded('ltx2_modality_scale') ? {} : { modalityScale: defaults.modalityScale }),
+ };
+ }
+ values = { ...values, loras: resolvedLoras, ...accelerator };
fields.push('loras');
}
@@ -739,7 +770,8 @@ export const buildVideoRecallSettings = ({
);
// All/remix recall clears current media before restoring recorded names because media determines graph family.
- if (hadMedia) {
+ // A partial recall keeps the panel's media; each slot it names displaces only its rivals when hydrated.
+ if (hadMedia && !partial) {
values = {
...values,
conditioningClip: null,
@@ -778,7 +810,17 @@ export const buildVideoRecallSettings = ({
mediaNames.sourceVideoTrim = startFrame !== null && endFrame !== null ? { endFrame, startFrame } : null;
}
fields.push('media');
- } else if (hadMedia) {
+ } else if (hadMedia && !partial) {
+ fields.push('media');
+ } else if (
+ partial &&
+ isRecord(metadata) &&
+ Array.isArray(metadata.minimax_h3_references) &&
+ metadata.minimax_h3_references.length === 0 &&
+ values.references.length > 0
+ ) {
+ // An explicitly empty list asks for no references; an absent one leaves them alone.
+ values = { ...values, references: [] };
fields.push('media');
}
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts
new file mode 100644
index 0000000000..02846ac842
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts
@@ -0,0 +1,442 @@
+import type { ModelConfig, ModelsSnapshot } from '@features/models';
+import type { SocketHub } from '@platform/transport/socketHub';
+import type { TFunction } from 'i18next';
+
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { getProjectWidgetValues } from '@workbench/widgetState';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const galleryApi = vi.hoisted(() => ({
+ galleryImages: { metadata: vi.fn(), resolveMany: vi.fn() },
+ galleryItems: { resolve: vi.fn() },
+ galleryVideos: { metadata: vi.fn() },
+}));
+const modelsApi = vi.hoisted(() => ({ ensureModelsLoaded: vi.fn(), getModelsSnapshot: vi.fn() }));
+
+vi.mock('@features/gallery', () => galleryApi);
+vi.mock('@features/models', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ ...modelsApi,
+}));
+
+import { createDefaultVideoWidgetValues } from '@features/video';
+
+import { createVideoRecallRuntime } from './videoRecallRuntime';
+
+type SocketHandler = (payload: never) => void;
+
+const createFakeSocketHub = () => {
+ const handlers = new Map<string, Set<SocketHandler>>();
+ const hub: Pick<SocketHub, 'on'> = {
+ on: (event, handler) => {
+ const eventHandlers = handlers.get(event) ?? new Set<SocketHandler>();
+ eventHandlers.add(handler);
+ handlers.set(event, eventHandlers);
+ return () => eventHandlers.delete(handler);
+ },
+ };
+
+ return {
+ emit: (payload: unknown) => {
+ for (const handler of handlers.get('video_recall_requested') ?? []) {
+ handler(payload as never);
+ }
+ },
+ hub,
+ };
+};
+
+const model = (fields: Record<string, unknown>) =>
+ ({
+ file_size: 1,
+ hash: 'h',
+ path: '/m',
+ source: 'local',
+ source_type: 'path',
+ type: 'main',
+ ...fields,
+ }) as ModelConfig;
+
+const WAN_I2V = model({ base: 'wan', format: 'diffusers', key: 'wan-i2v', name: 'Wan I2V', variant: 'i2v_a14b' });
+const WAN_T2V = model({ base: 'wan', format: 'diffusers', key: 'wan-t2v', name: 'Wan T2V', variant: 't2v_a14b' });
+const REF2VA = model({
+ base: 'minimax-h3',
+ format: 'checkpoint',
+ key: 'h3-ref2va',
+ name: 'H3 Ref2VA',
+ variant: 'ref2va',
+});
+
+const t = ((key: string) => key) as unknown as TFunction;
+
+const flush = () =>
+ new Promise<void>((resolve) => {
+ setTimeout(resolve, 0);
+ });
+
+const parametersEvent = (parameters: Record<string, unknown>, extra: Record<string, unknown> = {}) => ({
+ action: 'parameters',
+ mode: 'recall',
+ parameters,
+ queue_id: 'default',
+ strict: false,
+ user_id: 'owner',
+ ...extra,
+});
+
+const placementEvent = (action: 'initial_video' | 'reference_video', video: Record<string, unknown> = {}) => ({
+ action,
+ queue_id: 'default',
+ user_id: 'owner',
+ video: { duration: 5, fps: 16, height: 480, media_origin: null, video_name: 'clip.mp4', width: 832, ...video },
+});
+
+const heldFrame = { height: 480, image_name: 'held.png', width: 832 };
+
+const setup = (panelModel: ModelConfig = WAN_I2V) => {
+ const store = createWorkbenchStore();
+ const socket = createFakeSocketHub();
+ const openVideoWidget = vi.fn();
+ const projectId = store.queries.getSnapshot().activeProject.id;
+
+ store.commands.widgets.patchValues(
+ 'video',
+ {
+ ...createDefaultVideoWidgetValues([panelModel]),
+ ...(panelModel === WAN_I2V ? { firstFrameImage: heldFrame } : {}),
+ positivePrompt: 'before',
+ },
+ projectId
+ );
+ const runtime = createVideoRecallRuntime({
+ commands: store.commands,
+ hub: socket.hub,
+ openVideoWidget,
+ queries: store.queries,
+ t,
+ });
+ const videoValues = (id = projectId) => {
+ const project = store.queries.getProject(id);
+ return project ? getProjectWidgetValues(project, 'video') : {};
+ };
+ // Newest first.
+ const lastNotice = () => store.queries.getSnapshot().notifications[0];
+
+ return { lastNotice, openVideoWidget, projectId, runtime, socket, store, videoValues };
+};
+
+describe('createVideoRecallRuntime', () => {
+ beforeEach(() => {
+ accountLifecycle.activate('owner');
+ modelsApi.ensureModelsLoaded.mockReset();
+ modelsApi.ensureModelsLoaded.mockResolvedValue(undefined);
+ modelsApi.getModelsSnapshot.mockReset();
+ modelsApi.getModelsSnapshot.mockReturnValue({
+ error: null,
+ models: [WAN_I2V, WAN_T2V, REF2VA],
+ status: 'loaded',
+ } as ModelsSnapshot);
+ galleryApi.galleryItems.resolve.mockReset();
+ galleryApi.galleryItems.resolve.mockImplementation(({ name }: { name: string }) =>
+ Promise.resolve({ durationSeconds: 5, fps: 16, height: 480, kind: 'video', name, width: 832 })
+ );
+ galleryApi.galleryImages.resolveMany.mockReset();
+ galleryApi.galleryImages.resolveMany.mockImplementation((names: string[]) =>
+ Promise.resolve(names.map((imageName) => ({ height: 480, imageName, width: 832 })))
+ );
+ });
+
+ it('applies a non-strict recall on top of the panel and reveals the Video widget', async () => {
+ const { lastNotice, openVideoWidget, runtime, socket, videoValues } = setup();
+
+ socket.emit(parametersEvent({ positive_prompt: 'a heron', seed: 99 }));
+ await flush();
+
+ expect(videoValues()).toMatchObject({ firstFrameImage: heldFrame, positivePrompt: 'a heron', seed: 99 });
+ expect(lastNotice()).toEqual(expect.objectContaining({ kind: 'success', title: 'Recalled video data' }));
+ expect(openVideoWidget).toHaveBeenCalledTimes(1);
+
+ runtime.dispose();
+ });
+
+ it('clears media a strict recall does not name', async () => {
+ const { runtime, socket, videoValues } = setup();
+
+ socket.emit(parametersEvent({ positive_prompt: 'a heron' }, { strict: true }));
+ await flush();
+
+ expect(videoValues()).toMatchObject({ firstFrameImage: null, positivePrompt: 'a heron' });
+
+ runtime.dispose();
+ });
+
+ it('titles a remix as one', async () => {
+ const { lastNotice, runtime, socket } = setup();
+
+ socket.emit(parametersEvent({ positive_prompt: 'a heron' }, { mode: 'remix' }));
+ await flush();
+
+ expect(lastNotice()).toEqual(expect.objectContaining({ title: 'Remixed video' }));
+
+ runtime.dispose();
+ });
+
+ it('applies to the project it arrived for, without pulling a different project to the front', async () => {
+ const { openVideoWidget, projectId, runtime, socket, store, videoValues } = setup();
+ let releaseModels: () => void = () => {};
+ modelsApi.ensureModelsLoaded.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ releaseModels = resolve;
+ })
+ );
+
+ socket.emit(parametersEvent({ positive_prompt: 'for the first project' }));
+ const second = store.commands.projects.create();
+ await flush();
+ releaseModels();
+ await flush();
+
+ expect(videoValues(projectId).positivePrompt).toBe('for the first project');
+ expect(videoValues(second.id).positivePrompt).toBeUndefined();
+ expect(openVideoWidget).not.toHaveBeenCalled();
+
+ runtime.dispose();
+ });
+
+ it('sets the initial video as the Initial Video field would', async () => {
+ const { lastNotice, openVideoWidget, runtime, socket, videoValues } = setup();
+
+ socket.emit(placementEvent('initial_video'));
+ await flush();
+
+ expect(videoValues()).toMatchObject({ firstFrameImage: null, sourceVideo: { fps: 16, video_name: 'clip.mp4' } });
+ expect(lastNotice()).toEqual(
+ expect.objectContaining({ kind: 'success', title: 'widgets.video.placement.initialVideoSet' })
+ );
+ expect(openVideoWidget).toHaveBeenCalledTimes(1);
+
+ runtime.dispose();
+ });
+
+ it('declines a reference video the panel model cannot take, leaving the panel alone', async () => {
+ const { lastNotice, openVideoWidget, runtime, socket, videoValues } = setup();
+ const before = videoValues();
+
+ socket.emit(placementEvent('reference_video'));
+ await flush();
+
+ expect(videoValues()).toBe(before);
+ expect(lastNotice()).toEqual(
+ expect.objectContaining({
+ kind: 'info',
+ message: 'widgets.video.placement.referenceUnsupported',
+ title: 'widgets.video.placement.referenceNotAdded',
+ })
+ );
+ expect(openVideoWidget).not.toHaveBeenCalled();
+
+ runtime.dispose();
+ });
+
+ it.each([
+ ['a parameters event without its strict flag', { ...parametersEvent({}), strict: undefined }],
+ ['a placement without the video it places', { ...placementEvent('initial_video'), video: null }],
+ ['a placement whose video has no size', { ...placementEvent('initial_video'), video: { video_name: 'clip.mp4' } }],
+ ['an unknown action', { ...placementEvent('initial_video'), action: 'delete_video' }],
+ ])('ignores %s', async (_label, payload) => {
+ const { openVideoWidget, runtime, socket, store, videoValues } = setup();
+ const before = videoValues();
+ const notices = store.queries.getSnapshot().notifications.length;
+
+ socket.emit(payload);
+ await flush();
+
+ expect(videoValues()).toBe(before);
+ expect(store.queries.getSnapshot().notifications).toHaveLength(notices);
+ expect(openVideoWidget).not.toHaveBeenCalled();
+
+ runtime.dispose();
+ });
+
+ describe('partial media', () => {
+ const referenceNames = (values: Record<string, unknown>) =>
+ (
+ values.references as {
+ clip?: { video_name: string };
+ fromSourceVideo?: boolean;
+ image?: { image_name: string };
+ }[]
+ ).map((entry) =>
+ entry.image ? entry.image.image_name : `${entry.clip?.video_name}${entry.fromSourceVideo ? '*' : ''}`
+ );
+
+ it('keeps the Ref2VA continuity reference when the references are replaced, and moves it with the clip', async () => {
+ const { runtime, socket, videoValues } = setup(REF2VA);
+
+ socket.emit(placementEvent('initial_video'));
+ await flush();
+ expect(referenceNames(videoValues())).toEqual(['clip.mp4*']);
+
+ socket.emit(parametersEvent({ minimax_h3_references: [{ image_name: 'B.png', kind: 'image' }] }));
+ await flush();
+ expect(referenceNames(videoValues())).toEqual(['B.png', 'clip.mp4*']);
+ expect(videoValues()).toMatchObject({ sourceVideo: { video_name: 'clip.mp4' } });
+
+ socket.emit(parametersEvent({ source_video: { video_name: 'other.mp4' } }));
+ await flush();
+ expect(referenceNames(videoValues())).toEqual(['B.png', 'other.mp4*']);
+ expect(videoValues()).toMatchObject({ sourceVideo: { video_name: 'other.mp4' } });
+
+ runtime.dispose();
+ });
+
+ it('removes the initial video when a sent reference list leaves no slot for its continuity reference', async () => {
+ const { runtime, socket, videoValues } = setup(REF2VA);
+
+ socket.emit(placementEvent('initial_video'));
+ await flush();
+ socket.emit(
+ parametersEvent({
+ minimax_h3_references: ['a.mp4', 'b.mp4', 'c.mp4'].map((video_name) => ({ kind: 'video', video_name })),
+ })
+ );
+ await flush();
+
+ expect(referenceNames(videoValues())).toEqual(['a.mp4', 'b.mp4', 'c.mp4']);
+ expect(videoValues().sourceVideo).toBeNull();
+
+ runtime.dispose();
+ });
+
+ it('ignores a first frame a Ref2VA panel cannot use, keeping its initial video', async () => {
+ const { runtime, socket, videoValues } = setup(REF2VA);
+
+ socket.emit(placementEvent('initial_video'));
+ await flush();
+ socket.emit(parametersEvent({ first_frame_image: { image_name: 'first.png' } }));
+ await flush();
+
+ expect(videoValues()).toMatchObject({ firstFrameImage: null, sourceVideo: { video_name: 'clip.mp4' } });
+ expect(referenceNames(videoValues())).toEqual(['clip.mp4*']);
+
+ runtime.dispose();
+ });
+
+ it('does not let media the panel model cannot use displace what it holds', async () => {
+ const { lastNotice, runtime, socket, videoValues } = setup();
+
+ socket.emit(parametersEvent({ minimax_h3_references: [{ image_name: 'B.png', kind: 'image' }] }));
+ await flush();
+
+ expect(videoValues()).toMatchObject({ firstFrameImage: heldFrame, references: [] });
+ expect(lastNotice()).toEqual(
+ expect.objectContaining({ kind: 'info', title: 'widgets.video.externalRecall.nothingApplied' })
+ );
+
+ runtime.dispose();
+ });
+ });
+
+ it.each(['placed', 'floating'] as const)(
+ 'leaves the layout alone when the Video widget is already %s there',
+ async (where) => {
+ const { openVideoWidget, projectId, runtime, socket, store, videoValues } = setup();
+
+ store.commands.widgets.open({ projectId, region: 'left', widgetId: 'video' });
+ const project = store.queries.getProject(projectId)!;
+ const instanceId = Object.values(project.widgetInstances).find((instance) => instance.typeId === 'video')!.id;
+ if (where === 'floating') {
+ store.commands.widgets.float(instanceId);
+ }
+
+ socket.emit(parametersEvent({ positive_prompt: 'a heron' }));
+ await flush();
+
+ expect(videoValues().positivePrompt).toBe('a heron');
+ expect(openVideoWidget).not.toHaveBeenCalled();
+
+ runtime.dispose();
+ }
+ );
+
+ describe('placements', () => {
+ it('appends a reference video with the defaults its wire facts imply', async () => {
+ const { lastNotice, runtime, socket, videoValues } = setup(REF2VA);
+
+ socket.emit(placementEvent('reference_video', { duration: 10, fps: 24, media_origin: 'audio_upload' }));
+ await flush();
+
+ expect(videoValues().references).toEqual([
+ expect.objectContaining({
+ clip: expect.objectContaining({ endFrame: 239, fps: 24, numFrames: 240, video_name: 'clip.mp4' }),
+ conditioning: 'audio',
+ kind: 'video',
+ }),
+ ]);
+ expect(lastNotice()).toEqual(
+ expect.objectContaining({ kind: 'success', title: 'widgets.video.placement.referenceAdded' })
+ );
+
+ runtime.dispose();
+ });
+
+ it('declines an initial video a Ref2VA panel has no reference slot to anchor', async () => {
+ const { lastNotice, runtime, socket, videoValues } = setup(REF2VA);
+
+ for (const name of ['a.mp4', 'b.mp4', 'c.mp4']) {
+ socket.emit(placementEvent('reference_video', { video_name: name }));
+ await flush();
+ }
+ expect(videoValues().references).toHaveLength(3);
+ const before = videoValues();
+
+ socket.emit(placementEvent('initial_video'));
+ await flush();
+
+ expect(videoValues()).toBe(before);
+ expect(lastNotice()).toEqual(
+ expect.objectContaining({ kind: 'info', message: 'widgets.video.placement.initialVideoFull' })
+ );
+
+ runtime.dispose();
+ });
+
+ it('sets an initial video the panel model cannot extend, and says so', async () => {
+ const { lastNotice, runtime, socket, videoValues } = setup(WAN_T2V);
+
+ socket.emit(placementEvent('initial_video'));
+ await flush();
+
+ expect(videoValues()).toMatchObject({ sourceVideo: { video_name: 'clip.mp4' } });
+ expect(lastNotice()).toEqual(
+ expect.objectContaining({ kind: 'info', message: 'widgets.video.placement.initialVideoUnused' })
+ );
+
+ runtime.dispose();
+ });
+
+ it('places into the project it arrived for', async () => {
+ const { projectId, runtime, socket, store, videoValues } = setup();
+ let releaseModels: () => void = () => {};
+ modelsApi.ensureModelsLoaded.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ releaseModels = resolve;
+ })
+ );
+
+ socket.emit(placementEvent('initial_video'));
+ const second = store.commands.projects.create();
+ await flush();
+ releaseModels();
+ await flush();
+
+ expect(videoValues(projectId)).toMatchObject({ sourceVideo: { video_name: 'clip.mp4' } });
+ expect(videoValues(second.id).sourceVideo).toBeUndefined();
+
+ runtime.dispose();
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.ts
new file mode 100644
index 0000000000..ea59edf750
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.ts
@@ -0,0 +1,216 @@
+import type { ModelConfig } from '@features/models';
+import type { AccountScope } from '@platform/state/accountLifecycle';
+import type { SocketHub } from '@platform/transport/socketHub';
+import type { WorkbenchCommands, WorkbenchQueries } from '@workbench/workbenchStore';
+import type { TFunction } from 'i18next';
+
+import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { getProjectWidgetValues } from '@workbench/widgetState';
+
+import type { PlaceableVideo } from './index';
+import type { PendingRecallEvent, RecallRuntime } from './recallEventRuntime';
+
+// Through the package entry, not the modules themselves: the gallery's actions share these modules, and importing
+// them from this lazy runtime directly would split them out of the image-actions chunk into one more request on
+// every editor route.
+import { appendReferenceVideo, applyVideoRecallMetadata, placeInitialVideo } from './index';
+import { createRecallEventRuntime } from './recallEventRuntime';
+
+/** The `video` of a `video_recall_requested` event: a gallery video, as the backend describes it. */
+interface VideoRecallEventVideo {
+ duration: number;
+ fps: number | null;
+ height: number;
+ media_origin: string | null;
+ video_name: string;
+ width: number;
+}
+
+/** Wire payload of the backend's `video_recall_requested` socket event (`POST /api/v1/recall/video`). */
+export type VideoRecallRequestedEvent = { user_id: string } & (
+ | {
+ action: 'parameters';
+ mode: 'recall' | 'remix';
+ /** Resolved fields keyed like the video metadata record. */
+ parameters: Record<string, unknown>;
+ strict: boolean;
+ }
+ | { action: 'initial_video' | 'reference_video'; video: VideoRecallEventVideo }
+);
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const isPositiveNumber = (value: unknown): value is number =>
+ typeof value === 'number' && Number.isFinite(value) && value > 0;
+
+const isEventVideo = (value: unknown): value is VideoRecallEventVideo =>
+ isRecord(value) &&
+ typeof value.video_name === 'string' &&
+ isPositiveNumber(value.width) &&
+ isPositiveNumber(value.height) &&
+ typeof value.duration === 'number' &&
+ Number.isFinite(value.duration) &&
+ value.duration >= 0 &&
+ (value.fps === null || isPositiveNumber(value.fps)) &&
+ (value.media_origin === null || typeof value.media_origin === 'string');
+
+export const isVideoRecallRequestedEvent = (payload: unknown): payload is VideoRecallRequestedEvent => {
+ if (!isRecord(payload) || typeof payload.user_id !== 'string') {
+ return false;
+ }
+ if (payload.action === 'parameters') {
+ return (
+ (payload.mode === 'recall' || payload.mode === 'remix') &&
+ typeof payload.strict === 'boolean' &&
+ isRecord(payload.parameters)
+ );
+ }
+
+ return (payload.action === 'initial_video' || payload.action === 'reference_video') && isEventVideo(payload.video);
+};
+
+const toPlaceableVideo = (video: VideoRecallEventVideo): PlaceableVideo => ({
+ durationSeconds: video.duration,
+ fps: video.fps ?? undefined,
+ height: video.height,
+ mediaOrigin: video.media_origin ?? undefined,
+ name: video.video_name,
+ width: video.width,
+});
+
+/**
+ * Apply `video_recall_requested` events to their arrival-time project's Video panel: recall or remix parameters,
+ * set the Initial Video, or append a reference video. The panel's model is never switched to make a video fit; a
+ * placement it cannot take is declined with a notice. The Video widget is revealed when the project is still the
+ * one on screen.
+ */
+export const createVideoRecallRuntime = ({
+ commands,
+ getSessionUserId,
+ hub,
+ openVideoWidget,
+ queries,
+ replay,
+ t,
+}: {
+ commands: Pick<WorkbenchCommands, 'notifications' | 'widgets'>;
+ getSessionUserId?: () => string | null;
+ hub: Pick<SocketHub, 'on'>;
+ openVideoWidget: () => void;
+ queries: Pick<WorkbenchQueries, 'getProject' | 'getSnapshot'>;
+ replay?: readonly PendingRecallEvent[];
+ /** Resolves against the current language at call time; captured once, at attach. */
+ t: TFunction;
+}): RecallRuntime => {
+ // An external event arrives unprompted, so it only brings the Video widget into a layout that lacks it. Where the
+ // widget already sits (floating, or a tab of any region), revealing it would dock a floating window or switch the
+ // tab under whatever the user is doing; the notification reports the change instead.
+ const shouldRevealVideoWidget = (projectId: string, owner: AccountScope) => {
+ const project = queries.getSnapshot().activeProject;
+
+ if (!isAccountScopeCurrent(owner) || project.id !== projectId) {
+ return false;
+ }
+
+ const isVideo = (instanceId: string) => project.widgetInstances[instanceId]?.typeId === 'video';
+
+ return !(
+ Object.keys(project.floatingWidgets ?? {}).some(isVideo) ||
+ Object.values(project.widgetRegions).some((region) => region.instanceIds.some(isVideo))
+ );
+ };
+
+ const apply = async (
+ event: VideoRecallRequestedEvent,
+ { models, owner, projectId }: { models: ModelConfig[]; owner: AccountScope; projectId: string }
+ ): Promise<void> => {
+ const readVideoValues = () => {
+ const project = queries.getProject(projectId);
+ return project ? getProjectWidgetValues(project, 'video') : null;
+ };
+ const videoValues = readVideoValues();
+
+ // The project closed while the event waited.
+ if (!videoValues) {
+ return;
+ }
+
+ let applied = false;
+
+ if (event.action === 'parameters') {
+ applied = await applyVideoRecallMetadata({
+ commands,
+ emptyNotice: {
+ message: t('widgets.video.externalRecall.nothingAppliedDescription'),
+ title: t('widgets.video.externalRecall.nothingApplied'),
+ },
+ getVideoValues: () => readVideoValues() ?? {},
+ kind: event.mode === 'remix' ? 'remix' : 'all',
+ metadata: event.parameters,
+ models,
+ owner,
+ partial: !event.strict,
+ projectId,
+ requireGenerationMode: false,
+ });
+ } else if (event.action === 'initial_video') {
+ const placement = placeInitialVideo({ models, video: toPlaceableVideo(event.video), videoValues });
+
+ if (placement.status === 'full') {
+ commands.notifications.add({
+ kind: 'info',
+ message: t('widgets.video.placement.initialVideoFull'),
+ title: t('widgets.video.referenceExtendCapFull'),
+ });
+ } else {
+ commands.widgets.patchValues('video', placement.patch, projectId);
+ commands.notifications.add(
+ placement.usable
+ ? { kind: 'success', title: t('widgets.video.placement.initialVideoSet') }
+ : {
+ kind: 'info',
+ message: t('widgets.video.placement.initialVideoUnused'),
+ title: t('widgets.video.placement.initialVideoSet'),
+ }
+ );
+ applied = true;
+ }
+ } else {
+ const placement = appendReferenceVideo({ models, video: toPlaceableVideo(event.video), videoValues });
+
+ if (placement.status === 'appended') {
+ commands.widgets.patchValues('video', placement.patch, projectId);
+ commands.notifications.add({ kind: 'success', title: t('widgets.video.placement.referenceAdded') });
+ applied = true;
+ } else {
+ commands.notifications.add({
+ kind: 'info',
+ message: t(
+ placement.status === 'full'
+ ? 'widgets.video.placement.referenceFull'
+ : 'widgets.video.placement.referenceUnsupported'
+ ),
+ title: t('widgets.video.placement.referenceNotAdded'),
+ });
+ }
+ }
+
+ // The value patch itself routes the project's invocation to Video, where the user lets edits route it.
+ if (applied && shouldRevealVideoWidget(projectId, owner)) {
+ openVideoWidget();
+ }
+ };
+
+ return createRecallEventRuntime({
+ apply,
+ area: 'video-recall',
+ commands,
+ eventName: 'video_recall_requested',
+ getSessionUserId,
+ hub,
+ isEvent: isVideoRecallRequestedEvent,
+ queries,
+ replay,
+ });
+};
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 35caf5eabb..7da908f3a1 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
@@ -84,6 +84,7 @@ vi.mock('./previewHeaderStore', () => ({
}));
vi.mock('@workbench/widgetState', () => ({
+ getProjectWidgetInstance: () => undefined,
getProjectWidgetValues: () => ({ filmstripVisible: state.filmstripVisible, metadataOpen: false }),
}));