Skip to content

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

fix(canvas): match legacy filter parameter behavior

joshistoast4630941d30c4
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 13054b7502..af42f58203 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1224,6 +1224,41 @@
"size": "Size",
"value": "Value"
},
+ "filterOptions": {
+ "blur_type": {
+ "box": "Box",
+ "gaussian": "Gaussian"
+ },
+ "channel": {
+ "alpha": "Alpha (RGBA)",
+ "black": "Black (CMYK)",
+ "blue": "Blue (RGBA)",
+ "cb": "Cb (YCbCr)",
+ "cr": "Cr (YCbCr)",
+ "cyan": "Cyan (CMYK)",
+ "green": "Green (RGBA)",
+ "hue": "Hue (HSV)",
+ "lab_a": "A (LAB)",
+ "lab_b": "B (LAB)",
+ "luminosity": "Luminosity (LAB)",
+ "magenta": "Magenta (CMYK)",
+ "red": "Red (RGBA)",
+ "saturation": "Saturation (HSV)",
+ "value": "Value (HSV)",
+ "y": "Y (YCbCr)",
+ "yellow": "Yellow (CMYK)"
+ },
+ "model_size": {
+ "base": "Base",
+ "large": "Large",
+ "small": "Small",
+ "small_v2": "Small v2"
+ },
+ "noise_type": {
+ "gaussian": "Gaussian",
+ "salt_and_pepper": "Salt and pepper"
+ }
+ },
"filters": {
"adjust_image": "Adjust image",
"canny_edge_detection": "Canny",
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 52b605ce7b..412283e3e3 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -9216,13 +9216,84 @@ describe('guarded filter previews', () => {
expect(engine.getDocument()).toEqual(document);
expect((await engine.exportLayerPixels('manual')).status).toBe('ok');
- expect(engine.startFilterOperation('manual', 'normal_map')).toBe('started');
+ expect(engine.startFilterOperation('manual', 'normal_map')).toBe('not-ready');
+ expect(engine.stores.filterSession.get()).toBeNull();
+ expect(engine.startFilterOperation('manual')).toBe('started');
expect(engine.stores.filterSession.get()?.draft).toEqual(manual.filter);
engine.cancelFilterOperation();
expect(engine.getDocument()).toEqual(document);
engine.dispose();
});
+ it('does not replace another layer filter session with a recommendation', async () => {
+ const first = guardableLayer('first');
+ const second = guardableLayer('second');
+ const document = { ...emptyDoc(), layers: [first, second] };
+ const { store } = createReactiveStore(document);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ });
+ expect((await engine.exportLayerPixels('first')).status).toBe('ok');
+ expect(engine.startFilterOperation('first')).toBe('started');
+ engine.updateFilterOperation({ settings: { coarse: true }, type: 'lineart_edge_detection' });
+ const active = engine.stores.filterSession.get();
+
+ expect((await engine.exportLayerPixels('second')).status).toBe('ok');
+ expect(engine.startFilterOperation('second', 'normal_map')).toBe('not-ready');
+ expect(engine.stores.filterSession.get()).toEqual(active);
+ engine.dispose();
+ });
+
+ it('does not overwrite a same-layer draft or preview on rapid recommendations', async () => {
+ const layer = guardableLayer('recommended');
+ const document = { ...emptyDoc(), layers: [layer] };
+ const { store } = createReactiveStore(document);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ filterDeps: {
+ runGraph: vi.fn(() => Promise.resolve({ imageName: 'filtered', origin: 'canvas', output: {} })),
+ uploadIntermediate: vi.fn(() => Promise.resolve({ imageName: 'input' })),
+ },
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ });
+ expect((await engine.exportLayerPixels(layer.id)).status).toBe('ok');
+ expect(engine.startFilterOperation(layer.id, 'normal_map')).toBe('started');
+ engine.updateFilterOperation({ settings: { coarse: true }, type: 'lineart_edge_detection' });
+ await engine.processFilterOperation();
+ const active = engine.stores.filterSession.get();
+
+ expect(engine.startFilterOperation(layer.id, 'canny_edge_detection')).toBe('not-ready');
+ expect(engine.stores.filterSession.get()).toEqual(active);
+ engine.dispose();
+ });
+
+ it('does not replace a different active canvas operation with a recommendation', async () => {
+ const first = guardableLayer('first');
+ const second = guardableLayer('second');
+ const document = { ...emptyDoc(), layers: [first, second] };
+ const { store } = createReactiveStore(document);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ });
+ expect((await engine.exportLayerPixels('first')).status).toBe('ok');
+ expect(engine.startSelectObject('first')).toBe('started');
+ const operation = engine.canvasOperations.getSnapshot();
+
+ expect((await engine.exportLayerPixels('second')).status).toBe('ok');
+ expect(engine.startFilterOperation('second', 'normal_map')).toBe('not-ready');
+ expect(engine.canvasOperations.getSnapshot()).toEqual(operation);
+ expect(engine.stores.samSession.get()?.layerId).toBe('first');
+ 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 1c78ea8285..70fee2fec7 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -3246,6 +3246,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
const startFilterOperation = (layerId: string, recommendedFilterType?: string | null): StartFilterOperationResult => {
+ // Recommendations are opportunistic. Never replace an active manual filter,
+ // preview, Select Object session, or other canvas operation.
+ if (recommendedFilterType && canvasOperations.getSnapshot().status !== 'idle') {
+ return 'not-ready';
+ }
const document = mirror.getDocument();
const layer = document?.layers.find((candidate) => candidate.id === layerId);
if (!document || !layer) {
@@ -3254,6 +3259,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
if (layer.type !== 'raster' && layer.type !== 'control') {
return 'unsupported';
}
+ if (recommendedFilterType && layer.filter) {
+ return 'not-ready';
+ }
if (!layer.isEnabled) {
return 'disabled';
}
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 0e99a981bd..9b880e2944 100644
--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.test.ts
@@ -6,7 +6,9 @@ import {
CONTROL_FILTERS,
DEFAULT_CONTROL_FILTER_TYPE,
FILTER_NODE_ID,
+ getFilterNumberBounds,
getFilterDefinition,
+ isFilterConfigValid,
isSupportedFilterType,
} from './filterGraphs';
@@ -31,6 +33,13 @@ const EXPECTED_DEFAULTS: Record<string, Record<string, unknown>> = {
};
const EXPECTED_TYPES = Object.keys(EXPECTED_DEFAULTS);
+const SPANDREL_MODEL = {
+ base: 'any',
+ hash: 'blake3-hash',
+ key: 'upscale',
+ name: 'Upscaler',
+ type: 'spandrel_image_to_image',
+};
describe('CONTROL_FILTERS registry', () => {
it('contains exactly all sixteen legacy filter types', () => {
@@ -49,6 +58,70 @@ describe('CONTROL_FILTERS registry', () => {
it('names canny edge detection as the default control filter', () => {
expect(DEFAULT_CONTROL_FILTER_TYPE).toBe('canny_edge_detection');
});
+
+ it('declares localized labels for every enum option', () => {
+ for (const definition of CONTROL_FILTERS) {
+ for (const param of definition.params) {
+ if (param.kind === 'enum') {
+ expect(
+ param.options.every((option) => option.labelKey.startsWith('widgets.layers.control.filterOptions.'))
+ ).toBe(true);
+ }
+ }
+ }
+ });
+});
+
+describe('getFilterNumberBounds', () => {
+ it.each([
+ [
+ 'canny_edge_detection',
+ 'low_threshold',
+ {},
+ { inputMax: 255, inputMin: 0, sliderMax: 255, sliderMin: 0, step: 1 },
+ ],
+ [
+ 'canny_edge_detection',
+ 'high_threshold',
+ {},
+ { inputMax: 255, inputMin: 0, sliderMax: 255, sliderMin: 0, step: 1 },
+ ],
+ ['mlsd_detection', 'score_threshold', {}, { inputMax: 1, inputMin: 0, sliderMax: 1, sliderMin: 0, step: 0.01 }],
+ ['content_shuffle', 'scale_factor', {}, { inputMax: 4096, inputMin: 0, sliderMax: 4096, sliderMin: 0, step: 1 }],
+ ['mediapipe_face_detection', 'max_faces', {}, { inputMax: 20, inputMin: 1, sliderMax: 20, sliderMin: 1, step: 1 }],
+ [
+ 'mediapipe_face_detection',
+ 'min_confidence',
+ {},
+ { inputMax: 1, inputMin: 0, sliderMax: 1, sliderMin: 0, step: 0.01 },
+ ],
+ ['color_map', 'tile_size', {}, { inputMax: 4096, inputMin: 1, sliderMax: 256, sliderMin: 1, step: 1 }],
+ [
+ 'mlsd_detection',
+ 'distance_threshold',
+ {},
+ { inputMax: 1000, inputMin: 0, sliderMax: 100, sliderMin: 0, step: 1 },
+ ],
+ ['spandrel_filter', 'scale', {}, { inputMax: 16, inputMin: 1, sliderMax: 16, sliderMin: 1, step: 1 }],
+ ['img_blur', 'radius', {}, { inputMax: 4096, inputMin: 1, sliderMax: 64, sliderMin: 1, step: 0.1 }],
+ ['img_noise', 'amount', {}, { inputMax: 1, inputMin: 0, sliderMax: 1, sliderMin: 0, step: 0.01 }],
+ ['img_noise', 'size', {}, { inputMax: 256, inputMin: 1, sliderMax: 16, sliderMin: 1, step: 1 }],
+ ])('returns legacy slider and numeric bounds for %s.%s', (type, key, settings, expected) => {
+ const param = getFilterDefinition(type)?.params.find((candidate) => candidate.key === key);
+ if (param?.kind !== 'number') {
+ throw new Error(`Missing number param ${type}.${key}`);
+ }
+ expect(getFilterNumberBounds(param, settings)).toEqual(expected);
+ });
+
+ it('changes adjust value bounds with scale_values', () => {
+ const param = getFilterDefinition('adjust_image')?.params.find((candidate) => candidate.key === 'value');
+ if (param?.kind !== 'number') {
+ throw new Error('Missing adjust_image.value');
+ }
+ expect(getFilterNumberBounds(param, { scale_values: false })).toMatchObject({ inputMax: 2, sliderMax: 2 });
+ expect(getFilterNumberBounds(param, { scale_values: true })).toMatchObject({ inputMax: 255, sliderMax: 255 });
+ });
});
describe('isSupportedFilterType / getFilterDefinition', () => {
@@ -118,6 +191,18 @@ describe('buildFilterGraph', () => {
scale: 1.5,
type: 'img_channel_multiply',
});
+
+ const multipliedAtLegacyMax = buildFilterGraph('adjust_image', imageName, {
+ scale_values: true,
+ value: 999,
+ }).graph.nodes[FILTER_NODE_ID] as Record<string, unknown>;
+ expect(multipliedAtLegacyMax.scale).toBe(255);
+
+ const offsetAtMax = buildFilterGraph('adjust_image', imageName, {
+ scale_values: false,
+ value: 255,
+ }).graph.nodes[FILTER_NODE_ID] as Record<string, unknown>;
+ expect(offsetAtMax.offset).toBe(255);
});
it('builds padded gaussian blur with alpha nudge wiring', () => {
@@ -173,19 +258,17 @@ describe('buildFilterGraph', () => {
});
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]
+ buildFilterGraph('spandrel_filter', imageName, { model: SPANDREL_MODEL, scale: 4 }).graph.nodes[FILTER_NODE_ID]
).toMatchObject({
- image_to_image_model: model,
+ image_to_image_model: SPANDREL_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' });
+ const direct = buildFilterGraph('spandrel_filter', imageName, { autoScale: false, model: SPANDREL_MODEL }).graph
+ .nodes[FILTER_NODE_ID] as Record<string, unknown>;
+ expect(direct).toMatchObject({ image_to_image_model: SPANDREL_MODEL, type: 'spandrel_image_to_image' });
expect(direct.scale).toBeUndefined();
});
@@ -205,13 +288,12 @@ describe('buildFilterGraph', () => {
});
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;
+ malformed.model = SPANDREL_MODEL;
}
const node = buildFilterGraph(definition.type, imageName, malformed).graph.nodes[FILTER_NODE_ID] as Record<
string,
@@ -235,14 +317,13 @@ describe('buildFilterGraph', () => {
});
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 lowSettings = { model: SPANDREL_MODEL, [param.key]: Number.MIN_SAFE_INTEGER };
+ const highSettings = { model: SPANDREL_MODEL, [param.key]: Number.MAX_SAFE_INTEGER };
const low = buildFilterGraph(definition.type, imageName, lowSettings).graph.nodes[FILTER_NODE_ID] as Record<
string,
unknown
@@ -255,7 +336,7 @@ describe('buildFilterGraph', () => {
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);
+ expect(low[param.key], `${definition.type}.${param.key}.min`).toBe(param.coerceMin ?? 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);
@@ -264,6 +345,17 @@ describe('buildFilterGraph', () => {
}
});
+ it('requires a complete nonempty backend Spandrel model identifier', () => {
+ expect(isFilterConfigValid('spandrel_filter', { model: SPANDREL_MODEL })).toBe(true);
+ for (const field of ['key', 'hash', 'name', 'base', 'type'] as const) {
+ expect(isFilterConfigValid('spandrel_filter', { model: { ...SPANDREL_MODEL, [field]: '' } }), field).toBe(false);
+ }
+ expect(isFilterConfigValid('spandrel_filter', { model: { ...SPANDREL_MODEL, type: 'controlnet' } })).toBe(false);
+ expect(() => buildFilterGraph('spandrel_filter', imageName, { model: { ...SPANDREL_MODEL, hash: '' } })).toThrow(
+ /model/i
+ );
+ });
+
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 ee050dc7e3..47479a40aa 100644
--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.ts
+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/filterGraphs.ts
@@ -22,9 +22,26 @@ export const FILTER_NODE_ID = 'control_filter';
/** A filter parameter's UI + validation metadata (drives the settings editor). */
export type FilterParamSpec =
- | { kind: 'number'; key: string; default: number; min?: number; max?: number; step?: number; integer?: boolean }
+ | {
+ kind: 'number';
+ key: string;
+ default: number;
+ min: number;
+ max: number;
+ step: number;
+ integer?: boolean;
+ sliderMin?: number;
+ sliderMax?: number;
+ coerceMin?: number;
+ dynamicBounds?: 'adjust_value';
+ }
| { kind: 'boolean'; key: string; default: boolean }
- | { kind: 'enum'; key: string; default: string; options: readonly string[] }
+ | {
+ kind: 'enum';
+ key: string;
+ default: string;
+ options: readonly { labelKey: string; value: string }[];
+ }
| { kind: 'string'; key: string; default: string }
| { kind: 'model'; key: string; default: null; modelType: 'spandrel_image_to_image' };
@@ -53,8 +70,8 @@ export const buildFilterDefaults = (definition: FilterDefinition): Record<string
export const CONTROL_FILTERS: readonly FilterDefinition[] = [
{
params: [
- { default: 100, integer: true, key: 'low_threshold', kind: 'number', max: 255, min: 0 },
- { default: 200, integer: true, key: 'high_threshold', kind: 'number', max: 255, min: 0 },
+ { default: 100, integer: true, key: 'low_threshold', kind: 'number', max: 255, min: 0, step: 1 },
+ { default: 200, integer: true, key: 'high_threshold', kind: 'number', max: 255, min: 0, step: 1 },
],
type: 'canny_edge_detection',
},
@@ -64,7 +81,12 @@ export const CONTROL_FILTERS: readonly FilterDefinition[] = [
default: 'small_v2',
key: 'model_size',
kind: 'enum',
- options: ['large', 'base', 'small', 'small_v2'],
+ options: [
+ { labelKey: 'widgets.layers.control.filterOptions.model_size.large', value: 'large' },
+ { labelKey: 'widgets.layers.control.filterOptions.model_size.base', value: 'base' },
+ { labelKey: 'widgets.layers.control.filterOptions.model_size.small', value: 'small' },
+ { labelKey: 'widgets.layers.control.filterOptions.model_size.small_v2', value: 'small_v2' },
+ ],
},
],
type: 'depth_anything_depth_estimation',
@@ -87,8 +109,8 @@ export const CONTROL_FILTERS: readonly FilterDefinition[] = [
},
{
params: [
- { default: 0.1, key: 'score_threshold', kind: 'number', min: 0, step: 0.01 },
- { default: 20, key: 'distance_threshold', kind: 'number', min: 0, step: 0.1 },
+ { default: 0.1, key: 'score_threshold', kind: 'number', max: 1, min: 0, step: 0.01 },
+ { default: 20, key: 'distance_threshold', kind: 'number', max: 1000, min: 0, sliderMax: 100, step: 1 },
],
type: 'mlsd_detection',
},
@@ -100,18 +122,20 @@ export const CONTROL_FILTERS: readonly FilterDefinition[] = [
type: 'pidi_edge_detection',
},
{
- params: [{ default: 256, integer: true, key: 'scale_factor', kind: 'number', min: 1 }],
+ params: [{ default: 256, integer: true, key: 'scale_factor', kind: 'number', max: 4096, min: 0, step: 1 }],
type: 'content_shuffle',
},
{
params: [
- { default: 1, integer: true, key: 'max_faces', kind: 'number', min: 1 },
+ { default: 1, integer: true, key: 'max_faces', kind: 'number', max: 20, min: 1, step: 1 },
{ default: 0.5, key: 'min_confidence', kind: 'number', max: 1, min: 0, step: 0.01 },
],
type: 'mediapipe_face_detection',
},
{
- params: [{ default: 64, integer: true, key: 'tile_size', kind: 'number', min: 1 }],
+ params: [
+ { default: 64, integer: true, key: 'tile_size', kind: 'number', max: 4096, min: 1, sliderMax: 256, step: 1 },
+ ],
type: 'color_map',
},
{
@@ -121,26 +145,26 @@ export const CONTROL_FILTERS: readonly FilterDefinition[] = [
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)',
+ { labelKey: 'widgets.layers.control.filterOptions.channel.red', value: 'Red (RGBA)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.green', value: 'Green (RGBA)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.blue', value: 'Blue (RGBA)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.alpha', value: 'Alpha (RGBA)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.cyan', value: 'Cyan (CMYK)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.magenta', value: 'Magenta (CMYK)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.yellow', value: 'Yellow (CMYK)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.black', value: 'Black (CMYK)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.hue', value: 'Hue (HSV)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.saturation', value: 'Saturation (HSV)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.value', value: 'Value (HSV)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.luminosity', value: 'Luminosity (LAB)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.lab_a', value: 'A (LAB)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.lab_b', value: 'B (LAB)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.y', value: 'Y (YCbCr)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.cb', value: 'Cb (YCbCr)' },
+ { labelKey: 'widgets.layers.control.filterOptions.channel.cr', value: 'Cr (YCbCr)' },
],
},
- { default: 1, key: 'value', kind: 'number', max: 2, min: 0, step: 0.0025 },
+ { default: 1, dynamicBounds: 'adjust_value', key: 'value', kind: 'number', max: 255, min: 0, step: 0.0025 },
{ default: false, key: 'scale_values', kind: 'boolean' },
],
type: 'adjust_image',
@@ -151,23 +175,42 @@ export const CONTROL_FILTERS: readonly FilterDefinition[] = [
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 },
+ { default: 1, key: 'scale', kind: 'number', max: 16, min: 1, step: 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 },
+ {
+ default: 'gaussian',
+ key: 'blur_type',
+ kind: 'enum',
+ options: [
+ { labelKey: 'widgets.layers.control.filterOptions.blur_type.gaussian', value: 'gaussian' },
+ { labelKey: 'widgets.layers.control.filterOptions.blur_type.box', value: 'box' },
+ ],
+ },
+ { coerceMin: 0, default: 8, key: 'radius', kind: 'number', max: 4096, min: 1, sliderMax: 64, step: 0.1 },
],
type: 'img_blur',
},
{
params: [
- { default: 'gaussian', key: 'noise_type', kind: 'enum', options: ['gaussian', 'salt_and_pepper'] },
+ {
+ default: 'gaussian',
+ key: 'noise_type',
+ kind: 'enum',
+ options: [
+ { labelKey: 'widgets.layers.control.filterOptions.noise_type.gaussian', value: 'gaussian' },
+ {
+ labelKey: 'widgets.layers.control.filterOptions.noise_type.salt_and_pepper',
+ value: '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 },
+ { default: 1, integer: true, key: 'size', kind: 'number', max: 256, min: 1, sliderMax: 16, step: 1 },
],
type: 'img_noise',
},
@@ -186,20 +229,46 @@ 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);
+export interface FilterNumberBounds {
+ inputMax: number;
+ inputMin: number;
+ sliderMax: number;
+ sliderMin: number;
+ step: number;
+}
+
+/** Resolves legacy slider/input ranges, including adjust_image's mode-dependent value maximum. */
+export const getFilterNumberBounds = (
+ param: Extract<FilterParamSpec, { kind: 'number' }>,
+ settings: Record<string, unknown>
+): FilterNumberBounds => {
+ const dynamicMax = param.dynamicBounds === 'adjust_value' && settings.scale_values !== true ? 2 : param.max;
+ return {
+ inputMax: dynamicMax,
+ inputMin: param.min,
+ sliderMax: param.dynamicBounds === 'adjust_value' ? dynamicMax : (param.sliderMax ?? dynamicMax),
+ sliderMin: param.sliderMin ?? param.min,
+ step: param.step,
+ };
+};
+
+const isNonemptyStringField = (value: object, key: string): boolean =>
+ key in value &&
+ typeof (value as Record<string, unknown>)[key] === 'string' &&
+ ((value as Record<string, unknown>)[key] as string).trim().length > 0;
+
+export const isSpandrelModelIdentifier = (value: unknown): boolean =>
+ typeof value === 'object' &&
+ value !== null &&
+ ['key', 'hash', 'name', 'base', 'type'].every((key) => isNonemptyStringField(value, key)) &&
+ (value as { type: string }).type === 'spandrel_image_to_image';
+
/** 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'
- );
+ return isSpandrelModelIdentifier(settings.model);
};
/** Coerces arbitrary stored settings to the filter's params, falling back to each default. */
@@ -211,25 +280,23 @@ const resolveSettings = (
for (const param of definition.params) {
const value = settings?.[param.key];
if (param.kind === 'number' && typeof value === 'number' && Number.isFinite(value)) {
- const clamped = Math.min(
- param.max ?? Number.POSITIVE_INFINITY,
- Math.max(param.min ?? Number.NEGATIVE_INFINITY, value)
- );
+ const bounds = getFilterNumberBounds(param, settings ?? {});
+ const clamped = Math.min(bounds.inputMax, Math.max(param.coerceMin ?? bounds.inputMin, 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)) {
+ } else if (
+ param.kind === 'enum' &&
+ typeof value === 'string' &&
+ param.options.some((option) => option.value === 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
+ param.modelType === 'spandrel_image_to_image' &&
+ isSpandrelModelIdentifier(value)
) {
resolved[param.key] = value;
} else {
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 96b3e45552..ec7882e8ab 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
@@ -60,7 +60,13 @@ describe('getFilterActionEligibility', () => {
state({
draft: {
settings: {
- model: { base: 'any', key: 'upscale', name: 'Upscaler', type: 'spandrel_image_to_image' },
+ model: {
+ base: 'any',
+ hash: 'blake3-hash',
+ key: 'upscale',
+ name: 'Upscaler',
+ type: 'spandrel_image_to_image',
+ },
},
type: 'spandrel_filter',
},
@@ -68,4 +74,19 @@ describe('getFilterActionEligibility', () => {
)
).toMatchObject({ canProcess: true });
});
+
+ it('disables Process for stale partial Spandrel identifiers', () => {
+ expect(
+ getFilterActionEligibility(
+ state({
+ draft: {
+ settings: {
+ model: { base: 'any', hash: '', key: 'upscale', name: 'Upscaler', type: 'spandrel_image_to_image' },
+ },
+ type: 'spandrel_filter',
+ },
+ })
+ )
+ ).toMatchObject({ canProcess: false });
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
index 934f238f14..9bada9aba9 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx
@@ -1,9 +1,13 @@
-import type { SelectValueChangeDetails, SliderValueChangeDetails } from '@chakra-ui/react';
+import type {
+ NumberInput as ChakraNumberInput,
+ SelectValueChangeDetails,
+ SliderValueChangeDetails,
+} from '@chakra-ui/react';
import type { CanvasEngine } from '@workbench/canvas-engine/engine';
import type { ControlAdapterKind } from '@workbench/generation/canvas/addControlLayers';
import type { CanvasControlAdapterContract, CanvasControlLayerContract } from '@workbench/types';
-import { createListCollection, HStack, Stack, Switch, Text } from '@chakra-ui/react';
+import { createListCollection, HStack, NumberInput, 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';
@@ -14,7 +18,7 @@ import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/Workb
import { useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
-import { applyStructural, applyStructuralPreview, CONTROL_ADAPTER_DEFAULTS } from './layerOps';
+import { applyStructural, applyStructuralPreview, CONTROL_ADAPTER_DEFAULTS, CONTROL_WEIGHT_BOUNDS } from './layerOps';
const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: false } as const;
@@ -123,7 +127,7 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsProp
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) {
+ if (recommendation && !layer.filter) {
engine?.startFilterOperation(layer.id, recommendation);
}
}
@@ -175,6 +179,19 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsProp
},
[adapter.weight, commitAdapter, t]
);
+ const handleWeightInputChange = useCallback(
+ ({ valueAsNumber }: ChakraNumberInput.ValueChangeDetails) => {
+ if (
+ !Number.isFinite(valueAsNumber) ||
+ valueAsNumber < CONTROL_WEIGHT_BOUNDS.inputMin ||
+ valueAsNumber > CONTROL_WEIGHT_BOUNDS.inputMax
+ ) {
+ return;
+ }
+ commitAdapter({ weight: valueAsNumber }, { weight: adapter.weight }, t('widgets.layers.control.weight'));
+ },
+ [adapter.weight, commitAdapter, t]
+ );
const rangeBeforeRef = useRef<[number, number] | null>(null);
const handleRangeChange = useCallback(
@@ -245,7 +262,11 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsProp
const kindValue = useMemo(() => [adapter.kind], [adapter.kind]);
const modelValue = useMemo(() => (adapter.model ? [adapter.model] : []), [adapter.model]);
const controlModeValue = useMemo(() => [adapter.controlMode ?? 'balanced'], [adapter.controlMode]);
- const weightValue = useMemo(() => [adapter.weight], [adapter.weight]);
+ const weightValue = useMemo(
+ () => [Math.min(CONTROL_WEIGHT_BOUNDS.sliderMax, Math.max(CONTROL_WEIGHT_BOUNDS.sliderMin, adapter.weight))],
+ [adapter.weight]
+ );
+ const weightInputValue = String(adapter.weight);
const rangeValue = useMemo(() => [...adapter.beginEndStepPct], [adapter.beginEndStepPct]);
const weightAria = useMemo(() => [t('widgets.layers.control.weight')], [t]);
const rangeAria = useMemo(() => [t('widgets.layers.control.beginStep'), t('widgets.layers.control.endStep')], [t]);
@@ -305,18 +326,33 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsProp
/>
</Field>
<Field label={t('widgets.layers.control.weight')}>
- <Slider
- aria-label={weightAria}
- formatValue={formatWeight}
- max={0.75}
- min={0}
- size="sm"
- step={0.01}
- value={weightValue}
- withThumbTooltip
- onValueChange={handleWeightChange}
- onValueChangeEnd={handleWeightChangeEnd}
- />
+ <HStack gap="2">
+ <Slider
+ aria-label={weightAria}
+ flex="1"
+ formatValue={formatWeight}
+ max={CONTROL_WEIGHT_BOUNDS.sliderMax}
+ min={CONTROL_WEIGHT_BOUNDS.sliderMin}
+ size="sm"
+ step={CONTROL_WEIGHT_BOUNDS.step}
+ value={weightValue}
+ withThumbTooltip
+ onValueChange={handleWeightChange}
+ onValueChangeEnd={handleWeightChangeEnd}
+ />
+ <NumberInput.Root
+ max={CONTROL_WEIGHT_BOUNDS.inputMax}
+ min={CONTROL_WEIGHT_BOUNDS.inputMin}
+ size="xs"
+ step={CONTROL_WEIGHT_BOUNDS.step}
+ value={weightInputValue}
+ w="20"
+ onValueChange={handleWeightInputChange}
+ >
+ <NumberInput.Control />
+ <NumberInput.Input aria-label={t('widgets.layers.control.weight')} />
+ </NumberInput.Root>
+ </HStack>
</Field>
<Field label={t('widgets.layers.control.stepRange')}>
<Slider
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.tsx
index d217f35415..e5639f1aef 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.tsx
@@ -1,11 +1,20 @@
-import type { SelectValueChangeDetails, SliderValueChangeDetails } from '@chakra-ui/react';
+import type {
+ NumberInput as ChakraNumberInput,
+ 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, Input, Switch, Text } from '@chakra-ui/react';
+import { createListCollection, HStack, Input, NumberInput, Switch, Text } from '@chakra-ui/react';
import { Field, Select, Slider } from '@workbench/components/ui';
-import { CONTROL_FILTERS, getFilterDefinition } from '@workbench/generation/canvas/filterGraphs';
+import {
+ CONTROL_FILTERS,
+ getFilterDefinition,
+ getFilterNumberBounds,
+ isSpandrelModelIdentifier,
+} from '@workbench/generation/canvas/filterGraphs';
import { ModelSelect } from '@workbench/models/components/ModelSelect';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -79,6 +88,7 @@ export const LayerFilterControls = ({
key={param.key}
disabled={disabled}
param={param}
+ settings={settings}
value={settings[param.key]}
onChange={handleSettingChange}
/>
@@ -90,11 +100,12 @@ export const LayerFilterControls = ({
interface FilterParamFieldProps {
disabled: boolean;
param: FilterParamSpec;
+ settings: Record<string, unknown>;
value: unknown;
onChange: (key: string, value: unknown) => void;
}
-const FilterParamField = ({ disabled, param, value, onChange }: FilterParamFieldProps) => {
+const FilterParamField = ({ disabled, param, settings, value, onChange }: FilterParamFieldProps) => {
const { t } = useTranslation();
const label = t(`widgets.layers.control.filterParams.${param.key}`, param.key);
const labelAria = useMemo(() => [label], [label]);
@@ -120,6 +131,14 @@ const FilterParamField = ({ disabled, param, value, onChange }: FilterParamField
},
[onChange, param]
);
+ const handleNumberInput = useCallback(
+ ({ valueAsNumber }: ChakraNumberInput.ValueChangeDetails) => {
+ if (Number.isFinite(valueAsNumber)) {
+ onChange(param.key, param.kind === 'number' && param.integer ? Math.round(valueAsNumber) : valueAsNumber);
+ }
+ },
+ [onChange, param]
+ );
const handleModel = useCallback(
(model: ModelConfig | null) => {
onChange(
@@ -137,15 +156,27 @@ const FilterParamField = ({ disabled, param, value, onChange }: FilterParamField
const enumCollection = useMemo(
() =>
param.kind === 'enum'
- ? createListCollection({ items: param.options.map((option) => ({ label: option, value: option })) })
+ ? createListCollection({
+ items: param.options.map((option) => ({ label: t(option.labelKey, option.value), value: option.value })),
+ })
: null,
- [param]
+ [param, t]
);
const enumCurrent =
- param.kind === 'enum' && typeof value === 'string' && param.options.includes(value) ? value : param.default;
+ param.kind === 'enum' && typeof value === 'string' && param.options.some((option) => option.value === value)
+ ? value
+ : param.default;
+ const enumCurrentOption = param.kind === 'enum' ? param.options.find((option) => option.value === enumCurrent) : null;
+ const enumCurrentLabel = enumCurrentOption
+ ? t(enumCurrentOption.labelKey, enumCurrentOption.value)
+ : String(enumCurrent);
const enumValue = useMemo(() => [String(enumCurrent)], [enumCurrent]);
const numberCurrent = typeof value === 'number' && Number.isFinite(value) ? value : param.default;
- const numberValue = useMemo(() => [Number(numberCurrent)], [numberCurrent]);
+ const numberBounds = param.kind === 'number' ? getFilterNumberBounds(param, settings) : null;
+ const sliderCurrent = numberBounds
+ ? Math.min(numberBounds.sliderMax, Math.max(numberBounds.sliderMin, Number(numberCurrent)))
+ : Number(numberCurrent);
+ const numberValue = useMemo(() => [sliderCurrent], [sliderCurrent]);
if (param.kind === 'boolean') {
return (
@@ -177,7 +208,7 @@ const FilterParamField = ({ disabled, param, value, onChange }: FilterParamField
positioning={SELECT_POSITIONING}
size="xs"
value={enumValue}
- valueText={String(enumCurrent)}
+ valueText={enumCurrentLabel}
onValueChange={handleEnum}
/>
</Field>
@@ -185,7 +216,7 @@ const FilterParamField = ({ disabled, param, value, onChange }: FilterParamField
}
if (param.kind === 'model') {
- const model = typeof value === 'object' && value !== null && 'key' in value ? value : null;
+ const model = isSpandrelModelIdentifier(value) ? (value as { key: string }) : null;
return (
<Field label={label} required>
<ModelSelect
@@ -214,19 +245,39 @@ const FilterParamField = ({ disabled, param, value, onChange }: FilterParamField
);
}
+ if (param.kind !== 'number' || !numberBounds) {
+ return null;
+ }
+
return (
<Field label={label}>
- <Slider
- aria-label={labelAria}
- disabled={disabled}
- max={param.kind === 'number' ? (param.max ?? 255) : 255}
- min={param.kind === 'number' ? (param.min ?? 0) : 0}
- size="sm"
- step={param.kind === 'number' ? (param.step ?? (param.integer ? 1 : 0.01)) : 0.01}
- value={numberValue}
- withThumbTooltip
- onValueChangeEnd={handleNumberEnd}
- />
+ <HStack gap="2">
+ <Slider
+ aria-label={labelAria}
+ disabled={disabled}
+ flex="1"
+ max={numberBounds.sliderMax}
+ min={numberBounds.sliderMin}
+ size="sm"
+ step={numberBounds.step}
+ value={numberValue}
+ withThumbTooltip
+ onValueChangeEnd={handleNumberEnd}
+ />
+ <NumberInput.Root
+ disabled={disabled}
+ max={numberBounds.inputMax}
+ min={numberBounds.inputMin}
+ size="xs"
+ step={numberBounds.step}
+ value={String(numberCurrent)}
+ w="20"
+ onValueChange={handleNumberInput}
+ >
+ <NumberInput.Control />
+ <NumberInput.Input aria-label={label} />
+ </NumberInput.Root>
+ </HStack>
</Field>
);
};
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 25771c0a4e..5ff17e8f5b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts
@@ -31,6 +31,7 @@ import {
createRegionalReferenceImage,
DEFAULT_CONTROL_ADAPTER,
CONTROL_ADAPTER_DEFAULTS,
+ CONTROL_WEIGHT_BOUNDS,
DEFAULT_INPAINT_MASK_FILL,
fitLayerTransformToBbox,
getControlTransparencyEffectPatch,
@@ -313,6 +314,11 @@ describe('createControlLayer', () => {
});
});
+ it('keeps the 0.75 creation default separate from legacy weight input ranges', () => {
+ expect(DEFAULT_CONTROL_ADAPTER.weight).toBe(0.75);
+ expect(CONTROL_WEIGHT_BOUNDS).toEqual({ inputMax: 2, inputMin: -1, sliderMax: 2, sliderMin: 0, step: 0.05 });
+ });
+
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({
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
index c51fd94245..4e3be492fe 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
@@ -316,6 +316,14 @@ export const CONTROL_ADAPTER_DEFAULTS: Readonly<
},
};
+export const CONTROL_WEIGHT_BOUNDS = {
+ inputMax: 2,
+ inputMin: -1,
+ sliderMax: 2,
+ sliderMin: 0,
+ step: 0.05,
+} as const;
+
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). */