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(ltx2): enhance LTX-2.5 prompts through Expand Prompt
Lincoln Steinc9aa59414cdb
diff --git a/docs/src/content/docs/concepts/video-generation.mdx b/docs/src/content/docs/concepts/video-generation.mdxindex f3a74f9dbd..f71818ad09 100644--- a/docs/src/content/docs/concepts/video-generation.mdx+++ b/docs/src/content/docs/concepts/video-generation.mdx@@ -63,7 +63,7 @@ If you pick a model that can't run the current combination, the Invoke button te### Prompt-The prompt toolbar carries the same helpers as the image Generate panel — templates, prompt expansion, image-to-prompt, and history. The **negative prompt** behaves per family:+The prompt toolbar carries the same helpers as the image Generate panel — templates, prompt expansion, image-to-prompt, and history. On LTX-2, **Expand Prompt** starts from the enhancer LTX-2.5 was released with and, when a first frame is set, describes the video from that frame — see [prompt enhancement for LTX-2.5](/features/prompt-tools/#prompt-enhancement-for-ltx-25). The **negative prompt** behaves per family:* **Wan** — used only when CFG is greater than 1 (the field says so). With the Lightning fast path on (CFG 1), it is ignored by the graph.* **MiniMax H3** — hidden entirely. H3 is guidance-distilled and has no CFG, so a negative prompt has nothing to act on.diff --git a/docs/src/content/docs/features/prompt-tools.md b/docs/src/content/docs/features/prompt-tools.mdindex c0b4fc00d8..4cdc31f428 100644--- a/docs/src/content/docs/features/prompt-tools.md+++ b/docs/src/content/docs/features/prompt-tools.md@@ -2,7 +2,7 @@title: LLM Prompt Toolssidebar:order: 3-lastUpdated: 2026-08-09+lastUpdated: 2026-09-26---InvokeAI includes two built-in tools that use local language models to help you write better prompts. Both tools appear as small buttons in the top-right corner of the positive prompt area and are only visible when you have a compatible model installed.@@ -19,7 +19,7 @@ Takes your short prompt and expands it into a detailed, vivid description suitab4. Click **Expand**5. Your prompt is replaced with the expanded version-**Compatible models:** Any HuggingFace model with a `ForCausalLM` architecture. Recommended options:+**Compatible models:** Any HuggingFace model with a `ForCausalLM` architecture, plus Gemma-4 checkpoints (`Gemma4ForConditionalGeneration`), which can also read an image. Recommended options:| Model | Size | HuggingFace ID ||-------|------|----------------|@@ -29,6 +29,17 @@ Takes your short prompt and expands it into a detailed, vivid description suitabInstall by pasting the HuggingFace ID into the Model Manager. The model is automatically detected as a **Text LLM** type.+### Prompt enhancement for LTX-2.5++LTX-2.5 was trained on long, single-paragraph audio-visual captions, and its own text encoder is not trained to write them. Lightricks pairs the model with a small dedicated enhancer, and InvokeAI offers the same pairing through Expand Prompt:++* Install **LTX-2.5 Prompt Enhancer (Gemma-4 E2B)** from the starter models (`google/gemma-4-E2B-it`, ~10 GB). It is optional and not part of the LTX-2.5 bundle.+* Two system prompts ship with InvokeAI: **LTX-2.5 Text-to-Video** and **LTX-2.5 Image-to-Video**, the release's own texts.++In the Video panel with an LTX-2 model selected, Expand Prompt preselects the enhancer — when it was installed from the starter models or as `google/gemma-4-E2B-it`; otherwise the popover points you to the starter models — and the matching system prompt. With a **first frame** set it shows the frame with **Describe from the first frame** ticked and uses the Image-to-Video prompt, so the caption begins from what the image shows. Untick it, or pick a model that cannot read images (the popover says so), and it uses the Text-to-Video prompt instead. Any model or system prompt you choose in the popover overrides the suggestion.++The rewritten prompt replaces yours in the prompt box, where you can edit it before pressing Invoke; the prompt that is generated and recorded is exactly what the box holds.+### Reasoning ("thinking") modelsReasoning models such as Qwen3 or the DeepSeek-R1 distills normally write out a chain of thought before their answer. Prompt expansion returns the generated text as-is, so that reasoning would end up in your prompt. InvokeAI therefore renders the chat template with thinking disabled, which makes these models answer directly. Models whose chat template does not support the switch are unaffected, and models that always reason (with no way to turn it off) are not suitable for prompt expansion.@@ -60,6 +71,6 @@ The workflow editor provides **Text LLM** and **Text LLM (with System Prompt PreUsing the same seed reproduces sampling when the model, prompt, settings, hardware, and software versions remain the same. Results may differ across devices or software versions. The prompt area's **Expand Prompt** tool chooses a fresh seed for each request so repeated expansions can vary.-API callers can pass an optional seed to **Expand Prompt**; the response returns the effective seed for replay.+API callers can pass an optional seed to **Expand Prompt**; the response returns the effective seed for replay. They can also pass an `image_name` to condition the rewrite on a stored image, which requires a Text LLM whose `supports_images` is true.When a saved `1.0.0` Text LLM workflow is migrated, its new seed defaults to `0`, so repeated runs become deterministic. Connect a random integer node to **seed** if the workflow should vary between runs.diff --git a/invokeai/app/api/routers/utilities.py b/invokeai/app/api/routers/utilities.pyindex bf6cb1a85a..f47a22702e 100644--- a/invokeai/app/api/routers/utilities.py+++ b/invokeai/app/api/routers/utilities.py@@ -21,6 +21,7 @@ from invokeai.app.api.routers._access import assert_image_read_accessfrom invokeai.app.api.routers.image_move_maintenance import assert_image_move_maintenance_inactivefrom invokeai.app.services.events.events_base import EventServiceBasefrom invokeai.app.services.image_files.image_files_common import ImageFileNotFoundException+from invokeai.app.services.image_records.image_records_common import ImageRecordNotFoundExceptionfrom invokeai.app.services.model_records.model_records_base import UnknownModelExceptionfrom invokeai.app.services.system_prompt_records.system_prompt_records_common import (EXPAND_PROMPT_MAX_TOKENS_DEFAULT,@@ -376,6 +377,13 @@ class ExpandPromptRequest(BaseModel):task_id: str | None = Field(default=None, description="Client-supplied task ID used to correlate socket progress events to this request")+ image_name: str | None = Field(+ default=None,+ description=(+ "An image to condition the rewrite on, such as a video's first frame. Requires a model whose "+ "`supports_images` is true."+ ),+ )class ExpandPromptResponse(BaseModel):@@ -425,6 +433,7 @@ def _run_expand_prompt(seed: int | None,task_id: str | None,user_id: str,+ image_name: str | None = None,) -> tuple[str, int]:"""Run text LLM inference synchronously (called from thread)."""model_manager = ApiDependencies.invoker.services.model_manager@@ -433,18 +442,35 @@ def _run_expand_prompt(if model_config.type != ModelType.TextLLM:raise ValueError(f"Model '{model_key}' is not a TextLLM model (got {model_config.type})")+ # Only the TextLLM config carries the flag (the record type is a union); older records validate to False.+ if image_name is not None and not getattr(model_config, "supports_images", False):+ raise ValueError(f"Model '{model_config.name}' cannot read images; choose a vision-capable text LLM")++ # Read before the model load so a missing image fails fast.+ image = (+ ApiDependencies.invoker.services.images.get_pil_image(image_name).convert("RGB")+ if image_name is not None+ else None+ )if task_id is not None:events.emit_llm_task_progress(task_id=task_id, user_id=user_id, phase="loading_model", message="Loading model")+ # Loaded before the model so the disk reads do not hold it on the device. A processor carries its own+ # tokenizer; loading another would parse the (for Gemma, ~30 MB) vocabulary twice.+ model_abs_path = _resolve_model_path(model_config.path)+ processor = AutoProcessor.from_pretrained(model_abs_path, local_files_only=True) if image is not None else None+ tokenizer = (+ processor.tokenizer+ if processor is not None+ else AutoTokenizer.from_pretrained(model_abs_path, local_files_only=True)+ )+with _model_load_lock:loaded_model = model_manager.load.load_model(model_config, user_id=user_id)with torch.no_grad(), loaded_model.model_on_device() as (_, model):- model_abs_path = _resolve_model_path(model_config.path)- tokenizer = AutoTokenizer.from_pretrained(model_abs_path, local_files_only=True)-- pipeline = TextLLMPipeline(model, tokenizer)+ pipeline = TextLLMPipeline(model, tokenizer, processor)model_device = next(model.parameters()).deviceprogress_callback = _make_progress_callback(events, task_id, user_id)@@ -458,6 +484,7 @@ def _run_expand_prompt(device=model_device,dtype=TorchDevice.choose_torch_dtype(),progress_callback=progress_callback,+ image=image,)return output, effective_seed@@ -472,6 +499,11 @@ def _run_expand_prompt()async def expand_prompt(current_user: CurrentUserOrDefault, body: ExpandPromptRequest) -> ExpandPromptResponse:"""Expand a brief prompt into a detailed image generation prompt using a text LLM."""+ if body.image_name is not None:+ # Same policy as image-to-prompt: non-owners cannot probe stored images through this endpoint.+ await asyncio.to_thread(assert_image_move_maintenance_inactive)+ await asyncio.to_thread(assert_image_read_access, body.image_name, current_user)+events = ApiDependencies.invoker.services.eventstry:expanded, seed = await asyncio.to_thread(@@ -483,6 +515,7 @@ async def expand_prompt(current_user: CurrentUserOrDefault, body: ExpandPromptRebody.seed,body.task_id,current_user.user_id,+ body.image_name,)if body.task_id is not None:events.emit_llm_task_complete(task_id=body.task_id, user_id=current_user.user_id)@@ -491,6 +524,11 @@ async def expand_prompt(current_user: CurrentUserOrDefault, body: ExpandPromptReif body.task_id is not None:events.emit_llm_task_error(task_id=body.task_id, user_id=current_user.user_id, error="Model not found")raise HTTPException(status_code=404, detail=f"Model '{body.model_key}' not found")+ except (ImageFileNotFoundException, ImageRecordNotFoundException):+ # The record check matters for admins (and single-user mode), whose access check never reads the record.+ if body.task_id is not None:+ events.emit_llm_task_error(task_id=body.task_id, user_id=current_user.user_id, error="Image not found")+ raise HTTPException(status_code=404, detail=f"Image '{body.image_name}' not found")except ValueError as e:if body.task_id is not None:events.emit_llm_task_error(task_id=body.task_id, user_id=current_user.user_id, error=str(e))@@ -601,7 +639,7 @@ async def image_to_prompt(current_user: CurrentUserOrDefault, body: ImageToPrompif body.task_id is not None:events.emit_llm_task_error(task_id=body.task_id, user_id=current_user.user_id, error="Model not found")raise HTTPException(status_code=404, detail=f"Model '{body.model_key}' not found")- except ImageFileNotFoundException:+ except (ImageFileNotFoundException, ImageRecordNotFoundException):if body.task_id is not None:events.emit_llm_task_error(task_id=body.task_id, user_id=current_user.user_id, error="Image not found")raise HTTPException(status_code=404, detail=f"Image '{body.image_name}' not found")diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_26_add_ltx2_system_prompts.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_26_add_ltx2_system_prompts.pynew file mode 100644index 0000000000..5bb9210acc--- /dev/null+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_09_26_add_ltx2_system_prompts.py@@ -0,0 +1,111 @@+"""Seed the LTX-2.5 Text-to-Video and Image-to-Video system prompts for the Expand Prompt button.++LTX-2.5's own text encoder is not trained to enhance prompts; Lightricks pairs the model with+`google/gemma-4-E2B-it` and these two "capstyle_plus" system prompts, which rewrite a short request+into the single-paragraph audio-visual caption style the model was trained on. The texts are+verbatim from diffusers 0.40.0 (`pipelines/ltx2/utils.py`, `LTX2_5_T2V_DEFAULT_SYSTEM_PROMPT` and+`LTX2_5_I2V_DEFAULT_SYSTEM_PROMPT`); they are copied rather than imported so that a later diffusers+release cannot change what this migration seeds.++The Image-to-Video prompt describes the video from its first frame, so Expand Prompt sends that+frame along when the model can read images.++Same fixed-UUID / ``INSERT OR IGNORE`` shape as the MiniMax H3 Ref2VA seed: a prompt the user has+since edited or deleted stays edited or deleted.+"""++import sqlite3++from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration++LTX2_5_T2V_PROMPT_ID = "0f8f5b2e-1c9e-4f2a-9a4e-1f1f1f1f0009"+LTX2_5_I2V_PROMPT_ID = "0f8f5b2e-1c9e-4f2a-9a4e-1f1f1f1f0010"++LTX2_5_MAX_TOKENS = 600+"""Upstream's own cap (`GEMMA4_PROMPT_ENHANCEMENT_CONFIG.max_new_tokens`). The prompts ask for+150-220 words; measured outputs with Gemma-4-E2B ran 118-257 tokens."""++LTX2_5_T2V_PROMPT_CONTENT = """You are given a user's short text-to-video request. Write a single, highly detailed audio-visual caption describing the video that best fulfills that request, in the EXACT style of the training captions used for this video model. The generated video is scored against the user's ORIGINAL request, so preserve every element the user stated; expand faithfully into the full caption style without contradicting or dropping anything they asked for.++Match this captioning style precisely:++1. Begin immediately with the action or visual detail. Do NOT use "The scene opens…", "We see…", "There is…".++2. Objective, observable description only. Do not infer emotions or intentions — describe what is visible and audible (e.g. not "he looks sad" but "his eyebrows angle downward and his lips are pressed together").++3. Full visual detail: environment (materials, textures, lighting, colors), character appearance (clothing, posture, facial details), and the spatial positioning of all elements. When a human appears, identify them specifically (gendered terms when clearly implied; differentiate multiple people consistently) and describe visible physical attributes — apparent gender presentation, skin tone, estimated age group, hair color/length/style, build, clothing and accessories. Do not infer ethnicity, nationality, religion, or culture.++4. Precise motion and cinematic description. For every shot you MUST include, woven naturally into the prose (never as tags or labels):+ - Shot type (exactly one: extreme wide shot / wide shot / medium shot / medium close-up / close-up / extreme close-up)+ - Camera motion (always stated; if none, explicitly say the camera remains static). Camera movement is expected and good — match the user if they specified it, otherwise choose the treatment that best presents the requested scene.+ - Camera viewpoint relative to subject (front-facing / back-facing / side view / over-the-shoulder / top-down / low-angle / high-angle).+ Express these as flowing prose: "a medium shot frames…, captured from a front-facing angle as the camera slowly pans…". Never as "medium shot, static camera —".++5. Complete soundscape, integrated naturally: any dialogue (quote it exactly, in the original language), tone of voice, background music (type, mood, volume changes), and environmental sounds (footsteps, wind, traffic, animals). If the request implies sound, describe it plausibly.++6. Strict chronological, real-time flow using transitions like "Initially…", "A moment later…", "Simultaneously…". Keep every stated action in motion.++7. One single continuous paragraph. No bullet points, no section headers, no labels like "Audio:" or "Visual:". Exhaustive and lossless — include background elements, subtle movements, lighting, secondary sounds — detailed enough to reconstruct the scene. Aim for a rich, complete paragraph (roughly 150–220 words).++If the user wrote in another language, produce the English caption of the same content. Output ONLY the caption text — no JSON, no preamble.++AESTHETIC QUALITY (in addition to the above, without breaking the objective caption style): render the described scene with strong visual production value — cinematic, film-grade color and contrast, beautiful natural lighting, crisp fine detail and texture, pleasing composition and depth. Weave these quality descriptors naturally into the same observable prose (e.g. "warm cinematic lighting", "richly saturated film-grade color", "crisp high-resolution detail") — describe how the exact requested scene LOOKS at its most visually striking, never adding new objects or actions. Keep everything else (framing triple, soundscape, chronological single paragraph, faithfulness) exactly as specified.+"""++LTX2_5_I2V_PROMPT_CONTENT = """You are given a REFERENCE IMAGE (the exact first frame of the video) and a user's short image-to-video request. Write a single, highly detailed audio-visual caption describing the video that BEGINS from this exact reference image and best fulfills that request, in the EXACT style of the training captions used for this video model. The generated video is scored against the user's ORIGINAL request, so preserve every element the user stated; expand faithfully into the full caption style without contradicting or dropping anything they asked for.++FIRST-FRAME / IMAGE GROUNDING (do this first): the opening of your caption must match the reference image exactly — same subject(s), identity, appearance, clothing, setting, lighting, and composition as shown. The video starts on this frame; describe it faithfully, then narrate chronologically as the user's requested action unfolds from it. Never contradict, replace, or invent things not consistent with the image. Single continuous take — no hard cuts.++Match this captioning style precisely:++1. Begin immediately with the action or visual detail. Do NOT use "The scene opens…", "We see…", "There is…".++2. Objective, observable description only. Do not infer emotions or intentions — describe what is visible and audible (e.g. not "he looks sad" but "his eyebrows angle downward and his lips are pressed together").++3. Full visual detail: environment (materials, textures, lighting, colors), character appearance (clothing, posture, facial details), and the spatial positioning of all elements — grounded in and consistent with the reference image. When a human appears, identify them specifically (gendered terms when clearly implied; differentiate multiple people consistently) and describe visible physical attributes — apparent gender presentation, skin tone, estimated age group, hair color/length/style, build, clothing and accessories. Do not infer ethnicity, nationality, religion, or culture.++4. Precise motion and cinematic description. For every shot you MUST include, woven naturally into the prose (never as tags or labels):+ - Shot type (exactly one: extreme wide shot / wide shot / medium shot / medium close-up / close-up / extreme close-up) — consistent with how the reference image is framed at the start.+ - Camera motion (always stated; if none, explicitly say the camera remains static). Camera movement is expected and good — match the user if they specified it, otherwise choose the treatment that best presents the requested scene starting from this frame.+ - Camera viewpoint relative to subject (front-facing / back-facing / side view / over-the-shoulder / top-down / low-angle / high-angle) — matching the reference image's viewpoint at the opening.+ Express these as flowing prose: "a medium shot frames…, captured from a front-facing angle as the camera slowly pans…". Never as "medium shot, static camera —".++5. Complete soundscape, integrated naturally: any dialogue (quote it exactly, in the original language), tone of voice, background music (type, mood, volume changes), and environmental sounds (footsteps, wind, traffic, animals). If the request implies sound, describe it plausibly.++6. Strict chronological, real-time flow using transitions like "Initially…", "A moment later…", "Simultaneously…". Keep the user's requested motion/action central and in motion throughout.++7. One single continuous paragraph. No bullet points, no section headers, no labels like "Audio:" or "Visual:". Exhaustive and lossless — include background elements, subtle movements, lighting, secondary sounds — detailed enough to reconstruct the scene. Aim for a rich, complete paragraph (roughly 150–220 words).++If the user wrote in another language, produce the English caption of the same content. Output ONLY the caption text — no JSON, no preamble.++AESTHETIC QUALITY (in addition to the above, without breaking the objective caption style or contradicting the reference image): render the described scene with strong visual production value — cinematic, film-grade color and contrast, beautiful natural lighting, crisp fine detail and texture, pleasing composition and depth. Weave these quality descriptors naturally into the same observable prose (e.g. "warm cinematic lighting", "richly saturated film-grade color", "crisp high-resolution detail") — describe how the exact requested scene, starting from this frame, LOOKS at its most visually striking, never adding new objects or actions and never contradicting the first frame. Keep everything else (first-frame grounding, framing triple, soundscape, chronological single paragraph, faithfulness) exactly as specified.+"""+++LTX2_5_SYSTEM_PROMPTS = (+ (LTX2_5_T2V_PROMPT_ID, "LTX-2.5 Text-to-Video", LTX2_5_T2V_PROMPT_CONTENT),+ (LTX2_5_I2V_PROMPT_ID, "LTX-2.5 Image-to-Video", LTX2_5_I2V_PROMPT_CONTENT),+)+++class AddLtx2SystemPromptsCallback:+ def __call__(self, cursor: sqlite3.Cursor) -> None:+ cursor.executemany(+ """--sql+ INSERT OR IGNORE INTO system_prompts (id, name, content, user_id, is_public, max_tokens)+ VALUES (?, ?, ?, 'system', TRUE, ?);+ """,+ [(id, name, content, LTX2_5_MAX_TOKENS) for id, name, content in LTX2_5_SYSTEM_PROMPTS],+ )+++def build_migration() -> Migration:+ """Seed the LTX-2.5 prompt-enhancement system prompts.++ Depends on the migration that adds ``system_prompts.max_tokens``, which the rows set.+ """+ return Migration(+ id="2026_09_26_add_ltx2_system_prompts",+ depends_on="2026_09_09_add_system_prompt_max_tokens",+ callback=AddLtx2SystemPromptsCallback(),+ )diff --git a/invokeai/backend/model_manager/configs/text_llm.py b/invokeai/backend/model_manager/configs/text_llm.pyindex bb0a634976..7d0adf71be 100644--- a/invokeai/backend/model_manager/configs/text_llm.py+++ b/invokeai/backend/model_manager/configs/text_llm.py@@ -26,6 +26,14 @@ from invokeai.backend.model_manager.taxonomy import (# Gemma 2 variants (9B=3584, 27B=4608) are rejected there and must stay classifiable as a generic TextLLM._GEMMA2_2B_HIDDEN_SIZE = 2304+# Multimodal architectures that `AutoModelForCausalLM` still loads (transformers maps their model types+# onto these classes in its causal-LM table). Only listed ones are accepted, so a vision-language folder+# never becomes a TextLLM unless the generic loader is known to build it.+_CONDITIONAL_GENERATION_TEXT_LLMS = {"Gemma4ForConditionalGeneration"}++# Files that let `AutoProcessor` build the image side of a multimodal checkpoint.+_PROCESSOR_CONFIG_FILES = ("processor_config.json", "preprocessor_config.json")+class TextLLM_Diffusers_Config(Diffusers_Config_Base, Config_Base):"""Model config for text-only causal language models (e.g. Llama, Phi, Qwen, Mistral)."""@@ -33,6 +41,10 @@ class TextLLM_Diffusers_Config(Diffusers_Config_Base, Config_Base):type: Literal[ModelType.TextLLM] = Field(default=ModelType.TextLLM)base: Literal[BaseModelType.Any] = Field(default=BaseModelType.Any)cpu_only: bool | None = Field(default=None, description="Whether this model should run on CPU only")+ supports_images: bool = Field(+ default=False,+ description="Whether the model has a vision tower and processor, so Expand Prompt can condition on an image",+ )@classmethoddef from_model_on_disk(cls, mod: ModelOnDisk, override_fields: dict[str, Any]) -> Self:@@ -45,7 +57,7 @@ class TextLLM_Diffusers_Config(Diffusers_Config_Base, Config_Base):# MistralForCausalLM, GemmaForCausalLM, GPTNeoXForCausalLM, etc.config_dict = get_config_dict_or_raise(common_config_paths(mod.path))class_name = get_class_name_from_config_dict_or_raise(config_dict)- if not class_name.endswith("ForCausalLM"):+ if not class_name.endswith("ForCausalLM") and class_name not in _CONDITIONAL_GENERATION_TEXT_LLMS:raise NotAMatchError(f"model architecture '{class_name}' is not a causal language model")# During *automatic* classification, defer to the dedicated PiD Gemma2 encoder config — but only@@ -79,4 +91,10 @@ class TextLLM_Diffusers_Config(Diffusers_Config_Base, Config_Base):f"(expected at least one of: {', '.join(sorted(tokenizer_files))})")- return cls(**override_fields)+ # Only an allow-listed multimodal class is known to load with its vision tower through the generic loader.+ supports_images = (+ class_name in _CONDITIONAL_GENERATION_TEXT_LLMS+ and "vision_config" in config_dict+ and any((mod.path / f).exists() for f in _PROCESSOR_CONFIG_FILES)+ )+ return cls(**override_fields, supports_images=supports_images)diff --git a/invokeai/backend/model_manager/starter_models/__init__.py b/invokeai/backend/model_manager/starter_models/__init__.pyindex 809b9d13de..98717e710b 100644--- a/invokeai/backend/model_manager/starter_models/__init__.py+++ b/invokeai/backend/model_manager/starter_models/__init__.py@@ -151,6 +151,7 @@ from invokeai.backend.model_manager.starter_models.ltx_2 import (ltx2_5_dev_transformer_int8,ltx2_5_distilled_lora,ltx2_5_distilled_transformer_int8,+ ltx2_5_prompt_enhancer,ltx2_5_text_encoder_bf16,ltx2_5_text_encoder_int8,)@@ -474,6 +475,7 @@ STARTER_MODELS: list[StarterModel] = [ltx2_5_text_encoder_int8,ltx2_5_text_encoder_bf16,ltx2_5_components,+ ltx2_5_prompt_enhancer,gemini_flash_image,gemini_pro_image_preview,gemini_3_1_flash_image_preview,diff --git a/invokeai/backend/model_manager/starter_models/ltx_2.py b/invokeai/backend/model_manager/starter_models/ltx_2.pyindex e03b0a5796..0c6b8ad624 100644--- a/invokeai/backend/model_manager/starter_models/ltx_2.py+++ b/invokeai/backend/model_manager/starter_models/ltx_2.py@@ -41,6 +41,17 @@ ltx2_5_components = StarterModel(format=ModelFormat.Diffusers,)+ltx2_5_prompt_enhancer = StarterModel(+ name="LTX-2.5 Prompt Enhancer (Gemma-4 E2B)",+ base=BaseModelType.Any,+ source="google/gemma-4-E2B-it",+ description=(+ "The prompt enhancer LTX-2.5 was released with, for Expand Prompt. Pair it with the seeded LTX-2.5 "+ "system prompts; the Image-to-Video one also reads the first frame. Optional. (~10 GB)"+ ),+ type=ModelType.TextLLM,+)+ltx2_5_text_encoder_int8 = StarterModel(name="LTX-2.5 Text Encoder (Gemma-4 12B, int8)",base=BaseModelType.LTX2,diff --git a/invokeai/backend/text_llm_pipeline.py b/invokeai/backend/text_llm_pipeline.pyindex 608d566b88..e6bfd082fe 100644--- a/invokeai/backend/text_llm_pipeline.py+++ b/invokeai/backend/text_llm_pipeline.py@@ -1,10 +1,11 @@import queueimport threadingimport time-from typing import Callable+from typing import Any, Callableimport torch-from transformers import PreTrainedModel, PreTrainedTokenizerBase, TextIteratorStreamer+from PIL.Image import Image+from transformers import PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin, TextIteratorStreamerfrom transformers.generation.logits_process import LogitsProcessorDEFAULT_SYSTEM_PROMPT = (@@ -127,11 +128,18 @@ if torch.Tensor.multinomial is not _seeded_tensor_multinomial:class TextLLMPipeline:- """A wrapper for a causal language model + tokenizer for text generation."""+ """A wrapper for a causal language model + tokenizer for text generation.- def __init__(self, model: PreTrainedModel, tokenizer: PreTrainedTokenizerBase):+ A multimodal model can also condition on one image; that needs its ``processor``, which owns+ the image side of the input (resizing, patching and the image placeholder tokens).+ """++ def __init__(+ self, model: PreTrainedModel, tokenizer: PreTrainedTokenizerBase, processor: ProcessorMixin | None = None+ ):self._model = modelself._tokenizer = tokenizer+ self._processor = processordef run(self,@@ -142,16 +150,24 @@ class TextLLMPipeline:device: torch.device = torch.device("cpu"),dtype: torch.dtype = torch.float16,progress_callback: ProgressCallback | None = None,+ image: Image | None = None,) -> str:# Build messages for chat template if supported, otherwise use raw prompt.used_chat_template = (hasattr(self._tokenizer, "apply_chat_template") and self._tokenizer.chat_template is not None)+ if image is not None and (self._processor is None or not used_chat_template):+ raise ValueError("Conditioning on an image needs a multimodal model with a processor and a chat template")++ def user_content(text: str) -> str | list[dict[str, str]]:+ # The template renders the image placeholder; the processor expands it into the image's tokens.+ return text if image is None else [{"type": "image"}, {"type": "text", "text": text}]+if used_chat_template:- messages = []+ messages: list[dict[str, Any]] = []if system_prompt:messages.append({"role": "system", "content": system_prompt})- messages.append({"role": "user", "content": prompt})+ messages.append({"role": "user", "content": user_content(prompt)})try:# enable_thinking=False makes reasoning models (Qwen3, DeepSeek-R1 distills and# other templates that honour the flag) emit an empty thinking block instead of a@@ -164,7 +180,7 @@ class TextLLMPipeline:# Some chat templates (notably Gemma) reject a dedicated "system" role. Fold the# system prompt into the first user turn and retry instead of failing the expansion.if system_prompt and "system role" in str(e).lower():- merged = [{"role": "user", "content": f"{system_prompt}\n\n{prompt}"}]+ merged = [{"role": "user", "content": user_content(f"{system_prompt}\n\n{prompt}")}]formatted_prompt = self._tokenizer.apply_chat_template(merged, tokenize=False, add_generation_prompt=True, enable_thinking=False)@@ -179,9 +195,17 @@ class TextLLMPipeline:# A rendered chat template already carries the model's control tokens, so adding special# tokens again duplicates BOS for the families that use one (Gemma, Llama). The raw# fallback prompt above has no control tokens and still needs them.- inputs = self._tokenizer(formatted_prompt, return_tensors="pt", add_special_tokens=not used_chat_template).to(- device=device- )+ if image is None:+ inputs = self._tokenizer(+ formatted_prompt, return_tensors="pt", add_special_tokens=not used_chat_template+ ).to(device=device)+ else:+ assert self._processor is not None+ # BatchFeature.to casts floating tensors only, so the pixels follow the model's dtype and the+ # token ids stay integral.+ inputs = self._processor(+ text=formatted_prompt, images=[image], return_tensors="pt", add_special_tokens=False+ ).to(device=device, dtype=self._model.dtype)streamer = TextIteratorStreamer(self._tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=STREAM_TIMEOUTdiff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 3df74266f6..3ce6298aa1 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -31560,6 +31560,18 @@],"title": "Task Id","description": "Client-supplied task ID used to correlate socket progress events to this request"+ },+ "image_name": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Image Name",+ "description": "An image to condition the rewrite on, such as a video's first frame. Requires a model whose `supports_images` is true."}},"type": "object",@@ -101798,6 +101810,12 @@],"title": "Cpu Only","description": "Whether this model should run on CPU only"+ },+ "supports_images": {+ "type": "boolean",+ "title": "Supports Images",+ "description": "Whether the model has a vision tower and processor, so Expand Prompt can condition on an image",+ "default": false}},"type": "object",@@ -101817,7 +101835,8 @@"repo_variant","type","base",- "cpu_only"+ "cpu_only",+ "supports_images"],"title": "TextLLM_Diffusers_Config","description": "Model config for text-only causal language models (e.g. Llama, Phi, Qwen, Mistral)."diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex a195885c6a..c75eb6854c 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -12004,6 +12004,11 @@ export type components = {* @description Client-supplied task ID used to correlate socket progress events to this request*/task_id?: string | null;+ /**+ * Image Name+ * @description An image to condition the rewrite on, such as a video's first frame. Requires a model whose `supports_images` is true.+ */+ image_name?: string | null;};/** ExpandPromptResponse */ExpandPromptResponse: {@@ -45178,6 +45183,12 @@ export type components = {* @description Whether this model should run on CPU only*/cpu_only: boolean | null;+ /**+ * Supports Images+ * @description Whether the model has a vision tower and processor, so Expand Prompt can condition on an image+ * @default false+ */+ supports_images: boolean;};/** Tile */Tile: {diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex fa5a745995..c1374d5c6a 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2277,6 +2277,9 @@"enterPromptToExpand": "Enter a prompt to expand.","expand": "Expand","expandPrompt": "Expand prompt",+ "expandFromFirstFrame": "Describe from the first frame",+ "expandFirstFrameUnreadable": "This model can't read images, so the first frame won't be used.",+ "expandSuggestedModelMissing": "{{model}}, the prompt enhancer recommended for this model, isn't installed. It is among the starter models.","expandReferenceImage": "Expand reference image","generatePrompt": "Generate Prompt","guidance": "Guidance",diff --git a/invokeai/frontend/webv2/src/features/generation/core/types.ts b/invokeai/frontend/webv2/src/features/generation/core/types.tsindex 35f5da8832..e2f25ff569 100644--- a/invokeai/frontend/webv2/src/features/generation/core/types.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/types.ts@@ -78,6 +78,23 @@ export interface ImageWithDims {height: number;}+/**+ * What a widget suggests to Expand Prompt for its model family. Each part applies only until the+ * user picks a model or system prompt themselves.+ */+export interface ExpandPromptSuggestion {+ /** Source of the family's released enhancer, preselected when an installed text LLM has it. */+ modelSource: string | null;+ /** How the model is listed among the starter models, for the hint shown when it is not installed. */+ modelName: string | null;+ /** For a text-only rewrite. */+ systemPromptId: string | null;+ /** Replaces `systemPromptId` whenever `image` is actually sent; a prompt written for an image must not run without one. */+ imageSystemPromptId: string | null;+ /** An image the rewrite may describe from, such as a video's first frame. */+ image: ImageWithDims | null;+}+export interface CroppableImageWithDims {original: { image: ImageWithDims };crop?: {diff --git a/invokeai/frontend/webv2/src/features/generation/data/promptUtilities.ts b/invokeai/frontend/webv2/src/features/generation/data/promptUtilities.tsindex 5f5fb9518e..a4f6fde0ac 100644--- a/invokeai/frontend/webv2/src/features/generation/data/promptUtilities.ts+++ b/invokeai/frontend/webv2/src/features/generation/data/promptUtilities.ts@@ -7,6 +7,8 @@ export interface ExpandPromptRequest {max_tokens?: number;seed?: number | null;system_prompt?: string | null;+ /** Needs a model whose record has `supports_images`. */+ image_name?: string;}export interface ExpandPromptResponse {diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ExpandPromptSuggestion.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ExpandPromptSuggestion.browser.test.tsxnew file mode 100644index 0000000000..11d46077a0--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ExpandPromptSuggestion.browser.test.tsx@@ -0,0 +1,290 @@+/* oxlint-disable react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop */+import type { ExpandPromptSuggestion } from '@features/generation/core/types';+import type { ChangeEvent } from 'react';++import { ChakraProvider } from '@chakra-ui/react';+import { DndContext } from '@dnd-kit/core';+import { expandPrompt } from '@features/generation/data/promptUtilities';+import { PositivePromptField } from '@features/generation/ui/promptFields/PositivePromptField';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import i18next from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const i18n = i18next.createInstance();++await i18n.use(initReactI18next).init({+ fallbackLng: 'en',+ lng: 'en',+ resources: {+ en: { translation: { widgets: { generate: { expandSuggestedModelMissing: '{{model}} is not installed' } } } },+ },+});++const TEXT_ONLY = { base: 'any', key: 'qwen', name: 'Qwen', source: 'Qwen/Qwen2.5-1.5B-Instruct', type: 'text_llm' };+const ENHANCER = {+ base: 'any',+ key: 'e2b',+ name: 'Gemma-4 E2B',+ source: 'google/gemma-4-E2B-it',+ supports_images: true,+ type: 'text_llm',+};++const prompt = (id: string, content: string) => ({+ content,+ id,+ isPublic: true,+ maxTokens: null,+ name: id,+ userId: 'system',+});+const PROMPTS = [prompt('default', 'DEFAULT'), prompt('t2v', 'T2V'), prompt('i2v', 'I2V')];++const FRAME = { height: 512, image_name: 'frame.png', width: 768 };+const LTX_SUGGESTION: ExpandPromptSuggestion = {+ image: FRAME,+ imageSystemPromptId: 'i2v',+ modelName: 'LTX-2.5 Prompt Enhancer (Gemma-4 E2B)',+ modelSource: 'google/gemma-4-E2B-it',+ systemPromptId: 't2v',+};++// Read at render time by the mocks below, so each test can set them before rendering.+let catalog: (typeof TEXT_ONLY | typeof ENHANCER)[] = [];+let arePromptsLoading = false;++const StubSelect = ({+ label,+ onChange,+ options,+ value,+}: {+ label: string;+ onChange: (value: string) => void;+ options: { key: string; name: string }[];+ value: string | null;+}) => (+ <select+ aria-label={label}+ value={value ?? ''}+ onChange={(event: ChangeEvent<HTMLSelectElement>) => onChange(event.currentTarget.value)}+ >+ <option value="">none</option>+ {options.map((option) => (+ <option key={option.key} value={option.key}>+ {option.name}+ </option>+ ))}+ </select>+);++vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ GenerationModelSelect: ({+ onChange,+ value,+ }: {+ onChange: (model: (typeof catalog)[number] | null) => void;+ value: string | null;+ }) => (+ <StubSelect+ label="text llm"+ options={catalog}+ value={value}+ onChange={(key) => onChange(catalog.find((model) => model.key === key) ?? null)}+ />+ ),+ useGenerationUi: () => ({+ account: { isAdmin: false, userId: 'system' },+ capabilities: { canManagePromptTemplates: false, canManageSharedSystemPrompts: false },+ gallery: { selectedImage: null },+ models: { catalog, ensureLoaded: vi.fn(), openManager: vi.fn() },+ notifications: { reportError: vi.fn() },+ project: { activeProjectId: 'project-1' },+ promptHistory: { clear: vi.fn(), items: [] },+ }),+}));++vi.mock('@features/generation/ui/promptFields/SystemPromptsField', () => ({+ SystemPromptsField: ({+ onSelect,+ selectedId,+ }: {+ onSelect: (id: string | null) => void;+ selectedId: string | null;+ }) => (+ <StubSelect+ label="system prompt"+ options={PROMPTS.map(({ id, name }) => ({ key: id, name }))}+ value={selectedId}+ onChange={(id) => onSelect(id || null)}+ />+ ),+}));++vi.mock('@features/generation/ui/promptFields/useSystemPrompts', () => ({+ useSystemPrompts: () => ({+ isLoaded: !arePromptsLoading,+ isLoading: arePromptsLoading,+ prompts: arePromptsLoading ? [] : PROMPTS,+ }),+}));++vi.mock('@features/generation/data/promptUtilities', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ expandPrompt: vi.fn(() => Promise.resolve({ expanded_prompt: 'rewritten', seed: 1 })),+}));++vi.mock('@features/generation/data/wildcards', () => ({+ createWildcard: vi.fn(),+ deleteWildcard: vi.fn(),+ invalidateWildcardDependents: vi.fn(),+ updateWildcard: vi.fn(),+ wildcardsQueryOptions: () => ({ queryFn: () => Promise.resolve([]), queryKey: ['generation', 'wildcards'] }),+}));++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++beforeEach(() => {+ vi.mocked(expandPrompt).mockClear();+ catalog = [TEXT_ONLY, ENHANCER];+ arePromptsLoading = false;+});++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++const renderField = (suggestion: ExpandPromptSuggestion | null) =>+ root?.render(+ <I18nextProvider i18n={i18n}>+ <QueryClientProvider client={new QueryClient()}>+ <ChakraProvider value={system}>+ <DndContext>+ <PositivePromptField+ expandPromptSuggestion={suggestion}+ heightPx={96}+ loras={[]}+ projectId="project-1"+ selectedModel={undefined}+ showSyntaxHighlighting={false}+ value="she waves"+ onChange={vi.fn()}+ onResizeEnd={vi.fn()}+ onUsePrompt={vi.fn()}+ />+ </DndContext>+ </ChakraProvider>+ </QueryClientProvider>+ </I18nextProvider>+ );++const renderAndOpen = async (suggestion: ExpandPromptSuggestion | null) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);++ await act(() => renderField(suggestion));+ await act(() => host?.querySelector<HTMLButtonElement>('[aria-label="widgets.generate.expandPrompt"]')?.click());+};++const select = (label: string) => document.querySelector<HTMLSelectElement>(`select[aria-label="${label}"]`);+const choose = (label: string, value: string) =>+ act(() => {+ const element = select(label);+ if (element) {+ element.value = value;+ element.dispatchEvent(new Event('change', { bubbles: true }));+ }+ });+const expandButton = () =>+ [...document.querySelectorAll<HTMLButtonElement>('button')].find(+ (button) => button.textContent === 'widgets.generate.expand'+ );+const firstFrameCheckbox = () =>+ [...document.querySelectorAll('label')].find((label) =>+ label.textContent?.includes('widgets.generate.expandFromFirstFrame')+ );++const runExpand = async () => {+ await act(() => expandButton()?.click());+ expect(expandPrompt).toHaveBeenCalledOnce();+ return vi.mocked(expandPrompt).mock.calls[0][0];+};++it('starts from the suggested enhancer and describes from the first frame with the image prompt', async () => {+ await renderAndOpen(LTX_SUGGESTION);++ expect(select('text llm')?.value).toBe('e2b');+ expect(await runExpand()).toMatchObject({ image_name: 'frame.png', model_key: 'e2b', system_prompt: 'I2V' });+});++it('switches to the text prompt when the user leaves the frame out', async () => {+ await renderAndOpen(LTX_SUGGESTION);++ await act(() => firstFrameCheckbox()?.click());+ const request = await runExpand();+ expect(request.image_name).toBeUndefined();+ expect(request.system_prompt).toBe('T2V');+});++it('offers a different frame again after one was left out', async () => {+ await renderAndOpen(LTX_SUGGESTION);++ await act(() => firstFrameCheckbox()?.click());+ await act(() => renderField({ ...LTX_SUGGESTION, image: { ...FRAME, image_name: 'other.png' } }));+ expect(await runExpand()).toMatchObject({ image_name: 'other.png', system_prompt: 'I2V' });+});++it('uses the text prompt and says why for a model that cannot read images', async () => {+ await renderAndOpen(LTX_SUGGESTION);++ await choose('text llm', 'qwen');+ expect(firstFrameCheckbox()).toBeUndefined();+ expect(document.body.textContent).toContain('widgets.generate.expandFirstFrameUnreadable');+ const request = await runExpand();+ expect(request).toMatchObject({ model_key: 'qwen', system_prompt: 'T2V' });+ expect(request.image_name).toBeUndefined();+});++it("keeps the user's own system prompt over the suggestion", async () => {+ await renderAndOpen(LTX_SUGGESTION);++ await choose('system prompt', 'default');+ expect(await runExpand()).toMatchObject({ image_name: 'frame.png', system_prompt: 'DEFAULT' });+});++it('points to the starter models when the suggested enhancer is not installed', async () => {+ catalog = [TEXT_ONLY];+ await renderAndOpen(LTX_SUGGESTION);++ expect(select('text llm')?.value).toBe('');+ expect(document.body.textContent).toContain('LTX-2.5 Prompt Enhancer (Gemma-4 E2B) is not installed');+ // No model is chosen, so there is nothing to say about reading images yet.+ expect(document.body.textContent).not.toContain('widgets.generate.expandFirstFrameUnreadable');+ expect(expandButton()?.disabled).toBe(true);+});++it('waits for the system prompts before expanding', async () => {+ arePromptsLoading = true;+ await renderAndOpen(LTX_SUGGESTION);++ expect(expandButton()?.disabled).toBe(true);+});++it('preselects nothing without a suggestion', async () => {+ await renderAndOpen(null);++ expect(select('text llm')?.value).toBe('');+ expect(document.body.textContent).not.toContain('is not installed');+ expect(expandButton()?.disabled).toBe(true);+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsxindex 38ce80fc33..526561c615 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx@@ -1,11 +1,17 @@import type { GenerationModelCatalogItem as ModelConfig, PromptHistoryItem } from '@features/generation/contracts';import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';-import type { GenerateLora, GenerateModelConfig } from '@features/generation/core/types';+import type {+ ExpandPromptSuggestion,+ GenerateLora,+ GenerateModelConfig,+ ImageWithDims,+} from '@features/generation/core/types';import type { DynamicPromptsFieldConfig } from '@features/generation/ui/promptFields/DynamicPromptsPanel';import type { DroppedPromptImage } from '@features/generation/ui/promptFields/usePromptImageDrop';import type { ChangeEvent, MouseEvent } from 'react';-import { HStack, Icon, Image, Input, Popover, Portal, Separator, Stack, Text } from '@chakra-ui/react';+import { Checkbox, HStack, Icon, Image, Input, Popover, Portal, Separator, Stack, Text } from '@chakra-ui/react';+import { galleryImageUrls } from '@features/gallery/utility';import { filterPromptHistory } from '@features/generation/core/promptHistory';import { resolveSelectedSystemPromptId } from '@features/generation/core/systemPrompts';import { llmTaskProgressStore } from '@features/generation/data/llmTaskProgress';@@ -82,6 +88,8 @@ interface PositivePromptActionsProps {dynamicPrompts: DynamicPromptsFieldConfig | null;/** The authored prompt wrapped by the active template — what actually expands. */effectivePositivePrompt: string;+ /** Absent on surfaces whose model family has no prompt enhancer of its own. */+ expandPromptSuggestion?: ExpandPromptSuggestion | null;loras: GenerateLora[];isPromptTriggerPickerOpen: boolean;onUsePrompt: (prompt: PromptHistoryItem) => void;@@ -100,6 +108,7 @@ export const PositivePromptActions = ({droppedImage,dynamicPrompts,effectivePositivePrompt,+ expandPromptSuggestion,isPromptTriggerPickerOpen,onInsertText,onOpenPromptTriggerPicker,@@ -133,6 +142,7 @@ export const PositivePromptActions = ({isDisabled={template.isViewMode}positivePrompt={positivePrompt}projectId={projectId}+ suggestion={expandPromptSuggestion ?? null}onPositivePromptChange={onPositivePromptChangeImmediate}/><ImageToPromptButton@@ -366,10 +376,12 @@ const ExpandPromptButton = ({onPositivePromptChange,positivePrompt,projectId,+ suggestion,}: {isDisabled: boolean;positivePrompt: string;projectId: string;+ suggestion: ExpandPromptSuggestion | null;onPositivePromptChange: (prompt: string) => void;}) => {const { t } = useTranslation();@@ -385,12 +397,27 @@ const ExpandPromptButton = ({const [taskId, setTaskId] = useState<string | null>(null);const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);const [selectedSystemPromptId, setSelectedSystemPromptId] = useState<string | null>(null);+ // Keyed by image so unticking one frame does not carry over to the next one.+ const [excludedImageName, setExcludedImageName] = useState<string | null>(null);const textLlmModels = models.filter((model) => model.type === 'text_llm');- const selectedModel = selectedModelKey ? textLlmModels.find((model) => model.key === selectedModelKey) : null;+ const suggestedModelKey = suggestion?.modelSource+ ? (textLlmModels.find((model) => model.source === suggestion.modelSource)?.key ?? null)+ : null;+ // An explicit choice wins; otherwise the widget's suggested enhancer, when it is installed.+ const effectiveModelKey = selectedModelKey ?? suggestedModelKey;+ const selectedModel = effectiveModelKey ? textLlmModels.find((model) => model.key === effectiveModelKey) : null;+ const suggestedImage = suggestion?.image ?? null;+ const canReadImages = selectedModel?.supports_images === true;+ const isImageIncluded = suggestedImage !== null && excludedImageName !== suggestedImage.image_name;+ const conditioningImage = suggestedImage && canReadImages && isImageIncluded ? suggestedImage : null;// The list is behind the popover, so a closed button has nothing to fetch.const systemPrompts = useSystemPrompts({ isEnabled: isOpen });+ const suggestedSystemPromptId = conditioningImage ? suggestion?.imageSystemPromptId : suggestion?.systemPromptId;// Resolve selection at read time after deletion or without an explicit choice.- const effectiveSystemPromptId = resolveSelectedSystemPromptId(systemPrompts.prompts, selectedSystemPromptId);+ const effectiveSystemPromptId = resolveSelectedSystemPromptId(+ systemPrompts.prompts,+ selectedSystemPromptId ?? suggestedSystemPromptId ?? null+ );const selectedSystemPrompt = systemPrompts.prompts.find((prompt) => prompt.id === effectiveSystemPromptId);// eslint-disable-next-line react/refs@@ -412,6 +439,7 @@ const ExpandPromptButton = ({try {const result = await expandPrompt({// Forward the selected prompt's optional token cap to expansion.+ image_name: conditioningImage?.image_name,max_tokens: selectedSystemPrompt?.maxTokens ?? undefined,model_key: selectedModel.key,prompt: positivePrompt,@@ -436,9 +464,24 @@ const ExpandPromptButton = ({setTaskId(null);setIsLoading(false);}- }, [notifications, onPositivePromptChange, positivePrompt, projectId, selectedModel, selectedSystemPrompt, t]);+ }, [+ conditioningImage,+ notifications,+ onPositivePromptChange,+ positivePrompt,+ projectId,+ selectedModel,+ selectedSystemPrompt,+ t,+ ]);const popoverIds = useMemo(() => ({ trigger: triggerId }), [triggerId]);+ const suggestedImageName = suggestedImage?.image_name ?? null;+ const handleImageIncludedChange = useCallback(+ (event: { checked: boolean | 'indeterminate' }) =>+ setExcludedImageName(event.checked === true ? null : suggestedImageName),+ [suggestedImageName]+ );const handleOpenChange = useCallback((event: { open: boolean }) => setIsOpen(event.open), []);const handleModelChange = useCallback((model: ModelConfig | null) => setSelectedModelKey(model?.key ?? null), []);const handleRunExpandPrompt = useCallback(() => void runExpandPrompt(), [runExpandPrompt]);@@ -486,14 +529,32 @@ const ExpandPromptButton = ({modelTypes={TEXT_LLM_MODEL_TYPES}placeholder={t('widgets.generate.selectTextLlm')}size="xs"- value={selectedModelKey}+ value={effectiveModelKey}onChange={handleModelChange}/>+ {suggestion?.modelSource && !suggestedModelKey ? (+ <>+ <Text color="fg.subtle" fontSize="xs">+ {t('widgets.generate.expandSuggestedModelMissing', {+ model: suggestion.modelName ?? suggestion.modelSource,+ })}+ </Text>+ <OpenModelManagerButton modelType="text_llm" />+ </>+ ) : null}<SystemPromptsFieldcatalog={systemPrompts}selectedId={effectiveSystemPromptId}onSelect={setSelectedSystemPromptId}/>+ {suggestedImage && selectedModel ? (+ <ExpandPromptImageOption+ canReadImages={canReadImages}+ image={suggestedImage}+ isIncluded={isImageIncluded}+ onIncludedChange={handleImageIncludedChange}+ />+ ) : null}<LLMTaskProgressDisplay taskId={taskId} />{positivePrompt.trim() ? null : (<Text color="fg.subtle" fontSize="xs">@@ -501,7 +562,8 @@ const ExpandPromptButton = ({</Text>)}<Button- disabled={!selectedModel || !positivePrompt.trim()}+ // The request carries the system prompt's text, so it waits for the list.+ disabled={!selectedModel || !positivePrompt.trim() || systemPrompts.isLoading}loading={isLoading}size="xs"onClick={handleRunExpandPrompt}@@ -519,6 +581,46 @@ const ExpandPromptButton = ({);};+const ExpandPromptImageOption = ({+ canReadImages,+ image,+ isIncluded,+ onIncludedChange,+}: {+ canReadImages: boolean;+ image: ImageWithDims;+ isIncluded: boolean;+ onIncludedChange: (event: { checked: boolean | 'indeterminate' }) => void;+}) => {+ const { t } = useTranslation();++ return (+ <HStack gap="2">+ {/* Decorative: the checkbox label or the note beside it names the frame. */}+ <Image+ alt=""+ boxSize="10"+ flexShrink="0"+ objectFit="cover"+ opacity={canReadImages && isIncluded ? 1 : 0.5}+ rounded="md"+ src={galleryImageUrls.thumbnail(image.image_name)}+ />+ {canReadImages ? (+ <Checkbox.Root checked={isIncluded} size="sm" onCheckedChange={onIncludedChange}>+ <Checkbox.HiddenInput />+ <Checkbox.Control />+ <Checkbox.Label fontSize="xs">{t('widgets.generate.expandFromFirstFrame')}</Checkbox.Label>+ </Checkbox.Root>+ ) : (+ <Text color="fg.subtle" fontSize="xs">+ {t('widgets.generate.expandFirstFrameUnreadable')}+ </Text>+ )}+ </HStack>+ );+};+const ImageToPromptButton = ({droppedImage,isDisabled,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsxindex a90eb576a2..33134304a8 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx@@ -1,6 +1,6 @@import type { PromptHistoryItem } from '@features/generation/contracts';import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';-import type { GenerateLora, GenerateModelConfig } from '@features/generation/core/types';+import type { ExpandPromptSuggestion, GenerateLora, GenerateModelConfig } from '@features/generation/core/types';import type { ChangeEvent, KeyboardEvent } from 'react';import { Box, Text } from '@chakra-ui/react';@@ -29,6 +29,8 @@ interface PositivePromptFieldProps {batchCount?: number;/** Absent on surfaces whose prompt is not batch-expanded (Upscale). */dynamicPrompts?: DynamicPromptsFieldConfig | null;+ /** Absent on surfaces whose model family has no prompt enhancer of its own. */+ expandPromptSuggestion?: ExpandPromptSuggestion | null;/** Absent on surfaces with no template concept (Upscale). */promptTemplate?: PromptTemplateSnapshot | null;/** Show the merged prompt read-only instead of the authored text. */@@ -55,6 +57,7 @@ const POSITIVE_PROMPT_TRIGGER_KEYS = ['<', '_'] as const;export const PositivePromptField = ({batchCount = 1,dynamicPrompts = null,+ expandPromptSuggestion = null,heightPx,isTemplateViewMode = false,loras,@@ -193,6 +196,7 @@ export const PositivePromptField = ({batchCount={batchCount}droppedImage={droppedImage}dynamicPrompts={dynamicPrompts}+ expandPromptSuggestion={expandPromptSuggestion}isPromptTriggerPickerOpen={triggerPicker.isOpen}showSyntaxHighlighting={showSyntaxHighlighting}onInsertText={insertTextAtCaret}@@ -213,6 +217,7 @@ export const PositivePromptField = ({draftValue,dynamicPrompts,effectivePositivePrompt,+ expandPromptSuggestion,handleUsePrompt,droppedImage,insertTextAtCaret,diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.tsindex 4384ce6489..834e62ea85 100644--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts@@ -22,6 +22,7 @@ import {getEffectiveVideoTiming,getVideoComponentSectionPolicy,getVideoDimensions,+ getVideoExpandPromptSuggestion,getVideoModelAvailabilityReasons,getVideoModelPolicy,getVideoModelSelectionResult,@@ -227,6 +228,38 @@ describe('getVideoDimensions', () => {});});+describe('getVideoExpandPromptSuggestion', () => {+ const frame = { height: 512, image_name: 'frame.png', width: 768 };+ const promptSettings = {+ acceleratorEnabled: false,+ audioCfgScale: null,+ cfgScale: 3,+ cfgScaleLowNoise: null,+ negativePromptEnabled: true,+ wanLowNoiseModel: null,+ };++ it.each(['ltx2_dev', 'ltx2_distilled'])('suggests the LTX-2.5 enhancer and seeded prompts for %s', (variant) => {+ const { enhancer } = getVideoPromptPolicy(ltx2(variant), promptSettings);++ // The ids are the rows seeded by backend migration 2026_09_26_add_ltx2_system_prompts.+ expect(getVideoExpandPromptSuggestion(enhancer, frame)).toEqual({+ image: frame,+ imageSystemPromptId: '0f8f5b2e-1c9e-4f2a-9a4e-1f1f1f1f0010',+ modelName: 'LTX-2.5 Prompt Enhancer (Gemma-4 E2B)',+ modelSource: 'google/gemma-4-E2B-it',+ systemPromptId: '0f8f5b2e-1c9e-4f2a-9a4e-1f1f1f1f0009',+ });+ expect(getVideoExpandPromptSuggestion(enhancer, null)?.image).toBeNull();+ });++ it('suggests nothing for a family without an enhancer', () => {+ const { enhancer } = getVideoPromptPolicy(wanModel('t2v_a14b'), promptSettings);++ expect(getVideoExpandPromptSuggestion(enhancer, frame)).toBeNull();+ });+});+describe('getVideoPromptPolicy', () => {const promptSettings = (overrides: Partial<Parameters<typeof getVideoPromptPolicy>[1]> = {}) => ({acceleratorEnabled: false,diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.tsindex fd69b806d5..fb44158ced 100644--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts@@ -1,7 +1,9 @@import type {+ ExpandPromptSuggestion,GenerateLora,GenerationModelCatalogItem as ModelConfig,GenerationModelTaxonomyType as ModelTaxonomyType,+ ImageWithDims,LoraModelConfig,MainModelConfig,} from '@features/generation/contracts';@@ -169,12 +171,25 @@ interface VideoVariantConfig {/** What a fresh panel seeds the negative prompt with, when the family ships one. */defaultNegativePrompt?: string;negativePrompt: { visible: boolean; usage: VideoNegativePromptUsage };+ /** The family's released prompt enhancer, which Expand Prompt preselects. */+ promptEnhancer?: VideoPromptEnhancer;accelerator: VideoAcceleratorConfig | null;audioOutput: boolean;/** Ref2VA reference caps; present only on variants whose modes include 'reference'. */references?: { maxVideos: number; maxImages: number; extend?: boolean };}+export interface VideoPromptEnhancer {+ /** Starter source of the enhancer model; an installed text LLM with this source is preselected. */+ modelSource: string;+ /** The starter model's name (backend `starter_models/ltx_2.py`). */+ modelName: string;+ /** Seeded system prompts (backend migration `2026_09_26_add_ltx2_system_prompts`). */+ textToVideoSystemPromptId: string;+ /** Describes the video from its first frame; used only when Expand Prompt sends that frame along. */+ imageToVideoSystemPromptId: string;+}+/** A family whose only guidance control is the primary CFG scale. */const NO_EXTRA_GUIDANCE = { audioVisible: false, modalityVisible: false, stgVisible: false } as const;const NO_EXTRA_GUIDANCE_DEFAULTS = { audioCfgScale: null, modalityScale: null, stgScale: null } as const;@@ -344,6 +359,12 @@ const LTX2_FRAMES: VideoFramesGridPolicy = {const LTX2_COMMON = {accelerator: null,+ promptEnhancer: {+ imageToVideoSystemPromptId: '0f8f5b2e-1c9e-4f2a-9a4e-1f1f1f1f0010',+ modelName: 'LTX-2.5 Prompt Enhancer (Gemma-4 E2B)',+ modelSource: 'google/gemma-4-E2B-it',+ textToVideoSystemPromptId: '0f8f5b2e-1c9e-4f2a-9a4e-1f1f1f1f0009',+ },audioOutput: true,cfg: { lowNoiseVisible: false, visible: true },fps: { defaultValue: LTX2_FPS_DEFAULT, editable: true, max: LTX2_FPS_MAX, min: LTX2_FPS_MIN },@@ -703,12 +724,31 @@ export const getVideoPromptPolicy = ((config.negativePrompt.usage === 'cfg-gated' && (settings.cfgScale > 1 || lowNoiseCfgActive || audioCfgActive)));return {+ enhancer: config.promptEnhancer ?? null,negativeVisible: config.negativePrompt.visible && !guidanceDistilled,negativeUsedInGraph,...(config.negativePrompt.usage === 'cfg-gated' ? { negativeHelpTextKey: 'widgets.video.negativeCfgHelp' } : {}),};};+/**+ * What Expand Prompt starts from for this family: its enhancer and system prompts, with the first frame+ * offered when one is set (only a first frame opens the video it describes).+ */+export const getVideoExpandPromptSuggestion = (+ enhancer: VideoPromptEnhancer | null,+ firstFrameImage: ImageWithDims | null+): ExpandPromptSuggestion | null =>+ enhancer+ ? {+ image: firstFrameImage,+ imageSystemPromptId: enhancer.imageToVideoSystemPromptId,+ modelName: enhancer.modelName,+ modelSource: enhancer.modelSource,+ systemPromptId: enhancer.textToVideoSystemPromptId,+ }+ : null;+export interface VideoModelPolicy {isSupported: boolean;modes: readonly VideoGenerationMode[];@@ -731,6 +771,7 @@ export interface VideoModelPolicy {modalityScale: number | null;};prompt: {+ enhancer: VideoPromptEnhancer | null;negativeVisible: boolean;negativeUsedInGraph: boolean;/** Translation key for the negative prompt's inline help; absent when the field needs none. */diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsxindex 71cc3801fe..bd1fa7a6e8 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsx@@ -1,4 +1,9 @@-import type { GenerateLora, MainModelConfig, PromptHistoryItem } from '@features/generation/contracts';+import type {+ ExpandPromptSuggestion,+ GenerateLora,+ MainModelConfig,+ PromptHistoryItem,+} from '@features/generation/contracts';import type { VideoWidgetValues } from '@features/video/core/types';import { Stack } from '@chakra-ui/react';@@ -13,6 +18,7 @@ import { areVideoLorasEquivalent, areVideoModelsEquivalent } from './videoCompar*/export const VideoPromptFields = memo(function VideoPromptFields({+ expandPromptSuggestion,loras,model,negativeHelpText,@@ -26,6 +32,7 @@ export const VideoPromptFields = memo(projectId,showSyntaxHighlighting,}: {+ expandPromptSuggestion: ExpandPromptSuggestion | null;loras: GenerateLora[];model: MainModelConfig | null;negativeHelpText?: string;@@ -73,6 +80,7 @@ export const VideoPromptFields = memo(return (<Stack gap="2" p="2"><PositivePromptField+ expandPromptSuggestion={expandPromptSuggestion}heightPx={positivePromptHeightPx}loras={loras}projectId={projectId}@@ -102,6 +110,7 @@ export const VideoPromptFields = memo();},(previous, next) =>+ previous.expandPromptSuggestion === next.expandPromptSuggestion &&previous.negativePrompt === next.negativePrompt &&previous.negativePromptEnabled === next.negativePromptEnabled &&previous.negativePromptHeightPx === next.negativePromptHeightPx &&diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsxindex 92f51d4735..3e05629d21 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx@@ -34,6 +34,7 @@ import {getAcceleratorToggleResult,getEffectiveVideoTiming,getVideoDimensions,+ getVideoExpandPromptSuggestion,getVideoModelPolicy,getVideoModelSelectionResult,isVideoModelSelectable,@@ -422,6 +423,13 @@ export const VideoWidgetView = () => {const mode = resolveVideoMode(values);const supportsFirstFrame = policy.modes.includes('first-frame') || policy.modes.includes('first-last');const supportsLastFrame = policy.modes.includes('first-last') || policy.modes.includes('last-frame');+ const promptEnhancer = policy.prompt.enhancer;+ const firstFrameImage = values.firstFrameImage;+ // Memoized for VideoPromptFields' equality check; both inputs keep their identity between patches.+ const expandPromptSuggestion = useMemo(+ () => getVideoExpandPromptSuggestion(promptEnhancer, firstFrameImage),+ [promptEnhancer, firstFrameImage]+ );const supportsExtend = policy.modes.includes('extend');const supportsReferences = policy.modes.includes('reference');const supportsConditioningClip = policy.modes.includes('audio-to-video') || policy.modes.includes('video-to-audio');@@ -499,6 +507,7 @@ export const VideoWidgetView = () => {</Stack><VideoPromptFields+ expandPromptSuggestion={expandPromptSuggestion}loras={values.loras}model={values.model}negativeHelpText={policy.prompt.negativeHelpTextKey ? t(policy.prompt.negativeHelpTextKey) : undefined}diff --git a/tests/app/routers/test_utilities.py b/tests/app/routers/test_utilities.pyindex de5fd17b8c..a99b32ed75 100644--- a/tests/app/routers/test_utilities.py+++ b/tests/app/routers/test_utilities.py@@ -5,6 +5,7 @@ Covers:- image-to-prompt: image read-access check must fire BEFORE the model is loaded,so non-owners can't probe stored images.- image-to-prompt: a missing image surfaces as 404, not 500.+- expand-prompt with an image: the same read-access check, and a text-only model is refused before loading."""import shutil@@ -367,3 +368,64 @@ def test_list_user_fonts_skips_symlinked_files(assert r.status_code == status.HTTP_200_OKassert r.json()["fonts"] == []assert "Skipping font path" in caplog.text+++# ----------------------------- expand_prompt with an image -----------------------------+++def test_expand_prompt_image_forbidden_for_non_owner(+ client: TestClient, user1_token: str, user2_token: str, mock_invoker: Invoker+):+ """Attaching an image must not let a second user read a private image through the rewrite."""+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None+ _save_image(mock_invoker, "private-frame.png", user1.user_id)++ r = client.post(+ "/api/v1/utilities/expand-prompt",+ json={"prompt": "she waves", "model_key": "some-key", "image_name": "private-frame.png"},+ headers={"Authorization": f"Bearer {user2_token}"},+ )+ assert r.status_code == status.HTTP_403_FORBIDDEN+ mock_invoker.services.model_manager.store.get_model.assert_not_called()+++def test_expand_prompt_image_with_text_only_model_is_rejected_before_loading(+ client: TestClient, user1_token: str, mock_invoker: Invoker+):+ from invokeai.backend.model_manager.taxonomy import ModelType++ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None+ _save_image(mock_invoker, "frame.png", user1.user_id)+ mock_invoker.services.model_manager.store.get_model = MagicMock(+ return_value=MagicMock(type=ModelType.TextLLM, supports_images=False)+ )+ mock_invoker.services.model_manager.load.load_model = MagicMock()++ r = client.post(+ "/api/v1/utilities/expand-prompt",+ json={"prompt": "she waves", "model_key": "qwen", "image_name": "frame.png"},+ headers={"Authorization": f"Bearer {user1_token}"},+ )+ assert r.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT+ assert "cannot read images" in r.json()["detail"]+ mock_invoker.services.model_manager.load.load_model.assert_not_called()+++def test_expand_prompt_missing_image_is_404_for_an_admin(client: TestClient, admin_token: str, mock_invoker: Invoker):+ """Admins skip the ownership lookup, so a missing record surfaces on the read and must still be a 404."""+ from invokeai.backend.model_manager.taxonomy import ModelType++ mock_invoker.services.model_manager.store.get_model = MagicMock(+ return_value=MagicMock(type=ModelType.TextLLM, supports_images=True)+ )+ mock_invoker.services.model_manager.load.load_model = MagicMock()++ r = client.post(+ "/api/v1/utilities/expand-prompt",+ json={"prompt": "she waves", "model_key": "e2b", "image_name": "deleted-frame.png"},+ headers={"Authorization": f"Bearer {admin_token}"},+ )+ assert r.status_code == status.HTTP_404_NOT_FOUND+ mock_invoker.services.model_manager.load.load_model.assert_not_called()diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_26_add_ltx2_system_prompts.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_26_add_ltx2_system_prompts.pynew file mode 100644index 0000000000..6655e0fcda--- /dev/null+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_09_26_add_ltx2_system_prompts.py@@ -0,0 +1,65 @@+import sqlite3++from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_07_10_create_system_prompts import (+ DEFAULT_SYSTEM_PROMPTS,+ CreateSystemPromptsCallback,+)+from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_09_07_add_minimax_h3_ref2va_system_prompt import (+ MINIMAX_H3_REF2VA_PROMPT_ID,+ AddMiniMaxH3Ref2VASystemPromptCallback,+)+from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_09_09_add_system_prompt_max_tokens import (+ AddSystemPromptMaxTokensCallback,+)+from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_09_26_add_ltx2_system_prompts import (+ LTX2_5_I2V_PROMPT_ID,+ LTX2_5_MAX_TOKENS,+ LTX2_5_SYSTEM_PROMPTS,+ LTX2_5_T2V_PROMPT_ID,+ AddLtx2SystemPromptsCallback,+)+++def _db_before_migration() -> sqlite3.Connection:+ db = sqlite3.connect(":memory:")+ cursor = db.cursor()+ CreateSystemPromptsCallback()(cursor)+ AddMiniMaxH3Ref2VASystemPromptCallback()(cursor)+ AddSystemPromptMaxTokensCallback()(cursor)+ return db+++def test_seeds_both_prompts_shared_with_their_token_cap() -> None:+ db = _db_before_migration()+ cursor = db.cursor()++ AddLtx2SystemPromptsCallback()(cursor)++ cursor.execute(+ "SELECT id, name, content, user_id, is_public, max_tokens FROM system_prompts WHERE id IN (?, ?) ORDER BY id;",+ (LTX2_5_T2V_PROMPT_ID, LTX2_5_I2V_PROMPT_ID),+ )+ assert cursor.fetchall() == [+ (prompt_id, name, content, "system", 1, LTX2_5_MAX_TOKENS) for prompt_id, name, content in LTX2_5_SYSTEM_PROMPTS+ ]+ db.close()+++def test_leaves_a_row_that_already_holds_the_id_alone() -> None:+ db = _db_before_migration()+ cursor = db.cursor()+ cursor.execute(+ "INSERT INTO system_prompts (id, name, content, user_id, is_public) VALUES (?, 'Mine', 'edited', 'system', 0);",+ (LTX2_5_T2V_PROMPT_ID,),+ )++ AddLtx2SystemPromptsCallback()(cursor)++ cursor.execute("SELECT name, content, max_tokens FROM system_prompts WHERE id = ?;", (LTX2_5_T2V_PROMPT_ID,))+ assert cursor.fetchone() == ("Mine", "edited", None)+ db.close()+++def test_ids_do_not_collide_with_earlier_seeds() -> None:+ earlier = {default_id for default_id, _, _ in DEFAULT_SYSTEM_PROMPTS} | {MINIMAX_H3_REF2VA_PROMPT_ID}+ assert earlier.isdisjoint({LTX2_5_T2V_PROMPT_ID, LTX2_5_I2V_PROMPT_ID})diff --git a/tests/backend/model_manager/configs/test_text_llm_gemma4_config.py b/tests/backend/model_manager/configs/test_text_llm_gemma4_config.pynew file mode 100644index 0000000000..7dc36d6d1e--- /dev/null+++ b/tests/backend/model_manager/configs/test_text_llm_gemma4_config.py@@ -0,0 +1,66 @@+"""TextLLM classification of Gemma-4 multimodal checkpoints (the LTX-2.5 prompt enhancer, Gemma-4-E2B).++Stock Gemma-4 folders name `Gemma4ForConditionalGeneration`, which `AutoModelForCausalLM` loads on the+pinned transformers, so they classify as TextLLM. Whether Expand Prompt may send them an image depends+on the folder carrying both the vision config and the processor config that `AutoProcessor` needs.+"""++import json+from pathlib import Path+from unittest.mock import MagicMock++import pytest++from invokeai.backend.model_manager.configs.identification_utils import NotAMatchError+from invokeai.backend.model_manager.configs.text_llm import TextLLM_Diffusers_Config++_OVERRIDE_FIELDS: dict[str, object] = {+ "hash": "blake3:fakehash",+ "path": "/fake/models/test-model",+ "file_size": 1000,+ "name": "test-model",+ "description": "test",+ "source": "test",+ "source_type": "path",+ "key": "test-key",+}+++def _write_model(root: Path, *, architecture: str, vision: bool, processor: bool) -> MagicMock:+ config: dict[str, object] = {"architectures": [architecture], "model_type": "gemma4", "text_config": {}}+ if vision:+ config["vision_config"] = {}+ root.joinpath("config.json").write_text(json.dumps(config))+ root.joinpath("tokenizer.json").write_text("{}")+ if processor:+ root.joinpath("processor_config.json").write_text("{}")+ mod = MagicMock()+ mod.path = root+ return mod+++def test_gemma4_with_vision_and_processor_supports_images(tmp_path: Path) -> None:+ mod = _write_model(tmp_path, architecture="Gemma4ForConditionalGeneration", vision=True, processor=True)+ config = TextLLM_Diffusers_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))+ assert config.supports_images is True++[email protected](("vision", "processor"), [(True, False), (False, True)])+def test_gemma4_without_both_image_parts_is_text_only(tmp_path: Path, vision: bool, processor: bool) -> None:+ mod = _write_model(tmp_path, architecture="Gemma4ForConditionalGeneration", vision=vision, processor=processor)+ config = TextLLM_Diffusers_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))+ assert config.supports_images is False+++def test_causal_lm_with_image_parts_is_still_text_only(tmp_path: Path) -> None:+ """Only the allow-listed class is known to load with its vision tower through the generic loader."""+ mod = _write_model(tmp_path, architecture="SomeVisionForCausalLM", vision=True, processor=True)+ config = TextLLM_Diffusers_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))+ assert config.supports_images is False+++def test_unlisted_conditional_generation_is_not_a_text_llm(tmp_path: Path) -> None:+ """The generic loader is not known to build other vision-language classes, so they are not claimed."""+ mod = _write_model(tmp_path, architecture="LlavaOnevisionForConditionalGeneration", vision=True, processor=True)+ with pytest.raises(NotAMatchError, match="not a causal language model"):+ TextLLM_Diffusers_Config.from_model_on_disk(mod, dict(_OVERRIDE_FIELDS))diff --git a/tests/backend/text_llm/test_text_llm_api_models.py b/tests/backend/text_llm/test_text_llm_api_models.pyindex 8b15c582fc..d617521770 100644--- a/tests/backend/text_llm/test_text_llm_api_models.py+++ b/tests/backend/text_llm/test_text_llm_api_models.py@@ -4,6 +4,7 @@ from unittest.mock import MagicMock, patchimport pytestimport torch+from PIL import Imagefrom pydantic import ValidationErrorfrom invokeai.app.api.dependencies import ApiDependencies@@ -95,3 +96,32 @@ def test_expand_prompt_uses_fresh_seed() -> None:pipeline_class.return_value.run.reset_mock()assert _run_expand_prompt("cat", "model", 10, None, 456, None, "user") == ("expanded", 456)assert pipeline_class.return_value.run.call_args.kwargs["seed"] == 456+++def test_expand_prompt_with_an_image_runs_it_through_the_processor() -> None:+ """The stored image reaches the pipeline as RGB, next to the model's processor, whose tokenizer is reused."""+ model_config = MagicMock(type=ModelType.TextLLM, path="model", supports_images=True)+ model = MagicMock()+ model.parameters.side_effect = lambda: iter([torch.nn.Parameter(torch.zeros(1))])+ loaded_model = MagicMock()+ loaded_model.model_on_device.return_value.__enter__.return_value = (None, model)+ services = MagicMock()+ services.model_manager.store.get_model.return_value = model_config+ services.model_manager.load.load_model.return_value = loaded_model+ services.images.get_pil_image.return_value = Image.new("RGBA", (8, 8))++ with (+ patch.object(ApiDependencies, "invoker", MagicMock(services=services), create=True),+ patch("invokeai.app.api.routers.utilities._resolve_model_path", return_value="model"),+ patch("invokeai.app.api.routers.utilities.AutoTokenizer.from_pretrained") as load_tokenizer,+ patch("invokeai.app.api.routers.utilities.AutoProcessor.from_pretrained") as load_processor,+ patch("invokeai.app.api.routers.utilities.TextLLMPipeline") as pipeline_class,+ ):+ pipeline_class.return_value.run.return_value = "expanded"+ _run_expand_prompt("she waves", "model", 10, None, 1, None, "user", image_name="frame.png")++ services.images.get_pil_image.assert_called_once_with("frame.png")+ processor = load_processor.return_value+ load_tokenizer.assert_not_called()+ assert pipeline_class.call_args.args[1:] == (processor.tokenizer, processor)+ assert pipeline_class.return_value.run.call_args.kwargs["image"].mode == "RGB"diff --git a/tests/backend/text_llm/test_text_llm_pipeline.py b/tests/backend/text_llm/test_text_llm_pipeline.pyindex f88d842150..b2ccea350e 100644--- a/tests/backend/text_llm/test_text_llm_pipeline.py+++ b/tests/backend/text_llm/test_text_llm_pipeline.py@@ -7,7 +7,8 @@ from unittest.mock import MagicMock, patchimport pytestimport torch-from transformers import LlamaConfig, LlamaForCausalLM+from PIL import Image+from transformers import BatchFeature, LlamaConfig, LlamaForCausalLMfrom invokeai.backend import text_llm_pipelinefrom invokeai.backend.text_llm_pipeline import DEFAULT_SYSTEM_PROMPT, TextLLMPipeline, _SeededMultinomialMode@@ -484,3 +485,35 @@ def test_default_system_prompt_content():"""The default system prompt should mention image generation."""assert "image generation" in DEFAULT_SYSTEM_PROMPT.lower()assert "prompt" in DEFAULT_SYSTEM_PROMPT.lower()+++def test_pipeline_conditions_on_an_image_through_the_processor():+ """The image goes to the processor next to the rendered template, and its pixels reach generate() in+ the model's dtype while the token ids stay integral."""+ tokenizer = _make_mock_tokenizer(has_chat_template=True)+ model = _make_mock_model()+ model.dtype = torch.bfloat16+ processor = MagicMock(+ return_value=BatchFeature(+ {"input_ids": torch.tensor([[1, 2, 3]]), "pixel_values": torch.zeros(1, 3, 4, 4, dtype=torch.float32)}+ )+ )+ image = Image.new("RGB", (8, 8))+ pipeline = TextLLMPipeline(model, tokenizer, processor)++ with _patch_streamer():+ pipeline.run(prompt="she waves", system_prompt="S", device=torch.device("cpu"), image=image)++ messages = tokenizer.apply_chat_template.call_args[0][0]+ assert messages[-1] == {"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "she waves"}]}+ assert processor.call_args.kwargs["images"] == [image]+ tokenizer.assert_not_called()+ generate_kwargs = model.generate.call_args.kwargs+ assert generate_kwargs["pixel_values"].dtype == torch.bfloat16+ assert generate_kwargs["input_ids"].dtype == torch.long+++def test_pipeline_refuses_an_image_without_a_processor():+ pipeline = TextLLMPipeline(_make_mock_model(), _make_mock_tokenizer(has_chat_template=True))+ with pytest.raises(ValueError, match="multimodal model"):+ pipeline.run(prompt="a cat", image=Image.new("RGB", (8, 8)))