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.

fix(ideogram4): place canvas regional guidance in the structured caption (#10070)

Alexander Eichhorn4206a02b3756
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/ideogram4.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/ideogram4.mdx
index 34d675a105..88e751fe59 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/ideogram4.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/ideogram4.mdx
@@ -1,7 +1,7 @@
---
title: Ideogram 4
description: Generate images with the Ideogram 4 text-to-image models.
-lastUpdated: 2026-10-08
+lastUpdated: 2026-10-29
sidebar:
order: 7
---
@@ -86,10 +86,12 @@ Ideogram 4 keeps both transformer branches loaded for the whole generation. With
When an Ideogram 4 model is selected, Invoke builds the structured JSON prompt automatically:
- The **positive prompt** becomes the overall scene description.
-- Each enabled **Regional Guidance** layer on the Canvas contributes one element: its drawn box becomes the region's bounding box and its prompt becomes that region's description. Draw a box where you want something and describe it there.
-- To drive the model directly, paste a **raw JSON** object into the prompt box — anything starting with `{` is passed through unchanged.
+- Each enabled **Regional Guidance** layer on the Canvas contributes one object element. The layer's **Positive prompt** describes it, and its box is the rectangle around everything painted on the layer inside the generation frame. The shape does not matter, and separate painted areas on one layer share one box. A layer without a positive prompt is left out.
+- To drive the model directly, paste a **raw JSON** object into the prompt box — anything starting with `{` is passed through unchanged, and regional guidance layers are ignored.
-The exact JSON that was encoded is stored in the image metadata as **Structured Caption**, and can be recalled straight back into the prompt box from the metadata viewer.
+When a layer with a positive prompt has paint inside the generation frame, the main prompt cannot be blank: Invoke is disabled with *Ideogram 4 needs a prompt to place regional guidance in its layout. Enter a prompt or disable the regional guidance layers.* Every region is an object, so the layer offers no **Region type**. Regional negative prompts, auto-negative and regional reference images are not used with Ideogram 4; the layer hides its negative prompt and auto-negative controls.
+
+The caption is built when the generation runs, so dynamic prompts and batches vary the description inside it. The exact JSON that was encoded is saved in the image's metadata as `ideogram4_caption`; recalling the image restores the prompt you typed.
:::note[No negative prompt]
Ideogram 4 does not use a negative prompt — it has a dedicated unconditional branch instead, so the negative prompt box has no effect.
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx b/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx
index b4c258b658..f10db07666 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx
@@ -128,7 +128,7 @@ Regional guidance gives one area of the image its own prompt. For example, keep
To guide a region with an image instead of, or as well as, words, choose **Add reference image** from the regional guidance layer's right-click menu, or add a **Regional reference image** layer from the **+** menu. The reference appears as a row under the layer; select that row to choose its image, model and weight in Properties.
-Regional guidance works with SD 1.5, SDXL, FLUX.1, FLUX.2, Krea-2, Z-Image, Anima and MOSS-Image. MOSS-Image places each region as a box in a JSON layout instead of masking its prompt, and offers a **Region type** (Object by default, Character or Text); see [MOSS-Image](/users-guide/models/local-models/moss-image/#layout-with-canvas-regions). Regional negative prompts are available for SD 1.5 and SDXL, and regional reference images for SD 1.5, SDXL (IP-Adapter) and FLUX.1 (FLUX Redux). With other models, regional layers are skipped, and the layer's Properties say so. For a reference image that applies to the whole picture, use **Add reference image** in the Generate panel instead.
+Regional guidance works with SD 1.5, SDXL, FLUX.1, FLUX.2, Krea-2, Z-Image, Anima, MOSS-Image and Ideogram 4. MOSS-Image and Ideogram 4 place each region as a box in a JSON prompt instead of masking its prompt. MOSS-Image offers a **Region type** (Object by default, Character or Text); see [MOSS-Image](/users-guide/models/local-models/moss-image/#layout-with-canvas-regions) and [Ideogram 4](/users-guide/models/local-models/ideogram4/#prompting-ideogram-4). Regional negative prompts are available for SD 1.5 and SDXL, and regional reference images for SD 1.5, SDXL (IP-Adapter) and FLUX.1 (FLUX Redux). With other models, regional layers are skipped, and the layer's Properties say so. For a reference image that applies to the whole picture, use **Add reference image** in the Generate panel instead.
## Control layers
diff --git a/invokeai/backend/architectures/defs/ideogram_4.py b/invokeai/backend/architectures/defs/ideogram_4.py
index dee497926a..a9c27f9ff6 100644
--- a/invokeai/backend/architectures/defs/ideogram_4.py
+++ b/invokeai/backend/architectures/defs/ideogram_4.py
@@ -46,5 +46,9 @@ register(
dimension_grid=16,
guidance_label="Guidance",
scheduler_set="flow",
+ # Regions are not masked: each becomes an `obj` element with a normalized bbox in the structured
+ # caption (`ideogram4_caption_builder`), which has no negative counterpart, so `regional_negative`
+ # keeps its False default.
+ supports_regional_guidance=True,
),
)
diff --git a/invokeai/frontend/webv2/.oxfmtrc.json b/invokeai/frontend/webv2/.oxfmtrc.json
index 7cdbe2c914..abc319d0d2 100644
--- a/invokeai/frontend/webv2/.oxfmtrc.json
+++ b/invokeai/frontend/webv2/.oxfmtrc.json
@@ -12,6 +12,7 @@
"src/features/generation/core/__snapshots__/animaLLLiteCanvasGraphs.json",
"src/features/generation/core/__snapshots__/externalCanvasGraphs.json",
"src/features/generation/core/__snapshots__/mossImageLayoutCanvasGraphs.json",
+ "src/features/generation/core/__snapshots__/ideogram4RegionalCanvasGraphs.json",
"src/features/video/core/__snapshots__/videoGraphNodeTypes.json",
"src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.json",
"src/features/upscale/core/__snapshots__/upscaleIndexClippedStarts.json",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index c8bb200e64..4610bbf6e9 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -4769,8 +4769,9 @@
"addReferenceImage": "Add reference image",
"autoNegative": "Auto-Negative",
"clearReferenceImage": "Clear reference image",
+ "layoutBoxHelp": "{{model}} places the rectangle around everything painted on this layer inside the frame, so the shape does not matter and separate areas share one box.",
"layoutKind": "Region type",
- "layoutKindHelp": "{{model}} places the rectangle around everything painted on this layer inside the frame, so the shape does not matter and separate areas share one box. Character is for people and creatures, Object for everything else.",
+ "layoutKindHelp": "Character is for people and creatures, Object for everything else.",
"layoutKinds": {
"character": "Character",
"object": "Object",
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json b/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json
index c89e100a80..dff80f40d1 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json
@@ -635,7 +635,7 @@
"max_reference_images": 0,
"reference_images_require_variant": null,
"reference_images_require_format": null,
- "supports_regional_guidance": false,
+ "supports_regional_guidance": true,
"regional_negative": false,
"clip_skip_max": null,
"supports_seamless": false,
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 02f94892e2..5eb1715056 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json
@@ -648,6 +648,7 @@
},
"core_metadata": {
"inputs": [
+ "ideogram4_caption",
"moss_image_layout_prompt",
"negative_prompt",
"positive_prompt",
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/ideogram4RegionalCanvasGraphs.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/ideogram4RegionalCanvasGraphs.json
new file mode 100644
index 0000000000..a47a8e528e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/ideogram4RegionalCanvasGraphs.json
@@ -0,0 +1,247 @@
+{
+ "_comment": "Generated by compileCanvasGraph.test.ts; regenerate with `vitest -u`. Validated against the backend invocations by the Ideogram 4 regional graph tests.",
+ "txt2img": {
+ "edges": [
+ {
+ "destination": {
+ "field": "transformer",
+ "node_id": "denoise_latents"
+ },
+ "source": {
+ "field": "transformer",
+ "node_id": "model_loader"
+ }
+ },
+ {
+ "destination": {
+ "field": "qwen3_encoder",
+ "node_id": "pos_cond"
+ },
+ "source": {
+ "field": "qwen3_encoder",
+ "node_id": "model_loader"
+ }
+ },
+ {
+ "destination": {
+ "field": "vae",
+ "node_id": "canvas_output"
+ },
+ "source": {
+ "field": "vae",
+ "node_id": "model_loader"
+ }
+ },
+ {
+ "destination": {
+ "field": "prompt",
+ "node_id": "caption_builder"
+ },
+ "source": {
+ "field": "value",
+ "node_id": "positive_prompt"
+ }
+ },
+ {
+ "destination": {
+ "field": "prompt",
+ "node_id": "pos_cond"
+ },
+ "source": {
+ "field": "value",
+ "node_id": "caption_builder"
+ }
+ },
+ {
+ "destination": {
+ "field": "positive_conditioning",
+ "node_id": "denoise_latents"
+ },
+ "source": {
+ "field": "conditioning",
+ "node_id": "pos_cond"
+ }
+ },
+ {
+ "destination": {
+ "field": "seed",
+ "node_id": "denoise_latents"
+ },
+ "source": {
+ "field": "value",
+ "node_id": "seed"
+ }
+ },
+ {
+ "destination": {
+ "field": "latents",
+ "node_id": "canvas_output"
+ },
+ "source": {
+ "field": "latents",
+ "node_id": "denoise_latents"
+ }
+ },
+ {
+ "destination": {
+ "field": "seed",
+ "node_id": "core_metadata_0_i"
+ },
+ "source": {
+ "field": "value",
+ "node_id": "seed"
+ }
+ },
+ {
+ "destination": {
+ "field": "positive_prompt",
+ "node_id": "core_metadata_0_i"
+ },
+ "source": {
+ "field": "value",
+ "node_id": "positive_prompt"
+ }
+ },
+ {
+ "destination": {
+ "field": "negative_prompt",
+ "node_id": "core_metadata_0_i"
+ },
+ "source": {
+ "field": "value",
+ "node_id": "negative_prompt"
+ }
+ },
+ {
+ "destination": {
+ "field": "metadata",
+ "node_id": "canvas_output"
+ },
+ "source": {
+ "field": "metadata",
+ "node_id": "core_metadata_0_i"
+ }
+ },
+ {
+ "destination": {
+ "field": "ideogram4_caption",
+ "node_id": "core_metadata_0_i"
+ },
+ "source": {
+ "field": "value",
+ "node_id": "caption_builder"
+ }
+ }
+ ],
+ "id": "ideogram4_regional_canvas_txt2img",
+ "nodes": {
+ "negative_prompt": {
+ "is_intermediate": true,
+ "use_cache": true,
+ "id": "negative_prompt",
+ "type": "string"
+ },
+ "positive_prompt": {
+ "is_intermediate": true,
+ "use_cache": true,
+ "id": "positive_prompt",
+ "type": "string"
+ },
+ "seed": {
+ "is_intermediate": true,
+ "use_cache": true,
+ "id": "seed",
+ "type": "integer"
+ },
+ "model_loader": {
+ "is_intermediate": true,
+ "use_cache": true,
+ "id": "model_loader",
+ "model": {
+ "base": "ideogram-4",
+ "format": "diffusers",
+ "key": "ideogram4-model",
+ "name": "Ideogram 4",
+ "type": "main",
+ "hash": "blake3:ideogram4"
+ },
+ "type": "ideogram4_model_loader"
+ },
+ "caption_builder": {
+ "is_intermediate": true,
+ "use_cache": true,
+ "color_palette": [],
+ "id": "caption_builder",
+ "type": "ideogram4_caption_builder",
+ "regions": [
+ {
+ "bbox": [
+ 63,
+ 250,
+ 313,
+ 750
+ ],
+ "prompt": "a red kite"
+ },
+ {
+ "bbox": [
+ 625,
+ 667,
+ 1000,
+ 1000
+ ],
+ "prompt": "a dog digging in the sand"
+ }
+ ]
+ },
+ "pos_cond": {
+ "is_intermediate": true,
+ "use_cache": true,
+ "id": "pos_cond",
+ "type": "ideogram4_text_encoder"
+ },
+ "denoise_latents": {
+ "is_intermediate": true,
+ "use_cache": true,
+ "height": 1024,
+ "id": "denoise_latents",
+ "sampler_preset": "V4_QUALITY_48",
+ "type": "ideogram4_denoise",
+ "width": 768
+ },
+ "canvas_output": {
+ "is_intermediate": true,
+ "use_cache": false,
+ "id": "canvas_output",
+ "type": "ideogram4_l2i"
+ },
+ "core_metadata_0_i": {
+ "is_intermediate": true,
+ "use_cache": true,
+ "cfg_scale": 1,
+ "cfg_rescale_multiplier": 0,
+ "generation_mode": "ideogram4_txt2img",
+ "height": 1024,
+ "id": "core_metadata_0_i",
+ "model": {
+ "base": "ideogram-4",
+ "format": "diffusers",
+ "key": "ideogram4-model",
+ "name": "Ideogram 4",
+ "type": "main",
+ "hash": "blake3:ideogram4"
+ },
+ "rand_device": "cpu",
+ "scheduler": "euler",
+ "seamless_x": false,
+ "seamless_y": false,
+ "steps": 48,
+ "type": "core_metadata",
+ "width": 768,
+ "ideogram4_color_palette": [],
+ "ideogram4_sampler_preset": "V4_QUALITY_48",
+ "clip_skip": 0
+ }
+ }
+ }
+}
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 975fac43b8..7abdd5d88e 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
@@ -185,11 +185,22 @@ const hasEdge = (graph: TestGraph, s: string, sf: string, d: string, df: string)
seedArchitectureCapabilities();
describe('isRegionalGuidanceSupportedForBase', () => {
- it('supports every base whose encoder takes a mask and whose denoiser takes a conditioning list', () => {
- for (const base of ['sd-1', 'sd-2', 'sdxl', 'flux', 'flux2', 'krea-2', 'z-image', 'anima', 'moss-image']) {
+ it('supports every base that masks conditioning or places regions in a layout prompt', () => {
+ for (const base of [
+ 'sd-1',
+ 'sd-2',
+ 'sdxl',
+ 'flux',
+ 'flux2',
+ 'krea-2',
+ 'z-image',
+ 'anima',
+ 'moss-image',
+ 'ideogram-4',
+ ]) {
expect(isRegionalGuidanceSupportedForBase(base), base).toBe(true);
}
- for (const base of ['sd-3', 'cogview4', 'qwen-image', 'ideogram-4', 'wan', 'external']) {
+ for (const base of ['sd-3', 'cogview4', 'qwen-image', 'wan', 'external']) {
expect(isRegionalGuidanceSupportedForBase(base), base).toBe(false);
}
});
@@ -236,10 +247,20 @@ describe('getRegionalGuidanceSupport', () => {
expect(getRegionalGuidanceSupport(null)).toBeNull();
});
- it('places MOSS-Image regions as layout boxes, with no negative or reference-image side', () => {
+ it('places MOSS-Image and Ideogram 4 regions as layout boxes, with no negative or reference-image side', () => {
expect(getRegionalGuidanceSupport('moss-image')).toEqual({
autoNegative: false,
label: 'MOSS-Image',
+ layoutKinds: ['object', 'character', 'text'],
+ mode: 'layout',
+ negativePrompt: false,
+ referenceImages: null,
+ });
+ // The structured caption has object elements only.
+ expect(getRegionalGuidanceSupport('ideogram-4')).toEqual({
+ autoNegative: false,
+ label: 'Ideogram 4',
+ layoutKinds: ['object'],
mode: 'layout',
negativePrompt: false,
referenceImages: null,
@@ -608,14 +629,23 @@ describe('getRegionalGuidanceRejectionReason — layout bases', () => {
});
describe('getLayoutRegionIssue', () => {
+ const allKinds = ['object', 'character', 'text'] as const;
+
it('ignores text the object and character kinds keep for a later switch back', () => {
- expect(getLayoutRegionIssue({ layout: { kind: 'object', text: '' }, positivePrompt: 'a cat' })).toBeNull();
- expect(getLayoutRegionIssue({ layout: { kind: 'character' }, positivePrompt: 'a cat' })).toBeNull();
+ expect(
+ getLayoutRegionIssue({ layout: { kind: 'object', text: '' }, positivePrompt: 'a cat' }, allKinds)
+ ).toBeNull();
+ expect(getLayoutRegionIssue({ layout: { kind: 'character' }, positivePrompt: 'a cat' }, allKinds)).toBeNull();
});
it('names the caption before the text when both are missing', () => {
- expect(getLayoutRegionIssue({ layout: { kind: 'text' }, positivePrompt: null })).toBe('missing_prompt');
- expect(getLayoutRegionIssue({ layout: { kind: 'text' }, positivePrompt: 'a sign' })).toBe('missing_text');
+ expect(getLayoutRegionIssue({ layout: { kind: 'text' }, positivePrompt: null }, allKinds)).toBe('missing_prompt');
+ expect(getLayoutRegionIssue({ layout: { kind: 'text' }, positivePrompt: 'a sign' }, allKinds)).toBe('missing_text');
+ });
+
+ it('places a stored text role as an object on a base without text regions', () => {
+ expect(getLayoutRegionIssue({ layout: { kind: 'text' }, positivePrompt: 'a sign' }, ['object'])).toBeNull();
+ expect(getLayoutRegionIssue({ layout: { kind: 'text' }, positivePrompt: ' ' }, ['object'])).toBe('missing_prompt');
});
});
@@ -628,6 +658,18 @@ describe('getLayoutPromptRejectionReason', () => {
);
});
+ it('counts a stored text role without visible text as placeable on Ideogram 4', () => {
+ expect(
+ getLayoutPromptRejectionReason({
+ base: 'ideogram-4',
+ prompt: '',
+ regions: [{ layout: { kind: 'text' }, positivePrompt: 'a sign' }],
+ })
+ ).toBe(
+ 'Ideogram 4 needs a prompt to place regional guidance in its layout. Enter a prompt or disable the regional guidance layers.'
+ );
+ });
+
it('lets a prompt, regions the layout cannot place, or a mask base through', () => {
expect(getLayoutPromptRejectionReason({ base: 'moss-image', prompt: 'a cafe', regions: [placeable] })).toBeNull();
expect(
@@ -684,6 +726,10 @@ describe('getLayoutDraftRejectionReason', () => {
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();
+ // Ideogram 4 is a layout base too, but passes `{` prompts through and has no draft to compile.
+ expect(
+ reason('{"bbox_coord_space":"abs","bbox_format":"xyxy","summary":{"caption":"x"},"items":[', 'ideogram-4')
+ ).toBeNull();
});
it('passes compiled layouts, fenced or not, with or without regions', () => {
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 d60c565a9e..609fba5c1b 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts
@@ -19,7 +19,7 @@ const NEG_COND_COLLECT_ID = 'neg_cond_collect';
/** The bases whose text encoder accepts a region mask and whose denoiser accepts a conditioning list. */
export type MaskRegionalGuidanceBase = 'sd-1' | 'sd-2' | 'sdxl' | 'flux' | 'flux2' | 'krea-2' | 'z-image' | 'anima';
/** The bases that read regions as boxes of a structured layout prompt; a mask contributes only its bounds. */
-export type LayoutRegionalGuidanceBase = 'moss-image';
+export type LayoutRegionalGuidanceBase = 'moss-image' | 'ideogram-4';
export type RegionalGuidanceBase = MaskRegionalGuidanceBase | LayoutRegionalGuidanceBase;
/** How a base consumes a region: as masked conditioning, or as a layout box around the mask. */
@@ -39,10 +39,15 @@ export interface RegionalGuidanceSupport {
autoNegative: boolean;
/** Mask-scoped reference images, or `null` when the denoiser has no regional image path. */
referenceImages: RegionalReferenceImageKind | null;
+ /** The roles a layout prompt distinguishes; empty for mask bases. */
+ layoutKinds: readonly RegionalLayoutKind[];
}
type MaskSupportRow = Pick<RegionalGuidanceSupport, 'label' | 'referenceImages'> & { mode: 'masks' };
-type LayoutSupportRow = { label: string; mode: 'layout'; referenceImages: null };
+type LayoutSupportRow = Pick<RegionalGuidanceSupport, 'label' | 'layoutKinds'> & {
+ mode: 'layout';
+ referenceImages: null;
+};
/** Graph code owns node mapping and each base's mode; the backend owns regional-negative support. */
const REGIONAL_GUIDANCE_SUPPORT: Record<MaskRegionalGuidanceBase, MaskSupportRow> &
@@ -55,7 +60,14 @@ const REGIONAL_GUIDANCE_SUPPORT: Record<MaskRegionalGuidanceBase, MaskSupportRow
'krea-2': { label: 'Krea-2', mode: 'masks', referenceImages: null },
'z-image': { label: 'Z-Image', mode: 'masks', referenceImages: null },
anima: { label: 'Anima', mode: 'masks', referenceImages: null },
- 'moss-image': { label: 'MOSS-Image', mode: 'layout', referenceImages: null },
+ 'moss-image': {
+ label: 'MOSS-Image',
+ layoutKinds: ['object', 'character', 'text'],
+ mode: 'layout',
+ referenceImages: null,
+ },
+ // The structured caption has only `obj` elements.
+ 'ideogram-4': { label: 'Ideogram 4', layoutKinds: ['object'], mode: 'layout', referenceImages: null },
};
/** Frontend graph keys are narrower than backend capability answers. */
@@ -74,9 +86,12 @@ export const getRegionalGuidanceSupport = (base: string | null): RegionalGuidanc
}
const row = REGIONAL_GUIDANCE_SUPPORT[base];
- const negative = row.mode === 'masks' && (getArchitectureFeatures(base)?.regional_negative ?? false);
+ if (row.mode === 'layout') {
+ return { ...row, autoNegative: false, negativePrompt: false };
+ }
+ const negative = getArchitectureFeatures(base)?.regional_negative ?? false;
- return { ...row, autoNegative: negative, negativePrompt: negative };
+ return { ...row, autoNegative: negative, layoutKinds: [], negativePrompt: negative };
};
/** A region's role in a layout prompt; the canvas persists a subset of these and Canvas checks it does. */
@@ -88,21 +103,30 @@ export interface RegionalLayout {
text?: string;
}
+/**
+ * The role a layout base places a region as: its stored role when the base distinguishes it, otherwise an object. The
+ * stored role stays on the layer, so switching back to a base that has it restores it.
+ */
+export const getEffectiveLayoutKind = (
+ layoutKinds: readonly RegionalLayoutKind[],
+ layout: RegionalLayout | undefined
+): RegionalLayoutKind => (layout && layoutKinds.includes(layout.kind) ? layout.kind : 'object');
+
/** What keeps a layout base from placing a region. */
export type LayoutRegionIssue = 'missing_prompt' | 'missing_text';
/**
- * Why a layout base leaves a region out, or null when it can place it: every layout element needs a caption, and a
- * text element its visible text. Whitespace alone counts as missing.
+ * Why a layout base with these roles leaves a region out, or null when it can place it: every layout element needs a
+ * caption, and a text element its visible text. Whitespace alone counts as missing.
*/
-export const getLayoutRegionIssue = (region: {
- positivePrompt: string | null;
- layout?: RegionalLayout;
-}): LayoutRegionIssue | null => {
+export const getLayoutRegionIssue = (
+ region: { positivePrompt: string | null; layout?: RegionalLayout },
+ layoutKinds: readonly RegionalLayoutKind[]
+): LayoutRegionIssue | null => {
if (!region.positivePrompt?.trim()) {
return 'missing_prompt';
}
- if (region.layout?.kind === 'text' && !region.layout.text?.trim()) {
+ if (getEffectiveLayoutKind(layoutKinds, region.layout) === 'text' && !region.layout?.text?.trim()) {
return 'missing_text';
}
return null;
@@ -122,7 +146,7 @@ export const getLayoutPromptRejectionReason = (params: {
if (
support?.mode !== 'layout' ||
params.prompt.trim().length > 0 ||
- !params.regions.some((region) => getLayoutRegionIssue(region) === null)
+ !params.regions.some((region) => getLayoutRegionIssue(region, support.layoutKinds) === null)
) {
return null;
}
@@ -179,7 +203,8 @@ export const getLayoutDraftRejectionReason = (params: {
positivePrompt: string;
promptTemplate?: PromptTemplateSnapshot | null;
}): string | null => {
- if (getRegionalGuidanceSupport(params.base)?.mode !== 'layout') {
+ // Only MOSS-Image compiles drafts; other layout bases (Ideogram 4) take `{` prompts verbatim.
+ if (params.base !== 'moss-image') {
return null;
}
const effectivePrompt = getEffectivePositivePrompt(params.positivePrompt, params.promptTemplate ?? null);
@@ -493,7 +518,7 @@ export const getRegionalGuidanceRejectionReason = (params: {
return `Regional guidance "${layerName}" has no masked region.`;
}
if (support.mode === 'layout') {
- switch (getLayoutRegionIssue(params)) {
+ switch (getLayoutRegionIssue(params, support.layoutKinds)) {
case 'missing_prompt':
return `Regional guidance "${layerName}" has no prompt to place in the ${support.label} layout.`;
case 'missing_text':
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 bc11e83fda..a3784ce41a 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
@@ -82,6 +82,13 @@ const mossImageModel: MainModelConfig = {
name: 'MOSS-Image',
type: 'main',
};
+const ideogram4Model: MainModelConfig = {
+ base: 'ideogram-4',
+ format: 'diffusers',
+ key: 'ideogram4-model',
+ name: 'Ideogram 4',
+ type: 'main',
+};
const externalModel: GenerateModelConfig = {
base: 'external',
capabilities: { modes: ['txt2img'], supports_seed: true },
@@ -2389,6 +2396,96 @@ describe('compileCanvasGraph — regional guidance', () => {
expect(getEdge(backendGraph, 'layout_prompt', 'prompt')?.source.node_id).toBe('positive_prompt');
expect(getEdge(backendGraph, 'pos_cond', 'prompt')?.source.node_id).toBe('layout_prompt');
});
+
+ it('places Ideogram 4 regions on the caption builder as boxes normalized to the 768×1024 bbox', () => {
+ const { backendGraph } = compile(ideogram4Model, 'txt2img', {
+ regionalGuidance: [
+ // 0..1000 of each side, [y_min, x_min, y_max, x_max]: x 100..400 of 768, y 10..510 of 1024.
+ region('rounded', { maskBounds: { height: 500, width: 300, x: 100, y: 10 }, positivePrompt: 'a red kite' }),
+ // Starts above the bbox and ends past its right edge.
+ region('edge', { maskBounds: { height: 100, width: 200, x: 700, y: -20 } }),
+ // Ideogram has no text elements: the stored role stays on the layer, the region is placed as an object.
+ region('stale-text', { layout: { kind: 'text' }, positivePrompt: 'a shop sign' }),
+ region('outside', { maskBounds: { height: 50, width: 50, x: 900, y: 10 } }),
+ region('empty', { maskBounds: { height: 0, width: 0, x: 0, y: 0 } }),
+ region('no-prompt', { positivePrompt: null }),
+ region('blank-prompt', { positivePrompt: ' ' }),
+ ],
+ settings: { positivePrompt: 'a beach at noon' },
+ });
+
+ expect(backendGraph.nodes.caption_builder?.regions).toEqual([
+ { bbox: [10, 130, 498, 521], prompt: 'a red kite' },
+ { bbox: [0, 911, 78, 1000], prompt: 'a cat' },
+ { bbox: [125, 83, 375, 333], prompt: 'a shop sign' },
+ ]);
+ // The global prompt still reaches the caption through the batchable prompt node; no mask is encoded.
+ expect(getEdge(backendGraph, 'caption_builder', 'prompt')?.source.node_id).toBe('positive_prompt');
+ expect(getNodeByType(backendGraph, 'alpha_mask_to_tensor')).toBeUndefined();
+ const metadata = getNodeByType(backendGraph, 'core_metadata')!;
+ expect(getEdge(backendGraph, metadata.id, 'ideogram4_caption')?.source.node_id).toBe('caption_builder');
+ });
+
+ it('leaves the Ideogram 4 graph unchanged when no region can be placed', () => {
+ // Pin the minted ids so the two graphs compare whole.
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(0);
+ const random = vi.spyOn(Math, 'random').mockReturnValue(0.5);
+ try {
+ const settings = { positivePrompt: 'a beach at noon' };
+ const plain = compile(ideogram4Model, 'txt2img', { settings }).backendGraph;
+ const unplaceable = compile(ideogram4Model, 'txt2img', {
+ regionalGuidance: [region('outside', { maskBounds: { height: 50, width: 50, x: 900, y: 10 } })],
+ settings,
+ }).backendGraph;
+
+ expect(plain.nodes.caption_builder).not.toHaveProperty('regions');
+ expect(unplaceable).toEqual(plain);
+ } finally {
+ clock.mockRestore();
+ random.mockRestore();
+ }
+ });
+
+ it('blocks Ideogram 4 regions on a blank prompt', () => {
+ expect(() =>
+ compile(ideogram4Model, 'txt2img', { regionalGuidance: [region('r1')], settings: { positivePrompt: '' } })
+ ).toThrow(
+ 'Ideogram 4 needs a prompt to place regional guidance in its layout. Enter a prompt or disable the regional guidance layers.'
+ );
+ });
+
+ it('writes the Ideogram 4 regional canvas graph the backend validates', async () => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(0);
+ const random = vi.spyOn(Math, 'random').mockReturnValue(0.5);
+ // Installed models always carry a hash, which the backend's model identifier requires.
+ const model = { ...ideogram4Model, hash: 'blake3:ideogram4' };
+ // One box inside the 768×1024 frame and one that ends on its right and bottom edges.
+ const regions = [
+ region('kite', { maskBounds: { height: 256, width: 384, x: 192, y: 64 }, positivePrompt: 'a red kite' }),
+ region('dog', {
+ maskBounds: { height: 384, width: 256, x: 512, y: 640 },
+ positivePrompt: 'a dog digging in the sand',
+ }),
+ ];
+ let txt2img: BackendGraphContract;
+ try {
+ txt2img = compile(model, 'txt2img', {
+ regionalGuidance: regions,
+ settings: { positivePrompt: 'a beach at noon' },
+ }).backendGraph;
+ } finally {
+ clock.mockRestore();
+ random.mockRestore();
+ }
+ const fixture = {
+ _comment:
+ 'Generated by compileCanvasGraph.test.ts; regenerate with `vitest -u`. Validated against the backend invocations by the Ideogram 4 regional graph tests.',
+ txt2img: { ...txt2img, id: 'ideogram4_regional_canvas_txt2img' },
+ };
+ await expect(`${JSON.stringify(fixture, null, 2)}\n`).toMatchFileSnapshot(
+ '../__snapshots__/ideogram4RegionalCanvasGraphs.json'
+ );
+ });
});
describe('compileCanvasGraph — SDXL Refiner', () => {
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 c02e8b056e..9aebab1d67 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts
@@ -45,10 +45,13 @@ import type {
import { addControlLayers, getOrAddLliteCollector } from './addControlLayers';
import {
addRegionalGuidance,
+ getEffectiveLayoutKind,
getLayoutPromptRejectionReason,
getLayoutRegionIssue,
+ getRegionalGuidanceSupport,
isLayoutRegionalGuidanceBase,
isRegionalGuidanceSupportedForBase,
+ type LayoutRegionalGuidanceBase,
type RegionalGuidanceInput,
type RegionalLayoutKind,
} from './addRegionalGuidance';
@@ -215,7 +218,8 @@ const getCanvasValidationReasons = (input: CompileCanvasGraphInput, processingSi
reasons.push('Canvas inpainting requires an inpaint mask.');
}
- // The layout node refuses regions around a blank prompt. A mask with pixels in the bbox has an area to place.
+ // A layout is built around the global prompt, so regions around a blank one are refused. A mask with pixels in the
+ // bbox has an area to place.
const layoutPromptReason = getLayoutPromptRejectionReason({
base: model.base,
prompt: getEffectivePrompts(settings).positivePrompt,
@@ -873,6 +877,8 @@ interface LayoutRegionElement {
interface AddLayoutRegionsOptions {
/** The generation bbox the regions' mask bounds are measured in. */
bbox: Pick<Rect, 'width' | 'height'>;
+ /** The roles the base distinguishes. */
+ layoutKinds: readonly RegionalLayoutKind[];
regions: readonly RegionalGuidanceInput[];
}
@@ -881,11 +887,12 @@ const clamp = (value: number, max: number): number => Math.min(Math.max(value, 0
const toLayoutElement = (
region: RegionalGuidanceInput,
+ layoutKinds: readonly RegionalLayoutKind[],
scale: { x: number; y: number },
size: { width: number; height: number }
): LayoutRegionElement | null => {
const caption = region.positivePrompt;
- if (caption === null || getLayoutRegionIssue(region) !== null) {
+ if (caption === null || getLayoutRegionIssue(region, layoutKinds) !== null) {
return null;
}
const bounds = region.maskBounds;
@@ -897,7 +904,7 @@ const toLayoutElement = (
if (x2 <= x1 || y2 <= y1) {
return null;
}
- const kind = region.layout?.kind ?? 'object';
+ const kind = getEffectiveLayoutKind(layoutKinds, region.layout);
return {
bbox: [x1, y1, x2, y2],
caption,
@@ -911,17 +918,79 @@ const toLayoutElement = (
* (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 addMossImageLayoutRegions = (graph: BackendGraphContract, options: AddLayoutRegionsOptions): void => {
const layoutPrompt = graph.nodes.layout_prompt;
if (!layoutPrompt) {
- throw new Error('addLayoutRegions: base graph is missing the layout prompt node.');
+ throw new Error('addMossImageLayoutRegions: 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 };
// 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) ?? []);
+ layoutPrompt.regions = options.regions.flatMap(
+ (region) => toLayoutElement(region, options.layoutKinds, scale, size) ?? []
+ );
+};
+
+/** One element of the `ideogram4_caption_builder` node's `regions` input; `bbox` is `[y_min, x_min, y_max, x_max]`. */
+interface Ideogram4RegionElement {
+ prompt: string;
+ bbox: [number, number, number, number];
+}
+
+/** Ideogram 4 boxes are whole numbers from 0 to 1000 across the image, origin top-left. */
+const IDEOGRAM4_COORD_MAX = 1000;
+
+const toIdeogram4Coord = (pixels: number, extent: number): number =>
+ clamp(Math.round((pixels / extent) * IDEOGRAM4_COORD_MAX), IDEOGRAM4_COORD_MAX);
+
+const toIdeogram4Region = (
+ region: RegionalGuidanceInput,
+ options: AddLayoutRegionsOptions
+): Ideogram4RegionElement | null => {
+ const prompt = region.positivePrompt;
+ if (prompt === null || getLayoutRegionIssue(region, options.layoutKinds) !== null) {
+ return null;
+ }
+ const { maskBounds: bounds } = region;
+ const { height, width } = options.bbox;
+ const yMin = toIdeogram4Coord(bounds.y, height);
+ const xMin = toIdeogram4Coord(bounds.x, width);
+ const yMax = toIdeogram4Coord(bounds.y + bounds.height, height);
+ const xMax = toIdeogram4Coord(bounds.x + bounds.width, width);
+ // A mask that misses the bbox, or rounds to a line, has no box to place.
+ if (yMax <= yMin || xMax <= xMin) {
+ return null;
+ }
+ return { bbox: [yMin, xMin, yMax, xMax], prompt };
+};
+
+/**
+ * Ideogram 4 regions: each becomes an object element of the structured caption, boxed around its mask. The output is
+ * the bbox, resized, so boxes are normalized to the bbox rather than the denoise size. The base graph's
+ * `caption_builder` assembles the caption around the global prompt at run time, so batch prompt variation still flows
+ * through `positive_prompt`, and core metadata already records its output. Regions the caption cannot place are left
+ * out, and without any the graph stays untouched.
+ */
+const addIdeogram4Regions = (graph: BackendGraphContract, options: AddLayoutRegionsOptions): void => {
+ const captionBuilder = graph.nodes.caption_builder;
+ if (!captionBuilder) {
+ throw new Error('addIdeogram4Regions: base graph is missing the caption builder node.');
+ }
+ const regions = options.regions.flatMap((region) => toIdeogram4Region(region, options) ?? []);
+ if (regions.length > 0) {
+ captionBuilder.regions = regions;
+ }
+};
+
+/** Each layout base places its regions through its own prompt node. */
+const LAYOUT_REGION_GRAFTS: Record<
+ LayoutRegionalGuidanceBase,
+ (graph: BackendGraphContract, options: AddLayoutRegionsOptions) => void
+> = {
+ 'ideogram-4': addIdeogram4Regions,
+ 'moss-image': addMossImageLayoutRegions,
};
/** Throw the first validation reason. */
@@ -1010,9 +1079,11 @@ export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanv
// Regional masks and models must already be validated. Layout bases read only each mask's bounds.
const regions = input.regionalGuidance ?? [];
const regionalBase = model.base;
- if (regions.length > 0 && isRegionalGuidanceSupportedForBase(regionalBase)) {
+ // The support row answers the layout roles; the base guards narrow the base to the graph tables' keys.
+ const regionalSupport = getRegionalGuidanceSupport(regionalBase);
+ if (regions.length > 0 && regionalSupport && isRegionalGuidanceSupportedForBase(regionalBase)) {
if (isLayoutRegionalGuidanceBase(regionalBase)) {
- addLayoutRegions(backendGraph, { bbox, regions });
+ LAYOUT_REGION_GRAFTS[regionalBase](backendGraph, { bbox, layoutKinds: regionalSupport.layoutKinds, regions });
} else {
addRegionalGuidance(backendGraph, {
base: regionalBase,
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 d1fe813291..20558f36f0 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
@@ -1273,6 +1273,13 @@ describe('Krea-2, Ideogram 4 and Wan graphs', () => {
expect(getEdge(graph, 'caption_builder', 'prompt')?.source.node_id).toBe('positive_prompt');
expect(getEdge(graph, 'pos_cond', 'prompt')?.source.node_id).toBe('caption_builder');
+ // Metadata records the encoded caption next to the prompt the user typed, which recall restores.
+ const metadata = getNodeByType(graph, 'core_metadata')!;
+ expect(getEdge(graph, metadata.id, 'ideogram4_caption')?.source).toEqual({
+ field: 'value',
+ node_id: 'caption_builder',
+ });
+ expect(getEdge(graph, metadata.id, 'positive_prompt')?.source.node_id).toBe('positive_prompt');
// Ideogram 4's denoise node has no negative conditioning input at all.
expect(graph.nodes.neg_cond).toBeUndefined();
expect(getEdge(graph, 'denoise_latents', 'negative_conditioning')).toBeUndefined();
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
index f1b7d2cba9..5440ad8093 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
@@ -1837,7 +1837,7 @@ const buildIdeogram4Graph = (
addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');
addEdge(graph, seed, 'value', denoise, 'seed');
addEdge(graph, denoise, 'latents', output, 'latents');
- addMetadata(graph, output, settings, model, 'ideogram4_txt2img', projectSettings, {
+ const metadata = addMetadata(graph, output, settings, model, 'ideogram4_txt2img', projectSettings, {
ideogram4_color_palette: settings.ideogram4ColorPalette,
ideogram4_guidance_scale: settings.ideogram4GuidanceScale ?? undefined,
ideogram4_mu: settings.ideogram4Mu ?? undefined,
@@ -1848,6 +1848,8 @@ const buildIdeogram4Graph = (
qwen3_vl_encoder: qwen3VlEncoderModel ?? undefined,
vae: vaeModel ?? undefined,
});
+ // Record the caption the encoder saw; the positive prompt alone does not show regions or palette.
+ addEdge(graph, captionBuilder, 'value', metadata, 'ideogram4_caption');
return graph;
};
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphBuilder.ts b/invokeai/frontend/webv2/src/features/generation/core/graphBuilder.ts
index 4eddd53935..5df6681799 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graphBuilder.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graphBuilder.ts
@@ -145,7 +145,7 @@ export const addMetadata = (
generationMode: string | null,
projectSettings: GenerationProjectSettings & { randDevice?: string },
extras: Record<string, unknown> = {}
-) => {
+): BackendInvocationContract => {
const loadedLoras = getLoadedLoras(graph);
const scheduler = coerceSchedulerForGraph(model, settings.scheduler);
const metadata = addNode(graph, {
@@ -174,6 +174,7 @@ export const addMetadata = (
addEdge(graph, graph.nodes.negative_prompt, 'value', metadata, 'negative_prompt');
}
addEdge(graph, metadata, 'metadata', outputNode, 'metadata');
+ return metadata;
};
export const toGraphContract = (backendGraph: BackendGraphContract, label: string) => ({
diff --git a/invokeai/frontend/webv2/src/features/generation/graph.ts b/invokeai/frontend/webv2/src/features/generation/graph.ts
index 7fc1005721..5442756938 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 {
+ getEffectiveLayoutKind,
getLayoutDraftRejectionReason,
getLayoutPromptRejectionReason,
getLayoutRegionIssue,
diff --git a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts
index 1e484876b5..f7cff9263b 100644
--- a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts
@@ -4,6 +4,7 @@ import type {
VaeModelConfig,
ComponentModelConfig,
} from '@features/generation/contracts';
+import type { CanvasRegionalGuidanceLayerContract } from '@workbench/canvas-engine/api';
import { galleryKeys } from '@features/gallery/queries';
import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
@@ -120,6 +121,68 @@ describe('resolveAndSubmitGraphPreviewInvocation', () => {
expect(prepareCanvasInvocation.mock.calls[0]?.[0]).toMatchObject({ projectId: project.id });
});
+ it('prepares nothing for a Canvas preview of a blank prompt around a layout region while Generate is selected', () => {
+ const ideogramModel: MainModelConfig = {
+ base: 'ideogram-4',
+ format: 'diffusers',
+ key: 'ideogram-4-model',
+ name: 'Ideogram 4',
+ type: 'main',
+ };
+ const region: CanvasRegionalGuidanceLayerContract = {
+ autoNegative: false,
+ blendMode: 'normal',
+ id: 'region',
+ isEnabled: true,
+ isLocked: false,
+ mask: { bitmap: { height: 64, imageName: 'region.png', width: 64 }, fill: { color: '#00ff00', style: 'solid' } },
+ name: 'Region',
+ negativePrompt: null,
+ opacity: 1,
+ positivePrompt: 'a red kite',
+ referenceImages: [],
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 32, y: 32 },
+ type: 'regional_guidance',
+ };
+ const previewWithPrompt = (positivePrompt: string) => {
+ const project = withCanvasWidgetMounted(
+ getActiveProject({
+ ...getDefaultGenerateSettings(ideogramModel),
+ model: ideogramModel,
+ modelKey: ideogramModel.key,
+ positivePrompt,
+ })
+ );
+ const prepareCanvasInvocation = vi.fn();
+ const submitted = resolveAndSubmitGraphPreviewInvocation({
+ commands: createWorkbenchStore().commands,
+ formatControlLayerError,
+ formatUpscaleMetadataFailure,
+ models: undefined,
+ owner: captureAccountScope(),
+ prepareCanvasInvocation,
+ project: {
+ ...project,
+ canvas: {
+ ...project.canvas,
+ document: {
+ ...project.canvas.document,
+ bbox: { height: 512, width: 512, x: 0, y: 0 },
+ stacks: { ...project.canvas.document.stacks, regional_guidance: [region] },
+ },
+ },
+ invocation: { ...project.invocation, sourceId: 'generate' },
+ },
+ sourceId: 'canvas',
+ });
+ return { prepared: prepareCanvasInvocation.mock.calls.length, submitted };
+ };
+
+ // Nothing uploads for a submission the compiler would reject; with a prompt the same preview goes ahead.
+ expect(previewWithPrompt('')).toEqual({ prepared: 0, submitted: false });
+ expect(previewWithPrompt('a beach at noon')).toEqual({ prepared: 1, submitted: true });
+ });
+
it('dispatches submitResolvedInvocationSnapshot for a non-canvas source and never prepares the canvas', () => {
const project = getActiveProject(createGenerateValues());
const commands = createWorkbenchStore().commands;
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.test.ts b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
index ff4031777e..0e4a62e307 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.test.ts
@@ -11,6 +11,7 @@ import type {
CanvasLayerContract,
CanvasNodeContract,
CanvasRasterLayerContractV2,
+ CanvasRegionalGuidanceLayerContract,
} from '@workbench/canvas-engine/api';
import type { InvocationRoute } from '@workbench/invocationContracts';
import type { WidgetId } from '@workbench/widgetContracts';
@@ -43,7 +44,14 @@ vi.mock('./settings/store', async (importOriginal) => {
};
});
-import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
+import {
+ resetArchitectureCapabilities,
+ setArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities';
+import {
+ architectureCapabilitiesFixture,
+ seedArchitectureCapabilities,
+} from '@features/generation/core/architectureCapabilities.testing';
import {
areInvocationRouteInputsEqual,
@@ -454,38 +462,58 @@ describe('resolveInvocationRoute — canvas source', () => {
).toBe(true);
});
- it('measures each visible raster layer against the frame, for a text-only provider on a Canvas route', () => {
- const textOnly: GenerateModelConfig = { ...unknownExternalModel, provider_id: 'openai' };
- let project = getActiveProject(createGenerateValues(textOnly));
- const raster = (
- x: number,
- y: number,
- overrides: Partial<CanvasRasterLayerContractV2> = {}
- ): CanvasRasterLayerContractV2 => ({
- blendMode: 'normal',
- id: `raster-${x}-${y}`,
- isEnabled: true,
- isLocked: false,
- name: `Raster ${x},${y}`,
- opacity: 1,
- source: { image: { height: 64, imageName: 'raster.png', width: 64 }, type: 'image' },
- transform: { rotation: 0, scaleX: 1, scaleY: 1, x, y },
- type: 'raster',
- ...overrides,
- });
- const withRaster = (layers: CanvasNodeContract[], sourceId: InvocationRoute['sourceId'] = 'canvas') =>
- getInvocationRouteInput({
- ...project,
- canvas: {
- ...project.canvas,
- document: {
- ...project.canvas.document,
- bbox: { height: 100, width: 100, x: 200, y: 0 },
- stacks: { ...project.canvas.document.stacks, raster: layers },
- },
+ const textOnlyModel: GenerateModelConfig = { ...unknownExternalModel, provider_id: 'openai' };
+ const raster = (
+ x: number,
+ y: number,
+ overrides: Partial<CanvasRasterLayerContractV2> = {}
+ ): CanvasRasterLayerContractV2 => ({
+ blendMode: 'normal',
+ id: `raster-${x}-${y}`,
+ isEnabled: true,
+ isLocked: false,
+ name: `Raster ${x},${y}`,
+ opacity: 1,
+ source: { image: { height: 64, imageName: 'raster.png', width: 64 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x, y },
+ type: 'raster',
+ ...overrides,
+ });
+ /** A project whose 100×100 frame sits at (200, 0), with these raster layers and this source selected. */
+ const projectWithRaster = (
+ model: GenerateModelConfig,
+ layers: CanvasNodeContract[],
+ sourceId: InvocationRoute['sourceId'] = 'canvas'
+ ) => {
+ const project = getActiveProject(createGenerateValues(model));
+ return {
+ ...project,
+ canvas: {
+ ...project.canvas,
+ document: {
+ ...project.canvas.document,
+ bbox: { height: 100, width: 100, x: 200, y: 0 },
+ stacks: { ...project.canvas.document.stacks, raster: layers },
},
- invocation: { ...project.invocation, sourceId },
- }).canvasRasterInFrame;
+ },
+ invocation: { ...project.invocation, sourceId },
+ };
+ };
+ /**
+ * What the workflow graph preview resolves for its Canvas button: the project's route input with Canvas mounted,
+ * the Canvas source locked over the selected one, in dialog mode.
+ */
+ const resolveCanvasPreview = (project: ReturnType<typeof getActiveProject>) =>
+ resolveInvocationRouteInput(
+ { ...getInvocationRouteInput(project), mountedWidgetIds: ['canvas', 'generate'] as WidgetId[] },
+ 'dialog',
+ { ...project.invocation, sourceId: 'canvas', sourceLocked: true }
+ );
+
+ it('measures each visible raster layer against the frame, for a text-only provider whatever the source', () => {
+ let model: GenerateModelConfig = textOnlyModel;
+ const withRaster = (layers: CanvasNodeContract[], sourceId: InvocationRoute['sourceId'] = 'canvas') =>
+ getInvocationRouteInput(projectWithRaster(model, layers, sourceId)).canvasRasterInFrame;
expect(withRaster([])).toBe(false);
expect(withRaster([raster(250, 50)])).toBe(true);
@@ -526,12 +554,22 @@ describe('resolveInvocationRoute — canvas source', () => {
])
).toBe(false);
- // Other routes and other models never measure.
- expect(withRaster([raster(250, 50)], 'generate')).toBe(false);
- project = getActiveProject(validGenerateValues);
+ // A graph preview can ask for the Canvas route while Generate is selected, so the source does not matter.
+ expect(withRaster([raster(250, 50)], 'generate')).toBe(true);
+ // Other models never measure.
+ model = animaModel;
expect(withRaster([raster(250, 50)])).toBe(false);
});
+ it('refuses a Canvas graph preview for a text-only provider over raster content while Generate is selected', () => {
+ const preview = resolveCanvasPreview(projectWithRaster(textOnlyModel, [raster(250, 50)], 'generate'));
+
+ expect(preview.sourceValid).toBe(false);
+ expect(preview.validationReasons).toEqual([
+ 'Unknown External Provider cannot use image content in the generation frame. Hide or move raster content out of the frame to generate.',
+ ]);
+ });
+
it('invalidates a zero-area generation frame', () => {
const route = resolveInvocationRouteInput(
canvasInputFor({ bbox: { height: 0, width: 512 } }),
@@ -631,54 +669,170 @@ describe('resolveInvocationRoute — canvas source', () => {
expect(modelsLoadingRoute.validationReasons).toEqual([]);
});
- it('blocks MOSS-Image layout regions around a blank prompt before anything uploads', () => {
- const mossModel: MainModelConfig = {
- base: 'moss-image',
+ describe('layout regions', () => {
+ const layoutModel = (base: 'moss-image' | 'ideogram-4', name: string): MainModelConfig => ({
+ base,
format: 'diffusers',
- key: 'moss-model',
- name: 'MOSS-Image',
+ key: `${base}-model`,
+ name,
type: 'main',
+ });
+ const mossModel = layoutModel('moss-image', 'MOSS-Image');
+ const ideogramModel = layoutModel('ideogram-4', 'Ideogram 4');
+ // The frame sits away from the document origin, so bounds must be compared in document space.
+ const frame = { height: 512, width: 512, x: 256, y: 128 };
+ /** A captioned region whose 64×64 mask bitmap starts at the layer's position. */
+ const region = (
+ id: string,
+ position: { x: number; y: number },
+ overrides: Partial<CanvasRegionalGuidanceLayerContract> = {}
+ ): CanvasRegionalGuidanceLayerContract => ({
+ autoNegative: false,
+ blendMode: 'normal',
+ id,
+ isEnabled: true,
+ isLocked: false,
+ mask: { bitmap: { height: 64, imageName: `${id}.png`, width: 64 }, fill: { color: '#00ff00', style: 'solid' } },
+ name: id,
+ negativePrompt: null,
+ opacity: 1,
+ positivePrompt: 'a shop sign',
+ referenceImages: [],
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, ...position },
+ type: 'regional_guidance',
+ ...overrides,
+ });
+ const projectFor = (
+ model: MainModelConfig,
+ overrides: Partial<GenerateWidgetValues>,
+ layers: CanvasRegionalGuidanceLayerContract[],
+ sourceId: InvocationRoute['sourceId'] = 'canvas'
+ ) => {
+ const project = getActiveProject(createGenerateValues(model, overrides));
+ return {
+ ...project,
+ canvas: {
+ ...project.canvas,
+ document: {
+ ...project.canvas.document,
+ bbox: frame,
+ stacks: { ...project.canvas.document.stacks, regional_guidance: layers },
+ },
+ },
+ invocation: { ...project.invocation, sourceId },
+ };
};
- const region = (overrides: Partial<CanvasLayerContract> = {}): CanvasLayerContract =>
- ({
- autoNegative: false,
- blendMode: 'normal',
- id: 'region-1',
- isEnabled: true,
- isLocked: false,
- mask: { bitmap: { height: 64, imageName: 'mask.png', width: 64 }, fill: { color: '#00ff00', style: 'solid' } },
- name: 'Region 1',
- negativePrompt: null,
- opacity: 1,
- positivePrompt: 'a shop sign',
- referenceImages: [],
- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
- type: 'regional_guidance',
- ...overrides,
- }) as CanvasLayerContract;
- const reasonsFor = (overrides: Partial<GenerateWidgetValues>, layers: CanvasLayerContract[]) =>
+ const inputFor = (...args: Parameters<typeof projectFor>) => getInvocationRouteInput(projectFor(...args));
+ const reasonsFor = (
+ model: MainModelConfig,
+ overrides: Partial<GenerateWidgetValues>,
+ layers: CanvasRegionalGuidanceLayerContract[]
+ ) =>
resolveInvocationRouteInput(
- canvasInputFor({ generateValues: createGenerateValues(mossModel, overrides), layers }),
+ { ...inputFor(model, overrides, layers), mountedWidgetIds: ['canvas', 'generate'] as WidgetId[] },
'global',
canvasRoute
).validationReasons;
+ const blankPromptReason = (label: string) =>
+ `${label} needs a prompt to place regional guidance in its layout. Enter a prompt or disable the regional guidance layers.`;
+
+ it.each([
+ [mossModel, 'MOSS-Image'],
+ [ideogramModel, 'Ideogram 4'],
+ ])('blocks a region inside the frame around a blank prompt before anything uploads: %s', (model, label) => {
+ expect(reasonsFor(model, { positivePrompt: ' ' }, [region('inside', { x: 300, y: 200 })])).toEqual([
+ blankPromptReason(label),
+ ]);
+ // A prompt template supplies the prompt the layout is built around.
+ const template = { id: 'poster', name: 'Poster', negativePrompt: '', positivePrompt: 'a vintage poster' };
+ expect(
+ reasonsFor(model, { positivePrompt: '', promptTemplate: template }, [region('inside', { x: 300, y: 200 })])
+ ).toEqual([]);
+ });
- 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.',
- ]);
- // A prompt template supplies the prompt the layout is built around.
- const template = { id: 'poster', name: 'Poster', negativePrompt: '', positivePrompt: 'a vintage poster' };
- expect(reasonsFor({ positivePrompt: '', promptTemplate: template }, [region()])).toEqual([]);
- // Regions that never reach the layout leave a blank prompt alone.
- const unplaced = [
- region({ id: 'empty', mask: { bitmap: null, fill: { color: '#00ff00', style: 'solid' } } }),
- region({ id: 'uncaptioned', positivePrompt: null }),
- region({ id: 'disabled', isEnabled: false }),
- ];
- expect(reasonsFor({ positivePrompt: '' }, unplaced)).toEqual([]);
+ it.each([
+ [mossModel, 'MOSS-Image'],
+ [ideogramModel, 'Ideogram 4'],
+ ])('leaves a blank prompt alone for regions that never reach the layout: %s', (model) => {
+ expect(
+ reasonsFor(model, { positivePrompt: '' }, [
+ // Entirely outside the frame, and touching its left edge (x 192..256).
+ region('outside', { x: 0, y: 0 }),
+ region('touching', { x: 192, y: 200 }),
+ region('empty', { x: 300, y: 200 }, { mask: { bitmap: null, fill: { color: '#00ff00', style: 'solid' } } }),
+ region('uncaptioned', { x: 300, y: 200 }, { positivePrompt: null }),
+ region('disabled', { x: 300, y: 200 }, { isEnabled: false }),
+ ])
+ ).toEqual([]);
+ });
+
+ it('measures each mask in document space, with its offset and transform', () => {
+ const blocks = (layer: CanvasRegionalGuidanceLayerContract) =>
+ reasonsFor(ideogramModel, { positivePrompt: '' }, [layer]).length > 0;
+
+ // Partly inside: x 230..294 crosses the frame's left edge at 256.
+ expect(blocks(region('partial', { x: 230, y: 200 }))).toBe(true);
+ // The bitmap offset moves the mask from the origin into the frame.
+ const offsetMask = { bitmap: { height: 64, imageName: 'offset.png', width: 64 }, offset: { x: 300, y: 200 } };
+ expect(
+ blocks(region('offset', { x: 0, y: 0 }, { mask: { ...offsetMask, fill: { color: '#0f0', style: 'solid' } } }))
+ ).toBe(true);
+ // Scaled 4× from x 0 it ends on the frame's edge at 256; 5× reaches 320.
+ expect(
+ blocks(region('scaled-4', { x: 0, y: 200 }, { transform: { rotation: 0, scaleX: 4, scaleY: 1, x: 0, y: 200 } }))
+ ).toBe(false);
+ expect(
+ blocks(region('scaled-5', { x: 0, y: 200 }, { transform: { rotation: 0, scaleX: 5, scaleY: 1, x: 0, y: 200 } }))
+ ).toBe(true);
+ });
+
+ it('measures whatever the model or selected source, keeping the input stable', () => {
+ const inside = [region('inside', { x: 300, y: 200 })];
+ const measured = (...args: Parameters<typeof projectFor>) =>
+ inputFor(...args).canvasRegionalLayersInFrame.map((layer) => layer.id);
+
+ expect(measured(ideogramModel, {}, inside)).toEqual(['inside']);
+ expect(measured(animaModel, {}, inside)).toEqual(['inside']);
+ expect(measured(ideogramModel, {}, inside, 'generate')).toEqual(['inside']);
+
+ const withRegions = projectFor(ideogramModel, {}, inside);
+ // Recomputing over the same document yields an equal input, so the stable selector keeps its identity.
+ expect(
+ areInvocationRouteInputsEqual(getInvocationRouteInput(withRegions), getInvocationRouteInput(withRegions))
+ ).toBe(true);
+ });
+
+ it('blocks a blank prompt when the capability table arrives after the route input', () => {
+ // The project loads first: no base has regional support yet. The file's seed hooks restore the table after.
+ resetArchitectureCapabilities();
+ const input = inputFor(ideogramModel, { positivePrompt: '' }, [region('inside', { x: 300, y: 200 })]);
+ setArchitectureCapabilities(architectureCapabilitiesFixture);
+
+ expect(
+ resolveInvocationRouteInput(
+ { ...input, mountedWidgetIds: ['canvas', 'generate'] as WidgetId[] },
+ 'global',
+ canvasRoute
+ ).validationReasons
+ ).toEqual([blankPromptReason('Ideogram 4')]);
+ });
+
+ it.each([
+ [mossModel, 'MOSS-Image'],
+ [ideogramModel, 'Ideogram 4'],
+ ])('resolves a Canvas graph preview while Generate is selected against the frame: %s', (model, label) => {
+ const previewReasons = (layers: CanvasRegionalGuidanceLayerContract[]) =>
+ resolveCanvasPreview(projectFor(model, { positivePrompt: '' }, layers, 'generate')).validationReasons;
+
+ expect(previewReasons([region('inside', { x: 300, y: 200 })])).toEqual([blankPromptReason(label)]);
+ expect(previewReasons([region('outside', { x: 0, y: 0 })])).toEqual([]);
+ });
+
+ it('blocks a MOSS-Image layout draft that is not valid JSON on the Canvas route', () => {
+ expect(reasonsFor(mossModel, { 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.',
+ ]);
+ });
});
it('treats the layer stack identity as part of the route input', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.ts
index 74d5fcc432..e1507c1e5c 100644
--- a/invokeai/frontend/webv2/src/workbench/invocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts
@@ -1,6 +1,6 @@
import type { ModelConfig } from '@features/models';
import type { ProjectGraphState } from '@features/workflow/contracts';
-import type { CanvasLayerContract } from '@workbench/canvas-engine/api';
+import type { CanvasLayerContract, CanvasRegionalGuidanceLayerContract } from '@workbench/canvas-engine/api';
import type {
InvocationMode,
InvocationRoute,
@@ -119,9 +119,15 @@ export interface InvocationRouteInput {
canvasLayers: readonly CanvasLayerContract[];
/**
* Whether a visible raster layer's bounds overlap the frame, so a text-only hosted model is blocked before invoke
- * without reading pixels. Measured only for a Canvas route with such a model; false otherwise.
+ * without reading pixels. Measured only with such a model, whatever the selected source; false otherwise.
*/
canvasRasterInFrame: boolean;
+ /**
+ * The enabled, painted regional guidance layers whose mask bounds overlap the frame (identity-stable), which a
+ * layout base places around the global prompt. Measured whatever the model: which bases read them is capability
+ * data that can arrive after the project, so readiness decides that when it runs.
+ */
+ canvasRegionalLayersInFrame: readonly CanvasRegionalGuidanceLayerContract[];
}
const getMountedWidgetIds = (project: Project): WidgetId[] => {
@@ -149,6 +155,15 @@ const getMountedWidgetIds = (project: Project): WidgetId[] => {
return Array.from(mountedWidgetIds).sort();
};
+type FrameRect = Project['canvas']['document']['bbox'];
+
+/** Whether document-space bounds overlap the frame's interior; touching its edge does not. */
+const overlapsFrame = (bounds: FrameRect, frame: FrameRect): boolean =>
+ bounds.x < frame.x + frame.width &&
+ frame.x < bounds.x + bounds.width &&
+ bounds.y < frame.y + frame.height &&
+ frame.y < bounds.y + bounds.height;
+
/**
* Whether a raster layer the generation composite draws overlaps the frame's interior with its own bounds. Invoke
* decides from the composite's pixels, so this errs toward not blocking where geometry is uncertain: text is skipped
@@ -176,31 +191,52 @@ const hasRasterContentInFrame = (document: Project['canvas']['document']): boole
return false;
}
- const bounds = getSourceBounds(layer, document);
-
- return (
- bounds.x < bbox.x + bbox.width &&
- bbox.x < bounds.x + bounds.width &&
- bounds.y < bbox.y + bbox.height &&
- bbox.y < bounds.y + bounds.height
- );
+ return overlapsFrame(getSourceBounds(layer, document), bbox);
});
};
+const NO_REGIONAL_LAYERS: readonly CanvasRegionalGuidanceLayerContract[] = [];
+
+/**
+ * The compositable regional guidance layers whose mask bounds, offset and transform included, overlap the frame's
+ * interior: the regions a layout base can place. The one remaining approximation is a mask bitmap that reaches into
+ * the frame with transparent pixels only (a legacy document-sized mask, say), which still counts here although the
+ * canvas compiler, reading the uploaded mask's pixels, leaves it out.
+ */
+const getRegionalLayersInFrame = (
+ document: Project['canvas']['document'],
+ layers: readonly CanvasLayerContract[]
+): readonly CanvasRegionalGuidanceLayerContract[] => {
+ const { bbox } = document;
+
+ if (bbox.width <= 0 || bbox.height <= 0) {
+ return NO_REGIONAL_LAYERS;
+ }
+
+ const inFrame = layers.filter(
+ (layer): layer is CanvasRegionalGuidanceLayerContract =>
+ isCompositableRegionalGuidanceLayer(layer) && overlapsFrame(getSourceBounds(layer, document), bbox)
+ );
+
+ return inFrame.length > 0 ? inFrame : NO_REGIONAL_LAYERS;
+};
+
export const getInvocationRouteInput = (project: Project): InvocationRouteInput => {
const generateValues = getProjectWidgetValues(project, 'generate');
- // This runs on every project change, so only a Canvas route with the model it gates measures layers.
+ // Canvas facts are measured whatever source is selected: a graph preview resolves the Canvas route from this same
+ // input while another source is. This runs on every project change, over leaves the document index caches; raster
+ // layers are measured only for the model they gate.
const measuresRaster =
- project.invocation.sourceId === 'canvas' &&
- isGenerateModelConfig(generateValues.model) &&
- isExternalTextOnlyCanvasModel(generateValues.model);
+ isGenerateModelConfig(generateValues.model) && isExternalTextOnlyCanvasModel(generateValues.model);
+ const canvasLayers = compileContributingLayers(project.canvas.document);
return {
canvasBbox: {
height: project.canvas.document.bbox.height,
width: project.canvas.document.bbox.width,
},
- canvasLayers: compileContributingLayers(project.canvas.document),
+ canvasLayers,
+ canvasRegionalLayersInFrame: getRegionalLayersInFrame(project.canvas.document, canvasLayers),
canvasRasterInFrame: measuresRaster && hasRasterContentInFrame(project.canvas.document),
generateValues,
upscaleValues: getProjectWidgetValues(project, 'upscale'),
@@ -225,6 +261,7 @@ export const areInvocationRouteInputsEqual = (left: InvocationRouteInput, right:
left.canvasBbox.height === right.canvasBbox.height &&
left.canvasLayers === right.canvasLayers &&
left.canvasRasterInFrame === right.canvasRasterInFrame &&
+ areArraysEqual(left.canvasRegionalLayersInFrame, right.canvasRegionalLayersInFrame) &&
areArraysEqual(left.mountedWidgetIds, right.mountedWidgetIds);
export const createInvocationRouteInputSelector = () =>
@@ -374,11 +411,11 @@ export const resolveInvocationRouteInput = (
}).map((controlLayerIssue) => ({ controlLayerIssue }))
);
}
- // Before anything uploads; a region whose mask misses the frame still counts here.
+ // Before anything uploads, so only the regions whose mask bounds reach into the frame count.
const layoutPromptReason = getLayoutPromptRejectionReason({
base: values.model.base,
prompt: getEffectivePrompts(values).positivePrompt,
- regions: input.canvasLayers.filter(isCompositableRegionalGuidanceLayer),
+ regions: input.canvasRegionalLayersInFrame,
});
if (layoutPromptReason) {
validationReasons.push(layoutPromptReason);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx
index 596922ae01..6d78d9dd6a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx
@@ -225,10 +225,33 @@ describe('RegionalGuidanceSettings on a layout base', () => {
expect(host!.querySelector('[role="status"]')).toBeNull();
});
- it('names the region type by its label and describes it with the help text', async () => {
+ it('describes the region type by the roles and the prompt field by the box', async () => {
await renderLive('moss-image');
expect(descriptionOf(kindGroup().element())).toEqual(['widgets.layers.regionalGuidance.layoutKindHelp']);
+ expect(descriptionOf(promptInput().element())).toEqual(['widgets.layers.regionalGuidance.layoutBoxHelp']);
+ });
+
+ it('offers no region type or visible text on a base with objects only, keeping a stored text role', async () => {
+ await renderLive('ideogram-4', { layout: { kind: 'text' }, negativePrompt: 'blurry' });
+
+ expect(kindGroup().query()).toBeNull();
+ expect(visibleTextInput().query()).toBeNull();
+ expect(negativeInput().query()).toBeNull();
+ // Placed as an object, a text role needs no visible text.
+ expect(announced()).toBe('');
+ expect(descriptionOf(promptInput().element())).toEqual(['widgets.layers.regionalGuidance.layoutBoxHelp']);
+ expect(liveLayer().layout).toEqual({ kind: 'text' });
+ });
+
+ it('describes the prompt field by the box and a missing prompt together', async () => {
+ await renderLive('ideogram-4', { positivePrompt: null });
+
+ expect(announced()).toBe('widgets.layers.regionalGuidance.layoutMissingPrompt');
+ expect(descriptionOf(promptInput().element())).toEqual([
+ 'widgets.layers.regionalGuidance.layoutBoxHelp',
+ 'widgets.layers.regionalGuidance.layoutMissingPrompt',
+ ]);
});
it('records a type switch and the visible text as one undo step each, keeping text across a switch', async () => {
@@ -297,7 +320,10 @@ describe('RegionalGuidanceSettings on a layout base', () => {
it('commits an unsaved caption when Invoke flushes drafts from inside the field (Ctrl+Enter)', async () => {
await renderLive('moss-image', { positivePrompt: null });
expect(announced()).toBe('widgets.layers.regionalGuidance.layoutMissingPrompt');
- expect(descriptionOf(promptInput().element())).toEqual(['widgets.layers.regionalGuidance.layoutMissingPrompt']);
+ expect(descriptionOf(promptInput().element())).toEqual([
+ 'widgets.layers.regionalGuidance.layoutBoxHelp',
+ 'widgets.layers.regionalGuidance.layoutMissingPrompt',
+ ]);
await act(() => promptInput().fill('a neon sign'));
expect(stub.commits).toHaveLength(0);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
index dcf739978a..b9803e6d54 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
@@ -21,6 +21,7 @@ import {
} from '@chakra-ui/react';
import { PromptTextarea } from '@features/generation/components';
import {
+ getEffectiveLayoutKind,
getLayoutRegionIssue,
getRegionalGuidanceSupport,
supportsPromptAttentionSyntax,
@@ -167,14 +168,19 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett
[commitConfig, t]
);
- // Layout bases read the region's role and, for text, its exact text; the stored role survives model switches.
+ // Layout bases read the region's role and, for text, its exact text; the stored role survives model switches, and a
+ // base without it places the region as an object. A base with only one role offers no choice.
const isLayout = support?.mode === 'layout';
+ const layoutKinds = isLayout ? support.layoutKinds : [];
+ const showLayoutKinds = layoutKinds.length > 1;
const layoutKind = layer.layout?.kind ?? 'object';
+ const effectiveLayoutKind = getEffectiveLayoutKind(layoutKinds, layer.layout);
const storedVisibleText = layer.layout?.text;
// Null while not editing, so undo and edits from elsewhere show through.
const [visibleTextDraft, setVisibleTextDraft] = useState<string | null>(null);
const visibleText = visibleTextDraft ?? storedVisibleText ?? '';
const layoutKindFieldId = useId();
+ const promptFieldId = useId();
const promptIssueId = useId();
const visibleTextIssueId = useId();
@@ -235,10 +241,17 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett
// Generation skips a region the layout cannot place. The warning sits under the missing value and describes its
// control; a status region that exists before any warning announces each change.
- const layoutIssue =
- isLayout && support
- ? getLayoutRegionIssue({ layout: { kind: layoutKind, text: visibleText }, positivePrompt })
- : null;
+ const layoutIssue = isLayout
+ ? getLayoutRegionIssue({ layout: { kind: layoutKind, text: visibleText }, positivePrompt }, layoutKinds)
+ : null;
+ // The prompt field explains the box on every layout base; the region type's help explains only the roles.
+ const promptHelp = isLayout
+ ? t('widgets.layers.regionalGuidance.layoutBoxHelp', { model: support.label })
+ : undefined;
+ const promptDescription =
+ [promptHelp ? `${promptFieldId}-help` : null, layoutIssue === 'missing_prompt' ? promptIssueId : null]
+ .filter(Boolean)
+ .join(' ') || undefined;
const layoutIssueMessage = layoutIssue
? t(
layoutIssue === 'missing_prompt'
@@ -304,9 +317,9 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett
{t('widgets.layers.regionalGuidance.unsupportedModel')}
</Text>
) : null}
- {isLayout && support ? (
+ {isLayout && showLayoutKinds ? (
<Field
- helpText={t('widgets.layers.regionalGuidance.layoutKindHelp', { model: support.label })}
+ helpText={t('widgets.layers.regionalGuidance.layoutKindHelp')}
id={layoutKindFieldId}
label={t('widgets.layers.regionalGuidance.layoutKind')}
>
@@ -319,9 +332,9 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett
/>
</Field>
) : null}
- <Field label={t('widgets.layers.regionalGuidance.positivePrompt')}>
+ <Field helpText={promptHelp} id={promptFieldId} label={t('widgets.layers.regionalGuidance.positivePrompt')}>
<PromptTextarea
- aria-describedby={layoutIssue === 'missing_prompt' ? promptIssueId : undefined}
+ aria-describedby={promptDescription}
aria-label={t('widgets.layers.regionalGuidance.positivePrompt')}
attentionSyntax={attentionSyntax}
defaultHeightPx={REGIONAL_PROMPT_HEIGHT_PX}
@@ -340,7 +353,7 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett
{layoutIssueMessage}
</Text>
) : null}
- {isLayout && layoutKind === 'text' ? (
+ {isLayout && effectiveLayoutKind === 'text' ? (
<Field label={t('widgets.layers.regionalGuidance.visibleText')}>
<Textarea
aria-describedby={layoutIssue === 'missing_text' ? visibleTextIssueId : undefined}
diff --git a/tests/app/invocations/test_frontend_ideogram4_regional_graphs.py b/tests/app/invocations/test_frontend_ideogram4_regional_graphs.py
new file mode 100644
index 0000000000..02d1f457f5
--- /dev/null
+++ b/tests/app/invocations/test_frontend_ideogram4_regional_graphs.py
@@ -0,0 +1,88 @@
+"""The Ideogram 4 regional canvas graph webv2 compiles is a graph this backend accepts, and captions what was drawn.
+
+`ideogram4RegionalCanvasGraphs.json` is written by webv2's `compileCanvasGraph.test.ts` (regenerate with `vitest -u`)
+from the real canvas compiler: a txt2img submission on a 768x1024 canvas with two Regional Guidance layers, one inside
+the frame and one ending on its right and bottom edges. pydantic validates every node against its invocation, the
+regions against `Ideogram4Region` included; `Graph.validate_self` checks every edge type, the one into
+`core_metadata.ideogram4_caption` included; and the caption builder runs on its literal inputs. No model is loaded.
+"""
+
+import json
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from invokeai.app.invocations.ideogram4.ideogram4_caption import Ideogram4CaptionBuilderInvocation
+from invokeai.app.services.shared.graph import Graph
+
+FIXTURE_PATH = (
+ Path(__file__).parents[3]
+ / "invokeai"
+ / "frontend"
+ / "webv2"
+ / "src"
+ / "features"
+ / "generation"
+ / "core"
+ / "__snapshots__"
+ / "ideogram4RegionalCanvasGraphs.json"
+)
+
+RAW_GRAPH: dict[str, Any] = json.loads(FIXTURE_PATH.read_text(encoding="utf-8"))["txt2img"]
+
+
+def graph() -> Graph:
+ graph = Graph.model_validate(RAW_GRAPH)
+ graph.validate_self()
+ return graph
+
+
+def _source(graph: Graph, node_id: str, field: str) -> tuple[str, str]:
+ (edge,) = [e for e in graph.edges if e.destination.node_id == node_id and e.destination.field == field]
+ return edge.source.node_id, edge.source.field
+
+
+def test_every_field_the_frontend_writes_is_one_the_invocation_declares(graph: Graph) -> None:
+ """Pydantic ignores an unknown key, so a misnamed field (`desc` for a region's `prompt`) would validate and run
+ at its default. Region values must also survive validation unchanged."""
+ for node_id, raw in RAW_GRAPH["nodes"].items():
+ node = graph.nodes[node_id]
+ if type(node).model_config.get("extra") == "allow":
+ # `core_metadata` records whatever the graph gives it, feature fields included, and persists the extras.
+ continue
+ unknown = set(raw) - set(type(node).model_fields)
+ assert unknown == set(), f"{raw['type']} has no field(s) {sorted(unknown)}"
+
+ builder = graph.nodes["caption_builder"]
+ assert isinstance(builder, Ideogram4CaptionBuilderInvocation)
+ assert [region.model_dump() for region in builder.regions] == RAW_GRAPH["nodes"]["caption_builder"]["regions"]
+
+
+def test_the_caption_is_what_is_encoded_and_recorded(graph: Graph) -> None:
+ # The prompt that batching varies feeds the caption builder, whose output is the only thing the encoder sees.
+ assert _source(graph, "caption_builder", "prompt") == ("positive_prompt", "value")
+ assert _source(graph, "pos_cond", "prompt") == ("caption_builder", "value")
+ metadata_id = next(node.id for node in graph.nodes.values() if node.get_type() == "core_metadata")
+ assert _source(graph, metadata_id, "ideogram4_caption") == ("caption_builder", "value")
+ # Recall restores the prompt the user typed, not the compiled caption.
+ assert _source(graph, metadata_id, "positive_prompt") == ("positive_prompt", "value")
+
+
+def test_the_caption_builder_places_the_drawn_regions(graph: Graph) -> None:
+ builder = graph.nodes["caption_builder"]
+ assert isinstance(builder, Ideogram4CaptionBuilderInvocation)
+ # The positive prompt arrives through the edge at run time; this stands in for the batch value.
+ runtime = builder.model_copy(update={"prompt": "A sunny beach."})
+
+ caption = runtime.invoke(None).value # type: ignore[arg-type]
+
+ # 768x1024 in 0..1000, [y_min, x_min, y_max, x_max]: the kite spans x 192..576 and y 64..320, the dog
+ # x 512..768 and y 640..1024; 62.5 and 312.5 round up, 666.7 to 667.
+ assert caption == (
+ '{"high_level_description":"A sunny beach.","compositional_deconstruction":{"background":"","elements":['
+ '{"type":"obj","bbox":[63,250,313,750],"desc":"a red kite"},'
+ '{"type":"obj","bbox":[625,667,1000,1000],"desc":"a dog digging in the sand"}'
+ "]}}"
+ )
diff --git a/tests/backend/architectures/test_features.py b/tests/backend/architectures/test_features.py
index 181d046b20..cbbfade993 100644
--- a/tests/backend/architectures/test_features.py
+++ b/tests/backend/architectures/test_features.py
@@ -122,14 +122,25 @@ def test_regional_guidance_and_its_negative_subset() -> None:
`sdxl_compel_prompt` path masks both prompt polarities. The FLUX / FLUX.2 / Krea-2 / Z-Image /
Anima denoisers mask positive conditioning only -- Z-Image and Anima accept a negative list but
discard its masks, so a "regional" negative there would act globally and webv2 rejects it.
- MOSS-Image masks nothing: its regions become boxes in the JSON layout prompt, which has no
- negative counterpart.
+ MOSS-Image and Ideogram 4 mask nothing: their regions become boxes in a JSON layout prompt or
+ structured caption, which has no negative counterpart.
"""
regional = {
b.value for b in generative_bases() if (f := get(b, FeaturesFacet)) is not None and f.supports_regional_guidance
}
negative = {b.value for b in generative_bases() if (f := get(b, FeaturesFacet)) is not None and f.regional_negative}
- assert regional == {"sd-1", "sd-2", "sdxl", "flux", "flux2", "krea-2", "z-image", "anima", "moss-image"}
+ assert regional == {
+ "sd-1",
+ "sd-2",
+ "sdxl",
+ "flux",
+ "flux2",
+ "krea-2",
+ "z-image",
+ "anima",
+ "moss-image",
+ "ideogram-4",
+ }
assert negative == {"sd-1", "sd-2", "sdxl"}
assert negative < regional, "a regional negative prompt without regional guidance is meaningless"