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-recall): place a video as the LTX-2 conditioning clip
Lincoln Stein701b657d68b9
diff --git a/docs/src/content/docs/development/Guides/video-recall-api.mdx b/docs/src/content/docs/development/Guides/video-recall-api.mdxindex 6bf19e5095..8f189c3412 100644--- a/docs/src/content/docs/development/Guides/video-recall-api.mdx+++ b/docs/src/content/docs/development/Guides/video-recall-api.mdx@@ -16,8 +16,11 @@ browser, a script, another application — drive a user's open **Video** panel:outcome as the gallery's *Extend in Video* action.- **Use as Ref Video** — append a video to the reference list of models that takereference videos (today, MiniMax H3 Ref2VA).+- **Use as Conditioning Clip** — set a video as the conditioning clip of models that+ generate one half of a clip from the other (today, LTX-2): its soundtrack, to+ generate a picture for it, or its picture, to generate a soundtrack for it.-Send Video and Use as Ref Video take either the name of a video already in the+Send Video, Use as Ref Video and Use as Conditioning Clip take either the name of a video already in thegallery or a video file, which is uploaded into the gallery first.## How it works@@ -42,6 +45,8 @@ gallery or a video file, which is uploaded into the gallery first.| `POST /api/v1/recall/video/{queue_id}/initial-video/upload` | multipart `file` | Upload, then send || `POST /api/v1/recall/video/{queue_id}/reference-video?video_name=…` | none | Use a gallery video as a reference || `POST /api/v1/recall/video/{queue_id}/reference-video/upload` | multipart `file` | Upload, then use as a reference |+| `POST /api/v1/recall/video/{queue_id}/conditioning-video?video_name=…&role=…` | none | Use a gallery video as the conditioning clip |+| `POST /api/v1/recall/video/{queue_id}/conditioning-video/upload?role=…` | multipart `file` | Upload, then use as the conditioning clip |`queue_id` is the frontend's queue, normally `default`.@@ -76,7 +81,13 @@ the response's `overridden` maps it to the field that won — for exampleprecedence: a `source_video` that is missing from the gallery overrides nothing.Send only the fields you mean to set; the Swagger page offers minimal examples.-### Send Video and Use as Ref Video+### Send Video, Use as Ref Video and Use as Conditioning Clip++The conditioning-clip routes require a `role` query parameter naming which stream of+the video is the condition: `audio` keeps its soundtrack and generates a picture for+it (LTX-2 audio-to-video); `video` keeps its picture and generates a soundtrack for it+(video-to-audio). A missing or unknown `role` is rejected with `422` before any upload+is read.The name-only routes take `video_name` as a query parameter; the video must be inthe gallery and readable by the caller.@@ -93,8 +104,9 @@ answer `429` with a `Retry-After` header.Whether the video is usable depends on the model selected in the panel, which isnever 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.+extend a clip, a reference video needs a model that takes reference videos,+with room for another, and a conditioning clip needs a model that generates in the+requested role.## Frontend behavior@@ -132,9 +144,19 @@ in a text field; the notification still reports the change.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 whenthe 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.+- **Use as Conditioning Clip** sets the panel's *Conditioning Clip* in the requested+ role; the whole clip is used. A conditioning clip excludes every other medium, so+ where the panel's own field waits for you to clear them, this action clears the+ first and last frames, the initial video and the references itself, and the+ notification says so when there were any. It replaces a conditioning clip the+ panel already holds. It is declined, leaving the panel alone, when the panel's+ model cannot generate in that role, and in the `video` role for an uploaded audio+ file, whose picture is only a placeholder. Other settings are not changed to fit+ the clip: a two-stage resolution, or a clip whose length falls outside the+ model's frame range, still has to be fixed before the panel can generate.++The gallery's context menu offers the same *Extend in Video*, *Use as Reference+Video* and *Use as Conditioning Clip* actions for any video in the gallery.## Request schema@@ -227,6 +249,10 @@ curl -X POST "http://localhost:9090/api/v1/recall/video/default/initial-video?vi# Upload a clip onto a board and use it as a Ref2VA referencecurl -X POST "http://localhost:9090/api/v1/recall/video/default/reference-video/upload?board_id=<board-id>" \-F "[email protected]"++# Generate an LTX-2 picture for a song's soundtrack+curl -X POST "http://localhost:9090/api/v1/recall/video/default/conditioning-video/upload?role=audio" \+ -F "[email protected]"```In multi-user mode, add `-H "Authorization: Bearer <token>"`.@@ -266,7 +292,7 @@ exactly what the frontend receives. `skipped` lists fields whose model or mediumcould not be used; `overridden` maps media fields that lost to a higher-precedencemedium in the same request to the field that won.-Send Video / Use as Ref Video:+Send Video / Use as Ref Video / Use as Conditioning Clip:```json{ "status": "success", "queue_id": "default", "action": "reference_video", "video": { "video_name": "…", "…": "…" }, "uploaded": true }@@ -281,11 +307,11 @@ Send Video / Use as Ref Video:| `401` | Multi-user mode without a valid token || `400` | The upload ended before its body was complete || `403` | The caller may not read a referenced image or video, or may not add media to `board_id` |-| `404` | `video_name` (Send Video / Use as Ref Video) is not in the gallery, or `board_id` does not exist |+| `404` | `video_name` (Send Video / Use as Ref Video / Use as Conditioning Clip) is not in the gallery, or `board_id` does not exist || `409` | Image storage maintenance is running (Recall / Remix) || `413` | The upload exceeds the video upload size limit || `415` | The upload is not a supported video or audio file, or could not be converted |-| `422` | Malformed JSON or multipart body, an unknown field, a value out of bounds, or `metadata` that is not a JSON object |+| `422` | Malformed JSON or multipart body, an unknown field, a value out of bounds, a missing or unknown `role` (Use as Conditioning Clip), or `metadata` that is not a JSON object || `429` | Too many concurrent video uploads || `500` | The uploaded video could not be stored |@@ -297,11 +323,12 @@ Send Video / Use as Ref Video:|---|---|---|| `queue_id` | string | From the request path || `user_id` | string | The caller |-| `action` | `"parameters"` \| `"initial_video"` \| `"reference_video"` | What to do |+| `action` | `"parameters"` \| `"initial_video"` \| `"reference_video"` \| `"conditioning_video"` | What to do || `mode` | `"recall"` \| `"remix"` \| null | `parameters` only || `strict` | boolean | `parameters` only || `parameters` | object \| null | `parameters` only: the resolved fields, with models as `{key, hash, name, base, type}` || `video` | object \| null | Placements only: `{video_name, width, height, duration, fps, media_origin}` |+| `conditioning_role` | `"audio"` \| `"video"` \| null | `conditioning_video` only: which stream of `video` is the condition |## Implementationdiff --git a/invokeai/app/api/routers/video_recall.py b/invokeai/app/api/routers/video_recall.pyindex b35b5334a2..daa74b4f6f 100644--- a/invokeai/app/api/routers/video_recall.py+++ b/invokeai/app/api/routers/video_recall.py@@ -17,7 +17,12 @@ from invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.api.routers._access import assert_image_read_access, assert_video_read_accessfrom invokeai.app.api.routers.image_move_maintenance import assert_image_move_maintenance_inactivefrom invokeai.app.api.routers.videos import VIDEO_UPLOAD_OPENAPI_EXTRA, ingest_uploaded_video-from invokeai.app.services.events.events_common import VideoRecallAction, VideoRecallMode, VideoRecallVideo+from invokeai.app.services.events.events_common import (+ VideoRecallAction,+ VideoRecallConditioningRole,+ VideoRecallMode,+ VideoRecallVideo,+)from invokeai.app.services.image_records.image_records_common import ImageCategoryfrom invokeai.app.services.model_records.model_records_base import UnknownModelExceptionfrom invokeai.app.services.video_records.video_records_common import VideoRecordNotFoundException@@ -176,7 +181,7 @@ class VideoRecallParameter(BaseModel):ltx2_conditioning_video: Optional[VideoRefParameter] = Field(default=None, description="LTX-2: a clip whose audio (or picture) conditions the whole generation")- ltx2_conditioning_role: Optional[Literal["audio", "video"]] = Field(+ ltx2_conditioning_role: Optional[VideoRecallConditioningRole] = Field(default=None, description="LTX-2: which stream of `ltx2_conditioning_video` is the condition; required with it")minimax_h3_references: Optional[list[ReferenceParameter]] = Field(@@ -535,7 +540,12 @@ def recall_video_parameters(def _emit_video_placement(- queue_id: str, user_id: str, action: VideoRecallAction, video: VideoDTO, uploaded: bool+ queue_id: str,+ user_id: str,+ action: VideoRecallAction,+ video: VideoDTO,+ uploaded: bool,+ conditioning_role: Optional[VideoRecallConditioningRole] = None,) -> VideoRecallMediaResponse:ApiDependencies.invoker.services.events.emit_video_recall_requested(queue_id,@@ -549,19 +559,24 @@ def _emit_video_placement(fps=video.fps,media_origin=video.media_origin,),+ conditioning_role=conditioning_role,)return VideoRecallMediaResponse(status="success", queue_id=queue_id, action=action, video=video, uploaded=uploaded)def _place_gallery_video(- queue_id: str, action: VideoRecallAction, video_name: str, current_user: CurrentUserOrDefault+ queue_id: str,+ action: VideoRecallAction,+ video_name: str,+ current_user: CurrentUserOrDefault,+ conditioning_role: Optional[VideoRecallConditioningRole] = None,) -> VideoRecallMediaResponse:assert_video_read_access(video_name, current_user)try:video = ApiDependencies.invoker.services.videos.get_dto(video_name)except VideoRecordNotFoundException:raise HTTPException(status_code=404, detail="Video not found")- return _emit_video_placement(queue_id, current_user.user_id, action, video, uploaded=False)+ return _emit_video_placement(queue_id, current_user.user_id, action, video, False, conditioning_role)async def _place_uploaded_video(@@ -570,14 +585,22 @@ async def _place_uploaded_video(action: VideoRecallAction,board_id: Optional[str],current_user: CurrentUserOrDefault,+ conditioning_role: Optional[VideoRecallConditioningRole] = None,) -> VideoRecallMediaResponse:video = await ingest_uploaded_video(request, current_user, video_category=ImageCategory.GENERAL, is_intermediate=False, board_id=board_id)- return _emit_video_placement(queue_id, current_user.user_id, action, video, uploaded=True)+ return _emit_video_placement(queue_id, current_user.user_id, action, video, True, conditioning_role)_VIDEO_NAME_QUERY = Query(..., min_length=1, max_length=255, description="The name of the gallery video")+_CONDITIONING_ROLE_QUERY = Query(+ ...,+ description=(+ "Which stream of the video is the condition: `audio` generates a picture for its soundtrack, "+ "`video` generates a soundtrack for its picture"+ ),+)_BOARD_ID_QUERY = Query(default=None, description="The board to upload the video to; Uncategorized when omitted")_UPLOAD_RESPONSES: dict[int | str, dict[str, Any]] = {413: {"description": "The video exceeds the upload size limit"},@@ -646,3 +669,39 @@ async def recall_reference_video_upload() -> VideoRecallMediaResponse:"""Upload a video into the gallery and append it to the current user's reference videos."""return await _place_uploaded_video(request, queue_id, "reference_video", board_id, current_user)+++@video_recall_router.post(+ "/{queue_id}/conditioning-video",+ operation_id="recall_conditioning_video",+ response_model=VideoRecallMediaResponse,+)+def recall_conditioning_video(+ current_user: CurrentUserOrDefault,+ queue_id: str = Path(..., description="The queue id to perform this operation on"),+ video_name: str = _VIDEO_NAME_QUERY,+ role: VideoRecallConditioningRole = _CONDITIONING_ROLE_QUERY,+) -> VideoRecallMediaResponse:+ """Set a gallery video as the current user's conditioning clip (models that take one, e.g. LTX-2).++ The clip replaces the panel's other conditioning media: frames, initial video and references.+ """+ return _place_gallery_video(queue_id, "conditioning_video", video_name, current_user, role)+++@video_recall_router.post(+ "/{queue_id}/conditioning-video/upload",+ operation_id="recall_conditioning_video_upload",+ response_model=VideoRecallMediaResponse,+ responses=_UPLOAD_RESPONSES,+ openapi_extra=VIDEO_UPLOAD_OPENAPI_EXTRA,+)+async def recall_conditioning_video_upload(+ current_user: CurrentUserOrDefault,+ request: Request,+ queue_id: str = Path(..., description="The queue id to perform this operation on"),+ role: VideoRecallConditioningRole = _CONDITIONING_ROLE_QUERY,+ board_id: Optional[str] = _BOARD_ID_QUERY,+) -> 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)diff --git a/invokeai/app/api_app.py b/invokeai/app/api_app.pyindex a7f948531b..69c5bb7051 100644--- a/invokeai/app/api_app.py+++ b/invokeai/app/api_app.py@@ -545,7 +545,9 @@ class RequestBodyLimitASGIMiddleware:# The video-recall routes that take an upload ingest it exactly as /videos/upload does, so they# share its ingress cap and concurrency slots. Their name-only siblings take no body and stay# outside the limiter, so a caller mid-upload is never refused a slot for a bodyless request.-_VIDEO_RECALL_UPLOAD_PATH = re.compile(r"/api/v1/recall/video/[^/]+/(?:initial-video|reference-video)/upload")+_VIDEO_RECALL_UPLOAD_PATH = re.compile(+ r"/api/v1/recall/video/[^/]+/(?:initial-video|reference-video|conditioning-video)/upload"+)def _is_video_upload(method: str, path: str) -> bool:diff --git a/invokeai/app/services/events/events_base.py b/invokeai/app/services/events/events_base.pyindex 994be4555b..5ecbd7cc13 100644--- a/invokeai/app/services/events/events_base.py+++ b/invokeai/app/services/events/events_base.py@@ -43,6 +43,7 @@ from invokeai.app.services.events.events_common import (RecallParametersUpdatedEvent,UserAccessChangedEvent,VideoRecallAction,+ VideoRecallConditioningRole,VideoRecallMode,VideoRecallRequestedEvent,VideoRecallVideo,@@ -166,9 +167,14 @@ class EventServiceBase:strict: bool = False,parameters: dict | None = None,video: VideoRecallVideo | None = None,+ conditioning_role: VideoRecallConditioningRole | None = None,) -> 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))+ self.dispatch(+ VideoRecallRequestedEvent.build(+ queue_id, user_id, action, mode, strict, parameters, video, conditioning_role+ )+ )# endregiondiff --git a/invokeai/app/services/events/events_common.py b/invokeai/app/services/events/events_common.pyindex 80fee5c022..9c81a2c0f4 100644--- a/invokeai/app/services/events/events_common.py+++ b/invokeai/app/services/events/events_common.py@@ -2,7 +2,7 @@ from typing import TYPE_CHECKING, Any, ClassVar, Coroutine, Generic, Literal, Opfrom fastapi_events.handlers.local import local_handlerfrom fastapi_events.registry.payload_schema import registry as payload_schema-from pydantic import BaseModel, ConfigDict, Field+from pydantic import BaseModel, ConfigDict, Field, model_validatorfrom invokeai.app.services.board_records.board_records_common import BoardVisibilityfrom invokeai.app.services.image_records.image_records_common import ImageCategory@@ -925,7 +925,8 @@ class RecallParametersUpdatedEvent(QueueEventBase):return cls(queue_id=queue_id, user_id=user_id, parameters=parameters)-VideoRecallAction: TypeAlias = Literal["parameters", "initial_video", "reference_video"]+VideoRecallAction: TypeAlias = Literal["parameters", "initial_video", "reference_video", "conditioning_video"]+VideoRecallConditioningRole: TypeAlias = Literal["audio", "video"]VideoRecallMode: TypeAlias = Literal["recall", "remix"]@@ -961,8 +962,18 @@ class VideoRecallRequestedEvent(QueueEventBase):default=None, description="For `parameters`: recall fields, keyed like the video metadata record")video: Optional[VideoRecallVideo] = Field(- default=None, description="For `initial_video` and `reference_video`: the video to place"+ default=None, description="For `initial_video`, `reference_video` and `conditioning_video`: the video to place")+ conditioning_role: Optional[VideoRecallConditioningRole] = Field(+ default=None,+ description="For `conditioning_video`: which stream of the video is the condition; the other is generated",+ )++ @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")+ return self@classmethoddef build(@@ -974,6 +985,7 @@ class VideoRecallRequestedEvent(QueueEventBase):strict: bool = False,parameters: Optional[dict[str, Any]] = None,video: Optional[VideoRecallVideo] = None,+ conditioning_role: Optional[VideoRecallConditioningRole] = None,) -> "VideoRecallRequestedEvent":return cls(queue_id=queue_id,@@ -983,6 +995,7 @@ class VideoRecallRequestedEvent(QueueEventBase):strict=strict,parameters=parameters,video=video,+ conditioning_role=conditioning_role,)diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 7b5d82e2c4..503a31d1a9 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -16046,6 +16046,197 @@}}},+ "/api/v1/recall/video/{queue_id}/conditioning-video": {+ "post": {+ "tags": ["recall"],+ "summary": "Recall Conditioning Video",+ "description": "Set a gallery video as the current user's conditioning clip (models that take one, e.g. LTX-2).\n\nThe clip replaces the panel's other conditioning media: frames, initial video and references.",+ "operationId": "recall_conditioning_video",+ "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": "video_name",+ "in": "query",+ "required": true,+ "schema": {+ "type": "string",+ "minLength": 1,+ "maxLength": 255,+ "description": "The name of the gallery video",+ "title": "Video Name"+ },+ "description": "The name of the gallery video"+ },+ {+ "name": "role",+ "in": "query",+ "required": true,+ "schema": {+ "enum": ["audio", "video"],+ "type": "string",+ "description": "Which stream of the video is the condition: `audio` generates a picture for its soundtrack, `video` generates a soundtrack for its picture",+ "title": "Role"+ },+ "description": "Which stream of the video is the condition: `audio` generates a picture for its soundtrack, `video` generates a soundtrack for its picture"+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/VideoRecallMediaResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/recall/video/{queue_id}/conditioning-video/upload": {+ "post": {+ "tags": ["recall"],+ "summary": "Recall Conditioning Video Upload",+ "description": "Upload a video into the gallery and set it as the current user's conditioning clip.",+ "operationId": "recall_conditioning_video_upload",+ "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": "role",+ "in": "query",+ "required": true,+ "schema": {+ "enum": ["audio", "video"],+ "type": "string",+ "description": "Which stream of the video is the condition: `audio` generates a picture for its soundtrack, `video` generates a soundtrack for its picture",+ "title": "Role"+ },+ "description": "Which stream of the video is the condition: `audio` generates a picture for its soundtrack, `video` generates a soundtrack for its picture"+ },+ {+ "name": "board_id",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "The board to upload the video to; Uncategorized when omitted",+ "title": "Board Id"+ },+ "description": "The board to upload the video to; Uncategorized when omitted"+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/VideoRecallMediaResponse"+ }+ }+ }+ },+ "413": {+ "description": "The video exceeds the upload size limit"+ },+ "415": {+ "description": "The file is not a supported video or audio file"+ },+ "429": {+ "description": "Too many concurrent video uploads"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ },+ "requestBody": {+ "required": true,+ "content": {+ "multipart/form-data": {+ "schema": {+ "properties": {+ "file": {+ "type": "string",+ "contentMediaType": "application/octet-stream",+ "title": "File"+ },+ "metadata": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Metadata",+ "description": "The metadata to associate with the video, must be a stringified JSON dict"+ }+ },+ "type": "object",+ "required": ["file"],+ "title": "Body_upload_video"+ }+ }+ }+ }+ }+ },"/api/v2/custom_nodes/": {"get": {"tags": ["custom_nodes"],@@ -105889,7 +106080,7 @@},"action": {"type": "string",- "enum": ["parameters", "initial_video", "reference_video"],+ "enum": ["parameters", "initial_video", "reference_video", "conditioning_video"],"title": "Action"},"video": {@@ -106449,7 +106640,7 @@},"action": {"description": "What the frontend should do with the payload",- "enum": ["parameters", "initial_video", "reference_video"],+ "enum": ["parameters", "initial_video", "reference_video", "conditioning_video"],"title": "Action","type": "string"},@@ -106497,10 +106688,34 @@}],"default": null,- "description": "For `initial_video` and `reference_video`: the video to place"+ "description": "For `initial_video`, `reference_video` and `conditioning_video`: the video to place"+ },+ "conditioning_role": {+ "anyOf": [+ {+ "enum": ["audio", "video"],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "For `conditioning_video`: which stream of the video is the condition; the other is generated",+ "title": "Conditioning Role"}},- "required": ["timestamp", "queue_id", "user_id", "action", "mode", "strict", "parameters", "video"],+ "required": [+ "timestamp",+ "queue_id",+ "user_id",+ "action",+ "mode",+ "strict",+ "parameters",+ "video",+ "conditioning_role"+ ],"title": "VideoRecallRequestedEvent","type": "object"},diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 508a31ce75..a0435f025e 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -4142,6 +4142,48 @@ export type paths = {patch?: never;trace?: never;};+ "/api/v1/recall/video/{queue_id}/conditioning-video": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Recall Conditioning Video+ * @description Set a gallery video as the current user's conditioning clip (models that take one, e.g. LTX-2).+ *+ * The clip replaces the panel's other conditioning media: frames, initial video and references.+ */+ post: operations["recall_conditioning_video"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };+ "/api/v1/recall/video/{queue_id}/conditioning-video/upload": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Recall Conditioning Video Upload+ * @description Upload a video into the gallery and set it as the current user's conditioning clip.+ */+ post: operations["recall_conditioning_video_upload"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/v2/custom_nodes/": {parameters: {query?: never;@@ -47474,7 +47516,7 @@ export type components = {* Action* @enum {string}*/- action: "parameters" | "initial_video" | "reference_video";+ action: "parameters" | "initial_video" | "reference_video" | "conditioning_video";video: components["schemas"]["VideoDTO"];/*** Uploaded@@ -47709,7 +47751,7 @@ export type components = {* @description What the frontend should do with the payload* @enum {string}*/- action: "parameters" | "initial_video" | "reference_video";+ action: "parameters" | "initial_video" | "reference_video" | "conditioning_video";/*** Mode* @description For `parameters`: `remix` applies everything except the seed@@ -47731,10 +47773,16 @@ export type components = {[key: string]: unknown;} | null;/**- * @description For `initial_video` and `reference_video`: the video to place+ * @description For `initial_video`, `reference_video` and `conditioning_video`: the video to place* @default null*/video: components["schemas"]["VideoRecallVideo"] | null;+ /**+ * Conditioning Role+ * @description For `conditioning_video`: which stream of the video is the condition; the other is generated+ * @default null+ */+ conditioning_role: ("audio" | "video") | null;};/*** VideoRecallVideo@@ -58994,6 +59042,113 @@ export interface operations {};};};+ recall_conditioning_video: {+ parameters: {+ query: {+ /** @description The name of the gallery video */+ video_name: string;+ /** @description Which stream of the video is the condition: `audio` generates a picture for its soundtrack, `video` generates a soundtrack for its picture */+ role: "audio" | "video";+ };+ 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"]["VideoRecallMediaResponse"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };+ recall_conditioning_video_upload: {+ parameters: {+ query: {+ /** @description Which stream of the video is the condition: `audio` generates a picture for its soundtrack, `video` generates a soundtrack for its picture */+ role: "audio" | "video";+ /** @description The board to upload the video to; Uncategorized when omitted */+ board_id?: string | null;+ };+ header?: never;+ path: {+ /** @description The queue id to perform this operation on */+ queue_id: string;+ };+ cookie?: never;+ };+ requestBody: {+ content: {+ "multipart/form-data": {+ /** File */+ file: Blob;+ /**+ * Metadata+ * @description The metadata to associate with the video, must be a stringified JSON dict+ */+ metadata?: string | null;+ };+ };+ };+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["VideoRecallMediaResponse"];+ };+ };+ /** @description The video exceeds the upload size limit */+ 413: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };+ /** @description The file is not a supported video or audio file */+ 415: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ /** @description Too many concurrent video uploads */+ 429: {+ headers: {+ [name: string]: unknown;+ };+ content?: never;+ };+ };+ };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 ff6ce62634..92956d0925 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -4110,6 +4110,11 @@"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": {+ "conditioningClipDisplaced": "A conditioning clip is used on its own, so the panel's other conditioning media was cleared.",+ "conditioningClipNoPicture": "This is an uploaded audio file, so it has no picture to generate a soundtrack for. Use its soundtrack instead.",+ "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.","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.",diff --git a/invokeai/frontend/webv2/src/features/video/core/settings.ts b/invokeai/frontend/webv2/src/features/video/core/settings.tsindex 6ea3a77f10..ad84bd85be 100644--- a/invokeai/frontend/webv2/src/features/video/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/video/core/settings.ts@@ -944,6 +944,17 @@ export const getInitialVideoPatch = ({return sourceVideo && linked === references ? null : { references: linked, sourceVideo, ...displaced };};+/**+ * The panel patch that sets the conditioning clip, or clears it. A clip claims a whole modality, so it displaces+ * every other conditioning slot: the frames, the initial video and the references.+ */+export const getConditioningClipPatch = (+ conditioningClip: VideoConditioningClip | null+): Partial<VideoWidgetValues> => ({+ conditioningClip,+ ...(conditioningClip ? { firstFrameImage: null, lastFrameImage: null, references: [], sourceVideo: null } : {}),+});+/*** 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 adiff --git a/invokeai/frontend/webv2/src/features/video/index.ts b/invokeai/frontend/webv2/src/features/video/index.tsindex 304b8a74eb..15af94b652 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,+ getConditioningClipPatch,getInitialVideoPatch,getReferencesPatch,isImageWithDims,diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsxindex 3e05629d21..373d2bc9c4 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx@@ -22,6 +22,7 @@ import {import {applyReferenceExtendNumFrames,canPlaceReferenceExtendAnchor,+ getConditioningClipPatch,getInitialVideoPatch,getReferencesPatch,isVideoTargetResolution,@@ -274,11 +275,7 @@ export const VideoWidgetView = () => {// and each of those clears it in turn. The role a dropped clip arrives in comes from the gallery// record: an uploaded soundtrack has no picture to condition on.const setConditioningClip = useCallback(- (conditioningClip: VideoConditioningClip | null) =>- patch({- conditioningClip,- ...(conditioningClip ? { firstFrameImage: null, lastFrameImage: null, references: [], sourceVideo: null } : {}),- }),+ (conditioningClip: VideoConditioningClip | null) => patch(getConditioningClipPatch(conditioningClip)),[patch]);// This setter tracks references separately from patch-only field setters. Rebudget the linked tail with framediff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsxindex 06277289f7..8a372a009b 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@@ -38,6 +38,7 @@ const image = (imageName: string): GalleryImage => ({});const createActions = (deleteItems: ImageActions['deleteItems']): ImageActions => ({+ canUseAsConditioningClip: { audio: false, video: false },canUseAsReferenceImage: false,canUseAsReferenceVideo: false,copyImage: vi.fn(() => Promise.resolve()),@@ -66,6 +67,7 @@ const createActions = (deleteItems: ImageActions['deleteItems']): ImageActions =savePromptAsTemplate: vi.fn(),sendToInitialVideo: vi.fn(),useAsReferenceImage: vi.fn(),+ useAsConditioningClip: vi.fn(),useAsReferenceVideo: vi.fn(),});@@ -355,6 +357,58 @@ describe('ImageContextMenu video placement', () => {expect(getMenuItem('Use as Reference Video').getAttribute('aria-disabled')).toBe('true');expect(getMenuItem('Extend in Video').getAttribute('aria-disabled')).not.toBe('true');});++ const openConditioningSubmenu = async (): Promise<void> => {+ await hoverItem(getMenuItem('Use as Conditioning Clip'));+ await settleUntil(+ () =>+ Array.from(document.querySelectorAll('[role="menuitem"]')).some(+ (candidate) => candidate.textContent?.trim() === 'widgets.video.conditioningRoleAudio'+ ),+ 'the conditioning clip submenu to open',+ 5000+ );+ };++ it('hands the video to the conditioning clip action in the chosen role', async () => {+ const video = item('video', 'clip.mp4');+ const actions = { ...createActions(vi.fn()), canUseAsConditioningClip: { audio: true, video: true } };+ await renderVideoMenu(actions, video);+ await openConditioningSubmenu();++ await interact(() => getMenuItem('widgets.video.conditioningRoleAudio').click());++ expect(actions.useAsConditioningClip).toHaveBeenCalledExactlyOnceWith(video, 'audio');+ });++ it('enables each role from its own capability flag', async () => {+ const video = item('video', 'clip.mp4');+ const actions = { ...createActions(vi.fn()), canUseAsConditioningClip: { audio: false, video: true } };+ await renderVideoMenu(actions, video);+ await openConditioningSubmenu();++ expect(getMenuItem('widgets.video.conditioningRoleAudio').getAttribute('aria-disabled')).toBe('true');+ await interact(() => getMenuItem('widgets.video.conditioningRoleVideo').click());+ expect(actions.useAsConditioningClip).toHaveBeenCalledExactlyOnceWith(video, 'video');+ });++ it('disables the roles the Video panel cannot take, and the picture of a wrapped audio upload', async () => {+ const song = { ...item('video', 'song.mp4'), mediaOrigin: 'audio_upload' };+ const actions = { ...createActions(vi.fn()), canUseAsConditioningClip: { audio: true, video: true } };+ await renderVideoMenu(actions, song);+ await openConditioningSubmenu();++ expect(getMenuItem('widgets.video.conditioningRoleAudio').getAttribute('aria-disabled')).not.toBe('true');+ expect(getMenuItem('widgets.video.conditioningRoleVideo').getAttribute('aria-disabled')).toBe('true');++ await interact(() => root?.unmount());+ host?.remove();+ await renderVideoMenu(createActions(vi.fn()), item('video', 'clip.mp4'));+ await openConditioningSubmenu();++ expect(getMenuItem('widgets.video.conditioningRoleAudio').getAttribute('aria-disabled')).toBe('true');+ expect(getMenuItem('widgets.video.conditioningRoleVideo').getAttribute('aria-disabled')).toBe('true');+ });});describe('ImageContextMenu mixed-media action visibility', () => {diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsxindex dcf29f3d74..2196566c0d 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx@@ -1,5 +1,6 @@import type { GalleryBoard, GalleryImage, GalleryItem, GalleryItemKey, GalleryItemRef } from '@features/gallery';import type { GalleryItemContextMenuTarget } from '@features/gallery/react';+import type { VideoConditioningRole } from '@features/video';import type { GalleryCanvasImportDestination } from '@workbench/canvas-operations/api';import { HStack, Icon, Menu, Portal, ScrollArea, Text } from '@chakra-ui/react';@@ -16,6 +17,7 @@ import { useWorkbenchCommands } from '@workbench/WorkbenchContext';import {ClapperboardIcon,AsteriskIcon,+ AudioLinesIcon,ChevronRightIcon,CopyIcon,DownloadIcon,@@ -26,6 +28,7 @@ import {FilmIcon,FolderIcon,ImageIcon,+ ImagePlayIcon,ImagesIcon,LayersIcon,QuoteIcon,@@ -375,6 +378,16 @@ const SingleItemMenuItems = ({actions.useAsReferenceVideo(item);}}, [actions, item]);+ const makeConditioningClipHandler = useCallback(+ (role: VideoConditioningRole) => () => {+ if (item.kind === 'video') {+ actions.useAsConditioningClip(item, role);+ }+ },+ [actions, item]+ );+ const handleUseSoundtrack = useMemo(() => makeConditioningClipHandler('audio'), [makeConditioningClipHandler]);+ const handleUsePicture = useMemo(() => makeConditioningClipHandler('video'), [makeConditioningClipHandler]);return (<>@@ -446,6 +459,23 @@ const SingleItemMenuItems = ({value="use-as-reference-video"onClick={handleUseAsReferenceVideo}/>+ <ContextSubMenu icon={AudioLinesIcon} label="Use as Conditioning Clip">+ <ContextMenuItem+ disabled={!actions.canUseAsConditioningClip.audio}+ icon={AudioLinesIcon}+ label={t('widgets.video.conditioningRoleAudio')}+ value="use-as-conditioning-audio"+ onClick={handleUseSoundtrack}+ />+ {/* A wrapped audio upload's picture is a placeholder, so it has nothing to lend. */}+ <ContextMenuItem+ disabled={!actions.canUseAsConditioningClip.video || item.mediaOrigin === 'audio_upload'}+ icon={ImagePlayIcon}+ label={t('widgets.video.conditioningRoleVideo')}+ value="use-as-conditioning-video"+ onClick={handleUsePicture}+ />+ </ContextSubMenu></>) : 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.tsindex 8657edf200..9cd13ab5ac 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@@ -4,7 +4,12 @@ import type { VideoReferenceItem } from '@features/video';import { createDefaultVideoWidgetValues, createVideoReferenceEntry } from '@features/video';import { describe, expect, it } from 'vitest';-import { appendReferenceVideo, canAppendReferenceVideo, placeInitialVideo } from './executeVideoRecall';+import {+ appendReferenceVideo,+ getVideoPlacementRoom,+ placeConditioningClip,+ placeInitialVideo,+} from './executeVideoRecall';const model = (fields: Record<string, unknown>) =>({@@ -27,6 +32,7 @@ const REF2VA = model({name: 'H3 Ref2VA',variant: 'ref2va',});+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 };const videoReference = (name: string): Extract<VideoReferenceItem, { kind: 'video' }> =>@@ -117,7 +123,7 @@ describe('appendReferenceVideo', () => {};const videoValues = panel(REF2VA, { references: [videoReference('a.mp4'), videoReference('b.mp4'), image, image] });- expect(canAppendReferenceVideo({ models: [REF2VA], videoValues })).toBe(true);+ expect(getVideoPlacementRoom({ models: [REF2VA], videoValues }).referenceVideo).toBe(true);expect(appendReferenceVideo({ models: [REF2VA], video: clip, videoValues }).status).toBe('appended');});@@ -140,7 +146,7 @@ describe('appendReferenceVideo', () => {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);+ expect(getVideoPlacementRoom({ models: [REF2VA], videoValues }).referenceVideo).toBe(false);});it('declines, rather than switching models, when the panel model takes no reference videos', () => {@@ -149,7 +155,86 @@ describe('appendReferenceVideo', () => {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);+ expect(getVideoPlacementRoom({ models: [WAN_I2V, REF2VA], videoValues }).referenceVideo).toBe(false);+ expect(getVideoPlacementRoom({ models: [REF2VA], videoValues: panel(REF2VA) }).referenceVideo).toBe(true);+ });+});++describe('placeConditioningClip', () => {+ it('sets the clip in the requested role and clears every other conditioning slot', () => {+ const placement = placeConditioningClip({+ models: [LTX2],+ role: 'audio',+ video: clip,+ videoValues: panel(LTX2, {+ firstFrameImage: { height: 480, image_name: 'first.png', width: 832 },+ sourceVideo: { ...videoReference('source.mp4').clip },+ }),+ });++ expect(placement).toEqual({+ displaced: true,+ patch: {+ conditioningClip: expect.objectContaining({+ clip: expect.objectContaining({ video_name: 'clip.mp4' }),+ role: 'audio',+ }),+ firstFrameImage: null,+ lastFrameImage: null,+ references: [],+ sourceVideo: null,+ },+ status: 'placed',+ });+ });++ it('replacing a clip on an otherwise empty panel displaces nothing', () => {+ const first = placeConditioningClip({ models: [LTX2], role: 'video', video: clip, videoValues: panel(LTX2) });+ const held = first.status === 'placed' ? first.patch : {};++ expect(+ placeConditioningClip({+ models: [LTX2],+ role: 'audio',+ video: { ...clip, name: 'other.mp4' },+ videoValues: panel(LTX2, held),+ })+ ).toMatchObject({ displaced: false, status: 'placed' });+ });++ it('the requested role overrides the one the gallery record would default to', () => {+ // A plain clip defaults to lending its picture; the caller asked for its soundtrack.+ const placement = placeConditioningClip({ models: [LTX2], role: 'audio', video: clip, videoValues: panel(LTX2) });++ expect(placement.status === 'placed' && placement.patch.conditioningClip?.role).toBe('audio');+ });++ it('refuses the picture of a wrapped audio upload, but takes its soundtrack', () => {+ const song = { ...clip, mediaOrigin: 'audio_upload', name: 'song.mp4' };++ expect(placeConditioningClip({ models: [LTX2], role: 'video', video: song, videoValues: panel(LTX2) })).toEqual({+ status: 'no-picture',+ });+ expect(placeConditioningClip({ models: [LTX2], role: 'audio', video: song, videoValues: panel(LTX2) }).status).toBe(+ 'placed'+ );+ });++ it('declines, rather than switching models, when the panel model takes no conditioning clip', () => {+ const videoValues = panel(REF2VA, { references: [videoReference('dance.mp4')] });++ expect(placeConditioningClip({ models: [REF2VA, LTX2], role: 'audio', video: clip, videoValues })).toEqual({+ status: 'unsupported',+ });+ expect(getVideoPlacementRoom({ models: [REF2VA, LTX2], videoValues })).toEqual({+ conditioningAudio: false,+ conditioningVideo: false,+ referenceVideo: true,+ });+ expect(getVideoPlacementRoom({ models: [LTX2], videoValues: panel(LTX2) })).toEqual({+ conditioningAudio: true,+ conditioningVideo: true,+ referenceVideo: false,+ });});});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.tsindex dfb36c9a78..ccc3c7d53e 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.ts@@ -1,6 +1,12 @@import type { GalleryVideoItem } from '@features/gallery';import type { ModelConfig } from '@features/models';-import type { VideoReferenceItem, VideoWidgetValues } from '@features/video';+import type {+ VideoConditioningRole,+ VideoGenerationMode,+ VideoModelPolicy,+ VideoReferenceItem,+ VideoWidgetValues,+} from '@features/video';import type { AccountScope } from '@platform/state/accountLifecycle';import type { WorkbenchCommands } from '@workbench/workbenchStore';@@ -10,6 +16,7 @@ import {createVideoConditioningClip,createVideoReferenceEntry,createVideoSourceClip,+ getConditioningClipPatch,getDefaultReferenceConditioning,getInitialVideoPatch,getReferencesPatch,@@ -219,10 +226,7 @@ export const applyVideoRecallMetadata = async ({names.sourceVideoName = null;names.sourceVideoTrim = null;}- if (- names.conditioningClip &&- !modes.includes(names.conditioningClip.role === 'audio' ? 'audio-to-video' : 'video-to-audio')- ) {+ if (names.conditioningClip && !modes.includes(CONDITIONING_ROLE_MODE[names.conditioningClip.role])) {names.conditioningClip = null;}}@@ -556,9 +560,10 @@ 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;-+const getReferenceVideoRoom = (+ values: VideoWidgetValues,+ policy = values.model ? getVideoModelPolicy(values.model, values) : null+): 'available' | 'full' | 'unsupported' => {if (!policy?.references || !policy.modes.includes('reference')) {return 'unsupported';}@@ -568,15 +573,6 @@ const getReferenceVideoRoom = (values: VideoWidgetValues): 'available' | 'full': '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,@@ -604,3 +600,82 @@ export const appendReferenceVideo = ({status: 'appended',};};++/** The generation mode a conditioning clip in each role asks of the model. */+const CONDITIONING_ROLE_MODE = {+ audio: 'audio-to-video',+ video: 'video-to-audio',+} as const satisfies Record<VideoConditioningRole, VideoGenerationMode>;++export type ConditioningClipPlacement =+ | {+ /** Whether the clip cleared other conditioning media: frames, the initial video or references. */+ displaced: boolean;+ patch: Partial<VideoWidgetValues>;+ status: 'placed';+ }+ /** `no-picture`: a wrapped audio upload has only a placeholder picture, so it can only lend its soundtrack. */+ | { status: 'no-picture' | 'unsupported' };++const canConditionInRole = (policy: VideoModelPolicy | null, role: VideoConditioningRole): boolean =>+ Boolean(policy?.modes.includes(CONDITIONING_ROLE_MODE[role]));++/**+ * Set the video as the Video panel's conditioning clip in `role`. The panel's own field refuses a clip while other+ * conditioning media is set; this explicit action clears that media instead, as Extend in Video displaces a first+ * frame, and reports it. Unlike the Initial Video, a clip the panel's model cannot use is declined: it would clear+ * the other media for nothing.+ */+export const placeConditioningClip = ({+ models,+ role,+ video,+ videoValues,+}: {+ models: readonly ModelConfig[];+ role: VideoConditioningRole;+ video: PlaceableVideo;+ videoValues: Record<string, unknown>;+}): ConditioningClipPlacement => {+ if (role === 'video' && video.mediaOrigin === 'audio_upload') {+ return { status: 'no-picture' };+ }++ const values = getCurrentVideoValues({ models, videoValues });++ if (!canConditionInRole(values.model ? getVideoModelPolicy(values.model, values) : null, role)) {+ return { status: 'unsupported' };+ }++ return {+ displaced: Boolean(+ values.firstFrameImage || values.lastFrameImage || values.sourceVideo || values.references.length > 0+ ),+ patch: getConditioningClipPatch({ ...createVideoConditioningClip(video), role }),+ status: 'placed',+ };+};++/** Which gallery-video placements the Video panel's model can take right now. */+export interface VideoPlacementRoom {+ conditioningAudio: boolean;+ conditioningVideo: boolean;+ referenceVideo: boolean;+}++export const getVideoPlacementRoom = ({+ models,+ videoValues,+}: {+ models: readonly ModelConfig[];+ videoValues: Record<string, unknown>;+}): VideoPlacementRoom => {+ const values = getCurrentVideoValues({ models, videoValues });+ const policy = values.model ? getVideoModelPolicy(values.model, values) : null;++ return {+ conditioningAudio: canConditionInRole(policy, 'audio'),+ conditioningVideo: canConditionInRole(policy, 'video'),+ referenceVideo: getReferenceVideoRoom(values, policy) === 'available',+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts b/invokeai/frontend/webv2/src/workbench/image-actions/index.tsindex 011ae384d2..66557e07eb 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/index.ts@@ -20,6 +20,7 @@ export {appendReferenceVideo,applyVideoRecallMetadata,getCurrentVideoValues,+ placeConditioningClip,placeInitialVideo,type PlaceableVideo,} from './executeVideoRecall';diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex 2bdd278788..a97c7724d4 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -1,6 +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 { VideoConditioningRole } from '@features/video';import type { WorkbenchSnapshot } from '@workbench/workbenchStore';import {@@ -61,9 +62,11 @@ import { recordCanvasImportError } from './canvasImportError';import { executeImageRecall, executeLoadImageWorkflow, getCurrentGenerateValues } from './executeImageRecall';import {appendReferenceVideo,- canAppendReferenceVideo,executeVideoRecall,+ getVideoPlacementRoom,+ placeConditioningClip,placeInitialVideo,+ type VideoPlacementRoom,} from './executeVideoRecall';import {captureGalleryWidgetKeyValues,@@ -96,6 +99,8 @@ export interface ImageActions extends GalleryItemActions {canUseAsReferenceImage: boolean;/** Whether the video widget's current model takes reference videos and has room for another. */canUseAsReferenceVideo: boolean;+ /** Whether the video widget's current model takes a conditioning clip in each role. */+ canUseAsConditioningClip: Record<VideoConditioningRole, boolean>;copyImage: (image: GalleryImage) => Promise<void>;/** Opens a new project whose canvas holds these images as raster layers. */createCanvasFromImages: (images: readonly GalleryImage[]) => Promise<void>;@@ -126,19 +131,22 @@ export interface ImageActions extends GalleryItemActions {setImagesStarred: (imageNames: string[], starred: boolean) => Promise<void>;useAsReferenceImage: (image: GalleryImage) => void;useAsReferenceVideo: (item: GalleryVideoItem) => void;+ /** Sets a gallery video as the Video panel's conditioning clip in `role`, clearing the media it excludes. */+ useAsConditioningClip: (item: GalleryVideoItem, role: VideoConditioningRole) => 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.+ * Selected as booleans so Video panel edits re-render action consumers only when an answer flips (the workbench+ * selector compares shallowly). The cache skips re-normalizing video values that have not changed since the last+ * store update.*/-const createCanUseAsReferenceVideoSelector = (models: readonly ModelConfig[], projectId: string | undefined) => {+const createVideoPlacementRoomSelector = (models: readonly ModelConfig[], projectId: string | undefined) => {let lastValues: Record<string, unknown> | null = null;- let lastResult = false;+ let lastResult: VideoPlacementRoom = { conditioningAudio: false, conditioningVideo: false, referenceVideo: false };- return (snapshot: WorkbenchSnapshot): boolean => {+ return (snapshot: WorkbenchSnapshot): VideoPlacementRoom => {const project = projectId? snapshot.projects.find((candidate) => candidate.id === projectId): snapshot.activeProject;@@ -146,7 +154,7 @@ const createCanUseAsReferenceVideoSelector = (models: readonly ModelConfig[], prif (videoValues !== lastValues) {lastValues = videoValues;- lastResult = canAppendReferenceVideo({ models, videoValues });+ lastResult = getVideoPlacementRoom({ models, videoValues });}return lastResult;@@ -212,11 +220,17 @@ export const useImageActions = ({}, [generateValues, supportedModels]));- const selectCanUseAsReferenceVideo = useMemo(- () => createCanUseAsReferenceVideoSelector(models, projectId),+ const selectVideoPlacementRoom = useMemo(+ () => createVideoPlacementRoomSelector(models, projectId),[models, projectId]);- const canUseAsReferenceVideo = useWorkbenchSelector(selectCanUseAsReferenceVideo, Object.is);+ const videoPlacementRoom = useWorkbenchSelector(selectVideoPlacementRoom);+ const canUseAsReferenceVideo = videoPlacementRoom.referenceVideo;+ const { conditioningAudio, conditioningVideo } = videoPlacementRoom;+ const canUseAsConditioningClip = useMemo(+ () => ({ audio: conditioningAudio, video: conditioningVideo }),+ [conditioningAudio, conditioningVideo]+ );useMountEffect(() => {void ensureModelsLoaded();@@ -1046,6 +1060,7 @@ export const useImageActions = ({imageNames.map((name) => ({ kind: 'image', name })),starred),+ canUseAsConditioningClip,canUseAsReferenceImage,canUseAsReferenceVideo,sendToInitialVideo: (item) => {@@ -1091,6 +1106,33 @@ export const useImageActions = ({commands.widgets.patchValues('video', placement.patch, projectId);openWorkbenchWidget('video', { preferredRegions: ['left'] });},+ useAsConditioningClip: (item, role) => {+ const placement = placeConditioningClip({ models, role, video: item, videoValues: getLatestVideoValues() });++ // The menu offers this only when the model takes the clip; the panel's model can still change first.+ if (placement.status !== 'placed') {+ notifications.add({+ kind: 'info',+ message: t(+ placement.status === 'no-picture'+ ? 'widgets.video.placement.conditioningClipNoPicture'+ : 'widgets.video.placement.conditioningClipUnsupported'+ ),+ title: t('widgets.video.placement.conditioningClipNotSet'),+ });+ return;+ }++ commands.widgets.patchValues('video', placement.patch, projectId);+ openWorkbenchWidget('video', { preferredRegions: ['left'] });+ if (placement.displaced) {+ notifications.add({+ kind: 'info',+ message: t('widgets.video.placement.conditioningClipDisplaced'),+ title: t('widgets.video.placement.conditioningClipSet'),+ });+ }+ },useAsReferenceImage: (image) => {const result = appendReferenceImage({ generateValues: getLatestGenerateValues(), image, models });@@ -1104,6 +1146,7 @@ export const useImageActions = ({};}, [boards,+ canUseAsConditioningClip,canUseAsReferenceImage,canUseAsReferenceVideo,confirmImageDeletion,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.tsindex cd1c9b8fa6..6d832590b6 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts@@ -68,6 +68,7 @@ const REF2VA = model({name: 'H3 Ref2VA',variant: 'ref2va',});+const LTX2 = model({ base: 'ltx-2', format: 'checkpoint', key: 'ltx2', name: 'LTX-2.5 dev', variant: 'ltx2_dev' });const t = ((key: string) => key) as unknown as TFunction;@@ -86,7 +87,10 @@ const parametersEvent = (parameters: Record<string, unknown>, extra: Record<stri...extra,});-const placementEvent = (action: 'initial_video' | 'reference_video', video: Record<string, unknown> = {}) => ({+const placementEvent = (+ action: 'conditioning_video' | 'initial_video' | 'reference_video',+ video: Record<string, unknown> = {}+) => ({action,queue_id: 'default',user_id: 'owner',@@ -155,7 +159,7 @@ describe('createVideoRecallRuntime', () => {modelsApi.getModelsSnapshot.mockReset();modelsApi.getModelsSnapshot.mockReturnValue({error: null,- models: [WAN_I2V, WAN_T2V, REF2VA],+ models: [WAN_I2V, WAN_T2V, REF2VA, LTX2],status: 'loaded',} as ModelsSnapshot);galleryApi.galleryItems.resolve.mockReset();@@ -297,6 +301,11 @@ 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' }],+ ['a conditioning video without its role', placementEvent('conditioning_video')],+ [+ 'a conditioning video with an unknown role',+ { ...placementEvent('conditioning_video'), conditioning_role: 'both' },+ ],])('ignores %s', async (_label, payload) => {const { videoShown, runtime, socket, store, videoValues } = setup();const before = videoValues();@@ -477,6 +486,80 @@ describe('createVideoRecallRuntime', () => {runtime.dispose();});+ it('sets a conditioning clip in the sent role, clearing the frames it displaces, and says so', async () => {+ const { lastNotice, projectId, runtime, socket, store, videoShown, videoValues } = setup(LTX2);+ store.commands.widgets.patchValues('video', { firstFrameImage: heldFrame }, projectId);++ socket.emit({ ...placementEvent('conditioning_video'), conditioning_role: 'audio' });+ await flush();++ expect(videoValues()).toMatchObject({+ conditioningClip: { clip: { video_name: 'clip.mp4' }, fpsKnown: true, role: 'audio' },+ firstFrameImage: null,+ });+ expect(lastNotice()).toEqual(+ expect.objectContaining({+ kind: 'info',+ message: 'widgets.video.placement.conditioningClipDisplaced',+ title: 'widgets.video.placement.conditioningClipSet',+ })+ );+ expect(videoShown()).toBe(true);++ runtime.dispose();+ });++ it('sets a conditioning clip on an otherwise empty panel with a plain success notice', async () => {+ const { lastNotice, runtime, socket, videoValues } = setup(LTX2);++ socket.emit({ ...placementEvent('conditioning_video'), conditioning_role: 'video' });+ await flush();++ expect(videoValues()).toMatchObject({ conditioningClip: { role: 'video' } });+ expect(lastNotice()).toMatchObject({ kind: 'success', title: 'widgets.video.placement.conditioningClipSet' });+ expect(lastNotice()?.message).toBeUndefined();++ runtime.dispose();+ });++ it('declines the picture of a wrapped audio upload, leaving the panel alone', async () => {+ const { lastNotice, runtime, socket, videoValues } = setup(LTX2);+ const before = videoValues();++ socket.emit({+ ...placementEvent('conditioning_video', { media_origin: 'audio_upload' }),+ conditioning_role: 'video',+ });+ await flush();++ expect(videoValues()).toBe(before);+ expect(lastNotice()).toEqual(+ expect.objectContaining({ kind: 'info', message: 'widgets.video.placement.conditioningClipNoPicture' })+ );++ runtime.dispose();+ });++ it('declines a conditioning clip the panel model cannot take, leaving its media alone', async () => {+ const { lastNotice, runtime, socket, videoShown, videoValues } = setup(WAN_I2V);+ const before = videoValues();++ socket.emit({ ...placementEvent('conditioning_video'), conditioning_role: 'video' });+ await flush();++ expect(videoValues()).toBe(before);+ expect(lastNotice()).toEqual(+ expect.objectContaining({+ kind: 'info',+ message: 'widgets.video.placement.conditioningClipUnsupported',+ title: 'widgets.video.placement.conditioningClipNotSet',+ })+ );+ expect(videoShown()).toBe(false);++ runtime.dispose();+ });+it('places into the project it arrived for', async () => {const { projectId, runtime, socket, store, videoValues } = setup();let releaseModels: () => void = () => {};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.tsindex 2209ec8f40..1514a3b33e 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.ts@@ -1,4 +1,5 @@import type { ModelConfig } from '@features/models';+import type { VideoConditioningRole } from '@features/video';import type { AccountScope } from '@platform/state/accountLifecycle';import type { SocketHub } from '@platform/transport/socketHub';import type { WorkbenchCommands, WorkbenchQueries } from '@workbench/workbenchStore';@@ -12,7 +13,13 @@ import type { PendingRecallEvent, RecallRevealContext, RecallRuntime } from './r// 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, getCurrentVideoValues, placeInitialVideo } from './index';+import {+ appendReferenceVideo,+ applyVideoRecallMetadata,+ getCurrentVideoValues,+ placeConditioningClip,+ placeInitialVideo,+} from './index';import { bringRecallWidgetToFront, createRecallEventRuntime } from './recallEventRuntime';/** The `video` of a `video_recall_requested` event: a gallery video, as the backend describes it. */@@ -35,6 +42,7 @@ export type VideoRecallRequestedEvent = { user_id: string } & (strict: boolean;}| { action: 'initial_video' | 'reference_video'; video: VideoRecallEventVideo }+ | { action: 'conditioning_video'; conditioning_role: VideoConditioningRole; video: VideoRecallEventVideo });const isRecord = (value: unknown): value is Record<string, unknown> =>@@ -66,6 +74,12 @@ export const isVideoRecallRequestedEvent = (payload: unknown): payload is VideoR);}+ if (payload.action === 'conditioning_video') {+ return (+ (payload.conditioning_role === 'audio' || payload.conditioning_role === 'video') && isEventVideo(payload.video)+ );+ }+return (payload.action === 'initial_video' || payload.action === 'reference_video') && isEventVideo(payload.video);};@@ -80,7 +94,7 @@ const toPlaceableVideo = (video: VideoRecallEventVideo): PlaceableVideo => ({/*** 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+ * 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* placement it cannot take is declined with a notice. The Video widget is revealed when the project is still the* one on screen.*/@@ -163,6 +177,37 @@ export const createVideoRecallRuntime = ({);applied = true;}+ } else if (event.action === 'conditioning_video') {+ const placement = placeConditioningClip({+ models,+ role: event.conditioning_role,+ video: toPlaceableVideo(event.video),+ videoValues,+ });++ if (placement.status === 'placed') {+ commands.widgets.patchValues('video', placement.patch, projectId);+ commands.notifications.add(+ placement.displaced+ ? {+ kind: 'info',+ message: t('widgets.video.placement.conditioningClipDisplaced'),+ title: t('widgets.video.placement.conditioningClipSet'),+ }+ : { kind: 'success', title: t('widgets.video.placement.conditioningClipSet') }+ );+ applied = true;+ } else {+ commands.notifications.add({+ kind: 'info',+ message: t(+ placement.status === 'no-picture'+ ? 'widgets.video.placement.conditioningClipNoPicture'+ : 'widgets.video.placement.conditioningClipUnsupported'+ ),+ title: t('widgets.video.placement.conditioningClipNotSet'),+ });+ }} else {const placement = appendReferenceVideo({ models, video: toPlaceableVideo(event.video), videoValues });diff --git a/tests/app/api/test_video_upload_limits.py b/tests/app/api/test_video_upload_limits.pyindex 6d7a6118db..17d5b0d90b 100644--- a/tests/app/api/test_video_upload_limits.py+++ b/tests/app/api/test_video_upload_limits.py@@ -172,9 +172,11 @@ def test_other_routes_unaffected():[("/api/v1/recall/video/default/initial-video/upload", True),("/api/v1/recall/video/default/reference-video/upload", True),+ ("/api/v1/recall/video/default/conditioning-video/upload", True),# The name-only siblings carry no body, so they must not compete for upload slots.("/api/v1/recall/video/default/initial-video", False),("/api/v1/recall/video/default/reference-video", False),+ ("/api/v1/recall/video/default/conditioning-video", False),],)def test_video_recall_uploads_share_the_video_upload_bound(path: str, bounded: bool):diff --git a/tests/app/routers/test_video_recall.py b/tests/app/routers/test_video_recall.pyindex 4526e1e9b2..cbc017b251 100644--- a/tests/app/routers/test_video_recall.py+++ b/tests/app/routers/test_video_recall.py@@ -648,6 +648,50 @@ class TestGalleryVideoPlacement:event = _only_recall_event(invoker)assert event.video is not None and event.video.media_origin == "audio_upload"+ @pytest.mark.parametrize("role", ["audio", "video"])+ def test_a_conditioning_video_carries_its_role(self, invoker: Invoker, client: TestClient, role: str) -> None:+ _save_video(invoker, "clip.mp4")++ response = client.post(+ "/api/v1/recall/video/default/conditioning-video", params={"video_name": "clip.mp4", "role": role}+ )++ assert response.status_code == 200+ assert response.json()["action"] == "conditioning_video"+ event = _only_recall_event(invoker)+ assert event.action == "conditioning_video"+ assert event.conditioning_role == role+ assert event.video is not None and event.video.video_name == "clip.mp4"++ @pytest.mark.parametrize("params", [{}, {"role": "both"}], ids=["missing", "unknown"])+ def test_a_conditioning_video_needs_a_valid_role(+ self, invoker: Invoker, client: TestClient, params: dict[str, str]+ ) -> None:+ _save_video(invoker, "clip.mp4")++ response = client.post(+ "/api/v1/recall/video/default/conditioning-video", params={"video_name": "clip.mp4", **params}+ )++ assert response.status_code == 422+ assert _recall_events(invoker) == []++ @pytest.mark.parametrize(+ ("action", "role"), [("conditioning_video", None), ("reference_video", "audio")], ids=["missing", "stray"]+ )+ def test_the_event_carries_a_role_with_and_only_with_a_conditioning_video(+ self, action: str, role: str | None+ ) -> None:+ with pytest.raises(ValueError):+ VideoRecallRequestedEvent.build("default", "owner", action, conditioning_role=role) # type: ignore[arg-type]++ def test_other_placements_carry_no_role(self, invoker: Invoker, client: TestClient) -> None:+ _save_video(invoker, "clip.mp4")++ client.post("/api/v1/recall/video/default/reference-video", params={"video_name": "clip.mp4", "role": "audio"})++ assert _only_recall_event(invoker).conditioning_role is None+def test_an_unknown_video_is_a_404(self, invoker: Invoker, client: TestClient) -> None:response = client.post("/api/v1/recall/video/default/initial-video", params={"video_name": "nope.mp4"})@@ -715,6 +759,32 @@ class TestUploadedVideoPlacement:assert upload_ready.call_args.kwargs["board_id"] is Noneassert _only_recall_event(invoker).action == "initial_video"+ def test_an_uploaded_conditioning_video_carries_its_role(+ self, invoker: Invoker, client: TestClient, upload_ready: MagicMock+ ) -> None:+ response = client.post(+ "/api/v1/recall/video/default/conditioning-video/upload",+ params={"role": "audio"},+ files={"file": ("song.mp4", MP4_BYTES, "video/mp4")},+ )++ assert response.status_code == 200+ recall = _only_recall_event(invoker)+ assert recall.action == "conditioning_video"+ assert recall.conditioning_role == "audio"++ def test_an_uploaded_conditioning_video_without_a_role_is_refused_before_ingest(+ self, invoker: Invoker, client: TestClient, upload_ready: MagicMock+ ) -> None:+ response = client.post(+ "/api/v1/recall/video/default/conditioning-video/upload",+ files={"file": ("song.mp4", MP4_BYTES, "video/mp4")},+ )++ assert response.status_code == 422+ upload_ready.assert_not_called()+ assert _recall_events(invoker) == []+def test_a_rejected_upload_places_nothing(self, invoker: Invoker, client: TestClient, upload_ready: MagicMock) -> None: