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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(video): place a gallery image in the Video panel from the recall API
Lincoln Steinf9b5e99ab475
diff --git a/invokeai/app/api/routers/video_recall.py b/invokeai/app/api/routers/video_recall.pyindex daa74b4f6f..7341c5ce66 100644--- a/invokeai/app/api/routers/video_recall.py+++ b/invokeai/app/api/routers/video_recall.py@@ -20,10 +20,11 @@ from invokeai.app.api.routers.videos import VIDEO_UPLOAD_OPENAPI_EXTRA, ingest_ufrom invokeai.app.services.events.events_common import (VideoRecallAction,VideoRecallConditioningRole,+ VideoRecallImage,VideoRecallMode,VideoRecallVideo,)-from invokeai.app.services.image_records.image_records_common import ImageCategory+from invokeai.app.services.image_records.image_records_common import ImageCategory, ImageRecordNotFoundExceptionfrom invokeai.app.services.model_records.model_records_base import UnknownModelExceptionfrom invokeai.app.services.video_records.video_records_common import VideoRecordNotFoundExceptionfrom invokeai.app.services.videos.videos_common import VideoDTO@@ -236,6 +237,13 @@ class VideoRecallMediaResponse(BaseModel):uploaded: bool = Field(description="Whether the video was uploaded into the gallery by this request")+class VideoRecallImageResponse(BaseModel):+ status: Literal["success"]+ queue_id: str+ image: VideoRecallImage+ append: bool++def _model_identifier(config: AnyModelConfig) -> dict[str, Any]:return {"key": config.key,@@ -705,3 +713,37 @@ async def recall_conditioning_video_upload() -> VideoRecallMediaResponse:"""Upload a video into the gallery and set it as the current user's conditioning clip."""return await _place_uploaded_video(request, queue_id, "conditioning_video", board_id, current_user, role)+++@video_recall_router.post(+ "/{queue_id}/image",+ operation_id="recall_video_image",+ response_model=VideoRecallImageResponse,+)+def recall_video_image(+ current_user: CurrentUserOrDefault,+ queue_id: str = Path(..., description="The queue id to perform this operation on"),+ image_name: str = Query(..., min_length=1, max_length=255, description="The name of the gallery image"),+ append: bool = Query(+ default=False,+ description="Add the image after the panel's own images instead of replacing them",+ ),+) -> VideoRecallImageResponse:+ """Place a gallery image in the current user's Video panel, where the panel's model takes images.++ A model that takes reference images (e.g. MiniMax H3 Ref2VA) gets it as a reference: it replaces the reference+ images, or with `append` joins them. A model that takes frames (e.g. Wan, LTX-2) gets it as the first frame,+ clearing the last; with `append` it fills the first free frame slot, and is ignored when both are set. The+ panel's model decides, so the outcome is reported to the user there rather than in this response.+ """+ assert_image_move_maintenance_inactive()+ assert_image_read_access(image_name, current_user)+ try:+ record = ApiDependencies.invoker.services.image_records.get(image_name)+ except ImageRecordNotFoundException:+ raise HTTPException(status_code=404, detail="Image not found")+ image = VideoRecallImage(image_name=record.image_name, width=record.width, height=record.height)+ ApiDependencies.invoker.services.events.emit_video_recall_requested(+ queue_id, current_user.user_id, "image", image=image, append=append+ )+ return VideoRecallImageResponse(status="success", queue_id=queue_id, image=image, append=append)diff --git a/invokeai/app/services/events/events_base.py b/invokeai/app/services/events/events_base.pyindex a863d90151..95f3d67dd0 100644--- a/invokeai/app/services/events/events_base.py+++ b/invokeai/app/services/events/events_base.py@@ -41,6 +41,7 @@ from invokeai.app.services.events.events_common import (UserAccessChangedEvent,VideoRecallAction,VideoRecallConditioningRole,+ VideoRecallImage,VideoRecallMode,VideoRecallRequestedEvent,VideoRecallVideo,@@ -165,11 +166,13 @@ class EventServiceBase:parameters: dict | None = None,video: VideoRecallVideo | None = None,conditioning_role: VideoRecallConditioningRole | None = None,+ image: VideoRecallImage | None = None,+ append: bool = False,) -> None:"""Emitted when an external caller asks for a user's Video panel to be updated"""self.dispatch(VideoRecallRequestedEvent.build(- queue_id, user_id, action, mode, strict, parameters, video, conditioning_role+ queue_id, user_id, action, mode, strict, parameters, video, conditioning_role, image, append))diff --git a/invokeai/app/services/events/events_common.py b/invokeai/app/services/events/events_common.pyindex 9c81a2c0f4..1f5ff2712e 100644--- a/invokeai/app/services/events/events_common.py+++ b/invokeai/app/services/events/events_common.py@@ -925,7 +925,7 @@ class RecallParametersUpdatedEvent(QueueEventBase):return cls(queue_id=queue_id, user_id=user_id, parameters=parameters)-VideoRecallAction: TypeAlias = Literal["parameters", "initial_video", "reference_video", "conditioning_video"]+VideoRecallAction: TypeAlias = Literal["parameters", "initial_video", "reference_video", "conditioning_video", "image"]VideoRecallConditioningRole: TypeAlias = Literal["audio", "video"]VideoRecallMode: TypeAlias = Literal["recall", "remix"]@@ -943,6 +943,14 @@ class VideoRecallVideo(BaseModel):)+class VideoRecallImage(BaseModel):+ """The gallery image a video recall places into the Video panel."""++ image_name: str = Field(description="The name of the gallery image")+ width: int = Field(description="The image's width in pixels")+ height: int = Field(description="The image's height in pixels")++@payload_schema.registerclass VideoRecallRequestedEvent(QueueEventBase):"""Event model for video_recall_requested"""@@ -968,11 +976,23 @@ class VideoRecallRequestedEvent(QueueEventBase):default=None,description="For `conditioning_video`: which stream of the video is the condition; the other is generated",)+ image: Optional[VideoRecallImage] = Field(default=None, description="For `image`: the image to place")+ append: bool = Field(+ default=False,+ description=(+ "For `image`: add the image after the panel's own instead of replacing them -- to the reference images "+ "of a model that takes references, otherwise to the free frame slot"+ ),+ )@model_validator(mode="after")def _role_iff_conditioning_video(self) -> "VideoRecallRequestedEvent":if (self.action == "conditioning_video") != (self.conditioning_role is not None):raise ValueError("conditioning_role is given with, and only with, a conditioning_video action")+ if (self.action == "image") != (self.image is not None):+ raise ValueError("image is given with, and only with, an image action")+ if self.append and self.action != "image":+ raise ValueError("append is given only with an image action")return self@classmethod@@ -986,6 +1006,8 @@ class VideoRecallRequestedEvent(QueueEventBase):parameters: Optional[dict[str, Any]] = None,video: Optional[VideoRecallVideo] = None,conditioning_role: Optional[VideoRecallConditioningRole] = None,+ image: Optional[VideoRecallImage] = None,+ append: bool = False,) -> "VideoRecallRequestedEvent":return cls(queue_id=queue_id,@@ -996,6 +1018,8 @@ class VideoRecallRequestedEvent(QueueEventBase):parameters=parameters,video=video,conditioning_role=conditioning_role,+ image=image,+ append=append,)diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 9ed85a83e2..765b6c4217 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -16427,6 +16427,79 @@}}},+ "/api/v1/recall/video/{queue_id}/image": {+ "post": {+ "tags": ["recall"],+ "summary": "Recall Video Image",+ "description": "Place a gallery image in the current user's Video panel, where the panel's model takes images.\n\nA model that takes reference images (e.g. MiniMax H3 Ref2VA) gets it as a reference: it replaces the reference\nimages, or with `append` joins them. A model that takes frames (e.g. Wan, LTX-2) gets it as the first frame,\nclearing the last; with `append` it fills the first free frame slot, and is ignored when both are set. The\npanel's model decides, so the outcome is reported to the user there rather than in this response.",+ "operationId": "recall_video_image",+ "security": [+ {+ "HTTPBearer": []+ }+ ],+ "parameters": [+ {+ "name": "queue_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "description": "The queue id to perform this operation on",+ "title": "Queue Id"+ },+ "description": "The queue id to perform this operation on"+ },+ {+ "name": "image_name",+ "in": "query",+ "required": true,+ "schema": {+ "type": "string",+ "minLength": 1,+ "maxLength": 255,+ "description": "The name of the gallery image",+ "title": "Image Name"+ },+ "description": "The name of the gallery image"+ },+ {+ "name": "append",+ "in": "query",+ "required": false,+ "schema": {+ "type": "boolean",+ "description": "Add the image after the panel's own images instead of replacing them",+ "default": false,+ "title": "Append"+ },+ "description": "Add the image after the panel's own images instead of replacing them"+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/VideoRecallImageResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },"/api/v2/custom_nodes/": {"get": {"tags": ["custom_nodes"],@@ -107731,6 +107804,52 @@"title": "VideoOutput","type": "object"},+ "VideoRecallImage": {+ "properties": {+ "image_name": {+ "type": "string",+ "title": "Image Name",+ "description": "The name of the gallery image"+ },+ "width": {+ "type": "integer",+ "title": "Width",+ "description": "The image's width in pixels"+ },+ "height": {+ "type": "integer",+ "title": "Height",+ "description": "The image's height in pixels"+ }+ },+ "type": "object",+ "required": ["image_name", "width", "height"],+ "title": "VideoRecallImage",+ "description": "The gallery image a video recall places into the Video panel."+ },+ "VideoRecallImageResponse": {+ "properties": {+ "status": {+ "type": "string",+ "const": "success",+ "title": "Status"+ },+ "queue_id": {+ "type": "string",+ "title": "Queue Id"+ },+ "image": {+ "$ref": "#/components/schemas/VideoRecallImage"+ },+ "append": {+ "type": "boolean",+ "title": "Append"+ }+ },+ "type": "object",+ "required": ["status", "queue_id", "image", "append"],+ "title": "VideoRecallImageResponse"+ },"VideoRecallMediaResponse": {"properties": {"status": {@@ -107744,7 +107863,7 @@},"action": {"type": "string",- "enum": ["parameters", "initial_video", "reference_video", "conditioning_video"],+ "enum": ["parameters", "initial_video", "reference_video", "conditioning_video", "image"],"title": "Action"},"video": {@@ -108304,7 +108423,7 @@},"action": {"description": "What the frontend should do with the payload",- "enum": ["parameters", "initial_video", "reference_video", "conditioning_video"],+ "enum": ["parameters", "initial_video", "reference_video", "conditioning_video", "image"],"title": "Action","type": "string"},@@ -108367,6 +108486,24 @@"default": null,"description": "For `conditioning_video`: which stream of the video is the condition; the other is generated","title": "Conditioning Role"+ },+ "image": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/VideoRecallImage"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "For `image`: the image to place"+ },+ "append": {+ "default": false,+ "description": "For `image`: add the image after the panel's own instead of replacing them -- to the reference images of a model that takes references, otherwise to the free frame slot",+ "title": "Append",+ "type": "boolean"}},"required": [@@ -108378,7 +108515,9 @@"strict","parameters","video",- "conditioning_role"+ "conditioning_role",+ "image",+ "append"],"title": "VideoRecallRequestedEvent","type": "object"diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex 7e8bb9ae3b..ebb2f37029 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -4201,6 +4201,31 @@ export type paths = {patch?: never;trace?: never;};+ "/api/v1/recall/video/{queue_id}/image": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Recall Video Image+ * @description Place a gallery image in the current user's Video panel, where the panel's model takes images.+ *+ * A model that takes reference images (e.g. MiniMax H3 Ref2VA) gets it as a reference: it replaces the reference+ * images, or with `append` joins them. A model that takes frames (e.g. Wan, LTX-2) gets it as the first frame,+ * clearing the last; with `append` it fills the first free frame slot, and is ignored when both are set. The+ * panel's model decides, so the outcome is reported to the user there rather than in this response.+ */+ post: operations["recall_video_image"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/v2/custom_nodes/": {parameters: {query?: never;@@ -48258,6 +48283,40 @@ export type components = {*/type: "video_output";};+ /**+ * VideoRecallImage+ * @description The gallery image a video recall places into the Video panel.+ */+ VideoRecallImage: {+ /**+ * Image Name+ * @description The name of the gallery image+ */+ image_name: string;+ /**+ * Width+ * @description The image's width in pixels+ */+ width: number;+ /**+ * Height+ * @description The image's height in pixels+ */+ height: number;+ };+ /** VideoRecallImageResponse */+ VideoRecallImageResponse: {+ /**+ * Status+ * @constant+ */+ status: "success";+ /** Queue Id */+ queue_id: string;+ image: components["schemas"]["VideoRecallImage"];+ /** Append */+ append: boolean;+ };/** VideoRecallMediaResponse */VideoRecallMediaResponse: {/**@@ -48271,7 +48330,7 @@ export type components = {* Action* @enum {string}*/- action: "parameters" | "initial_video" | "reference_video" | "conditioning_video";+ action: "parameters" | "initial_video" | "reference_video" | "conditioning_video" | "image";video: components["schemas"]["VideoDTO"];/*** Uploaded@@ -48506,7 +48565,7 @@ export type components = {* @description What the frontend should do with the payload* @enum {string}*/- action: "parameters" | "initial_video" | "reference_video" | "conditioning_video";+ action: "parameters" | "initial_video" | "reference_video" | "conditioning_video" | "image";/*** Mode* @description For `parameters`: `remix` applies everything except the seed@@ -48538,6 +48597,17 @@ export type components = {* @default null*/conditioning_role: ("audio" | "video") | null;+ /**+ * @description For `image`: the image to place+ * @default null+ */+ image: components["schemas"]["VideoRecallImage"] | null;+ /**+ * Append+ * @description For `image`: add the image after the panel's own instead of replacing them -- to the reference images of a model that takes references, otherwise to the free frame slot+ * @default false+ */+ append: boolean;};/*** VideoRecallVideo@@ -59963,6 +60033,43 @@ export interface operations {};};};+ recall_video_image: {+ parameters: {+ query: {+ /** @description The name of the gallery image */+ image_name: string;+ /** @description Add the image after the panel's own images instead of replacing them */+ append?: boolean;+ };+ header?: never;+ path: {+ /** @description The queue id to perform this operation on */+ queue_id: string;+ };+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["VideoRecallImageResponse"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };list_custom_node_packs: {parameters: {query?: never;diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 61567aca25..e56596267d 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -4231,11 +4231,18 @@"conditioningClipNotSet": "Conditioning clip not set","conditioningClipSet": "Conditioning clip set","conditioningClipUnsupported": "The selected video model can't generate from a conditioning clip. Choose one that can, such as LTX-2.",+ "firstFrameSet": "First frame set",+ "imageDisplaced": "The image can't be used with the panel's conditioning clip or initial video, so that was cleared.",+ "imageFull": "The selected video model's image slots are already in use. Send the image instead of appending it to replace them.",+ "imageNotPlaced": "Image not placed",+ "imageUnsupported": "The selected video model doesn't take images. Choose one that does, such as Wan 2.2 I2V or MiniMax H3 Ref2VA.","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.",+ "lastFrameSet": "Last frame set","referenceAdded": "Reference video added","referenceFull": "All video reference slots are in use. Remove a video reference and try again.",+ "referenceImageAdded": "Reference image added","referenceNotAdded": "Reference video not added","referenceUnsupported": "The selected video model doesn't take reference videos. Choose one that does, such as MiniMax H3 Ref2VA."},diff --git a/invokeai/frontend/webv2/src/features/video/index.ts b/invokeai/frontend/webv2/src/features/video/index.tsindex 15af94b652..e57f973dc3 100644--- a/invokeai/frontend/webv2/src/features/video/index.ts+++ b/invokeai/frontend/webv2/src/features/video/index.ts@@ -22,6 +22,7 @@ export {createVideoSourceClip,getDefaultConditioningRole,getDefaultReferenceConditioning,+ getDefaultReferenceImageDetail,getConditioningClipPatch,getInitialVideoPatch,getReferencesPatch,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.tsindex 9cd13ab5ac..3feec39628 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.placement.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.placement.test.ts@@ -9,6 +9,7 @@ import {getVideoPlacementRoom,placeConditioningClip,placeInitialVideo,+ placeVideoImage,} from './executeVideoRecall';const model = (fields: Record<string, unknown>) =>@@ -32,6 +33,7 @@ const REF2VA = model({name: 'H3 Ref2VA',variant: 'ref2va',});+const WAN_TI2V = model({ base: 'wan', format: 'diffusers', key: 'wan-ti2v', name: 'Wan TI2V', variant: 'ti2v_5b' });const LTX2 = model({ base: 'ltx-2', format: 'checkpoint', key: 'ltx2', name: 'LTX-2.5 dev', variant: 'ltx2_dev' });const clip = { durationSeconds: 5, fps: 16, height: 480, name: 'clip.mp4', width: 832 };@@ -238,3 +240,167 @@ describe('placeConditioningClip', () => {});});});++describe('placeVideoImage', () => {+ const still = (name: string) => ({ height: 512, image_name: name, width: 512 });+ const imageReference = (name: string): VideoReferenceItem => ({ detail: 'match', image: still(name), kind: 'image' });+ const referenceNames = (placement: ReturnType<typeof placeVideoImage>) =>+ (placement.status === 'placed' ? (placement.patch.references ?? []) : []).map((entry) =>+ entry.kind === 'image' ? entry.image.image_name : entry.clip.video_name+ );++ describe('on a model that takes reference images', () => {+ const held = [imageReference('a.png'), videoReference('dance.mp4'), imageReference('b.png')];++ it('replaces the reference images, keeping the reference videos', () => {+ const placement = placeVideoImage({+ append: false,+ image: still('new.png'),+ models: [REF2VA],+ videoValues: panel(REF2VA, { references: held }),+ });++ expect(placement).toMatchObject({ slot: 'reference', status: 'placed' });+ expect(referenceNames(placement)).toEqual(['dance.mp4', 'new.png']);+ });++ it('appends after the held references, with the detail a later image defaults to', () => {+ const placement = placeVideoImage({+ append: true,+ image: still('new.png'),+ models: [REF2VA],+ videoValues: panel(REF2VA, { references: held }),+ });++ expect(referenceNames(placement)).toEqual(['a.png', 'dance.mp4', 'b.png', 'new.png']);+ expect(placement.status === 'placed' && placement.patch.references?.at(-1)).toMatchObject({ detail: 'match' });+ });++ it('gives the first reference image max detail', () => {+ const placement = placeVideoImage({+ append: false,+ image: still('new.png'),+ models: [REF2VA],+ videoValues: panel(REF2VA, { references: held }),+ });++ expect(placement.status === 'placed' && placement.patch.references?.at(-1)).toMatchObject({ detail: 'max' });+ });++ it('keeps a reference-extend continuity anchor last', () => {+ const anchor: VideoReferenceItem = { ...videoReference('source.mp4'), fromSourceVideo: true };+ const placement = placeVideoImage({+ append: true,+ image: still('new.png'),+ models: [REF2VA],+ videoValues: panel(REF2VA, { references: [anchor] }),+ });++ expect(referenceNames(placement)).toEqual(['new.png', 'source.mp4']);+ });++ it('declines an append when every image slot is taken, but a send still replaces them', () => {+ const videoValues = panel(REF2VA, {+ references: Array.from({ length: 9 }, (_, index) => imageReference(`${index}.png`)),+ });++ expect(placeVideoImage({ append: true, image: still('new.png'), models: [REF2VA], videoValues })).toEqual({+ status: 'full',+ });+ expect(+ referenceNames(placeVideoImage({ append: false, image: still('new.png'), models: [REF2VA], videoValues }))+ ).toEqual(['new.png']);+ });+ });++ describe('on a model that takes frames', () => {+ const first = { height: 480, image_name: 'first.png', width: 832 };+ const last = { height: 480, image_name: 'last.png', width: 832 };++ it('sends the image as the first frame, clearing the last frame and the initial video', () => {+ const placement = placeVideoImage({+ append: false,+ image: still('new.png'),+ models: [WAN_I2V],+ videoValues: panel(WAN_I2V, { lastFrameImage: last, sourceVideo: { ...videoReference('source.mp4').clip } }),+ });++ expect(placement).toEqual({+ displaced: true,+ patch: {+ conditioningClip: null,+ firstFrameImage: still('new.png'),+ lastFrameImage: null,+ references: [],+ sourceVideo: null,+ },+ slot: 'firstFrame',+ status: 'placed',+ });+ });++ it('appends into the first frame, then the last, then declines', () => {+ let videoValues = panel(WAN_I2V);+ const slots: string[] = [];++ for (const name of ['one.png', 'two.png', 'three.png']) {+ const placement = placeVideoImage({ append: true, image: still(name), models: [WAN_I2V], videoValues });++ slots.push(placement.status === 'placed' ? placement.slot : placement.status);+ videoValues = placement.status === 'placed' ? { ...videoValues, ...placement.patch } : videoValues;+ }++ expect(slots).toEqual(['firstFrame', 'lastFrame', 'full']);+ expect(videoValues).toMatchObject({ firstFrameImage: still('one.png'), lastFrameImage: still('two.png') });+ });++ it('appends into the last frame beside an initial video, which holds the first', () => {+ const placement = placeVideoImage({+ append: true,+ image: still('new.png'),+ models: [WAN_I2V],+ videoValues: panel(WAN_I2V, { sourceVideo: { ...videoReference('source.mp4').clip } }),+ });++ expect(placement).toEqual({+ displaced: false,+ patch: { conditioningClip: null, lastFrameImage: still('new.png') },+ slot: 'lastFrame',+ status: 'placed',+ });+ });++ it('declines an appended second frame on a model without a last frame', () => {+ expect(+ placeVideoImage({+ append: true,+ image: still('new.png'),+ models: [WAN_TI2V],+ videoValues: panel(WAN_TI2V, { firstFrameImage: first }),+ })+ ).toEqual({ status: 'full' });+ });++ it('clears a conditioning clip, as the frame fields do', () => {+ const placement = placeVideoImage({+ append: true,+ image: still('new.png'),+ models: [LTX2],+ videoValues: panel(LTX2),+ });++ expect(placement).toMatchObject({ patch: { conditioningClip: null, firstFrameImage: still('new.png') } });+ });+ });++ it('declines, rather than switching models, when the panel model takes no images', () => {+ expect(+ placeVideoImage({+ append: false,+ image: still('new.png'),+ models: [WAN_T2V, WAN_I2V],+ videoValues: panel(WAN_T2V),+ })+ ).toEqual({ status: 'unsupported' });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.tsindex ccc3c7d53e..9a345a1bce 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts@@ -1,4 +1,5 @@import type { GalleryVideoItem } from '@features/gallery';+import type { ImageWithDims } from '@features/generation/contracts';import type { ModelConfig } from '@features/models';import type {VideoConditioningRole,@@ -18,6 +19,7 @@ import {createVideoSourceClip,getConditioningClipPatch,getDefaultReferenceConditioning,+ getDefaultReferenceImageDetail,getInitialVideoPatch,getReferencesPatch,getVideoModelPolicy,@@ -601,6 +603,102 @@ export const appendReferenceVideo = ({};};+export type VideoImagePlacement =+ | {+ /** Whether placing the image cleared media it can't be used with: a conditioning clip or an initial video. */+ displaced: boolean;+ patch: Partial<VideoWidgetValues>;+ slot: 'firstFrame' | 'lastFrame' | 'reference';+ status: 'placed';+ }+ /** `full`: an append found every image slot the model takes already in use. */+ | { status: 'full' | 'unsupported' };++/**+ * Place a gallery image where the Video panel's model takes images. A model with reference images gets it as one:+ * it replaces the reference images (reference videos stay), or with `append` joins them. A frame model gets it as+ * the first frame, clearing the last, as if the frames were a two-image list; with `append` it fills the first free+ * frame slot, and an initial video holds the first. The panel's model is never switched to make the image fit.+ */+export const placeVideoImage = ({+ append,+ image,+ models,+ videoValues,+}: {+ append: boolean;+ image: ImageWithDims;+ models: readonly ModelConfig[];+ videoValues: Record<string, unknown>;+}): VideoImagePlacement => {+ const values = getCurrentVideoValues({ models, videoValues });+ const policy = values.model ? getVideoModelPolicy(values.model, values) : null;++ if (!policy) {+ return { status: 'unsupported' };+ }++ if (policy.references && policy.modes.includes('reference')) {+ const kept = append ? values.references : values.references.filter((entry) => entry.kind === 'video');++ if (kept.filter((entry) => entry.kind === 'image').length >= policy.references.maxImages) {+ return { status: 'full' };+ }+ const referenceExtend = Boolean(policy.references.extend);++ return {+ displaced: Boolean(values.conditioningClip || (values.sourceVideo && !referenceExtend)),+ patch: getReferencesPatch({+ referenceExtend,+ references: [...kept, { detail: getDefaultReferenceImageDetail(kept), image, kind: 'image' }],+ }),+ slot: 'reference',+ status: 'placed',+ };+ }++ const takesFirstFrame = policy.modes.includes('first-frame') || policy.modes.includes('first-last');++ if (!takesFirstFrame) {+ return { status: 'unsupported' };+ }++ // The same displacements as the panel's own frame fields: a first frame shares its slot with the initial video,+ // and either frame clears a conditioning clip.+ if (!append) {+ return {+ displaced: Boolean(values.conditioningClip || values.sourceVideo),+ patch: {+ conditioningClip: null,+ firstFrameImage: image,+ lastFrameImage: null,+ references: [],+ sourceVideo: null,+ },+ slot: 'firstFrame',+ status: 'placed',+ };+ }+ if (!values.firstFrameImage && !values.sourceVideo) {+ return {+ displaced: Boolean(values.conditioningClip),+ patch: { conditioningClip: null, firstFrameImage: image, references: [] },+ slot: 'firstFrame',+ status: 'placed',+ };+ }+ if (!values.lastFrameImage && policy.modes.includes('first-last')) {+ return {+ displaced: Boolean(values.conditioningClip),+ patch: { conditioningClip: null, lastFrameImage: image },+ slot: 'lastFrame',+ status: 'placed',+ };+ }++ return { status: 'full' };+};+/** The generation mode a conditioning clip in each role asks of the model. */const CONDITIONING_ROLE_MODE = {audio: 'audio-to-video',diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts b/invokeai/frontend/webv2/src/workbench/image-actions/index.tsindex 66557e07eb..2e436275e3 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/index.ts@@ -22,6 +22,7 @@ export {getCurrentVideoValues,placeConditioningClip,placeInitialVideo,+ placeVideoImage,type PlaceableVideo,} from './executeVideoRecall';export { getImageRecallVerb, IMAGE_RECALL_KINDS } from './RecallActionButtons';diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.tsindex 6d832590b6..a2f405237c 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts@@ -301,6 +301,15 @@ describe('createVideoRecallRuntime', () => {['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' }],+ [+ 'an image placement without its append flag',+ { action: 'image', image: { height: 1, image_name: 'a.png', width: 1 }, user_id: 'owner' },+ ],+ [+ 'an image placement whose image has no size',+ { action: 'image', append: false, image: { image_name: 'a.png' }, user_id: 'owner' },+ ],+['a conditioning video without its role', placementEvent('conditioning_video')],['a conditioning video with an unknown role',@@ -451,6 +460,88 @@ describe('createVideoRecallRuntime', () => {runtime.dispose();});+ const imageEvent = (append: boolean, image_name = 'still.png') => ({+ action: 'image',+ append,+ image: { height: 512, image_name, width: 512 },+ queue_id: 'default',+ user_id: 'owner',+ });++ it('sends an image as a Ref2VA reference image and appends the next one', async () => {+ const { lastNotice, runtime, socket, videoShown, videoValues } = setup(REF2VA);++ socket.emit(imageEvent(false, 'a.png'));+ await flush();+ socket.emit(imageEvent(true, 'b.png'));+ await flush();++ expect(videoValues().references).toEqual([+ { detail: 'max', image: { height: 512, image_name: 'a.png', width: 512 }, kind: 'image' },+ { detail: 'match', image: { height: 512, image_name: 'b.png', width: 512 }, kind: 'image' },+ ]);+ expect(lastNotice()).toMatchObject({ kind: 'success', title: 'widgets.video.placement.referenceImageAdded' });+ expect(videoShown()).toBe(true);++ runtime.dispose();+ });++ it('sends an image as the first frame of a frame model and appends the last frame', async () => {+ const { lastNotice, runtime, socket, videoValues } = setup();++ socket.emit(imageEvent(false, 'first.png'));+ await flush();+ expect(videoValues()).toMatchObject({ firstFrameImage: { image_name: 'first.png' }, lastFrameImage: null });+ expect(lastNotice()).toMatchObject({ title: 'widgets.video.placement.firstFrameSet' });++ socket.emit(imageEvent(true, 'last.png'));+ await flush();+ expect(videoValues()).toMatchObject({+ firstFrameImage: { image_name: 'first.png' },+ lastFrameImage: { image_name: 'last.png' },+ });+ expect(lastNotice()).toMatchObject({ title: 'widgets.video.placement.lastFrameSet' });++ runtime.dispose();+ });++ it('says so when an image clears a conditioning clip', async () => {+ const { lastNotice, runtime, socket, videoValues } = setup(LTX2);+ socket.emit({ ...placementEvent('conditioning_video'), conditioning_role: 'audio' });+ await flush();+ expect(videoValues()).toMatchObject({ conditioningClip: { role: 'audio' } });++ socket.emit(imageEvent(true));+ await flush();++ expect(videoValues()).toMatchObject({ conditioningClip: null, firstFrameImage: { image_name: 'still.png' } });+ expect(lastNotice()).toMatchObject({+ kind: 'info',+ message: 'widgets.video.placement.imageDisplaced',+ title: 'widgets.video.placement.firstFrameSet',+ });++ runtime.dispose();+ });++ it.each([+ [WAN_T2V, false, 'widgets.video.placement.imageUnsupported'],+ [WAN_I2V, true, 'widgets.video.placement.imageFull'],+ ])('declines an image with nowhere to go, leaving the panel alone', async (panelModel, append, message) => {+ const { lastNotice, projectId, runtime, socket, store, videoShown, videoValues } = setup(panelModel);+ store.commands.widgets.patchValues('video', { lastFrameImage: heldFrame }, projectId);+ const before = videoValues();++ socket.emit(imageEvent(append));+ await flush();++ expect(videoValues()).toBe(before);+ expect(lastNotice()).toMatchObject({ kind: 'info', message, title: 'widgets.video.placement.imageNotPlaced' });+ expect(videoShown()).toBe(false);++ runtime.dispose();+ });+it('declines an initial video a Ref2VA panel has no reference slot to anchor', async () => {const { lastNotice, runtime, socket, videoValues } = setup(REF2VA);diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.tsindex 1514a3b33e..df6e3ad3b8 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.ts@@ -19,6 +19,7 @@ import {getCurrentVideoValues,placeConditioningClip,placeInitialVideo,+ placeVideoImage,} from './index';import { bringRecallWidgetToFront, createRecallEventRuntime } from './recallEventRuntime';@@ -32,6 +33,13 @@ interface VideoRecallEventVideo {width: number;}+/** The `image` of a `video_recall_requested` event: a gallery image, as the backend describes it. */+interface VideoRecallEventImage {+ height: number;+ image_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 } & (| {@@ -43,6 +51,7 @@ export type VideoRecallRequestedEvent = { user_id: string } & (}| { action: 'initial_video' | 'reference_video'; video: VideoRecallEventVideo }| { action: 'conditioning_video'; conditioning_role: VideoConditioningRole; video: VideoRecallEventVideo }+ | { action: 'image'; append: boolean; image: VideoRecallEventImage });const isRecord = (value: unknown): value is Record<string, unknown> =>@@ -62,6 +71,12 @@ const isEventVideo = (value: unknown): value is VideoRecallEventVideo =>(value.fps === null || isPositiveNumber(value.fps)) &&(value.media_origin === null || typeof value.media_origin === 'string');+const isEventImage = (value: unknown): value is VideoRecallEventImage =>+ isRecord(value) &&+ typeof value.image_name === 'string' &&+ isPositiveNumber(value.width) &&+ isPositiveNumber(value.height);+export const isVideoRecallRequestedEvent = (payload: unknown): payload is VideoRecallRequestedEvent => {if (!isRecord(payload) || typeof payload.user_id !== 'string') {return false;@@ -74,6 +89,10 @@ export const isVideoRecallRequestedEvent = (payload: unknown): payload is VideoR);}+ if (payload.action === 'image') {+ return typeof payload.append === 'boolean' && isEventImage(payload.image);+ }+if (payload.action === 'conditioning_video') {return ((payload.conditioning_role === 'audio' || payload.conditioning_role === 'video') && isEventVideo(payload.video)@@ -92,9 +111,16 @@ const toPlaceableVideo = (video: VideoRecallEventVideo): PlaceableVideo => ({width: video.width,});+const IMAGE_PLACED_TITLES = {+ firstFrame: 'widgets.video.placement.firstFrameSet',+ lastFrame: 'widgets.video.placement.lastFrameSet',+ reference: 'widgets.video.placement.referenceImageAdded',+} as const;+/*** Apply `video_recall_requested` events to their arrival-time project's Video panel: recall or remix parameters,- * set the Initial Video, append a reference video, or set the conditioning clip. The panel's model is never switched to make a video fit; a+ * set the Initial Video, append a reference video, set the conditioning clip, or place an image as a reference or+ * frame. 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.*/@@ -177,6 +203,37 @@ export const createVideoRecallRuntime = ({);applied = true;}+ } else if (event.action === 'image') {+ const placement = placeVideoImage({+ append: event.append,+ image: { height: event.image.height, image_name: event.image.image_name, width: event.image.width },+ models,+ videoValues,+ });++ if (placement.status === 'placed') {+ commands.widgets.patchValues('video', placement.patch, projectId);+ commands.notifications.add(+ placement.displaced+ ? {+ kind: 'info',+ message: t('widgets.video.placement.imageDisplaced'),+ title: t(IMAGE_PLACED_TITLES[placement.slot]),+ }+ : { kind: 'success', title: t(IMAGE_PLACED_TITLES[placement.slot]) }+ );+ applied = true;+ } else {+ commands.notifications.add({+ kind: 'info',+ message: t(+ placement.status === 'full'+ ? 'widgets.video.placement.imageFull'+ : 'widgets.video.placement.imageUnsupported'+ ),+ title: t('widgets.video.placement.imageNotPlaced'),+ });+ }} else if (event.action === 'conditioning_video') {const placement = placeConditioningClip({models,diff --git a/tests/app/routers/test_video_recall.py b/tests/app/routers/test_video_recall.pyindex cbc017b251..7b04c889fe 100644--- a/tests/app/routers/test_video_recall.py+++ b/tests/app/routers/test_video_recall.py@@ -16,7 +16,11 @@ from fastapi.testclient import TestClientfrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.api.routers import videosfrom invokeai.app.services.board_records.board_records_common import BoardChanges, BoardVisibility-from invokeai.app.services.events.events_common import VideoRecallRequestedEvent, VideoUploadedEvent+from invokeai.app.services.events.events_common import (+ VideoRecallImage,+ VideoRecallRequestedEvent,+ VideoUploadedEvent,+)from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOriginfrom invokeai.app.services.invoker import Invokerfrom invokeai.app.services.model_records.model_records_base import UnknownModelException@@ -699,6 +703,70 @@ class TestGalleryVideoPlacement:assert _recall_events(invoker) == []+class TestGalleryImagePlacement:+ @pytest.mark.parametrize("append", [False, True])+ def test_a_gallery_image_is_delivered_with_its_size_and_append_flag(+ self, invoker: Invoker, client: TestClient, append: bool+ ) -> None:+ _save_image(invoker, "still.png")++ response = client.post(+ "/api/v1/recall/video/queue-b/image", params={"image_name": "still.png", "append": str(append).lower()}+ )++ assert response.status_code == 200+ expected_image = {"image_name": "still.png", "width": 64, "height": 64}+ assert response.json() == {+ "status": "success",+ "queue_id": "queue-b",+ "image": expected_image,+ "append": append,+ }+ event = _only_recall_event(invoker)+ assert event.action == "image"+ assert event.queue_id == "queue-b"+ assert event.append is append+ assert event.image is not None and event.image.model_dump() == expected_image+ assert event.video is None and event.parameters is None++ def test_an_image_replaces_unless_asked_to_append(self, invoker: Invoker, client: TestClient) -> None:+ _save_image(invoker, "still.png")++ client.post("/api/v1/recall/video/default/image", params={"image_name": "still.png"})++ assert _only_recall_event(invoker).append is False++ def test_an_unknown_image_is_a_404(self, invoker: Invoker, client: TestClient) -> None:+ response = client.post("/api/v1/recall/video/default/image", params={"image_name": "nope.png"})++ assert response.status_code == 404+ assert _recall_events(invoker) == []++ def test_blocked_during_image_move_maintenance(self, invoker: Invoker, client: TestClient) -> None:+ _save_image(invoker, "still.png")+ invoker.services.image_moves.is_maintenance_active.return_value = True # type: ignore[attr-defined]++ response = client.post("/api/v1/recall/video/default/image", params={"image_name": "still.png"})++ assert response.status_code == 409+ assert _recall_events(invoker) == []++ @pytest.mark.parametrize(+ ("action", "image", "append"),+ [+ ("image", None, False),+ ("reference_video", VideoRecallImage(image_name="still.png", width=64, height=64), False),+ ("parameters", None, True),+ ],+ ids=["missing-image", "stray-image", "stray-append"],+ )+ def test_the_event_carries_an_image_and_append_with_and_only_with_an_image_action(+ self, action: str, image: VideoRecallImage | None, append: bool+ ) -> None:+ with pytest.raises(ValueError):+ VideoRecallRequestedEvent.build("default", "owner", action, image=image, append=append) # type: ignore[arg-type]++def _create_board(invoker: Invoker, owner_id: str, visibility: BoardVisibility) -> str:board = invoker.services.board_records.save("Board", owner_id)invoker.services.board_records.update(board.board_id, BoardChanges(board_visibility=visibility))@@ -830,8 +898,9 @@ class TestMultiUserAccess:("/api/v1/recall/video/default/reference-video", {"params": {"video_name": "clip.mp4"}}),("/api/v1/recall/video/default/initial-video/upload", {"files": {"file": ("c.mp4", MP4_BYTES)}}),("/api/v1/recall/video/default/reference-video/upload", {"files": {"file": ("c.mp4", MP4_BYTES)}}),+ ("/api/v1/recall/video/default/image", {"params": {"image_name": "still.png"}}),],- ids=["parameters", "initial-video", "reference-video", "initial-upload", "reference-upload"],+ ids=["parameters", "initial-video", "reference-video", "initial-upload", "reference-upload", "image"],)def test_every_route_requires_authentication(self, invoker: Invoker, client: TestClient, multiuser: dict[str, Any], method_path: str, kwargs: dict@@ -855,6 +924,32 @@ class TestMultiUserAccess:assert response.status_code == status.HTTP_403_FORBIDDENassert _recall_events(invoker) == []+ def test_an_unknown_image_is_a_404_for_a_non_admin_too(+ self, invoker: Invoker, client: TestClient, multiuser: dict[str, Any]+ ) -> None:+ response = client.post(+ "/api/v1/recall/video/default/image",+ params={"image_name": "nope.png"},+ headers=multiuser["other"]["headers"],+ )++ assert response.status_code == status.HTTP_404_NOT_FOUND+ assert _recall_events(invoker) == []++ def test_another_users_private_image_cannot_be_placed(+ self, invoker: Invoker, client: TestClient, multiuser: dict[str, Any]+ ) -> None:+ _save_image(invoker, "private.png", multiuser["owner"]["id"])++ response = client.post(+ "/api/v1/recall/video/default/image",+ params={"image_name": "private.png"},+ headers=multiuser["other"]["headers"],+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert _recall_events(invoker) == []+@pytest.mark.parametrize("body",[