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: expand generate settings controls

joshistoastf7603404cc28
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx
index f071ecefb3..db72826012 100644
--- a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx
@@ -6,28 +6,12 @@ import {
type QueueCoordinator,
type ReconcileInput,
} from './backend/queueCoordinator';
-import type { GenerateSettings } from './generation/types';
+import { normalizeGenerateSettings } from './generation/settings';
import { addImagesToGalleryBoard } from './gallery/api';
import type { Project, QueueItem } from './types';
import { useWorkbench } from './WorkbenchContext';
import type { WorkbenchAction } from './workbenchState';
-const isGenerateSettings = (value: unknown): value is GenerateSettings => {
- if (!value || typeof value !== 'object') {
- return false;
- }
-
- const record = value as Record<string, unknown>;
-
- return (
- typeof record.modelKey === 'string' &&
- typeof record.positivePrompt === 'string' &&
- typeof record.negativePrompt === 'string' &&
- typeof record.seed === 'number' &&
- Number.isFinite(record.seed)
- );
-};
-
const getSnapshotGalleryBoardId = (queueItem: QueueItem): string | null => {
const selectedBoardId = queueItem.snapshot.widgetStates.gallery.values.selectedBoardId;
@@ -84,9 +68,9 @@ const submitQueueItem = (
dispatch: Dispatch<WorkbenchAction>
): void => {
const graph = queueItem.snapshot.graph.backendGraph;
- const generateValues = queueItem.snapshot.widgetStates.generate.values;
+ const generateValues = normalizeGenerateSettings(queueItem.snapshot.widgetStates.generate.values);
- if (!graph || !isGenerateSettings(generateValues)) {
+ if (!graph || !generateValues) {
dispatch({
error: 'Generate queue item is missing a compiled backend graph.',
projectId: project.id,
@@ -108,6 +92,7 @@ const submitQueueItem = (
positivePromptNodeId: 'positive_prompt',
seed: generateValues.seed,
seedNodeId: 'seed',
+ shouldRandomizeSeed: generateValues.shouldRandomizeSeed,
sourceQueueItemId: queueItem.id,
})
.then(({ batchId, itemIds }) => {
diff --git a/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.test.ts b/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.test.ts
index 38de96116c..c1cfd09c60 100644
--- a/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.test.ts
@@ -85,6 +85,7 @@ const generateRequest: EnqueueGenerateRequest = {
positivePromptNodeId: 'positive_prompt',
seed: 1,
seedNodeId: 'seed',
+ shouldRandomizeSeed: false,
sourceQueueItemId: 'local-1',
};
diff --git a/invokeai/frontend/webv2/src/workbench/generation/api.test.ts b/invokeai/frontend/webv2/src/workbench/generation/api.test.ts
new file mode 100644
index 0000000000..6c431d5787
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/generation/api.test.ts
@@ -0,0 +1,89 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { EnqueueGenerateRequest } from './types';
+
+const mocks = vi.hoisted(() => ({
+ apiFetchJson: vi.fn(),
+}));
+
+vi.mock('../backend/http', () => ({
+ absolutizeApiUrl: (url: string) => url,
+ ApiError: class ApiError extends Error {
+ status: number;
+
+ constructor(status: number) {
+ super('API error');
+ this.status = status;
+ }
+ },
+ apiFetchJson: mocks.apiFetchJson,
+}));
+
+const createRequest = (overrides: Partial<EnqueueGenerateRequest> = {}): EnqueueGenerateRequest => ({
+ batchCount: 3,
+ destination: 'gallery',
+ graph: { edges: [], id: 'graph-1', nodes: {} },
+ negativePrompt: 'low quality',
+ negativePromptNodeId: 'negative_prompt',
+ positivePrompt: 'a fjord at dawn',
+ positivePromptNodeId: 'positive_prompt',
+ seed: 10,
+ seedNodeId: 'seed',
+ shouldRandomizeSeed: false,
+ sourceQueueItemId: 'local-1',
+ ...overrides,
+});
+
+const getSubmittedBody = () => {
+ const init = mocks.apiFetchJson.mock.calls[0]?.[1] as RequestInit | undefined;
+
+ expect(init?.body).toEqual(expect.any(String));
+
+ return JSON.parse(init?.body as string) as {
+ batch: {
+ data: { field_name: string; items: unknown[]; node_path: string }[][];
+ runs: number;
+ };
+ };
+};
+
+describe('enqueueGenerateGraph', () => {
+ beforeEach(() => {
+ mocks.apiFetchJson.mockReset();
+ mocks.apiFetchJson.mockResolvedValue({ batch: { batch_id: 'batch-1' }, item_ids: [1, 2, 3] });
+ });
+
+ it('keeps a fixed seed for every run when randomization is disabled', async () => {
+ const { enqueueGenerateGraph } = await import('./api');
+
+ await enqueueGenerateGraph(createRequest({ shouldRandomizeSeed: false }));
+
+ const body = getSubmittedBody();
+
+ expect(body.batch.runs).toBe(3);
+ expect(body.batch.data[0]).toEqual([
+ { field_name: 'value', items: [10], node_path: 'seed' },
+ { field_name: 'value', items: ['a fjord at dawn'], node_path: 'positive_prompt' },
+ { field_name: 'value', items: ['low quality'], node_path: 'negative_prompt' },
+ ]);
+ });
+
+ it('expands seeds per batch item only when randomization is enabled', async () => {
+ const { enqueueGenerateGraph } = await import('./api');
+
+ await enqueueGenerateGraph(createRequest({ shouldRandomizeSeed: true }));
+
+ const body = getSubmittedBody();
+
+ expect(body.batch.runs).toBe(1);
+ expect(body.batch.data[0]).toEqual([
+ { field_name: 'value', items: [10, 11, 12], node_path: 'seed' },
+ {
+ field_name: 'value',
+ items: ['a fjord at dawn', 'a fjord at dawn', 'a fjord at dawn'],
+ node_path: 'positive_prompt',
+ },
+ { field_name: 'value', items: ['low quality', 'low quality', 'low quality'], node_path: 'negative_prompt' },
+ ]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/generation/api.ts b/invokeai/frontend/webv2/src/workbench/generation/api.ts
index 0f2bac6cb0..47edf3708f 100644
--- a/invokeai/frontend/webv2/src/workbench/generation/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/generation/api.ts
@@ -1,6 +1,7 @@
-import { absolutizeApiUrl, apiFetchJson } from '../backend/http';
+import { absolutizeApiUrl, ApiError, apiFetchJson } from '../backend/http';
import { buildQueueItemOrigin } from '../backend/events';
import type { BackendGraphContract } from '../types';
+import { generateSeedSequence } from './graph';
import type { EnqueueGenerateRequest, EnqueueGenerateResult, ImageDTO, MainModelConfig, QueueItemDTO } from './types';
export const listMainModels = async (): Promise<MainModelConfig[]> => {
@@ -10,19 +11,25 @@ export const listMainModels = async (): Promise<MainModelConfig[]> => {
};
export const enqueueGenerateGraph = async (request: EnqueueGenerateRequest): Promise<EnqueueGenerateResult> => {
+ const batchCount = Math.max(1, Math.round(request.batchCount));
+ const seeds = request.shouldRandomizeSeed ? generateSeedSequence(request.seed, batchCount) : [request.seed];
+ const prompts = request.shouldRandomizeSeed ? seeds.map(() => request.positivePrompt) : [request.positivePrompt];
+ const negativePrompts = request.shouldRandomizeSeed
+ ? seeds.map(() => request.negativePrompt)
+ : [request.negativePrompt];
const body = {
batch: {
data: [
[
- { field_name: 'value', items: [request.seed], node_path: request.seedNodeId },
- { field_name: 'value', items: [request.positivePrompt], node_path: request.positivePromptNodeId },
- { field_name: 'value', items: [request.negativePrompt], node_path: request.negativePromptNodeId },
+ { field_name: 'value', items: seeds, node_path: request.seedNodeId },
+ { field_name: 'value', items: prompts, node_path: request.positivePromptNodeId },
+ { field_name: 'value', items: negativePrompts, node_path: request.negativePromptNodeId },
],
],
destination: request.destination,
graph: request.graph satisfies BackendGraphContract,
origin: buildQueueItemOrigin(request.sourceQueueItemId),
- runs: request.batchCount,
+ runs: request.shouldRandomizeSeed ? 1 : batchCount,
},
prepend: false,
};
@@ -40,26 +47,38 @@ export const getQueueItem = (itemId: number): Promise<QueueItemDTO> =>
export const listAllQueueItems = (): Promise<QueueItemDTO[]> =>
apiFetchJson<QueueItemDTO[]>('/api/v1/queue/default/list_all');
-const getImageDTO = async (imageName: string, queuedAt: string, sourceQueueItemId: string): Promise<ImageDTO> => {
- const body = await apiFetchJson<{
- image_name: string;
- image_url: string;
- thumbnail_url: string;
- width: number;
- height: number;
- is_intermediate: boolean;
- }>(`/api/v1/images/i/${encodeURIComponent(imageName)}`);
-
- return {
- height: body.height,
- imageName: body.image_name,
- imageUrl: absolutizeApiUrl(body.image_url),
- isIntermediate: body.is_intermediate,
- queuedAt,
- sourceQueueItemId,
- thumbnailUrl: absolutizeApiUrl(body.thumbnail_url),
- width: body.width,
- };
+const getImageDTO = async (
+ imageName: string,
+ queuedAt: string,
+ sourceQueueItemId: string
+): Promise<ImageDTO | null> => {
+ try {
+ const body = await apiFetchJson<{
+ image_name: string;
+ image_url: string;
+ thumbnail_url: string;
+ width: number;
+ height: number;
+ is_intermediate: boolean;
+ }>(`/api/v1/images/i/${encodeURIComponent(imageName)}`);
+
+ return {
+ height: body.height,
+ imageName: body.image_name,
+ imageUrl: absolutizeApiUrl(body.image_url),
+ isIntermediate: body.is_intermediate,
+ queuedAt,
+ sourceQueueItemId,
+ thumbnailUrl: absolutizeApiUrl(body.thumbnail_url),
+ width: body.width,
+ };
+ } catch (error) {
+ if (error instanceof ApiError && error.status === 404) {
+ return null;
+ }
+
+ throw error;
+ }
};
const getResultImageNames = (queueItem: QueueItemDTO): string[] => {
@@ -87,9 +106,11 @@ export const getQueueItemResultImages = async (
): Promise<ImageDTO[]> => {
const queueItem = await getQueueItem(itemId);
- return Promise.all(
+ const images = await Promise.all(
getResultImageNames(queueItem).map((imageName) => getImageDTO(imageName, queuedAt, sourceQueueItemId))
);
+
+ return images.filter((image): image is ImageDTO => image !== null);
};
export const cancelQueueItemsByBatchIds = async (batchIds: string[]): Promise<void> => {
diff --git a/invokeai/frontend/webv2/src/workbench/generation/graph.test.ts b/invokeai/frontend/webv2/src/workbench/generation/graph.test.ts
new file mode 100644
index 0000000000..3375a4a4b0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/generation/graph.test.ts
@@ -0,0 +1,87 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { compileGenerateGraph, generateSeedSequence, getDefaultGenerateSettings, resolveGenerateSeed } from './graph';
+import type { GenerateSettings, MainModelConfig, VaeModelConfig } from './types';
+
+const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };
+const sdxlModel: MainModelConfig = { base: 'sdxl', key: 'sdxl-model', name: 'SDXL', type: 'main' };
+const vae: VaeModelConfig = { base: 'sd-1', key: 'vae-model', name: 'Custom VAE', type: 'vae' };
+
+const createSettings = (model: MainModelConfig, overrides: Partial<GenerateSettings> = {}): GenerateSettings => ({
+ ...getDefaultGenerateSettings(model),
+ seed: 1,
+ shouldRandomizeSeed: false,
+ ...overrides,
+});
+
+const compile = (model: MainModelConfig, overrides: Partial<GenerateSettings> = {}) =>
+ compileGenerateGraph(createSettings(model, overrides), model, 'gallery', { useCpuNoise: true }).backendGraph;
+
+const getEdge = (graph: ReturnType<typeof compile>, targetNodeId: string, targetField: string) =>
+ graph.edges.find((edge) => edge.destination.node_id === targetNodeId && edge.destination.field === targetField);
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('compileGenerateGraph', () => {
+ it('builds a plain txt2img graph without optional nodes', () => {
+ const graph = compile(sd1Model);
+
+ expect(graph.nodes.seamless).toBeUndefined();
+ expect(graph.nodes.vae_loader).toBeUndefined();
+ expect(getEdge(graph, 'denoise_latents', 'unet')?.source.node_id).toBe('model_loader');
+ expect(getEdge(graph, 'canvas_output', 'vae')?.source.node_id).toBe('model_loader');
+ expect(graph.nodes.canvas_output?.fp32).toBe(true);
+ });
+
+ it('wires CLIP skip into the SD1 conditioning chain', () => {
+ const graph = compile(sd1Model, { clipSkip: 2 });
+
+ expect(graph.nodes.clip_skip?.skipped_layers).toBe(2);
+ });
+
+ it('routes the UNet and VAE through the seamless node when tiling is enabled', () => {
+ const graph = compile(sd1Model, { seamlessXAxis: true, vae });
+
+ expect(graph.nodes.seamless?.seamless_x).toBe(true);
+ expect(graph.nodes.seamless?.seamless_y).toBe(false);
+ expect(graph.nodes.vae_loader?.vae_model).toEqual(vae);
+ expect(getEdge(graph, 'seamless', 'unet')?.source.node_id).toBe('model_loader');
+ expect(getEdge(graph, 'seamless', 'vae')?.source.node_id).toBe('vae_loader');
+ expect(getEdge(graph, 'denoise_latents', 'unet')?.source.node_id).toBe('seamless');
+ expect(getEdge(graph, 'canvas_output', 'vae')?.source.node_id).toBe('seamless');
+ });
+
+ it('uses a VAE override only when it matches the model base', () => {
+ const matching = compile(sd1Model, { vae, vaePrecision: 'fp16' });
+
+ expect(getEdge(matching, 'canvas_output', 'vae')?.source.node_id).toBe('vae_loader');
+ expect(matching.nodes.canvas_output?.fp32).toBe(false);
+
+ const mismatched = compile(sdxlModel, { vae });
+
+ expect(mismatched.nodes.vae_loader).toBeUndefined();
+ expect(getEdge(mismatched, 'canvas_output', 'vae')?.source.node_id).toBe('model_loader');
+ });
+});
+
+describe('generate seeds', () => {
+ it('keeps an explicit seed when randomization is disabled', () => {
+ const settings = createSettings(sdxlModel, { seed: 123, shouldRandomizeSeed: false });
+
+ expect(resolveGenerateSeed(settings)).toBe(123);
+ });
+
+ it('resolves a random seed when randomization is enabled', () => {
+ vi.spyOn(Math, 'random').mockReturnValue(0.5);
+
+ const settings = createSettings(sdxlModel, { seed: 123, shouldRandomizeSeed: true });
+
+ expect(resolveGenerateSeed(settings)).toBe(2147483647);
+ });
+
+ it('builds the legacy-style sequential seed batch starting from the resolved seed', () => {
+ expect(generateSeedSequence(10, 4)).toEqual([10, 11, 12, 13]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/generation/graph.ts b/invokeai/frontend/webv2/src/workbench/generation/graph.ts
index 6244b197ae..733887219c 100644
--- a/invokeai/frontend/webv2/src/workbench/generation/graph.ts
+++ b/invokeai/frontend/webv2/src/workbench/generation/graph.ts
@@ -5,6 +5,7 @@ import type {
ProjectSettings,
ResultDestination,
} from '../types';
+import { clampDimension, deriveAspectRatioId, getOptimalDimension, SEED_MAX } from './settings';
import type { CompiledGenerateGraph, GenerateSettings, MainModelConfig, SupportedGenerateBase } from './types';
const now = (): string => new Date().toISOString();
@@ -15,29 +16,38 @@ const createId = (prefix: string): string =>
const getNumber = (value: number | null | undefined, fallback: number): number =>
Number.isFinite(value) && value !== null && value !== undefined ? value : fallback;
-const clampDimension = (value: number): number => Math.max(64, Math.round(value / 8) * 8);
-
-export const isSupportedGenerateModel = (
- model: MainModelConfig
-): model is MainModelConfig & { base: SupportedGenerateBase } =>
+export const isSupportedGenerateModel = <T extends { base: string; type: string }>(
+ model: T
+): model is T & { base: SupportedGenerateBase; type: 'main' } =>
model.type === 'main' && (model.base === 'sdxl' || model.base === 'sd-1' || model.base === 'sd-2');
export const getDefaultGenerateSettings = (model?: MainModelConfig): GenerateSettings => {
const defaults = model?.default_settings;
+ const optimalDimension = getOptimalDimension(model?.base ?? 'sdxl');
+ const width = clampDimension(getNumber(defaults?.width, optimalDimension));
+ const height = clampDimension(getNumber(defaults?.height, optimalDimension));
return {
+ aspectRatioId: deriveAspectRatioId(width, height),
+ aspectRatioIsLocked: false,
+ aspectRatioValue: height > 0 ? width / height : 1,
batchCount: 1,
cfgRescaleMultiplier: getNumber(defaults?.cfg_rescale_multiplier, 0),
cfgScale: getNumber(defaults?.cfg_scale, 7),
- height: clampDimension(getNumber(defaults?.height, 1024)),
+ clipSkip: 0,
+ height,
modelKey: model?.key ?? '',
negativePrompt: '',
positivePrompt: '',
scheduler: defaults?.scheduler ?? 'euler_a',
- seed: Math.floor(Math.random() * 4_294_967_295),
+ seamlessXAxis: false,
+ seamlessYAxis: false,
+ seed: Math.floor(Math.random() * SEED_MAX),
shouldRandomizeSeed: true,
steps: Math.max(1, Math.round(getNumber(defaults?.steps, 30))),
- width: clampDimension(getNumber(defaults?.width, 1024)),
+ vae: null,
+ vaePrecision: defaults?.vae_precision === 'fp16' ? 'fp16' : 'fp32',
+ width,
};
};
@@ -46,12 +56,18 @@ export const getSettingsWithModelDefaults = (settings: GenerateSettings, model:
return {
...settings,
+ aspectRatioId: modelDefaults.aspectRatioId,
+ aspectRatioIsLocked: false,
+ aspectRatioValue: modelDefaults.aspectRatioValue,
cfgRescaleMultiplier: modelDefaults.cfgRescaleMultiplier,
cfgScale: modelDefaults.cfgScale,
height: modelDefaults.height,
modelKey: model.key,
scheduler: modelDefaults.scheduler,
steps: modelDefaults.steps,
+ // VAE overrides are base-specific; the widget re-resolves the model's default VAE after a switch.
+ vae: null,
+ vaePrecision: modelDefaults.vaePrecision,
width: modelDefaults.width,
};
};
@@ -99,9 +115,13 @@ const addMetadata = (
model,
rand_device: projectSettings.useCpuNoise ? 'cpu' : 'cuda',
scheduler: settings.scheduler,
+ seamless_x: settings.seamlessXAxis,
+ seamless_y: settings.seamlessYAxis,
steps: settings.steps,
type: 'core_metadata',
+ vae: settings.vae ?? undefined,
width: settings.width,
+ ...(model.base === 'sdxl' ? {} : { clip_skip: settings.clipSkip }),
});
addEdge(graph, graph.nodes.seed, 'value', metadata, 'seed');
@@ -146,12 +166,26 @@ const buildSDGraph = (
type: 'denoise_latents',
});
const output = addNode(graph, {
- fp32: false,
+ fp32: settings.vaePrecision === 'fp32',
id: 'canvas_output',
is_intermediate: outputIsIntermediate,
type: 'l2i',
use_cache: false,
});
+ // A VAE override only applies when it matches the main model's architecture.
+ const vaeLoader =
+ settings.vae && settings.vae.base === model.base
+ ? addNode(graph, { id: 'vae_loader', type: 'vae_loader', vae_model: settings.vae })
+ : null;
+ const seamless =
+ settings.seamlessXAxis || settings.seamlessYAxis
+ ? addNode(graph, {
+ id: 'seamless',
+ seamless_x: settings.seamlessXAxis,
+ seamless_y: settings.seamlessYAxis,
+ type: 'seamless',
+ })
+ : null;
if (model.base === 'sdxl') {
addEdge(graph, modelLoader, 'clip', posCond, 'clip');
@@ -163,7 +197,7 @@ const buildSDGraph = (
addEdge(graph, negativePrompt, 'value', negCond, 'prompt');
addEdge(graph, negativePrompt, 'value', negCond, 'style');
} else {
- const clipSkip = addNode(graph, { id: 'clip_skip', skipped_layers: 0, type: 'clip_skip' });
+ const clipSkip = addNode(graph, { id: 'clip_skip', skipped_layers: settings.clipSkip, type: 'clip_skip' });
addEdge(graph, modelLoader, 'clip', clipSkip, 'clip');
addEdge(graph, clipSkip, 'clip', posCond, 'clip');
@@ -177,10 +211,20 @@ const buildSDGraph = (
addEdge(graph, negCond, 'conditioning', negCondCollect, 'item');
addEdge(graph, negCondCollect, 'collection', denoise, 'negative_conditioning');
addEdge(graph, seed, 'value', noise, 'seed');
- addEdge(graph, modelLoader, 'unet', denoise, 'unet');
+
+ // Seamless slots in between the model loader and the denoise/decode nodes,
+ // patching both the UNet and the (possibly overridden) VAE.
+ if (seamless) {
+ addEdge(graph, modelLoader, 'unet', seamless, 'unet');
+ addEdge(graph, vaeLoader ?? modelLoader, 'vae', seamless, 'vae');
+ addEdge(graph, seamless, 'unet', denoise, 'unet');
+ } else {
+ addEdge(graph, modelLoader, 'unet', denoise, 'unet');
+ }
+
addEdge(graph, noise, 'noise', denoise, 'noise');
addEdge(graph, denoise, 'latents', output, 'latents');
- addEdge(graph, modelLoader, 'vae', output, 'vae');
+ addEdge(graph, seamless ?? vaeLoader ?? modelLoader, 'vae', output, 'vae');
addMetadata(graph, output, settings, model, model.base === 'sdxl' ? 'sdxl_txt2img' : 'txt2img', projectSettings);
return graph;
@@ -224,4 +268,15 @@ export const compileGenerateGraph = (
};
export const resolveGenerateSeed = (settings: GenerateSettings): number =>
- settings.shouldRandomizeSeed ? Math.floor(Math.random() * 4_294_967_295) : settings.seed;
+ settings.shouldRandomizeSeed ? Math.floor(Math.random() * SEED_MAX) : settings.seed;
+
+export const generateSeedSequence = (start: number, count: number): number[] => {
+ const seedCount = Math.max(1, Math.round(count));
+ const seeds: number[] = [];
+
+ for (let index = 0; index < seedCount; index += 1) {
+ seeds.push((start + index) % SEED_MAX);
+ }
+
+ return seeds;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/generation/settings.test.ts b/invokeai/frontend/webv2/src/workbench/generation/settings.test.ts
new file mode 100644
index 0000000000..99a21b2adc
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/generation/settings.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from 'vitest';
+
+import { calculateNewSize, deriveAspectRatioId, isGenerateSettings, normalizeGenerateSettings } from './settings';
+
+/** The persisted widget-value shape from before aspect ratio / VAE / seamless / CLIP skip landed. */
+const legacyStoredValues = {
+ batchCount: 2,
+ cfgRescaleMultiplier: 0,
+ cfgScale: 7,
+ height: 768,
+ modelKey: 'legacy-model',
+ negativePrompt: 'blurry',
+ positivePrompt: 'a castle',
+ scheduler: 'euler_a',
+ seed: 123,
+ shouldRandomizeSeed: false,
+ steps: 30,
+ width: 512,
+};
+
+describe('normalizeGenerateSettings', () => {
+ it('upgrades legacy persisted values without losing the core fields', () => {
+ const normalized = normalizeGenerateSettings(legacyStoredValues);
+
+ expect(normalized).not.toBeNull();
+ expect(normalized?.positivePrompt).toBe('a castle');
+ expect(normalized?.width).toBe(512);
+ expect(normalized?.height).toBe(768);
+ expect(normalized?.aspectRatioId).toBe('2:3');
+ expect(normalized?.aspectRatioIsLocked).toBe(false);
+ expect(normalized?.clipSkip).toBe(0);
+ expect(normalized?.seamlessXAxis).toBe(false);
+ expect(normalized?.vae).toBeNull();
+ expect(normalized?.vaePrecision).toBe('fp32');
+ expect(normalized && isGenerateSettings(normalized)).toBe(true);
+ });
+
+ it('rejects values missing core fields', () => {
+ expect(normalizeGenerateSettings({})).toBeNull();
+ expect(normalizeGenerateSettings({ ...legacyStoredValues, seed: Number.NaN })).toBeNull();
+ expect(normalizeGenerateSettings({ ...legacyStoredValues, positivePrompt: undefined })).toBeNull();
+ expect(normalizeGenerateSettings(null)).toBeNull();
+ });
+
+ it('drops malformed values for the newer fields back to defaults', () => {
+ const normalized = normalizeGenerateSettings({
+ ...legacyStoredValues,
+ aspectRatioId: 'bogus',
+ vae: { key: 'k', name: 'n', type: 'main' },
+ vaePrecision: 'fp64',
+ });
+
+ expect(normalized?.aspectRatioId).toBe('2:3');
+ expect(normalized?.vae).toBeNull();
+ expect(normalized?.vaePrecision).toBe('fp32');
+ });
+});
+
+describe('dimension helpers', () => {
+ it('derives the closest preset aspect ratio', () => {
+ expect(deriveAspectRatioId(1024, 1024)).toBe('1:1');
+ expect(deriveAspectRatioId(1536, 1024)).toBe('3:2');
+ expect(deriveAspectRatioId(1000, 770)).toBe('Free');
+ });
+
+ it('fits a ratio into a pixel area on the dimension grid', () => {
+ const { height, width } = calculateNewSize(1, 1024 * 1024);
+
+ expect(width).toBe(1024);
+ expect(height).toBe(1024);
+
+ const wide = calculateNewSize(16 / 9, 1024 * 1024);
+
+ expect(wide.width % 8).toBe(0);
+ expect(wide.height % 8).toBe(0);
+ expect(wide.width / wide.height).toBeCloseTo(16 / 9, 1);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/generation/settings.ts b/invokeai/frontend/webv2/src/workbench/generation/settings.ts
new file mode 100644
index 0000000000..8b2138c0ab
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/generation/settings.ts
@@ -0,0 +1,229 @@
+import type {
+ AspectRatioId,
+ GenerateSettings,
+ GenerateWidgetValues,
+ MainModelConfig,
+ SupportedGenerateBase,
+ VaeModelConfig,
+ VaePrecision,
+} from './types';
+
+/** Schedulers accepted by the backend `denoise_latents` invocation. */
+export const SCHEDULER_OPTIONS: { value: string; label: string }[] = [
+ { label: 'DDIM', value: 'ddim' },
+ { label: 'DDPM', value: 'ddpm' },
+ { label: 'DEIS', value: 'deis' },
+ { label: 'DEIS Karras', value: 'deis_k' },
+ { label: 'DPM++ 2S', value: 'dpmpp_2s' },
+ { label: 'DPM++ 2S Karras', value: 'dpmpp_2s_k' },
+ { label: 'DPM++ 2M', value: 'dpmpp_2m' },
+ { label: 'DPM++ 2M Karras', value: 'dpmpp_2m_k' },
+ { label: 'DPM++ 2M SDE', value: 'dpmpp_2m_sde' },
+ { label: 'DPM++ 2M SDE Karras', value: 'dpmpp_2m_sde_k' },
+ { label: 'DPM++ 3M', value: 'dpmpp_3m' },
+ { label: 'DPM++ 3M Karras', value: 'dpmpp_3m_k' },
+ { label: 'DPM++ SDE', value: 'dpmpp_sde' },
+ { label: 'DPM++ SDE Karras', value: 'dpmpp_sde_k' },
+ { label: 'ER-SDE', value: 'er_sde' },
+ { label: 'Euler', value: 'euler' },
+ { label: 'Euler Karras', value: 'euler_k' },
+ { label: 'Euler Ancestral', value: 'euler_a' },
+ { label: 'Heun', value: 'heun' },
+ { label: 'Heun Karras', value: 'heun_k' },
+ { label: 'KDPM 2', value: 'kdpm_2' },
+ { label: 'KDPM 2 Karras', value: 'kdpm_2_k' },
+ { label: 'KDPM 2 Ancestral', value: 'kdpm_2_a' },
+ { label: 'KDPM 2 Ancestral Karras', value: 'kdpm_2_a_k' },
+ { label: 'LCM', value: 'lcm' },
+ { label: 'LMS', value: 'lms' },
+ { label: 'LMS Karras', value: 'lms_k' },
+ { label: 'PNDM', value: 'pndm' },
+ { label: 'TCD', value: 'tcd' },
+ { label: 'UniPC', value: 'unipc' },
+ { label: 'UniPC Karras', value: 'unipc_k' },
+];
+
+const KNOWN_SCHEDULERS = new Set(SCHEDULER_OPTIONS.map((option) => option.value));
+
+export const isKnownScheduler = (value: string): boolean => KNOWN_SCHEDULERS.has(value);
+
+/** Preset ratios, with the preset to switch to when dimensions are swapped. */
+export const ASPECT_RATIO_MAP: Record<Exclude<AspectRatioId, 'Free'>, { ratio: number; inverseId: AspectRatioId }> = {
+ '8:1': { inverseId: '1:8', ratio: 8 / 1 },
+ '4:1': { inverseId: '1:4', ratio: 4 / 1 },
+ '21:9': { inverseId: '9:21', ratio: 21 / 9 },
+ '16:9': { inverseId: '9:16', ratio: 16 / 9 },
+ '3:2': { inverseId: '2:3', ratio: 3 / 2 },
+ '5:4': { inverseId: '4:5', ratio: 5 / 4 },
+ '4:3': { inverseId: '3:4', ratio: 4 / 3 },
+ '1:1': { inverseId: '1:1', ratio: 1 },
+ '3:4': { inverseId: '4:3', ratio: 3 / 4 },
+ '4:5': { inverseId: '5:4', ratio: 4 / 5 },
+ '2:3': { inverseId: '3:2', ratio: 2 / 3 },
+ '9:16': { inverseId: '16:9', ratio: 9 / 16 },
+ '1:4': { inverseId: '4:1', ratio: 1 / 4 },
+ '9:21': { inverseId: '21:9', ratio: 9 / 21 },
+ '1:8': { inverseId: '8:1', ratio: 1 / 8 },
+};
+
+export const ASPECT_RATIO_OPTIONS: AspectRatioId[] = [
+ 'Free',
+ '21:9',
+ '16:9',
+ '3:2',
+ '4:3',
+ '1:1',
+ '3:4',
+ '2:3',
+ '9:16',
+ '9:21',
+];
+
+export const isAspectRatioId = (value: unknown): value is AspectRatioId =>
+ value === 'Free' || (typeof value === 'string' && value in ASPECT_RATIO_MAP);
+
+/** SD-family models generate at multiples of 8 pixels. */
+export const DIMENSION_GRID = 8;
+export const MIN_DIMENSION = 64;
+export const MAX_DIMENSION = 4096;
+
+export const SEED_MAX = 4_294_967_295;
+
+/** Max skippable CLIP layers per base (mirrors the legacy CLIP_SKIP map). */
+export const CLIP_SKIP_MAX: Record<SupportedGenerateBase, number> = {
+ 'sd-1': 12,
+ 'sd-2': 24,
+ sdxl: 24,
+};
+
+export const getOptimalDimension = (base: string): number => (base === 'sd-1' || base === 'sd-2' ? 512 : 1024);
+
+export const clampDimension = (value: number): number =>
+ Math.min(MAX_DIMENSION, Math.max(MIN_DIMENSION, Math.round(value / DIMENSION_GRID) * DIMENSION_GRID));
+
+/** Fit a width/height of the given ratio into approximately the given pixel area, snapped to the grid. */
+export const calculateNewSize = (ratio: number, area: number): { width: number; height: number } => {
+ const exactWidth = Math.sqrt(area * ratio);
+
+ return { height: clampDimension(exactWidth / ratio), width: clampDimension(exactWidth) };
+};
+
+/** Best-matching preset for existing dimensions, falling back to Free. */
+export const deriveAspectRatioId = (width: number, height: number): AspectRatioId => {
+ if (height <= 0) {
+ return 'Free';
+ }
+
+ const ratio = width / height;
+
+ for (const [id, entry] of Object.entries(ASPECT_RATIO_MAP)) {
+ if (Math.abs(entry.ratio - ratio) < 0.0001) {
+ return id as AspectRatioId;
+ }
+ }
+
+ return 'Free';
+};
+
+const isRecord = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object';
+
+const hasFiniteNumber = (record: Record<string, unknown>, key: string): boolean =>
+ typeof record[key] === 'number' && Number.isFinite(record[key]);
+
+export const isMainModelConfig = (value: unknown): value is MainModelConfig =>
+ isRecord(value) && typeof value.key === 'string' && typeof value.name === 'string' && value.type === 'main';
+
+export const isVaeModelConfig = (value: unknown): value is VaeModelConfig =>
+ isRecord(value) && typeof value.key === 'string' && typeof value.name === 'string' && value.type === 'vae';
+
+const isVaePrecision = (value: unknown): value is VaePrecision => value === 'fp16' || value === 'fp32';
+
+/**
+ * Validate stored widget values and fill in fields that older persisted
+ * projects predate. The core fields must be present and well-typed; newer
+ * fields fall back to their defaults so old projects keep their prompts and
+ * dimensions instead of being reset wholesale.
+ */
+export const normalizeGenerateSettings = (values: unknown): GenerateSettings | null => {
+ if (!isRecord(values)) {
+ return null;
+ }
+
+ const isCoreShapeValid =
+ typeof values.modelKey === 'string' &&
+ typeof values.positivePrompt === 'string' &&
+ typeof values.negativePrompt === 'string' &&
+ typeof values.scheduler === 'string' &&
+ typeof values.shouldRandomizeSeed === 'boolean' &&
+ ['batchCount', 'width', 'height', 'steps', 'cfgScale', 'cfgRescaleMultiplier', 'seed'].every((key) =>
+ hasFiniteNumber(values, key)
+ );
+
+ if (!isCoreShapeValid) {
+ return null;
+ }
+
+ const width = values.width as number;
+ const height = values.height as number;
+
+ return {
+ aspectRatioId: isAspectRatioId(values.aspectRatioId) ? values.aspectRatioId : deriveAspectRatioId(width, height),
+ aspectRatioIsLocked: typeof values.aspectRatioIsLocked === 'boolean' ? values.aspectRatioIsLocked : false,
+ aspectRatioValue:
+ hasFiniteNumber(values, 'aspectRatioValue') && (values.aspectRatioValue as number) > 0
+ ? (values.aspectRatioValue as number)
+ : height > 0
+ ? width / height
+ : 1,
+ batchCount: values.batchCount as number,
+ cfgRescaleMultiplier: values.cfgRescaleMultiplier as number,
+ cfgScale: values.cfgScale as number,
+ clipSkip: hasFiniteNumber(values, 'clipSkip') ? (values.clipSkip as number) : 0,
+ height,
+ modelKey: values.modelKey as string,
+ negativePrompt: values.negativePrompt as string,
+ positivePrompt: values.positivePrompt as string,
+ scheduler: values.scheduler as string,
+ seamlessXAxis: typeof values.seamlessXAxis === 'boolean' ? values.seamlessXAxis : false,
+ seamlessYAxis: typeof values.seamlessYAxis === 'boolean' ? values.seamlessYAxis : false,
+ seed: values.seed as number,
+ shouldRandomizeSeed: values.shouldRandomizeSeed as boolean,
+ steps: values.steps as number,
+ vae: isVaeModelConfig(values.vae) ? values.vae : null,
+ vaePrecision: isVaePrecision(values.vaePrecision) ? values.vaePrecision : 'fp32',
+ width,
+ };
+};
+
+export const normalizeGenerateWidgetValues = (values: unknown): GenerateWidgetValues | null => {
+ const settings = normalizeGenerateSettings(values);
+
+ if (!settings || !isRecord(values) || !isMainModelConfig(values.model)) {
+ return null;
+ }
+
+ return { ...settings, model: values.model };
+};
+
+export const isGenerateSettings = (values: unknown): values is GenerateSettings => {
+ const normalized = normalizeGenerateSettings(values);
+
+ if (!normalized || !isRecord(values)) {
+ return false;
+ }
+
+ // Strict only over the keys normalize would have to invent.
+ return (
+ isAspectRatioId(values.aspectRatioId) &&
+ typeof values.aspectRatioIsLocked === 'boolean' &&
+ hasFiniteNumber(values, 'aspectRatioValue') &&
+ hasFiniteNumber(values, 'clipSkip') &&
+ typeof values.seamlessXAxis === 'boolean' &&
+ typeof values.seamlessYAxis === 'boolean' &&
+ isVaePrecision(values.vaePrecision) &&
+ (values.vae === null || isVaeModelConfig(values.vae))
+ );
+};
+
+export const isGenerateWidgetValues = (values: unknown): values is GenerateWidgetValues =>
+ isGenerateSettings(values) && isMainModelConfig((values as unknown as Record<string, unknown>).model);
diff --git a/invokeai/frontend/webv2/src/workbench/generation/types.ts b/invokeai/frontend/webv2/src/workbench/generation/types.ts
index e4a381a399..1c9c976d82 100644
--- a/invokeai/frontend/webv2/src/workbench/generation/types.ts
+++ b/invokeai/frontend/webv2/src/workbench/generation/types.ts
@@ -15,11 +15,40 @@ export type MainModelConfig = {
cfg_rescale_multiplier?: number | null;
width?: number | null;
height?: number | null;
+ vae?: string | null;
vae_precision?: string | null;
} | null;
[key: string]: unknown;
};
+export type VaeModelConfig = {
+ key: string;
+ name: string;
+ base: string;
+ type: 'vae';
+ [key: string]: unknown;
+};
+
+export type VaePrecision = 'fp16' | 'fp32';
+
+export type AspectRatioId =
+ | 'Free'
+ | '8:1'
+ | '4:1'
+ | '21:9'
+ | '16:9'
+ | '3:2'
+ | '5:4'
+ | '4:3'
+ | '1:1'
+ | '3:4'
+ | '4:5'
+ | '2:3'
+ | '9:16'
+ | '1:4'
+ | '9:21'
+ | '1:8';
+
export interface GenerateSettings {
batchCount: number;
modelKey: string;
@@ -27,12 +56,22 @@ export interface GenerateSettings {
negativePrompt: string;
width: number;
height: number;
+ aspectRatioId: AspectRatioId;
+ /** width / height ratio enforced while locked. Tracks the preset, or the captured ratio in Free mode. */
+ aspectRatioValue: number;
+ aspectRatioIsLocked: boolean;
steps: number;
cfgScale: number;
cfgRescaleMultiplier: number;
scheduler: string;
+ clipSkip: number;
seed: number;
shouldRandomizeSeed: boolean;
+ seamlessXAxis: boolean;
+ seamlessYAxis: boolean;
+ /** Optional VAE override; null uses the VAE bundled with the main model. */
+ vae: VaeModelConfig | null;
+ vaePrecision: VaePrecision;
}
export interface GenerateWidgetValues extends GenerateSettings {
@@ -75,6 +114,7 @@ export interface EnqueueGenerateRequest {
positivePromptNodeId: string;
seed: number;
seedNodeId: string;
+ shouldRandomizeSeed: boolean;
sourceQueueItemId: string;
}
diff --git a/invokeai/frontend/webv2/src/workbench/queueSummary.test.ts b/invokeai/frontend/webv2/src/workbench/queueSummary.test.ts
index 59d9d4d17f..9a2c7addfe 100644
--- a/invokeai/frontend/webv2/src/workbench/queueSummary.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/queueSummary.test.ts
@@ -22,7 +22,7 @@ const createQueueItem = ({
id,
snapshot: {
canvas: {
- document: { height: 1024, layers: [], width: 1024 },
+ document: { height: 1024, layers: [], version: 1, width: 1024 },
stagingArea: {
areThumbnailsVisible: false,
isVisible: false,
@@ -38,7 +38,7 @@ const createQueueItem = ({
submittedAt,
widgetStates: {
generate: { id: 'generate', label: 'Generate', values: { batchCount }, version: 1 },
- } as QueueItem['snapshot']['widgetStates'],
+ } as unknown as QueueItem['snapshot']['widgetStates'],
},
status,
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateAdvancedFields.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateAdvancedFields.tsx
new file mode 100644
index 0000000000..32ccb83fe9
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateAdvancedFields.tsx
@@ -0,0 +1,140 @@
+import { Badge, HStack, Input, NativeSelect, Switch, Text } from '@chakra-ui/react';
+import type { ChangeEvent } from 'react';
+
+import { Field } from '../../components/ui/Field';
+import { ModelSelect } from '../../components/ModelSelect';
+import { CLIP_SKIP_MAX, isVaeModelConfig } from '../../generation/settings';
+import type { GenerateSettings, MainModelConfig, VaePrecision } from '../../generation/types';
+import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';
+
+interface GenerateAdvancedFieldsProps {
+ settings: GenerateSettings;
+ selectedModel: MainModelConfig | undefined;
+ onCommit: (patch: Partial<GenerateSettings>) => void;
+}
+
+const SeamlessSwitch = ({
+ checked,
+ label,
+ onCheckedChange,
+}: {
+ checked: boolean;
+ label: string;
+ onCheckedChange: (checked: boolean) => void;
+}) => (
+ <Switch.Root checked={checked} flex="1" size="sm" onCheckedChange={(event) => onCheckedChange(event.checked)}>
+ <Switch.HiddenInput />
+ <Switch.Control _checked={{ bg: 'accent.solid' }}>
+ <Switch.Thumb />
+ </Switch.Control>
+ <Switch.Label fontSize="xs">{label}</Switch.Label>
+ </Switch.Root>
+);
+
+export const GenerateAdvancedFields = ({ onCommit, selectedModel, settings }: GenerateAdvancedFieldsProps) => {
+ const modelBase = selectedModel?.base;
+ // CLIP skip and CFG rescale target the SD1/SD2 text encoder; SDXL conditioning does not use them.
+ const supportsClipSkip = modelBase === 'sd-1' || modelBase === 'sd-2';
+ const clipSkipMax = supportsClipSkip ? CLIP_SKIP_MAX[modelBase] : 0;
+
+ const updateNumber =
+ (key: 'cfgRescaleMultiplier' | 'clipSkip', max: number) => (event: ChangeEvent<HTMLInputElement>) => {
+ const value = Number(event.currentTarget.value);
+
+ if (!Number.isFinite(value)) {
+ return;
+ }
+
+ onCommit({ [key]: Math.min(max, Math.max(0, value)) });
+ };
+
+ const customVae = Boolean(settings.vae?.key);
+
+ const badges = (
+ <>
+ {settings.seamlessXAxis && <Badge size="xs">Tile X</Badge>}
+ {settings.seamlessYAxis && <Badge size="xs">Tile Y</Badge>}
+ {customVae && (
+ <Badge maxW="32" size="xs" truncate>
+ {settings.vae?.name}
+ </Badge>
+ )}
+ </>
+ );
+
+ return (
+ <GenerateCollapsibleSection label="Advanced" defaultOpen={false} badges={badges}>
+ <HStack alignItems="flex-start" gap="2" p="2">
+ <Field flex="2" label="VAE" helpText={settings.vae ? undefined : 'Using the VAE bundled with the model.'}>
+ <ModelSelect
+ filter={(model) => model.base === modelBase}
+ modelTypes={['vae']}
+ size="xs"
+ placeholder="Model default"
+ value={settings.vae?.key ?? null}
+ onChange={(model) => onCommit({ vae: isVaeModelConfig(model) ? model : null })}
+ />
+ </Field>
+ <Field flex="1" label="VAE precision">
+ <NativeSelect.Root size="xs">
+ <NativeSelect.Field
+ aria-label="VAE precision"
+ value={settings.vaePrecision}
+ onChange={(event: ChangeEvent<HTMLSelectElement>) =>
+ onCommit({ vaePrecision: event.currentTarget.value as VaePrecision })
+ }
+ >
+ <option value="fp16">FP16</option>
+ <option value="fp32">FP32</option>
+ </NativeSelect.Field>
+ <NativeSelect.Indicator />
+ </NativeSelect.Root>
+ </Field>
+ </HStack>
+
+ {supportsClipSkip ? (
+ <HStack gap="2" p="2">
+ <Field label="CLIP skip">
+ <Input
+ max={String(clipSkipMax)}
+ min="0"
+ size="xs"
+ type="number"
+ value={settings.clipSkip}
+ onChange={updateNumber('clipSkip', clipSkipMax)}
+ />
+ </Field>
+ <Field label="CFG rescale">
+ <Input
+ max="0.99"
+ min="0"
+ size="xs"
+ step="0.05"
+ type="number"
+ value={settings.cfgRescaleMultiplier}
+ onChange={updateNumber('cfgRescaleMultiplier', 0.99)}
+ />
+ </Field>
+ </HStack>
+ ) : null}
+
+ <Field label="Seamless tiling" p="2">
+ <HStack gap="4">
+ <SeamlessSwitch
+ checked={settings.seamlessXAxis}
+ label="X axis"
+ onCheckedChange={(checked) => onCommit({ seamlessXAxis: checked })}
+ />
+ <SeamlessSwitch
+ checked={settings.seamlessYAxis}
+ label="Y axis"
+ onCheckedChange={(checked) => onCommit({ seamlessYAxis: checked })}
+ />
+ </HStack>
+ </Field>
+ <Text color="fg.subtle" fontSize="2xs" p="2">
+ LoRAs, reference images, and the SDXL refiner are not wired into the Generate graph yet.
+ </Text>
+ </GenerateCollapsibleSection>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateDimensionFields.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateDimensionFields.tsx
new file mode 100644
index 0000000000..651dc2020a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateDimensionFields.tsx
@@ -0,0 +1,415 @@
+import {
+ Badge,
+ Box,
+ createListCollection,
+ HStack,
+ Icon,
+ InputGroup,
+ NumberInput,
+ Portal,
+ Select,
+ Stack,
+ Text,
+} from '@chakra-ui/react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { ArrowLeftRightIcon, LockIcon, LockOpenIcon, RulerDimensionLineIcon, ScalingIcon } from 'lucide-react';
+
+import { IconButton } from '../../components/ui/Button';
+import { Field } from '../../components/ui/Field';
+import { Tooltip } from '../../components/ui/Tooltip';
+import {
+ ASPECT_RATIO_MAP,
+ ASPECT_RATIO_OPTIONS,
+ calculateNewSize,
+ clampDimension,
+ getOptimalDimension,
+ isAspectRatioId,
+} from '../../generation/settings';
+import type { AspectRatioId, GenerateSettings, MainModelConfig } from '../../generation/types';
+import { AspectRatioPreview } from './shared/AspectRatioPreview';
+import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';
+
+interface GenerateDimensionFieldsProps {
+ settings: GenerateSettings;
+ selectedModel: MainModelConfig | undefined;
+ onCommit: (patch: Partial<GenerateSettings>) => void;
+}
+
+type Dimensions = Pick<GenerateSettings, 'height' | 'width'>;
+type AspectRatioOption = { id: AspectRatioId; ratio: number };
+
+const DIMENSION_COMMIT_DEBOUNCE_MS = 150;
+
+/** The ratio to enforce, preferring the stored value and falling back to the current dimensions. */
+const getActiveRatio = (settings: GenerateSettings): number =>
+ settings.aspectRatioValue > 0
+ ? settings.aspectRatioValue
+ : settings.height > 0
+ ? settings.width / settings.height
+ : 1;
+
+const getAspectRatioOptionRatio = (id: AspectRatioId, fallbackRatio: number): number =>
+ id === 'Free' ? fallbackRatio : ASPECT_RATIO_MAP[id].ratio;
+
+export const GenerateDimensionFields = ({ onCommit, selectedModel, settings }: GenerateDimensionFieldsProps) => {
+ const [draftDimensions, setDraftDimensions] = useState<Dimensions | null>(null);
+ const isRatioConstrained = settings.aspectRatioId !== 'Free' || settings.aspectRatioIsLocked;
+ const displayDimensions = draftDimensions ?? { height: settings.height, width: settings.width };
+ const onCommitRef = useRef(onCommit);
+ const pendingDimensionsRef = useRef<Dimensions | null>(null);
+ const commitTimeoutRef = useRef<number | null>(null);
+ const previousSettingsDimensionsRef = useRef<Dimensions>({ height: settings.height, width: settings.width });
+ const dimensionRatio = displayDimensions.height > 0 ? displayDimensions.width / displayDimensions.height : 1;
+ const aspectRatioOptions = useMemo<AspectRatioOption[]>(
+ () =>
+ ASPECT_RATIO_OPTIONS.map((id) => ({
+ id,
+ ratio: getAspectRatioOptionRatio(id, dimensionRatio),
+ })),
+ [dimensionRatio]
+ );
+ const aspectRatioCollection = useMemo(
+ () =>
+ createListCollection({
+ itemToString: (item: AspectRatioOption) => item.id,
+ itemToValue: (item: AspectRatioOption) => item.id,
+ items: aspectRatioOptions,
+ }),
+ [aspectRatioOptions]
+ );
+ const activeAspectRatioPreviewRatio = getAspectRatioOptionRatio(settings.aspectRatioId, dimensionRatio);
+
+ useEffect(() => {
+ onCommitRef.current = onCommit;
+ }, [onCommit]);
+
+ const clearPendingDimensionCommit = useCallback(() => {
+ if (commitTimeoutRef.current !== null) {
+ window.clearTimeout(commitTimeoutRef.current);
+ commitTimeoutRef.current = null;
+ }
+ }, []);
+
+ const commitDimensions = useCallback(
+ (dimensions: Dimensions) => {
+ clearPendingDimensionCommit();
+ pendingDimensionsRef.current = dimensions;
+ onCommitRef.current(dimensions);
+ },
+ [clearPendingDimensionCommit]
+ );
+
+ const scheduleDimensionCommit = useCallback(
+ (dimensions: Dimensions) => {
+ clearPendingDimensionCommit();
+ pendingDimensionsRef.current = dimensions;
+ commitTimeoutRef.current = window.setTimeout(() => {
+ commitTimeoutRef.current = null;
+
+ if (pendingDimensionsRef.current) {
+ onCommitRef.current(pendingDimensionsRef.current);
+ }
+ }, DIMENSION_COMMIT_DEBOUNCE_MS);
+ },
+ [clearPendingDimensionCommit]
+ );
+
+ useEffect(
+ () => () => {
+ clearPendingDimensionCommit();
+ },
+ [clearPendingDimensionCommit]
+ );
+
+ useEffect(() => {
+ const previousSettingsDimensions = previousSettingsDimensionsRef.current;
+ previousSettingsDimensionsRef.current = { height: settings.height, width: settings.width };
+
+ if (!draftDimensions) {
+ return;
+ }
+
+ if (settings.width === draftDimensions.width && settings.height === draftDimensions.height) {
+ pendingDimensionsRef.current = null;
+ setDraftDimensions(null);
+ return;
+ }
+
+ if (settings.width === previousSettingsDimensions.width && settings.height === previousSettingsDimensions.height) {
+ return;
+ }
+
+ pendingDimensionsRef.current = null;
+ clearPendingDimensionCommit();
+ setDraftDimensions(null);
+ }, [clearPendingDimensionCommit, draftDimensions, settings.height, settings.width]);
+
+ const getNextDimensions = (key: 'height' | 'width', value: number): Dimensions => {
+ if (!isRatioConstrained) {
+ return { ...displayDimensions, [key]: value };
+ }
+
+ const ratio = getActiveRatio({ ...settings, ...displayDimensions });
+
+ return key === 'width'
+ ? { height: clampDimension(value / ratio), width: value }
+ : { height: value, width: clampDimension(value * ratio) };
+ };
+
+ const setDimension =
+ (key: 'height' | 'width') =>
+ ({ valueAsNumber }: NumberInput.ValueChangeDetails) => {
+ const value = valueAsNumber;
+
+ if (!Number.isFinite(value) || value <= 0) {
+ return;
+ }
+
+ const dimensions = getNextDimensions(key, value);
+
+ setDraftDimensions(dimensions);
+ scheduleDimensionCommit(dimensions);
+ };
+
+ const commitDimension =
+ (key: 'height' | 'width') =>
+ ({ valueAsNumber }: NumberInput.ValueChangeDetails) => {
+ const value = valueAsNumber;
+
+ if (!Number.isFinite(value) || value <= 0) {
+ return;
+ }
+
+ const dimensions = getNextDimensions(key, value);
+
+ setDraftDimensions(dimensions);
+ commitDimensions(dimensions);
+ };
+
+ const snapDimension = (key: 'height' | 'width') => () => {
+ const snapped = clampDimension(displayDimensions[key]);
+
+ if (snapped !== displayDimensions[key]) {
+ const dimensions = getNextDimensions(key, snapped);
+
+ setDraftDimensions(dimensions);
+ commitDimensions(dimensions);
+ }
+ };
+
+ const commitSettings = (patch: Partial<GenerateSettings>) => {
+ clearPendingDimensionCommit();
+ pendingDimensionsRef.current = null;
+ setDraftDimensions(null);
+ onCommit(patch);
+ };
+
+ const setAspectRatioId = ({ value }: Select.ValueChangeDetails<AspectRatioOption>) => {
+ const id = value[0];
+
+ if (!isAspectRatioId(id)) {
+ return;
+ }
+
+ if (id === 'Free') {
+ commitSettings({
+ aspectRatioId: 'Free',
+ aspectRatioIsLocked: false,
+ aspectRatioValue: displayDimensions.height > 0 ? displayDimensions.width / displayDimensions.height : 1,
+ ...displayDimensions,
+ });
+ return;
+ }
+
+ const ratio = ASPECT_RATIO_MAP[id].ratio;
+
+ commitSettings({
+ aspectRatioId: id,
+ aspectRatioIsLocked: true,
+ aspectRatioValue: ratio,
+ ...calculateNewSize(ratio, displayDimensions.width * displayDimensions.height),
+ });
+ };
+
+ const toggleLock = () => {
+ commitSettings({
+ aspectRatioIsLocked: !settings.aspectRatioIsLocked,
+ // Locking in Free mode captures the current ratio so further edits preserve it.
+ aspectRatioValue:
+ !settings.aspectRatioIsLocked && settings.aspectRatioId === 'Free' && displayDimensions.height > 0
+ ? displayDimensions.width / displayDimensions.height
+ : settings.aspectRatioValue,
+ ...displayDimensions,
+ });
+ };
+
+ const swapDimensions = () => {
+ const inverseId: AspectRatioId =
+ settings.aspectRatioId === 'Free' ? 'Free' : ASPECT_RATIO_MAP[settings.aspectRatioId].inverseId;
+
+ commitSettings({
+ aspectRatioId: inverseId,
+ aspectRatioValue: settings.aspectRatioValue > 0 ? 1 / settings.aspectRatioValue : 1,
+ height: displayDimensions.width,
+ width: displayDimensions.height,
+ });
+ };
+
+ const optimizeSize = () => {
+ const optimal = getOptimalDimension(selectedModel?.base ?? 'sdxl');
+ const ratio = isRatioConstrained
+ ? getActiveRatio({ ...settings, ...displayDimensions })
+ : displayDimensions.height > 0
+ ? displayDimensions.width / displayDimensions.height
+ : 1;
+
+ commitSettings(calculateNewSize(ratio, optimal * optimal));
+ };
+
+ const badges = (
+ <>
+ <Badge size="xs">
+ {displayDimensions.width}x{displayDimensions.height}
+ </Badge>
+ {settings.aspectRatioIsLocked && (
+ <Badge size="xs">
+ <Icon as={LockIcon} boxSize="3" />
+ </Badge>
+ )}
+ </>
+ );
+
+ return (
+ <GenerateCollapsibleSection label="Dimensions" badges={badges} defaultOpen>
+ <Field label="Aspect ratio" p="2">
+ <HStack gap="1">
+ <Select.Root
+ collection={aspectRatioCollection}
+ flex="1"
+ size="xs"
+ value={[settings.aspectRatioId]}
+ onValueChange={setAspectRatioId}
+ >
+ <Select.HiddenSelect />
+ <Select.Control>
+ <Select.Trigger>
+ <Select.ValueText>
+ <HStack as="span" gap="2" minW="0">
+ <AspectRatioPreview boxSize="5" ratio={activeAspectRatioPreviewRatio} />
+ <Text as="span" fontSize="xs" truncate>
+ {settings.aspectRatioId}
+ </Text>
+ </HStack>
+ </Select.ValueText>
+ </Select.Trigger>
+ <Select.IndicatorGroup>
+ <Select.Indicator />
+ </Select.IndicatorGroup>
+ </Select.Control>
+ <Portal>
+ <Select.Positioner>
+ <Select.Content
+ bg="bg.muted"
+ borderColor="border.emphasized"
+ borderWidth="1px"
+ color="fg"
+ maxH="18rem"
+ rounded="lg"
+ shadow="lg"
+ zIndex="popover"
+ >
+ {aspectRatioOptions.map((option) => (
+ <Select.Item key={option.id} item={option}>
+ <Select.ItemText>
+ <HStack as="span" gap="2">
+ <AspectRatioPreview boxSize="6" ratio={option.ratio} />
+ <Text as="span" fontSize="xs">
+ {option.id}
+ </Text>
+ </HStack>
+ </Select.ItemText>
+ <Select.ItemIndicator />
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select.Positioner>
+ </Portal>
+ </Select.Root>
+ <Tooltip content={settings.aspectRatioIsLocked ? 'Unlock aspect ratio' : 'Lock aspect ratio'}>
+ <IconButton
+ aria-label={settings.aspectRatioIsLocked ? 'Unlock aspect ratio' : 'Lock aspect ratio'}
+ size="xs"
+ variant={settings.aspectRatioIsLocked ? 'solid' : 'outline'}
+ onClick={toggleLock}
+ >
+ {settings.aspectRatioIsLocked ? <LockIcon /> : <LockOpenIcon />}
+ </IconButton>
+ </Tooltip>
+ <Tooltip content="Swap width and height">
+ <IconButton aria-label="Swap width and height" size="xs" variant="outline" onClick={swapDimensions}>
+ <ArrowLeftRightIcon />
+ </IconButton>
+ </Tooltip>
+ <Tooltip content="Set size to the model's optimal pixel count">
+ <IconButton aria-label="Set optimal size" size="xs" variant="outline" onClick={optimizeSize}>
+ <ScalingIcon />
+ </IconButton>
+ </Tooltip>
+ </HStack>
+ </Field>
+ <HStack alignItems="flex-start" gap="2" p="2">
+ <Stack w="full">
+ <Field label="Width">
+ <NumberInput.Root
+ size="xs"
+ allowMouseWheel
+ value={String(displayDimensions.width)}
+ step={8}
+ onBlur={snapDimension('width')}
+ onValueCommit={commitDimension('width')}
+ onValueChange={setDimension('width')}
+ >
+ <NumberInput.Control />
+ <InputGroup
+ startElementProps={{ pointerEvents: 'auto' }}
+ startElement={
+ <NumberInput.Scrubber>
+ <Icon as={RulerDimensionLineIcon} boxSize="3" />
+ </NumberInput.Scrubber>
+ }
+ >
+ <NumberInput.Input />
+ </InputGroup>
+ </NumberInput.Root>
+ </Field>
+ <Field label="Height">
+ <NumberInput.Root
+ size="xs"
+ allowMouseWheel
+ value={String(displayDimensions.height)}
+ step={8}
+ onBlur={snapDimension('height')}
+ onValueCommit={commitDimension('height')}
+ onValueChange={setDimension('height')}
+ >
+ <NumberInput.Control />
+ <InputGroup
+ startElementProps={{ pointerEvents: 'auto' }}
+ startElement={
+ <NumberInput.Scrubber>
+ <Icon as={RulerDimensionLineIcon} boxSize="3" rotate="90" />
+ </NumberInput.Scrubber>
+ }
+ >
+ <NumberInput.Input />
+ </InputGroup>
+ </NumberInput.Root>
+ </Field>
+ </Stack>
+ <Box w="1/3" aspectRatio="1/1" borderColor="bg.emphasized" borderWidth={1} p={1} rounded="sm">
+ <AspectRatioPreview boxSize="full" ratio={dimensionRatio} />
+ </Box>
+ </HStack>
+ </GenerateCollapsibleSection>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateModelFields.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateModelFields.tsx
new file mode 100644
index 0000000000..c75b09390c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateModelFields.tsx
@@ -0,0 +1,152 @@
+import { HStack, NativeSelect, NumberInput, Stack } from '@chakra-ui/react';
+import { DicesIcon } from 'lucide-react';
+import type { ChangeEvent } from 'react';
+
+import { Button, IconButton } from '../../components/ui/Button';
+import { Field } from '../../components/ui/Field';
+import { ModelSelect } from '../../components/ModelSelect';
+import { Tooltip } from '../../components/ui/Tooltip';
+import { getSettingsWithModelDefaults, isSupportedGenerateModel } from '../../generation/graph';
+import { isKnownScheduler, isMainModelConfig, SCHEDULER_OPTIONS, SEED_MAX } from '../../generation/settings';
+import type { GenerateSettings, MainModelConfig, VaeModelConfig } from '../../generation/types';
+import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';
+
+interface GenerateModelFieldsProps {
+ settings: GenerateSettings;
+ selectedModel: MainModelConfig | undefined;
+ vaeModels: VaeModelConfig[];
+ onCommit: (patch: Partial<GenerateSettings>) => void;
+ onCommitSettings: (nextSettings: GenerateSettings) => void;
+}
+
+export const GenerateModelFields = ({
+ onCommit,
+ onCommitSettings,
+ selectedModel,
+ settings,
+ vaeModels,
+}: GenerateModelFieldsProps) => {
+ const commitNumber = (key: 'cfgScale' | 'seed' | 'steps', value: number) => {
+ if (!Number.isFinite(value)) {
+ return;
+ }
+
+ onCommit({ [key]: value });
+ };
+
+ const updateNumberInput =
+ (key: 'cfgScale' | 'seed' | 'steps') =>
+ ({ valueAsNumber }: NumberInput.ValueChangeDetails) => {
+ commitNumber(key, valueAsNumber);
+ };
+
+ const selectModel = (model: MainModelConfig) => {
+ // The model's configured default VAE (a model key) only applies if that VAE is installed.
+ const defaultVaeKey = model.default_settings?.vae;
+ const defaultVae = defaultVaeKey
+ ? (vaeModels.find((vae) => vae.key === defaultVaeKey && vae.base === model.base) ?? null)
+ : null;
+
+ onCommitSettings({ ...getSettingsWithModelDefaults(settings, model), vae: defaultVae });
+ };
+
+ return (
+ <GenerateCollapsibleSection label="Model" defaultOpen>
+ <Stack gap="2" p="2">
+ <Field label="Model">
+ <ModelSelect
+ filter={(model) => isMainModelConfig(model) && isSupportedGenerateModel(model)}
+ modelTypes={['main']}
+ placeholder="Select a model…"
+ value={selectedModel?.key ?? null}
+ size="xs"
+ onChange={(model) => {
+ if (isMainModelConfig(model) && isSupportedGenerateModel(model)) {
+ selectModel(model);
+ }
+ }}
+ />
+ </Field>
+ <HStack gap="2">
+ <Field label="Steps">
+ <NumberInput.Root
+ size="xs"
+ value={String(settings.steps)}
+ onValueChange={updateNumberInput('steps')}
+ min={1}
+ allowMouseWheel
+ >
+ <NumberInput.Input />
+ <NumberInput.Control />
+ </NumberInput.Root>
+ </Field>
+ <Field label="CFG">
+ <NumberInput.Root
+ size="xs"
+ value={String(settings.cfgScale)}
+ onValueChange={updateNumberInput('cfgScale')}
+ min={0}
+ max={10}
+ step={0.5}
+ >
+ <NumberInput.Input />
+ <NumberInput.Control />
+ </NumberInput.Root>
+ </Field>
+ <Field label="Scheduler">
+ <NativeSelect.Root size="xs">
+ <NativeSelect.Field
+ aria-label="Scheduler"
+ value={settings.scheduler}
+ onChange={(event: ChangeEvent<HTMLSelectElement>) => onCommit({ scheduler: event.currentTarget.value })}
+ >
+ {isKnownScheduler(settings.scheduler) ? null : (
+ <option value={settings.scheduler}>{settings.scheduler}</option>
+ )}
+ {SCHEDULER_OPTIONS.map((option) => (
+ <option key={option.value} value={option.value}>
+ {option.label}
+ </option>
+ ))}
+ </NativeSelect.Field>
+ <NativeSelect.Indicator />
+ </NativeSelect.Root>
+ </Field>
+ </HStack>
+ <Field label="Seed">
+ <HStack gap="2">
+ <NumberInput.Root
+ size="xs"
+ value={String(settings.seed)}
+ onValueChange={updateNumberInput('seed')}
+ min={0}
+ max={SEED_MAX}
+ w="full"
+ disabled={settings.shouldRandomizeSeed}
+ >
+ <NumberInput.Input />
+ </NumberInput.Root>
+ <Tooltip content="Shuffle seed">
+ <IconButton
+ aria-label="Shuffle seed"
+ disabled={settings.shouldRandomizeSeed}
+ size="xs"
+ variant="outline"
+ onClick={() => onCommit({ seed: Math.floor(Math.random() * SEED_MAX) })}
+ >
+ <DicesIcon />
+ </IconButton>
+ </Tooltip>
+ <Button
+ size="xs"
+ variant={settings.shouldRandomizeSeed ? 'solid' : 'outline'}
+ onClick={() => onCommit({ shouldRandomizeSeed: !settings.shouldRandomizeSeed })}
+ >
+ Random
+ </Button>
+ </HStack>
+ </Field>
+ </Stack>
+ </GenerateCollapsibleSection>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GeneratePromptFields.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/GeneratePromptFields.tsx
new file mode 100644
index 0000000000..6b6c294e09
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/GeneratePromptFields.tsx
@@ -0,0 +1,58 @@
+import { Stack, Textarea } from '@chakra-ui/react';
+import type { ChangeEvent } from 'react';
+
+import { Field } from '../../components/ui/Field';
+import type { GenerateSettings } from '../../generation/types';
+
+interface GeneratePromptFieldsProps {
+ settings: GenerateSettings;
+ onCommit: (patch: Partial<GenerateSettings>) => void;
+}
+
+interface PromptFieldProps {
+ value: string;
+ onChange: (value: string) => void;
+}
+
+const PositivePromptField = ({ onChange, value }: PromptFieldProps) => (
+ <Field label="Prompt">
+ <Textarea
+ aria-label="Positive prompt"
+ minH="6rem"
+ resize="vertical"
+ size="xs"
+ fontFamily="mono"
+ value={value}
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) => onChange(event.currentTarget.value)}
+ />
+ </Field>
+);
+
+const NegativePromptField = ({ onChange, value }: PromptFieldProps) => (
+ <Field label="Negative prompt">
+ <Textarea
+ aria-label="Negative prompt"
+ minH="3.5rem"
+ resize="vertical"
+ size="xs"
+ fontFamily="mono"
+ value={value}
+ onChange={(event: ChangeEvent<HTMLTextAreaElement>) => onChange(event.currentTarget.value)}
+ />
+ </Field>
+);
+
+export const GeneratePromptFields = ({ onCommit, settings }: GeneratePromptFieldsProps) => {
+ return (
+ <Stack gap="1">
+ <PositivePromptField
+ value={settings.positivePrompt}
+ onChange={(positivePrompt) => onCommit({ positivePrompt })}
+ />
+ <NegativePromptField
+ value={settings.negativePrompt}
+ onChange={(negativePrompt) => onCommit({ negativePrompt })}
+ />
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateSettingsForm.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateSettingsForm.tsx
index 4db7a78f81..a17bc7aac4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateSettingsForm.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateSettingsForm.tsx
@@ -1,145 +1,48 @@
-import { HStack, Input, NativeSelect, Stack, Text, Textarea } from '@chakra-ui/react';
-import type { ChangeEvent } from 'react';
+import { Stack, Text } from '@chakra-ui/react';
-import { Button } from '../../components/ui/Button';
-import { Field } from '../../components/ui/Field';
-import { getSettingsWithModelDefaults } from '../../generation/graph';
-import type { GenerateSettings, MainModelConfig } from '../../generation/types';
+import type { GenerateSettings, MainModelConfig, VaeModelConfig } from '../../generation/types';
+import { GenerateAdvancedFields } from './GenerateAdvancedFields';
+import { GenerateDimensionFields } from './GenerateDimensionFields';
+import { GenerateModelFields } from './GenerateModelFields';
+import { GeneratePromptFields } from './GeneratePromptFields';
interface GenerateSettingsFormProps {
isLoadingModels: boolean;
loadError: string | null;
settings: GenerateSettings;
+ selectedModel: MainModelConfig | undefined;
supportedModels: MainModelConfig[];
+ vaeModels: VaeModelConfig[];
onCommitSettings: (nextSettings: GenerateSettings) => void;
}
export const GenerateSettingsForm = ({
isLoadingModels,
loadError,
+ onCommitSettings,
+ selectedModel,
settings,
supportedModels,
- onCommitSettings,
+ vaeModels,
}: GenerateSettingsFormProps) => {
- const updateText = (key: 'negativePrompt' | 'positivePrompt') => (event: ChangeEvent<HTMLTextAreaElement>) => {
- onCommitSettings({ ...settings, [key]: event.currentTarget.value });
+ const commit = (patch: Partial<GenerateSettings>) => {
+ onCommitSettings({ ...settings, ...patch });
};
- const updateNumber =
- (key: 'cfgScale' | 'height' | 'seed' | 'steps' | 'width') => (event: ChangeEvent<HTMLInputElement>) => {
- const value = Number(event.currentTarget.value);
-
- if (!Number.isFinite(value)) {
- return;
- }
-
- onCommitSettings({ ...settings, [key]: value });
- };
-
return (
- <Stack gap="3">
- <Field label="Prompt">
- <Textarea
- aria-label="Positive prompt"
- minH="6rem"
- resize="vertical"
- size="xs"
- fontFamily="mono"
- value={settings.positivePrompt}
- onChange={updateText('positivePrompt')}
- />
- </Field>
- <Field label="Negative prompt">
- <Textarea
- aria-label="Negative prompt"
- minH="3.5rem"
- resize="vertical"
- size="xs"
- fontFamily="mono"
- value={settings.negativePrompt}
- onChange={updateText('negativePrompt')}
- />
- </Field>
- <Field label="Model">
- <NativeSelect.Root disabled={supportedModels.length === 0} size="sm">
- <NativeSelect.Field
- aria-label="Model"
- value={settings.modelKey}
- onChange={(event: ChangeEvent<HTMLSelectElement>) => {
- const model = supportedModels.find((candidate) => candidate.key === event.currentTarget.value);
+ <Stack gap="1" px={1}>
+ <GeneratePromptFields settings={settings} onCommit={commit} />
- if (!model) {
- return;
- }
+ <GenerateModelFields
+ selectedModel={selectedModel}
+ settings={settings}
+ vaeModels={vaeModels}
+ onCommit={commit}
+ onCommitSettings={onCommitSettings}
+ />
- onCommitSettings({
- ...getSettingsWithModelDefaults(settings, model),
- negativePrompt: settings.negativePrompt,
- positivePrompt: settings.positivePrompt,
- });
- }}
- >
- {supportedModels.map((model) => (
- <option key={model.key} value={model.key}>
- {model.name} ({model.base})
- </option>
- ))}
- </NativeSelect.Field>
- <NativeSelect.Indicator />
- </NativeSelect.Root>
- </Field>
- <HStack gap="2">
- <Field label="Width">
- <Input min="64" size="sm" step="8" type="number" value={settings.width} onChange={updateNumber('width')} />
- </Field>
- <Field label="Height">
- <Input min="64" size="sm" step="8" type="number" value={settings.height} onChange={updateNumber('height')} />
- </Field>
- </HStack>
- <HStack gap="2">
- <Field label="Steps">
- <Input min="1" size="sm" type="number" value={settings.steps} onChange={updateNumber('steps')} />
- </Field>
- <Field label="CFG">
- <Input
- min="0"
- size="sm"
- step="0.5"
- type="number"
- value={settings.cfgScale}
- onChange={updateNumber('cfgScale')}
- />
- </Field>
- </HStack>
- <Field label="Scheduler">
- <Input
- aria-label="Scheduler"
- size="sm"
- value={settings.scheduler}
- onChange={(event: ChangeEvent<HTMLInputElement>) =>
- onCommitSettings({ ...settings, scheduler: event.currentTarget.value })
- }
- />
- </Field>
- <Field label="Seed">
- <HStack gap="2">
- <Input
- disabled={settings.shouldRandomizeSeed}
- min="0"
- size="sm"
- type="number"
- value={settings.seed}
- onChange={updateNumber('seed')}
- />
- <Button
- size="xs"
- variant={settings.shouldRandomizeSeed ? 'solid' : 'outline'}
- onClick={() => onCommitSettings({ ...settings, shouldRandomizeSeed: !settings.shouldRandomizeSeed })}
- >
- Random
- </Button>
- </HStack>
- </Field>
+ <GenerateDimensionFields selectedModel={selectedModel} settings={settings} onCommit={commit} />
+ <GenerateAdvancedFields selectedModel={selectedModel} settings={settings} onCommit={commit} />
{isLoadingModels ? (
<Text color="fg.subtle" fontSize="2xs">
Loading backend models...
@@ -152,9 +55,9 @@ export const GenerateSettingsForm = ({
<Text color="fg.subtle" fontSize="2xs">
No SD/SDXL main models were found on the backend.
</Text>
- ) : (
- <Text color="fg.subtle" fontSize="2xs">
- Current settings compile into an immutable Generate graph snapshot when you invoke.
+ ) : selectedModel ? null : (
+ <Text color="fg.error" fontSize="2xs">
+ Select a model to enable invocation.
</Text>
)}
</Stack>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx
index 702056010a..4830a0c9a5 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/GenerateWidgetView.tsx
@@ -1,57 +1,30 @@
-import { useEffect, useMemo, useState } from 'react';
+import { useEffect, useMemo } from 'react';
-import { listMainModels } from '../../generation/api';
import { getDefaultGenerateSettings, isSupportedGenerateModel } from '../../generation/graph';
-import type { GenerateSettings, MainModelConfig } from '../../generation/types';
+import { normalizeGenerateSettings, normalizeGenerateWidgetValues } from '../../generation/settings';
+import type { GenerateSettings, VaeModelConfig } from '../../generation/types';
+import { ensureModelsLoaded, useModelsSnapshot } from '../../models/modelsStore';
+import type { ModelConfig } from '../../models/types';
import { useWorkbench } from '../../WorkbenchContext';
import { GenerateSettingsForm } from './GenerateSettingsForm';
-import { isGenerateSettings, isGenerateWidgetValues } from './generateWidgetGuards';
export const GenerateWidgetView = () => {
const { activeProject, dispatch } = useWorkbench();
- const [models, setModels] = useState<MainModelConfig[]>([]);
- const [isLoadingModels, setIsLoadingModels] = useState(true);
- const [loadError, setLoadError] = useState<string | null>(null);
- const supportedModels = useMemo(() => models.filter(isSupportedGenerateModel), [models]);
- const storedValues = activeProject.widgetStates.generate.values;
- const selectedModel = supportedModels.find(
- (model) => model.key === activeProject.widgetStates.generate.values.modelKey
- );
- const settings = isGenerateSettings(storedValues)
- ? storedValues
- : getDefaultGenerateSettings(selectedModel ?? supportedModels[0]);
+ const { error, models, status } = useModelsSnapshot();
useEffect(() => {
- let isStale = false;
-
- listMainModels()
- .then((nextModels) => {
- if (isStale) {
- return;
- }
-
- setModels(nextModels);
- setLoadError(null);
- })
- .catch((error: unknown) => {
- if (isStale) {
- return;
- }
+ ensureModelsLoaded();
+ }, []);
- const message = error instanceof Error ? error.message : 'Failed to load models.';
- setLoadError(message);
- dispatch({ message, type: 'recordError' });
- })
- .finally(() => {
- if (!isStale) {
- setIsLoadingModels(false);
- }
- });
-
- return () => {
- isStale = true;
- };
- }, [dispatch]);
+ const supportedModels = useMemo(() => models.filter(isSupportedGenerateModel), [models]);
+ const vaeModels = useMemo(
+ () => models.filter((model): model is ModelConfig & VaeModelConfig => model.type === 'vae'),
+ [models]
+ );
+ const storedValues = activeProject.widgetStates.generate.values;
+ const normalizedSettings = normalizeGenerateSettings(storedValues);
+ const selectedModel = supportedModels.find((model) => model.key === normalizedSettings?.modelKey);
+ const settings = normalizedSettings ?? getDefaultGenerateSettings(selectedModel ?? supportedModels[0]);
useEffect(() => {
const model = selectedModel ?? supportedModels[0];
@@ -60,7 +33,9 @@ export const GenerateWidgetView = () => {
return;
}
- if (isGenerateWidgetValues(storedValues) && storedValues.model.key === model.key) {
+ const storedWidgetValues = normalizeGenerateWidgetValues(storedValues);
+
+ if (storedWidgetValues && storedWidgetValues.model.key === model.key) {
return;
}
@@ -81,10 +56,12 @@ export const GenerateWidgetView = () => {
return (
<GenerateSettingsForm
- isLoadingModels={isLoadingModels}
- loadError={loadError}
+ isLoadingModels={status === 'idle' || status === 'loading'}
+ loadError={error}
+ selectedModel={selectedModel}
settings={settings}
supportedModels={supportedModels}
+ vaeModels={vaeModels}
onCommitSettings={commitSettings}
/>
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/generateWidgetGuards.ts b/invokeai/frontend/webv2/src/workbench/widgets/generate/generateWidgetGuards.ts
deleted file mode 100644
index a1045aeaa1..0000000000
--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/generateWidgetGuards.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import type { GenerateSettings, GenerateWidgetValues } from '../../generation/types';
-
-export const isGenerateSettings = (values: unknown): values is GenerateSettings => {
- if (!values || typeof values !== 'object') {
- return false;
- }
-
- const record = values as Record<string, unknown>;
- const hasFiniteNumber = (key: string) => typeof record[key] === 'number' && Number.isFinite(record[key]);
-
- return (
- typeof record.modelKey === 'string' &&
- typeof record.positivePrompt === 'string' &&
- typeof record.negativePrompt === 'string' &&
- hasFiniteNumber('batchCount') &&
- hasFiniteNumber('width') &&
- hasFiniteNumber('height') &&
- hasFiniteNumber('steps') &&
- hasFiniteNumber('cfgScale') &&
- hasFiniteNumber('cfgRescaleMultiplier') &&
- typeof record.scheduler === 'string' &&
- hasFiniteNumber('seed') &&
- typeof record.shouldRandomizeSeed === 'boolean'
- );
-};
-
-export const isGenerateWidgetValues = (values: unknown): values is GenerateWidgetValues => {
- if (!isGenerateSettings(values)) {
- return false;
- }
-
- const model = (values as unknown as Record<string, unknown>).model;
-
- return Boolean(model && typeof model === 'object' && (model as Record<string, unknown>).type === 'main');
-};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/shared/AspectRatioPreview.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/shared/AspectRatioPreview.tsx
new file mode 100644
index 0000000000..274a12ded2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/shared/AspectRatioPreview.tsx
@@ -0,0 +1,30 @@
+import { Box, Flex } from '@chakra-ui/react';
+
+type Props = {
+ ratio: number; // e.g. 16 / 9
+ boxSize?: string | number;
+};
+
+export const AspectRatioPreview = ({ boxSize = '8', ratio }: Props) => {
+ const normalizedRatio = Number.isFinite(ratio) && ratio > 0 ? ratio : 1;
+ const isWide = normalizedRatio >= 1;
+
+ return (
+ <Flex as="span" alignItems="center" boxSize={boxSize} flexShrink={0} justifyContent="center" p="0.5">
+ <Box
+ as="span"
+ aria-hidden="true"
+ bg="bg.subtle"
+ borderColor="fg.muted"
+ borderStyle="dashed"
+ borderWidth="1px"
+ display="block"
+ h={isWide ? `${100 / normalizedRatio}%` : 'full'}
+ minH="1px"
+ minW="1px"
+ rounded="2px"
+ w={isWide ? 'full' : `${normalizedRatio * 100}%`}
+ />
+ </Flex>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/shared/GenerateCollapsibleSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/shared/GenerateCollapsibleSection.tsx
new file mode 100644
index 0000000000..6410250d09
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/shared/GenerateCollapsibleSection.tsx
@@ -0,0 +1,43 @@
+import { Box, Collapsible, Flex, Text } from '@chakra-ui/react';
+import { ChevronRightIcon } from 'lucide-react';
+
+type Props = {
+ label: string;
+ isOpen?: boolean;
+ defaultOpen?: boolean;
+ badges?: React.ReactNode;
+ children: React.ReactNode;
+};
+
+export const GenerateCollapsibleSection = ({ label, defaultOpen, isOpen, children, badges }: Props) => {
+ return (
+ <Collapsible.Root defaultOpen={defaultOpen} open={isOpen} bg="bg.subtle">
+ <Collapsible.Trigger display="flex" gap={2} w="full" p={2} alignItems="center">
+ <Collapsible.Indicator _open={{ transform: 'rotate(90deg)' }} transition="transform 0.2s">
+ <ChevronRightIcon size="14" />
+ </Collapsible.Indicator>
+ <Text
+ as="span"
+ fontSize="2xs"
+ truncate
+ letterSpacing="widest"
+ fontWeight="bold"
+ textTransform="uppercase"
+ color="fg.muted"
+ lineHeight="1"
+ >
+ {label}
+ </Text>
+
+ <Flex gap={1} ml="auto" fontFamily="mono">
+ {badges}
+ </Flex>
+ </Collapsible.Trigger>
+ <Collapsible.Content>
+ <Box borderTopWidth={1} borderColor="bg">
+ {children}
+ </Box>
+ </Collapsible.Content>
+ </Collapsible.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index f9bc567872..68c73af0aa 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -13,18 +13,26 @@ const model: MainModelConfig = {
};
const createGenerateValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWidgetValues => ({
+ aspectRatioId: '1:1',
+ aspectRatioIsLocked: false,
+ aspectRatioValue: 1,
batchCount: 1,
cfgRescaleMultiplier: 0,
cfgScale: 7,
+ clipSkip: 0,
height: 1024,
model,
modelKey: model.key,
negativePrompt: '',
positivePrompt: 'first prompt',
scheduler: 'euler_a',
+ seamlessXAxis: false,
+ seamlessYAxis: false,
seed: 123,
shouldRandomizeSeed: false,
steps: 30,
+ vae: null,
+ vaePrecision: 'fp32',
width: 1024,
...overrides,
});
@@ -229,7 +237,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
const secondValues = secondQueueItem?.snapshot.widgetStates.generate.values as unknown as GenerateWidgetValues;
expect(firstValues.positivePrompt).toBe('first prompt');
- expect(firstValues.shouldRandomizeSeed).toBe(false);
+ expect(firstValues.shouldRandomizeSeed).toBe(true);
expect(typeof firstValues.seed).toBe('number');
expect(secondValues.positivePrompt).toBe('second prompt');
expect(secondValues.seed).toBe(999);
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index ad032fe22b..6326f854cd 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -5,8 +5,9 @@ import {
resolveInvocationRoute,
} from './invocation';
import { compileGenerateGraph, resolveGenerateSeed } from './generation/graph';
+import { normalizeGenerateWidgetValues } from './generation/settings';
import type { GallerySettings } from './gallery/settings';
-import type { GenerateWidgetValues, MainModelConfig } from './generation/types';
+import type { GenerateWidgetValues } from './generation/types';
import { defaultLayoutPreset, getLayoutPreset } from './layoutPresets';
import { normalizeProjectSettings } from './settings/store';
import type {
@@ -673,40 +674,6 @@ const updateActiveInvocation = (
};
});
-const isMainModelConfig = (value: unknown): value is MainModelConfig => {
- if (!value || typeof value !== 'object') {
- return false;
- }
-
- const record = value as Record<string, unknown>;
-
- return typeof record.key === 'string' && typeof record.name === 'string' && record.type === 'main';
-};
-
-const isGenerateWidgetValues = (values: unknown): values is GenerateWidgetValues => {
- if (!values || typeof values !== 'object') {
- return false;
- }
-
- const record = values as Record<string, unknown>;
- const hasFiniteNumber = (key: string) => typeof record[key] === 'number' && Number.isFinite(record[key]);
-
- return (
- typeof record.modelKey === 'string' &&
- typeof record.positivePrompt === 'string' &&
- typeof record.negativePrompt === 'string' &&
- hasFiniteNumber('width') &&
- hasFiniteNumber('height') &&
- hasFiniteNumber('steps') &&
- hasFiniteNumber('cfgScale') &&
- hasFiniteNumber('cfgRescaleMultiplier') &&
- typeof record.scheduler === 'string' &&
- hasFiniteNumber('seed') &&
- typeof record.shouldRandomizeSeed === 'boolean' &&
- isMainModelConfig(record.model)
- );
-};
-
const selectGraphForInvocation = (project: Project, invocation: InvocationRoute): GraphContract => {
const widgetGraph = project.widgetGraphs[invocation.sourceId as WidgetId];
@@ -723,16 +690,15 @@ const compileInvocationSnapshot = (
return { graph: selectGraphForInvocation(project, route), widgetStates };
}
- const values = project.widgetStates.generate.values;
+ const values = normalizeGenerateWidgetValues(project.widgetStates.generate.values);
- if (!isGenerateWidgetValues(values)) {
+ if (!values) {
return null;
}
const resolvedSettings: GenerateWidgetValues = {
...values,
seed: resolveGenerateSeed(values),
- shouldRandomizeSeed: false,
};
const compiledGraph = compileGenerateGraph(
resolvedSettings,