Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(canvas): regional guidance for every base the backend masks
Josh Corbett693c999bedc6
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 77a490fbd3..499ecd732b 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -3230,7 +3230,6 @@"addReferenceImage": "Add reference image","autoNegative": "Auto-Negative","clearReferenceImage": "Clear reference image",- "flux2PositiveOnly": "FLUX.2 regional guidance supports positive prompts only. Negative prompts, Auto-Negative, and reference images must be removed before generation.","method": "Method","methods": {"composition": "Composition",@@ -3251,6 +3250,7 @@"referenceImages": "Reference images","removeReferenceImage": "Remove reference image","selectModel": "Select a model",+ "unsupportedModel": "The selected model does not support regional guidance. This layer is skipped during generation.","weight": "Weight"},"types": {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.tsindex feaa093a2a..c0a0e78676 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@@ -5,6 +5,7 @@ import type { AddRegionalGuidanceOptions, RegionalGuidanceInput, RegionalReferenimport {addRegionalGuidance,getRegionalGuidanceRejectionReason,+ getRegionalGuidanceSupport,isRegionalGuidanceSupportedForBase,} from './addRegionalGuidance';@@ -112,6 +113,39 @@ const krea2BaseGraph = (): TestGraph => ({},});+/** A minimal Qwen3-encoder graph (Z-Image / Anima): pos + neg collectors, CFG on. */+const qwen3BaseGraph = (encoderType: 'z_image_text_encoder' | 'anima_text_encoder'): TestGraph => ({+ edges: [+ {+ destination: { field: 'qwen3_encoder', node_id: 'pos_cond' },+ source: { field: 'qwen3_encoder', node_id: 'model_loader' },+ },+ {+ destination: { field: 'qwen3_encoder', node_id: 'neg_cond' },+ source: { field: 'qwen3_encoder', node_id: 'model_loader' },+ },+ {+ destination: { field: 'positive_conditioning', node_id: 'denoise_latents' },+ source: { field: 'collection', node_id: 'pos_cond_collect' },+ },+ {+ destination: { field: 'negative_conditioning', node_id: 'denoise_latents' },+ source: { field: 'collection', node_id: 'neg_cond_collect' },+ },+ ],+ id: 'g',+ nodes: {+ denoise_latents: {+ id: 'denoise_latents',+ type: encoderType === 'anima_text_encoder' ? 'anima_denoise' : 'z_image_denoise',+ },+ neg_cond: { id: 'neg_cond', type: encoderType },+ neg_cond_collect: { id: 'neg_cond_collect', type: 'collect' },+ pos_cond: { id: 'pos_cond', type: encoderType },+ pos_cond_collect: { id: 'pos_cond_collect', type: 'collect' },+ },+});+const ipModel = (base: string): RegionalReferenceModel => ({base,key: `ip-${base}`,@@ -141,14 +175,61 @@ const hasEdge = (graph: TestGraph, s: string, sf: string, d: string, df: string));describe('isRegionalGuidanceSupportedForBase', () => {- it('supports sd-1 / sdxl / flux / flux2 / krea-2 and nothing else', () => {- expect(isRegionalGuidanceSupportedForBase('sd-1')).toBe(true);- expect(isRegionalGuidanceSupportedForBase('sdxl')).toBe(true);- expect(isRegionalGuidanceSupportedForBase('flux')).toBe(true);- expect(isRegionalGuidanceSupportedForBase('flux2')).toBe(true);- expect(isRegionalGuidanceSupportedForBase('krea-2')).toBe(true);- expect(isRegionalGuidanceSupportedForBase('sd-3')).toBe(false);- expect(isRegionalGuidanceSupportedForBase('cogview4')).toBe(false);+ 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']) {+ expect(isRegionalGuidanceSupportedForBase(base), base).toBe(true);+ }+ for (const base of ['sd-3', 'cogview4', 'qwen-image', 'ideogram-4', 'wan', 'external']) {+ expect(isRegionalGuidanceSupportedForBase(base), base).toBe(false);+ }+ });+});++describe('getRegionalGuidanceSupport', () => {+ it('masks both polarities plus IP-Adapters on the SD family only', () => {+ for (const base of ['sd-1', 'sd-2', 'sdxl']) {+ expect(getRegionalGuidanceSupport(base)).toMatchObject({+ autoNegative: true,+ negativePrompt: true,+ referenceImages: 'ip_adapter',+ });+ }+ expect(getRegionalGuidanceSupport('flux')).toMatchObject({+ autoNegative: false,+ negativePrompt: false,+ referenceImages: 'flux_redux',+ });+ for (const base of ['flux2', 'krea-2', 'z-image', 'anima']) {+ expect(getRegionalGuidanceSupport(base), base).toMatchObject({+ autoNegative: false,+ negativePrompt: false,+ referenceImages: null,+ });+ }+ expect(getRegionalGuidanceSupport('sd-3')).toBeNull();+ expect(getRegionalGuidanceSupport(null)).toBeNull();+ });+});++describe('addRegionalGuidance — Z-Image / Anima', () => {+ it.each([+ ['z-image', 'z_image_text_encoder'],+ ['anima', 'anima_text_encoder'],+ ] as const)('%s wires a masked positive prompt through its Qwen3 encoder, positive only', (base, encoderType) => {+ const g = run(qwen3BaseGraph(encoderType), {+ base,+ regions: [region({ autoNegative: true, negativePrompt: 'blurry' })],+ });++ expect(g.nodes.rg_pos_cond_r1).toMatchObject({ prompt: 'a cat', type: encoderType });+ expect(hasEdge(g, 'model_loader', 'qwen3_encoder', 'rg_pos_cond_r1', 'qwen3_encoder')).toBe(true);+ expect(hasEdge(g, 'rg_mask_to_tensor_r1', 'mask', 'rg_pos_cond_r1', 'mask')).toBe(true);+ expect(hasEdge(g, 'rg_pos_cond_r1', 'conditioning', 'pos_cond_collect', 'item')).toBe(true);+ // The backend discards masks on negative conditioning for these bases, so nothing reaches the+ // negative collector even though the graph has one.+ expect(g.nodes.rg_neg_cond_r1).toBeUndefined();+ expect(g.nodes.rg_pos_cond_inverted_r1).toBeUndefined();+ expect(g.edges.some((e) => e.destination.node_id === 'neg_cond_collect')).toBe(false);});});@@ -273,6 +354,16 @@ describe('addRegionalGuidance — SD1', () => {});});+describe('addRegionalGuidance — SD2', () => {+ it('uses the compel encoder with both polarities like SD1', () => {+ const g = run(sdBaseGraph(), { base: 'sd-2', regions: [region({ autoNegative: true, negativePrompt: 'blurry' })] });+ expect(g.nodes.rg_pos_cond_r1).toMatchObject({ prompt: 'a cat', type: 'compel' });+ expect(g.nodes.rg_neg_cond_r1).toMatchObject({ prompt: 'blurry', type: 'compel' });+ expect(g.nodes.rg_pos_cond_inverted_r1).toBeDefined();+ expect(hasEdge(g, 'clip_skip', 'clip', 'rg_pos_cond_r1', 'clip')).toBe(true);+ });+});+describe('addRegionalGuidance — SDXL', () => {it('sets prompt + style on the sdxl encoder and copies clip + clip2', () => {const g = run(sdBaseGraph({ sdxl: true }), { base: 'sdxl', regions: [region()] });@@ -360,7 +451,6 @@ describe('addRegionalGuidance — multiple regions coexist', () => {describe('getRegionalGuidanceRejectionReason', () => {const params = {- autoNegative: false,hasContent: true,layerName: 'Region 1',mainBase: 'sd-1',@@ -382,41 +472,54 @@ describe('getRegionalGuidanceRejectionReason', () => {});it('rejects a region with no prompt and no reference images', () => {- expect(getRegionalGuidanceRejectionReason({ ...params, positivePrompt: null, referenceImageCount: 0 })).toMatch(- /no prompt or reference/- );+ expect(getRegionalGuidanceRejectionReason({ ...params, positivePrompt: null })).toMatch(/no prompt or reference/);});- it('rejects a FLUX negative prompt / autoNegative', () => {- expect(getRegionalGuidanceRejectionReason({ ...params, mainBase: 'flux', negativePrompt: 'blurry' })).toMatch(- /negative prompts are not supported for FLUX/- );- expect(getRegionalGuidanceRejectionReason({ ...params, autoNegative: true, mainBase: 'flux' })).toMatch(- /auto-negative is not supported for FLUX/- );+ it('accepts an SD region that only carries a negative prompt or a reference image', () => {+ expect(+ getRegionalGuidanceRejectionReason({ ...params, negativePrompt: 'blurry', positivePrompt: null })+ ).toBeNull();+ expect(getRegionalGuidanceRejectionReason({ ...params, positivePrompt: null, referenceImageCount: 1 })).toBeNull();+ expect(+ getRegionalGuidanceRejectionReason({ ...params, mainBase: 'sd-2', positivePrompt: null, referenceImageCount: 1 })+ ).toBeNull();});- it('rejects FLUX.2 negative prompts, autoNegative, and reference images', () => {- expect(getRegionalGuidanceRejectionReason({ ...params, mainBase: 'flux2', negativePrompt: 'blurry' })).toMatch(- /negative prompts are not supported for FLUX\.2/- );- expect(getRegionalGuidanceRejectionReason({ ...params, autoNegative: true, mainBase: 'flux2' })).toMatch(- /auto-negative is not supported for FLUX\.2/- );- expect(getRegionalGuidanceRejectionReason({ ...params, mainBase: 'flux2', referenceImageCount: 1 })).toMatch(- /reference images are not supported for FLUX\.2/- );+ it.each(['flux', 'flux2', 'krea-2', 'z-image', 'anima'])(+ 'keeps a %s region whose positive prompt is usable even with unsupported extras attached',+ (mainBase) => {+ expect(+ getRegionalGuidanceRejectionReason({+ ...params,+ mainBase,+ negativePrompt: 'blurry',+ referenceImageCount: 1,+ })+ ).toBeNull();+ }+ );++ it.each([+ ['flux', 'FLUX', 0],+ ['flux2', 'FLUX.2', 1],+ ['krea-2', 'Krea-2', 1],+ ['z-image', 'Z-Image', 1],+ ['anima', 'Anima', 1],+ ])('rejects a %s region that carries only what the base ignores', (mainBase, label, referenceImageCount) => {+ expect(+ getRegionalGuidanceRejectionReason({+ ...params,+ mainBase,+ negativePrompt: 'blurry',+ positivePrompt: null,+ referenceImageCount,+ })+ ).toBe(`Regional guidance "Region 1" has no prompt or reference image ${label} can use.`);});- it('rejects Krea-2 negative prompts, autoNegative, and reference images', () => {- expect(getRegionalGuidanceRejectionReason({ ...params, mainBase: 'krea-2', negativePrompt: 'blurry' })).toMatch(- /negative prompts are not supported for Krea-2/- );- expect(getRegionalGuidanceRejectionReason({ ...params, autoNegative: true, mainBase: 'krea-2' })).toMatch(- /auto-negative is not supported for Krea-2/- );- expect(getRegionalGuidanceRejectionReason({ ...params, mainBase: 'krea-2', referenceImageCount: 1 })).toMatch(- /reference images are not supported for Krea-2/- );+ it('keeps a FLUX region that only carries a Redux reference image', () => {+ expect(+ getRegionalGuidanceRejectionReason({ ...params, mainBase: 'flux', positivePrompt: null, referenceImageCount: 1 })+ ).toBeNull();});});diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.tsindex 65b0bf460c..064f152d70 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts@@ -10,15 +10,48 @@ const NEG_COND_ID = 'neg_cond';const POS_COND_COLLECT_ID = 'pos_cond_collect';const NEG_COND_COLLECT_ID = 'neg_cond_collect';-/** The base models regional guidance supports. */-export type RegionalGuidanceBase = 'sd-1' | 'sdxl' | 'flux' | 'flux2' | 'krea-2';+/** The base models whose text encoder accepts a region mask and whose denoiser accepts a conditioning list. */+export type RegionalGuidanceBase = 'sd-1' | 'sd-2' | 'sdxl' | 'flux' | 'flux2' | 'krea-2' | 'z-image' | 'anima';++/** The reference-image node kind a base's regions can consume. */+export type RegionalReferenceImageKind = 'ip_adapter' | 'flux_redux';++/** What the backend honours per region for one base, beyond the masked positive prompt. */+export interface RegionalGuidanceSupport {+ /** Display name used in rejection reasons and settings hints. */+ label: string;+ /** Masked regional negative prompts reach the negative collector. */+ negativePrompt: boolean;+ /** The positive prompt can be re-encoded over the inverted mask as a negative. */+ autoNegative: boolean;+ /** Mask-scoped reference images, or `null` when the denoiser has no regional image path. */+ referenceImages: RegionalReferenceImageKind | null;+}++/**+ * Mirrors the backend: `compel` / `sdxl_compel_prompt` + `denoise_latents` mask both+ * prompt polarities; FLUX / FLUX.2 / Krea-2 / Z-Image / Anima denoisers mask positive+ * conditioning only (Z-Image and Anima accept negative lists but discard their masks,+ * so a "regional" negative there would silently act globally and is rejected instead).+ */+const REGIONAL_GUIDANCE_SUPPORT: Record<RegionalGuidanceBase, RegionalGuidanceSupport> = {+ 'sd-1': { autoNegative: true, label: 'SD 1.x', negativePrompt: true, referenceImages: 'ip_adapter' },+ 'sd-2': { autoNegative: true, label: 'SD 2.x', negativePrompt: true, referenceImages: 'ip_adapter' },+ sdxl: { autoNegative: true, label: 'SDXL', negativePrompt: true, referenceImages: 'ip_adapter' },+ flux: { autoNegative: false, label: 'FLUX', negativePrompt: false, referenceImages: 'flux_redux' },+ flux2: { autoNegative: false, label: 'FLUX.2', negativePrompt: false, referenceImages: null },+ 'krea-2': { autoNegative: false, label: 'Krea-2', negativePrompt: false, referenceImages: null },+ 'z-image': { autoNegative: false, label: 'Z-Image', negativePrompt: false, referenceImages: null },+ anima: { autoNegative: false, label: 'Anima', negativePrompt: false, referenceImages: null },+};/** True when `base` supports regional guidance at all. */export const isRegionalGuidanceSupportedForBase = (base: string): base is RegionalGuidanceBase =>- base === 'sd-1' || base === 'sdxl' || base === 'flux' || base === 'flux2' || base === 'krea-2';+ Object.hasOwn(REGIONAL_GUIDANCE_SUPPORT, base);-/** Whether a base supports regional NEGATIVE prompts / autoNegative (SD family only). */-const supportsRegionalNegative = (base: RegionalGuidanceBase): boolean => base === 'sd-1' || base === 'sdxl';+/** The per-base support matrix, or `null` for a base with no regional path. */+export const getRegionalGuidanceSupport = (base: string | null): RegionalGuidanceSupport | null =>+ base !== null && isRegionalGuidanceSupportedForBase(base) ? REGIONAL_GUIDANCE_SUPPORT[base] : null;/** A resolved reference-image (component) model identifier — the backend model field shape. */export interface RegionalReferenceModel {@@ -91,7 +124,12 @@ const conditioningNodeType = (base: RegionalGuidanceBase, modelVariant?: stringreturn modelVariant === 'dev' ? 'flux2_dev_text_encoder' : 'flux2_klein_text_encoder';case 'krea-2':return 'krea2_text_encoder';+ case 'z-image':+ return 'z_image_text_encoder';+ case 'anima':+ return 'anima_text_encoder';case 'sd-1':+ case 'sd-2':return 'compel';}};@@ -115,7 +153,11 @@ const copyEncoderFields = (base: RegionalGuidanceBase, modelVariant?: string | nreturn modelVariant === 'dev' ? ['mistral_encoder', 'max_seq_len'] : ['qwen3_encoder', 'max_seq_len'];case 'krea-2':return ['qwen3_vl_encoder'];+ case 'z-image':+ case 'anima':+ return ['qwen3_encoder'];case 'sd-1':+ case 'sd-2':return ['clip'];}};@@ -188,10 +230,11 @@ const addRegionalConditioning = (* filter first. Wires, per enabled region:* - `alpha_mask_to_tensor` from the uploaded region mask;* - positive prompt → regional conditioning → `pos_cond_collect`;- * - negative prompt (SD only) → regional conditioning → `neg_cond_collect`;- * - autoNegative (SD only) → `invert_tensor_mask` + positive prompt re-encoded →+ * - negative prompt → regional conditioning → `neg_cond_collect`;+ * - autoNegative → `invert_tensor_mask` + positive prompt re-encoded →* `neg_cond_collect` (push the positive prompt away outside the region);- * - reference images → mask-scoped `ip_adapter` (SD) / `flux_redux` (FLUX).+ * - reference images → mask-scoped `ip_adapter` (SD) / `flux_redux` (FLUX);+ * each gated by the base's {@link RegionalGuidanceSupport}.*/export const addRegionalGuidance = (graph: BackendGraphContract, options: AddRegionalGuidanceOptions): void => {const { base, modelVariant, regions, transformRegionalPositiveConditioning } = options;@@ -204,7 +247,7 @@ export const addRegionalGuidance = (graph: BackendGraphContract, options: AddRegthrow new Error('addRegionalGuidance: base graph is missing the positive conditioning collector.');}const negCondCollect = graph.nodes[NEG_COND_COLLECT_ID] ?? null;- const withNegative = supportsRegionalNegative(base);+ const support = REGIONAL_GUIDANCE_SUPPORT[base];let ipAdapterCollector: BackendInvocationContract | null = null;let fluxReduxCollector: BackendInvocationContract | null = null;@@ -231,8 +274,8 @@ export const addRegionalGuidance = (graph: BackendGraphContract, options: AddRegaddEdge(graph, conditioningSource, 'conditioning', posCondCollect, 'item');}- // Negative prompt → negative collector (SD only; FLUX has no negative path).- if (region.negativePrompt && withNegative && negCondCollect) {+ // Negative prompt → negative collector.+ if (region.negativePrompt && support.negativePrompt && negCondCollect) {const negCond = addRegionalConditioning(graph,base,@@ -247,7 +290,7 @@ export const addRegionalGuidance = (graph: BackendGraphContract, options: AddReg// autoNegative: re-encode the POSITIVE prompt over the INVERTED mask into the// negative collector — pushes the region's prompt away everywhere outside it.- if (region.autoNegative && region.positivePrompt && withNegative && negCondCollect) {+ if (region.autoNegative && region.positivePrompt && support.autoNegative && negCondCollect) {const invert = addNode(graph, { id: `rg_invert_mask_${region.id}`, type: 'invert_tensor_mask' });addEdge(graph, maskToTensor, 'mask', invert, 'mask');const inverted = addRegionalConditioning(@@ -264,7 +307,7 @@ export const addRegionalGuidance = (graph: BackendGraphContract, options: AddReg// Reference images (mask-scoped): ip_adapter on SD, flux_redux on FLUX.for (const ref of region.referenceImages) {- if (ref.type === 'ip_adapter' && (base === 'sd-1' || base === 'sdxl')) {+ if (ref.type === 'ip_adapter' && support.referenceImages === 'ip_adapter') {if (!ipAdapterCollector) {ipAdapterCollector = resolveDenoiseCollector(graph, denoise, 'ip_adapter', 'regional_ip_adapter_collector');}@@ -281,7 +324,7 @@ export const addRegionalGuidance = (graph: BackendGraphContract, options: AddReg});addEdge(graph, maskToTensor, 'mask', node, 'mask');addEdge(graph, node, 'ip_adapter', ipAdapterCollector, 'item');- } else if (ref.type === 'flux_redux' && base === 'flux') {+ } else if (ref.type === 'flux_redux' && support.referenceImages === 'flux_redux') {if (!fluxReduxCollector) {fluxReduxCollector = resolveDenoiseCollector(graph,@@ -306,17 +349,19 @@ export const addRegionalGuidance = (graph: BackendGraphContract, options: AddReg};/**- * Returns the legacy-parity rejection reason for a regional-guidance region, or- * `null` when it can contribute to generation. Mirrors- * `getRegionalGuidanceWarnings`:- * - unsupported main base (sd-2 / sd-3 / cogview / …) → "unsupported model";+ * Returns the rejection reason for a regional-guidance region, or `null` when it+ * can contribute to generation:+ * - a base with no regional path (sd-3 / cogview / …) → "unsupported model";* - no drawn mask content → "no region";- * - no positive prompt, no negative prompt, and no reference images → "empty";- * - FLUX-family and Krea-2 negative prompts / autoNegative are unsupported;- * - FLUX.2 and Krea-2 regional reference images are unsupported.+ * - nothing the base's {@link RegionalGuidanceSupport} honours → "empty".+ *+ * A negative prompt or reference images the base does not honour are simply not+ * submitted (the layer keeps them for other models); the region still+ * contributes whatever the base does honour. Auto-negative never decides on its+ * own: it only re-encodes an existing positive prompt.*- * Per-reference-image model/image validity is resolved by the caller (which drops- * incomplete reference images before building), matching how control layers work.+ * `referenceImageCount` counts references the caller has already resolved to a+ * usable image + model, matching how control layers work.*/export const getRegionalGuidanceRejectionReason = (params: {layerName: string;@@ -324,29 +369,23 @@ export const getRegionalGuidanceRejectionReason = (params: {hasContent: boolean;positivePrompt: string | null;negativePrompt: string | null;- autoNegative: boolean;referenceImageCount: number;}): string | null => {- const { autoNegative, hasContent, layerName, mainBase, negativePrompt, positivePrompt, referenceImageCount } = params;+ const { hasContent, layerName, mainBase, negativePrompt, positivePrompt, referenceImageCount } = params;- if (!isRegionalGuidanceSupportedForBase(mainBase)) {+ const support = getRegionalGuidanceSupport(mainBase);+ if (!support) {return `Regional guidance "${layerName}" is not supported for the selected base model.`;}if (!hasContent) {return `Regional guidance "${layerName}" has no masked region.`;}- if (!positivePrompt && !negativePrompt && referenceImageCount === 0) {- return `Regional guidance "${layerName}" has no prompt or reference image.`;- }- const positiveOnlyLabel = mainBase === 'flux' ? 'FLUX' : mainBase === 'flux2' ? 'FLUX.2' : 'Krea-2';- if ((mainBase === 'flux' || mainBase === 'flux2' || mainBase === 'krea-2') && negativePrompt) {- return `Regional guidance "${layerName}" negative prompts are not supported for ${positiveOnlyLabel}.`;- }- if ((mainBase === 'flux' || mainBase === 'flux2' || mainBase === 'krea-2') && autoNegative) {- return `Regional guidance "${layerName}" auto-negative is not supported for ${positiveOnlyLabel}.`;- }- if ((mainBase === 'flux2' || mainBase === 'krea-2') && referenceImageCount > 0) {- return `Regional guidance "${layerName}" reference images are not supported for ${positiveOnlyLabel}.`;+ const contributes =+ Boolean(positivePrompt) ||+ (Boolean(negativePrompt) && support.negativePrompt) ||+ (referenceImageCount > 0 && support.referenceImages !== null);+ if (!contributes) {+ return `Regional guidance "${layerName}" has no prompt or reference image ${support.label} can use.`;}return null;};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.tsindex 271b5c9bb0..e7317a5eb7 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@@ -904,11 +904,42 @@ describe('compileCanvasGraph — regional guidance', () => {expect(backendGraph.nodes.rg_pos_cond_inverted_r1).toBeDefined();});- it('is a no-op for an unsupported base (sd-2)', () => {- const { backendGraph } = compile(sd2Model, 'txt2img', { regionalGuidance: [region('r1')] });+ it('grafts SD2 regional conditioning through compel like SD1', () => {+ const { backendGraph } = compile(sd2Model, 'txt2img', {+ regionalGuidance: [region('r1', { negativePrompt: 'blurry' })],+ });+ expect(backendGraph.nodes.rg_pos_cond_r1).toMatchObject({ prompt: 'a cat', type: 'compel' });+ expect(backendGraph.nodes.rg_neg_cond_r1).toMatchObject({ prompt: 'blurry', type: 'compel' });+ expect(getEdge(backendGraph, 'rg_pos_cond_r1', 'clip')?.source.node_id).toBe(+ getEdge(backendGraph, 'pos_cond', 'clip')?.source.node_id+ );+ });++ it('is a no-op for a base with no regional path (sd-3)', () => {+ const { backendGraph } = compile(sd3Model, 'txt2img', { regionalGuidance: [region('r1')] });expect(backendGraph.nodes.rg_mask_to_tensor_r1).toBeUndefined();});+ it.each([+ ['Z-Image', zImageModel, 'z_image_text_encoder'],+ ['Anima', animaModel, 'anima_text_encoder'],+ ] as const)('grafts %s regions through the shared Qwen3 encoder', (_label, model, encoderType) => {+ const { backendGraph } = compile(model, 'txt2img', {+ regionalGuidance: [region('r1'), region('r2', { positivePrompt: 'a dog' })],+ settings: { cfgScale: 4 },+ });++ expect(backendGraph.nodes.rg_pos_cond_r1).toMatchObject({ prompt: 'a cat', type: encoderType });+ expect(backendGraph.nodes.rg_pos_cond_r2).toMatchObject({ prompt: 'a dog', type: encoderType });+ expect(getEdge(backendGraph, 'rg_pos_cond_r1', 'qwen3_encoder')?.source.node_id).toBe('model_loader');+ expect(getEdge(backendGraph, 'rg_pos_cond_r1', 'mask')?.source.node_id).toBe('rg_mask_to_tensor_r1');+ const collected = backendGraph.edges+ .filter((edge) => edge.destination.node_id === 'pos_cond_collect')+ .map((edge) => edge.source.node_id);+ expect(collected).toEqual(['pos_cond', 'rg_pos_cond_r1', 'rg_pos_cond_r2']);+ expect(getEdge(backendGraph, 'neg_cond_collect', 'item')?.source.node_id).toBe('neg_cond');+ });+it('coexists with control layers in one graph', () => {const control: ControlLayerGraphInput = {beginEndStepPct: [0, 0.75],diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.tsindex e9b0b11652..edd61731ad 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts@@ -744,7 +744,7 @@ export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanv// Regional guidance applies in every mode too. The executor already composited// + uploaded each region's mask and resolved its reference-image models; it- // passes only valid regions for a supported base (SD1 / SDXL / FLUX / FLUX.2 / Krea-2).+ // passes only regions valid for the base's regional-guidance support matrix.if (input.regionalGuidance && input.regionalGuidance.length > 0 && isRegionalGuidanceSupportedForBase(model.base)) {addRegionalGuidance(backendGraph, {base: model.base,diff --git a/invokeai/frontend/webv2/src/features/generation/graph.ts b/invokeai/frontend/webv2/src/features/generation/graph.tsindex f670562346..8b56d8d0dc 100644--- a/invokeai/frontend/webv2/src/features/generation/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/graph.ts@@ -28,7 +28,7 @@ export {export { getControlLayerRejectionReason, getControlValidationReasonMessage } from './core/canvas/addControlLayers';export {getRegionalGuidanceRejectionReason,- isRegionalGuidanceSupportedForBase,+ getRegionalGuidanceSupport,type RegionalGuidanceInput,type RegionalReferenceImageInput,} from './core/canvas/addRegionalGuidance';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.tsindex fcecdf678d..09409c224b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts@@ -1010,6 +1010,125 @@ describe('runCanvasInvocation', () => {});});+// ---- Regional guidance through the real composite pipeline ---------------++const animaModel: MainModelConfig = { base: 'anima', key: 'anima-model', name: 'Anima', type: 'main' };+const animaGenerateValues = (): Record<string, unknown> => ({+ ...generateValuesFor(animaModel),+ cfgScale: 4,+ qwen3EncoderModel: { base: 'any', key: 'qwen3', name: 'Qwen3 Encoder', type: 'qwen3_encoder', variant: 'qwen3_06b' },+ vae: { base: 'anima', key: 'anima-vae', name: 'Anima VAE', type: 'vae' },+});++const regionalLayer = (+ id: string,+ overrides: Partial<+ Pick<+ CanvasLayerContract & { type: 'regional_guidance' },+ 'positivePrompt' | 'negativePrompt' | 'autoNegative' | 'referenceImages'+ >+ > = {}+): CanvasLayerContract => ({+ autoNegative: false,+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: { height: 64, imageName: `${id}-bmp`, width: 64 }, fill: { color: '#00ff00', style: 'solid' } },+ name: id,+ negativePrompt: null,+ opacity: 0.5,+ positivePrompt: 'a red hat',+ referenceImages: [],+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'regional_guidance',+ ...overrides,+});++describe('runCanvasInvocation — regional guidance on a Qwen3 base', () => {+ const makeAnimaHarness = (layer: CanvasLayerContract) => {+ const harness = makeHarness({ document: docWithLayers([layer]), model: animaModel });+ harness.deps.generateValues = animaGenerateValues();+ return harness;+ };++ it('composites an Anima region and grafts its masked prompt into the positive collector', async () => {+ const harness = makeAnimaHarness(regionalLayer('rg'));++ await runCanvasInvocation(harness.deps);++ expect(harness.notices()).toHaveLength(0);+ // The only upload is the region's own mask composite (no raster content → no base composite).+ expect(harness.uploadImage).toHaveBeenCalledTimes(1);+ const graph = harness.submittedGraphs()[0]?.graph.backendGraph;+ expect(graph?.nodes.rg_pos_cond_rg).toMatchObject({ prompt: 'a red hat', type: 'anima_text_encoder' });+ expect(graph?.nodes.rg_mask_to_tensor_rg).toMatchObject({+ image: { image_name: 'composite-1.png' },+ type: 'alpha_mask_to_tensor',+ });+ expect(+ graph?.edges.some(+ (edge) => edge.source.node_id === 'rg_pos_cond_rg' && edge.destination.node_id === 'pos_cond_collect'+ )+ ).toBe(true);+ });++ it.each([+ ['a negative prompt', { negativePrompt: 'blurry' }],+ ['auto-negative', { autoNegative: true }],+ [+ 'a complete IP-Adapter reference',+ {+ referenceImages: [+ {+ config: {+ beginEndStepPct: [0, 1],+ clipVisionModel: 'ViT-H',+ image: { imageName: 'ref.png' },+ method: 'full',+ model: { base: 'anima', key: 'ipa', name: 'IP Adapter', type: 'ip_adapter' },+ type: 'ip_adapter',+ weight: 1,+ },+ id: 'ref',+ isEnabled: true,+ },+ ],+ },+ ],+ ] as const)(+ 'still submits the positive prompt of an Anima region carrying %s, without the extra',+ async (_label, overrides) => {+ const harness = makeAnimaHarness(regionalLayer('rg', overrides as Parameters<typeof regionalLayer>[1]));++ await runCanvasInvocation(harness.deps);++ expect(harness.notices()).toHaveLength(0);+ const graph = harness.submittedGraphs()[0]?.graph.backendGraph;+ expect(graph?.nodes.rg_pos_cond_rg).toMatchObject({ prompt: 'a red hat', type: 'anima_text_encoder' });+ expect(graph?.nodes.rg_neg_cond_rg).toBeUndefined();+ expect(graph?.nodes.rg_pos_cond_inverted_rg).toBeUndefined();+ expect(graph?.nodes.ip_adapter_ref).toBeUndefined();+ const negativeSources = graph?.edges+ .filter((edge) => edge.destination.node_id === 'neg_cond_collect')+ .map((edge) => edge.source.node_id);+ expect(negativeSources).toEqual(['neg_cond']);+ }+ );++ it('skips an Anima region that carries only a negative prompt', async () => {+ const harness = makeAnimaHarness(regionalLayer('rg', { negativePrompt: 'blurry', positivePrompt: null }));++ await runCanvasInvocation(harness.deps);++ expect(harness.notices()).toHaveLength(0);+ expect(harness.uploadImage).not.toHaveBeenCalled();+ const graph = harness.submittedGraphs()[0]?.graph.backendGraph;+ expect(graph?.nodes.denoise_latents?.type).toBe('anima_denoise');+ expect(graph?.nodes.rg_mask_to_tensor_rg).toBeUndefined();+ });+});+// ---- Inpaint / outpaint mode dispatch -------------------------------------const inpaintMaskLayer = (id: string): CanvasLayerContract => ({@@ -1131,8 +1250,18 @@ describe('resolveRegionalReferenceImages', () => {expect(resolveRegionalReferenceImages({ referenceImages: [ipAdapterRef(asset)] }, 'flux2')).toEqual([]);});- it('drops regional reference images for Krea-2', () => {- expect(resolveRegionalReferenceImages({ referenceImages: [ipAdapterRef(asset)] }, 'krea-2')).toEqual([]);+ it.each(['krea-2', 'z-image', 'anima'])('drops regional reference images for %s', (base) => {+ const ref = ipAdapterRef(asset);+ const matchingBase = { ...ref, config: { ...ref.config, model: { ...ipAdapterModel, base } } };+ expect(resolveRegionalReferenceImages({ referenceImages: [matchingBase] }, base)).toEqual([]);+ });++ it('keeps an SD2 IP-Adapter ref whose model matches the base', () => {+ const sd2Ref = {+ ...ipAdapterRef(asset),+ config: { ...ipAdapterRef(asset).config, model: { ...ipAdapterModel, base: 'sd-2' } },+ };+ expect(resolveRegionalReferenceImages({ referenceImages: [sd2Ref] }, 'sd-2')).toHaveLength(1);});it('drops a FLUX Redux ref with no image assigned', () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.tsindex 2dbbfbcbc3..f832c08f66 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts@@ -49,7 +49,7 @@ import {getControlValidationReason,getControlValidationReasonMessage,getRegionalGuidanceRejectionReason,- isRegionalGuidanceSupportedForBase,+ getRegionalGuidanceSupport,type ControlLayerGraphInput,type ControlValidationReason,type RegionalGuidanceInput,@@ -216,12 +216,13 @@ export const resolveRegionalReferenceImages = (base: string): RegionalReferenceImageInput[] => {const inputs: RegionalReferenceImageInput[] = [];+ const kind = getRegionalGuidanceSupport(base)?.referenceImages ?? null;for (const ref of region.referenceImages) {if (!ref.isEnabled) {continue;}const { config } = ref;- if (config.type === 'ip_adapter' && (base === 'sd-1' || base === 'sdxl')) {+ if (config.type === 'ip_adapter' && kind === 'ip_adapter') {if (!config.image || !config.model || config.model.base !== base) {continue;}@@ -241,7 +242,7 @@ export const resolveRegionalReferenceImages = (type: 'ip_adapter',weight: config.weight,});- } else if (config.type === 'flux_redux' && base === 'flux') {+ } else if (config.type === 'flux_redux' && kind === 'flux_redux') {if (!config.image || !config.model || config.model.base !== base) {continue;}@@ -266,8 +267,8 @@ export const resolveRegionalReferenceImages = (/*** Regional-guidance policy + metadata side-channel for the composite operation.* `shouldComposite` resolves each region's reference images and rejects regions- * invalid for the base (unsupported base, FLUX + negative/autoNegative, all- * prompts + references empty) with a SILENT skip, mirroring legacy.+ * that cannot contribute for the base (no regional support, or nothing the+ * base's support matrix honours) with a SILENT skip, mirroring legacy.* `toGraphInputs` joins the composited mask image names back with the recorded* prompt/reference metadata.*/@@ -281,18 +282,14 @@ const createRegionalGuidanceCollector = (return {shouldComposite: (layer) => {- if (!isRegionalGuidanceSupportedForBase(model.base)) {- return false;- }const referenceImages = resolveRegionalReferenceImages(layer, model.base);const rejection = getRegionalGuidanceRejectionReason({- autoNegative: layer.autoNegative,hasContent: true,layerName: layer.name,mainBase: model.base,negativePrompt: layer.negativePrompt,positivePrompt: layer.positivePrompt,- referenceImageCount: layer.referenceImages.length,+ referenceImageCount: referenceImages.length,});if (rejection) {return false;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.tsxnew file mode 100644index 0000000000..59d162dc9d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx@@ -0,0 +1,101 @@+import type { CanvasRegionalGuidanceLayerContract } from '@workbench/canvas-engine/api';+import type { ComponentProps } from 'react';++import { ChakraProvider } from '@chakra-ui/react';+import { applyThemeToRoot } from '@theme/applyTheme';+import { system } from '@theme/system';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { RegionalGuidanceSettings } from './RegionalGuidanceSettings';++let selectedBase: string | null = null;+vi.mock('./useSelectedModelBase', () => ({ useSelectedModelBase: () => selectedBase }));++type Layer = ComponentProps<typeof RegionalGuidanceSettings>['layer'];++const i18n = createInstance();+void i18n.use(initReactI18next).init({ fallbackLng: 'en', initAsync: false, lng: 'en', resources: {} });++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLDivElement | null = null;+let root: Root | null = null;++const createLayer = (overrides: Partial<CanvasRegionalGuidanceLayerContract> = {}): Layer =>+ ({+ autoNegative: false,+ id: 'rg-1',+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: null, fill: { color: '#ff0000', style: 'solid' } },+ name: 'Region 1',+ negativePrompt: null,+ opacity: 1,+ positivePrompt: 'a cat',+ referenceImages: [],+ type: 'regional_guidance',+ ...overrides,+ }) as unknown as Layer;++const render = async (base: string | null, layer: Layer) => {+ selectedBase = base;+ applyThemeToRoot('classic');+ host = document.createElement('div');+ host.style.width = '260px';+ document.body.append(host);+ root = createRoot(host);+ await act(() => {+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <RegionalGuidanceSettings engine={null} layer={layer} />+ </ChakraProvider>+ </I18nextProvider>+ );+ });+};++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++const alerts = () => [...host!.querySelectorAll('[role="alert"]')].map((el) => el.textContent);+const hasNegativeField = () =>+ host!.querySelector('[aria-label="widgets.layers.regionalGuidance.negativePrompt"]') !== null;+const hasAutoNegativeSwitch = () =>+ Boolean(host!.textContent?.includes('widgets.layers.regionalGuidance.autoNegative'));++describe('RegionalGuidanceSettings per model base', () => {+ it('offers both prompt polarities on an SD base', async () => {+ await render('sd-1', createLayer());+ expect(alerts()).toEqual([]);+ expect(hasNegativeField()).toBe(true);+ expect(hasAutoNegativeSwitch()).toBe(true);+ });++ it('hides the negative controls on a positive-only base even when the layer still holds a negative', async () => {+ await render('anima', createLayer({ autoNegative: true, negativePrompt: 'blurry' }));+ expect(alerts()).toEqual([]);+ expect(hasNegativeField()).toBe(false);+ expect(hasAutoNegativeSwitch()).toBe(false);+ });++ it('warns that a base with no regional path skips the layer', async () => {+ await render('sd-3', createLayer());+ expect(alerts()).toEqual(['widgets.layers.regionalGuidance.unsupportedModel']);+ expect(hasNegativeField()).toBe(true);+ });++ it('offers everything while no model is selected', async () => {+ await render(null, createLayer());+ expect(alerts()).toEqual([]);+ expect(hasNegativeField()).toBe(true);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsxindex e9e2a01346..7279f50cd6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx@@ -9,6 +9,7 @@ import type { ChangeEvent, FocusEvent } from 'react';import { createListCollection, HStack, IconButton, Stack, Switch, Text } from '@chakra-ui/react';import { PROMPT_ATTENTION_TARGET_PROPS, PromptTextarea } from '@features/generation/components';+import { getRegionalGuidanceSupport } from '@features/generation/graph';import { Button, ColorPicker, Field, Select, Tooltip } from '@platform/ui';import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';import { armMaskTintTarget } from '@workbench/widgets/canvas/color-system/maskTintTarget';@@ -70,10 +71,11 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettconst [negativePrompt, setNegativePrompt] = useState(layer.negativePrompt ?? '');const fill = layer.mask.fill;- const isFlux = base === 'flux';- const isFlux2 = base === 'flux2';- const isFluxFamily = isFlux || isFlux2;- const showNegativeControls = !isFluxFamily || Boolean(layer.negativePrompt) || layer.autoNegative;+ // Negative controls are hidden on bases whose backend ignores regional negatives; the values+ // stay on the layer for other models. With no selected model every control is offered.+ const support = getRegionalGuidanceSupport(base);+ const showNegativeControls = support?.negativePrompt !== false;+ const unsupportedModel = base !== null && support === null;const commitConfig = useCallback((label: string, next: RegionalConfigPatch, before: RegionalConfigPatch) => {@@ -208,11 +210,11 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettreturn (<Stack gap="2">- {isFlux2 && (- <Text color="fg.warning" fontSize="xs" role="alert">- {t('widgets.layers.regionalGuidance.flux2PositiveOnly')}+ {unsupportedModel ? (+ <Text color="fg.warning" fontSize="2xs" role="alert">+ {t('widgets.layers.regionalGuidance.unsupportedModel')}</Text>- )}+ ) : null}<Field label={t('widgets.layers.regionalGuidance.positivePrompt')}><PromptTextarea{...PROMPT_ATTENTION_TARGET_PROPS}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.test.tsindex 05d3739417..fe4bcf59ac 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.test.ts@@ -32,10 +32,14 @@ describe('ADD_LAYER_MENU', () => {});describe('isAddLayerItemAvailable', () => {- it('hides only regional reference-image creation for FLUX.2', () => {- expect(isAddLayerItemAvailable('regional_reference_image', 'flux2')).toBe(false);- expect(isAddLayerItemAvailable('regional_guidance', 'flux2')).toBe(true);- expect(isAddLayerItemAvailable('regional_reference_image', 'flux')).toBe(true);+ it('hides only regional reference-image creation on bases without a regional image path', () => {+ for (const base of ['flux2', 'krea-2', 'z-image', 'anima', 'sd-3']) {+ expect(isAddLayerItemAvailable('regional_reference_image', base), base).toBe(false);+ expect(isAddLayerItemAvailable('regional_guidance', base), base).toBe(true);+ }+ for (const base of ['sd-1', 'sd-2', 'sdxl', 'flux', null]) {+ expect(isAddLayerItemAvailable('regional_reference_image', base), String(base)).toBe(true);+ }});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.tsindex 5d6811b01b..0bfb4aa47a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.ts@@ -1,11 +1,13 @@/**- * Pure data for the layers-panel add-layer surfaces (kept free of React so the- * grouping is unit-testable). The header menu renders {@link ADD_LAYER_MENU}; each+ * React-free data and base gating for the layers-panel add-layer surfaces, so+ * the grouping is unit-testable. The header menu renders {@link ADD_LAYER_MENU}; each* stack header's "New" button uses {@link stackAddItemId} to add its own type.*/import type { LayerStackKind } from '@workbench/canvas-engine/api';+import { canAddRegionalReferenceImage } from './layerOps';+/** The distinct "add a layer" actions offered across the panel's add surfaces. */export type AddLayerItemId =| 'inpaint_mask'@@ -53,7 +55,7 @@ export const ADD_LAYER_MENU: readonly AddLayerMenuGroup[] = [/** Whether an add action is supported by the selected model base. */export const isAddLayerItemAvailable = (id: AddLayerItemId, base: string | null): boolean =>- id !== 'regional_reference_image' || base !== 'flux2';+ id !== 'regional_reference_image' || canAddRegionalReferenceImage(base);/** The add-layer action a stack-header "New" button triggers for its type. */export const stackAddItemId = (stack: LayerStackKind): AddLayerItemId => stack;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex 253d01bce9..a7367a6668 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -530,11 +530,19 @@ describe('getLayerContextActions', () => {expect(effects.setColorLabel).toHaveBeenLastCalledWith(null);});- it('offers add-reference-image on regional layers unless the model base is flux2', () => {+ it('offers add-reference-image on regional layers unless the model base has no regional image path', () => {const regional = makeLayer('regional_guidance');expect(byId(getLayerContextActions(makeState(regional)), 'add-reference-image').isDisabled).toBe(false);- const flux2Actions = getLayerContextActions(makeState(regional, { modelBase: 'flux2' }));- expect(flux2Actions.some((action) => action.id === 'add-reference-image')).toBe(false);+ expect(+ byId(getLayerContextActions(makeState(regional, { modelBase: 'flux' })), 'add-reference-image')+ ).toBeDefined();+ for (const modelBase of ['flux2', 'anima', 'z-image']) {+ const actions = getLayerContextActions(makeState(regional, { modelBase }));+ expect(+ actions.some((action) => action.id === 'add-reference-image'),+ modelBase+ ).toBe(false);+ }const rasterActions = getLayerContextActions(makeState(makeLayer('raster')));expect(rasterActions.some((action) => action.id === 'add-reference-image')).toBe(false);});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex 6ca28a0a9f..b0eb26e3c2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -52,7 +52,7 @@ import {} from 'lucide-react';import { COLOR_LABEL_ITEMS } from './colorLabels';-import { canConvertRasterControl, canMergeLayerDown } from './layerOps';+import { canAddRegionalReferenceImage, canConvertRasterControl, canMergeLayerDown } from './layerOps';export type LayerContextActionId =| 'add-reference-image'@@ -546,7 +546,7 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefiniicon: ImagePlusIcon,id: 'add-reference-image',isEnabled: isLayerMutable,- isVisible: (context) => context.modelBase !== 'flux2',+ isVisible: (context) => canAddRegionalReferenceImage(context.modelBase),labelKey: 'widgets.layers.regionalGuidance.addReferenceImage',order: 55,section: 'primary',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.tsindex 9882796356..9343aa35de 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts@@ -25,6 +25,7 @@ import type {export type { CanvasStructuralEngine } from '@workbench/canvas-engine/api';+import { getRegionalGuidanceSupport } from '@features/generation/graph';import { getSourceContentRect, isMergeableRasterLayer, mergeDownEligibility } from '@workbench/canvas-engine/api';import { CONTROL_ADAPTER_DEFAULTS } from '@workbench/controlAdapters';@@ -287,7 +288,7 @@ export const createRegionalReferenceImage = (base: string | null,id: string = createReferenceImageId()): RegionalGuidanceReferenceImage => {- if (base === 'flux') {+ if (getRegionalGuidanceSupport(base)?.referenceImages === 'flux_redux') {return {config: { image: null, imageInfluence: 'highest', model: null, type: 'flux_redux' },id,@@ -309,6 +310,10 @@ export const createRegionalReferenceImage = (};};+/** Whether a regional reference image can be added; with no model selected every option stays open. */+export const canAddRegionalReferenceImage = (base: string | null): boolean =>+ base === null || Boolean(getRegionalGuidanceSupport(base)?.referenceImages);+/*** Builds a regional-guidance layer pre-seeded with ONE empty reference image* (legacy's "regional guidance with a reference image" add-layer path). Identical