Skip to content

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

feat(canvas): add legacy control preprocessors

joshistoasta8000a69d52a
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index abeb328e8e..13054b7502 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1196,6 +1196,10 @@
"endStep": "End step",
"filter": "Filter",
"filterParams": {
+ "amount": "Amount",
+ "autoScale": "Autoscale",
+ "blur_type": "Blur type",
+ "channel": "Channel",
"coarse": "Coarse",
"distance_threshold": "Distance threshold",
"draw_body": "Draw body",
@@ -1205,24 +1209,38 @@
"low_threshold": "Low threshold",
"max_faces": "Max faces",
"min_confidence": "Min confidence",
+ "model": "Image-to-image model",
"model_size": "Model size",
"quantize_edges": "Quantize edges",
"scale_factor": "Scale factor",
+ "scale": "Scale",
+ "scale_values": "Multiply values",
"score_threshold": "Score threshold",
"scribble": "Scribble",
- "tile_size": "Tile size"
+ "tile_size": "Tile size",
+ "noise_color": "Color noise",
+ "noise_type": "Noise type",
+ "radius": "Radius",
+ "size": "Size",
+ "value": "Value"
},
"filters": {
+ "adjust_image": "Adjust image",
"canny_edge_detection": "Canny",
"color_map": "Color map",
"content_shuffle": "Content shuffle",
"depth_anything_depth_estimation": "Depth Anything",
"dw_openpose_detection": "DW Openpose",
"hed_edge_detection": "HED",
+ "img_blur": "Blur",
+ "img_noise": "Noise",
+ "lineart_anime_edge_detection": "Lineart Anime",
"lineart_edge_detection": "Lineart",
"mediapipe_face_detection": "Mediapipe Face",
"mlsd_detection": "MLSD",
- "pidi_edge_detection": "PiDiNet"
+ "normal_map": "Normal map",
+ "pidi_edge_detection": "PiDiNet",
+ "spandrel_filter": "Spandrel"
},
"kind": "Adapter type",
"kinds": {
@@ -1242,6 +1260,14 @@
"selectModel": "Select a model",
"stepRange": "Step range",
"transparencyEffect": "Transparency effect",
+ "validation": {
+ "control_lora_limit": "Only one Control LoRA can be used at a time.",
+ "flux_fill_control_lora": "Control LoRA is not compatible with FLUX Fill.",
+ "incompatible_adapter": "The selected model does not match this adapter type.",
+ "incompatible_base": "The control model is incompatible with the selected base model.",
+ "missing_model": "Select a control model before generating.",
+ "unsupported_adapter": "This control adapter is not supported by the selected base model."
+ },
"weight": "Weight"
},
"rasterFilter": {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index d245fefc94..52b605ce7b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -9195,6 +9195,34 @@ describe('guarded filter previews', () => {
engine.dispose();
});
+ it('starts an unfiltered layer with a recommendation but preserves an existing manual filter and Cancel', async () => {
+ const unfiltered = guardableLayer('recommended');
+ const manual = {
+ ...guardableLayer('manual'),
+ filter: { settings: { coarse: true }, type: 'lineart_edge_detection' },
+ };
+ const document = { ...emptyDoc(), layers: [unfiltered, manual] };
+ const { store } = createReactiveStore(document);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ });
+ expect((await engine.exportLayerPixels('recommended')).status).toBe('ok');
+ expect(engine.startFilterOperation('recommended', 'normal_map')).toBe('started');
+ expect(engine.stores.filterSession.get()?.draft).toEqual({ settings: {}, type: 'normal_map' });
+ engine.cancelFilterOperation();
+ expect(engine.getDocument()).toEqual(document);
+
+ expect((await engine.exportLayerPixels('manual')).status).toBe('ok');
+ expect(engine.startFilterOperation('manual', 'normal_map')).toBe('started');
+ expect(engine.stores.filterSession.get()?.draft).toEqual(manual.filter);
+ engine.cancelFilterOperation();
+ expect(engine.getDocument()).toEqual(document);
+ engine.dispose();
+ });
+
const filterFlowLayer = (
type: 'raster' | 'control'
): Extract<CanvasLayerContract, { type: 'raster' | 'control' }> => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 5e12dfbfe1..1c78ea8285 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -410,7 +410,7 @@ export interface CanvasEngine {
/** Selects the requested raster/control layer, starts Select Object, and activates the SAM tool. */
startSelectObject(layerId: string): StartSelectObjectSessionResult;
/** Starts one engine-owned guarded filter operation for a raster or control layer. */
- startFilterOperation(layerId: string): StartFilterOperationResult;
+ startFilterOperation(layerId: string, recommendedFilterType?: string | null): StartFilterOperationResult;
updateFilterOperation(draft: LayerFilterSettings): void;
processFilterOperation(): Promise<void>;
resetFilterOperation(settings: Record<string, unknown>): void;
@@ -3245,7 +3245,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
stores.filterSession.set(null);
};
- const startFilterOperation = (layerId: string): StartFilterOperationResult => {
+ const startFilterOperation = (layerId: string, recommendedFilterType?: string | null): StartFilterOperationResult => {
const document = mirror.getDocument();
const layer = document?.layers.find((candidate) => candidate.id === layerId);
if (!document || !layer) {
@@ -3264,11 +3264,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
if (!guard) {
return 'not-ready';
}
- const definition = getFilterDefinition(layer.filter?.type ?? DEFAULT_CONTROL_FILTER_TYPE);
+ const initialType = layer.filter?.type ?? recommendedFilterType ?? DEFAULT_CONTROL_FILTER_TYPE;
+ const definition = getFilterDefinition(initialType);
const initialFilter = layer.filter ? structuredClone(layer.filter) : null;
const draft = initialFilter ?? {
settings: definition ? buildFilterDefaults(definition) : {},
- type: DEFAULT_CONTROL_FILTER_TYPE,
+ type: definition?.type ?? DEFAULT_CONTROL_FILTER_TYPE,
};
clearOwnedSelectObjectSession();
diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/addControlLayers.test.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/addControlLayers.test.ts
index 069b47b7c5..e2d4baa346 100644
--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/addControlLayers.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/addControlLayers.test.ts
@@ -36,11 +36,11 @@ const baseGraph = (): TestGraph => ({
edges: [],
});
-const model = (base: string): ControlModelIdentifier => ({
+const model = (base: string, type = 'controlnet'): ControlModelIdentifier => ({
key: `model-${base}`,
name: `Model ${base}`,
base,
- type: 'controlnet',
+ type,
});
const layer = (overrides: Partial<ControlLayerGraphInput> = {}): ControlLayerGraphInput => ({
@@ -211,7 +211,7 @@ describe('addControlLayers — controlnet on flux', () => {
describe('addControlLayers — t2i_adapter on sdxl', () => {
it('creates a t2i_adapter node with exact fields and wires collector to denoise.t2i_adapter', () => {
- const m = model('sdxl');
+ const m = model('sdxl', 't2i_adapter');
const graph = run({
base: 'sdxl',
layers: [
@@ -272,7 +272,7 @@ describe('addControlLayers — t2i_adapter on sdxl', () => {
describe('addControlLayers — control_lora on flux', () => {
it('creates a flux_control_lora_loader wired directly to denoise.control_lora with no collector', () => {
- const m = model('flux');
+ const m = model('flux', 'control_lora');
const graph = run({
base: 'flux',
layers: [layer({ id: 'CL1', kind: 'control_lora', imageName: 'lora.png', model: m, weight: 0.9 })],
@@ -308,32 +308,26 @@ describe('addControlLayers — control_lora on flux', () => {
// ---------------------------------------------------------------------------
describe('addControlLayers — control_lora limits', () => {
- it('adds at most one control_lora; the second layer is skipped', () => {
- const graph = run({
- base: 'flux',
- layers: [
- layer({ id: 'CL1', kind: 'control_lora', model: model('flux') }),
- layer({ id: 'CL2', kind: 'control_lora', model: model('flux') }),
- ],
- });
-
- const loraNodes = Object.values(graph.nodes).filter((n) => n.type === 'flux_control_lora_loader');
- expect(loraNodes).toHaveLength(1);
- expect(graph.nodes['control_lora_CL1']).toBeDefined();
- expect(graph.nodes['control_lora_CL2']).toBeUndefined();
+ it('rejects a second control_lora with the shared reason code', () => {
+ expect(() =>
+ run({
+ base: 'flux',
+ layers: [
+ layer({ id: 'CL1', kind: 'control_lora', model: model('flux', 'control_lora') }),
+ layer({ id: 'CL2', kind: 'control_lora', model: model('flux', 'control_lora') }),
+ ],
+ })
+ ).toThrow(/control_lora_limit/);
});
- it('skips control_lora entirely for a dev_fill main model variant', () => {
- const graph = run({
- base: 'flux',
- modelVariant: 'dev_fill',
- layers: [layer({ id: 'CL1', kind: 'control_lora', model: model('flux') })],
- });
-
- expect(Object.values(graph.nodes).some((n) => n.type === 'flux_control_lora_loader')).toBe(false);
- // Only the denoise node remains.
- expect(Object.keys(graph.nodes)).toEqual(['denoise_latents']);
- expect(graph.edges).toHaveLength(0);
+ it('rejects control_lora for a dev_fill main model variant', () => {
+ expect(() =>
+ run({
+ base: 'flux',
+ modelVariant: 'dev_fill',
+ layers: [layer({ id: 'CL1', kind: 'control_lora', model: model('flux', 'control_lora') })],
+ })
+ ).toThrow(/flux_fill_control_lora/);
});
});
@@ -373,28 +367,30 @@ describe('addControlLayers — per-layer separation', () => {
// 8. Unsupported kind for base is silently skipped
// ---------------------------------------------------------------------------
-describe('addControlLayers — unsupported kind skipped', () => {
- it('adds nothing for a t2i_adapter layer on flux', () => {
- const graph = run({
- base: 'flux',
- layers: [layer({ id: 'X', kind: 't2i_adapter', model: model('flux') })],
- });
-
- expect(Object.keys(graph.nodes)).toEqual(['denoise_latents']);
- expect(graph.edges).toHaveLength(0);
+describe('addControlLayers — unsupported kind rejected', () => {
+ it('rejects a t2i_adapter layer on flux', () => {
+ expect(() =>
+ run({
+ base: 'flux',
+ layers: [layer({ id: 'X', kind: 't2i_adapter', model: model('flux', 't2i_adapter') })],
+ })
+ ).toThrow(/unsupported_adapter/);
});
- it('skips only unsupported layers while keeping supported ones', () => {
- const graph = run({
- base: 'flux',
- layers: [
- layer({ id: 'skip', kind: 't2i_adapter', model: model('flux') }),
- layer({ id: 'keep', kind: 'controlnet', model: model('flux') }),
- ],
- });
+ it('rejects a mixed set containing an unsupported layer', () => {
+ expect(() =>
+ run({
+ base: 'flux',
+ layers: [
+ layer({ id: 'skip', kind: 't2i_adapter', model: model('flux', 't2i_adapter') }),
+ layer({ id: 'keep', kind: 'controlnet', model: model('flux') }),
+ ],
+ })
+ ).toThrow(/unsupported_adapter/);
+ });
- expect(graph.nodes['t2i_adapter_skip']).toBeUndefined();
- expect(graph.nodes['control_net_keep']).toBeDefined();
+ it('rejects a graph input whose resolved model has an incompatible base', () => {
+ expect(() => run({ base: 'sd-1', layers: [layer({ model: model('sdxl') })] })).toThrow(/incompatible_base/);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/addControlLayers.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/addControlLayers.ts
index 1859d03ca9..dd9eddcda2 100644
--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/addControlLayers.ts
+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/addControlLayers.ts
@@ -24,11 +24,15 @@ import type { BackendGraphContract, BackendInvocationContract } from '@workbench
import { addEdge, addNode } from '@workbench/generation/graphBuilder';
+import type { ControlAdapterKind } from './controlValidation';
+
+import { getControlValidationReason } from './controlValidation';
+
/** The deterministic denoise node id every canvas base graph uses. */
export const CONTROL_DENOISE_NODE_ID = 'denoise_latents';
/** The control-adapter kinds a control layer can carry. */
-export type ControlAdapterKind = 'controlnet' | 't2i_adapter' | 'control_lora';
+export type { ControlAdapterKind } from './controlValidation';
/** A resolved control-adapter model identifier (the backend model field shape). */
export interface ControlModelIdentifier {
@@ -57,16 +61,7 @@ export interface ControlLayerGraphInput {
* True when `base` supports control adapters of `kind` (legacy support matrix).
* `controlMode` and adapter-model base compatibility are validated separately.
*/
-export const isControlKindSupportedForBase = (base: string, kind: ControlAdapterKind): boolean => {
- switch (kind) {
- case 'controlnet':
- return base === 'sd-1' || base === 'sdxl' || base === 'flux';
- case 't2i_adapter':
- return base === 'sd-1' || base === 'sdxl';
- case 'control_lora':
- return base === 'flux';
- }
-};
+export { isControlKindSupportedForBase } from './controlValidation';
/** Options for {@link addControlLayers}. */
export interface AddControlLayersOptions {
@@ -82,9 +77,9 @@ export interface AddControlLayersOptions {
const controlNetNodeType = (base: string): string => (base === 'flux' ? 'flux_controlnet' : 'controlnet');
/**
- * Grafts control layers onto a built canvas base graph. Assumes every input is
- * already validated (supported base+kind, compatible non-null model, non-empty
- * content) — use {@link getControlLayerRejectionReason} to filter first. Wires:
+ * Grafts control layers onto a built canvas base graph. Revalidates support,
+ * model compatibility, the Control LoRA limit, and FLUX Fill restrictions so a
+ * caller cannot bypass the same shared validation used by invoke and UI. Wires:
* - controlnet → `control_net_collector` (collect) → `denoise.control`;
* - t2i_adapter → `t2i_adapter_collector` (collect) → `denoise.t2i_adapter`;
* - control_lora → `denoise.control_lora` directly (FLUX, first layer only).
@@ -98,7 +93,7 @@ export const addControlLayers = (graph: BackendGraphContract, options: AddContro
let controlNetCollector: BackendInvocationContract | null = null;
let t2iAdapterCollector: BackendInvocationContract | null = null;
- let controlLoraAdded = false;
+ let controlLoraCount = 0;
const ensureControlNetCollector = (): BackendInvocationContract => {
if (!controlNetCollector) {
@@ -117,8 +112,15 @@ export const addControlLayers = (graph: BackendGraphContract, options: AddContro
};
for (const layer of layers) {
- if (!isControlKindSupportedForBase(base, layer.kind)) {
- continue;
+ const reason = getControlValidationReason({
+ adapterModel: layer.model,
+ controlLoraIndex: layer.kind === 'control_lora' ? controlLoraCount : 0,
+ kind: layer.kind,
+ mainBase: base,
+ mainVariant: modelVariant,
+ });
+ if (reason) {
+ throw new Error(`Invalid control layer: ${reason}`);
}
if (layer.kind === 'controlnet') {
@@ -148,10 +150,6 @@ export const addControlLayers = (graph: BackendGraphContract, options: AddContro
});
addEdge(graph, node, 't2i_adapter', ensureT2iAdapterCollector(), 'item');
} else {
- // control_lora — FLUX only, at most one, never with a FLUX Fill main model.
- if (controlLoraAdded || modelVariant === 'dev_fill') {
- continue;
- }
const node = addNode(graph, {
id: `control_lora_${layer.id}`,
image: { image_name: layer.imageName },
@@ -160,7 +158,7 @@ export const addControlLayers = (graph: BackendGraphContract, options: AddContro
weight: layer.weight,
});
addEdge(graph, node, 'control_lora', denoise, 'control_lora');
- controlLoraAdded = true;
+ controlLoraCount += 1;
}
}
};
@@ -178,7 +176,7 @@ export const getControlLayerRejectionReason = (params: {
layerName: string;
hasContent: boolean;
kind: ControlAdapterKind;
- adapterModel: { base: string } | null;
+ adapterModel: { base: string; type?: string } | null;
mainBase: string;
mainVariant?: string;
}): string | null => {
@@ -187,17 +185,27 @@ export const getControlLayerRejectionReason = (params: {
if (!hasContent) {
return `Control layer "${layerName}" has no control content.`;
}
- if (!adapterModel) {
+ const reason = getControlValidationReason({
+ adapterModel: adapterModel ? { base: adapterModel.base, type: adapterModel.type ?? kind } : null,
+ controlLoraIndex: 0,
+ kind,
+ mainBase,
+ mainVariant,
+ });
+ if (!reason) {
+ return null;
+ }
+ if (reason === 'missing_model') {
return `Control layer "${layerName}" has no control model selected.`;
}
- if (!isControlKindSupportedForBase(mainBase, kind)) {
+ if (reason === 'unsupported_adapter') {
return `Control layer "${layerName}" is not supported for the selected base model.`;
}
- if (adapterModel.base !== mainBase) {
+ if (reason === 'incompatible_base') {
return `Control layer "${layerName}" uses an incompatible base model.`;
}
- if (mainBase === 'flux' && mainVariant === 'dev_fill' && kind === 'control_lora') {
- return `Control LoRA is not compatible with FLUX Fill.`;
+ if (reason === 'flux_fill_control_lora') {
+ return 'Control LoRA is not compatible with FLUX Fill.';
}
- return null;
+ return `Control layer "${layerName}" uses an incompatible control adapter.`;
};
diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/controlRecommendations.test.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/controlRecommendations.test.ts
new file mode 100644
index 0000000000..0d43066f14
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/controlRecommendations.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveDefaultFilterForModel } from './controlRecommendations';
+
+describe('resolveDefaultFilterForModel', () => {
+ it.each([
+ ['canny_edge_detection', 'canny_edge_detection'],
+ ['canny_image_processor', 'canny_edge_detection'],
+ ['normalbae_image_processor', 'normal_map'],
+ ['zoe_depth_image_processor', 'depth_anything_depth_estimation'],
+ ['lineart_anime_image_processor', 'lineart_anime_edge_detection'],
+ ])('resolves current ids and legacy alias %s', (preprocessor, expected) => {
+ expect(resolveDefaultFilterForModel({ default_settings: { preprocessor } })).toBe(expected);
+ });
+
+ it('returns null for missing or unknown metadata', () => {
+ expect(resolveDefaultFilterForModel(null)).toBeNull();
+ expect(resolveDefaultFilterForModel({ default_settings: null })).toBeNull();
+ expect(resolveDefaultFilterForModel({ default_settings: { preprocessor: 'future_processor' } })).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/controlRecommendations.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/controlRecommendations.ts
new file mode 100644
index 0000000000..51cad604cd
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/controlRecommendations.ts
@@ -0,0 +1,32 @@
+import type { ModelConfig } from '@workbench/models/types';
+
+import { isSupportedFilterType } from './filterGraphs';
+
+export const PROCESSOR_TO_FILTER_MAP: Readonly<Record<string, string>> = {
+ canny_image_processor: 'canny_edge_detection',
+ color_map_image_processor: 'color_map',
+ content_shuffle_image_processor: 'content_shuffle',
+ depth_anything_image_processor: 'depth_anything_depth_estimation',
+ dw_openpose_image_processor: 'dw_openpose_detection',
+ hed_image_processor: 'hed_edge_detection',
+ lineart_anime_image_processor: 'lineart_anime_edge_detection',
+ lineart_image_processor: 'lineart_edge_detection',
+ mediapipe_face_processor: 'mediapipe_face_detection',
+ mlsd_image_processor: 'mlsd_detection',
+ normalbae_image_processor: 'normal_map',
+ pidi_image_processor: 'pidi_edge_detection',
+ zoe_depth_image_processor: 'depth_anything_depth_estimation',
+};
+
+export const resolveDefaultFilterForModel = (
+ model: Pick<ModelConfig, 'default_settings'> | null | undefined
+): string | null => {
+ const preprocessor = model?.default_settings?.preprocessor;
+ if (!preprocessor) {
+ return null;
+ }
+ if (isSupportedFilterType(preprocessor)) {
+ return preprocessor;
+ }
+ return PROCESSOR_TO_FILTER_MAP[preprocessor] ?? null;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/controlValidation.test.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/controlValidation.test.ts
new file mode 100644
index 0000000000..e6f7063276
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/controlValidation.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+
+import { getControlValidationReason } from './controlValidation';
+
+const valid = {
+ adapterModel: { base: 'sd-1', type: 'controlnet' },
+ controlLoraIndex: 0,
+ kind: 'controlnet' as const,
+ mainBase: 'sd-1',
+ mainVariant: undefined,
+};
+
+describe('getControlValidationReason', () => {
+ it('returns stable reason codes for the validation matrix', () => {
+ expect(getControlValidationReason(valid)).toBeNull();
+ expect(getControlValidationReason({ ...valid, adapterModel: null })).toBe('missing_model');
+ expect(getControlValidationReason({ ...valid, mainBase: 'sd-2' })).toBe('unsupported_adapter');
+ expect(getControlValidationReason({ ...valid, adapterModel: { base: 'sdxl', type: 'controlnet' } })).toBe(
+ 'incompatible_base'
+ );
+ expect(getControlValidationReason({ ...valid, adapterModel: { base: 'sd-1', type: 't2i_adapter' } })).toBe(
+ 'incompatible_adapter'
+ );
+ expect(
+ getControlValidationReason({
+ adapterModel: { base: 'flux', type: 'control_lora' },
+ controlLoraIndex: 1,
+ kind: 'control_lora',
+ mainBase: 'flux',
+ })
+ ).toBe('control_lora_limit');
+ expect(
+ getControlValidationReason({
+ adapterModel: { base: 'flux', type: 'control_lora' },
+ controlLoraIndex: 0,
+ kind: 'control_lora',
+ mainBase: 'flux',
+ mainVariant: 'dev_fill',
+ })
+ ).toBe('flux_fill_control_lora');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/controlValidation.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/controlValidation.ts
new file mode 100644
index 0000000000..b890552e01
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/controlValidation.ts
@@ -0,0 +1,48 @@
+export type ControlAdapterKind = 'controlnet' | 't2i_adapter' | 'control_lora';
+
+export type ControlValidationReason =
+ | 'missing_model'
+ | 'unsupported_adapter'
+ | 'incompatible_base'
+ | 'incompatible_adapter'
+ | 'control_lora_limit'
+ | 'flux_fill_control_lora';
+
+export const isControlKindSupportedForBase = (base: string, kind: ControlAdapterKind): boolean => {
+ if (kind === 'controlnet') {
+ return base === 'sd-1' || base === 'sdxl' || base === 'flux';
+ }
+ if (kind === 't2i_adapter') {
+ return base === 'sd-1' || base === 'sdxl';
+ }
+ return base === 'flux';
+};
+
+export const getControlValidationReason = (params: {
+ adapterModel: { base: string; type: string } | null;
+ controlLoraIndex: number;
+ kind: ControlAdapterKind;
+ mainBase: string;
+ mainVariant?: string;
+}): ControlValidationReason | null => {
+ const { adapterModel, controlLoraIndex, kind, mainBase, mainVariant } = params;
+ if (!adapterModel) {
+ return 'missing_model';
+ }
+ if (!isControlKindSupportedForBase(mainBase, kind)) {
+ return 'unsupported_adapter';
+ }
+ if (adapterModel.base !== mainBase) {
+ return 'incompatible_base';
+ }
+ if (adapterModel.type !== kind) {
+ return 'incompatible_adapter';
+ }
+ if (kind === 'control_lora' && controlLoraIndex > 0) {
+ return 'control_lora_limit';
+ }
+ if (kind === 'control_lora' && mainBase === 'flux' && mainVariant === 'dev_fill') {
+ return 'flux_fill_control_lora';
+ }
+ return null;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.test.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.test.ts
index b2e1eb86f4..0e99a981bd 100644
--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.test.ts
@@ -22,15 +22,21 @@ const EXPECTED_DEFAULTS: Record<string, Record<string, unknown>> = {
content_shuffle: { scale_factor: 256 },
mediapipe_face_detection: { max_faces: 1, min_confidence: 0.5 },
color_map: { tile_size: 64 },
+ adjust_image: { channel: 'Luminosity (LAB)', value: 1, scale_values: false },
+ lineart_anime_edge_detection: {},
+ normal_map: {},
+ spandrel_filter: { model: null, autoScale: true, scale: 1 },
+ img_blur: { blur_type: 'gaussian', radius: 8 },
+ img_noise: { noise_type: 'gaussian', amount: 0.3, noise_color: true, size: 1 },
};
const EXPECTED_TYPES = Object.keys(EXPECTED_DEFAULTS);
describe('CONTROL_FILTERS registry', () => {
- it('contains exactly the ten legacy filter types', () => {
+ it('contains exactly all sixteen legacy filter types', () => {
const types = CONTROL_FILTERS.map((definition) => definition.type);
- expect(types).toHaveLength(10);
- expect(new Set(types).size).toBe(10);
+ expect(types).toHaveLength(16);
+ expect(new Set(types).size).toBe(16);
expect(types).toEqual(EXPECTED_TYPES);
});
@@ -62,8 +68,11 @@ describe('isSupportedFilterType / getFilterDefinition', () => {
describe('buildFilterGraph', () => {
const imageName = 'source-image.png';
- it('builds a single-node graph with default params for every filter', () => {
- for (const type of EXPECTED_TYPES) {
+ it('builds the direct legacy filter nodes with default params', () => {
+ const directTypes = EXPECTED_TYPES.filter(
+ (type) => !['adjust_image', 'spandrel_filter', 'img_blur', 'img_noise'].includes(type)
+ );
+ for (const type of directTypes) {
const { graph, outputNodeId } = buildFilterGraph(type, imageName);
expect(outputNodeId).toBe(FILTER_NODE_ID);
@@ -88,6 +97,173 @@ describe('buildFilterGraph', () => {
}
});
+ it('builds adjust_image as offset or channel multiply', () => {
+ const offset = buildFilterGraph('adjust_image', imageName).graph.nodes[FILTER_NODE_ID] as Record<string, unknown>;
+ expect(offset).toMatchObject({
+ channel: 'Luminosity (LAB)',
+ image: { image_name: imageName },
+ offset: 0,
+ type: 'img_channel_offset',
+ });
+
+ const multiplied = buildFilterGraph('adjust_image', imageName, {
+ channel: 'Red (RGBA)',
+ scale_values: true,
+ value: 1.5,
+ }).graph.nodes[FILTER_NODE_ID] as Record<string, unknown>;
+ expect(multiplied).toMatchObject({
+ channel: 'Red (RGBA)',
+ image: { image_name: imageName },
+ invert_channel: false,
+ scale: 1.5,
+ type: 'img_channel_multiply',
+ });
+ });
+
+ it('builds padded gaussian blur with alpha nudge wiring', () => {
+ const { graph, outputNodeId } = buildFilterGraph('img_blur', imageName);
+ expect(graph.nodes.control_filter_pad).toMatchObject({
+ bottom: 24,
+ image: { image_name: imageName },
+ left: 24,
+ right: 24,
+ top: 24,
+ type: 'img_pad_crop',
+ });
+ expect(graph.nodes[FILTER_NODE_ID]).toMatchObject({ blur_type: 'gaussian', radius: 8, type: 'img_blur' });
+ expect(graph.nodes.control_filter_alpha).toMatchObject({
+ channel: 'Alpha (RGBA)',
+ offset: 1,
+ type: 'img_channel_offset',
+ });
+ expect(graph.edges).toEqual([
+ {
+ destination: { field: 'image', node_id: FILTER_NODE_ID },
+ source: { field: 'image', node_id: 'control_filter_pad' },
+ },
+ {
+ destination: { field: 'image', node_id: 'control_filter_alpha' },
+ source: { field: 'image', node_id: FILTER_NODE_ID },
+ },
+ ]);
+ expect(outputNodeId).toBe('control_filter_alpha');
+ });
+
+ it('builds zero-radius blur directly without padding', () => {
+ const { graph, outputNodeId } = buildFilterGraph('img_blur', imageName, { radius: 0 });
+ expect(Object.keys(graph.nodes)).toEqual([FILTER_NODE_ID]);
+ expect(graph.nodes[FILTER_NODE_ID]).toMatchObject({ image: { image_name: imageName }, radius: 0 });
+ expect(graph.edges).toEqual([]);
+ expect(outputNodeId).toBe(FILTER_NODE_ID);
+ });
+
+ it('builds noise with an uncached rand_int seed edge', () => {
+ const { graph } = buildFilterGraph('img_noise', imageName);
+ expect(graph.nodes[FILTER_NODE_ID]).toMatchObject({ amount: 0.3, noise_color: true, size: 1, type: 'img_noise' });
+ expect(graph.nodes.control_filter_seed).toMatchObject({
+ high: 2147483647,
+ low: 0,
+ type: 'rand_int',
+ use_cache: false,
+ });
+ expect(graph.edges).toContainEqual({
+ destination: { field: 'seed', node_id: FILTER_NODE_ID },
+ source: { field: 'value', node_id: 'control_filter_seed' },
+ });
+ });
+
+ it('builds Spandrel autoscale and direct nodes and rejects a missing model', () => {
+ const model = { base: 'any', key: 'upscale', name: 'Upscaler', type: 'spandrel_image_to_image' };
+ expect(() => buildFilterGraph('spandrel_filter', imageName)).toThrow(/model/i);
+ expect(
+ buildFilterGraph('spandrel_filter', imageName, { model, scale: 4 }).graph.nodes[FILTER_NODE_ID]
+ ).toMatchObject({
+ image_to_image_model: model,
+ scale: 4,
+ type: 'spandrel_image_to_image_autoscale',
+ });
+ const direct = buildFilterGraph('spandrel_filter', imageName, { autoScale: false, model }).graph.nodes[
+ FILTER_NODE_ID
+ ] as Record<string, unknown>;
+ expect(direct).toMatchObject({ image_to_image_model: model, type: 'spandrel_image_to_image' });
+ expect(direct.scale).toBeUndefined();
+ });
+
+ it('clamps and coerces persisted numeric settings to declared bounds', () => {
+ const canny = buildFilterGraph('canny_edge_detection', imageName, {
+ high_threshold: 999,
+ low_threshold: -12.8,
+ }).graph.nodes[FILTER_NODE_ID] as Record<string, unknown>;
+ expect(canny.low_threshold).toBe(0);
+ expect(canny.high_threshold).toBe(255);
+
+ const noise = buildFilterGraph('img_noise', imageName, { amount: -2, size: 0.2 }).graph.nodes[
+ FILTER_NODE_ID
+ ] as Record<string, unknown>;
+ expect(noise.amount).toBe(0);
+ expect(noise.size).toBe(1);
+ });
+
+ it('coerces malformed persisted settings for every parameter of all sixteen filters', () => {
+ const model = { base: 'any', key: 'upscale', name: 'Upscaler', type: 'spandrel_image_to_image' };
+ for (const definition of CONTROL_FILTERS) {
+ const malformed: Record<string, unknown> = Object.fromEntries(
+ definition.params.map((param) => [param.key, param.kind === 'boolean' ? 'false' : { invalid: true }])
+ );
+ if (definition.type === 'spandrel_filter') {
+ malformed.model = model;
+ }
+ const node = buildFilterGraph(definition.type, imageName, malformed).graph.nodes[FILTER_NODE_ID] as Record<
+ string,
+ unknown
+ >;
+ for (const param of definition.params) {
+ if (param.kind === 'model') {
+ continue;
+ }
+ const projectedKey = definition.type === 'adjust_image' && param.key === 'value' ? 'offset' : param.key;
+ if (definition.type === 'adjust_image' && param.key === 'value') {
+ expect(node[projectedKey], definition.type).toBe(0);
+ } else if (
+ (definition.type !== 'adjust_image' || param.key !== 'scale_values') &&
+ (definition.type !== 'spandrel_filter' || param.key !== 'autoScale')
+ ) {
+ expect(node[projectedKey], `${definition.type}.${param.key}`).toBe(param.default);
+ }
+ }
+ }
+ });
+
+ it('clamps every declared numeric parameter at both bounds', () => {
+ const model = { base: 'any', key: 'upscale', name: 'Upscaler', type: 'spandrel_image_to_image' };
+ for (const definition of CONTROL_FILTERS) {
+ for (const param of definition.params) {
+ if (param.kind !== 'number') {
+ continue;
+ }
+ const lowSettings = { model, [param.key]: Number.MIN_SAFE_INTEGER };
+ const highSettings = { model, [param.key]: Number.MAX_SAFE_INTEGER };
+ const low = buildFilterGraph(definition.type, imageName, lowSettings).graph.nodes[FILTER_NODE_ID] as Record<
+ string,
+ unknown
+ >;
+ const high = buildFilterGraph(definition.type, imageName, highSettings).graph.nodes[FILTER_NODE_ID] as Record<
+ string,
+ unknown
+ >;
+ if (definition.type === 'adjust_image' && param.key === 'value') {
+ expect(low.offset).toBe(-255);
+ expect(high.offset).toBe(255);
+ } else if (param.min !== undefined) {
+ expect(low[param.key], `${definition.type}.${param.key}.min`).toBe(param.min);
+ }
+ if (param.max !== undefined && !(definition.type === 'adjust_image' && param.key === 'value')) {
+ expect(high[param.key], `${definition.type}.${param.key}.max`).toBe(param.max);
+ }
+ }
+ }
+ });
+
it('applies valid custom settings, overriding defaults', () => {
const { graph } = buildFilterGraph('canny_edge_detection', imageName, {
low_threshold: 50,
diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.ts
index a9f0f8bad2..ee050dc7e3 100644
--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.ts
+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.ts
@@ -1,5 +1,5 @@
/**
- * Pure single-node control-filter graph builders (legacy parity).
+ * Pure control-filter graph builders (legacy parity).
*
* A control layer can non-destructively preview a filter (canny, depth, pose, …)
* over its composited source. This module names each supported filter, its
@@ -10,9 +10,9 @@
*
* Node type strings + defaults mirror legacy
* `features/controlLayers/store/filters.ts` (`IMAGE_FILTERS`): every filter here
- * builds a single node whose backend `type` equals the filter id, fed
- * `image: { image_name }` plus the filter's parameters. The registry is the
- * spec — settings editors read `buildDefaults()` and the param metadata.
+ * builds the exact backend nodes used by legacy, fed `image: { image_name }`
+ * plus the filter's parameters. The registry is the spec — settings editors
+ * read `buildDefaults()` and the param metadata.
*/
import type { BackendGraphContract } from '@workbench/types';
@@ -24,7 +24,9 @@ export const FILTER_NODE_ID = 'control_filter';
export type FilterParamSpec =
| { kind: 'number'; key: string; default: number; min?: number; max?: number; step?: number; integer?: boolean }
| { kind: 'boolean'; key: string; default: boolean }
- | { kind: 'enum'; key: string; default: string; options: readonly string[] };
+ | { kind: 'enum'; key: string; default: string; options: readonly string[] }
+ | { kind: 'string'; key: string; default: string }
+ | { kind: 'model'; key: string; default: null; modelType: 'spandrel_image_to_image' };
/** One filter's identity, defaults, and node-arg projection. */
export interface FilterDefinition {
@@ -112,6 +114,63 @@ export const CONTROL_FILTERS: readonly FilterDefinition[] = [
params: [{ default: 64, integer: true, key: 'tile_size', kind: 'number', min: 1 }],
type: 'color_map',
},
+ {
+ params: [
+ {
+ default: 'Luminosity (LAB)',
+ key: 'channel',
+ kind: 'enum',
+ options: [
+ 'Red (RGBA)',
+ 'Green (RGBA)',
+ 'Blue (RGBA)',
+ 'Alpha (RGBA)',
+ 'Cyan (CMYK)',
+ 'Magenta (CMYK)',
+ 'Yellow (CMYK)',
+ 'Black (CMYK)',
+ 'Hue (HSV)',
+ 'Saturation (HSV)',
+ 'Value (HSV)',
+ 'Luminosity (LAB)',
+ 'A (LAB)',
+ 'B (LAB)',
+ 'Y (YCbCr)',
+ 'Cb (YCbCr)',
+ 'Cr (YCbCr)',
+ ],
+ },
+ { default: 1, key: 'value', kind: 'number', max: 2, min: 0, step: 0.0025 },
+ { default: false, key: 'scale_values', kind: 'boolean' },
+ ],
+ type: 'adjust_image',
+ },
+ { params: [], type: 'lineart_anime_edge_detection' },
+ { params: [], type: 'normal_map' },
+ {
+ params: [
+ { default: null, key: 'model', kind: 'model', modelType: 'spandrel_image_to_image' },
+ { default: true, key: 'autoScale', kind: 'boolean' },
+ { default: 1, key: 'scale', kind: 'number', max: 16, min: 1 },
+ ],
+ type: 'spandrel_filter',
+ },
+ {
+ params: [
+ { default: 'gaussian', key: 'blur_type', kind: 'enum', options: ['gaussian', 'box'] },
+ { default: 8, key: 'radius', kind: 'number', max: 4096, min: 0, step: 0.1 },
+ ],
+ type: 'img_blur',
+ },
+ {
+ params: [
+ { default: 'gaussian', key: 'noise_type', kind: 'enum', options: ['gaussian', 'salt_and_pepper'] },
+ { default: 0.3, key: 'amount', kind: 'number', max: 1, min: 0, step: 0.01 },
+ { default: true, key: 'noise_color', kind: 'boolean' },
+ { default: 1, integer: true, key: 'size', kind: 'number', max: 256, min: 1 },
+ ],
+ type: 'img_noise',
+ },
];
const FILTERS_BY_TYPE: ReadonlyMap<string, FilterDefinition> = new Map(
@@ -127,6 +186,22 @@ export const getFilterDefinition = (type: string): FilterDefinition | undefined
/** True when `type` names a supported control filter. */
export const isSupportedFilterType = (type: string): boolean => FILTERS_BY_TYPE.has(type);
+/** True when settings contain everything required to run the selected filter. */
+export const isFilterConfigValid = (type: string, settings: Record<string, unknown>): boolean => {
+ if (type !== 'spandrel_filter') {
+ return FILTERS_BY_TYPE.has(type);
+ }
+ const model = settings.model;
+ return (
+ typeof model === 'object' &&
+ model !== null &&
+ 'key' in model &&
+ typeof model.key === 'string' &&
+ 'type' in model &&
+ model.type === 'spandrel_image_to_image'
+ );
+};
+
/** Coerces arbitrary stored settings to the filter's params, falling back to each default. */
const resolveSettings = (
definition: FilterDefinition,
@@ -136,11 +211,27 @@ const resolveSettings = (
for (const param of definition.params) {
const value = settings?.[param.key];
if (param.kind === 'number' && typeof value === 'number' && Number.isFinite(value)) {
- resolved[param.key] = param.integer ? Math.round(value) : value;
+ const clamped = Math.min(
+ param.max ?? Number.POSITIVE_INFINITY,
+ Math.max(param.min ?? Number.NEGATIVE_INFINITY, value)
+ );
+ resolved[param.key] = param.integer ? Math.round(clamped) : clamped;
} else if (param.kind === 'boolean' && typeof value === 'boolean') {
resolved[param.key] = value;
} else if (param.kind === 'enum' && typeof value === 'string' && param.options.includes(value)) {
resolved[param.key] = value;
+ } else if (param.kind === 'string' && typeof value === 'string') {
+ resolved[param.key] = value;
+ } else if (
+ param.kind === 'model' &&
+ typeof value === 'object' &&
+ value !== null &&
+ 'key' in value &&
+ typeof value.key === 'string' &&
+ 'type' in value &&
+ value.type === param.modelType
+ ) {
+ resolved[param.key] = value;
} else {
resolved[param.key] = param.default;
}
@@ -174,21 +265,109 @@ export const buildFilterGraph = (
throw new Error(`Unknown control filter "${filterType}".`);
}
+ const resolved = resolveSettings(definition, settings);
const node = {
id: FILTER_NODE_ID,
image: { image_name: imageName },
is_intermediate: true,
type: definition.type,
use_cache: true,
- ...resolveSettings(definition, settings),
+ ...resolved,
};
+ const graph: BackendGraphContract = {
+ edges: [],
+ id: `control-filter-${definition.type}`,
+ nodes: { [FILTER_NODE_ID]: node },
+ };
+ const edge = (sourceId: string, sourceField: string, destinationId: string, destinationField: string): void => {
+ graph.edges.push({
+ destination: { field: destinationField, node_id: destinationId },
+ source: { field: sourceField, node_id: sourceId },
+ });
+ };
+
+ if (filterType === 'adjust_image') {
+ const { channel, scale_values: scaleValues, value } = resolved;
+ graph.nodes[FILTER_NODE_ID] = scaleValues
+ ? {
+ ...node,
+ channel,
+ invert_channel: false,
+ scale: value,
+ scale_values: undefined,
+ type: 'img_channel_multiply',
+ value: undefined,
+ }
+ : {
+ ...node,
+ channel,
+ offset: Math.round(255 * ((value as number) - 1)),
+ scale_values: undefined,
+ type: 'img_channel_offset',
+ value: undefined,
+ };
+ } else if (filterType === 'spandrel_filter') {
+ const model = resolved.model;
+ if (!model) {
+ throw new Error('Spandrel filter requires an image-to-image model.');
+ }
+ graph.nodes[FILTER_NODE_ID] = resolved.autoScale
+ ? {
+ ...node,
+ autoScale: undefined,
+ image_to_image_model: model,
+ model: undefined,
+ type: 'spandrel_image_to_image_autoscale',
+ }
+ : {
+ ...node,
+ autoScale: undefined,
+ image_to_image_model: model,
+ model: undefined,
+ scale: undefined,
+ type: 'spandrel_image_to_image',
+ };
+ } else if (filterType === 'img_blur') {
+ const radius = resolved.radius as number;
+ const padding = Math.max(0, Math.ceil(radius * (resolved.blur_type === 'gaussian' ? 3 : 1)));
+ if (padding > 0) {
+ delete graph.nodes[FILTER_NODE_ID]!.image;
+ graph.nodes.control_filter_pad = {
+ bottom: padding,
+ id: 'control_filter_pad',
+ image: { image_name: imageName },
+ left: padding,
+ right: padding,
+ top: padding,
+ type: 'img_pad_crop',
+ use_cache: true,
+ };
+ graph.nodes.control_filter_alpha = {
+ channel: 'Alpha (RGBA)',
+ id: 'control_filter_alpha',
+ is_intermediate: true,
+ offset: 1,
+ type: 'img_channel_offset',
+ use_cache: true,
+ };
+ edge('control_filter_pad', 'image', FILTER_NODE_ID, 'image');
+ edge(FILTER_NODE_ID, 'image', 'control_filter_alpha', 'image');
+ return { graph, outputNodeId: 'control_filter_alpha' };
+ }
+ } else if (filterType === 'img_noise') {
+ graph.nodes.control_filter_seed = {
+ high: 2147483647,
+ id: 'control_filter_seed',
+ low: 0,
+ type: 'rand_int',
+ use_cache: false,
+ };
+ edge('control_filter_seed', 'value', FILTER_NODE_ID, 'seed');
+ }
+
return {
- graph: {
- edges: [],
- id: `control-filter-${definition.type}`,
- nodes: { [FILTER_NODE_ID]: node },
- },
+ graph,
outputNodeId: FILTER_NODE_ID,
};
};
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.ts
index e528dd93f5..fbe8920725 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
@@ -9,6 +9,7 @@ import type {
} from '@workbench/generation/types';
import type {
CanvasDocumentContractV2,
+ CanvasControlLayerContract,
CanvasLayerContract,
CanvasRasterLayerContractV2,
WorkbenchState,
@@ -98,6 +99,7 @@ interface HarnessOptions {
uploadImage?: (blob: Blob) => Promise<CanvasImageUploadResult>;
projectId?: string;
dispatch?: ReturnType<typeof vi.fn<(action: WorkbenchAction) => void>>;
+ models?: RunCanvasInvocationDeps['models'];
}
const makeHarness = (options: HarnessOptions = {}): Harness => {
@@ -166,6 +168,7 @@ const makeHarness = (options: HarnessOptions = {}): Harness => {
generateValues: generateValuesFor(model),
getDocument: () => options.document ?? makeDoc([rasterLayer('layer-a')]),
inFlight: options.inFlight ?? new Set<string>(),
+ models: options.models,
projectId: options.projectId ?? 'project-1',
projectSettings: { useCpuNoise: true },
strength: options.strength ?? 0.75,
@@ -179,6 +182,33 @@ const makeHarness = (options: HarnessOptions = {}): Harness => {
return { deps, dispatch, events, flushPendingUploads, notices, submittedGraphs, uploadImage };
};
+const controlLayer = (
+ id: string,
+ overrides: Partial<CanvasControlLayerContract['adapter']> = {},
+ hasContent = true
+): CanvasControlLayerContract => ({
+ adapter: {
+ beginEndStepPct: [0, 1],
+ controlMode: 'balanced',
+ kind: 'controlnet',
+ model: null,
+ weight: 0.75,
+ ...overrides,
+ },
+ blendMode: 'normal',
+ id,
+ isEnabled: true,
+ isLocked: false,
+ name: id,
+ opacity: 1,
+ source: hasContent
+ ? { image: { height: 64, imageName: `${id}.png`, width: 64 }, type: 'image' }
+ : { bitmap: null, type: 'paint' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'control',
+ withTransparencyEffect: true,
+});
+
describe('runCanvasInvocation', () => {
beforeEach(() => {
vi.restoreAllMocks();
@@ -341,6 +371,48 @@ describe('runCanvasInvocation', () => {
expect(notices[0]?.message).toBe('upload exploded');
});
+ it('blocks invocation with the shared reason code when a nonempty control layer has no model', async () => {
+ const harness = makeHarness({ document: docWithLayers([controlLayer('control')]) });
+ await runCanvasInvocation(harness.deps);
+ expect(harness.submittedGraphs()).toHaveLength(0);
+ expect(harness.notices()).toHaveLength(1);
+ expect(harness.notices()[0]?.message).toContain('missing_model');
+ });
+
+ it('ignores an empty control layer with no model', async () => {
+ const harness = makeHarness({ document: docWithLayers([controlLayer('control', {}, false)]) });
+ await runCanvasInvocation(harness.deps);
+ expect(harness.submittedGraphs()).toHaveLength(1);
+ expect(harness.notices()).toHaveLength(0);
+ });
+
+ it('blocks the second enabled nonempty Control LoRA', async () => {
+ const model = {
+ base: 'flux',
+ file_size: 1,
+ format: 'checkpoint',
+ hash: 'hash',
+ key: 'control-lora',
+ name: 'Control LoRA',
+ path: 'control-lora',
+ source: 'control-lora',
+ source_type: 'path' as const,
+ type: 'control_lora',
+ };
+ const flux = { ...sd1Model, base: 'flux' as const, key: 'flux', name: 'FLUX' };
+ const harness = makeHarness({
+ document: docWithLayers([
+ controlLayer('first', { kind: 'control_lora', model: model.key }),
+ controlLayer('second', { kind: 'control_lora', model: model.key }),
+ ]),
+ model: flux,
+ models: [model],
+ });
+ await runCanvasInvocation(harness.deps);
+ expect(harness.submittedGraphs()).toHaveLength(0);
+ expect(harness.notices()[0]?.message).toContain('control_lora_limit');
+ });
+
it('ignores a concurrent invoke while a prior prepare for the same project is in flight', async () => {
const inFlight = new Set<string>();
let releaseFlush = (): void => {};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
index 0b47284969..9331840951 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts
@@ -54,7 +54,6 @@ import {
executeMaskComposite,
executeRegionalMaskComposite,
} from '@workbench/canvas-engine/export/compositeForGeneration';
-import { getControlLayerRejectionReason } from '@workbench/generation/canvas/addControlLayers';
import {
getRegionalGuidanceRejectionReason,
isRegionalGuidanceSupportedForBase,
@@ -66,6 +65,7 @@ import {
planControlComposites,
planRegionalMaskComposites,
} from '@workbench/generation/canvas/compositePlan';
+import { getControlValidationReason } from '@workbench/generation/canvas/controlValidation';
import { resolveGenerateSeed } from '@workbench/generation/graph';
import { normalizeGenerateWidgetValues, syncGenerateWidgetValuesWithModels } from '@workbench/generation/settings';
import { DEFAULT_CANVAS_COMPOSITING } from '@workbench/widgets/canvas/invoke/canvasCompositing';
@@ -121,11 +121,9 @@ const recordNotice = (
/**
* Composites + resolves the enabled control layers into graph inputs. Each
* content-bearing control layer is composited SEPARATELY (never blended) and its
- * adapter model resolved from the loaded models; layers that are invalid for the
- * selected base (unsupported base/kind, no/incompatible model) are skipped
- * silently, mirroring legacy (their warning surfaces in the layer's settings,
- * they never block generation). Content-less control layers are already excluded
- * by `planControlComposites`.
+ * adapter model resolved from the loaded models. Enabled nonempty invalid layers
+ * throw a shared reason code and block invocation; content-less control layers
+ * are already excluded by `planControlComposites` and remain harmless.
*/
const collectControlLayerInputs = async (
document: CanvasDocumentContractV2,
@@ -141,6 +139,7 @@ const collectControlLayerInputs = async (
const layerById = new Map(document.layers.map((layer) => [layer.id, layer]));
const inputs: ControlLayerGraphInput[] = [];
+ let controlLoraCount = 0;
for (const { entry, layerId } of composites) {
const layer = layerById.get(layerId);
@@ -150,16 +149,18 @@ const collectControlLayerInputs = async (
const { adapter } = layer;
const resolved = adapter.model ? models?.find((candidate) => candidate.key === adapter.model) : undefined;
- const rejection = getControlLayerRejectionReason({
- adapterModel: resolved ? { base: resolved.base } : null,
- hasContent: true,
+ const rejection = getControlValidationReason({
+ adapterModel: resolved ? { base: resolved.base, type: resolved.type } : null,
+ controlLoraIndex: adapter.kind === 'control_lora' ? controlLoraCount : 0,
kind: adapter.kind,
- layerName: layer.name,
mainBase: model.base,
mainVariant: model.variant ?? undefined,
});
if (rejection || !resolved) {
- continue;
+ throw new Error(`[${rejection ?? 'missing_model'}] Control layer "${layer.name}" is invalid.`);
+ }
+ if (adapter.kind === 'control_lora') {
+ controlLoraCount += 1;
}
const result = await executeControlComposite(entry, executorDeps);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.ts
index cd2607d3c3..96b3e45552 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.ts
@@ -50,4 +50,22 @@ describe('getFilterActionEligibility', () => {
canSave: false,
});
});
+
+ it('disables Process for Spandrel until a compatible model is selected', () => {
+ expect(
+ getFilterActionEligibility(state({ draft: { settings: { model: null }, type: 'spandrel_filter' } }))
+ ).toMatchObject({ canProcess: false });
+ expect(
+ getFilterActionEligibility(
+ state({
+ draft: {
+ settings: {
+ model: { base: 'any', key: 'upscale', name: 'Upscaler', type: 'spandrel_image_to_image' },
+ },
+ type: 'spandrel_filter',
+ },
+ })
+ )
+ ).toMatchObject({ canProcess: true });
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx
index 380d8cd7ee..902c141e76 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx
@@ -3,7 +3,11 @@ import type { FilterOperationSessionState } from '@workbench/widgets/layers/filt
import { HStack, Menu, Portal, Text } from '@chakra-ui/react';
import { Button, MenuContent } from '@workbench/components/ui';
import { makeImageDurable } from '@workbench/gallery/api';
-import { buildFilterDefaults, getFilterDefinition } from '@workbench/generation/canvas/filterGraphs';
+import {
+ buildFilterDefaults,
+ getFilterDefinition,
+ isFilterConfigValid,
+} from '@workbench/generation/canvas/filterGraphs';
import { useFilterSession } from '@workbench/widgets/canvas/engineStoreHooks';
import { LayerFilterControls } from '@workbench/widgets/layers/LayerFilterControls';
import { ChevronDownIcon } from 'lucide-react';
@@ -24,11 +28,12 @@ export interface FilterActionEligibility {
export const getFilterActionEligibility = (session: FilterOperationSessionState): FilterActionEligibility => {
const busy = session.status === 'processing' || session.status === 'committing';
const hasPreview = session.preview !== null && !busy;
+ const isValid = isFilterConfigValid(session.draft.type, session.draft.settings);
return {
canApply: hasPreview,
canCancel: true,
canEdit: !busy,
- canProcess: !busy,
+ canProcess: !busy && isValid,
canReset: !busy,
canSave: hasPreview,
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
index 2b1f19055d..934f238f14 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
@@ -6,13 +6,15 @@ import type { CanvasControlAdapterContract, CanvasControlLayerContract } from '@
import { createListCollection, HStack, Stack, Switch, Text } from '@chakra-ui/react';
import { Button, Field, Select, Slider } from '@workbench/components/ui';
import { isControlKindSupportedForBase } from '@workbench/generation/canvas/addControlLayers';
+import { resolveDefaultFilterForModel } from '@workbench/generation/canvas/controlRecommendations';
+import { getControlValidationReason } from '@workbench/generation/canvas/controlValidation';
import { useModelsSelector } from '@workbench/models/modelsStore';
import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';
import { useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
-import { applyStructural, applyStructuralPreview } from './layerOps';
+import { applyStructural, applyStructuralPreview, CONTROL_ADAPTER_DEFAULTS } from './layerOps';
const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: false } as const;
@@ -28,14 +30,14 @@ const formatUnitPercent = (value: number): string => `${Math.round(value * 100)}
const formatWeight = (value: number): string => value.toFixed(2);
/** The main model's base, read from the generate widget values (drives adapter support). */
-const useSelectedModelBase = (): string | null => {
+const useSelectedMainModel = () => {
const modelKey = useActiveProjectSelector((project) => {
const values = getProjectWidgetValues(project, 'generate');
const model = values?.model;
return model && typeof model === 'object' && 'key' in model ? String((model as { key: unknown }).key) : null;
});
const models = useModelsSelector((snapshot) => snapshot.models);
- return useMemo(() => models.find((model) => model.key === modelKey)?.base ?? null, [models, modelKey]);
+ return useMemo(() => models.find((model) => model.key === modelKey) ?? null, [models, modelKey]);
};
interface ControlLayerSettingsProps {
@@ -55,7 +57,8 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsProp
const { t } = useTranslation();
const dispatch = useWorkbenchDispatch();
const models = useModelsSelector((snapshot) => snapshot.models);
- const base = useSelectedModelBase();
+ const mainModel = useSelectedMainModel();
+ const base = mainModel?.base ?? null;
const { adapter } = layer;
const commitAdapter = useCallback(
@@ -103,13 +106,14 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsProp
}
// Switching kind clears the model (its base/type no longer matches) and, for
// non-ControlNet kinds, drops the control mode.
+ const defaults = CONTROL_ADAPTER_DEFAULTS[kind];
commitAdapter(
- { controlMode: kind === 'controlnet' ? (adapter.controlMode ?? 'balanced') : null, kind, model: null },
- { controlMode: adapter.controlMode, kind: adapter.kind, model: adapter.model },
+ { ...defaults, beginEndStepPct: [...defaults.beginEndStepPct] },
+ { ...adapter, beginEndStepPct: [...adapter.beginEndStepPct] },
t('widgets.layers.control.kind')
);
},
- [adapter.controlMode, adapter.kind, adapter.model, commitAdapter, t]
+ [adapter, commitAdapter, t]
);
const handleModelChange = useCallback(
@@ -117,9 +121,14 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsProp
const model = value[0] ?? null;
if (model !== adapter.model) {
commitAdapter({ model }, { model: adapter.model }, t('widgets.layers.control.model'));
+ const selected = models.find((candidate) => candidate.key === model);
+ const recommendation = resolveDefaultFilterForModel(selected);
+ if (recommendation && !layer.filter && engine?.stores.filterSession.get()?.layerId !== layer.id) {
+ engine?.startFilterOperation(layer.id, recommendation);
+ }
}
},
- [adapter.model, commitAdapter, t]
+ [adapter.model, commitAdapter, engine, layer.filter, layer.id, models, t]
);
const handleControlModeChange = useCallback(
@@ -242,6 +251,31 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsProp
const rangeAria = useMemo(() => [t('widgets.layers.control.beginStep'), t('widgets.layers.control.endStep')], [t]);
const selectedModelName = modelOptions.find((model) => model.key === adapter.model)?.name;
+ const adapterModel = models.find((model) => model.key === adapter.model) ?? null;
+ const hasContent = engine?.hasExportableLayerContent(layer.id) ?? false;
+ const controlLoraIndex =
+ adapter.kind === 'control_lora' && engine
+ ? (engine
+ .getDocument()
+ ?.layers.filter(
+ (candidate) =>
+ candidate.isEnabled &&
+ candidate.type === 'control' &&
+ candidate.adapter.kind === 'control_lora' &&
+ engine.hasExportableLayerContent(candidate.id)
+ )
+ .findIndex((candidate) => candidate.id === layer.id) ?? 0)
+ : 0;
+ const validationReason =
+ layer.isEnabled && hasContent && mainModel
+ ? getControlValidationReason({
+ adapterModel: adapterModel ? { base: adapterModel.base, type: adapterModel.type } : null,
+ controlLoraIndex: Math.max(0, controlLoraIndex),
+ kind: adapter.kind,
+ mainBase: mainModel.base,
+ mainVariant: mainModel.variant ?? undefined,
+ })
+ : null;
const startFilter = useCallback(() => engine?.startFilterOperation(layer.id), [engine, layer.id]);
return (
@@ -274,8 +308,8 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsProp
<Slider
aria-label={weightAria}
formatValue={formatWeight}
- max={2}
- min={-1}
+ max={0.75}
+ min={0}
size="sm"
step={0.01}
value={weightValue}
@@ -328,6 +362,11 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsProp
<Button disabled={!engine || layer.isLocked} size="xs" variant="outline" onClick={startFilter}>
{t('widgets.layers.control.filter')}
</Button>
+ {validationReason ? (
+ <Text color="fg.warning" fontSize="2xs" role="alert">
+ {t(`widgets.layers.control.validation.${validationReason}`)}
+ </Text>
+ ) : null}
</Stack>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.tsx
index 031fd6de2c..d217f35415 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.tsx
@@ -1,13 +1,17 @@
import type { SelectValueChangeDetails, SliderValueChangeDetails } from '@chakra-ui/react';
import type { FilterParamSpec } from '@workbench/generation/canvas/filterGraphs';
+import type { ModelConfig, ModelTaxonomyType } from '@workbench/models/types';
+import type { ChangeEvent } from 'react';
-import { createListCollection, Switch, Text } from '@chakra-ui/react';
+import { createListCollection, Input, Switch, Text } from '@chakra-ui/react';
import { Field, Select, Slider } from '@workbench/components/ui';
import { CONTROL_FILTERS, getFilterDefinition } from '@workbench/generation/canvas/filterGraphs';
+import { ModelSelect } from '@workbench/models/components/ModelSelect';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: false } as const;
+const SPANDREL_MODEL_TYPES: ModelTaxonomyType[] = ['spandrel_image_to_image'];
interface LayerFilterControlsProps {
filterType: string;
@@ -116,6 +120,19 @@ const FilterParamField = ({ disabled, param, value, onChange }: FilterParamField
},
[onChange, param]
);
+ const handleModel = useCallback(
+ (model: ModelConfig | null) => {
+ onChange(
+ param.key,
+ model ? { base: model.base, hash: model.hash, key: model.key, name: model.name, type: model.type } : null
+ );
+ },
+ [onChange, param.key]
+ );
+ const handleString = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => onChange(param.key, event.currentTarget.value),
+ [onChange, param.key]
+ );
const enumCollection = useMemo(
() =>
@@ -167,6 +184,36 @@ const FilterParamField = ({ disabled, param, value, onChange }: FilterParamField
);
}
+ if (param.kind === 'model') {
+ const model = typeof value === 'object' && value !== null && 'key' in value ? value : null;
+ return (
+ <Field label={label} required>
+ <ModelSelect
+ disabled={disabled}
+ invalid={!model}
+ modelTypes={SPANDREL_MODEL_TYPES}
+ placeholder={label}
+ size="xs"
+ value={model && typeof model.key === 'string' ? model.key : null}
+ onChange={handleModel}
+ />
+ </Field>
+ );
+ }
+
+ if (param.kind === 'string') {
+ return (
+ <Field label={label}>
+ <Input
+ disabled={disabled}
+ size="xs"
+ value={typeof value === 'string' ? value : param.default}
+ onChange={handleString}
+ />
+ </Field>
+ );
+ }
+
return (
<Field label={label}>
<Slider
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts
index e57cfa213d..25771c0a4e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts
@@ -30,6 +30,7 @@ import {
createRegionalGuidanceLayerWithRefImage,
createRegionalReferenceImage,
DEFAULT_CONTROL_ADAPTER,
+ CONTROL_ADAPTER_DEFAULTS,
DEFAULT_INPAINT_MASK_FILL,
fitLayerTransformToBbox,
getControlTransparencyEffectPatch,
@@ -298,6 +299,20 @@ describe('nextInpaintMaskName', () => {
});
describe('createControlLayer', () => {
+ it('centralizes legacy defaults for every adapter kind', () => {
+ expect(CONTROL_ADAPTER_DEFAULTS).toEqual({
+ control_lora: { beginEndStepPct: [0, 0.75], controlMode: null, kind: 'control_lora', model: null, weight: 0.75 },
+ controlnet: {
+ beginEndStepPct: [0, 0.75],
+ controlMode: 'balanced',
+ kind: 'controlnet',
+ model: null,
+ weight: 0.75,
+ },
+ t2i_adapter: { beginEndStepPct: [0, 0.75], controlMode: null, kind: 't2i_adapter', model: null, weight: 0.75 },
+ });
+ });
+
it('builds an empty control layer with the legacy-default ControlNet adapter and transparency on', () => {
const layer = createControlLayer('Control Layer 1', 'c1');
expect(layer).toMatchObject({
@@ -309,6 +324,7 @@ describe('createControlLayer', () => {
});
expect(layer.source).toEqual({ bitmap: null, type: 'paint' });
expect(layer.adapter).toEqual(DEFAULT_CONTROL_ADAPTER);
+ expect(layer.adapter.weight).toBe(0.75);
// The default adapter's mutable array must be copied, not shared.
expect(layer.adapter.beginEndStepPct).not.toBe(DEFAULT_CONTROL_ADAPTER.beginEndStepPct);
expect(layer.adapter.beginEndStepPct).toEqual([0, 0.75]);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
index 1cb28b9d89..c51fd94245 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
@@ -287,17 +287,37 @@ export const createRegionalGuidanceLayerWithRefImage = (
/**
* The legacy-default control adapter for a freshly created control layer
* (`features/controlLayers/store/util.ts` `initialControlNet`): a ControlNet with
- * weight 1, an active range of the first 75% of steps, `balanced` control mode,
+ * weight 0.75, an active range of the first 75% of steps, `balanced` control mode,
* and no model selected yet.
*/
-export const DEFAULT_CONTROL_ADAPTER: CanvasControlAdapterContract = {
- beginEndStepPct: [0, 0.75],
- controlMode: 'balanced',
- kind: 'controlnet',
- model: null,
- weight: 1,
+export const CONTROL_ADAPTER_DEFAULTS: Readonly<
+ Record<CanvasControlAdapterContract['kind'], CanvasControlAdapterContract>
+> = {
+ control_lora: {
+ beginEndStepPct: [0, 0.75],
+ controlMode: null,
+ kind: 'control_lora',
+ model: null,
+ weight: 0.75,
+ },
+ controlnet: {
+ beginEndStepPct: [0, 0.75],
+ controlMode: 'balanced',
+ kind: 'controlnet',
+ model: null,
+ weight: 0.75,
+ },
+ t2i_adapter: {
+ beginEndStepPct: [0, 0.75],
+ controlMode: null,
+ kind: 't2i_adapter',
+ model: null,
+ weight: 0.75,
+ },
};
+export const DEFAULT_CONTROL_ADAPTER = CONTROL_ADAPTER_DEFAULTS.controlnet;
+
/** The next free "Control Layer N" name given the existing layer names (N ≥ 1, first gap). */
export const nextControlLayerName = (existingNames: readonly string[]): string => {
const used = new Set<number>();