Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(moss-image): expand prompts into MOSS-Image captions or layout drafts (#10054)

Alexander Eichhorn036efa7489ad
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdx
index 88880288e3..d029ac19ec 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdx
@@ -1,7 +1,7 @@
---
title: MOSS-Image
-description: Generate and edit images with OpenMOSS's MOSS-Image Base and SFT, from the Diffusers pipelines or a single-file transformer, including JSON layout prompts and layouts from canvas regions.
-lastUpdated: 2026-10-18
+description: Generate and edit images with OpenMOSS's MOSS-Image Base and SFT, from the Diffusers pipelines or a single-file transformer, including JSON layout prompts, layouts from canvas regions and a prompt enhancer.
+lastUpdated: 2026-10-28
sidebar:
order: 8
---
@@ -191,11 +191,69 @@ with *MOSS-Image needs a prompt to place regional guidance in its layout. Enter
regional guidance layers.* Regional negative prompts, auto-negative and regional reference images are not used
with MOSS-Image; the layer hides its negative prompt and auto-negative controls.
-Without regions the prompt is sent unchanged. If the prompt already is a JSON layout in the format above, the
+Without regions the prompt is sent unchanged. If the prompt is a [layout draft](#prompt-enhancer), it is
+compiled and the regions follow its items. If it already is a JSON layout in the format above, the
regions are added to its `items`; a layout with another `bbox_coord_space` or `bbox_format` makes the
generation fail with a message. Any other prompt, including JSON that is not a layout, becomes the caption.
-The layout is built when the generation runs, so dynamic prompts and batches vary the caption inside it. The
-encoded layout is saved in the image's metadata as `moss_image_layout_prompt`.
+The layout is built when the generation runs, so for a plain-text prompt dynamic prompts and batches vary the
+caption inside it. A prompt that already is a JSON layout or draft is sent as written, without expanding
+dynamic prompts or wildcards and without a prompt template's positive text.
+
+The prompt the model encodes, in the Generate tab and on the Canvas, is saved in the image's metadata as
+`moss_image_layout_prompt`: the compiled layout when there is one, otherwise the prompt as sent.
+
+### Prompt enhancer
+
+MOSS-Image follows long, specific prompts best. **Expand Prompt** in the prompt toolbar can write them for
+you with the **MOSS-Image Prompt Enhancer** system prompt, derived from OpenMOSS's prompt-enhancer skill. See
+[Prompt Tools](/users-guide/image-generation/prompt-tools/#expand-prompt) for the tool itself.
+
+1. Select a MOSS-Image model and type a short idea, such as `a jazz festival poster titled "BLUE NOTES"`.
+2. Open **Expand prompt** in the Generate panel's prompt toolbar; Canvas generations use the same prompt.
+ With MOSS-Image selected it preselects the **MOSS-Image Prompt Enhancer** system prompt. The model saved for
+ the project stays selected; without one, **Gemma 4 E4B (Prompt Enhancer)** is preselected when installed.
+ When Gemma is installed but another model is selected, the popover shows **Recommended for this model** with
+ a **Use it** button; when it is not installed, the popover points you to that starter model. A model or
+ system prompt you pick in the open popover overrides the suggestion.
+3. Click **Expand**, check the result in the prompt box and press Invoke.
+
+The language model decides between two kinds of output:
+
+- **A caption**: one detailed paragraph, for photos, scenes and most images without precise placement.
+ It is sent as written.
+- **A layout draft**: JSON for posters, covers, infographics and other images where text or elements must sit
+ in particular places. It holds a `summary` with the scene caption, a list of `items` with a label, a caption,
+ the text to render for text items and a box, plus the `width` and `height` the boxes refer to. Boxes are
+ `[x1, y1, x2, y2]` pixel edges from the top-left corner (`"bbox_coord_space": "abs"`,
+ `"bbox_format": "xyxy"`).
+
+You can edit a draft in the prompt box like any other text. It is compiled into the model's
+[JSON layout](#json-layouts) when the generation runs:
+
+- **Size**: Expand Prompt never changes the image size. The draft's `width` and `height` only set its
+ coordinate frame, and its boxes are scaled to the width and height you generate at, so you can change the
+ size after expanding.
+- **Tolerance**: a Markdown code fence around the JSON (with or without a language tag such as `json`), unknown fields and unknown labels are accepted, boxes
+ that leave the image are clamped to it, and items whose box has no area are dropped. A draft without a scene
+ caption, without any usable item, or with a text item that has no text fails with a message naming the item.
+- **Canvas regions**: on the Canvas, enabled [regional guidance](#layout-with-canvas-regions) layers are
+ appended after the draft's items.
+
+A JSON object with `"bbox_coord_space": "abs"` is treated as a draft. When it lacks a summary caption, items,
+or a numeric width and height, or its `bbox_format` is not `xyxy`, Invoke is disabled with a message saying
+so. A compiled layout (`abs_centralized`, `yxyx`) is never blocked. Run Expand Prompt
+again or fix the JSON.
+
+#### Recommended language model
+
+Install **Gemma 4 E4B (Prompt Enhancer)** from the starter models (`google/gemma-4-E4B-it`, ~16 GB). It is
+optional and not part of the MOSS-Image bundle. In InvokeAI's tests on an RTX 4090 in bf16, it chose
+between caption and layout correctly for all 10 test requests and every draft it wrote was valid. A request
+took 8 to 26 s and peaked at about 15 GiB of VRAM.
+
+Small language models of about 1.5 to 1.7B parameters, such as **Qwen2.5 1.5B Instruct** or SmolLM-class
+models, are not recommended for this system prompt: they write layouts for nearly every request, and their
+drafts are often invalid.
## Limitations
@@ -210,7 +268,7 @@ encoded layout is saved in the image's metadata as `moss_image_layout_prompt`.
| Node | Purpose |
| --------------------------------- | -------------------------------------------------------------------------- |
| **Main Model - MOSS-Image** | Loads the transformer, and the Qwen3.5 9B encoder and VAE from the pipeline or from the standalone models selected |
-| **Layout Prompt - MOSS-Image** | Builds a JSON layout from a prompt and a list of regions, each with a type, a caption, visible text for text regions, and a pixel box `[x1, y1, x2, y2]` from the image's top-left. The Canvas feeds it for regional guidance; its regions input has no editor widget |
+| **Layout Prompt - MOSS-Image** | Builds the prompt the model encodes from a prompt, the image size and a list of regions, each with a type, a caption, visible text for text regions, and a pixel box `[x1, y1, x2, y2]` from the image's top-left. Compiles a layout draft at the given size. Every MOSS-Image graph from the Generate tab and the Canvas uses it; its regions input has no editor widget |
| **Prompt - MOSS-Image** | Encodes a prompt with the Qwen3.5 9B encoder |
| **Denoise - MOSS-Image** | Runs sampling; accepts image-to-image latents and an inpainting mask, and takes the skip layers as **Uncond Skip Layers** |
| **Image to Latents - FLUX2** | VAE encode, for image-to-image and inpainting |
diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/prompt-tools.md b/docs/src/content/docs/Users Guide/04.Image Generation/prompt-tools.md
index 2f9d9f6810..57e9f917d9 100644
--- a/docs/src/content/docs/Users Guide/04.Image Generation/prompt-tools.md
+++ b/docs/src/content/docs/Users Guide/04.Image Generation/prompt-tools.md
@@ -2,7 +2,7 @@
title: Prompt Tools
sidebar:
order: 4
-lastUpdated: 2026-09-30
+lastUpdated: 2026-10-28
---
The prompt toolbar holds tools that help you write prompts. **Expand Prompt** and **Image to Prompt** use local language models to write or rewrite a prompt for you; if no compatible model is installed, the tool's popover says so and offers an **Open Model Manager** button. **Prompt triggers** insert the trigger phrases, embeddings and wildcards your models need.
@@ -22,7 +22,7 @@ Takes your short prompt and expands it into a detailed, vivid description suitab
### System prompts
-InvokeAI ships with a **Default** system prompt and several tuned for particular model families, such as FLUX.2, Z-Image, Qwen Image and Krea-2. To add your own, click the gear button next to the System prompt selector (**Manage system prompts**) and choose **New**. A system prompt has a **Name**, the **Instructions** given to the language model, and an optional **Max output length** in tokens (300 by default).
+InvokeAI ships with a **Default** system prompt and several tuned for particular model families, such as FLUX.2, Z-Image, Qwen Image, Krea-2 and MOSS-Image. To add your own, click the gear button next to the System prompt selector (**Manage system prompts**) and choose **New**. A system prompt has a **Name**, the **Instructions** given to the language model, and an optional **Max output length** in tokens (300 by default).
You can duplicate, edit and delete your own system prompts. Shared system prompts, including the built-in ones, are marked **Shared**. On a multi-user installation only administrators can edit them, and changes apply to every user.
@@ -43,10 +43,14 @@ LTX-2.5 was trained on long, single-paragraph audio-visual captions, and its own
* 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.
+In the Video panel with an LTX-2 model selected, Expand Prompt preselects the matching system prompt. For the model, a pick in the open popover comes first, then the model saved for the project, then the enhancer when it was installed from the starter models or as `google/gemma-4-E2B-it`, then the first available model. When the enhancer is installed but another model is selected, the popover shows **Recommended for this model** with a **Use it** button, which saves it like any other pick; when it is not installed, the popover points you to the starter models. 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. A model or system prompt you pick in the open 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.
+### Prompt enhancement for MOSS-Image
+
+The **MOSS-Image Prompt Enhancer** system prompt, derived from OpenMOSS's prompt-enhancer skill, has the language model write either a detailed caption or, for posters and other images with placed text, a layout draft that MOSS-Image compiles into its JSON layout at generation time. With a MOSS-Image model selected, Expand Prompt in the Generate panel (whose prompt the Canvas also uses) preselects this system prompt and the **Gemma 4 E4B (Prompt Enhancer)** starter model (`google/gemma-4-E4B-it`, ~16 GB), following the same rule as for LTX-2 above. Small models such as Qwen2.5 1.5B are not recommended for this system prompt. See [MOSS-Image](/users-guide/models/local-models/moss-image/#prompt-enhancer) for caption versus layout, image size and canvas regions.
+
### Reasoning ("thinking") models
Reasoning 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.
diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/prompting-guide.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/prompting-guide.mdx
index 9916dfcbaa..423467862a 100644
--- a/docs/src/content/docs/Users Guide/04.Image Generation/prompting-guide.mdx
+++ b/docs/src/content/docs/Users Guide/04.Image Generation/prompting-guide.mdx
@@ -1,7 +1,7 @@
---
title: Prompting Guide
description: Write prompts that work, then go further with prompt templates, dynamic prompts and wildcards.
-lastUpdated: 2026-09-30
+lastUpdated: 2026-10-28
sidebar:
order: 2
---
@@ -165,6 +165,7 @@ a red fox in the snow. photography. f/2.8 macro photo, bokeh, photorealism
* Only the first `{prompt}` is replaced. Any further copies stay in the text as written.
* A template without `{prompt}` is added to the end of your prompt, after a space.
* Templates can carry negative text too. It is combined with your negative prompt by the same rules, for models that use a negative prompt.
+* A positive prompt that is JSON, such as a [MOSS-Image layout](/users-guide/models/local-models/moss-image/#json-layouts), is sent as written: the template's positive text is not added around it. Its negative text is still combined with your negative prompt.
While a template is applied, an eye button in the prompt toolbar (**Show the merged prompt**) shows the prompt exactly as it will be sent, with the template's words distinguished from yours. The prompt boxes are read-only in this view. Click the text, or the button again (**Back to editing your prompt**), to return to editing.
@@ -281,6 +282,7 @@ Turn on **New seed for every image** to give each image its own seed instead, fo
### Dynamic prompts and other features
* **Prompt templates.** Expansion runs on your prompt after the [template](#prompt-templates) has been applied, so a template can contain dynamic syntax too.
+* **JSON prompts.** A prompt that is a JSON object or array, also inside a Markdown code fence such as ```` ```json ````, is sent as written for every model. Dynamic syntax and [wildcards](#wildcards) in it are not expanded, and the **Dynamic** badge stays off.
* **Image metadata.** Each image records the expanded prompt that produced it and its own seed. The original dynamic prompt and the dynamic prompt settings are not recorded.
* **Workflows.** The workflow editor has a **Dynamic Prompt** node, and batch generators for random and combinatorial expansion.
diff --git a/invokeai/app/invocations/moss_image/moss_image_layout_prompt.py b/invokeai/app/invocations/moss_image/moss_image_layout_prompt.py
index 885d7e9e16..a51d21acfb 100644
--- a/invokeai/app/invocations/moss_image/moss_image_layout_prompt.py
+++ b/invokeai/app/invocations/moss_image/moss_image_layout_prompt.py
@@ -17,14 +17,15 @@ class MossImageLayoutPromptInvocation(BaseInvocation):
"""Places regions on a MOSS-Image prompt as a JSON layout, at generation time.
The layout is built here rather than by the graph builder so the prompt that dynamic prompts and batching vary is
- the one laid out. Without regions the prompt passes through unchanged; a prompt that already is a layout gets the
- regions appended to its items.
+ the one laid out. A layout draft with absolute pixel boxes (what Expand Prompt's MOSS-Image Prompt Enhancer writes)
+ is compiled at this width and height, regions following its items. Otherwise, without regions the prompt passes
+ through unchanged, and a prompt that already is a compiled layout gets the regions appended to its items.
"""
prompt: str = InputField(
default="",
description="The image prompt: plain text becomes the layout's summary caption, a compiled layout gets the "
- "regions appended.",
+ "regions appended, and a layout draft with absolute pixel boxes is compiled at this width and height.",
ui_component=UIComponent.Textarea,
)
regions: list[MossImageLayoutRegion] = InputField(
diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_10_28_add_moss_image_enhancer_system_prompt.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_10_28_add_moss_image_enhancer_system_prompt.py
new file mode 100644
index 0000000000..ab26af3c90
--- /dev/null
+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_10_28_add_moss_image_enhancer_system_prompt.py
@@ -0,0 +1,102 @@
+"""Seed the "MOSS-Image Prompt Enhancer" system prompt for the Expand Prompt button.
+
+MOSS-Image reads either a plain caption or a compact JSON layout. The prompt asks the enhancer LLM for one of the
+two: prose by default, or an absolute-pixel layout draft (``"bbox_coord_space":"abs","bbox_format":"xyxy"``) for
+images with visible text, designed images or fixed placements. The MOSS-Image layout prompt node compiles such a
+draft into the model's convention (``invokeai/backend/moss_image/layout.py``) at the generation size.
+
+The text is derived from OpenMOSS' prompt-enhancer skill, https://github.com/OpenMOSS/MOSS-Image
+(``skills/moss-image-prompt-enhancer/SKILL.md`` and ``references/layout.md``, commit
+c1355e6b1986dfe8fba3c0455783a05899212342), Apache-2.0 (see ``invokeai/backend/moss_image/NOTICE.md``), condensed
+into a single system prompt for small local LLMs such as Gemma 4 E4B.
+
+Same fixed-UUID, insert-if-absent shape as the earlier system-prompt seeds: a prompt the user has since edited or
+deleted stays edited or deleted.
+"""
+
+from sqlalchemy import column, exists, insert, select, table, true
+
+from invokeai.app.services.shared.database.types import now_text
+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import (
+ PortableMigration,
+ PortableMigrationContext,
+)
+
+MOSS_IMAGE_ENHANCER_PROMPT_ID = "0f8f5b2e-1c9e-4f2a-9a4e-1f1f1f1f0011"
+MOSS_IMAGE_ENHANCER_PROMPT_NAME = "MOSS-Image Prompt Enhancer"
+
+MOSS_IMAGE_ENHANCER_MAX_TOKENS = 1536
+"""Room for a layout draft with several text items; captions stay far below it."""
+
+MOSS_IMAGE_ENHANCER_PROMPT_CONTENT = r"""You expand a short image idea into a prompt for the MOSS-Image text-to-image model. Reply with the prompt only: no greeting, no explanation, no markdown, no code fences.
+
+Choose one of two outputs.
+
+CAPTION (the default): for ordinary scenes, photographs and illustrations. Reply with cohesive English prose that describes subject and action, appearance, setting, camera and framing, medium, lighting, materials, palette and mood. Describe spatial relations in words and quote any visible wording exactly. Paragraphs are fine. No coordinates, no JSON.
+
+LAYOUT: when the idea contains words that must appear in the image, or is a designed image: a poster, flyer, book or album cover, menu, sign, label, packaging, advertisement, title card, comic or other multi-panel image; or when it fixes the positions of several objects. A detailed scene without visible text does not need a layout. If the user asks for a layout or a caption, give that. Reply with exactly one JSON object and nothing else:
+{"width":W,"height":H,"bbox_coord_space":"abs","bbox_format":"xyxy","summary":{"caption":"..."},"items":[...]}
+- width and height: positive multiples of 16. Use the size the user gives; otherwise 1024 and 1024, or a shape the medium suggests (for example 1536 by 1024 for a landscape poster).
+- summary.caption: the global description of the whole image (style, background, lighting, palette, mood). Optional: "meta" (array of medium or genre tags), "canvas" ("single", "multi_panel" or "collage"), "palette" (array of colours).
+- items: a flat, non-empty array. Each item has "label" ("object", "character" or "text"), a non-empty "caption" describing its visible appearance (for text: typography and surface treatment), and "bbox": [x_min, y_min, x_max, y_max] in pixels from the top-left corner, with 0 <= x_min < x_max <= width and 0 <= y_min < y_max <= height. Do not normalise or centre the numbers.
+- A "text" item also needs "text": the exact visible characters, with \n for an intended line break. Use separate text items only when they must be placed independently.
+- Optional on items: "tags" and "palette" (arrays of strings). No other fields: no ids, children, parents or notes.
+- Use one box per coherent visible unit. Boxes may overlap. A box marks placement; it is not a border or panel to draw.
+- Make boxes agree with the captions. Give text boxes enough room for their characters at the chosen size: a long line needs a wide box, two lines need more height.
+
+For both outputs:
+- Keep the user's subjects, counts, relationships, medium, style, exclusions and intended visible wording. Fill ordinary creative gaps yourself.
+- Write descriptions in English unless the user asks for another language. Keep visible text verbatim in its original language, including punctuation, capitalisation and line breaks. A quoted sentence in the request is not necessarily text to render.
+- Write the actual copy, never placeholders such as "headline here". No quality tags such as "masterpiece" or "8k", no notes about JSON or boxes inside descriptions.
+- Keep a minimalist request minimalist.
+
+Example layout reply for "a calm campaign image for a handmade ceramic cup with the Chinese slogan 把日常,过成诗。 and two lines of supporting copy, landscape":
+{"width":1536,"height":1024,"bbox_coord_space":"abs","bbox_format":"xyxy","summary":{"meta":["product campaign","studio photography"],"canvas":"single","caption":"A warm studio campaign for a handmade ceramic cup, with an ivory backdrop, soft side lighting and restrained dark-green typography. Keep the ceramic texture tactile and the composition calm."},"items":[{"label":"object","caption":"An ivory ceramic cup with a rounded handle, fine speckled glaze and a soft contact shadow, photographed at a three-quarter angle.","bbox":[176,224,800,864]},{"label":"text","caption":"Large dark-green Chinese title in crisp, moderately heavy lettering, with generous spacing and no backing panel.","text":"把日常,过成诗。","bbox":[928,272,1408,448]},{"label":"text","caption":"Smaller dark-green Chinese supporting copy, comfortably legible on two lines.","text":"一杯温暖\n一刻从容","bbox":[928,512,1376,656]}]}"""
+
+_system_prompts = table(
+ "system_prompts",
+ column("id"),
+ column("name"),
+ column("content"),
+ column("user_id"),
+ column("is_public"),
+ column("max_tokens"),
+ column("created_at"),
+ column("updated_at"),
+)
+
+
+def _add_moss_image_enhancer_system_prompt(context: PortableMigrationContext) -> None:
+ already_there = context.conn.execute(
+ select(exists().where(_system_prompts.c.id == MOSS_IMAGE_ENHANCER_PROMPT_ID))
+ ).scalar()
+ if already_there:
+ return
+ # Only SQLite declares defaults for the timestamps; on a server the application supplies them, as here.
+ created_at = now_text()
+ context.conn.execute(
+ insert(_system_prompts).values(
+ id=MOSS_IMAGE_ENHANCER_PROMPT_ID,
+ name=MOSS_IMAGE_ENHANCER_PROMPT_NAME,
+ content=MOSS_IMAGE_ENHANCER_PROMPT_CONTENT,
+ user_id="system",
+ is_public=true(),
+ max_tokens=MOSS_IMAGE_ENHANCER_MAX_TOKENS,
+ created_at=created_at,
+ updated_at=created_at,
+ )
+ )
+
+
+def build_migration() -> PortableMigration:
+ """Seed the MOSS-Image prompt enhancer.
+
+ Depends on the migration that adds ``system_prompts.max_tokens``, which the row sets. That one is SQLite-only;
+ a server database starts from the frozen cutover schema with every SQLite-only migration recorded as applied, so
+ the dependency holds on every backend.
+ """
+ return PortableMigration(
+ id="2026_10_28_add_moss_image_enhancer_system_prompt",
+ depends_on="2026_09_09_add_system_prompt_max_tokens",
+ callback=_add_moss_image_enhancer_system_prompt,
+ )
diff --git a/invokeai/backend/model_manager/starter_models/__init__.py b/invokeai/backend/model_manager/starter_models/__init__.py
index a570e43cda..79e191b5a3 100644
--- a/invokeai/backend/model_manager/starter_models/__init__.py
+++ b/invokeai/backend/model_manager/starter_models/__init__.py
@@ -212,7 +212,11 @@ from invokeai.backend.model_manager.starter_models.minimax_h3 import (
minimax_h3_ref2va_int8_transformer,
minimax_h3_turbo_lora,
)
-from invokeai.backend.model_manager.starter_models.moss_image import moss_image_base, moss_image_sft
+from invokeai.backend.model_manager.starter_models.moss_image import (
+ moss_image_base,
+ moss_image_prompt_enhancer,
+ moss_image_sft,
+)
from invokeai.backend.model_manager.starter_models.qwen_image import (
pid_1_5_decoder_qwenimage_2kto4k,
pid_1_5_decoder_qwenimage_2kto4k_int8,
@@ -533,6 +537,7 @@ STARTER_MODELS: list[StarterModel] = [
qwen3_vl_encoder_8b,
moss_image_base,
moss_image_sft,
+ moss_image_prompt_enhancer,
wan_22_t5_encoder,
wan_22_a14b_vae,
wan_22_5b_vae,
diff --git a/invokeai/backend/model_manager/starter_models/moss_image.py b/invokeai/backend/model_manager/starter_models/moss_image.py
index f88a2465ec..e654f407bc 100644
--- a/invokeai/backend/model_manager/starter_models/moss_image.py
+++ b/invokeai/backend/model_manager/starter_models/moss_image.py
@@ -33,3 +33,15 @@ moss_image_sft = StarterModel(
),
type=ModelType.Main,
)
+
+moss_image_prompt_enhancer = StarterModel(
+ name="Gemma 4 E4B (Prompt Enhancer)",
+ base=BaseModelType.Any,
+ source="google/gemma-4-E4B-it",
+ description=(
+ "The recommended Expand Prompt model for MOSS-Image. Pair it with the seeded MOSS-Image Prompt Enhancer "
+ "system prompt, which turns a short idea into a detailed caption or, for posters and other images with "
+ "visible text, a layout. Optional. (~16 GB)"
+ ),
+ type=ModelType.TextLLM,
+)
diff --git a/invokeai/backend/moss_image/NOTICE.md b/invokeai/backend/moss_image/NOTICE.md
index 8e0e680f6d..e97e408467 100644
--- a/invokeai/backend/moss_image/NOTICE.md
+++ b/invokeai/backend/moss_image/NOTICE.md
@@ -23,7 +23,9 @@ prompt-enhancer skill, https://github.com/OpenMOSS/MOSS-Image (file
`LICENSE` is likewise the unmodified Apache-2.0 text. InvokeAI builds the layout items from canvas
regions instead of compiling a whole draft; the differences are listed in the module docstring.
`tests/backend/moss_image/test_layout.py` ports expectations from that skill's
-`test_compile_prompt.py`.
+`test_compile_prompt.py`. The seeded "MOSS-Image Prompt Enhancer" system prompt
+(`invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_10_28_add_moss_image_enhancer_system_prompt.py`)
+is derived from that skill's `SKILL.md` and `references/layout.md` at the same commit, under the same terms.
The remaining modules in this package are original InvokeAI code that drives the vendored model
in InvokeAI invocations.
diff --git a/invokeai/backend/moss_image/layout.py b/invokeai/backend/moss_image/layout.py
index 1d94797308..be3dad6c7c 100644
--- a/invokeai/backend/moss_image/layout.py
+++ b/invokeai/backend/moss_image/layout.py
@@ -6,23 +6,43 @@ convention the model was trained on. The box conversion and the serialization ar
enhancer, https://github.com/OpenMOSS/MOSS-Image at commit c1355e6b1986dfe8fba3c0455783a05899212342,
``skills/moss-image-prompt-enhancer/scripts/compile_prompt.py`` (``centered_box`` and the end of
``compile_prompt``; vocabulary in ``references/layout.md``), Apache-2.0 (see ``NOTICE.md``). The reference compiles a
-whole draft; InvokeAI builds only the items, from Regional Guidance layers, and either wraps them around the user's
-prompt or appends them to a layout the user already wrote.
+whole draft; InvokeAI builds items from Regional Guidance layers, and either wraps them around the user's prompt or
+appends them to a layout the user already wrote. It also compiles a whole draft, as the reference does, when the prompt
+is one: that is what Expand Prompt's "MOSS-Image Prompt Enhancer" system prompt asks the LLM to write for layouts.
Differences from the reference:
- A region's ``kind`` is the item ``label``. Only ``text`` regions carry ``text``: the reference also accepts it on
objects, but InvokeAI's region panel offers the visible-text field for text regions only, so a value on another
kind would be a stale one that reaches the model unseen.
-- Items have no ``tags`` or ``palette``, and their keys are always in the order ``label, caption, bbox, text``. The
+- Region items have no ``tags`` or ``palette``, and their keys are always in the order ``label, caption, bbox, text``. The
reference compiler keeps whatever order a draft has, and the sources disagree: ``USERGUIDE.md`` and
``references/layout.md`` put ``text`` before ``bbox``, while the gallery's layout prompts in the same repository
commit (``assets/images/011/parameters.json`` and ``014``) use ``label, caption, bbox, text``, which is what this
- module emits (``002`` puts ``bbox`` first).
+ module emits (``002`` puts ``bbox`` first). A compiled draft keeps its own key order, as in the reference.
+- A draft is compiled at the generation size, not its own: boxes are scaled per axis from the draft's ``width`` and
+ ``height``, which only set the coordinate frame (so they need not be multiples of 16). Expand Prompt never changes
+ the image size.
+- Drafts are read leniently, because they come from an LLM and the user cannot easily repair its output. The
+ reference rejects these; this module repairs them:
+
+ - Unknown fields (at the root, in ``summary`` or on items, such as ``id`` or ``notes``) are dropped. The reference
+ rejects them so that nothing a user wrote is lost unseen; here the alternative is a failed generation, and the
+ model would not read those fields anyway.
+ - An unknown item ``label`` becomes ``text`` when the item has non-blank ``text``, otherwise ``object``.
+ - A duplicate JSON key keeps its last value, as Python's parser does; the reference rejects duplicates.
+ - A box that leaves the canvas is clamped to it. An item whose box has no area, before or after clamping or at
+ whole-pixel precision after scaling, is dropped; only a draft left without items is an error.
+
+ Everything else is checked as in the reference, with an error naming the item: a missing or blank
+ ``summary.caption`` (it is the global description, and inventing one from the items would describe a different
+ image), a ``text`` item without text, a blank caption, malformed ``meta``, ``palette``, ``tags`` or ``canvas``, and
+ boxes that are not four finite numbers.
"""
import json
import math
+import re
from collections.abc import Sequence
from typing import Annotated, Any, Literal
@@ -32,6 +52,16 @@ from pydantic import BaseModel, Field, field_validator, model_validator
_COORD_SPACE = "abs_centralized"
_BBOX_FORMAT = "yxyx"
+# The draft's box convention: pixel edges [x1, y1, x2, y2] from the top-left corner.
+_DRAFT_COORD_SPACE = "abs"
+_DRAFT_BBOX_FORMAT = "xyxy"
+_LABELS = ("object", "character", "text")
+_CANVASES = ("single", "multi_panel", "collage")
+_SUMMARY_FIELDS = ("caption", "meta", "canvas", "palette")
+_ITEM_FIELDS = ("label", "caption", "bbox", "text", "tags", "palette")
+# LLMs like to wrap JSON in a Markdown code fence, optionally naming the language.
+_CODE_FENCE = re.compile(r"\A```[A-Za-z0-9_+-]*[ \t]*\r?\n(.*?)\r?\n?```\Z", re.DOTALL)
+
# Four pixel edges [x1, y1, x2, y2] from the top-left of the image. Strict floats take JSON ints and floats but,
# like the reference's `type(v) in (int, float)` check, reject booleans and numeric strings.
MossImageLayoutBbox = Annotated[
@@ -87,21 +117,28 @@ def build_moss_image_layout_prompt(
) -> str:
"""The prompt MOSS-Image encodes for ``prompt`` with ``regions`` placed on a ``width`` x ``height`` image.
- - No regions: ``prompt`` unchanged, whether plain text or a JSON layout.
+ - The prompt is a layout draft (a JSON object with ``"bbox_coord_space":"abs"`` and ``"bbox_format":"xyxy"``,
+ optionally in a Markdown code fence): it is compiled at ``width`` x ``height`` (see the module docstring), and
+ the regions follow its items.
+ - No regions: any other prompt unchanged, whether plain text or a compiled JSON layout.
- The prompt is a compiled layout (a JSON object with ``summary`` and ``items``): the regions are appended to its
``items``; every other key keeps its value and position. A layout in another box convention is refused rather
than mixed with these boxes.
- Anything else, including JSON that is not such a layout and text that is not valid JSON, is the caption of a new
layout: ``{"summary":{"caption":prompt},"items":[...],"bbox_coord_space":...,"bbox_format":...}``.
- Raises ValueError for a blank caption, a layout in another convention, or a region whose box leaves the image or
- has no area at whole-pixel precision.
+ Raises ValueError for an invalid draft, a blank caption, a layout in another convention, or a region whose box
+ leaves the image or has no area at whole-pixel precision.
"""
- if not regions:
+ draft = _parse_layout_draft(prompt)
+ if draft is not None:
+ layout = _compile_layout_draft(draft, width, height)
+ elif not regions:
return prompt
+ else:
+ layout = _parse_compiled_layout(prompt)
items = [_layout_item(index, region, width, height) for index, region in enumerate(regions)]
- layout = _parse_compiled_layout(prompt)
if layout is None:
if not prompt.strip():
raise ValueError("MOSS-Image layout regions need a prompt: it becomes the layout's summary caption.")
@@ -122,21 +159,124 @@ def _layout_item(index: int, region: MossImageLayoutRegion, width: int, height:
# x1 and y1 are >= 0 and below x2 and y2 (MossImageLayoutRegion), so these two bounds keep the box on the image.
if x2 > width or y2 > height:
raise ValueError(f"{name} has bbox {region.bbox}, which leaves the {width}x{height} image.")
- # Enclose the box in whole pixels, then centre it (reference `centered_box`).
+ bbox = _centered_box(x1, y1, x2, y2, width, height)
+ if bbox is None:
+ raise ValueError(f"{name} has bbox {region.bbox}, which has no area at whole-pixel precision.")
+ item: dict[str, Any] = {"label": region.kind, "caption": region.caption, "bbox": bbox}
+ if region.text is not None:
+ item["text"] = region.text
+ return item
+
+
+def _centered_box(x1: float, y1: float, x2: float, y2: float, width: int, height: int) -> list[int] | None:
+ """The box enclosed in whole pixels, then centred as [y1, x1, y2, x2] (reference ``centered_box``); None when
+ nothing is left."""
bbox = [
math.floor(round(y1, 9)) - height // 2,
math.floor(round(x1, 9)) - width // 2,
math.ceil(round(y2, 9)) - height // 2,
math.ceil(round(x2, 9)) - width // 2,
]
- if not (bbox[0] < bbox[2] and bbox[1] < bbox[3]):
- raise ValueError(f"{name} has bbox {region.bbox}, which has no area at whole-pixel precision.")
- item: dict[str, Any] = {"label": region.kind, "caption": region.caption, "bbox": bbox}
- if region.text is not None:
- item["text"] = region.text
+ return bbox if bbox[0] < bbox[2] and bbox[1] < bbox[3] else None
+
+
+def _parse_layout_draft(prompt: str) -> dict[str, Any] | None:
+ """The prompt as an absolute-pixel layout draft, or None when it is something else."""
+ source = prompt.strip()
+ fenced = _CODE_FENCE.match(source)
+ if fenced is not None:
+ source = fenced.group(1)
+ try:
+ parsed = json.loads(source, parse_constant=_reject_constant)
+ except ValueError:
+ return None
+ if (
+ isinstance(parsed, dict)
+ and parsed.get("bbox_coord_space") == _DRAFT_COORD_SPACE
+ and parsed.get("bbox_format") == _DRAFT_BBOX_FORMAT
+ ):
+ return parsed
+ return None
+
+
+def _compile_layout_draft(draft: dict[str, Any], width: int, height: int) -> dict[str, Any]:
+ """The draft as a compiled layout at ``width`` x ``height``, leniently validated (see the module docstring)."""
+ draft_width = draft.get("width")
+ draft_height = draft.get("height")
+ if not (_is_number(draft_width) and _is_number(draft_height) and draft_width > 0 and draft_height > 0):
+ raise ValueError("Layout draft: width and height must be positive numbers.")
+
+ summary = draft.get("summary")
+ if not isinstance(summary, dict) or not _is_text(summary.get("caption")):
+ raise ValueError("Layout draft: the summary has no caption.")
+ summary = {key: value for key, value in summary.items() if key in _SUMMARY_FIELDS}
+ if "canvas" in summary and summary["canvas"] not in _CANVASES:
+ raise ValueError("Layout draft: the summary canvas must be single, multi_panel or collage.")
+ for key in ("meta", "palette"):
+ if key in summary and not _is_text_list(summary[key]):
+ raise ValueError(f"Layout draft: the summary {key} must be a list of non-blank strings.")
+
+ items = draft.get("items")
+ if not isinstance(items, list) or not items:
+ raise ValueError("Layout draft: it has no items.")
+ frame = (draft_width, draft_height, width, height)
+ compiled = [
+ compiled_item
+ for index, item in enumerate(items)
+ if (compiled_item := _compile_draft_item(f"Layout draft: item {index + 1}", item, *frame)) is not None
+ ]
+ if not compiled:
+ raise ValueError("Layout draft: no item has a box on the canvas.")
+ return {"summary": summary, "items": compiled, "bbox_coord_space": _COORD_SPACE, "bbox_format": _BBOX_FORMAT}
+
+
+def _compile_draft_item(
+ name: str, item: Any, draft_width: float, draft_height: float, width: int, height: int
+) -> dict[str, Any] | None:
+ """One compiled item in the draft's key order, or None when its box has no area on the canvas."""
+ if not isinstance(item, dict):
+ raise ValueError(f"{name} is not an object.")
+ item = {key: value for key, value in item.items() if key in _ITEM_FIELDS}
+ if not _is_text(item.get("caption")):
+ raise ValueError(f"{name} has no caption.")
+ if "text" in item and not _is_text(item["text"]):
+ raise ValueError(f"{name} has blank text.")
+ if item.get("label") not in _LABELS:
+ item["label"] = "text" if "text" in item else "object"
+ if item["label"] == "text" and "text" not in item:
+ raise ValueError(f"{name} has no text.")
+ for key in ("tags", "palette"):
+ if key in item and not _is_text_list(item[key]):
+ raise ValueError(f"{name}: its {key} must be a list of non-blank strings.")
+
+ box = item.get("bbox")
+ if not (isinstance(box, list) and len(box) == 4 and all(_is_number(value) for value in box)):
+ raise ValueError(f"{name} needs a box of four numbers [x1, y1, x2, y2].")
+ x1, y1, x2, y2 = max(box[0], 0), max(box[1], 0), min(box[2], draft_width), min(box[3], draft_height)
+ if not (x1 < x2 and y1 < y2):
+ return None
+ # Per axis, so the draft's frame maps onto the whole image even when its shape differs.
+ scale_x, scale_y = width / draft_width, height / draft_height
+ bbox = _centered_box(x1 * scale_x, y1 * scale_y, x2 * scale_x, y2 * scale_y, width, height)
+ if bbox is None:
+ return None
+ item["bbox"] = bbox
return item
+def _is_number(value: Any) -> bool:
+ # Like the reference's `type(v) in (int, float)` check: booleans and numeric strings are not numbers.
+ return type(value) is int or (type(value) is float and math.isfinite(value))
+
+
+def _is_text(value: Any) -> bool:
+ return isinstance(value, str) and bool(value.strip())
+
+
+def _is_text_list(value: Any) -> bool:
+ return isinstance(value, list) and all(_is_text(entry) for entry in value)
+
+
def _parse_compiled_layout(prompt: str) -> dict[str, Any] | None:
"""The prompt as a compiled layout, or None when it is caption text."""
try:
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index e0ea5af47a..537a606fe5 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -94996,7 +94996,7 @@
"category": "conditioning",
"class": "invocation",
"classification": "prototype",
- "description": "Places regions on a MOSS-Image prompt as a JSON layout, at generation time.\n\nThe layout is built here rather than by the graph builder so the prompt that dynamic prompts and batching vary is\nthe one laid out. Without regions the prompt passes through unchanged; a prompt that already is a layout gets the\nregions appended to its items.",
+ "description": "Places regions on a MOSS-Image prompt as a JSON layout, at generation time.\n\nThe layout is built here rather than by the graph builder so the prompt that dynamic prompts and batching vary is\nthe one laid out. A layout draft with absolute pixel boxes (what Expand Prompt's MOSS-Image Prompt Enhancer writes)\nis compiled at this width and height, regions following its items. Otherwise, without regions the prompt passes\nthrough unchanged, and a prompt that already is a compiled layout gets the regions appended to its items.",
"node_pack": "invokeai",
"properties": {
"id": {
@@ -95025,7 +95025,7 @@
},
"prompt": {
"default": "",
- "description": "The image prompt: plain text becomes the layout's summary caption, a compiled layout gets the regions appended.",
+ "description": "The image prompt: plain text becomes the layout's summary caption, a compiled layout gets the regions appended, and a layout draft with absolute pixel boxes is compiled at this width and height.",
"field_kind": "input",
"input": "any",
"orig_default": "",
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index c740748360..d8fdaa0ee3 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -40080,8 +40080,9 @@ export type components = {
* @description Places regions on a MOSS-Image prompt as a JSON layout, at generation time.
*
* The layout is built here rather than by the graph builder so the prompt that dynamic prompts and batching vary is
- * the one laid out. Without regions the prompt passes through unchanged; a prompt that already is a layout gets the
- * regions appended to its items.
+ * the one laid out. A layout draft with absolute pixel boxes (what Expand Prompt's MOSS-Image Prompt Enhancer writes)
+ * is compiled at this width and height, regions following its items. Otherwise, without regions the prompt passes
+ * through unchanged, and a prompt that already is a compiled layout gets the regions appended to its items.
*/
MossImageLayoutPromptInvocation: {
/**
@@ -40103,7 +40104,7 @@ export type components = {
use_cache?: boolean;
/**
* Prompt
- * @description The image prompt: plain text becomes the layout's summary caption, a compiled layout gets the regions appended.
+ * @description The image prompt: plain text becomes the layout's summary caption, a compiled layout gets the regions appended, and a layout draft with absolute pixel boxes is compiled at this width and height.
* @default
*/
prompt?: string;
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index e1289b61c0..3a442b809d 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2823,6 +2823,9 @@
"expandPrompt": "Expand prompt",
"expandFromFirstFrame": "Describe from the first frame",
"expandFirstFrameUnreadable": "This model can't read images, so the first frame won't be used.",
+ "expandSuggestedModelAvailable": "Recommended for this model: {{model}}",
+ "expandUseSuggestedModel": "Use it",
+ "expandUseSuggestedModelLabel": "Use {{model}}",
"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",
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json
index 0e541268bd..02f94892e2 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json
@@ -375,6 +375,7 @@
"img_watermark",
"integer",
"moss_image_denoise",
+ "moss_image_layout_prompt",
"moss_image_model_loader",
"moss_image_text_encoder",
"string"
@@ -647,6 +648,7 @@
},
"core_metadata": {
"inputs": [
+ "moss_image_layout_prompt",
"negative_prompt",
"positive_prompt",
"seed"
@@ -1782,6 +1784,29 @@
"latents"
]
},
+ "moss_image_layout_prompt": {
+ "inputs": [
+ "prompt"
+ ],
+ "literalInputs": {
+ "height": [
+ 1024
+ ],
+ "is_intermediate": [
+ true
+ ],
+ "regions": [],
+ "use_cache": [
+ true
+ ],
+ "width": [
+ 1024
+ ]
+ },
+ "outputs": [
+ "value"
+ ]
+ },
"moss_image_model_loader": {
"inputs": [],
"literalInputs": {
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/mossImageLayoutCanvasGraphs.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/mossImageLayoutCanvasGraphs.json
index 3bb308fc5f..16a681e9dc 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/mossImageLayoutCanvasGraphs.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/mossImageLayoutCanvasGraphs.json
@@ -62,6 +62,16 @@
"node_id": "positive_prompt"
}
},
+ {
+ "destination": {
+ "field": "prompt",
+ "node_id": "pos_cond"
+ },
+ "source": {
+ "field": "value",
+ "node_id": "layout_prompt"
+ }
+ },
{
"destination": {
"field": "positive_conditioning",
@@ -152,6 +162,16 @@
"node_id": "core_metadata_0_i"
}
},
+ {
+ "destination": {
+ "field": "moss_image_layout_prompt",
+ "node_id": "core_metadata_0_i"
+ },
+ "source": {
+ "field": "value",
+ "node_id": "layout_prompt"
+ }
+ },
{
"destination": {
"field": "vae",
@@ -221,26 +241,6 @@
"field": "image",
"node_id": "expand_mask"
}
- },
- {
- "destination": {
- "field": "prompt",
- "node_id": "pos_cond"
- },
- "source": {
- "field": "value",
- "node_id": "layout_prompt"
- }
- },
- {
- "destination": {
- "field": "moss_image_layout_prompt",
- "node_id": "core_metadata_0_i"
- },
- "source": {
- "field": "value",
- "node_id": "layout_prompt"
- }
}
],
"id": "moss_image_layout_canvas_inpaint",
@@ -304,6 +304,47 @@
],
"width": 768
},
+ "layout_prompt": {
+ "is_intermediate": true,
+ "use_cache": true,
+ "height": 1024,
+ "id": "layout_prompt",
+ "regions": [
+ {
+ "bbox": [
+ 0,
+ 0,
+ 512,
+ 256
+ ],
+ "caption": "a hand-lettered cafe sign",
+ "kind": "text",
+ "text": "一杯温暖\n一刻从容"
+ },
+ {
+ "bbox": [
+ 64,
+ 128,
+ 256,
+ 384
+ ],
+ "caption": "a barista pouring latte art",
+ "kind": "character"
+ },
+ {
+ "bbox": [
+ 512,
+ 640,
+ 768,
+ 1024
+ ],
+ "caption": "a steaming ceramic cup",
+ "kind": "object"
+ }
+ ],
+ "type": "moss_image_layout_prompt",
+ "width": 768
+ },
"core_metadata_0_i": {
"is_intermediate": true,
"use_cache": true,
@@ -379,47 +420,6 @@
},
"type": "invokeai_img_blend",
"id": "canvas_output"
- },
- "layout_prompt": {
- "is_intermediate": true,
- "use_cache": true,
- "height": 1024,
- "id": "layout_prompt",
- "regions": [
- {
- "bbox": [
- 0,
- 0,
- 512,
- 256
- ],
- "caption": "a hand-lettered cafe sign",
- "kind": "text",
- "text": "一杯温暖\n一刻从容"
- },
- {
- "bbox": [
- 64,
- 128,
- 256,
- 384
- ],
- "caption": "a barista pouring latte art",
- "kind": "character"
- },
- {
- "bbox": [
- 512,
- 640,
- 768,
- 1024
- ],
- "caption": "a steaming ceramic cup",
- "kind": "object"
- }
- ],
- "type": "moss_image_layout_prompt",
- "width": 768
}
}
},
@@ -485,6 +485,16 @@
"node_id": "positive_prompt"
}
},
+ {
+ "destination": {
+ "field": "prompt",
+ "node_id": "pos_cond"
+ },
+ "source": {
+ "field": "value",
+ "node_id": "layout_prompt"
+ }
+ },
{
"destination": {
"field": "positive_conditioning",
@@ -575,16 +585,6 @@
"node_id": "core_metadata_0_i"
}
},
- {
- "destination": {
- "field": "prompt",
- "node_id": "pos_cond"
- },
- "source": {
- "field": "value",
- "node_id": "layout_prompt"
- }
- },
{
"destination": {
"field": "moss_image_layout_prompt",
@@ -663,34 +663,6 @@
"id": "canvas_output",
"type": "flux2_vae_decode"
},
- "core_metadata_0_i": {
- "is_intermediate": true,
- "use_cache": true,
- "cfg_scale": 3,
- "cfg_rescale_multiplier": 0,
- "generation_mode": "moss_image_txt2img",
- "height": 1024,
- "id": "core_metadata_0_i",
- "model": {
- "base": "moss-image",
- "format": "diffusers",
- "key": "moss-image-model",
- "name": "MOSS-Image",
- "type": "main",
- "hash": "blake3:moss"
- },
- "rand_device": "cpu",
- "scheduler": "euler",
- "seamless_x": false,
- "seamless_y": false,
- "steps": 50,
- "type": "core_metadata",
- "width": 768,
- "moss_image_uncond_skip_layers": [
- 22
- ],
- "clip_skip": 0
- },
"layout_prompt": {
"is_intermediate": true,
"use_cache": true,
@@ -731,6 +703,34 @@
],
"type": "moss_image_layout_prompt",
"width": 768
+ },
+ "core_metadata_0_i": {
+ "is_intermediate": true,
+ "use_cache": true,
+ "cfg_scale": 3,
+ "cfg_rescale_multiplier": 0,
+ "generation_mode": "moss_image_txt2img",
+ "height": 1024,
+ "id": "core_metadata_0_i",
+ "model": {
+ "base": "moss-image",
+ "format": "diffusers",
+ "key": "moss-image-model",
+ "name": "MOSS-Image",
+ "type": "main",
+ "hash": "blake3:moss"
+ },
+ "rand_device": "cpu",
+ "scheduler": "euler",
+ "seamless_x": false,
+ "seamless_y": false,
+ "steps": 50,
+ "type": "core_metadata",
+ "width": 768,
+ "moss_image_uncond_skip_layers": [
+ 22
+ ],
+ "clip_skip": 0
}
}
}
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts
index 58dcf0c801..eaf46787bc 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts
@@ -27,6 +27,8 @@ import {
getGenerationModelAvailabilityReasons,
getGenerationUiPolicy,
getGenerationValidationReasons,
+ getImageExpandPromptSuggestion,
+ isModelFromRepo,
getKrea2EditLoraState,
getMaxReferenceImages,
getMissingReferenceImageFormat,
@@ -194,6 +196,18 @@ describe('architecture policy, read from the backend capability table', () => {
expect(coerceSchedulerForGraph(zbase, 'lcm')).toBe('euler');
});
+ it('suggests the MOSS-Image prompt enhancer to Expand Prompt and nothing for other image bases', () => {
+ expect(getImageExpandPromptSuggestion(createModel('moss-image'))).toEqual({
+ image: null,
+ imageSystemPromptId: null,
+ modelName: 'Gemma 4 E4B (Prompt Enhancer)',
+ modelSource: 'google/gemma-4-E4B-it',
+ systemPromptId: '0f8f5b2e-1c9e-4f2a-9a4e-1f1f1f1f0011',
+ });
+ expect(getImageExpandPromptSuggestion(createModel('flux'))).toBeNull();
+ expect(getImageExpandPromptSuggestion(undefined)).toBeNull();
+ });
+
it('matches expected prompt policy per base', () => {
expect(getPromptPolicy(createModel('flux'), { cfgScale: 4, negativePromptEnabled: true })).toMatchObject({
negativeVisible: false,
@@ -2720,3 +2734,28 @@ describe('SDXL Refiner policy', () => {
expect(getGenerationModelAvailabilityReasons(sdxl, settings, [sdxl as never, refiner as never])).toEqual([]);
});
});
+
+const REPO = 'google/gemma-4-E4B-it';
+
+describe('isModelFromRepo', () => {
+ it('matches the repo in its Hugging Face forms', () => {
+ expect(isModelFromRepo('google/gemma-4-E4B-it', REPO)).toBe(true);
+ expect(isModelFromRepo('Google/Gemma-4-e4b-IT', REPO)).toBe(true);
+ expect(isModelFromRepo('google/gemma-4-E4B-it::text_encoder', REPO)).toBe(true);
+ expect(isModelFromRepo('https://huggingface.co/google/gemma-4-E4B-it/tree/main', REPO)).toBe(true);
+ });
+
+ it('matches a local folder named like the repo', () => {
+ expect(isModelFromRepo('E:/ModelStuffSSD/gemma-4-E4B-it', REPO)).toBe(true);
+ expect(isModelFromRepo('E:\\ModelStuffSSD\\GEMMA-4-E4B-IT\\', REPO)).toBe(true);
+ expect(isModelFromRepo('/models/gemma-4-E4B-it', REPO)).toBe(true);
+ });
+
+ it('refuses other repos, other folders and a missing source', () => {
+ expect(isModelFromRepo('google/gemma-4-E2B-it', REPO)).toBe(false);
+ expect(isModelFromRepo('someone/gemma-4-E4B-it', REPO)).toBe(false);
+ expect(isModelFromRepo('E:/ModelStuffSSD/gemma-4-E4B-it-q4', REPO)).toBe(false);
+ expect(isModelFromRepo('E:/ModelStuffSSD/gemma-4-E4B-it/model.safetensors', REPO)).toBe(false);
+ expect(isModelFromRepo(null, REPO)).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
index 5e70b3203d..dcfeff1b76 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
@@ -18,6 +18,7 @@ import {
import { SEED_MAX } from '@platform/core/seed';
import type {
+ ExpandPromptSuggestion,
ExternalGenerationMode,
GenerateModelConfig,
GenerateReferenceImage,
@@ -368,6 +369,63 @@ export const getPromptPolicy = (
};
};
+const HF_REPO_ID = /^[A-Za-z0-9][\w.-]*\/[\w.-]+$/;
+
+/**
+ * Whether an installed model's source is the Hugging Face repo `repoId`: the repo itself (also `repo::subfolder` or a
+ * huggingface.co URL), or a local folder named like the repo, as an in-place install of a downloaded copy is.
+ * Case-insensitive, as Hugging Face repo ids are.
+ */
+export const isModelFromRepo = (source: string | null | undefined, repoId: string): boolean => {
+ if (!source) {
+ return false;
+ }
+ const wanted = repoId.toLowerCase();
+ const withoutSubfolder = source.split('::')[0]!.trim();
+ const hfPath = /^https?:\/\/(?:www\.)?huggingface\.co\/([^?#]+)/i.exec(withoutSubfolder)?.[1];
+ const candidate = (hfPath ? hfPath.split('/').slice(0, 2).join('/') : withoutSubfolder).replace(/[/\\]+$/, '');
+ if (HF_REPO_ID.test(candidate)) {
+ return candidate.toLowerCase() === wanted;
+ }
+ const folder = candidate.split(/[/\\]/).pop() ?? '';
+ return folder.toLowerCase() === wanted.split('/').pop();
+};
+
+/** A family's released prompt enhancer, which Expand Prompt preselects for a text-only rewrite. */
+interface ImagePromptEnhancer {
+ /** Starter source of the enhancer model; an installed text LLM with this source is preselected. */
+ modelSource: string;
+ /** The starter model's name, for the hint shown when it is not installed. */
+ modelName: string;
+ /** Seeded public system prompt. */
+ systemPromptId: string;
+}
+
+const IMAGE_PROMPT_ENHANCERS: Partial<Record<string, ImagePromptEnhancer>> = {
+ // The OpenMOSS prompt-enhancer skill writes a layout draft the `moss_image_layout_prompt` node compiles.
+ 'moss-image': {
+ modelName: 'Gemma 4 E4B (Prompt Enhancer)',
+ modelSource: 'google/gemma-4-E4B-it',
+ systemPromptId: '0f8f5b2e-1c9e-4f2a-9a4e-1f1f1f1f0011',
+ },
+};
+
+/** What Expand Prompt starts from for this image family, or null when the family ships no enhancer. */
+export const getImageExpandPromptSuggestion = (
+ model: GenerateModelConfig | undefined
+): ExpandPromptSuggestion | null => {
+ const enhancer = model?.type === 'main' ? IMAGE_PROMPT_ENHANCERS[model.base] : undefined;
+ return enhancer
+ ? {
+ image: null,
+ imageSystemPromptId: null,
+ modelName: enhancer.modelName,
+ modelSource: enhancer.modelSource,
+ systemPromptId: enhancer.systemPromptId,
+ }
+ : null;
+};
+
export const getGenerationUiPolicy = (model: GenerateModelConfig | undefined) => {
const config = getBaseGenerationConfig(model);
const seedVisible = model?.type === 'external_image_generator' ? model.capabilities?.supports_seed === true : true;
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts
index c3e3f0797a..975fac43b8 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts
@@ -8,6 +8,7 @@ import type { AddRegionalGuidanceOptions, RegionalGuidanceInput, RegionalReferen
import {
addRegionalGuidance,
+ getLayoutDraftRejectionReason,
getLayoutPromptRejectionReason,
getLayoutRegionIssue,
getRegionalGuidanceRejectionReason,
@@ -639,3 +640,111 @@ describe('getLayoutPromptRejectionReason', () => {
expect(getLayoutPromptRejectionReason({ base: 'z-image', prompt: '', regions: [placeable] })).toBeNull();
});
});
+
+describe('getLayoutDraftRejectionReason', () => {
+ // The 1536x1024 example from the OpenMOSS prompt-enhancer skill's layout reference.
+ const draft = {
+ width: 1536,
+ height: 1024,
+ bbox_coord_space: 'abs',
+ bbox_format: 'xyxy',
+ summary: {
+ meta: ['product campaign', 'studio photography'],
+ canvas: 'single',
+ caption:
+ 'A warm studio campaign for a handmade ceramic cup, with an ivory backdrop, soft side lighting and restrained dark-green typography. Keep the ceramic texture tactile and the composition calm.',
+ },
+ items: [
+ {
+ label: 'object',
+ caption:
+ 'An ivory ceramic cup with a rounded handle, fine speckled glaze and a soft contact shadow, photographed at a three-quarter angle.',
+ bbox: [176, 224, 800, 864],
+ },
+ {
+ label: 'text',
+ caption:
+ 'Large dark-green Chinese title in crisp, moderately heavy lettering, with generous spacing and no backing panel.',
+ text: '把日常,过成诗。',
+ bbox: [928, 272, 1408, 448],
+ },
+ {
+ label: 'text',
+ caption: 'Smaller dark-green Chinese supporting copy, comfortably legible on two lines.',
+ text: '一杯温暖\n一刻从容',
+ bbox: [928, 512, 1376, 656],
+ },
+ ],
+ };
+ const reason = (prompt: string, base = 'moss-image') =>
+ getLayoutDraftRejectionReason({ base, positivePrompt: prompt });
+
+ it('accepts a well-formed draft, bare or fenced, and leaves plain prompts and other bases alone', () => {
+ expect(reason(JSON.stringify(draft, null, 2))).toBeNull();
+ expect(reason(` \`\`\`json\n${JSON.stringify(draft, null, 2)}\n\`\`\`\n`)).toBeNull();
+ expect(reason('a cafe with {curly} braces and "bbox_coord_space" words')).toBeNull();
+ expect(reason('{"bbox_coord_space": ', 'z-image')).toBeNull();
+ });
+
+ it('passes compiled layouts, fenced or not, with or without regions', () => {
+ const compiled = {
+ bbox_coord_space: 'abs_centralized',
+ bbox_format: 'yxyx',
+ summary: { caption: 'a cafe' },
+ items: [{ bbox: [-288, -592, 352, 32], caption: 'a cup', label: 'object' }],
+ };
+ expect(reason(JSON.stringify(compiled))).toBeNull();
+ expect(reason(JSON.stringify({ ...compiled, items: [] }))).toBeNull();
+ expect(reason(`\`\`\`json\r\n${JSON.stringify(compiled, null, 2)}\r\n\`\`\``)).toBeNull();
+ expect(reason('{"bbox_coord_space": "abs_centralized", "items": [')).toBeNull();
+ });
+
+ it('checks a draft both as authored and as the template makes it', () => {
+ const notJson =
+ 'The prompt looks like a MOSS-Image layout draft but is not valid JSON. Run Expand Prompt again or fix it.';
+ const prefix = { id: 'photo', name: 'Photo', negativePrompt: '', positivePrompt: 'photo of {prompt}' };
+ const scaffold = {
+ id: 'poster',
+ name: 'Poster',
+ negativePrompt: '',
+ positivePrompt: JSON.stringify({ ...draft, summary: { ...draft.summary, caption: '{prompt}' } }),
+ };
+ const withTemplate = (positivePrompt: string, promptTemplate: typeof prefix) =>
+ getLayoutDraftRejectionReason({ base: 'moss-image', positivePrompt, promptTemplate });
+
+ expect(withTemplate('{"bbox_coord_space": "abs", "items": [', prefix)).toBe(notJson);
+ expect(withTemplate('a "neon" sign', scaffold)).toBe(notJson);
+ expect(withTemplate('a neon sign', scaffold)).toBeNull();
+ expect(withTemplate(JSON.stringify(draft), prefix)).toBeNull();
+ });
+
+ it('refuses a draft in a box format the layout node does not compile', () => {
+ expect(reason(JSON.stringify({ ...draft, bbox_format: 'xywh' }))).toBe(
+ 'The MOSS-Image layout draft in the prompt uses a bbox_format other than xyxy. Run Expand Prompt again or fix it.'
+ );
+ });
+
+ it('refuses a draft that does not parse', () => {
+ expect(reason('```json\n{"bbox_coord_space": "abs", "items": [\n```')).toBe(
+ 'The prompt looks like a MOSS-Image layout draft but is not valid JSON. Run Expand Prompt again or fix it.'
+ );
+ });
+
+ it('refuses a draft missing what the layout node starts from', () => {
+ const message =
+ 'The MOSS-Image layout draft in the prompt needs a summary with a caption, at least one item, and a numeric width and height. Run Expand Prompt again or fix it.';
+ const { summary: _summary, ...withoutSummary } = draft;
+ for (const broken of [
+ withoutSummary,
+ { ...draft, summary: 'a cafe' },
+ { ...draft, summary: null },
+ { ...draft, summary: { ...draft.summary, caption: ' ' } },
+ { ...draft, items: [] },
+ { ...draft, items: {} },
+ { ...draft, width: '1536' },
+ { ...draft, height: null },
+ ]) {
+ expect(reason(JSON.stringify(broken))).toBe(message);
+ }
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts
index 84f58eb588..d60c565a9e 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts
@@ -1,8 +1,10 @@
import type { BackendGraphContract, BackendInvocationContract } from '@features/generation/core/contracts';
+import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';
import { getArchitectureFeatures } from '@features/generation/core/architectureCapabilities';
import { addEdge, addNode } from '@features/generation/core/graphBuilder';
import { COMPEL_PROMPT_NODE_TYPES } from '@features/generation/core/prompt/compel';
+import { getEffectivePositivePrompt, unwrapPromptFence } from '@features/generation/core/promptTemplates';
import type { Rect } from './types';
@@ -127,6 +129,66 @@ export const getLayoutPromptRejectionReason = (params: {
return `${support.label} needs a prompt to place regional guidance in its layout. Enter a prompt or disable the regional guidance layers.`;
};
+const LOOKS_LIKE_LAYOUT_DRAFT = /"bbox_coord_space"\s*:\s*"abs"/;
+const LAYOUT_DRAFT_FIX = 'Run Expand Prompt again or fix it.';
+
+const getDraftRejectionReason = (prompt: string): string | null => {
+ const body = unwrapPromptFence(prompt);
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(body);
+ } catch {
+ return body.trimStart().startsWith('{') && LOOKS_LIKE_LAYOUT_DRAFT.test(body)
+ ? `The prompt looks like a MOSS-Image layout draft but is not valid JSON. ${LAYOUT_DRAFT_FIX}`
+ : null;
+ }
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
+ return null;
+ }
+ const draft = parsed as Record<string, unknown>;
+ if (draft.bbox_coord_space !== 'abs') {
+ return null;
+ }
+ if (draft.bbox_format !== 'xyxy') {
+ return `The MOSS-Image layout draft in the prompt uses a bbox_format other than xyxy. ${LAYOUT_DRAFT_FIX}`;
+ }
+ const summary =
+ typeof draft.summary === 'object' && draft.summary !== null ? (draft.summary as Record<string, unknown>) : null;
+ if (
+ typeof summary?.caption !== 'string' ||
+ !summary.caption.trim() ||
+ !Array.isArray(draft.items) ||
+ draft.items.length === 0 ||
+ typeof draft.width !== 'number' ||
+ typeof draft.height !== 'number'
+ ) {
+ return `The MOSS-Image layout draft in the prompt needs a summary with a caption, at least one item, and a numeric width and height. ${LAYOUT_DRAFT_FIX}`;
+ }
+ return null;
+};
+
+/**
+ * Why a MOSS-Image prompt holding a layout draft (as Expand Prompt writes it: a JSON object with
+ * `bbox_coord_space: "abs"`, optionally in a ``` fence) cannot be compiled, or null. Plain text and compiled layouts
+ * (`abs_centralized`) pass. Only the shape the layout node needs to start is checked; the backend validates the boxes.
+ * Both the authored prompt and the one the template makes of it are checked: template text around a broken draft
+ * would hide it, and a template that is itself a draft can break around authored text (an unescaped quote).
+ */
+export const getLayoutDraftRejectionReason = (params: {
+ base: string;
+ positivePrompt: string;
+ promptTemplate?: PromptTemplateSnapshot | null;
+}): string | null => {
+ if (getRegionalGuidanceSupport(params.base)?.mode !== 'layout') {
+ return null;
+ }
+ const effectivePrompt = getEffectivePositivePrompt(params.positivePrompt, params.promptTemplate ?? null);
+ return (
+ getDraftRejectionReason(params.positivePrompt) ??
+ (effectivePrompt === params.positivePrompt ? null : getDraftRejectionReason(effectivePrompt))
+ );
+};
+
/** A resolved reference-image (component) model identifier — the backend model field shape. */
export interface RegionalReferenceModel {
key: string;
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
index 233f09e3c4..bc11e83fda 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
@@ -2281,13 +2281,12 @@ describe('compileCanvasGraph — regional guidance', () => {
]);
});
- it('adds no layout node, even on a blank prompt, when no region can be placed', () => {
+ it('places no region, even on a blank prompt, when no region can be placed', () => {
const { backendGraph } = compile(mossImageModel, 'txt2img', {
regionalGuidance: [region('empty', { maskBounds: { height: 0, width: 0, x: 0, y: 0 } })],
});
- expect(backendGraph.nodes.layout_prompt).toBeUndefined();
- expect(getEdge(backendGraph, 'pos_cond', 'prompt')?.source.node_id).toBe('positive_prompt');
+ expect(backendGraph.nodes.layout_prompt?.regions).toEqual([]);
});
it('blocks MOSS-Image regions on a blank prompt unless a prompt template supplies one', () => {
@@ -2383,11 +2382,12 @@ describe('compileCanvasGraph — regional guidance', () => {
);
});
- it('keeps a MOSS-Image canvas graph without regions on the plain prompt', () => {
+ it('routes a MOSS-Image canvas prompt without regions through the layout node at the denoise size', () => {
const { backendGraph } = compile(mossImageModel, 'txt2img');
- expect(backendGraph.nodes.layout_prompt).toBeUndefined();
- expect(getEdge(backendGraph, 'pos_cond', 'prompt')?.source.node_id).toBe('positive_prompt');
+ expect(backendGraph.nodes.layout_prompt).toMatchObject({ height: 1024, regions: [], width: 768 });
+ expect(getEdge(backendGraph, 'layout_prompt', 'prompt')?.source.node_id).toBe('positive_prompt');
+ expect(getEdge(backendGraph, 'pos_cond', 'prompt')?.source.node_id).toBe('layout_prompt');
});
});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts
index 0e6ed97c77..c02e8b056e 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts
@@ -908,45 +908,20 @@ const toLayoutElement = (
/**
* MOSS-Image regions: each becomes a box around its mask, scaled from bbox pixels to the size the denoiser generates
- * (which PiD can shrink below the processing size) and clamped to it. A `layout_prompt` node between the global prompt
- * and the positive encoder assembles them at run time, so batch prompt variation still flows through
- * `positive_prompt`; core metadata records the assembled prompt. Regions the layout cannot place are left out, and
- * without any the graph stays untouched.
+ * (which PiD can shrink below the processing size) and clamped to it. The base graph's `layout_prompt` node assembles
+ * them with the global prompt at run time; regions the layout cannot place are left out.
*/
const addLayoutRegions = (graph: BackendGraphContract, options: AddLayoutRegionsOptions): void => {
- const posCond = graph.nodes.pos_cond;
- if (!posCond) {
- throw new Error('addLayoutRegions: base graph is missing the positive conditioning node.');
+ const layoutPrompt = graph.nodes.layout_prompt;
+ if (!layoutPrompt) {
+ throw new Error('addLayoutRegions: base graph is missing the layout prompt node.');
}
const size = getDenoiseSize(graph, requireDenoise(graph));
const scale = { x: size.width / options.bbox.width, y: size.height / options.bbox.height };
- const elements = options.regions.flatMap((region) => toLayoutElement(region, scale, size) ?? []);
- if (elements.length === 0) {
- return;
- }
- const promptEdge = graph.edges.find(
- (edge) =>
- edge.source.node_id === 'positive_prompt' &&
- edge.destination.node_id === posCond.id &&
- edge.destination.field === 'prompt'
- );
- if (!promptEdge) {
- throw new Error('addLayoutRegions: the positive prompt does not feed the positive conditioning.');
- }
-
- const layoutPrompt = addNode(graph, {
- height: size.height,
- id: 'layout_prompt',
- regions: elements,
- type: 'moss_image_layout_prompt',
- width: size.width,
- });
- promptEdge.destination = { field: 'prompt', node_id: layoutPrompt.id };
- addEdge(graph, layoutPrompt, 'value', posCond, 'prompt');
- const metadata = findMetadataNode(graph);
- if (metadata) {
- addEdge(graph, layoutPrompt, 'value', metadata, 'moss_image_layout_prompt');
- }
+ // The frame and the boxes come from one size, so they cannot drift apart.
+ layoutPrompt.width = size.width;
+ layoutPrompt.height = size.height;
+ layoutPrompt.regions = options.regions.flatMap((region) => toLayoutElement(region, scale, size) ?? []);
};
/** Throw the first validation reason. */
diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
index f1a513880e..394ddd7005 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.test.ts
@@ -20,6 +20,17 @@ describe('hasDynamicPromptSyntax', () => {
expect(hasDynamicPromptSyntax('multi\nline {a|b}')).toBe(true);
});
+ it('never treats a JSON prompt as dynamic, fenced or not', () => {
+ const draft =
+ '{"width":1024,"height":1536,"bbox_coord_space":"abs","bbox_format":"xyxy","summary":{"caption":"a #1 poster"},"items":[{"caption":"__colors__"}]}';
+ expect(hasDynamicPromptSyntax(draft)).toBe(false);
+ expect(hasDynamicPromptSyntax(`\`\`\`json\n${draft}\n\`\`\``)).toBe(false);
+ expect(hasDynamicPromptSyntax('[{"caption": "a {red|green} ball"}]')).toBe(false);
+ // Braces that do not form JSON are still variants.
+ expect(hasDynamicPromptSyntax('{"caption": a {red|green} ball}')).toBe(true);
+ expect(hasDynamicPromptSyntax('a poster {"caption": "x"}')).toBe(true);
+ });
+
it('detects a wildcard reference', () => {
expect(hasDynamicPromptSyntax('a __colors__ ball')).toBe(true);
expect(hasDynamicPromptSyntax('prefix__name__')).toBe(true);
@@ -273,6 +284,29 @@ describe('planGenerateSubmission', () => {
expect(suppressed.effectivePrompts.negativePrompt).toBe('blurry, lowres');
});
+ it('sends a JSON prompt whole and unexpanded under a template, with the negative side templated', () => {
+ const layout =
+ '{"bbox_coord_space":"abs_centralized","bbox_format":"yxyx","summary":{"caption":"a {red|green} cup"},"items":[]}';
+ const promptTemplate = {
+ id: 't',
+ name: 'Photo',
+ negativePrompt: '{prompt}, lowres',
+ positivePrompt: 'photo of {prompt}',
+ };
+ const plan = planGenerateSubmission(
+ source({ dynamicPromptsSeedBehaviour: 'per-image', positivePrompt: layout, promptTemplate }),
+ ['stale expansion']
+ );
+
+ expect(plan.submission).toEqual({
+ batchCount: 2,
+ negativePrompt: 'blurry, lowres',
+ positivePrompt: layout,
+ seed: 10,
+ seedStep: plan.seedPlan.step,
+ });
+ });
+
it('sends an expansion and its seed behaviour only for a prompt with dynamic syntax', () => {
const expansion = ['a red cat', 'a green cat'];
const expanded = planGenerateSubmission(
diff --git a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
index 5296729523..0f7b376f95 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/dynamicPrompts.ts
@@ -2,7 +2,7 @@ import { planSeedSubmission, type SeedMode, type SeedStep, type SeedSubmissionPl
import type { EffectivePrompts, PromptTemplateSnapshot } from './promptTemplates';
-import { getEffectivePrompts } from './promptTemplates';
+import { getEffectivePrompts, isJsonPrompt } from './promptTemplates';
const SEED_MAX = 4_294_967_295;
@@ -275,9 +275,13 @@ export const getWildcardNameError = (
return null;
};
-/** # is expansion syntax because the backend strips comments without an escape, even without other dynamic syntax. */
+/**
+ * # is expansion syntax because the backend strips comments without an escape, even without other dynamic syntax. A
+ * JSON prompt is never expanded: its braces are data.
+ */
export const hasDynamicPromptSyntax = (prompt: string): boolean =>
- /\{[\s\S]*\}/.test(prompt) || prompt.includes('#') || scanWildcardReferences(prompt).length > 0;
+ (/\{[\s\S]*\}/.test(prompt) || prompt.includes('#') || scanWildcardReferences(prompt).length > 0) &&
+ !isJsonPrompt(prompt);
export const isDynamicPromptsSeedBehaviour = (value: unknown): value is DynamicPromptsSeedBehaviour =>
value === 'per-iteration' || value === 'per-image';
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
index 422d9da89a..d1fe813291 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
@@ -1625,6 +1625,24 @@ describe('MOSS-Image graphs', () => {
expect(getNodeByType(graph, 'core_metadata')?.generation_mode).toBe('moss_image_txt2img');
});
+ it('routes the positive prompt through the layout node, which compiles a layout draft at the denoise size', () => {
+ const graph = compile(mossDiffusers, { height: 768, width: 1280 });
+ const metadata = getNodeByType(graph, 'core_metadata')!;
+
+ expect(graph.nodes.layout_prompt).toMatchObject({
+ height: 768,
+ regions: [],
+ type: 'moss_image_layout_prompt',
+ width: 1280,
+ });
+ expect(getEdge(graph, 'layout_prompt', 'prompt')?.source).toEqual({ field: 'value', node_id: 'positive_prompt' });
+ expect(getEdge(graph, 'pos_cond', 'prompt')?.source).toEqual({ field: 'value', node_id: 'layout_prompt' });
+ expect(getEdge(graph, metadata.id, 'moss_image_layout_prompt')?.source).toEqual({
+ field: 'value',
+ node_id: 'layout_prompt',
+ });
+ });
+
it('encodes the negative prompt only while CFG runs the negative branch', () => {
const withCfg = compile(mossDiffusers, { cfgScale: 4 });
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
index 6c0ae4a563..f1b7d2cba9 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
@@ -1663,7 +1663,18 @@ const buildMossImageGraph = (
// The denoise node reads the VAE's BatchNorm statistics, which define the latent space it works in.
addEdge(graph, modelLoader, 'vae', denoise, 'vae');
addEdge(graph, modelLoader, 'qwen3_5_encoder', posCond, 'qwen3_5_encoder');
- addEdge(graph, positivePrompt, 'value', posCond, 'prompt');
+ // The layout node compiles a layout draft (e.g. from Expand Prompt) and canvas regions into the model's layout
+ // prompt at run time, and passes plain text through. Canvas fills `regions`; batch prompt variation still flows
+ // through `positive_prompt`.
+ const layoutPrompt = addNode(graph, {
+ height: denoiseSize.height,
+ id: 'layout_prompt',
+ regions: [],
+ type: 'moss_image_layout_prompt',
+ width: denoiseSize.width,
+ });
+ addEdge(graph, positivePrompt, 'value', layoutPrompt, 'prompt');
+ addEdge(graph, layoutPrompt, 'value', posCond, 'prompt');
addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');
if (negCond) {
@@ -1679,6 +1690,10 @@ const buildMossImageGraph = (
vae: vaeModel ?? undefined,
...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),
});
+ const metadata = Object.values(graph.nodes).find((node) => node.type === 'core_metadata');
+ if (metadata) {
+ addEdge(graph, layoutPrompt, 'value', metadata, 'moss_image_layout_prompt');
+ }
return graph;
};
diff --git a/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.test.ts b/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.test.ts
index a1f4b4d9ca..4192c2e7e8 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.test.ts
@@ -4,6 +4,7 @@ import {
applyPromptTemplate,
flattenPromptTemplateExpansion,
getEffectivePrompts,
+ getPositivePromptTemplateChunks,
getPromptTemplateChunks,
isCanonicalPromptTemplateSnapshot,
sanitizePromptTemplateSnapshot,
@@ -31,6 +32,20 @@ describe('prompt template expansion', () => {
expect(applyPromptTemplate(templatePrompt, prompt)).toBe(expected);
});
+ it('keeps a JSON positive prompt whole under a template and still applies the negative side', () => {
+ const layout = '```json\n{"bbox_coord_space":"abs_centralized","items":[]}\n```';
+ expect(getEffectivePrompts({ negativePrompt: 'noise', positivePrompt: layout, promptTemplate: template })).toEqual({
+ negativePrompt: 'noise, blurry',
+ positivePrompt: layout,
+ });
+ });
+
+ it('splits the merged positive view as it generates, with a JSON prompt whole', () => {
+ const layout = '{"bbox_coord_space":"abs_centralized","items":[]}';
+ expect(getPositivePromptTemplateChunks(layout, template)).toEqual(['', layout, '']);
+ expect(getPositivePromptTemplateChunks('owl', template)).toEqual(['photo of ', 'owl', ', 35mm']);
+ });
+
it('merges both prompt sides and passes them through when no template is active', () => {
expect(getEffectivePrompts({ negativePrompt: 'noise', positivePrompt: 'owl' })).toEqual({
negativePrompt: 'noise',
diff --git a/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.ts b/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.ts
index b3a609574b..b0d32aad17 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/promptTemplates.ts
@@ -1,5 +1,31 @@
export const PROMPT_TEMPLATE_PLACEHOLDER = '{prompt}';
+// Same pattern as the backend layout node: the whole prompt is one fenced block, as language models write JSON.
+const PROMPT_FENCE = /^```[A-Za-z0-9_+-]*[ \t]*\r?\n([\s\S]*?)\r?\n?```$/;
+
+/** The trimmed prompt, or the body of the one ``` block it consists of. */
+export const unwrapPromptFence = (prompt: string): string => {
+ const trimmed = prompt.trim();
+ return PROMPT_FENCE.exec(trimmed)?.[1] ?? trimmed;
+};
+
+/**
+ * Whether the prompt (unwrapped) is a JSON object or array, such as a MOSS-Image layout or a structured prompt. Its
+ * braces are data, never dynamic-prompt syntax.
+ */
+export const isJsonPrompt = (prompt: string): boolean => {
+ const body = unwrapPromptFence(prompt).trim();
+ if (!body.startsWith('{') && !body.startsWith('[')) {
+ return false;
+ }
+ try {
+ const parsed: unknown = JSON.parse(body);
+ return typeof parsed === 'object' && parsed !== null;
+ } catch {
+ return false;
+ }
+};
+
export interface PromptTemplateSnapshot {
id: string;
name: string;
@@ -24,6 +50,21 @@ export const applyPromptTemplate = (templatePrompt: string, prompt: string): str
? templatePrompt.replace(PROMPT_TEMPLATE_PLACEHOLDER, () => prompt)
: `${prompt} ${templatePrompt}`;
+/**
+ * The template's positive side as it applies to `prompt`. Text around a JSON prompt (a MOSS-Image layout, a structured
+ * prompt) would stop it parsing, so a JSON prompt gets the bare placeholder and stays whole.
+ */
+const getPositiveTemplatePrompt = (template: PromptTemplateSnapshot, prompt: string): string =>
+ isJsonPrompt(prompt) ? PROMPT_TEMPLATE_PLACEHOLDER : template.positivePrompt;
+
+/**
+ * The positive prompt that generates: the authored prompt inside the template's positive side. Submission, the prompt
+ * box's merged view and dynamic-prompt previews and counts all read it, so they cannot disagree. Layout-draft
+ * validation checks it and the authored prompt, as template text around a broken draft would hide it.
+ */
+export const getEffectivePositivePrompt = (prompt: string, template: PromptTemplateSnapshot | null): string =>
+ template ? applyPromptTemplate(getPositiveTemplatePrompt(template, prompt), prompt) : prompt;
+
export const getEffectivePrompts = (settings: AuthoredPrompts): EffectivePrompts => {
const { negativePrompt, positivePrompt, promptTemplate } = settings;
@@ -33,7 +74,7 @@ export const getEffectivePrompts = (settings: AuthoredPrompts): EffectivePrompts
return {
negativePrompt: applyPromptTemplate(promptTemplate.negativePrompt, negativePrompt),
- positivePrompt: applyPromptTemplate(promptTemplate.positivePrompt, positivePrompt),
+ positivePrompt: getEffectivePositivePrompt(positivePrompt, promptTemplate),
};
};
@@ -67,6 +108,12 @@ export const getPromptTemplateChunks = (prompt: string, templatePrompt: string):
return [before ?? '', prompt, after.join(PROMPT_TEMPLATE_PLACEHOLDER)];
};
+/** {@link getEffectivePositivePrompt} split around the authored prompt, for the merged view. */
+export const getPositivePromptTemplateChunks = (
+ prompt: string,
+ template: PromptTemplateSnapshot
+): [string, string, string] => getPromptTemplateChunks(prompt, getPositiveTemplatePrompt(template, prompt));
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
diff --git a/invokeai/frontend/webv2/src/features/generation/graph.ts b/invokeai/frontend/webv2/src/features/generation/graph.ts
index 8398e60a00..7fc1005721 100644
--- a/invokeai/frontend/webv2/src/features/generation/graph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/graph.ts
@@ -30,6 +30,7 @@ export {
isControlModelUsableForKind,
} from './core/canvas/controlValidation';
export {
+ getLayoutDraftRejectionReason,
getLayoutPromptRejectionReason,
getLayoutRegionIssue,
getRegionalGuidanceRejectionReason,
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.tsx
index e4b0eb8821..b5a8c1cf37 100644
--- 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.tsx
@@ -22,7 +22,17 @@ await i18n.use(initReactI18next).init({
fallbackLng: 'en',
lng: 'en',
resources: {
- en: { translation: { widgets: { generate: { expandSuggestedModelMissing: '{{model}} is not installed' } } } },
+ en: {
+ translation: {
+ widgets: {
+ generate: {
+ expandSuggestedModelAvailable: 'Recommended: {{model}}',
+ expandSuggestedModelMissing: '{{model}} is not installed',
+ expandUseSuggestedModelLabel: 'Use {{model}}',
+ },
+ },
+ },
+ },
},
});
@@ -36,6 +46,16 @@ const ENHANCER = {
type: 'text_llm',
};
+const MOSS_ENHANCER = { ...ENHANCER, key: 'e4b', name: 'Gemma 4 E4B', source: 'google/gemma-4-E4B-it' };
+const MOSS_PROMPT_ID = '0f8f5b2e-1c9e-4f2a-9a4e-1f1f1f1f0011';
+const MOSS_SUGGESTION: ExpandPromptSuggestion = {
+ image: null,
+ imageSystemPromptId: null,
+ modelName: 'Gemma 4 E4B (Prompt Enhancer)',
+ modelSource: 'google/gemma-4-E4B-it',
+ systemPromptId: MOSS_PROMPT_ID,
+};
+
const prompt = (id: string, content: string) => ({
content,
id,
@@ -47,7 +67,12 @@ const prompt = (id: string, content: string) => ({
const VISION_A = { base: 'any', key: 'llava-a', name: 'LLaVA A', type: 'llava_onevision' };
const VISION_B = { base: 'any', key: 'llava-b', name: 'LLaVA B', type: 'llava_onevision' };
-const PROMPTS = [prompt('default', 'DEFAULT'), prompt('t2v', 'T2V'), prompt('i2v', 'I2V')];
+const PROMPTS = [
+ prompt('default', 'DEFAULT'),
+ prompt('t2v', 'T2V'),
+ prompt('i2v', 'I2V'),
+ prompt(MOSS_PROMPT_ID, 'MOSS'),
+];
const FRAME = { height: 512, image_name: 'frame.png', width: 768 };
const LTX_SUGGESTION: ExpandPromptSuggestion = {
@@ -173,7 +198,19 @@ afterEach(async () => {
root = null;
});
-const renderField = (suggestion: ExpandPromptSuggestion | null, savedPromptModels?: SavedPromptModels) =>
+/** What the field was last rendered with, so a saved slot can render its own change back. */
+let rendered: {
+ projectId: string;
+ savedPromptModels: SavedPromptModels | undefined;
+ suggestion: ExpandPromptSuggestion | null;
+} | null = null;
+
+const renderField = (
+ suggestion: ExpandPromptSuggestion | null,
+ savedPromptModels?: SavedPromptModels,
+ projectId = 'project-1'
+) => {
+ rendered = { projectId, savedPromptModels, suggestion };
root?.render(
<I18nextProvider i18n={i18n}>
<QueryClientProvider client={new QueryClient()}>
@@ -183,7 +220,7 @@ const renderField = (suggestion: ExpandPromptSuggestion | null, savedPromptModel
expandPromptSuggestion={suggestion}
heightPx={96}
loras={[]}
- projectId="project-1"
+ projectId={projectId}
savedPromptModels={savedPromptModels}
selectedModel={undefined}
showSyntaxHighlighting={false}
@@ -197,6 +234,7 @@ const renderField = (suggestion: ExpandPromptSuggestion | null, savedPromptModel
</QueryClientProvider>
</I18nextProvider>
);
+};
const renderAndOpen = async (
suggestion: ExpandPromptSuggestion | null,
@@ -211,12 +249,15 @@ const renderAndOpen = async (
await act(() => host?.querySelector<HTMLButtonElement>(`[aria-label="${trigger}"]`)?.click());
};
-const savedModels = (overrides: Partial<SavedPromptModels> = {}): SavedPromptModels => ({
- expandPromptModelKey: null,
- imageToPromptModelKey: null,
- onChange: vi.fn(),
- ...overrides,
-});
+/** A saved slot that, like Generate's draft, holds a saved pick by the next render. */
+const savedModels = (overrides: Partial<SavedPromptModels> = {}): SavedPromptModels => {
+ const onChange = vi.fn((patch: Partial<SavedPromptModels>) => {
+ if (rendered?.savedPromptModels?.onChange === onChange) {
+ renderField(rendered.suggestion, { ...rendered.savedPromptModels, ...patch }, rendered.projectId);
+ }
+ });
+ return { expandPromptModelKey: null, imageToPromptModelKey: null, ...overrides, onChange };
+};
const select = (label: string) => document.querySelector<HTMLSelectElement>(`select[aria-label="${label}"]`);
const choose = (label: string, value: string) =>
@@ -310,18 +351,76 @@ it('starts from the first listed model without a suggestion', async () => {
expect(await runExpand()).toMatchObject({ model_key: 'e2b' });
});
-it("uses the surface's saved pick over the suggestion and saves a different one", async () => {
+const useSuggestedButton = (name: string) =>
+ document.querySelector<HTMLButtonElement>(`button[aria-label="Use ${name}"]`);
+
+it("keeps the surface's saved pick over an installed suggestion, also after a remount, and saves a different one", async () => {
const saved = savedModels({ expandPromptModelKey: 'qwen' });
await renderAndOpen(LTX_SUGGESTION, saved);
expect(select('text llm')?.value).toBe('qwen');
+ expect(document.body.textContent).toContain('Recommended: Gemma-4 E2B');
+ await act(() => root?.unmount());
+ host?.remove();
+ await renderAndOpen(LTX_SUGGESTION, saved);
+ expect(select('text llm')?.value).toBe('qwen');
+
await choose('text llm', 'e2b');
expect(saved.onChange).toHaveBeenCalledExactlyOnceWith({ expandPromptModelKey: 'e2b' });
+});
- // Once saved, picking the same model again saves nothing.
- await act(() => renderField(LTX_SUGGESTION, { ...saved, expandPromptModelKey: 'e2b' }));
- await choose('text llm', 'e2b');
- expect(saved.onChange).toHaveBeenCalledOnce();
+it('switches to the recommended MOSS-Image enhancer from the hint and saves it', async () => {
+ catalog = [TEXT_ONLY, ENHANCER, MOSS_ENHANCER];
+ const saved = savedModels({ expandPromptModelKey: 'e2b' });
+ await renderAndOpen(MOSS_SUGGESTION, saved);
+
+ expect(select('text llm')?.value).toBe('e2b');
+ await act(() => useSuggestedButton('Gemma 4 E4B')?.click());
+ expect(select('text llm')?.value).toBe('e4b');
+ expect(useSuggestedButton('Gemma 4 E4B')).toBeNull();
+ expect(saved.onChange).toHaveBeenCalledExactlyOnceWith({ expandPromptModelKey: 'e4b' });
+ expect(await runExpand()).toMatchObject({ model_key: 'e4b', system_prompt: 'MOSS' });
+});
+
+it('preselects an installed suggestion when nothing is saved, without the hint', async () => {
+ catalog = [TEXT_ONLY, ENHANCER, MOSS_ENHANCER];
+ await renderAndOpen(MOSS_SUGGESTION, savedModels());
+
+ expect(select('text llm')?.value).toBe('e4b');
+ expect(useSuggestedButton('Gemma 4 E4B')).toBeNull();
+});
+
+it('recognises the MOSS-Image enhancer installed in place from a local folder', async () => {
+ catalog = [TEXT_ONLY, { ...MOSS_ENHANCER, source: 'E:/ModelStuffSSD/gemma-4-E4B-it' }];
+ await renderAndOpen(MOSS_SUGGESTION, savedModels());
+
+ expect(select('text llm')?.value).toBe('e4b');
+ expect(document.body.textContent).not.toContain('is not installed');
+});
+
+it('points to the MOSS-Image enhancer starter model when it is not installed', async () => {
+ await renderAndOpen(MOSS_SUGGESTION, savedModels({ expandPromptModelKey: 'e2b' }));
+
+ expect(select('text llm')?.value).toBe('e2b');
+ expect(document.body.textContent).toContain('Gemma 4 E4B (Prompt Enhancer) is not installed');
+ expect(document.body.textContent).not.toContain('Recommended:');
+});
+
+it("starts another project from its own saved Expand Prompt model, not the previous project's pick", async () => {
+ await renderAndOpen(null, savedModels());
+ await choose('text llm', 'qwen');
+ expect(select('text llm')?.value).toBe('qwen');
+
+ await act(() => renderField(null, savedModels({ expandPromptModelKey: 'e2b' }), 'project-2'));
+ expect(select('text llm')?.value).toBe('e2b');
+});
+
+it('keeps the session pick of a surface without a saved slot across a project switch', async () => {
+ await renderAndOpen(null);
+ await choose('text llm', 'qwen');
+
+ await act(() => renderField(null, undefined, 'project-2'));
+ expect(select('text llm')?.value).toBe('qwen');
});
it('falls back when the saved pick is no longer installed', async () => {
@@ -439,3 +538,13 @@ it('starts Image to Prompt from the first listed vision model and saves a differ
await choose('text llm', 'llava-b');
expect(saved.onChange).toHaveBeenCalledExactlyOnceWith({ imageToPromptModelKey: 'llava-b' });
});
+
+it("starts another project from its own saved Image to Prompt model, not the previous project's pick", async () => {
+ catalog = [VISION_A, VISION_B];
+ await renderAndOpen(null, savedModels(), 'widgets.generate.imageToPrompt');
+ await choose('text llm', 'llava-b');
+ expect(select('text llm')?.value).toBe('llava-b');
+
+ await act(() => renderField(null, savedModels({ imageToPromptModelKey: 'llava-a' }), 'project-2'));
+ expect(select('text llm')?.value).toBe('llava-a');
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx
index 456f6a8aaf..d0c1deec47 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/GeneratePromptFields.tsx
@@ -4,7 +4,7 @@ import type { PromptTemplateSnapshot } from '@features/generation/core/promptTem
import type { GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';
import { HStack, Stack, Tag } from '@chakra-ui/react';
-import { getPromptPolicy } from '@features/generation/core/baseGenerationPolicies';
+import { getImageExpandPromptSuggestion, getPromptPolicy } from '@features/generation/core/baseGenerationPolicies';
import { sanitizeBatchCount } from '@features/generation/core/batch';
import { flattenPromptTemplateExpansion } from '@features/generation/core/promptTemplates';
import { type GenerateDraft, pickGenerateSettings } from '@features/generation/ui/generateDebounce';
@@ -200,11 +200,14 @@ export const GeneratePromptFields = ({
[onCommitImmediate, settings.expandPromptModelKey, settings.imageToPromptModelKey]
);
+ const expandPromptSuggestion = useMemo(() => getImageExpandPromptSuggestion(selectedModel), [selectedModel]);
+
return (
<Stack gap="1" py="2">
<PositivePromptField
batchCount={batchCount}
dynamicPrompts={dynamicPrompts}
+ expandPromptSuggestion={expandPromptSuggestion}
heightPx={promptValues.positivePromptHeightPx}
value={promptValues.positivePrompt}
loras={settings.loras}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
index e2e7673d63..c32eae8579 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx
@@ -25,6 +25,7 @@ import {
Text,
} from '@chakra-ui/react';
import { galleryImageUrls } from '@features/gallery/utility';
+import { isModelFromRepo } from '@features/generation/core/baseGenerationPolicies';
import { filterPromptHistory } from '@features/generation/core/promptHistory';
import { resolveSelectedSystemPromptId } from '@features/generation/core/systemPrompts';
import { llmTaskProgressStore } from '@features/generation/data/llmTaskProgress';
@@ -473,7 +474,9 @@ const ExpandPromptButton = ({
const [excludedImageName, setExcludedImageName] = useState<string | null>(null);
const textLlmModels = models.filter((model) => model.type === 'text_llm');
const suggestedModelKey = suggestion?.modelSource
- ? (textLlmModels.find((model) => model.source === suggestion.modelSource)?.key ?? null)
+ ? (textLlmModels.find((model) =>
+ isModelFromRepo(typeof model.source === 'string' ? model.source : null, suggestion.modelSource ?? '')
+ )?.key ?? null)
: null;
const onSaveModelKey = savedPromptModels?.onChange;
const saveModelKey = useMemo(
@@ -486,6 +489,11 @@ const ExpandPromptButton = ({
savedKey: savedPromptModels?.expandPromptModelKey,
suggestedKey: suggestedModelKey,
});
+ const suggestedModel = textLlmModels.find((model) => model.key === suggestedModelKey) ?? null;
+ const handleUseSuggestedModel = useCallback(
+ () => handleModelChange(suggestedModel),
+ [handleModelChange, suggestedModel]
+ );
const suggestedImage = suggestion?.image ?? null;
const canReadImages = selectedModel?.supports_images === true;
const isImageIncluded = suggestedImage !== null && excludedImageName !== suggestedImage.image_name;
@@ -622,6 +630,23 @@ const ExpandPromptButton = ({
<OpenModelManagerButton modelType="text_llm" />
</>
) : null}
+ {suggestedModel && selectedModel?.key !== suggestedModel.key ? (
+ <HStack gap="2">
+ <Text color="fg.subtle" fontSize="md">
+ {t('widgets.generate.expandSuggestedModelAvailable', { model: suggestedModel.name })}
+ </Text>
+ <Button
+ aria-label={t('widgets.generate.expandUseSuggestedModelLabel', {
+ model: suggestedModel.name,
+ })}
+ size="xs"
+ variant="outline"
+ onClick={handleUseSuggestedModel}
+ >
+ {t('widgets.generate.expandUseSuggestedModel')}
+ </Button>
+ </HStack>
+ ) : null}
<SystemPromptsField
catalog={systemPrompts}
selectedId={effectiveSystemPromptId}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx
index 8d01dbc28b..b287fe9f3b 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx
@@ -1,5 +1,6 @@
/* oxlint-disable react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop */
import type { GenerateModelConfig } from '@features/generation/core/types';
+import type { DynamicPromptsFieldConfig } from '@features/generation/ui/promptFields/DynamicPromptsPanel';
import { ChakraProvider } from '@chakra-ui/react';
import { DndContext } from '@dnd-kit/core';
@@ -17,6 +18,13 @@ const i18n = i18next.createInstance();
await i18n.use(initReactI18next).init({ fallbackLng: 'en', lng: 'en', resources: { en: { translation: {} } } });
+const parseDynamicPrompts = vi.hoisted(() => vi.fn());
+
+vi.mock('@features/generation/data/promptUtilities', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ parseDynamicPrompts,
+}));
+
vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) => ({
...(await importOriginal<object>()),
useGenerationUi: () => ({
@@ -148,3 +156,68 @@ it('colours and weights attention syntax only while the selected model reads it'
expect(await weightCat()).toBe(true);
await expect.poll(() => textarea().value).toBe('a cat++');
});
+
+const DYNAMIC_PROMPTS: DynamicPromptsFieldConfig = {
+ combinatorial: true,
+ isSeedFixed: false,
+ maxPrompts: 100,
+ onChange: vi.fn(),
+ resample: true,
+ sampleSeed: 0,
+ seedBehaviour: 'per-iteration',
+};
+const PHOTO_TEMPLATE = { id: 'photo', name: 'Photo', negativePrompt: '', positivePrompt: 'photo of {prompt}' };
+
+it('shows a JSON prompt under a template whole, as it generates, and never expands its braces', async () => {
+ parseDynamicPrompts.mockResolvedValue({ error: null, prompts: ['a red cup', 'a green cup'] });
+ const layout =
+ '{"bbox_coord_space":"abs_centralized","bbox_format":"yxyx","summary":{"caption":"a {red|green} cup"},"items":[]}';
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+
+ await act(() => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <QueryClientProvider client={new QueryClient()}>
+ <ChakraProvider value={system}>
+ <DndContext>
+ <PositivePromptField
+ batchCount={2}
+ dynamicPrompts={DYNAMIC_PROMPTS}
+ heightPx={96}
+ isTemplateViewMode
+ loras={[]}
+ projectId="project-1"
+ promptTemplate={PHOTO_TEMPLATE}
+ selectedModel={undefined}
+ showSyntaxHighlighting
+ value={layout}
+ onChange={vi.fn()}
+ onResizeEnd={vi.fn()}
+ onTemplateViewModeChange={vi.fn()}
+ onUsePrompt={vi.fn()}
+ />
+ </DndContext>
+ </ChakraProvider>
+ </QueryClientProvider>
+ </I18nextProvider>
+ );
+ });
+ // Past the dynamic prompts debounce, when a dynamic prompt would have been parsed.
+ await act(async () => {
+ await new Promise((resolve) => {
+ window.setTimeout(resolve, 700);
+ });
+ });
+
+ expect(host.querySelector('textarea')?.value).toBe(layout);
+ // The merged-view overlay lines up with the textarea: no template text around the layout.
+ expect(host.querySelector('pre')?.textContent).toBe(layout);
+ const dynamicButton = [...host.querySelectorAll('button')].find((button) =>
+ button.textContent?.includes('widgets.generate.dynamicButton')
+ );
+ expect(dynamicButton).toBeDefined();
+ expect(dynamicButton?.textContent).not.toMatch(/\d/);
+ expect(parseDynamicPrompts).not.toHaveBeenCalled();
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
index d53aff50b5..ad96168c74 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx
@@ -5,7 +5,7 @@ import type { ChangeEvent, KeyboardEvent } from 'react';
import { Box, Text } from '@chakra-ui/react';
import { supportsPromptAttentionSyntax } from '@features/generation/core/prompt/compel';
-import { applyPromptTemplate, getPromptTemplateChunks } from '@features/generation/core/promptTemplates';
+import { getEffectivePositivePrompt, getPositivePromptTemplateChunks } from '@features/generation/core/promptTemplates';
import { useRegisterGenerateDraftFlusher } from '@features/generation/ui/generateDraftRegistry';
import { useDebouncedDraftValue } from '@features/generation/ui/useDebouncedDraftValue';
import { useWildcards } from '@features/generation/ui/useWildcards';
@@ -175,7 +175,7 @@ export const PositivePromptField = ({
// Merge against the live draft so expansion counts do not lag behind debounce.
const effectivePositivePrompt = useMemo(
- () => (promptTemplate ? applyPromptTemplate(promptTemplate.positivePrompt, draftValue) : draftValue),
+ () => getEffectivePositivePrompt(draftValue, promptTemplate),
[draftValue, promptTemplate]
);
@@ -255,7 +255,7 @@ export const PositivePromptField = ({
const handlePromptClick = useCallback(() => autocomplete.refresh(textareaRef.current), [autocomplete]);
const templateChunks = useMemo(
- () => (isViewingMerged ? getPromptTemplateChunks(draftValue, promptTemplate.positivePrompt) : null),
+ () => (isViewingMerged ? getPositivePromptTemplateChunks(draftValue, promptTemplate) : null),
[draftValue, isViewingMerged, promptTemplate]
);
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.test.ts b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
index 1e139763a1..ff4031777e 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
@@ -190,6 +190,41 @@ describe('resolveInvocationRoute', () => {
expect(route.sourceValid).toBe(false);
expect(route.validationReasons).toContain("No invocation node registered for external provider 'future-provider'.");
});
+
+ it('blocks a MOSS-Image layout draft that a prompt template hides or breaks', () => {
+ const mossModel: MainModelConfig = {
+ base: 'moss-image',
+ format: 'diffusers',
+ key: 'moss-model',
+ name: 'MOSS-Image',
+ type: 'main',
+ };
+ const reasonsFor = (positivePrompt: string, templatePrompt: string) =>
+ resolveInvocationRoute(
+ getActiveProject(
+ createGenerateValues(mossModel, {
+ positivePrompt,
+ promptTemplate: { id: 't', name: 'Template', negativePrompt: '', positivePrompt: templatePrompt },
+ })
+ )
+ ).validationReasons;
+ const notJson = [
+ 'The prompt looks like a MOSS-Image layout draft but is not valid JSON. Run Expand Prompt again or fix it.',
+ ];
+ const scaffold =
+ '{"width":1024,"height":1024,"bbox_coord_space":"abs","bbox_format":"xyxy","summary":{"caption":"{prompt}"},"items":[{"label":"object","caption":"a sign","bbox":[0,0,512,512]}]}';
+
+ // A prefix hides a truncated draft from the authored prompt alone...
+ expect(
+ reasonsFor(
+ '{"bbox_coord_space":"abs","bbox_format":"xyxy","summary":{"caption":"a poster"},"items":[',
+ 'photo of {prompt}'
+ )
+ ).toEqual(notJson);
+ // ...and a template that is a draft breaks around an unescaped quote in a plain prompt.
+ expect(reasonsFor('a "neon" sign', scaffold)).toEqual(notJson);
+ expect(reasonsFor('a neon sign', scaffold)).toEqual([]);
+ });
});
describe('resolveInvocationRoute — upscale source', () => {
@@ -628,6 +663,9 @@ describe('resolveInvocationRoute — canvas source', () => {
canvasRoute
).validationReasons;
+ expect(reasonsFor({ positivePrompt: '```json\n{"bbox_coord_space": "abs",\n```' }, [])).toEqual([
+ 'The prompt looks like a MOSS-Image layout draft but is not valid JSON. Run Expand Prompt again or fix it.',
+ ]);
expect(reasonsFor({ positivePrompt: ' ' }, [region()])).toEqual([
'MOSS-Image needs a prompt to place regional guidance in its layout. Enter a prompt or disable the regional guidance layers.',
]);
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.ts
index d8e2499de2..74d5fcc432 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts
@@ -12,7 +12,7 @@ import type {
import type { Project } from '@workbench/projectContracts';
import type { WidgetId } from '@workbench/widgetContracts';
-import { getLayoutPromptRejectionReason } from '@features/generation/graph';
+import { getLayoutDraftRejectionReason, getLayoutPromptRejectionReason } from '@features/generation/graph';
import {
describeExternalCanvasRefusal,
getEffectivePrompts,
@@ -262,6 +262,13 @@ const getGenerateSnapshotValidationReasons = (
mode
),
...(models ? getGenerationModelAvailabilityReasons(values.model, values, models) : []),
+ ...[
+ getLayoutDraftRejectionReason({
+ base: values.model.base,
+ positivePrompt: values.positivePrompt,
+ promptTemplate: values.promptTemplate,
+ }),
+ ].filter((reason) => reason !== null),
];
};
diff --git a/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts b/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts
index 8be6c11953..35e350b68d 100644
--- a/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocationSubmit.test.ts
@@ -464,12 +464,12 @@ describe('submitResolvedInvocation with a random dynamic prompt', () => {
describe('submitResolvedInvocation without dynamic prompts', () => {
seedArchitectureCapabilities();
- const submitGenerate = async (prepend?: boolean) => {
+ const submitGenerate = async (prepend?: boolean, positivePrompt = 'a cat') => {
const model: MainModelConfig = { base: 'sd-1', key: 'main', name: 'Main', type: 'main' };
const project = getActiveProject(
workbenchReducer(createInitialWorkbenchState(), {
type: 'setGenerateSettings',
- values: { ...getDefaultGenerateSettings(model), model, modelKey: model.key, positivePrompt: 'a cat' },
+ values: { ...getDefaultGenerateSettings(model), model, modelKey: model.key, positivePrompt },
})
);
const route = resolveInvocationRoute(project, 'global', {
@@ -509,6 +509,19 @@ describe('submitResolvedInvocation without dynamic prompts', () => {
expect(back.mock.calls[0]?.[0]).not.toHaveProperty('prepend');
});
+ it('dispatches a JSON prompt literally, without expanding its braces', async () => {
+ const draft =
+ '```json\n{"width":1024,"height":1536,"bbox_coord_space":"abs","bbox_format":"xyxy","summary":{"caption":"a poster"},"items":[{"label":"object","caption":"a cup","bbox":[0,0,10,10]}]}\n```';
+ const compiled =
+ '{"bbox_coord_space":"abs_centralized","bbox_format":"yxyx","summary":{"caption":"a poster"},"items":[]}';
+ for (const prompt of [draft, compiled]) {
+ const submitted = await submitGenerate(undefined, prompt);
+ expect(submitted).toHaveBeenCalledTimes(1);
+ expect(submitted.mock.calls[0]?.[0]).not.toHaveProperty('positivePrompts');
+ submitted.mockRestore();
+ }
+ });
+
it('keeps Invoke Front on a Workflow dispatch', async () => {
generatorsMock.resolveWorkflowGenerators.mockImplementation(
(_client: unknown, pending: Array<{ key: string; nodeId: string }>) =>
diff --git a/tests/app/invocations/test_moss_image_layout_prompt.py b/tests/app/invocations/test_moss_image_layout_prompt.py
index e67b0a4d05..9fe8144ad9 100644
--- a/tests/app/invocations/test_moss_image_layout_prompt.py
+++ b/tests/app/invocations/test_moss_image_layout_prompt.py
@@ -71,3 +71,18 @@ def test_the_layout_prompt_can_be_recorded_in_core_metadata() -> None:
graph.add_edge(edge)
assert graph.edges == [edge]
+
+
+def test_the_node_compiles_a_layout_draft_at_its_own_size() -> None:
+ # Expand Prompt's MOSS-Image Prompt Enhancer writes drafts in their own frame; the generation size wins.
+ draft = (
+ '```json\n{"width":1000,"height":1000,"bbox_coord_space":"abs","bbox_format":"xyxy",'
+ '"summary":{"caption":"a poster"},"items":[{"label":"text","caption":"a title","text":"TEA",'
+ '"bbox":[0,0,1000,250]}]}\n```'
+ )
+
+ assert _node(prompt=draft, width=768, height=1344).invoke(MagicMock()).value == (
+ '{"summary":{"caption":"a poster"},"items":['
+ '{"label":"text","caption":"a title","text":"TEA","bbox":[-672,-384,-336,384]}'
+ '],"bbox_coord_space":"abs_centralized","bbox_format":"yxyx"}'
+ )
diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_10_28_add_moss_image_enhancer_system_prompt.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_10_28_add_moss_image_enhancer_system_prompt.py
new file mode 100644
index 0000000000..31d6e16d81
--- /dev/null
+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_10_28_add_moss_image_enhancer_system_prompt.py
@@ -0,0 +1,110 @@
+"""The MOSS-Image prompt enhancer is seeded once; a row the user changed keeps their changes."""
+
+import re
+from logging import Logger
+from pathlib import Path
+
+from sqlalchemy import MetaData, create_engine, delete, select, update
+
+from invokeai.app.services.shared.database.database import Database
+from invokeai.app.services.shared.database.schema.migrator import applied_migrations
+from invokeai.app.services.shared.database.schema.system_prompts import system_prompts
+from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_10_28_add_moss_image_enhancer_system_prompt import (
+ MOSS_IMAGE_ENHANCER_PROMPT_CONTENT,
+ MOSS_IMAGE_ENHANCER_PROMPT_ID,
+ build_migration,
+)
+from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import PortableMigrationContext
+from tests.fixtures.database import migrate_to_newest
+from tests.fixtures.migration_state import alembic_operations
+
+MIGRATION_ID = "2026_10_28_add_moss_image_enhancer_system_prompt"
+
+
+def _row(database: Database) -> tuple | None:
+ with database.begin(write=False) as conn:
+ row = conn.execute(
+ select(
+ system_prompts.c.name,
+ system_prompts.c.content,
+ system_prompts.c.user_id,
+ system_prompts.c.is_public,
+ system_prompts.c.max_tokens,
+ ).where(system_prompts.c.id == MOSS_IMAGE_ENHANCER_PROMPT_ID)
+ ).one_or_none()
+ return None if row is None else tuple(row)
+
+
+def _forget_migration(database: Database) -> None:
+ with database.begin(write=True) as conn:
+ conn.execute(delete(applied_migrations).where(applied_migrations.c.migration_id == MIGRATION_ID))
+
+
+def test_seeds_a_shared_prompt_with_its_token_cap(database: Database) -> None:
+ assert _row(database) == (
+ "MOSS-Image Prompt Enhancer",
+ MOSS_IMAGE_ENHANCER_PROMPT_CONTENT,
+ "system",
+ True,
+ 1536,
+ )
+ # The prompt asks for the draft convention the layout prompt node compiles.
+ assert '"bbox_coord_space":"abs","bbox_format":"xyxy"' in MOSS_IMAGE_ENHANCER_PROMPT_CONTENT
+ with database.begin(write=False) as conn:
+ created_at, updated_at = conn.execute(
+ select(system_prompts.c.created_at, system_prompts.c.updated_at).where(
+ system_prompts.c.id == MOSS_IMAGE_ENHANCER_PROMPT_ID
+ )
+ ).one()
+ assert re.fullmatch(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}", created_at)
+ assert updated_at == created_at
+
+
+def test_supplies_every_value_a_server_has_no_default_for() -> None:
+ """A server declares no defaults for the timestamps, which only SQLite has (`inserted_at`, `updated_at`).
+
+ The table here is the schema's with the SQLite-only defaults left out, so it holds the server's NOT NULL
+ columns without a default; the insert must name each of them.
+ """
+ server_shaped = system_prompts.to_metadata(MetaData())
+ for column in server_shaped.columns:
+ column.info.clear()
+ assert {
+ column.name for column in server_shaped.columns if not column.nullable and column.server_default is None
+ } >= {
+ "created_at",
+ "updated_at",
+ }
+ engine = create_engine("sqlite://")
+ with engine.begin() as conn:
+ server_shaped.create(conn)
+ context = PortableMigrationContext(conn=conn, op=alembic_operations(conn), logger=Logger("test"))
+ build_migration().callback(context)
+ row = conn.execute(select(server_shaped.c.id, server_shaped.c.created_at, server_shaped.c.updated_at)).one()
+ engine.dispose()
+ assert row.id == MOSS_IMAGE_ENHANCER_PROMPT_ID
+ assert row.created_at is not None and row.updated_at == row.created_at
+
+
+def test_running_again_leaves_an_edited_prompt_alone(database: Database, tmp_path: Path) -> None:
+ with database.begin(write=True) as conn:
+ conn.execute(
+ update(system_prompts)
+ .where(system_prompts.c.id == MOSS_IMAGE_ENHANCER_PROMPT_ID)
+ .values(name="Mine", content="edited", is_public=False, max_tokens=None)
+ )
+ _forget_migration(database)
+
+ migrate_to_newest(database, tmp_path)
+
+ assert _row(database) == ("Mine", "edited", "system", False, None)
+
+
+def test_running_again_does_not_restore_a_deleted_prompt(database: Database, tmp_path: Path) -> None:
+ """Deleting a seeded prompt is the user's choice; only a database that never ran the migration gets it."""
+ with database.begin(write=True) as conn:
+ conn.execute(delete(system_prompts).where(system_prompts.c.id == MOSS_IMAGE_ENHANCER_PROMPT_ID))
+
+ migrate_to_newest(database, tmp_path)
+
+ assert _row(database) is None
diff --git a/tests/backend/moss_image/test_layout.py b/tests/backend/moss_image/test_layout.py
index 613befab55..27d71e84da 100644
--- a/tests/backend/moss_image/test_layout.py
+++ b/tests/backend/moss_image/test_layout.py
@@ -162,12 +162,6 @@ def test_regions_are_appended_to_a_compiled_layout_which_keeps_everything_else()
@pytest.mark.parametrize(
"prompt",
[
- # An uncompiled OpenMOSS draft: absolute xyxy boxes, which the new centred yxyx boxes must not join.
- pytest.param(
- '{"width":1024,"height":1024,"bbox_coord_space":"abs","bbox_format":"xyxy","summary":{"caption":"x"},'
- '"items":[]}',
- id="uncompiled-draft",
- ),
pytest.param(
'{"summary":{"caption":"x"},"items":[],"bbox_coord_space":"normalized_1000","bbox_format":"yxyx"}',
id="other-coord-space",
@@ -219,3 +213,168 @@ def test_regions_need_a_prompt_to_caption_the_layout(prompt: str) -> None:
# OpenMOSS requires a non-blank summary.caption.
with pytest.raises(ValueError, match="need a prompt"):
build_moss_image_layout_prompt(prompt, [_region("object", "a cup", [0, 0, 16, 16])], 1024, 1024)
+
+
+# Layout drafts: the absolute-pixel JSON that Expand Prompt's MOSS-Image Prompt Enhancer asks an LLM to write.
+
+_DRAFT = (
+ '{"width":1536,"height":1024,"bbox_coord_space":"abs","bbox_format":"xyxy",'
+ '"summary":{"meta":["poster"],"canvas":"single","caption":"A ceramic campaign."},"items":['
+ '{"label":"object","caption":"An ivory cup.","bbox":[176,224,800,864],"tags":["product"]},'
+ '{"label":"text","caption":"Dark-green lettering.","text":"把日常,过成诗。\\n\\"MOSS\\" 🪴","bbox":[928,272,1408,448]},'
+ '{"label":"character","caption":"A potter.","palette":["ochre"],"bbox":[10.9,20.1,100.01,200.99]}]}'
+)
+# What the OpenMOSS reference `compile_prompt` returns for _DRAFT, captured from it at the commit named above.
+_DRAFT_COMPILED_BY_REFERENCE = (
+ '{"summary":{"meta":["poster"],"canvas":"single","caption":"A ceramic campaign."},"items":['
+ '{"label":"object","caption":"An ivory cup.","bbox":[-288,-592,352,32],"tags":["product"]},'
+ '{"label":"text","caption":"Dark-green lettering.","text":"把日常,过成诗。\\n\\"MOSS\\" 🪴","bbox":[-240,160,-64,640]},'
+ '{"label":"character","caption":"A potter.","palette":["ochre"],"bbox":[-492,-758,-311,-667]}'
+ '],"bbox_coord_space":"abs_centralized","bbox_format":"yxyx"}'
+)
+
+
+def _draft(**changes: object) -> dict:
+ draft = json.loads(_DRAFT)
+ draft.update(changes)
+ return draft
+
+
+def _items(*items: object) -> dict:
+ return _draft(items=list(items))
+
+
+def _compile(draft: dict, width: int = 1536, height: int = 1024) -> dict:
+ return json.loads(build_moss_image_layout_prompt(json.dumps(draft, ensure_ascii=False), [], width, height))
+
+
+def test_a_draft_at_its_own_size_compiles_exactly_as_the_reference_does() -> None:
+ assert build_moss_image_layout_prompt(_DRAFT, [], 1536, 1024) == _DRAFT_COMPILED_BY_REFERENCE
+
+
+ "prompt",
+ [
+ pytest.param(f"\n {_DRAFT}\n", id="whitespace"),
+ pytest.param(f"```json\n{_DRAFT}\n```", id="json-fence"),
+ pytest.param(f" ```\n{_DRAFT}\n```\n", id="bare-fence"),
+ pytest.param(f"```json5\n{_DRAFT}\n```", id="json5-fence"),
+ pytest.param(f"```ld-json \t\n{_DRAFT}\n```", id="ld-json-fence"),
+ pytest.param(f"```json\r\n{_DRAFT}\r\n```", id="crlf-fence"),
+ ],
+)
+def test_a_draft_wrapped_the_way_llms_reply_is_compiled(prompt: str) -> None:
+ assert build_moss_image_layout_prompt(prompt, [], 1536, 1024) == _DRAFT_COMPILED_BY_REFERENCE
+
+
+def test_a_draft_is_scaled_per_axis_to_the_generation_size() -> None:
+ # 1536 -> 1024 wide (2/3), height unchanged; edges are enclosed in whole pixels after scaling.
+ layout = _compile(_draft(), 1024, 1024)
+
+ assert [item["bbox"] for item in layout["items"]] == [
+ [-288, -395, 352, 22],
+ [-240, 106, -64, 427],
+ [-492, -505, -311, -445],
+ ]
+
+
+def test_a_draft_frame_need_not_be_a_multiple_of_16() -> None:
+ # Small LLMs write sizes like 1000; they only set the frame the boxes are measured in.
+ draft = _draft(
+ width=1000, height=1000, items=[{"label": "object", "caption": "a cup", "bbox": [250, 500, 750, 1000]}]
+ )
+ assert _compile(draft, 1024, 1024)["items"][0]["bbox"] == [0, -256, 512, 256]
+
+
+def test_regions_follow_the_compiled_draft_items() -> None:
+ prompt = build_moss_image_layout_prompt(_DRAFT, [_region("object", "a vase", [0, 0, 16, 16])], 1536, 1024)
+
+ items = json.loads(prompt)["items"]
+ assert [item["caption"] for item in items] == ["An ivory cup.", "Dark-green lettering.", "A potter.", "a vase"]
+ assert items[-1]["bbox"] == [-512, -768, -496, -752]
+
+
+def test_unknown_fields_are_dropped_and_unknown_labels_become_objects_or_text() -> None:
+ draft = _draft(id="draft-1", notes="ignore", width=1000, height=1000)
+ draft["summary"]["mood"] = "calm"
+ draft["items"] = [
+ {"id": 1, "label": "product", "caption": "a cup", "bbox": [0, 0, 500, 500], "children": []},
+ {"label": "headline", "caption": "a title", "text": "TEA", "bbox": [500, 0, 1000, 500]},
+ ]
+
+ assert _compile(draft, 1024, 1024) == {
+ "summary": {"meta": ["poster"], "canvas": "single", "caption": "A ceramic campaign."},
+ "items": [
+ {"label": "object", "caption": "a cup", "bbox": [-512, -512, 0, 0]},
+ {"label": "text", "caption": "a title", "text": "TEA", "bbox": [-512, 0, 0, 512]},
+ ],
+ "bbox_coord_space": "abs_centralized",
+ "bbox_format": "yxyx",
+ }
+
+
+def test_boxes_leaving_the_canvas_are_clamped_and_boxes_without_area_dropped() -> None:
+ layout = _compile(
+ _items(
+ {"label": "object", "caption": "clamped", "bbox": [-20, -20, 1600, 512]},
+ {"label": "object", "caption": "off canvas", "bbox": [1600, 0, 1700, 100]},
+ {"label": "object", "caption": "inverted", "bbox": [100, 0, 50, 100]},
+ {"label": "object", "caption": "a hairline", "bbox": [0, 0, 0.00000000001, 100]},
+ )
+ )
+
+ assert layout["items"] == [{"label": "object", "caption": "clamped", "bbox": [-512, -768, 0, 768]}]
+
+
+def test_a_draft_without_any_box_on_the_canvas_is_refused() -> None:
+ with pytest.raises(ValueError, match="no item has a box on the canvas"):
+ _compile(_items({"label": "object", "caption": "off canvas", "bbox": [1600, 0, 1700, 100]}))
+
+
+ ("draft", "message"),
+ [
+ # OpenMOSS: text items require literal text.
+ (_items({"label": "text", "caption": "a title", "bbox": [0, 0, 16, 16]}), "item 1 has no text"),
+ (_items({"label": "text", "caption": "a title", "text": " ", "bbox": [0, 0, 16, 16]}), "item 1 has blank text"),
+ (_items({"label": "object", "caption": "", "bbox": [0, 0, 16, 16]}), "item 1 has no caption"),
+ (_items({"label": "object", "caption": "a cup", "bbox": [0, 0, 16]}), "item 1 needs a box"),
+ # OpenMOSS: booleans and numeric strings are not coordinates.
+ (_items({"label": "object", "caption": "a cup", "bbox": [True, 0, 16, 16]}), "item 1 needs a box"),
+ (_items({"label": "object", "caption": "a cup", "bbox": [0, 0, "16", 16]}), "item 1 needs a box"),
+ (_items({"label": "object", "caption": "a cup", "tags": "cup", "bbox": [0, 0, 16, 16]}), "item 1: its tags"),
+ (_items("a cup"), "item 1 is not an object"),
+ (_draft(items=[]), "it has no items"),
+ (_draft(summary={"meta": ["poster"]}), "the summary has no caption"),
+ (_draft(summary={"caption": " "}), "the summary has no caption"),
+ (_draft(summary={"caption": "x", "canvas": "grid"}), "the summary canvas"),
+ (_draft(summary={"caption": "x", "meta": "poster"}), "the summary meta"),
+ # OpenMOSS rejects these sizes too; a frame that is not a multiple of 16 is accepted here.
+ (_draft(width=0), "width and height"),
+ (_draft(width=True), "width and height"),
+ (_draft(height="1024"), "width and height"),
+ ],
+)
+def test_an_invalid_draft_is_refused_naming_what_is_wrong(draft: dict, message: str) -> None:
+ with pytest.raises(ValueError, match=f"^Layout draft: {message}"):
+ _compile(draft)
+
+
+def test_a_draft_number_that_is_not_json_makes_the_prompt_a_caption() -> None:
+ # OpenMOSS rejects NaN; such text is not JSON, so it passes through like any other caption.
+ prompt = _DRAFT.replace("[176,224,800,864]", "[176,224,NaN,864]")
+ assert build_moss_image_layout_prompt(prompt, [], 1536, 1024) == prompt
+
+
+ "prompt",
+ [
+ # Other conventions are not drafts; without regions they pass through as before.
+ '{"width":1024,"height":1024,"bbox_coord_space":"abs_centralized","bbox_format":"xyxy","summary":{},"items":[]}',
+ '{"width":1024,"height":1024,"bbox_coord_space":"normalized_1000","bbox_format":"xyxy","items":[]}',
+ # Prose around a fence is not unwrapped.
+ f"Here is the layout:\n```json\n{_DRAFT}\n```",
+ ],
+)
+def test_json_that_is_not_a_draft_is_left_alone(prompt: str) -> None:
+ assert build_moss_image_layout_prompt(prompt, [], 1536, 1024) == prompt