Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
Merge upstream/main into v7/main
Josh Corbett6a8c9269ee53
diff --cc invokeai/app/services/gallery/gallery_default.pyindex dbb6efb088,0a23717eb8..c5f39feb25--- a/invokeai/app/services/gallery/gallery_default.py+++ b/invokeai/app/services/gallery/gallery_default.py@@@ -432,16 -434,12 +448,20 @@@ class SqliteGalleryService(GalleryServiconditions += f" AND DATE({base_table}.created_at) = ? "params.append(created_date)+ if created_from is not None:+ conditions += f" AND {base_table}.created_at >= ? "+ params.append(created_from)++ if created_to is not None:+ conditions += f" AND {base_table}.created_at < DATE(?, '+1 day') "+ params.append(created_to)+if board_id == "none":- conditions += f" AND {join_table}.board_id IS NULL "+ conditions += f""" AND NOT EXISTS (+ SELECT 1+ FROM {join_table}+ WHERE {join_table}.{name_col} = {base_table}.{name_col}+ ) """if user_id is not None and not is_admin:conditions += f" AND {base_table}.user_id = ? "params.append(user_id)diff --cc invokeai/app/services/image_records/image_records_sqlite.pyindex a4e0f69e6b,a69bb7005d..3664662306--- a/invokeai/app/services/image_records/image_records_sqlite.py+++ b/invokeai/app/services/image_records/image_records_sqlite.py@@@ -25,108 -22,6 +25,181 @@@ from invokeai.app.services.shared.sqlitfrom invokeai.app.services.virtual_boards.virtual_boards_common import VirtualSubBoardDTO+@dataclass(frozen=True)+class _ImageQueryFilters:+ image_origin: Optional[ResourceOrigin] = None+ categories: Optional[list[ImageCategory]] = None+ is_intermediate: Optional[bool] = None+ board_id: Optional[str] = None+ search_term: Optional[str] = None+ created_from: Optional[str] = None+ created_to: Optional[str] = None+ user_id: Optional[str] = None+ is_admin: bool = False+++# Every uncategorized image plus every image on an active (non-archived) board:+# the board_id="all" visibility scope for admins and single-user installs.+_ALL_ACTIVE_BOARDS_CONDITION = """(+ board_images.board_id IS NULL+ OR EXISTS (+ SELECT 1+ FROM boards+ WHERE boards.board_id = board_images.board_id+ AND boards.archived = 0+ )+ )"""++- def _build_image_query_conditions(filters: _ImageQueryFilters) -> tuple[str, list[Union[int, str, bool]]]:- """Build the shared filters for image-list and image-name queries."""++def _build_image_query_conditions(++ filters: _ImageQueryFilters, *, use_board_join: bool = True++) -> tuple[str, list[Union[int, str, bool]]]:++ """Build shared image filters.++++ Paginated DTO queries keep the outer board join because they return board++ data. Names-only queries use correlated membership checks so SQLite can++ scan images directly without multiplying rows or probing a redundant join.++ """+ conditions: list[str] = []+ params: list[Union[int, str, bool]] = []++ if filters.image_origin is not None:+ conditions.append("images.image_origin = ?")+ params.append(filters.image_origin.value)++ if filters.categories is not None:+ category_strings = [category.value for category in set(filters.categories)]+ placeholders = ",".join("?" * len(category_strings))+ conditions.append(f"images.image_category IN ( {placeholders} )")+ params.extend(category_strings)++ if filters.is_intermediate is not None:+ conditions.append("images.is_intermediate = ?")+ params.append(filters.is_intermediate)++ if filters.board_id == "none":- conditions.append("board_images.board_id IS NULL")++ conditions.append(++ "board_images.board_id IS NULL"++ if use_board_join++ else """NOT EXISTS (++ SELECT 1++ FROM board_images++ WHERE board_images.image_name = images.image_name++ )"""++ )+ if filters.user_id is not None and not filters.is_admin:+ conditions.append("images.user_id = ?")+ params.append(filters.user_id)+ elif filters.board_id == "all":- if filters.is_admin:- conditions.append(_ALL_ACTIVE_BOARDS_CONDITION)- elif filters.user_id is not None:++ if use_board_join:++ if filters.is_admin:++ conditions.append(_ALL_ACTIVE_BOARDS_CONDITION)++ elif filters.user_id is not None:++ conditions.append(++ """(++ (board_images.board_id IS NULL AND images.user_id = ?)++ OR EXISTS (++ SELECT 1++ FROM boards++ WHERE boards.board_id = board_images.board_id++ AND boards.archived = 0++ AND (++ boards.user_id = ?++ OR boards.board_visibility IN ('shared', 'public')++ OR EXISTS (++ SELECT 1++ FROM shared_boards++ WHERE shared_boards.board_id = boards.board_id++ AND shared_boards.user_id = ?++ )++ )++ )++ )"""++ )++ params.extend([filters.user_id, filters.user_id, filters.user_id])++ else:++ # Single-user mode has no current user; it reads the administrative scope.++ conditions.append(_ALL_ACTIVE_BOARDS_CONDITION)++ elif filters.is_admin or filters.user_id is None:+ conditions.append(+ """(- (board_images.board_id IS NULL AND images.user_id = ?)++ NOT EXISTS (++ SELECT 1++ FROM board_images++ WHERE board_images.image_name = images.image_name++ )+ OR EXISTS (+ SELECT 1- FROM boards- WHERE boards.board_id = board_images.board_id++ FROM board_images++ INNER JOIN boards ON boards.board_id = board_images.board_id++ WHERE board_images.image_name = images.image_name++ AND boards.archived = 0++ )++ )"""++ )++ else:++ conditions.append(++ """(++ (++ NOT EXISTS (++ SELECT 1++ FROM board_images++ WHERE board_images.image_name = images.image_name++ )++ AND images.user_id = ?++ )++ OR EXISTS (++ SELECT 1++ FROM board_images++ INNER JOIN boards ON boards.board_id = board_images.board_id++ WHERE board_images.image_name = images.image_name+ AND boards.archived = 0+ AND (+ boards.user_id = ?+ OR boards.board_visibility IN ('shared', 'public')+ OR EXISTS (+ SELECT 1+ FROM shared_boards+ WHERE shared_boards.board_id = boards.board_id+ AND shared_boards.user_id = ?+ )+ )+ )+ )"""+ )+ params.extend([filters.user_id, filters.user_id, filters.user_id])- else:- # Single-user mode has no current user; it reads the administrative scope.- conditions.append(_ALL_ACTIVE_BOARDS_CONDITION)+ elif filters.board_id is not None:- conditions.append("board_images.board_id = ?")++ conditions.append(++ "board_images.board_id = ?"++ if use_board_join++ else """EXISTS (++ SELECT 1++ FROM board_images++ WHERE board_images.image_name = images.image_name++ AND board_images.board_id = ?++ )"""++ )+ params.append(filters.board_id)+ elif filters.user_id is not None and not filters.is_admin:+ conditions.append("images.user_id = ?")+ params.append(filters.user_id)++ if filters.search_term:+ conditions.append("(images.metadata LIKE ? OR images.created_at LIKE ?)")+ search_pattern = f"%{filters.search_term.lower()}%"+ params.extend([search_pattern, search_pattern])++ if filters.created_from:+ conditions.append("images.created_at >= ?")+ params.append(filters.created_from)++ if filters.created_to:+ conditions.append("images.created_at < DATE(?, '+1 day')")+ params.append(filters.created_to)++ return "".join(f"\nAND {condition}" for condition in conditions), params++class SqliteImageRecordStorage(ImageRecordStorageBase):def __init__(self, db: SqliteDatabase) -> None:super().__init__()@@@ -500,19 -431,73 +573,20 @@@is_admin: bool = False,) -> ImageNamesResult:with self._db.transaction() as cursor:- # Build query conditions (reused for both starred count and image names queries)- query_conditions = ""- query_params: list[Union[int, str, bool]] = []-- if image_origin is not None:- query_conditions += """--sql- AND images.image_origin = ?- """- query_params.append(image_origin.value)-- if categories is not None:- category_strings = [c.value for c in set(categories)]- placeholders = ",".join("?" * len(category_strings))- query_conditions += f"""--sql- AND images.image_category IN ( {placeholders} )- """- for c in category_strings:- query_params.append(c)-- if is_intermediate is not None:- query_conditions += """--sql- AND images.is_intermediate = ?- """- query_params.append(is_intermediate)-- if board_id == "none":- query_conditions += """--sql- AND NOT EXISTS (- SELECT 1- FROM board_images- WHERE board_images.image_name = images.image_name- )- """- # For uncategorized images, filter by user_id to ensure per-user isolation- # Admin users can see all uncategorized images from all users- if user_id is not None and not is_admin:- query_conditions += """--sql- AND images.user_id = ?- """- query_params.append(user_id)- elif board_id is not None:- query_conditions += """--sql- AND EXISTS (- SELECT 1- FROM board_images- WHERE board_images.image_name = images.image_name- AND board_images.board_id = ?- )- """- query_params.append(board_id)- elif user_id is not None and not is_admin:- # No board_id supplied — still enforce per-user isolation so- # non-admins cannot enumerate other users' images- query_conditions += """--sql- AND images.user_id = ?- """- query_params.append(user_id)-- if search_term:- query_conditions += """--sql- AND (- images.metadata LIKE ?- OR images.created_at LIKE ?- )- """- query_params.append(f"%{search_term.lower()}%")- query_params.append(f"%{search_term.lower()}%")+ query_conditions, query_params = _build_image_query_conditions(+ _ImageQueryFilters(+ image_origin=image_origin,+ categories=categories,+ is_intermediate=is_intermediate,+ board_id=board_id,+ search_term=search_term,+ created_from=created_from,+ created_to=created_to,+ user_id=user_id,+ is_admin=is_admin,- )++ ),++ use_board_join=False,+ )# Get starred count if starred_first is enabledstarred_count = 0diff --cc invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.tsindex 1ec8e181d8,0000000000..76d9855b31mode 100644,000000..100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts@@@ -1,1053 -1,0 +1,1124 @@@+import { describe, expect, it } from 'vitest';++import type {+ ComponentModelConfig,+ GenerateModelConfig,+ GenerateSettings,+ LoraModelConfig,+ MainModelConfig,+ VaeModelConfig,+} from './types';++import {+ BASE_GENERATION,+ coerceSchedulerForGraph,+ getComponentSectionPolicy,+ getAutoFlux2ComponentSourceModel,+ getDefaultGenerateSettings,+ getGenerateModelSelectionResult,+ getGenerationDimensions,+ getGenerationModelAvailabilityReasons,+ getGenerationModelPolicy,+ getGenerationValidationReasons,+ getMaxReferenceImages,+ getPromptPolicy,+ getSettingsWithModelDefaults,+ isReferenceImageSupported,+ isSupportedGenerateModel,+ SUPPORTED_GENERATE_BASES,+} from './baseGenerationPolicies';++const createModel = (base: string, overrides: Partial<MainModelConfig> = {}): MainModelConfig => ({+ base,+ key: `${base}-model`,+ name: `${base} model`,+ type: 'main',+ ...overrides,+});++const createSettings = (model: GenerateModelConfig, overrides: Partial<GenerateSettings> = {}): GenerateSettings => ({+ ...getDefaultGenerateSettings(model),+ seed: 1,+ shouldRandomizeSeed: false,+ ...overrides,+});++const t5Encoder: ComponentModelConfig = { base: 'any', key: 't5', name: 'T5 Encoder', type: 't5_encoder' };+const clipEmbed: ComponentModelConfig = { base: 'any', key: 'clip', name: 'CLIP Embed', type: 'clip_embed' };++const mistralEncoder: ComponentModelConfig = {++ base: 'any',++ key: 'mistral',++ name: 'Mistral Encoder',++ type: 'mistral_encoder',++};+const qwenVlEncoder: ComponentModelConfig = {+ base: 'any',+ key: 'qwen-vl',+ name: 'Qwen VL Encoder',+ type: 'qwen_vl_encoder',+};+const qwen3Encoder: ComponentModelConfig = {+ base: 'any',+ key: 'qwen3',+ name: 'Qwen3 Encoder',+ type: 'qwen3_encoder',+ variant: 'qwen3_8b',+};+const animaQwen3Encoder: ComponentModelConfig = {+ base: 'any',+ key: 'anima-qwen3',+ name: 'Anima Qwen3 Encoder',+ type: 'qwen3_encoder',+ variant: 'qwen3_06b',+};+const fluxVae: VaeModelConfig = { base: 'flux', key: 'flux-vae', name: 'FLUX VAE', type: 'vae' };+const flux2Vae: VaeModelConfig = { base: 'flux2', key: 'flux2-vae', name: 'FLUX.2 VAE', type: 'vae' };+const qwenImageVae: VaeModelConfig = { base: 'qwen-image', key: 'qwen-vae', name: 'Qwen VAE', type: 'vae' };+const sdxlVae: VaeModelConfig = { base: 'sdxl', key: 'sdxl-vae', name: 'SDXL VAE', type: 'vae' };+const sd1Lora: LoraModelConfig = { base: 'sd-1', key: 'sd1-lora', name: 'SD 1 LoRA', type: 'lora' };+const sdxlLora: LoraModelConfig = { base: 'sdxl', key: 'sdxl-lora', name: 'SDXL LoRA', type: 'lora' };+const sd1IpAdapter: ComponentModelConfig = {+ base: 'sd-1',+ key: 'sd1-ip-adapter',+ name: 'SD 1 IP Adapter',+ type: 'ip_adapter',+};+const sdxlIpAdapter: ComponentModelConfig = {+ base: 'sdxl',+ key: 'sdxl-ip-adapter',+ name: 'SDXL IP Adapter',+ type: 'ip_adapter',+};+const referenceImage = {+ original: { image: { height: 768, image_name: 'reference.png', width: 512 } },+};+const externalModel: GenerateModelConfig = {+ base: 'external',+ capabilities: { modes: ['txt2img'], supports_negative_prompt: false, supports_seed: false },+ format: 'external_api',+ key: 'external-model',+ name: 'External Model',+ provider_id: 'openai',+ type: 'external_image_generator',+};++describe('BASE_GENERATION', () => {+ it('matches expected dimensions per base', () => {+ expect(getGenerationDimensions(createModel('sd-1'))).toMatchObject({ grid: 8, optimal: 512 });+ expect(getGenerationDimensions(createModel('sdxl'))).toMatchObject({ grid: 8, optimal: 1024 });+ expect(getGenerationDimensions(createModel('flux2'))).toMatchObject({ grid: 16, optimal: 1024 });+ expect(getGenerationDimensions(createModel('cogview4'))).toMatchObject({ grid: 32, optimal: 1024 });+ });++ it('matches expected defaults per base', () => {+ expect(getDefaultGenerateSettings(createModel('sdxl'))).toMatchObject({+ steps: 30,+ cfgScale: 7,+ scheduler: 'euler_a',+ width: 1024,+ height: 1024,+ });+ expect(getDefaultGenerateSettings(createModel('flux'))).toMatchObject({+ steps: 4,+ cfgScale: 4,+ scheduler: 'euler',+ });+ expect(getDefaultGenerateSettings(createModel('flux2'))).toMatchObject({+ steps: 4,+ cfgScale: 1,+ scheduler: 'euler',+ });+ expect(getDefaultGenerateSettings(createModel('qwen-image'))).toMatchObject({+ steps: 40,+ cfgScale: 4,+ scheduler: 'euler_a',+ });+ expect(getDefaultGenerateSettings(createModel('z-image'))).toMatchObject({+ steps: 8,+ cfgScale: 1,+ scheduler: 'euler',+ });+ });++ it('matches expected scheduler sets per base', () => {+ const flux = createModel('flux');+ const zbase = createModel('z-image', { variant: 'zbase' });+ const anima = createModel('anima');++ expect(+ getGenerationModelPolicy(createModel('sdxl'), createSettings(createModel('sdxl'))).scheduler.options.map(+ (option) => option.value+ )+ ).toContain('euler_a');+ expect(+ getGenerationModelPolicy(flux, createSettings(flux)).scheduler.options.map((option) => option.value)+ ).toEqual(['euler', 'heun', 'lcm']);+ expect(+ getGenerationModelPolicy(zbase, createSettings(zbase)).scheduler.options.map((option) => option.value)+ ).toEqual(['euler', 'heun']);+ expect(+ getGenerationModelPolicy(anima, createSettings(anima)).scheduler.options.map((option) => option.value)+ ).toEqual(['euler', 'heun', 'dpmpp_2m', 'dpmpp_2m_sde', 'er_sde', 'lcm']);+ expect(coerceSchedulerForGraph(zbase, 'lcm')).toBe('euler');+ });++ it('matches expected prompt policy per base', () => {+ expect(getPromptPolicy(createModel('flux'), { cfgScale: 4, negativePromptEnabled: true })).toMatchObject({+ negativeVisible: false,+ negativeUsedInGraph: false,+ });+ expect(getPromptPolicy(createModel('sdxl'), { cfgScale: 1, negativePromptEnabled: true })).toMatchObject({+ negativeVisible: true,+ negativeUsedInGraph: true,+ });+ expect(getPromptPolicy(createModel('sdxl'), { cfgScale: 1, negativePromptEnabled: false })).toMatchObject({+ negativeVisible: true,+ negativeUsedInGraph: false,+ });+ expect(getPromptPolicy(createModel('qwen-image'), { cfgScale: 1, negativePromptEnabled: true })).toMatchObject({+ negativeVisible: true,+ negativeUsedInGraph: false,+ });+ expect(getPromptPolicy(createModel('qwen-image'), { cfgScale: 2, negativePromptEnabled: true })).toMatchObject({+ negativeVisible: true,+ negativeUsedInGraph: true,+ negativeHelpText: 'Used only when CFG is greater than 1.',+ });+ expect(getPromptPolicy(externalModel, { cfgScale: 7, negativePromptEnabled: true })).toMatchObject({+ negativeVisible: false,+ negativeUsedInGraph: false,+ });+ expect(+ getPromptPolicy(+ { ...externalModel, capabilities: { supports_negative_prompt: true } },+ { cfgScale: 7, negativePromptEnabled: true }+ )+ ).toMatchObject({ negativeVisible: true, negativeUsedInGraph: true });+ });++ it('matches expected UI availability per base', () => {+ expect(getGenerationModelPolicy(createModel('sd-1'), createSettings(createModel('sd-1'))).ui).toMatchObject({+ clipSkipMax: 12,+ cfgRescaleVisible: true,+ hiDiffusionVisible: true,+ schedulerVisible: true,+ });+ expect(getGenerationModelPolicy(createModel('sd-2'), createSettings(createModel('sd-2'))).ui).toMatchObject({+ clipSkipMax: 24,+ cfgRescaleVisible: true,+ hiDiffusionVisible: false,+ });+ expect(getGenerationModelPolicy(createModel('sdxl'), createSettings(createModel('sdxl'))).ui).toMatchObject({+ hiDiffusionVisible: true,+ });+ expect(getGenerationModelPolicy(createModel('flux'), createSettings(createModel('flux'))).ui).toMatchObject({+ guidanceLabel: 'Guidance',+ hiDiffusionVisible: false,+ schedulerVisible: true,+ clipSkipMax: null,+ });+ expect(getGenerationModelPolicy(createModel('sd-3'), createSettings(createModel('sd-3'))).ui).toMatchObject({+ schedulerVisible: false,+ sdVaeVisible: false,+ });+ expect(+ getGenerationModelPolicy(createModel('qwen-image'), createSettings(createModel('qwen-image'))).ui.schedulerVisible+ ).toBe(false);+ expect(getGenerationModelPolicy(externalModel, createSettings(externalModel)).ui.seedVisible).toBe(false);+ expect(+ getGenerationModelPolicy(+ { ...externalModel, capabilities: { supports_seed: true } },+ createSettings(externalModel)+ ).ui.seedVisible+ ).toBe(true);+ });++ it('has generation config for every graph builder base', () => {+ expect(SUPPORTED_GENERATE_BASES).toEqual([+ 'sd-1',+ 'sd-2',+ 'sdxl',+ 'sd-3',+ 'flux',+ 'flux2',+ 'cogview4',+ 'qwen-image',+ 'z-image',+ 'ideogram-4',+ 'krea-2',+ 'wan',+ 'anima',+ ]);+ });++ it('does not mark display-only bases as generatable', () => {+ expect(isSupportedGenerateModel(createModel('sdxl-refiner'))).toBe(false);+ expect(isSupportedGenerateModel(createModel('unknown'))).toBe(false);+ expect(isSupportedGenerateModel(createModel('made-up'))).toBe(false);+ expect(BASE_GENERATION).not.toHaveProperty('external');+ });+});++describe('component policies', () => {+ it('validates FLUX T5, CLIP embed, and VAE requirements', () => {+ const model = createModel('flux');++ expect(getGenerationValidationReasons(model, createSettings(model))).toEqual([+ 'Generate needs a T5 Encoder for FLUX models.',+ 'Generate needs a CLIP Embed model for FLUX models.',+ 'Generate needs a VAE for FLUX models.',+ ]);+ expect(+ getGenerationValidationReasons(+ model,+ createSettings(model, { clipEmbedModel: clipEmbed, t5EncoderModel: t5Encoder, vae: fluxVae })+ )+ ).toEqual([]);+ expect(+ getGenerationValidationReasons(+ model,+ createSettings(model, {+ clipEmbedModel: t5Encoder,+ t5EncoderModel: clipEmbed,+ vae: fluxVae,+ })+ )+ ).toEqual(['Generate needs a T5 Encoder for FLUX models.', 'Generate needs a CLIP Embed model for FLUX models.']);+ });++ it('rejects unsupported FLUX dev_fill variant', () => {+ const model = createModel('flux', { variant: 'dev_fill' });++ expect(+ getGenerationValidationReasons(+ model,+ createSettings(model, { clipEmbedModel: clipEmbed, t5EncoderModel: t5Encoder, vae: fluxVae })+ )+ ).toEqual(['FLUX Fill models do not support text-to-image generation.']);+ });++ it('validates FLUX.2 Qwen3 and VAE requirements and allows bundled alternatives', () => {+ const model = createModel('flux2', { format: 'gguf_quantized', variant: 'klein_9b' });+ const source = createModel('flux2', { format: 'diffusers', variant: 'klein_9b' });+ const incompatibleSource = createModel('flux2', {+ format: 'diffusers',+ key: 'flux2-4b-source',+ variant: 'klein_4b',+ });++ expect(getGenerationValidationReasons(model, createSettings(model))).toEqual([+ 'Generate needs a Qwen3 Encoder for non-Diffusers FLUX.2 models.',+ 'Generate needs a VAE for non-Diffusers FLUX.2 models.',+ ]);+ expect(getGenerationValidationReasons(model, createSettings(model, { componentSourceModel: source }))).toEqual([]);+ expect(+ getGenerationValidationReasons(model, createSettings(model, { componentSourceModel: incompatibleSource }))+ ).toEqual(['Generate needs a Qwen3 Encoder for non-Diffusers FLUX.2 models.']);+ expect(+ getGenerationValidationReasons(model, createSettings(model, { qwen3EncoderModel: qwen3Encoder, vae: flux2Vae }))+ ).toEqual([]);+ });+++ it('validates FLUX.2 [dev] Mistral and VAE requirements and allows bundled alternatives', () => {++ const model = createModel('flux2', { format: 'gguf_quantized', variant: 'dev' });++ const source = createModel('flux2', { format: 'diffusers', key: 'flux2-dev-source', variant: 'dev' });++ const kleinSource = createModel('flux2', {++ format: 'diffusers',++ key: 'flux2-klein-source',++ variant: 'klein_9b',++ });++++ expect(getGenerationValidationReasons(model, createSettings(model))).toEqual([++ 'Generate needs a Mistral Encoder for non-Diffusers FLUX.2 [dev] models.',++ 'Generate needs a VAE for non-Diffusers FLUX.2 models.',++ ]);++ expect(getGenerationValidationReasons(model, createSettings(model, { componentSourceModel: source }))).toEqual([]);++ expect(getGenerationValidationReasons(model, createSettings(model, { componentSourceModel: kleinSource }))).toEqual(++ ['Generate needs a Mistral Encoder for non-Diffusers FLUX.2 [dev] models.']++ );++ expect(++ getGenerationValidationReasons(++ model,++ createSettings(model, { mistralEncoderModel: mistralEncoder, vae: flux2Vae })++ )++ ).toEqual([]);++ expect(getComponentSectionPolicy(model, createSettings(model)).slots.map((slot) => slot.key)).toEqual([++ 'mistralEncoderModel',++ 'vae',++ 'pidDecoderModel',++ 'gemma2EncoderModel',++ ]);++ });+++ it('keeps FLUX.2 component source hidden and auto-selects installed Diffusers sources', () => {+ const model = createModel('flux2', { format: 'gguf_quantized', variant: 'klein_9b' });+ const source = createModel('flux2', { format: 'diffusers', variant: 'klein_9b' });+ const incompatibleSource = createModel('flux2', {+ format: 'diffusers',+ key: 'flux2-4b-source',+ variant: 'klein_4b',+ });+ const settings = createSettings(model);++ // FLUX.2 supports PiD, so its two slots follow the base's own components.+ expect(getComponentSectionPolicy(model, settings).slots.map((slot) => slot.key)).toEqual([+ 'qwen3EncoderModel',+ 'vae',+ 'pidDecoderModel',+ 'gemma2EncoderModel',+ ]);+ expect(getAutoFlux2ComponentSourceModel(model, settings, [incompatibleSource, source])?.key).toBe(source.key);+ expect(+ getAutoFlux2ComponentSourceModel(model, { ...settings, qwen3EncoderModel: qwen3Encoder }, [incompatibleSource])+ ?.key+ ).toBe(incompatibleSource.key);+ });++ it('validates Qwen Image Qwen-VL and VAE requirements', () => {+ const model = createModel('qwen-image', { format: 'checkpoint' });++ expect(getGenerationValidationReasons(model, createSettings(model))).toEqual([+ 'Generate needs a Qwen VL Encoder for non-Diffusers Qwen Image models.',+ 'Generate needs a VAE for non-Diffusers Qwen Image models.',+ ]);+ expect(+ getGenerationValidationReasons(+ model,+ createSettings(model, { qwenVLEncoderModel: qwenVlEncoder, vae: qwenImageVae })+ )+ ).toEqual([]);+ });++ it('validates Z-Image non-anima Qwen3 and flux VAE requirements', () => {+ const model = createModel('z-image', { format: 'checkpoint' });++ expect(getGenerationValidationReasons(model, createSettings(model))).toEqual([+ 'Generate needs a Qwen3 Encoder for Z-Image models.',+ 'Generate needs a VAE for Z-Image models.',+ ]);+ expect(+ getGenerationValidationReasons(model, createSettings(model, { qwen3EncoderModel: qwen3Encoder, vae: fluxVae }))+ ).toEqual([]);+ });++ it('validates Anima Qwen3 and allowed VAE bases', () => {+ const model = createModel('anima');++ expect(getGenerationValidationReasons(model, createSettings(model))).toEqual([+ 'Generate needs a Qwen3 Encoder for Anima models.',+ 'Generate needs a VAE for Anima models.',+ ]);+ expect(+ getGenerationValidationReasons(+ model,+ createSettings(model, { qwen3EncoderModel: animaQwen3Encoder, vae: qwenImageVae })+ )+ ).toEqual([]);+ });++ it('validates dimensions against bounds and model-family grid', () => {+ const model = createModel('flux2');++ expect(getGenerationValidationReasons(model, createSettings(model, { width: 0 }))).toContain(+ 'Generate width must be between 64 and 4096.'+ );+ expect(getGenerationValidationReasons(model, createSettings(model, { height: 4104 }))).toContain(+ 'Generate height must be between 64 and 4096.'+ );+ expect(getGenerationValidationReasons(model, createSettings(model, { height: 888 }))).toContain(+ 'Generate height must be a multiple of 16.'+ );+ });++ it('rejects external image generators without a registered invocation node', () => {+ const model: GenerateModelConfig = {+ base: 'external',+ capabilities: { modes: ['txt2img'] },+ format: 'external_api',+ key: 'external-unknown',+ name: 'Unknown External Provider',+ provider_id: 'future-provider',+ type: 'external_image_generator',+ };++ expect(getGenerationValidationReasons(model, createSettings(model))).toContain(+ "No invocation node registered for external provider 'future-provider'."+ );+ });++ it('renders no component slots for bases without extra requirements', () => {+ expect(getComponentSectionPolicy(createModel('cogview4'), createSettings(createModel('cogview4'))).slots).toEqual(+ []+ );+ });++ it('offers only the PiD slots for a PiD-capable base with no other components', () => {+ // SDXL needs no encoders or VAE of its own, but it can decode through PiD, so the two+ // PiD slots are offered (and are only *required* once PiD is switched on).+ const model = createModel('sdxl');++ expect(getComponentSectionPolicy(model, createSettings(model)).slots.map((slot) => slot.key)).toEqual([+ 'pidDecoderModel',+ 'gemma2EncoderModel',+ ]);+ });++ it('does not offer PiD slots for a base with no PiD decode node', () => {+ const model = createModel('cogview4');++ expect(getComponentSectionPolicy(model, createSettings(model)).slots).toEqual([]);+ });++ it('clears incompatible selections when the selected model changes', () => {+ const model = createModel('sdxl');+ const settings = createSettings(createModel('sd-1'), {+ cfgRescaleMultiplier: 0.5,+ clipSkip: 2,+ loras: [+ { isEnabled: true, model: sd1Lora, weight: 1 },+ { isEnabled: true, model: sdxlLora, weight: 1 },+ ],+ seamlessXAxis: true,+ t5EncoderModel: t5Encoder,+ vae: sdxlVae,+ });++ const result = getGenerateModelSelectionResult({ currentValues: settings, model, models: [] });++ expect(result.settings.modelKey).toBe(model.key);+ expect(result.settings.loras.map((lora) => lora.model.key)).toEqual(['sdxl-lora']);+ expect(result.settings.vae).toEqual(sdxlVae);+ expect(result.settings.t5EncoderModel).toBeNull();+ expect(result.settings.clipSkip).toBe(0);+ expect(result.settings.cfgRescaleMultiplier).toBe(0);+ expect(result.settings.seamlessXAxis).toBe(true);+ expect(result.clearedLabels).toEqual(['LoRAs', 'T5 Encoder', 'CLIP skip', 'CFG rescale']);+ });++ it('turns HiDiffusion off when changing to an unsupported model family', () => {+ const result = getGenerateModelSelectionResult({+ currentValues: createSettings(createModel('sd-1'), { hiDiffusionEnabled: true }),+ model: createModel('flux'),+ models: [],+ });++ expect(result.settings.hiDiffusionEnabled).toBe(false);+ expect(result.clearedLabels).toContain('HiDiffusion');+ });++ it('initializes empty and malformed values from the selected model defaults', () => {+ const model = createModel('cogview4', { default_settings: { steps: 17 } });++ for (const currentValues of [{}, { batchCount: 8 }]) {+ const result = getGenerateModelSelectionResult({ currentValues, model, models: [] });++ expect(result.settings).toMatchObject({+ batchCount: 1,+ height: 1024,+ modelKey: model.key,+ steps: 17,+ width: 1024,+ });+ expect(result.clearedLabels).toEqual([]);+ }+ });++ it('preserves model-independent and compatible settings across a model selection', () => {+ const model = createModel('sdxl', { key: 'sdxl-other' });+ const settings = createSettings(createModel('sdxl'), {+ batchCount: 4,+ negativePrompt: 'blurry',+ positivePrompt: 'a lighthouse',+ seed: 1234,+ shouldRandomizeSeed: false,+ vae: sdxlVae,+ });++ const result = getGenerateModelSelectionResult({ currentValues: settings, model, models: [] });++ expect(result.settings).toMatchObject({+ batchCount: 4,+ modelKey: model.key,+ negativePrompt: 'blurry',+ positivePrompt: 'a lighthouse',+ seed: 1234,+ shouldRandomizeSeed: false,+ vae: sdxlVae,+ });+ expect(result.clearedLabels).toEqual([]);+ });++ it('applies automatic FLUX.2 component sources as part of model selection', () => {+ const model = createModel('flux2', { format: 'gguf_quantized', variant: 'klein_9b' });+ const source = createModel('flux2', { format: 'diffusers', key: 'flux2-source', variant: 'klein_9b' });++ const result = getGenerateModelSelectionResult({+ currentValues: createSettings(createModel('sdxl')),+ model,+ models: [source],+ });++ expect(result.settings.componentSourceModel).toBe(source);+ });+++ it('auto-selects a matching FLUX.2 [dev] source and rejects Klein sources', () => {++ const model = createModel('flux2', { format: 'gguf_quantized', variant: 'dev' });++ const devSource = createModel('flux2', { format: 'diffusers', key: 'flux2-dev-source', variant: 'dev' });++ const kleinSource = createModel('flux2', { format: 'diffusers', key: 'flux2-klein-source', variant: 'klein_9b' });++++ const result = getGenerateModelSelectionResult({++ currentValues: createSettings(createModel('sdxl')),++ model,++ models: [kleinSource, devSource],++ });++++ expect(result.settings.componentSourceModel).toBe(devSource);++ });+++ it('reconciles dimensions to the new model grid when the selected model changes', () => {+ const model = createModel('cogview4');+ const settings = createSettings(createModel('sdxl'), { height: 520, width: 520 });+ const result = getGenerateModelSelectionResult({ currentValues: settings, model, models: [] });++ expect(result.settings.width).toBe(512);+ expect(result.settings.height).toBe(512);+ expect(result.clearedLabels).toContain('Dimensions');+ });++ it('keeps selected VAE when applying model defaults without a VAE override', () => {+ const model = createModel('sdxl', { default_settings: { steps: 12 } });+ const settings = createSettings(model, { vae: sdxlVae });+ const nextSettings = getSettingsWithModelDefaults(settings, model);++ expect(nextSettings.steps).toBe(12);+ expect(nextSettings.vae).toBe(sdxlVae);+ });++ it('reports selected model records that disappeared from the backend model list', () => {+ const model = createModel('flux');+ const settings = createSettings(model, {+ clipEmbedModel: clipEmbed,+ loras: [{ isEnabled: true, model: sd1Lora, weight: 1 }],+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ });++ expect(getGenerationModelAvailabilityReasons(model, settings, [model as never, t5Encoder as never])).toEqual([+ 'CLIP Embed "CLIP Embed" is no longer installed.',+ 'VAE "FLUX VAE" is no longer installed.',+ 'LoRA "SD 1 LoRA" is no longer installed.',+ ]);+ });++ it('clears same-base FLUX.2 component selections that do not match the new variant', () => {+ const model = createModel('flux2', { format: 'gguf_quantized', variant: 'klein_9b' });+ const incompatibleQwen3: ComponentModelConfig = {+ base: 'any',+ key: 'qwen3-4b',+ name: 'Qwen3 4B Encoder',+ type: 'qwen3_encoder',+ variant: 'qwen3_4b',+ };+ const settings = createSettings(createModel('flux2', { format: 'gguf_quantized', variant: 'klein_4b' }), {+ qwen3EncoderModel: incompatibleQwen3,+ vae: flux2Vae,+ });++ const result = getGenerateModelSelectionResult({ currentValues: settings, model, models: [] });++ expect(result.settings.qwen3EncoderModel).toBeNull();+ expect(result.settings.vae).toEqual(flux2Vae);+ expect(result.clearedLabels).toEqual(['Qwen3 Encoder']);+ });+++ it('clears Klein and dev encoders when switching FLUX.2 variants', () => {++ const devModel = createModel('flux2', { format: 'gguf_quantized', variant: 'dev' });++ const kleinModel = createModel('flux2', { format: 'gguf_quantized', variant: 'klein_9b' });++ const toDev = getGenerateModelSelectionResult({++ currentValues: createSettings(kleinModel, { qwen3EncoderModel: qwen3Encoder, vae: flux2Vae }),++ model: devModel,++ models: [],++ });++ const toKlein = getGenerateModelSelectionResult({++ currentValues: createSettings(devModel, { mistralEncoderModel: mistralEncoder, vae: flux2Vae }),++ model: kleinModel,++ models: [],++ });++++ expect(toDev.settings.qwen3EncoderModel).toBeNull();++ expect(toDev.clearedLabels).toContain('Qwen3 Encoder');++ expect(toKlein.settings.mistralEncoderModel).toBeNull();++ expect(toKlein.clearedLabels).toContain('Mistral Encoder');++ });+++ it('requires enabled IP Adapter reference images to have an image and compatible adapter model', () => {+ const model = createModel('sd-1');++ expect(+ getGenerationValidationReasons(+ model,+ createSettings(model, {+ referenceImages: [+ {+ id: 'ref-1',+ isEnabled: true,+ config: {+ beginEndStepPct: [0, 1],+ clipVisionModel: 'ViT-H',+ image: null,+ method: 'full',+ model: sd1IpAdapter,+ type: 'ip_adapter',+ weight: 1,+ },+ },+ ],+ })+ )+ ).toContain('Reference Image #1 needs an image.');++ expect(+ getGenerationValidationReasons(+ model,+ createSettings(model, {+ referenceImages: [+ {+ id: 'ref-1',+ isEnabled: true,+ config: {+ beginEndStepPct: [0, 1],+ clipVisionModel: 'ViT-H',+ image: referenceImage,+ method: 'full',+ model: null,+ type: 'ip_adapter',+ weight: 1,+ },+ },+ ],+ })+ )+ ).toContain('Reference Image #1 needs a compatible IP Adapter model.');+ });++ it('clears reference images when switching to a model without reference image support', () => {+ const settings = createSettings(createModel('sdxl'), {+ referenceImages: [+ {+ id: 'ref-1',+ isEnabled: true,+ config: {+ beginEndStepPct: [0, 1],+ clipVisionModel: 'ViT-H',+ image: referenceImage,+ method: 'full',+ model: sdxlIpAdapter,+ type: 'ip_adapter',+ weight: 1,+ },+ },+ ],+ });++ const result = getGenerateModelSelectionResult({+ currentValues: settings,+ model: createModel('cogview4'),+ models: [sdxlIpAdapter],+ });++ expect(result.settings.referenceImages).toEqual([]);+ expect(result.clearedLabels).toContain('Reference Images');+ });++ it('re-targets reference image configs to the new model base, keeping the image and enabled state', () => {+ const settings = createSettings(createModel('sdxl'), {+ referenceImages: [+ {+ id: 'ref-1',+ isEnabled: false,+ config: {+ beginEndStepPct: [0, 1],+ clipVisionModel: 'ViT-H',+ image: referenceImage,+ method: 'style',+ model: sdxlIpAdapter,+ type: 'ip_adapter',+ weight: 0.5,+ },+ },+ ],+ });++ const result = getGenerateModelSelectionResult({+ currentValues: settings,+ model: createModel('sd-1'),+ models: [sd1IpAdapter, sdxlIpAdapter],+ });++ expect(result.settings.referenceImages).toEqual([+ {+ id: 'ref-1',+ isEnabled: false,+ config: {+ beginEndStepPct: [0, 1],+ clipVisionModel: 'ViT-H',+ image: referenceImage,+ method: 'full',+ model: sd1IpAdapter,+ type: 'ip_adapter',+ weight: 1,+ },+ },+ ]);+ expect(result.clearedLabels).toContain('Reference Images');+ });++ it('re-targets reference images across a flux2 -> sdxl -> flux2 round trip', () => {+ const flux2Model = createModel('flux2');+ const sdxlModel = createModel('sdxl');+ const settings = createSettings(flux2Model, {+ referenceImages: [+ { id: 'ref-1', isEnabled: true, config: { image: referenceImage, type: 'flux2_reference_image' } },+ ],+ });++ const toSdxl = getGenerateModelSelectionResult({+ currentValues: settings,+ model: sdxlModel,+ models: [sdxlIpAdapter],+ });++ expect(toSdxl.settings.referenceImages[0]?.config).toMatchObject({+ image: referenceImage,+ model: sdxlIpAdapter,+ type: 'ip_adapter',+ });++ const backToFlux2 = getGenerateModelSelectionResult({+ currentValues: toSdxl.settings,+ model: flux2Model,+ models: [sdxlIpAdapter],+ });++ expect(backToFlux2.settings.referenceImages).toEqual([+ { id: 'ref-1', isEnabled: true, config: { image: referenceImage, type: 'flux2_reference_image' } },+ ]);+ });++ it('keeps compatible reference images untouched when the selected model changes', () => {+ const referenceImages: GenerateSettings['referenceImages'] = [+ {+ id: 'ref-1',+ isEnabled: true,+ config: {+ beginEndStepPct: [0, 1],+ clipVisionModel: 'ViT-H',+ image: referenceImage,+ method: 'full',+ model: sdxlIpAdapter,+ type: 'ip_adapter',+ weight: 1,+ },+ },+ ];+ const settings = createSettings(createModel('sdxl'), { referenceImages });++ const result = getGenerateModelSelectionResult({+ currentValues: settings,+ model: createModel('sdxl', { key: 'sdxl-other' }),+ models: [sdxlIpAdapter],+ });++ expect(result.settings.referenceImages).toBe(referenceImages);+ expect(result.clearedLabels).not.toContain('Reference Images');+ });++ it('reports reference image support per model', () => {+ expect(isReferenceImageSupported(createModel('sdxl'))).toBe(true);+ expect(isReferenceImageSupported(createModel('cogview4'))).toBe(false);+ expect(isReferenceImageSupported(createModel('qwen-image'))).toBe(false);+ expect(isReferenceImageSupported(createModel('qwen-image', { variant: 'edit' }))).toBe(true);+ expect(isReferenceImageSupported(externalModel)).toBe(false);+ expect(+ isReferenceImageSupported({+ ...externalModel,+ capabilities: { ...externalModel.capabilities, supports_reference_images: true },+ })+ ).toBe(true);+ expect(isReferenceImageSupported(undefined)).toBe(false);+ });++ it('derives the reference image limit from external provider capabilities', () => {+ expect(getMaxReferenceImages(createModel('sdxl'))).toBe(5);+ expect(getMaxReferenceImages(createModel('cogview4'))).toBe(0);+ expect(+ getMaxReferenceImages({+ ...externalModel,+ capabilities: { ...externalModel.capabilities, max_reference_images: 14, supports_reference_images: true },+ })+ ).toBe(14);+ expect(+ getMaxReferenceImages({+ ...externalModel,+ capabilities: { ...externalModel.capabilities, supports_reference_images: true },+ })+ ).toBe(5);+ });++ it('rejects unsupported reference image configs for the selected model', () => {+ const model = createModel('sd-3');++ expect(+ getGenerationValidationReasons(+ model,+ createSettings(model, {+ referenceImages: [+ { id: 'ref-1', isEnabled: true, config: { image: referenceImage, type: 'flux2_reference_image' } },+ ],+ })+ )+ ).toContain('Reference Image #1 is not supported by sd-3 model.');+ });++ it('reports missing reference image model dependencies', () => {+ const model = createModel('sd-1');++ expect(+ getGenerationModelAvailabilityReasons(+ model,+ createSettings(model, {+ referenceImages: [+ {+ id: 'ref-1',+ isEnabled: true,+ config: {+ beginEndStepPct: [0, 1],+ clipVisionModel: 'ViT-H',+ image: referenceImage,+ method: 'full',+ model: sd1IpAdapter,+ type: 'ip_adapter',+ weight: 1,+ },+ },+ ],+ }),+ [model as never]+ )+ ).toContain('Reference Image model "SD 1 IP Adapter" is no longer installed.');+ });++ it('ignores missing reference image model dependencies when the reference image is disabled', () => {+ const model = createModel('sd-1');++ expect(+ getGenerationModelAvailabilityReasons(+ model,+ createSettings(model, {+ referenceImages: [+ {+ id: 'ref-1',+ isEnabled: false,+ config: {+ beginEndStepPct: [0, 1],+ clipVisionModel: 'ViT-H',+ image: referenceImage,+ method: 'full',+ model: sd1IpAdapter,+ type: 'ip_adapter',+ weight: 1,+ },+ },+ ],+ }),+ [model as never]+ )+ ).toEqual([]);+ });+});++describe('Krea-2, Ideogram 4 and Wan policies', () => {+ const krea2Vae: VaeModelConfig = { base: 'qwen-image', key: 'krea2-vae', name: 'Qwen VAE', type: 'vae' };+ const qwen3VlEncoder: ComponentModelConfig = {+ base: 'any',+ key: 'qwen3-vl',+ name: 'Qwen3-VL',+ type: 'qwen3_vl_encoder',+ };+ const wanVae: VaeModelConfig = { base: 'wan', key: 'wan-vae', name: 'Wan VAE', type: 'vae' };+ const wanT5Encoder: ComponentModelConfig = { base: 'any', key: 'wan-t5', name: 'Wan T5', type: 'wan_t5_encoder' };++ it('uses a 16px grid for all three, matching their transformer patch sizes', () => {+ expect(getGenerationDimensions(createModel('krea-2'))).toMatchObject({ grid: 16, optimal: 1024 });+ expect(getGenerationDimensions(createModel('ideogram-4'))).toMatchObject({ grid: 16, optimal: 1024 });+ expect(getGenerationDimensions(createModel('wan'))).toMatchObject({ grid: 16, optimal: 1024 });+ });++ it('rejects Ideogram 4 dimensions that are not multiples of 16', () => {+ const model = createModel('ideogram-4');+ const reasons = getGenerationValidationReasons(model, createSettings(model, { height: 1020, width: 1000 }));++ expect(reasons).toContain('Generate width must be a multiple of 16.');+ expect(reasons).toContain('Generate height must be a multiple of 16.');+ });++ it('accepts a Qwen-Image VAE registered under the anima base, as the backend loader does', () => {+ // The same physical Qwen-Image VAE is registered as `anima` or `qwen-image` depending on+ // which family it was installed for, and krea2_model_loader declares+ // ui_model_base=[QwenImage, Anima]. Accepting only `qwen-image` hid a working VAE.+ const animaRegisteredVae: VaeModelConfig = {+ base: 'anima',+ key: 'anima-qwen-vae',+ name: 'Qwen VAE (installed for Anima)',+ type: 'vae',+ };+ const checkpoint = createModel('krea-2', { format: 'checkpoint' });+ const settings = createSettings(checkpoint, {+ qwen3VLEncoderModel: qwen3VlEncoder,+ vae: animaRegisteredVae,+ });++ expect(getGenerationValidationReasons(checkpoint, settings)).toEqual([]);++ const slots = getComponentSectionPolicy(checkpoint, settings).slots;+ const vaeSlotPolicy = slots.find((slot) => slot.key === 'vae');++ // The picker filter and the validator must agree, or the dropdown hides a VAE that+ // validation would then demand.+ expect(+ vaeSlotPolicy?.filter?.(animaRegisteredVae, {+ model: checkpoint,+ selectedComponents: { ...settings },+ settings,+ })+ ).toBe(true);+ });++ it('still rejects a VAE from an unrelated family for Krea-2', () => {+ const checkpoint = createModel('krea-2', { format: 'checkpoint' });+ const reasons = getGenerationValidationReasons(+ checkpoint,+ createSettings(checkpoint, { qwen3VLEncoderModel: qwen3VlEncoder, vae: sdxlVae })+ );++ expect(reasons).toContain('Generate needs a VAE for non-Diffusers Krea-2 models.');+ });++ it('requires a VAE and Qwen3-VL encoder for a non-diffusers Krea-2 but not a diffusers one', () => {+ const checkpoint = createModel('krea-2', { format: 'checkpoint' });+ const missing = getGenerationValidationReasons(checkpoint, createSettings(checkpoint));++ expect(missing).toContain('Generate needs a VAE for non-Diffusers Krea-2 models.');+ expect(missing).toContain('Generate needs a Qwen3-VL Encoder for non-Diffusers Krea-2 models.');++ const supplied = getGenerationValidationReasons(+ checkpoint,+ createSettings(checkpoint, { qwen3VLEncoderModel: qwen3VlEncoder, vae: krea2Vae })+ );++ expect(supplied).toEqual([]);++ const diffusers = createModel('krea-2', { format: 'diffusers' });++ expect(getGenerationValidationReasons(diffusers, createSettings(diffusers))).toEqual([]);+ });++ it('blocks unparseable Krea-2 rebalance weights only while rebalance is on', () => {+ const model = createModel('krea-2', { format: 'diffusers' });+ const invalid = { krea2RebalanceEnabled: true, krea2RebalanceWeights: '1.0,2.0' };++ expect(getGenerationValidationReasons(model, createSettings(model, invalid))).toContain(+ 'Krea-2 rebalance weights must be 12 comma-separated numbers.'+ );+ // Off, the string never reaches the backend parser, so it must not block generation.+ expect(+ getGenerationValidationReasons(model, createSettings(model, { ...invalid, krea2RebalanceEnabled: false }))+ ).toEqual([]);+ });++ it('rejects non-numeric Krea-2 weights even at the right count', () => {+ const model = createModel('krea-2', { format: 'diffusers' });+ const weights = '1,1,1,1,1,1,1,1,1,1,1,nope';++ expect(+ getGenerationValidationReasons(+ model,+ createSettings(model, { krea2RebalanceEnabled: true, krea2RebalanceWeights: weights })+ )+ ).toContain('Krea-2 rebalance weights must be 12 comma-separated numbers.');+ });++ it('requires a VAE and Wan T5 encoder for a GGUF Wan main', () => {+ const gguf = createModel('wan', { format: 'gguf_quantized' });+ const missing = getGenerationValidationReasons(gguf, createSettings(gguf));++ expect(missing).toContain('Generate needs a VAE for Wan models.');+ expect(missing).toContain('Generate needs a Wan T5 Encoder for Wan models.');++ expect(+ getGenerationValidationReasons(gguf, createSettings(gguf, { vae: wanVae, wanT5EncoderModel: wanT5Encoder }))+ ).toEqual([]);+ });++ it('never requires the low-noise Wan expert, which is an optional quality upgrade', () => {+ const diffusers = createModel('wan', { format: 'diffusers' });++ expect(getGenerationValidationReasons(diffusers, createSettings(diffusers))).toEqual([]);+ });++ it('reports an enabled Wan LoRA that targets the other family instead of dropping it silently', () => {+ const main = createModel('wan', { format: 'diffusers', variant: 'ti2v_5b' });+ const a14bLora: LoraModelConfig = {+ base: 'wan',+ key: 'a14b-lora',+ name: 'A14B LoRA',+ type: 'lora',+ variant: 'a14b',+ };+ const reasons = getGenerationValidationReasons(+ main,+ createSettings(main, { loras: [{ isEnabled: true, model: a14bLora, weight: 1 }] })+ );++ expect(reasons).toContain(`A14B LoRA targets a different Wan model family than ${main.name}.`);+ });++ it('accepts a Wan LoRA whose family matches, across both A14B main variants', () => {+ const a14bLora: LoraModelConfig = {+ base: 'wan',+ key: 'a14b-lora',+ name: 'A14B LoRA',+ type: 'lora',+ variant: 'a14b',+ };++ for (const variant of ['t2v_a14b', 'i2v_a14b']) {+ const main = createModel('wan', { format: 'diffusers', variant });++ expect(+ getGenerationValidationReasons(+ main,+ createSettings(main, { loras: [{ isEnabled: true, model: a14bLora, weight: 1 }] })+ )+ ).toEqual([]);+ }+ });++ it('ignores a disabled mismatched Wan LoRA', () => {+ const main = createModel('wan', { format: 'diffusers', variant: 'ti2v_5b' });+ const a14bLora: LoraModelConfig = {+ base: 'wan',+ key: 'a14b-lora',+ name: 'A14B LoRA',+ type: 'lora',+ variant: 'a14b',+ };++ expect(+ getGenerationValidationReasons(+ main,+ createSettings(main, { loras: [{ isEnabled: false, model: a14bLora, weight: 1 }] })+ )+ ).toEqual([]);+ });+});diff --cc invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex 1e2407150d,0000000000..0cc66d71a2mode 100644,000000..100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@@ -1,1720 -1,0 +1,1754 @@@+import type {+ GenerationModelCatalogItem as ModelConfig,+ GenerationModelTaxonomyType as ModelTaxonomyType,+ KnownGenerationModelBase as KnownModelBase,+ PromptHistoryItem,+} from '@features/generation/core/contracts';++import type {+ GenerateModelConfig,+ GenerateReferenceImage,+ GenerateReferenceImageAsset,+ GenerateReferenceImageConfig,+ GenerateSettings,+ MainModelConfig,+ PidMode,+ VaePrecision,+} from './types';++import {+ getCompatibleDiffusersComponentSource,+ isAnimaQwen3Encoder,+ isAnimaVae,+ isKrea2Vae,+ isClipVariant,+ isDiffusersMainForBase,+ isFlux2DiffusersSourceForModel,++ isFlux2MistralEncoder,+ isFlux2Qwen3EncoderForModel,+ isNonAnimaQwen3Encoder,+ isVaeForBases,+ type GenerateComponentFilter,+} from './componentCompatibility';+import { DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS } from './dynamicPrompts';+import {+ DEFAULT_PID_STEPS,+ getIsPidActive,+ getIsPidSupportedBase,+ getPidDecoderBaseForMainBase,+ getPidDimensionOverrides,+} from './pid';+import {+ clampDimension,+ DEFAULT_HIDIFFUSION_T1_RATIO,+ DEFAULT_HIDIFFUSION_T2_RATIO,+ DEFAULT_IDEOGRAM4_SAMPLER_PRESET,+ DEFAULT_KREA2_REBALANCE_MULTIPLIER,+ DEFAULT_KREA2_REBALANCE_WEIGHTS,+ DEFAULT_KREA2_SEED_VARIANCE_RANDOMIZE_PERCENT,+ DEFAULT_KREA2_SEED_VARIANCE_STRENGTH,+ DEFAULT_REFERENCE_IMAGE_LIMIT,+ deriveAspectRatioId,+ isGenerateSettings,+ isLoraCompatibleWithModel,+ isValidKrea2RebalanceWeights,+ isWanLoraTargetingMain,+ KREA2_REBALANCE_WEIGHT_COUNT,+ MAX_DIMENSION,+ MIN_DIMENSION,+ normalizeGenerateSettings,+ SEED_MAX,+} from './settings';++// Generation policy registry keyed by model base. Display identity stays in @features/models;+// graph topology stays explicit in graph.ts.++export interface SchedulerOption {+ value: string;+ label: string;+}++export type SchedulerSetId = 'standard' | 'flow' | 'flow-no-lcm' | 'anima';++export type NegativePromptUsage = 'always' | 'cfg-gated' | 'never';++export type GuidanceLabel = 'CFG' | 'Guidance';++export interface BaseGenerationConfig {+ dimensions: {+ grid: number;+ optimalSide: number;+ };+ defaults: {+ steps: number;+ cfgScale: number;+ scheduler: string;+ };+ schedulerSet: SchedulerSetId;+ schedulerAppliesToGraph: boolean;+ guidanceLabel: GuidanceLabel;+ negativePrompt: {+ visible: boolean;+ usage: NegativePromptUsage;+ };+ ui: {+ sdVaeOverride: boolean;+ colorCompensation: boolean;+ vaePrecision: boolean;+ seamless: boolean;+ cfgRescale: boolean;+ clipSkipMax?: number;+ };+}++type GenerateDefaultSettings =+ | {+ scheduler?: string | null;+ steps?: number | null;+ cfg_scale?: number | null;+ guidance?: number | null;+ cfg_rescale_multiplier?: number | null;+ width?: number | null;+ height?: number | null;+ vae?: string | null;+ vae_precision?: string | null;+ }+ | null+ | undefined;++export const SCHEDULER_OPTIONS: SchedulerOption[] = [+ { 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' },+];++export const FLOW_SCHEDULER_OPTIONS: SchedulerOption[] = [+ { label: 'Euler', value: 'euler' },+ { label: 'Heun (2nd order)', value: 'heun' },+ { label: 'LCM', value: 'lcm' },+];++export const FLOW_SCHEDULER_OPTIONS_WITHOUT_LCM: SchedulerOption[] = [+ { label: 'Euler', value: 'euler' },+ { label: 'Heun (2nd order)', value: 'heun' },+];++export const ANIMA_SCHEDULER_OPTIONS: SchedulerOption[] = [+ { label: 'Euler', value: 'euler' },+ { label: 'Heun (2nd order)', value: 'heun' },+ { label: 'DPM++ 2M', value: 'dpmpp_2m' },+ { label: 'DPM++ 2M SDE', value: 'dpmpp_2m_sde' },+ { label: 'ER-SDE', value: 'er_sde' },+ { label: 'LCM', value: 'lcm' },+];++const KNOWN_SCHEDULERS = new Set(SCHEDULER_OPTIONS.map((option) => option.value));+const FLOW_SCHEDULERS = new Set(FLOW_SCHEDULER_OPTIONS.map((option) => option.value));+const FLOW_SCHEDULERS_WITHOUT_LCM = new Set(FLOW_SCHEDULER_OPTIONS_WITHOUT_LCM.map((option) => option.value));+const ANIMA_SCHEDULERS = new Set(ANIMA_SCHEDULER_OPTIONS.map((option) => option.value));++export const isKnownScheduler = (value: string): boolean => KNOWN_SCHEDULERS.has(value);++export const BASE_GENERATION = {+ 'sd-1': {+ dimensions: { grid: 8, optimalSide: 512 },+ defaults: { steps: 30, cfgScale: 7, scheduler: 'euler_a' },+ schedulerSet: 'standard',+ schedulerAppliesToGraph: true,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'always' },+ ui: {+ sdVaeOverride: true,+ colorCompensation: false,+ vaePrecision: true,+ seamless: true,+ cfgRescale: true,+ clipSkipMax: 12,+ },+ },+ 'sd-2': {+ dimensions: { grid: 8, optimalSide: 512 },+ defaults: { steps: 30, cfgScale: 7, scheduler: 'euler_a' },+ schedulerSet: 'standard',+ schedulerAppliesToGraph: true,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'always' },+ ui: {+ sdVaeOverride: true,+ colorCompensation: false,+ vaePrecision: true,+ seamless: true,+ cfgRescale: true,+ clipSkipMax: 24,+ },+ },+ sdxl: {+ dimensions: { grid: 8, optimalSide: 1024 },+ defaults: { steps: 30, cfgScale: 7, scheduler: 'euler_a' },+ schedulerSet: 'standard',+ schedulerAppliesToGraph: true,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'always' },+ ui: { sdVaeOverride: true, colorCompensation: true, vaePrecision: true, seamless: true, cfgRescale: false },+ },+ 'sd-3': {+ dimensions: { grid: 16, optimalSide: 1024 },+ defaults: { steps: 30, cfgScale: 7, scheduler: 'euler_a' },+ schedulerSet: 'standard',+ schedulerAppliesToGraph: false,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'always' },+ ui: { sdVaeOverride: false, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+ flux: {+ dimensions: { grid: 16, optimalSide: 1024 },+ defaults: { steps: 4, cfgScale: 4, scheduler: 'euler' },+ schedulerSet: 'flow',+ schedulerAppliesToGraph: true,+ guidanceLabel: 'Guidance',+ negativePrompt: { visible: false, usage: 'never' },+ ui: { sdVaeOverride: false, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+ flux2: {+ dimensions: { grid: 16, optimalSide: 1024 },+ defaults: { steps: 4, cfgScale: 1, scheduler: 'euler' },+ schedulerSet: 'flow',+ schedulerAppliesToGraph: true,+ guidanceLabel: 'Guidance',+ negativePrompt: { visible: false, usage: 'never' },+ ui: { sdVaeOverride: false, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+ cogview4: {+ dimensions: { grid: 32, optimalSide: 1024 },+ defaults: { steps: 30, cfgScale: 7, scheduler: 'euler_a' },+ schedulerSet: 'standard',+ schedulerAppliesToGraph: false,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'always' },+ ui: { sdVaeOverride: false, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+ 'qwen-image': {+ dimensions: { grid: 16, optimalSide: 1024 },+ defaults: { steps: 40, cfgScale: 4, scheduler: 'euler_a' },+ schedulerSet: 'standard',+ schedulerAppliesToGraph: false,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'cfg-gated' },+ ui: { sdVaeOverride: false, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+ 'z-image': {+ dimensions: { grid: 16, optimalSide: 1024 },+ defaults: { steps: 8, cfgScale: 1, scheduler: 'euler' },+ schedulerSet: 'flow',+ schedulerAppliesToGraph: true,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'cfg-gated' },+ ui: { sdVaeOverride: false, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+ 'ideogram-4': {+ // Enforced by ideogram4_denoise: width/height carry multipleOf=16.+ dimensions: { grid: 16, optimalSide: 1024 },+ // Steps and guidance come from the sampler preset unless explicitly overridden, so the+ // shared step/CFG fields are inert here; the preset default is V4_QUALITY_48 (48 steps).+ defaults: { steps: 48, cfgScale: 1, scheduler: 'euler' },+ schedulerSet: 'flow',+ schedulerAppliesToGraph: false,+ guidanceLabel: 'Guidance',+ negativePrompt: { visible: false, usage: 'never' },+ ui: { sdVaeOverride: false, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+ 'krea-2': {+ dimensions: { grid: 16, optimalSide: 1024 },+ // Krea-2-Turbo's numbers. Krea-2-Raw wants ~28 steps at CFG ~4.5, which comes through the+ // model's own default_settings rather than being hardcoded per variant here.+ defaults: { steps: 8, cfgScale: 1, scheduler: 'euler' },+ schedulerSet: 'flow',+ schedulerAppliesToGraph: false,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'cfg-gated' },+ ui: { sdVaeOverride: false, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+ wan: {+ // Wan's transformer patch-embeds with stride 2 and un-patches by 2; combined with the VAE's+ // 8x spatial scale, dimensions must be multiples of 16 or the scheduler step fails on a+ // latents-vs-noise spatial mismatch.+ dimensions: { grid: 16, optimalSide: 1024 },+ defaults: { steps: 40, cfgScale: 4, scheduler: 'euler' },+ schedulerSet: 'flow',+ schedulerAppliesToGraph: false,+ guidanceLabel: 'Guidance',+ negativePrompt: { visible: true, usage: 'always' },+ ui: { sdVaeOverride: false, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+ anima: {+ dimensions: { grid: 8, optimalSide: 1024 },+ defaults: { steps: 30, cfgScale: 4, scheduler: 'euler' },+ schedulerSet: 'anima',+ schedulerAppliesToGraph: true,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'cfg-gated' },+ ui: { sdVaeOverride: false, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },+ },+} as const satisfies Partial<Record<KnownModelBase, BaseGenerationConfig>>;++export type SupportedGenerateBase = keyof typeof BASE_GENERATION;++export const SUPPORTED_GENERATE_BASES = Object.keys(BASE_GENERATION) as SupportedGenerateBase[];++export interface GenerationModelPolicy {+ isSupported: boolean;+ dimensions: {+ grid: number;+ min: number;+ max: number;+ optimal: number;+ };+ defaults: {+ steps: number;+ cfgScale: number;+ cfgRescaleMultiplier: number;+ scheduler: string;+ vaePrecision: VaePrecision;+ };+ scheduler: {+ options: readonly SchedulerOption[];+ defaultValue: string;+ appliesToGraph: boolean;+ coerceForGraph: (value: string) => string;+ };+ prompt: {+ negativeVisible: boolean;+ negativeUsedInGraph: boolean;+ negativeHelpText?: string;+ };+ ui: {+ guidanceLabel: GuidanceLabel;+ schedulerVisible: boolean;+ clipSkipMax: number | null;+ cfgRescaleVisible: boolean;+ colorCompensationVisible: boolean;+ hiDiffusionVisible: boolean;+ seamlessVisible: boolean;+ sdVaeVisible: boolean;+ vaePrecisionVisible: boolean;+ seedVisible: boolean;+ };+}++const FALLBACK_GENERATION_CONFIG: BaseGenerationConfig = {+ dimensions: { grid: 8, optimalSide: 1024 },+ defaults: { steps: 30, cfgScale: 7, scheduler: 'euler_a' },+ schedulerSet: 'standard',+ schedulerAppliesToGraph: false,+ guidanceLabel: 'CFG',+ negativePrompt: { visible: true, usage: 'never' },+ ui: { sdVaeOverride: false, colorCompensation: false, vaePrecision: false, seamless: false, cfgRescale: false },+};++// Fallbacks keep UI selectors crash-safe; isSupportedGenerateModel() still blocks invocation.+const getBaseGenerationConfig = (+ model: Pick<GenerateModelConfig, 'base' | 'type'> | undefined+): BaseGenerationConfig => {+ if (!model || model.type === 'external_image_generator') {+ return FALLBACK_GENERATION_CONFIG;+ }++ return (BASE_GENERATION as Partial<Record<string, BaseGenerationConfig>>)[model.base] ?? FALLBACK_GENERATION_CONFIG;+};++const getNumber = (value: number | null | undefined, fallback: number): number =>+ Number.isFinite(value) && value !== null && value !== undefined ? value : fallback;++/**+ * The dimension rules for a model, optionally adjusted for PiD.+ *+ * `pidMode` is optional so the many callers that only care about the model keep+ * working unchanged. In PiD native mode the requested size is the 4x decode target, so+ * the grid is multiplied by 4 (keeping requested / 4 on the model's own grid) and the+ * optimal side becomes PiD's 2048 rather than the model's 1024.+ */+export const getGenerationDimensions = (+ model: Pick<GenerateModelConfig, 'base' | 'type'> | undefined,+ pidMode: PidMode = 'off'+) => {+ const config = getBaseGenerationConfig(model);+ const { grid, optimalSide } = getPidDimensionOverrides(+ pidMode,+ model?.base,+ config.dimensions.grid,+ config.dimensions.optimalSide+ );++ return {+ grid,+ min: MIN_DIMENSION,+ max: MAX_DIMENSION,+ optimal: optimalSide,+ };+};++export const getGenerationDefaults = (model: GenerateModelConfig | undefined) => {+ const config = getBaseGenerationConfig(model);+ const defaults = model?.default_settings as GenerateDefaultSettings;++ return {+ cfgRescaleMultiplier: getNumber(defaults?.cfg_rescale_multiplier, 0),+ cfgScale: getNumber(defaults?.cfg_scale ?? defaults?.guidance, config.defaults.cfgScale),+ scheduler: defaults?.scheduler ?? config.defaults.scheduler,+ steps: Math.max(1, Math.round(getNumber(defaults?.steps, config.defaults.steps))),+ vaePrecision: defaults?.vae_precision === 'fp16' ? ('fp16' as const) : ('fp32' as const),+ };+};++export const getSchedulerOptions = (+ model:+ | (Pick<GenerateModelConfig, 'base' | 'type' | 'variant'> & Partial<Pick<MainModelConfig, 'format'>>)+ | undefined,+ currentValue?: string+): readonly SchedulerOption[] => {+ const config = getBaseGenerationConfig(model);+ const options = (() => {+ if (model?.base === 'z-image' && model.variant === 'zbase') {+ return FLOW_SCHEDULER_OPTIONS_WITHOUT_LCM;+ }++ switch (config.schedulerSet) {+ case 'flow':+ return FLOW_SCHEDULER_OPTIONS;+ case 'flow-no-lcm':+ return FLOW_SCHEDULER_OPTIONS_WITHOUT_LCM;+ case 'anima':+ return ANIMA_SCHEDULER_OPTIONS;+ case 'standard':+ return SCHEDULER_OPTIONS;+ }+ })();++ // Keep persisted/metadata scheduler values visible until the user picks a supported option.+ return currentValue && !options.some((option) => option.value === currentValue)+ ? [{ label: currentValue, value: currentValue }, ...options]+ : options;+};++export const coerceSchedulerForGraph = (+ model:+ | (Pick<GenerateModelConfig, 'base' | 'type' | 'variant'> & Partial<Pick<MainModelConfig, 'format'>>)+ | undefined,+ scheduler: string+): string => {+ const config = getBaseGenerationConfig(model);++ // Some graph builders ignore scheduler entirely; coerce to stable metadata/defaults instead of leaking stale UI state.+ if (!config.schedulerAppliesToGraph) {+ return config.defaults.scheduler;+ }++ if (model?.base === 'z-image' && model.variant === 'zbase') {+ return FLOW_SCHEDULERS_WITHOUT_LCM.has(scheduler) ? scheduler : 'euler';+ }++ switch (config.schedulerSet) {+ case 'flow':+ return FLOW_SCHEDULERS.has(scheduler) ? scheduler : 'euler';+ case 'flow-no-lcm':+ return FLOW_SCHEDULERS_WITHOUT_LCM.has(scheduler) ? scheduler : 'euler';+ case 'anima':+ return ANIMA_SCHEDULERS.has(scheduler) ? scheduler : 'euler';+ case 'standard':+ return KNOWN_SCHEDULERS.has(scheduler) ? scheduler : config.defaults.scheduler;+ }+};++export const getPromptPolicy = (+ model: GenerateModelConfig | undefined,+ settings: Pick<GenerateSettings, 'cfgScale' | 'negativePromptEnabled'>+) => {+ if (model?.type === 'external_image_generator') {+ const supportsNegativePrompt = model.capabilities?.supports_negative_prompt === true;++ return {+ negativeVisible: supportsNegativePrompt,+ negativeUsedInGraph: settings.negativePromptEnabled && supportsNegativePrompt,+ };+ }++ const config = getBaseGenerationConfig(model);+ // Visibility controls the textarea; usage controls whether the graph wires negative conditioning.+ const negativeUsedInGraph =+ settings.negativePromptEnabled &&+ (config.negativePrompt.usage === 'always' ||+ (config.negativePrompt.usage === 'cfg-gated' && settings.cfgScale > 1));++ return {+ negativeVisible: config.negativePrompt.visible,+ negativeUsedInGraph,+ ...(config.negativePrompt.usage === 'cfg-gated'+ ? { negativeHelpText: 'Used only when CFG is greater than 1.' }+ : {}),+ };+};++export const getGenerationUiPolicy = (+ model: GenerateModelConfig | undefined,+ _settings: Pick<GenerateSettings, 'cfgScale'>+) => {+ const config = getBaseGenerationConfig(model);+ const seedVisible = model?.type === 'external_image_generator' ? model.capabilities?.supports_seed === true : true;++ return {+ guidanceLabel: config.guidanceLabel,+ schedulerVisible: config.schedulerAppliesToGraph,+ clipSkipMax: config.ui.clipSkipMax ?? null,+ cfgRescaleVisible: config.ui.cfgRescale,+ colorCompensationVisible: config.ui.colorCompensation,+ hiDiffusionVisible: model?.type === 'main' && (model.base === 'sd-1' || model.base === 'sdxl'),+ seamlessVisible: config.ui.seamless,+ sdVaeVisible: config.ui.sdVaeOverride,+ vaePrecisionVisible: config.ui.vaePrecision,+ seedVisible,+ // Shown for any base with a PiD decode node, whether or not PiD is currently on, so+ // it can be turned on without hunting for the control.+ pidVisible: getIsPidSupportedBase(model?.base),+ };+};++export const isSupportedGenerateModel = <T extends { base: string; type: string }>(+ model: T+): model is T & GenerateModelConfig =>+ (model.type === 'main' && model.base in BASE_GENERATION) ||+ (model.type === 'external_image_generator' && model.base === 'external');++export const isGenerateModelSelectable = <T extends ModelConfig>(model: T): boolean => isSupportedGenerateModel(model);++/** Pure prompt-history recall patch shared by keyboard and palette entry points. */+export const getPromptHistoryRecallPatch = ({+ item,+ models,+ values,+}: {+ item: PromptHistoryItem;+ models: readonly ModelConfig[] | undefined;+ values: Record<string, unknown>;+}): Record<string, unknown> | null => {+ const settings = normalizeGenerateSettings(values);++ if (!settings) {+ return null;+ }++ const selectedModel = models?.filter(isSupportedGenerateModel).find((model) => model.key === settings.modelKey);+ const promptPolicy = getPromptPolicy(selectedModel, settings);+ const patch: Record<string, unknown> = { positivePrompt: item.positivePrompt };++ if (promptPolicy.negativeVisible) {+ patch.negativePrompt = item.negativePrompt ?? '';+ patch.negativePromptEnabled = item.negativePrompt ? true : settings.negativePromptEnabled;+ }++ return patch;+};++export const EXTERNAL_PROVIDER_NODE_TYPES: Record<string, string> = {+ alibabacloud: 'alibabacloud_image_generation',+ gemini: 'gemini_image_generation',+ openai: 'openai_image_generation',+ seedream: 'seedream_image_generation',+};++export const getExternalProviderNodeType = (providerId: unknown): string | null =>+ typeof providerId === 'string' ? (EXTERNAL_PROVIDER_NODE_TYPES[providerId] ?? null) : null;++export const getGenerationModelPolicy = (+ model: GenerateModelConfig | undefined,+ settings: GenerateSettings+): GenerationModelPolicy => {+ const config = getBaseGenerationConfig(model);+ const dimensions = getGenerationDimensions(model);+ const defaults = getGenerationDefaults(model);++ return {+ isSupported: model ? isSupportedGenerateModel(model) : false,+ dimensions,+ defaults,+ scheduler: {+ options: getSchedulerOptions(model, settings.scheduler),+ defaultValue: defaults.scheduler,+ appliesToGraph: config.schedulerAppliesToGraph,+ coerceForGraph: (value: string) => coerceSchedulerForGraph(model, value),+ },+ prompt: getPromptPolicy(model, settings),+ ui: getGenerationUiPolicy(model, settings),+ };+};++export const getDefaultGenerateSettings = (model?: GenerateModelConfig): GenerateSettings => {+ const defaults = getGenerationDefaults(model);+ const dimensions = getGenerationDimensions(model);+ const defaultSettings = model?.default_settings as GenerateDefaultSettings;+ const width = clampDimension(getNumber(defaultSettings?.width, dimensions.optimal), dimensions.grid);+ const height = clampDimension(getNumber(defaultSettings?.height, dimensions.optimal), dimensions.grid);++ return {+ aspectRatioId: deriveAspectRatioId(width, height),+ aspectRatioIsLocked: false,+ aspectRatioValue: height > 0 ? width / height : 1,+ batchCount: 1,+ cfgRescaleMultiplier: defaults.cfgRescaleMultiplier,+ cfgScale: defaults.cfgScale,+ clipSkip: 0,+ colorCompensation: false,+ hiDiffusionEnabled: false,+ hiDiffusionRauNetEnabled: true,+ hiDiffusionWindowAttentionEnabled: true,+ hiDiffusionT1Ratio: DEFAULT_HIDIFFUSION_T1_RATIO,+ hiDiffusionT2Ratio: DEFAULT_HIDIFFUSION_T2_RATIO,+ dynamicPromptsCombinatorial: true,+ dynamicPromptsMaxPrompts: DYNAMIC_PROMPTS_DEFAULT_MAX_PROMPTS,+ dynamicPromptsSampleSeed: 0,+ dynamicPromptsSeedBehaviour: 'per-iteration',+ clipEmbedModel: null,+ clipGEmbedModel: null,+ clipLEmbedModel: null,+ componentSourceModel: null,+ height,+ loras: [],++ mistralEncoderModel: null,+ modelKey: model?.key ?? '',+ negativePromptEnabled: true,+ negativePrompt: '',+ negativePromptHeightPx: 56,+ positivePrompt: '',+ positivePromptHeightPx: 96,+ promptTemplate: null,+ promptTemplateViewMode: false,+ qwen3EncoderModel: null,+ qwenVLEncoderModel: null,+ qwen3VLEncoderModel: null,+ wanT5EncoderModel: null,+ wanLowNoiseModel: null,+ wanGuidanceScaleLowNoise: null,+ ideogram4SamplerPreset: DEFAULT_IDEOGRAM4_SAMPLER_PRESET,+ ideogram4Steps: null,+ ideogram4GuidanceScale: null,+ ideogram4Mu: null,+ ideogram4ColorPalette: [],+ krea2RebalanceEnabled: false,+ krea2RebalanceMultiplier: DEFAULT_KREA2_REBALANCE_MULTIPLIER,+ krea2RebalanceWeights: DEFAULT_KREA2_REBALANCE_WEIGHTS,+ krea2SeedVarianceEnabled: false,+ krea2SeedVarianceStrength: DEFAULT_KREA2_SEED_VARIANCE_STRENGTH,+ krea2SeedVarianceRandomizePercent: DEFAULT_KREA2_SEED_VARIANCE_RANDOMIZE_PERCENT,+ pidMode: 'off',+ pidDecoderModel: null,+ gemma2EncoderModel: null,+ pidSteps: DEFAULT_PID_STEPS,+ referenceImages: [],+ scheduler: defaults.scheduler,+ seamlessXAxis: false,+ seamlessYAxis: false,+ seed: Math.floor(Math.random() * SEED_MAX),+ shouldRandomizeSeed: true,+ steps: defaults.steps,+ t5EncoderModel: null,+ vae: null,+ vaePrecision: defaults.vaePrecision,+ width,+ };+};++export const getSettingsWithModelDefaults = (+ settings: GenerateSettings,+ model: GenerateModelConfig+): GenerateSettings => {+ const modelDefaults = getDefaultGenerateSettings(model);++ return {+ ...settings,+ aspectRatioId: modelDefaults.aspectRatioId,+ aspectRatioIsLocked: false,+ aspectRatioValue: modelDefaults.aspectRatioValue,+ cfgRescaleMultiplier: modelDefaults.cfgRescaleMultiplier,+ cfgScale: modelDefaults.cfgScale,+ colorCompensation: modelDefaults.colorCompensation,+ height: modelDefaults.height,+ loras: settings.loras.map((lora) =>+ isLoraCompatibleWithModel(lora.model, model) ? lora : { ...lora, isEnabled: false }+ ),+ modelKey: model.key,+ scheduler: modelDefaults.scheduler,+ steps: modelDefaults.steps,+ vaePrecision: modelDefaults.vaePrecision,+ width: modelDefaults.width,+ };+};++export type GenerateComponentValueKey =+ | 't5EncoderModel'+ | 'clipEmbedModel'+ | 'clipLEmbedModel'+ | 'clipGEmbedModel'++ | 'mistralEncoderModel'+ | 'qwen3EncoderModel'+ | 'qwenVLEncoderModel'+ | 'qwen3VLEncoderModel'+ | 'wanT5EncoderModel'+ | 'wanLowNoiseModel'+ | 'componentSourceModel'+ | 'pidDecoderModel'+ | 'gemma2EncoderModel'+ | 'vae';++export interface ComponentPolicyContext {+ model: GenerateModelConfig;+ settings: GenerateSettings;+ selectedComponents: Pick<GenerateSettings, GenerateComponentValueKey>;+}++export interface ComponentSlotPolicy {+ key: GenerateComponentValueKey;+ label: string;+ modelTypes: readonly ModelTaxonomyType[];+ valueKind: 'component' | 'vae' | 'main';+ helpText?: string;+ placeholder?: string;+ defaultOpen?: boolean;+ filter?: (candidate: ModelConfig, ctx: ComponentPolicyContext) => boolean;+ required?: (ctx: ComponentPolicyContext) => boolean;+ missingMessage?: string;+}++export interface ComponentSectionPolicy {+ defaultOpen: boolean;+ slots: readonly ComponentSlotPolicy[];+ validate: (ctx: ComponentPolicyContext) => string[];+}++export interface GenerateModelSelectionResult {+ settings: GenerateSettings;+ clearedLabels: readonly string[];+}++const TYPE_CLIP_EMBED: ModelTaxonomyType[] = ['clip_embed'];+const TYPE_MAIN: ModelTaxonomyType[] = ['main'];++const TYPE_MISTRAL: ModelTaxonomyType[] = ['mistral_encoder'];+const TYPE_QWEN3: ModelTaxonomyType[] = ['qwen3_encoder'];+const TYPE_QWEN_VL: ModelTaxonomyType[] = ['qwen_vl_encoder'];+const TYPE_QWEN3_VL: ModelTaxonomyType[] = ['qwen3_vl_encoder'];+const TYPE_WAN_T5: ModelTaxonomyType[] = ['wan_t5_encoder'];+const TYPE_PID_DECODER: ModelTaxonomyType[] = ['pid_decoder'];+const TYPE_GEMMA2: ModelTaxonomyType[] = ['gemma2_encoder'];+const TYPE_T5: ModelTaxonomyType[] = ['t5_encoder'];+const TYPE_VAE: ModelTaxonomyType[] = ['vae'];++const wrapFilter = (filter: GenerateComponentFilter) => (candidate: ModelConfig) => filter(candidate);++const slot = (policy: ComponentSlotPolicy): ComponentSlotPolicy => policy;++const componentSourceSlot = (+ filter: (candidate: ModelConfig, ctx: ComponentPolicyContext) => boolean,+ helpText: string+): ComponentSlotPolicy =>+ slot({+ key: 'componentSourceModel',+ label: 'Component source',+ modelTypes: TYPE_MAIN,+ valueKind: 'main',+ helpText,+ filter,+ });++const t5EncoderSlot = (helpText: string): ComponentSlotPolicy =>+ slot({+ key: 't5EncoderModel',+ label: 'T5 Encoder',+ modelTypes: TYPE_T5,+ valueKind: 'component',+ helpText,+ filter: (candidate) => candidate.type === 't5_encoder',+ });++const clipEmbedSlot = (helpText: string): ComponentSlotPolicy =>+ slot({+ key: 'clipEmbedModel',+ label: 'CLIP Embed',+ modelTypes: TYPE_CLIP_EMBED,+ valueKind: 'component',+ helpText,+ filter: (candidate) => candidate.type === 'clip_embed',+ });++const qwenVlEncoderSlot = (helpText: string): ComponentSlotPolicy =>+ slot({+ key: 'qwenVLEncoderModel',+ label: 'Qwen VL Encoder',+ modelTypes: TYPE_QWEN_VL,+ valueKind: 'component',+ helpText,+ filter: (candidate) => candidate.type === 'qwen_vl_encoder',+ });++const qwen3VlEncoderSlot = (helpText: string): ComponentSlotPolicy =>+ slot({+ key: 'qwen3VLEncoderModel',+ label: 'Qwen3-VL Encoder',+ modelTypes: TYPE_QWEN3_VL,+ valueKind: 'component',+ helpText,+ filter: (candidate) => candidate.type === 'qwen3_vl_encoder',+ });++/**+ * PiD's decoder and caption encoder.+ *+ * Both are only *required* while PiD is on, but the slots are always offered for a+ * PiD-capable base so the models can be chosen before switching PiD on. The decoder is+ * filtered to the base whose checkpoints are valid for the selected model — Z-Image+ * shows FLUX decoders, since it shares FLUX's VAE and ships none of its own.+ */+const pidDecoderSlot = (): ComponentSlotPolicy =>+ slot({+ key: 'pidDecoderModel',+ label: 'PiD Decoder',+ modelTypes: TYPE_PID_DECODER,+ valueKind: 'component',+ helpText: 'Required while PiD is on. Must match the main model’s base.',+ filter: (candidate, ctx) =>+ candidate.type === 'pid_decoder' && candidate.base === getPidDecoderBaseForMainBase(ctx.model.base),+ required: (ctx) => getIsPidActive(ctx.settings.pidMode, ctx.model.base),+ missingMessage: 'Generate needs a PiD decoder while PiD is on.',+ });++const gemma2EncoderSlot = (): ComponentSlotPolicy =>+ slot({+ key: 'gemma2EncoderModel',+ label: 'Gemma-2 Encoder',+ modelTypes: TYPE_GEMMA2,+ valueKind: 'component',+ helpText: 'Required while PiD is on. Shared by every PiD decoder.',+ filter: (candidate) => candidate.type === 'gemma2_encoder',+ required: (ctx) => getIsPidActive(ctx.settings.pidMode, ctx.model.base),+ missingMessage: 'Generate needs a Gemma-2 encoder while PiD is on.',+ });++/** The PiD slots, for splicing into a PiD-capable base's component list. */+const pidSlots = (): ComponentSlotPolicy[] => [pidDecoderSlot(), gemma2EncoderSlot()];++const wanT5EncoderSlot = (helpText: string): ComponentSlotPolicy =>+ slot({+ key: 'wanT5EncoderModel',+ label: 'Wan T5 Encoder',+ modelTypes: TYPE_WAN_T5,+ valueKind: 'component',+ helpText,+ filter: (candidate) => candidate.type === 'wan_t5_encoder',+ });++/**+ * The second (low-noise) expert of a Wan A14B mixture-of-experts pair. Never required: the+ * loader falls back to running the high-noise expert across the whole schedule.+ */+const wanLowNoiseSlot = (helpText: string): ComponentSlotPolicy =>+ slot({+ key: 'wanLowNoiseModel',+ label: 'Low-noise expert',+ modelTypes: TYPE_MAIN,+ valueKind: 'main',+ helpText,+ filter: (candidate) => candidate.type === 'main' && candidate.base === 'wan',+ });++const qwen3EncoderSlot = (helpText: string, filter?: GenerateComponentFilter): ComponentSlotPolicy =>+ slot({+ key: 'qwen3EncoderModel',+ label: 'Qwen3 Encoder',+ modelTypes: TYPE_QWEN3,+ valueKind: 'component',+ helpText,+ filter: filter+ ? (candidate) => candidate.type === 'qwen3_encoder' && filter(candidate)+ : (candidate) => candidate.type === 'qwen3_encoder',+ });+++const mistralEncoderSlot = (helpText: string): ComponentSlotPolicy =>++ slot({++ key: 'mistralEncoderModel',++ label: 'Mistral Encoder',++ modelTypes: TYPE_MISTRAL,++ valueKind: 'component',++ helpText,++ filter: wrapFilter(isFlux2MistralEncoder),++ });+++const clipVariantSlot = (+ key: 'clipLEmbedModel' | 'clipGEmbedModel',+ label: string,+ variant: string,+ helpText: string+) =>+ slot({+ key,+ label,+ modelTypes: TYPE_CLIP_EMBED,+ valueKind: 'component',+ helpText,+ filter: wrapFilter(isClipVariant(variant)),+ });++const vaeSlot = (helpText: string, filter: GenerateComponentFilter): ComponentSlotPolicy =>+ slot({ key: 'vae', label: 'VAE', modelTypes: TYPE_VAE, valueKind: 'vae', helpText, filter: wrapFilter(filter) });++const hasCompatibleComponentSource = (ctx: ComponentPolicyContext): boolean =>+ ctx.model.type !== 'external_image_generator' &&+ Boolean(getCompatibleDiffusersComponentSource(ctx.model, ctx.settings.componentSourceModel));++type ComponentSourceCandidate = {+ base: string;+ key: string;+ name: string;+ type: string;+ format?: string;+ variant?: unknown;+};++const isFlux2DiffusersSource = (source: ComponentSourceCandidate | null | undefined): source is MainModelConfig =>+ Boolean(source && source.type === 'main' && source.base === 'flux2' && source.format === 'diffusers');++const hasFlux2DiffusersVaeSource = (ctx: ComponentPolicyContext): boolean =>+ ctx.model.type !== 'external_image_generator' &&+ (ctx.model.format === 'diffusers' || isFlux2DiffusersSource(ctx.settings.componentSourceModel));+- const hasFlux2DiffusersQwen3Source = (ctx: ComponentPolicyContext): boolean =>++const hasFlux2DiffusersEncoderSource = (ctx: ComponentPolicyContext): boolean =>+ ctx.model.type !== 'external_image_generator' &&+ (ctx.model.format === 'diffusers' ||+ Boolean(+ ctx.settings.componentSourceModel && isFlux2DiffusersSourceForModel(ctx.model)(ctx.settings.componentSourceModel)+ ));++export const getFlux2DiffusersComponentSource = (+ model: MainModelConfig,+ settings: GenerateSettings+): MainModelConfig | undefined => {+ const source = settings.componentSourceModel;++ if (!isFlux2DiffusersSource(source)) {+ return undefined;+ }+- if (settings.qwen3EncoderModel) {++ const hasStandaloneEncoder = model.variant === 'dev' ? settings.mistralEncoderModel : settings.qwen3EncoderModel;++++ if (hasStandaloneEncoder) {+ return source;+ }++ return isFlux2DiffusersSourceForModel(model)(source) ? source : undefined;+};++export const getAutoFlux2ComponentSourceModel = (+ model: GenerateModelConfig | undefined,- settings: Pick<GenerateSettings, 'qwen3EncoderModel' | 'vae'>,++ settings: Pick<GenerateSettings, 'mistralEncoderModel' | 'qwen3EncoderModel' | 'vae'>,+ models: readonly ComponentSourceCandidate[]+): MainModelConfig | null | undefined => {+ if (!model || model.type === 'external_image_generator' || model.base !== 'flux2') {+ return undefined;+ }+- if (model.format === 'diffusers' || (settings.qwen3EncoderModel && settings.vae)) {++ const encoderModel = model.variant === 'dev' ? settings.mistralEncoderModel : settings.qwen3EncoderModel;++++ if (model.format === 'diffusers' || (encoderModel && settings.vae)) {+ return null;+ }++ const diffusersModels = models.filter(isFlux2DiffusersSource);+ const variantMatch = diffusersModels.find(isFlux2DiffusersSourceForModel(model));+- if (!settings.qwen3EncoderModel && settings.vae) {++ if (!encoderModel && settings.vae) {+ return variantMatch ?? null;+ }++ return variantMatch ?? diffusersModels[0] ?? null;+};++// Split/quantized families can satisfy required encoder/VAE slots from a bundled Diffusers source.+const isBundledOrDiffusersSourceSatisfied = (ctx: ComponentPolicyContext): boolean =>+ ctx.model.type !== 'external_image_generator' &&+ (ctx.model.format === 'diffusers' || hasCompatibleComponentSource(ctx));++// Slot validation is shared by invocation readiness and graph preflight so picker requirements cannot drift.+const validateSlots = (policy: Pick<ComponentSectionPolicy, 'slots'>, ctx: ComponentPolicyContext): string[] =>+ policy.slots.flatMap((slotPolicy) => {+ if (!slotPolicy.required?.(ctx)) {+ return [];+ }++ const value = ctx.selectedComponents[slotPolicy.key];+ const isValid = value && (!slotPolicy.filter || slotPolicy.filter(value as ModelConfig, ctx));++ return isValid ? [] : [slotPolicy.missingMessage ?? `Generate needs a ${slotPolicy.label} for this model.`];+ });++const createPolicy = (defaultOpen: boolean, slots: readonly ComponentSlotPolicy[]): ComponentSectionPolicy => ({+ defaultOpen,+ slots,+ validate: (ctx) => validateSlots({ slots }, ctx),+});++const EMPTY_COMPONENT_POLICY: ComponentSectionPolicy = createPolicy(false, []);++const getBaseComponentSectionPolicy = (+ model: GenerateModelConfig | undefined,+ _settings: GenerateSettings+): ComponentSectionPolicy => {+ if (!model || model.type === 'external_image_generator') {+ return EMPTY_COMPONENT_POLICY;+ }++ switch (model.base) {+ case 'flux':+ return {+ ...createPolicy(false, [+ {+ ...t5EncoderSlot('Required for FLUX.1 models.'),+ required: () => true,+ missingMessage: 'Generate needs a T5 Encoder for FLUX models.',+ },+ {+ ...clipEmbedSlot('Required for FLUX.1 models.'),+ required: () => true,+ missingMessage: 'Generate needs a CLIP Embed model for FLUX models.',+ },+ {+ ...vaeSlot('Required for FLUX.1 models.', isVaeForBases(['flux'])),+ required: () => true,+ missingMessage: 'Generate needs a VAE for FLUX models.',+ },+ ]),+ validate: (ctx) => [+ ...(ctx.model.type !== 'external_image_generator' && ctx.model.variant === 'dev_fill'+ ? ['FLUX Fill models do not support text-to-image generation.']+ : []),+ ...validateSlots(getBaseComponentSectionPolicy(ctx.model, ctx.settings), ctx),+ ],+ };- case 'flux2':++ case 'flux2': {++ const encoderSlot: ComponentSlotPolicy =++ model.variant === 'dev'++ ? {++ ...mistralEncoderSlot(++ 'Optional override; otherwise a compatible installed FLUX.2 [dev] Diffusers model is used.'++ ),++ required: (ctx) => !hasFlux2DiffusersEncoderSource(ctx),++ missingMessage: 'Generate needs a Mistral Encoder for non-Diffusers FLUX.2 [dev] models.',++ }++ : {++ ...qwen3EncoderSlot(++ 'Optional override; otherwise a compatible installed FLUX.2 Diffusers model is used.'++ ),++ filter: (candidate, ctx) =>++ ctx.model.type !== 'external_image_generator' && isFlux2Qwen3EncoderForModel(ctx.model)(candidate),++ required: (ctx) => !hasFlux2DiffusersEncoderSource(ctx),++ missingMessage: 'Generate needs a Qwen3 Encoder for non-Diffusers FLUX.2 models.',++ };+++ return createPolicy(model.format !== 'diffusers', [- {- ...qwen3EncoderSlot('Optional override; otherwise a compatible installed FLUX.2 Diffusers model is used.'),- filter: (candidate, ctx) =>- ctx.model.type !== 'external_image_generator' && isFlux2Qwen3EncoderForModel(ctx.model)(candidate),- required: (ctx) => !hasFlux2DiffusersQwen3Source(ctx),- missingMessage: 'Generate needs a Qwen3 Encoder for non-Diffusers FLUX.2 models.',- },++ encoderSlot,+ {+ ...vaeSlot(+ 'Optional override; otherwise an installed FLUX.2 Diffusers model is used.',+ isVaeForBases(['flux2'])+ ),+ required: (ctx) => !hasFlux2DiffusersVaeSource(ctx),+ missingMessage: 'Generate needs a VAE for non-Diffusers FLUX.2 models.',+ },+ ]);++ }+ case 'sd-3':+ return createPolicy(false, [+ t5EncoderSlot('Optional override; the main model is used when omitted.'),+ clipVariantSlot('clipLEmbedModel', 'CLIP L', 'large', 'Optional CLIP-L override.'),+ clipVariantSlot('clipGEmbedModel', 'CLIP G', 'gigantic', 'Optional CLIP-G override.'),+ vaeSlot('Optional VAE override.', isVaeForBases(['sd-3'])),+ ]);+ case 'qwen-image':+ return createPolicy(model.format !== 'diffusers', [+ componentSourceSlot(+ (candidate) => isDiffusersMainForBase('qwen-image')(candidate),+ 'For non-Diffusers Qwen Image models, select this or provide separate VAE and Qwen VL models.'+ ),+ {+ ...qwenVlEncoderSlot('Optional override, or required with a non-Diffusers model and no component source.'),+ required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),+ missingMessage: 'Generate needs a Qwen VL Encoder for non-Diffusers Qwen Image models.',+ },+ {+ ...vaeSlot(+ 'Optional override, or required with a non-Diffusers model and no component source.',+ isVaeForBases(['qwen-image'])+ ),+ required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),+ missingMessage: 'Generate needs a VAE for non-Diffusers Qwen Image models.',+ },+ ]);+ case 'z-image':+ return createPolicy(model.format !== 'diffusers', [+ componentSourceSlot(+ (candidate) => isDiffusersMainForBase('z-image')(candidate),+ 'Select a Diffusers Z-Image model to provide VAE and Qwen3 components.'+ ),+ {+ ...qwen3EncoderSlot('Required unless a Diffusers component source is available.', isNonAnimaQwen3Encoder),+ required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),+ missingMessage: 'Generate needs a Qwen3 Encoder for Z-Image models.',+ },+ {+ ...vaeSlot('Required unless a Diffusers component source is available.', isVaeForBases(['flux'])),+ required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),+ missingMessage: 'Generate needs a VAE for Z-Image models.',+ },+ ]);+ case 'krea-2':+ // A non-diffusers Krea-2 (single-file checkpoint / GGUF) carries only the transformer, so+ // both submodels must be selected. Diffusers models bundle them, hence optional there.+ return createPolicy(model.format !== 'diffusers', [+ {+ ...vaeSlot('Required for non-Diffusers Krea-2 models. Qwen-Image VAEs are used.', isKrea2Vae),+ required: (ctx) => ctx.model.format !== 'diffusers',+ missingMessage: 'Generate needs a VAE for non-Diffusers Krea-2 models.',+ },+ {+ ...qwen3VlEncoderSlot('Required for non-Diffusers Krea-2 models.'),+ required: (ctx) => ctx.model.format !== 'diffusers',+ missingMessage: 'Generate needs a Qwen3-VL Encoder for non-Diffusers Krea-2 models.',+ },+ ]);+ case 'wan':+ // A GGUF Wan main carries only the transformer; the VAE and UMT5-XXL encoder must come+ // from standalone models or a Diffusers component source.+ return createPolicy(model.format !== 'diffusers', [+ componentSourceSlot(+ (candidate) => isDiffusersMainForBase('wan')(candidate),+ 'Select a Diffusers Wan model to provide VAE and text-encoder components.'+ ),+ {+ ...vaeSlot('Required unless a Diffusers component source is available.', isVaeForBases(['wan'])),+ required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),+ missingMessage: 'Generate needs a VAE for Wan models.',+ },+ {+ ...wanT5EncoderSlot('Required unless a Diffusers component source is available.'),+ required: (ctx) => !isBundledOrDiffusersSourceSatisfied(ctx),+ missingMessage: 'Generate needs a Wan T5 Encoder for Wan models.',+ },+ wanLowNoiseSlot('Optional second A14B expert. Without it the high-noise expert runs the whole schedule.'),+ ]);+ case 'anima':+ return createPolicy(true, [+ {+ ...qwen3EncoderSlot('Required for Anima models.', isAnimaQwen3Encoder),+ required: () => true,+ missingMessage: 'Generate needs a Qwen3 Encoder for Anima models.',+ },+ {+ ...vaeSlot('Required for Anima models. Qwen Image and FLUX VAEs are supported.', isAnimaVae),+ required: () => true,+ missingMessage: 'Generate needs a VAE for Anima models.',+ },+ ]);+ default:+ return EMPTY_COMPONENT_POLICY;+ }+};++/**+ * The component slots for a model, plus PiD's two slots on any PiD-capable base.+ *+ * Appended in a wrapper rather than written into each base's case: PiD supports six+ * bases, one of which (SDXL) has no component case at all, and each existing case keeps+ * its own bespoke validation untouched this way. Only the PiD slots are validated here+ * — the inner policy validates its own.+ */+export const getComponentSectionPolicy = (+ model: GenerateModelConfig | undefined,+ settings: GenerateSettings+): ComponentSectionPolicy => {+ const policy = getBaseComponentSectionPolicy(model, settings);++ if (!model || model.type === 'external_image_generator' || !getIsPidSupportedBase(model.base)) {+ return policy;+ }++ const slots = [...policy.slots, ...pidSlots()];++ return {+ defaultOpen: policy.defaultOpen,+ slots,+ validate: (ctx) => [...policy.validate(ctx), ...validateSlots({ slots: pidSlots() }, ctx)],+ };+};++const getComponentPolicyContext = (model: GenerateModelConfig, settings: GenerateSettings): ComponentPolicyContext => ({+ model,+ settings,+ selectedComponents: {+ clipEmbedModel: settings.clipEmbedModel,+ clipGEmbedModel: settings.clipGEmbedModel,+ clipLEmbedModel: settings.clipLEmbedModel,+ componentSourceModel: settings.componentSourceModel,++ mistralEncoderModel: settings.mistralEncoderModel,+ qwen3EncoderModel: settings.qwen3EncoderModel,+ qwenVLEncoderModel: settings.qwenVLEncoderModel,+ qwen3VLEncoderModel: settings.qwen3VLEncoderModel,+ wanT5EncoderModel: settings.wanT5EncoderModel,+ wanLowNoiseModel: settings.wanLowNoiseModel,+ t5EncoderModel: settings.t5EncoderModel,+ pidDecoderModel: settings.pidDecoderModel,+ gemma2EncoderModel: settings.gemma2EncoderModel,+ vae: settings.vae,+ },+});++const COMPONENT_SETTING_LABELS: Record<GenerateComponentValueKey, string> = {+ clipEmbedModel: 'CLIP Embed',+ clipGEmbedModel: 'CLIP G',+ clipLEmbedModel: 'CLIP L',++ mistralEncoderModel: 'Mistral Encoder',+ qwen3EncoderModel: 'Qwen3 Encoder',+ qwenVLEncoderModel: 'Qwen VL Encoder',+ qwen3VLEncoderModel: 'Qwen3-VL Encoder',+ wanT5EncoderModel: 'Wan T5 Encoder',+ wanLowNoiseModel: 'Low-noise expert',+ t5EncoderModel: 'T5 Encoder',+ pidDecoderModel: 'PiD Decoder',+ gemma2EncoderModel: 'Gemma-2 Encoder',+ vae: 'VAE',+ componentSourceModel: 'Component source',+};++const addClearedLabel = (labels: string[], label: string) => {+ if (!labels.includes(label)) {+ labels.push(label);+ }+};++const isSelectedComponentCompatible = (+ slotPolicy: ComponentSlotPolicy | undefined,+ model: GenerateModelConfig,+ settings: GenerateSettings,+ key: GenerateComponentValueKey+): boolean => {+ const value = settings[key];++ if (!value) {+ return true;+ }++ if (key === 'componentSourceModel' && model.type !== 'external_image_generator' && model.base === 'flux2') {+ return Boolean(getFlux2DiffusersComponentSource(model, settings));+ }++ if (!slotPolicy) {+ return false;+ }++ return !slotPolicy.filter || slotPolicy.filter(value as ModelConfig, getComponentPolicyContext(model, settings));+};++type ReferenceModelCandidate = { base: string; key: string; name: string; type: string };++const isFluxKontextModel = (model: GenerateModelConfig | undefined): model is MainModelConfig =>+ Boolean(+ model &&+ model.type !== 'external_image_generator' &&+ model.base === 'flux' &&+ model.name.toLowerCase().includes('kontext')+ );++/**+ * Whether the model can consume reference images at all. Kept strict so the UI+ * only offers reference images where `getGenerationValidationReasons` would+ * accept them (e.g. Qwen Image requires the `edit` variant).+ */+export const isReferenceImageSupported = (model: GenerateModelConfig | undefined): boolean => {+ if (!model) {+ return false;+ }++ if (model.type === 'external_image_generator') {+ return model.capabilities?.supports_reference_images === true;+ }++ if (model.base === 'qwen-image') {+ return model.variant === 'edit';+ }++ return ['flux', 'flux2', 'sd-1', 'sdxl'].includes(model.base);+};++export const getMaxReferenceImages = (model: GenerateModelConfig | undefined): number => {+ if (!model || !isReferenceImageSupported(model)) {+ return 0;+ }++ if (model.type === 'external_image_generator' && typeof model.capabilities?.max_reference_images === 'number') {+ return Math.max(0, model.capabilities.max_reference_images);+ }++ return DEFAULT_REFERENCE_IMAGE_LIMIT;+};++export const createReferenceImageId = (): string =>+ `reference_image_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;++export const getDefaultReferenceImageConfig = (+ model: GenerateModelConfig | undefined,+ models: readonly ReferenceModelCandidate[],+ image: GenerateReferenceImageAsset | null = null+): GenerateReferenceImageConfig => {+ const modelBase: string | undefined = model?.base;++ if (model?.type === 'external_image_generator') {+ return { image, type: 'external_reference_image' };+ }++ if (modelBase === 'flux2') {+ return { image, type: 'flux2_reference_image' };+ }++ if (modelBase === 'qwen-image') {+ return { image, type: 'qwen_image_reference_image' };+ }++ if (isFluxKontextModel(model)) {+ return { image, model, type: 'flux_kontext_reference_image' };+ }++ const adapterModel =+ models.find((candidate) => candidate.type === 'ip_adapter' && candidate.base === modelBase) ?? null;++ return {+ beginEndStepPct: [0, 1],+ clipVisionModel: modelBase === 'flux' ? 'ViT-L' : 'ViT-H',+ image,+ method: 'full',+ model: adapterModel,+ type: 'ip_adapter',+ weight: 1,+ };+};++const getReferenceImageConfigSupported = (+ model: GenerateModelConfig,+ referenceImage: GenerateReferenceImage+): boolean => {+ switch (referenceImage.config.type) {+ case 'external_reference_image':+ return model.type === 'external_image_generator' && model.capabilities?.supports_reference_images === true;+ case 'flux2_reference_image':+ return model.type !== 'external_image_generator' && model.base === 'flux2';+ case 'qwen_image_reference_image':+ return model.type !== 'external_image_generator' && model.base === 'qwen-image' && model.variant === 'edit';+ case 'flux_kontext_reference_image':+ return isFluxKontextModel(model);+ case 'flux_redux':+ return model.type !== 'external_image_generator' && model.base === 'flux';+ case 'ip_adapter':+ return model.type !== 'external_image_generator' && ['sd-1', 'sdxl', 'flux'].includes(model.base);+ }+};++export const isReferenceImageCompatibleWithModel = (+ model: GenerateModelConfig,+ referenceImage: GenerateReferenceImage+): boolean => {+ if (!getReferenceImageConfigSupported(model, referenceImage)) {+ return false;+ }++ const config = referenceImage.config;++ if ((config.type === 'ip_adapter' || config.type === 'flux_redux') && config.model) {+ return config.model.base === model.base;+ }++ if (config.type === 'flux_kontext_reference_image' && config.model) {+ return config.model.key === model.key;+ }++ return true;+};++/**+ * Reference images carried over to `model`: dropped entirely when the model+ * does not support reference images, and re-targeted to a default config for+ * the new model (keeping the image and enabled state) when incompatible.+ * Returns the input array untouched when nothing changes.+ */+export const getCompatibleReferenceImages = (+ referenceImages: GenerateReferenceImage[],+ model: GenerateModelConfig,+ models: readonly ReferenceModelCandidate[]+): GenerateReferenceImage[] => {+ if (referenceImages.length === 0) {+ return referenceImages;+ }++ if (!isReferenceImageSupported(model)) {+ return [];+ }++ let didChange = false;+ const next = referenceImages.map((referenceImage) => {+ if (isReferenceImageCompatibleWithModel(model, referenceImage)) {+ return referenceImage;+ }++ didChange = true;+ return { ...referenceImage, config: getDefaultReferenceImageConfig(model, models, referenceImage.config.image) };+ });++ return didChange ? next : referenceImages;+};++const getSettingsWithCompatibleModelSelections = (+ settings: GenerateSettings,+ model: GenerateModelConfig,+ models: readonly ReferenceModelCandidate[]+): GenerateModelSelectionResult => {+ const nextSettings: GenerateSettings = { ...settings, modelKey: model.key };+ const clearedLabels: string[] = [];+ const compatibleLoras = settings.loras.filter((lora) => isLoraCompatibleWithModel(lora.model, model));+ const dimensions = getGenerationDimensions(model);+ const width = clampDimension(nextSettings.width, dimensions.grid);+ const height = clampDimension(nextSettings.height, dimensions.grid);++ if (width !== nextSettings.width || height !== nextSettings.height) {+ nextSettings.width = width;+ nextSettings.height = height;+ nextSettings.aspectRatioId = deriveAspectRatioId(width, height);+ nextSettings.aspectRatioValue = height > 0 ? width / height : 1;+ addClearedLabel(clearedLabels, 'Dimensions');+ }++ if (compatibleLoras.length !== settings.loras.length) {+ nextSettings.loras = compatibleLoras;+ addClearedLabel(clearedLabels, 'LoRAs');+ }++ const compatibleReferenceImages = getCompatibleReferenceImages(settings.referenceImages, model, models);++ if (compatibleReferenceImages !== settings.referenceImages) {+ nextSettings.referenceImages = compatibleReferenceImages;+ addClearedLabel(clearedLabels, 'Reference Images');+ }++ const policy = getComponentSectionPolicy(model, nextSettings);+ const slotsByKey = new Map(policy.slots.map((slotPolicy) => [slotPolicy.key, slotPolicy]));+ const uiPolicy = getGenerationUiPolicy(model, nextSettings);++ for (const key of Object.keys(COMPONENT_SETTING_LABELS) as GenerateComponentValueKey[]) {+ if (!nextSettings[key]) {+ continue;+ }++ if (key === 'vae' && !slotsByKey.has(key) && uiPolicy.sdVaeVisible && nextSettings.vae?.base === model.base) {+ continue;+ }++ if (!isSelectedComponentCompatible(slotsByKey.get(key), model, nextSettings, key)) {+ nextSettings[key] = null;+ addClearedLabel(clearedLabels, COMPONENT_SETTING_LABELS[key]);+ }+ }++ if (!uiPolicy.clipSkipMax && nextSettings.clipSkip !== 0) {+ nextSettings.clipSkip = 0;+ addClearedLabel(clearedLabels, 'CLIP skip');+ } else if (uiPolicy.clipSkipMax && nextSettings.clipSkip > uiPolicy.clipSkipMax) {+ nextSettings.clipSkip = uiPolicy.clipSkipMax;+ addClearedLabel(clearedLabels, 'CLIP skip');+ }++ if (!uiPolicy.cfgRescaleVisible && nextSettings.cfgRescaleMultiplier !== 0) {+ nextSettings.cfgRescaleMultiplier = 0;+ addClearedLabel(clearedLabels, 'CFG rescale');+ }++ if (!uiPolicy.colorCompensationVisible && nextSettings.colorCompensation) {+ nextSettings.colorCompensation = false;+ addClearedLabel(clearedLabels, 'Color compensation');+ }++ if (!uiPolicy.hiDiffusionVisible && nextSettings.hiDiffusionEnabled) {+ nextSettings.hiDiffusionEnabled = false;+ addClearedLabel(clearedLabels, 'HiDiffusion');+ }++ if (!uiPolicy.seamlessVisible && (nextSettings.seamlessXAxis || nextSettings.seamlessYAxis)) {+ nextSettings.seamlessXAxis = false;+ nextSettings.seamlessYAxis = false;+ addClearedLabel(clearedLabels, 'Seamless tiling');+ }++ if (!uiPolicy.vaePrecisionVisible) {+ const defaultVaePrecision = getGenerationDefaults(model).vaePrecision;++ if (nextSettings.vaePrecision !== defaultVaePrecision) {+ nextSettings.vaePrecision = defaultVaePrecision;+ addClearedLabel(clearedLabels, 'VAE precision');+ }+ }++ return { settings: nextSettings, clearedLabels };+};++/**+ * Canonical transition for every Generate model-selection entry point.+ * Normalizes persisted values, reconciles incompatible selections, and applies+ * automatic component-source policy before callers persist the result.+ */+export const getGenerateModelSelectionResult = ({+ currentValues,+ model,+ models,+}: {+ currentValues: unknown;+ model: GenerateModelConfig;+ models: readonly ModelConfig[];+}): GenerateModelSelectionResult => {+ const currentSettings = isGenerateSettings(currentValues)+ ? currentValues+ : (normalizeGenerateSettings(currentValues) ?? getDefaultGenerateSettings(model));+ const result = getSettingsWithCompatibleModelSelections(currentSettings, model, models);+ const componentSourceModel = getAutoFlux2ComponentSourceModel(model, result.settings, models);++ if (componentSourceModel === undefined || componentSourceModel?.key === result.settings.componentSourceModel?.key) {+ return result;+ }++ return {+ ...result,+ settings: { ...result.settings, componentSourceModel },+ };+};++const hasModelKey = (models: readonly ModelConfig[], key: string, type?: string): boolean =>+ models.some((model) => model.key === key && (!type || model.type === type));++export const getGenerationModelAvailabilityReasons = (+ model: GenerateModelConfig,+ settings: GenerateSettings,+ models: readonly ModelConfig[]+): string[] => {+ const reasons: string[] = [];++ if (!hasModelKey(models, model.key, model.type)) {+ reasons.push(`Selected model "${model.name}" is no longer installed.`);+ }++ for (const key of Object.keys(COMPONENT_SETTING_LABELS) as GenerateComponentValueKey[]) {+ const value = settings[key];++ if (value && !hasModelKey(models, value.key, value.type)) {+ reasons.push(`${COMPONENT_SETTING_LABELS[key]} "${value.name}" is no longer installed.`);+ }+ }++ for (const lora of settings.loras) {+ if (!hasModelKey(models, lora.model.key, 'lora')) {+ reasons.push(`LoRA "${lora.model.name}" is no longer installed.`);+ }+ }++ for (const referenceImage of settings.referenceImages) {+ if (!referenceImage.isEnabled) {+ continue;+ }++ const config = referenceImage.config;++ if ('model' in config && config.model && !hasModelKey(models, config.model.key, config.model.type)) {+ reasons.push(`Reference Image model "${config.model.name}" is no longer installed.`);+ }+ }++ return reasons;+};++const getDimensionValidationReasons = (model: GenerateModelConfig, settings: GenerateSettings): string[] => {+ const reasons: string[] = [];+ // The PiD-adjusted grid: in native mode the requested size is the 4x target, so it must+ // be a multiple of grid * 4 for requested / 4 to land on the model's own grid.+ const dimensions = getGenerationDimensions(model, settings.pidMode);++ if (!Number.isFinite(settings.width) || settings.width < dimensions.min || settings.width > dimensions.max) {+ reasons.push(`Generate width must be between ${dimensions.min} and ${dimensions.max}.`);+ } else if (settings.width % dimensions.grid !== 0) {+ reasons.push(`Generate width must be a multiple of ${dimensions.grid}.`);+ }++ if (!Number.isFinite(settings.height) || settings.height < dimensions.min || settings.height > dimensions.max) {+ reasons.push(`Generate height must be between ${dimensions.min} and ${dimensions.max}.`);+ } else if (settings.height % dimensions.grid !== 0) {+ reasons.push(`Generate height must be a multiple of ${dimensions.grid}.`);+ }++ return reasons;+};++/**+ * PiD guards beyond "are the models selected", which the component slots already cover.+ *+ * PiD is only wired for text-to-image here, so a mode left on for an unsupported base is+ * reported rather than silently ignored — otherwise the user would get an ordinary decode+ * and wonder why the image is not 4x.+ */+const getPidValidationReasons = (model: GenerateModelConfig, settings: GenerateSettings): string[] => {+ if (settings.pidMode === 'off') {+ return [];+ }++ if (!getIsPidSupportedBase(model.base)) {+ return [`PiD is not supported for ${model.name}. Turn PiD off to generate with this model.`];+ }++ const reasons: string[] = [];++ if (settings.pidSteps < 1) {+ reasons.push('PiD steps must be at least 1.');+ }++ return reasons;+};++const getReferenceImageValidationReasons = (model: GenerateModelConfig, settings: GenerateSettings): string[] => {+ const reasons: string[] = [];+ const enabled = settings.referenceImages.filter((referenceImage) => referenceImage.isEnabled);+ const maxReferenceImages =+ model.type === 'external_image_generator' && typeof model.capabilities?.max_reference_images === 'number'+ ? model.capabilities.max_reference_images+ : DEFAULT_REFERENCE_IMAGE_LIMIT;++ if (enabled.length > maxReferenceImages) {+ reasons.push(`Generate supports at most ${maxReferenceImages} reference images for ${model.name}.`);+ }++ enabled.forEach((referenceImage, index) => {+ const prefix = `Reference Image #${index + 1}`;++ if (!getReferenceImageConfigSupported(model, referenceImage)) {+ reasons.push(`${prefix} is not supported by ${model.base} model.`);+ return;+ }++ if (!referenceImage.config.image) {+ reasons.push(`${prefix} needs an image.`);+ }++ if (referenceImage.config.type === 'ip_adapter') {+ if (!referenceImage.config.model || referenceImage.config.model.base !== model.base) {+ reasons.push(`${prefix} needs a compatible IP Adapter model.`);+ }+ }++ if (referenceImage.config.type === 'flux_redux') {+ if (!referenceImage.config.model || referenceImage.config.model.base !== model.base) {+ reasons.push(`${prefix} needs a compatible FLUX Redux model.`);+ }+ }++ if (referenceImage.config.type === 'flux_kontext_reference_image') {+ if (!referenceImage.config.model || referenceImage.config.model.key !== model.key) {+ reasons.push(`${prefix} needs the selected FLUX Kontext model.`);+ }+ }+ });++ return reasons;+};++/**+ * Rules that belong to one model family and have no home in the component-slot policies:+ * the slot machinery validates model selections, not scalar parameters or LoRA pairings.+ */+const getModelFamilyValidationReasons = (model: MainModelConfig, settings: GenerateSettings): string[] => {+ const reasons: string[] = [];++ // The rebalance weights are free text forwarded straight to the backend's _parse_weights().+ // Catching a malformed string here beats failing mid-generation on a queued item.+ if (+ model.base === 'krea-2' &&+ settings.krea2RebalanceEnabled &&+ !isValidKrea2RebalanceWeights(settings.krea2RebalanceWeights)+ ) {+ reasons.push(`Krea-2 rebalance weights must be ${KREA2_REBALANCE_WEIGHT_COUNT} comma-separated numbers.`);+ }++ // A14B and 5B Wan LoRAs are not interchangeable — the layer patcher fails on a tensor-shape+ // mismatch. getActiveCompatibleLoras would silently drop a mismatched one, so say so instead.+ if (model.base === 'wan') {+ for (const lora of settings.loras) {+ if (lora.isEnabled && !isWanLoraTargetingMain(lora.model.variant, model.variant)) {+ reasons.push(`${lora.model.name} targets a different Wan model family than ${model.name}.`);+ }+ }+ }++ return reasons;+};++export const getGenerationValidationReasons = (model: GenerateModelConfig, settings: GenerateSettings): string[] => {+ if (!isSupportedGenerateModel(model)) {+ return ['Generate needs a supported model before it can be invoked.'];+ }++ const reasons = [+ ...getDimensionValidationReasons(model, settings),+ ...getReferenceImageValidationReasons(model, settings),+ ...getPidValidationReasons(model, settings),+ ];++ if (model.type === 'external_image_generator') {+ if (model.capabilities?.modes && !model.capabilities.modes.includes('txt2img')) {+ reasons.push(`${model.name} does not support text-to-image generation.`);+ }++ if (!getExternalProviderNodeType(model.provider_id)) {+ reasons.push(`No invocation node registered for external provider '${model.provider_id ?? ''}'.`);+ }++ return reasons;+ }++ const componentPolicy = getComponentSectionPolicy(model, settings);+ reasons.push(...componentPolicy.validate(getComponentPolicyContext(model, settings)));+ reasons.push(...getModelFamilyValidationReasons(model, settings));++ return reasons;+};diff --cc invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.tsindex 6c385c1e2a,0000000000..65b0bf460cmode 100644,000000..100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts@@@ -1,347 -1,0 +1,352 @@@+import type { BackendGraphContract, BackendInvocationContract } from '@features/generation/core/contracts';++import { addEdge, addNode } from '@features/generation/core/graphBuilder';++/** The deterministic denoise node id every canvas base graph uses. */+const DENOISE_NODE_ID = 'denoise_latents';+/** The deterministic global positive/negative conditioning + collector node ids. */+const POS_COND_ID = 'pos_cond';+const NEG_COND_ID = 'neg_cond';+const POS_COND_COLLECT_ID = 'pos_cond_collect';+const NEG_COND_COLLECT_ID = 'neg_cond_collect';++/** The base models regional guidance supports. */+export type RegionalGuidanceBase = 'sd-1' | 'sdxl' | 'flux' | 'flux2' | 'krea-2';++/** True when `base` supports regional guidance at all. */+export const isRegionalGuidanceSupportedForBase = (base: string): base is RegionalGuidanceBase =>+ base === 'sd-1' || base === 'sdxl' || base === 'flux' || base === 'flux2' || base === 'krea-2';++/** Whether a base supports regional NEGATIVE prompts / autoNegative (SD family only). */+const supportsRegionalNegative = (base: RegionalGuidanceBase): boolean => base === 'sd-1' || base === 'sdxl';++/** A resolved reference-image (component) model identifier — the backend model field shape. */+export interface RegionalReferenceModel {+ key: string;+ hash?: string;+ name: string;+ base: string;+ type: string;+}++/** A regional `ip_adapter` reference image (SD1 / SDXL). */+export interface RegionalIPAdapterInput {+ type: 'ip_adapter';+ /** The reference-image id (mints the deterministic `ip_adapter_${id}` node id). */+ id: string;+ imageName: string;+ model: RegionalReferenceModel;+ weight: number;+ method: string;+ clipVisionModel: string;+ beginEndStepPct: [number, number];+}++/** A regional `flux_redux` reference image (FLUX). */+export interface RegionalFluxReduxInput {+ type: 'flux_redux';+ /** The reference-image id (mints the deterministic `flux_redux_${id}` node id). */+ id: string;+ imageName: string;+ model: RegionalReferenceModel;+ /** Backend redux knobs (downsampling_factor + weight), resolved from imageInfluence upstream. */+ settings: { downsampling_factor: number; weight: number };+}++/** One resolved regional reference image. */+export type RegionalReferenceImageInput = RegionalIPAdapterInput | RegionalFluxReduxInput;++/** One fully-resolved region's graph contribution (invalid regions filtered out first). */+export interface RegionalGuidanceInput {+ /** The document layer id (mints deterministic node ids). */+ id: string;+ /** The uploaded per-region mask image name (alpha = region coverage). */+ maskImageName: string;+ positivePrompt: string | null;+ negativePrompt: string | null;+ autoNegative: boolean;+ referenceImages: readonly RegionalReferenceImageInput[];+}++/** Options for {@link addRegionalGuidance}. */+export interface AddRegionalGuidanceOptions {+ base: RegionalGuidanceBase;++ modelVariant?: string | null;+ regions: readonly RegionalGuidanceInput[];+ /** Applies model-specific transforms before a regional positive conditioning is collected. */+ transformRegionalPositiveConditioning?: (+ conditioning: BackendInvocationContract,+ regionId: string+ ) => BackendInvocationContract;+}++/** Per-base conditioning encoder node type + the fields carrying the prompt. */- const conditioningNodeType = (base: RegionalGuidanceBase): string => {++const conditioningNodeType = (base: RegionalGuidanceBase, modelVariant?: string | null): string => {+ switch (base) {+ case 'sdxl':+ return 'sdxl_compel_prompt';+ case 'flux':+ return 'flux_text_encoder';+ case 'flux2':- return 'flux2_klein_text_encoder';++ return modelVariant === 'dev' ? 'flux2_dev_text_encoder' : 'flux2_klein_text_encoder';+ case 'krea-2':+ return 'krea2_text_encoder';+ case 'sd-1':+ return 'compel';+ }+};++/** The prompt input fields to set on a regional conditioning node (SDXL mirrors prompt→style). */+const promptFields = (base: RegionalGuidanceBase): readonly string[] =>+ base === 'sdxl' ? ['prompt', 'style'] : ['prompt'];++/**+ * The encoder-input fields to COPY from the global conditioning node onto a+ * regional one, so the region shares the same CLIP / T5 encoders (legacy copies+ * the CLIP/T5 edges verbatim). `mask` is wired separately, so it's excluded here.+ */- const copyEncoderFields = (base: RegionalGuidanceBase): readonly string[] => {++const copyEncoderFields = (base: RegionalGuidanceBase, modelVariant?: string | null): readonly string[] => {+ switch (base) {+ case 'sdxl':+ return ['clip', 'clip2'];+ case 'flux':+ return ['clip', 't5_encoder', 't5_max_seq_len'];+ case 'flux2':- return ['qwen3_encoder', 'max_seq_len'];++ return modelVariant === 'dev' ? ['mistral_encoder', 'max_seq_len'] : ['qwen3_encoder', 'max_seq_len'];+ case 'krea-2':+ return ['qwen3_vl_encoder'];+ case 'sd-1':+ return ['clip'];+ }+};++/**+ * Copies every edge feeding `sourceNodeId`'s `fields` onto `target` (same source,+ * same field). Used to share the global conditioning node's CLIP/T5 encoder+ * inputs with a per-region conditioning node.+ */+const copyEncoderEdges = (+ graph: BackendGraphContract,+ sourceNodeId: string,+ target: BackendInvocationContract,+ fields: readonly string[]+): void => {+ const fieldSet = new Set(fields);+ for (const edge of graph.edges) {+ if (edge.destination.node_id !== sourceNodeId || !fieldSet.has(edge.destination.field)) {+ continue;+ }+ graph.edges.push({+ destination: { field: edge.destination.field, node_id: target.id },+ source: { field: edge.source.field, node_id: edge.source.node_id },+ });+ }+};++/** Resolves (or lazily creates) the collector feeding `denoise.<field>`, with a stable fallback id. */+const resolveDenoiseCollector = (+ graph: BackendGraphContract,+ denoise: BackendInvocationContract,+ denoiseField: string,+ fallbackId: string+): BackendInvocationContract => {+ const existing = graph.edges.find(+ (edge) => edge.destination.node_id === denoise.id && edge.destination.field === denoiseField+ );+ if (existing) {+ const node = graph.nodes[existing.source.node_id];+ if (node) {+ return node;+ }+ }+ const collector = addNode(graph, { id: fallbackId, type: 'collect' });+ addEdge(graph, collector, 'collection', denoise, denoiseField);+ return collector;+};++/** Builds a per-region conditioning node with its prompt set and encoder edges copied. */+const addRegionalConditioning = (+ graph: BackendGraphContract,+ base: RegionalGuidanceBase,++ modelVariant: string | null | undefined,+ nodeId: string,+ prompt: string,+ copyFrom: string+): BackendInvocationContract => {- const node = addNode(graph, { id: nodeId, type: conditioningNodeType(base) });++ const node = addNode(graph, { id: nodeId, type: conditioningNodeType(base, modelVariant) });+ for (const field of promptFields(base)) {+ (node as Record<string, unknown>)[field] = prompt;+ }- copyEncoderEdges(graph, copyFrom, node, copyEncoderFields(base));++ copyEncoderEdges(graph, copyFrom, node, copyEncoderFields(base, modelVariant));+ return node;+};++/**+ * Grafts regional guidance onto a built canvas base graph. Assumes every input is+ * already validated for `base` (supported base, non-empty region, resolved+ * reference-image models) — use {@link getRegionalGuidanceRejectionReason} to+ * filter first. Wires, per enabled region:+ * - `alpha_mask_to_tensor` from the uploaded region mask;+ * - positive prompt → regional conditioning → `pos_cond_collect`;+ * - negative prompt (SD only) → regional conditioning → `neg_cond_collect`;+ * - autoNegative (SD only) → `invert_tensor_mask` + positive prompt re-encoded →+ * `neg_cond_collect` (push the positive prompt away outside the region);+ * - reference images → mask-scoped `ip_adapter` (SD) / `flux_redux` (FLUX).+ */+export const addRegionalGuidance = (graph: BackendGraphContract, options: AddRegionalGuidanceOptions): void => {- const { base, regions, transformRegionalPositiveConditioning } = options;++ const { base, modelVariant, regions, transformRegionalPositiveConditioning } = options;+ const denoise = graph.nodes[DENOISE_NODE_ID];+ if (!denoise) {+ throw new Error('addRegionalGuidance: base graph is missing the denoise node.');+ }+ const posCondCollect = graph.nodes[POS_COND_COLLECT_ID];+ if (!posCondCollect) {+ throw new Error('addRegionalGuidance: base graph is missing the positive conditioning collector.');+ }+ const negCondCollect = graph.nodes[NEG_COND_COLLECT_ID] ?? null;+ const withNegative = supportsRegionalNegative(base);++ let ipAdapterCollector: BackendInvocationContract | null = null;+ let fluxReduxCollector: BackendInvocationContract | null = null;++ for (const region of regions) {+ const maskToTensor = addNode(graph, {+ id: `rg_mask_to_tensor_${region.id}`,+ image: { image_name: region.maskImageName },+ type: 'alpha_mask_to_tensor',+ });++ // Positive prompt → positive collector (mask-scoped).+ if (region.positivePrompt) {+ const posCond = addRegionalConditioning(+ graph,+ base,++ modelVariant,+ `rg_pos_cond_${region.id}`,+ region.positivePrompt,+ POS_COND_ID+ );+ addEdge(graph, maskToTensor, 'mask', posCond, 'mask');+ const conditioningSource = transformRegionalPositiveConditioning?.(posCond, region.id) ?? posCond;+ addEdge(graph, conditioningSource, 'conditioning', posCondCollect, 'item');+ }++ // Negative prompt → negative collector (SD only; FLUX has no negative path).+ if (region.negativePrompt && withNegative && negCondCollect) {+ const negCond = addRegionalConditioning(+ graph,+ base,++ modelVariant,+ `rg_neg_cond_${region.id}`,+ region.negativePrompt,+ NEG_COND_ID+ );+ addEdge(graph, maskToTensor, 'mask', negCond, 'mask');+ addEdge(graph, negCond, 'conditioning', negCondCollect, 'item');+ }++ // autoNegative: re-encode the POSITIVE prompt over the INVERTED mask into the+ // negative collector — pushes the region's prompt away everywhere outside it.+ if (region.autoNegative && region.positivePrompt && withNegative && negCondCollect) {+ const invert = addNode(graph, { id: `rg_invert_mask_${region.id}`, type: 'invert_tensor_mask' });+ addEdge(graph, maskToTensor, 'mask', invert, 'mask');+ const inverted = addRegionalConditioning(+ graph,+ base,++ modelVariant,+ `rg_pos_cond_inverted_${region.id}`,+ region.positivePrompt,+ POS_COND_ID+ );+ addEdge(graph, invert, 'mask', inverted, 'mask');+ addEdge(graph, inverted, 'conditioning', negCondCollect, 'item');+ }++ // Reference images (mask-scoped): ip_adapter on SD, flux_redux on FLUX.+ for (const ref of region.referenceImages) {+ if (ref.type === 'ip_adapter' && (base === 'sd-1' || base === 'sdxl')) {+ if (!ipAdapterCollector) {+ ipAdapterCollector = resolveDenoiseCollector(graph, denoise, 'ip_adapter', 'regional_ip_adapter_collector');+ }+ const node = addNode(graph, {+ begin_step_percent: ref.beginEndStepPct[0],+ clip_vision_model: ref.clipVisionModel,+ end_step_percent: ref.beginEndStepPct[1],+ id: `ip_adapter_${ref.id}`,+ image: { image_name: ref.imageName },+ ip_adapter_model: ref.model,+ method: ref.method,+ type: 'ip_adapter',+ weight: ref.weight,+ });+ addEdge(graph, maskToTensor, 'mask', node, 'mask');+ addEdge(graph, node, 'ip_adapter', ipAdapterCollector, 'item');+ } else if (ref.type === 'flux_redux' && base === 'flux') {+ if (!fluxReduxCollector) {+ fluxReduxCollector = resolveDenoiseCollector(+ graph,+ denoise,+ 'redux_conditioning',+ 'regional_flux_redux_collector'+ );+ }+ const node = addNode(graph, {+ downsampling_factor: ref.settings.downsampling_factor,+ id: `flux_redux_${ref.id}`,+ image: { image_name: ref.imageName },+ redux_model: ref.model,+ type: 'flux_redux',+ weight: ref.settings.weight,+ });+ addEdge(graph, maskToTensor, 'mask', node, 'mask');+ addEdge(graph, node, 'redux_cond', fluxReduxCollector, 'item');+ }+ }+ }+};++/**+ * Returns the legacy-parity rejection reason for a regional-guidance region, or+ * `null` when it can contribute to generation. Mirrors+ * `getRegionalGuidanceWarnings`:+ * - unsupported main base (sd-2 / sd-3 / cogview / …) → "unsupported model";+ * - no drawn mask content → "no region";+ * - no positive prompt, no negative prompt, and no reference images → "empty";+ * - FLUX-family and Krea-2 negative prompts / autoNegative are unsupported;+ * - FLUX.2 and Krea-2 regional reference images are unsupported.+ *+ * Per-reference-image model/image validity is resolved by the caller (which drops+ * incomplete reference images before building), matching how control layers work.+ */+export const getRegionalGuidanceRejectionReason = (params: {+ layerName: string;+ mainBase: string;+ hasContent: boolean;+ positivePrompt: string | null;+ negativePrompt: string | null;+ autoNegative: boolean;+ referenceImageCount: number;+}): string | null => {+ const { autoNegative, hasContent, layerName, mainBase, negativePrompt, positivePrompt, referenceImageCount } = params;++ if (!isRegionalGuidanceSupportedForBase(mainBase)) {+ return `Regional guidance "${layerName}" is not supported for the selected base model.`;+ }+ if (!hasContent) {+ return `Regional guidance "${layerName}" has no masked region.`;+ }+ if (!positivePrompt && !negativePrompt && referenceImageCount === 0) {+ return `Regional guidance "${layerName}" has no prompt or reference image.`;+ }+ const positiveOnlyLabel = mainBase === 'flux' ? 'FLUX' : mainBase === 'flux2' ? 'FLUX.2' : 'Krea-2';+ if ((mainBase === 'flux' || mainBase === 'flux2' || mainBase === 'krea-2') && negativePrompt) {+ return `Regional guidance "${layerName}" negative prompts are not supported for ${positiveOnlyLabel}.`;+ }+ if ((mainBase === 'flux' || mainBase === 'flux2' || mainBase === 'krea-2') && autoNegative) {+ return `Regional guidance "${layerName}" auto-negative is not supported for ${positiveOnlyLabel}.`;+ }+ if ((mainBase === 'flux2' || mainBase === 'krea-2') && referenceImageCount > 0) {+ return `Regional guidance "${layerName}" reference images are not supported for ${positiveOnlyLabel}.`;+ }+ return null;+};diff --cc invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.tsindex d082282819,0000000000..04ae26fe13mode 100644,000000..100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts@@@ -1,806 -1,0 +1,820 @@@+import type { BackendGraphContract, GenerationProjectSettings } from '@features/generation/core/contracts';+import type {+ ComponentModelConfig,+ GenerateModelConfig,+ GenerateSettings,+ MainModelConfig,+ VaeModelConfig,+} from '@features/generation/core/types';++import { getDefaultGenerateSettings } from '@features/generation/core/baseGenerationPolicies';+import { describe, expect, it } from 'vitest';++import type { ControlLayerGraphInput } from './addControlLayers';+import type { RegionalGuidanceInput } from './addRegionalGuidance';+import type { CanvasCompileMode, CanvasCompositingSettings, Rect } from './types';++import { compileCanvasGraph } from './compileCanvasGraph';+import { DEFAULT_CANVAS_COMPOSITING } from './types';++const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };+const sd2Model: MainModelConfig = { base: 'sd-2', key: 'sd2-model', name: 'SD 2', type: 'main' };+const sdxlModel: MainModelConfig = { base: 'sdxl', key: 'sdxl-model', name: 'SDXL', type: 'main' };+const sd3Model: MainModelConfig = { base: 'sd-3', key: 'sd3-model', name: 'SD3', type: 'main' };+const fluxModel: MainModelConfig = { base: 'flux', key: 'flux-model', name: 'FLUX dev', type: 'main' };+const flux2Model: MainModelConfig = {+ base: 'flux2',+ format: 'diffusers',+ key: 'flux2-model',+ name: 'FLUX.2',+ type: 'main',+};++const flux2DevModel: MainModelConfig = {++ ...flux2Model,++ key: 'flux2-dev-model',++ name: 'FLUX.2 [dev]',++ variant: 'dev',++};+const cogView4Model: MainModelConfig = { base: 'cogview4', key: 'cog-model', name: 'CogView4', type: 'main' };+const qwenImageModel: MainModelConfig = {+ base: 'qwen-image',+ format: 'diffusers',+ key: 'qwen-model',+ name: 'Qwen Image',+ type: 'main',+};+const zImageModel: MainModelConfig = {+ base: 'z-image',+ format: 'diffusers',+ key: 'z-model',+ name: 'Z-Image',+ type: 'main',+};+const animaModel: MainModelConfig = { base: 'anima', key: 'anima-model', name: 'Anima', type: 'main' };+const krea2Model: MainModelConfig = {+ base: 'krea-2',+ format: 'diffusers',+ key: 'krea2-model',+ name: 'Krea-2',+ type: 'main',+};+const externalModel: GenerateModelConfig = {+ base: 'external',+ capabilities: { modes: ['txt2img'], supports_seed: true },+ format: 'external_api',+ key: 'external-model',+ name: 'OpenAI Image',+ provider_id: 'openai',+ type: 'external_image_generator',+};++const fluxVae: VaeModelConfig = { base: 'flux', key: 'flux-vae', name: 'FLUX VAE', type: 'vae' };+const qwenImageVae: VaeModelConfig = { base: 'qwen-image', key: 'qwen-vae', name: 'Qwen VAE', type: 'vae' };+const t5Encoder: ComponentModelConfig = { base: 'any', key: 't5', name: 'T5 Encoder', type: 't5_encoder' };+const clipEmbed: ComponentModelConfig = { base: 'any', key: 'clip', name: 'CLIP Embed', type: 'clip_embed' };+const qwen3Encoder: ComponentModelConfig = {+ base: 'any',+ key: 'qwen3',+ name: 'Qwen3 Encoder',+ type: 'qwen3_encoder',+ variant: 'qwen3_06b',+};++const PROJECT_SETTINGS: GenerationProjectSettings = { useCpuNoise: true };++const settingsFor = (model: GenerateModelConfig, overrides: Partial<GenerateSettings> = {}): GenerateSettings => ({+ ...getDefaultGenerateSettings(model),+ seed: 1,+ shouldRandomizeSeed: false,+ ...overrides,+});++/** Per-base overrides needed to pass component validation. */+const COMPONENT_OVERRIDES: Partial<Record<string, Partial<GenerateSettings>>> = {+ flux: { clipEmbedModel: clipEmbed, t5EncoderModel: t5Encoder, vae: fluxVae },+ anima: { qwen3EncoderModel: qwen3Encoder, vae: qwenImageVae },+};++const bbox: Rect = { height: 1024, width: 768, x: 128, y: 64 };++const compile = (+ model: GenerateModelConfig,+ mode: CanvasCompileMode,+ overrides: {+ settings?: Partial<GenerateSettings>;+ bbox?: Rect;+ compositeImageName?: string | null;+ maskImageName?: string | null;+ noiseMaskImageName?: string | null;+ compositing?: Partial<CanvasCompositingSettings>;+ strength?: number;+ destination?: 'canvas' | 'gallery';+ controlLayers?: readonly ControlLayerGraphInput[];+ regionalGuidance?: readonly RegionalGuidanceInput[];+ } = {}+) =>+ compileCanvasGraph({+ bbox: overrides.bbox ?? bbox,+ compositeImageName:+ 'compositeImageName' in overrides ? (overrides.compositeImageName ?? null) : 'canvas-composite.png',+ compositing: overrides.compositing+ ? { ...DEFAULT_CANVAS_COMPOSITING, ...overrides.compositing }+ : DEFAULT_CANVAS_COMPOSITING,+ controlLayers: overrides.controlLayers,+ regionalGuidance: overrides.regionalGuidance,+ destination: overrides.destination ?? 'canvas',+ maskImageName:+ 'maskImageName' in overrides ? overrides.maskImageName : mode === 'inpaint' ? 'canvas-mask.png' : null,+ mode,+ model,+ noiseMaskImageName: overrides.noiseMaskImageName ?? null,+ projectSettings: PROJECT_SETTINGS,+ settings: settingsFor(model, {+ ...COMPONENT_OVERRIDES[model.base],+ ...overrides.settings,+ }),+ strength: overrides.strength ?? 0.6,+ });++const getEdge = (graph: BackendGraphContract, targetNodeId: string, targetField: string) =>+ graph.edges.find((edge) => edge.destination.node_id === targetNodeId && edge.destination.field === targetField);++const getNodeByType = (graph: BackendGraphContract, type: string) =>+ Object.values(graph.nodes).find((node) => node.type === type);++interface BaseCase {+ model: MainModelConfig;+ encodeType: string;+ outputType: string;+ denoiseType: string;+ txt2imgMode: string;+ img2imgMode: string;+ /** sd-3 / flux / flux2 rescale strength with an exponent of 0.2 (legacy parity). */+ optimizedDenoising: boolean;+}++/** Legacy-equivalent denoising_start for a strength on a given base. */+const expectedDenoisingStart = (strength: number, optimizedDenoising: boolean): number =>+ 1 - strength ** (optimizedDenoising ? 0.2 : 1);++const BASE_CASES: BaseCase[] = [+ {+ model: sd1Model,+ encodeType: 'i2l',+ outputType: 'l2i',+ denoiseType: 'denoise_latents',+ txt2imgMode: 'txt2img',+ img2imgMode: 'img2img',+ optimizedDenoising: false,+ },+ {+ model: sd2Model,+ encodeType: 'i2l',+ outputType: 'l2i',+ denoiseType: 'denoise_latents',+ txt2imgMode: 'txt2img',+ img2imgMode: 'img2img',+ optimizedDenoising: false,+ },+ {+ model: sdxlModel,+ encodeType: 'i2l',+ outputType: 'l2i',+ denoiseType: 'denoise_latents',+ txt2imgMode: 'sdxl_txt2img',+ img2imgMode: 'sdxl_img2img',+ optimizedDenoising: false,+ },+ {+ model: sd3Model,+ encodeType: 'sd3_i2l',+ outputType: 'sd3_l2i',+ denoiseType: 'sd3_denoise',+ txt2imgMode: 'sd3_txt2img',+ img2imgMode: 'sd3_img2img',+ optimizedDenoising: true,+ },+ {+ model: fluxModel,+ encodeType: 'flux_vae_encode',+ outputType: 'flux_vae_decode',+ denoiseType: 'flux_denoise',+ txt2imgMode: 'flux_txt2img',+ img2imgMode: 'flux_img2img',+ optimizedDenoising: true,+ },+ {+ model: flux2Model,+ encodeType: 'flux2_vae_encode',+ outputType: 'flux2_vae_decode',+ denoiseType: 'flux2_denoise',+ txt2imgMode: 'flux2_txt2img',+ img2imgMode: 'flux2_img2img',+ optimizedDenoising: true,+ },+ {+ model: cogView4Model,+ encodeType: 'cogview4_i2l',+ outputType: 'cogview4_l2i',+ denoiseType: 'cogview4_denoise',+ txt2imgMode: 'cogview4_txt2img',+ img2imgMode: 'cogview4_img2img',+ optimizedDenoising: false,+ },+ {+ model: qwenImageModel,+ encodeType: 'qwen_image_i2l',+ outputType: 'qwen_image_l2i',+ denoiseType: 'qwen_image_denoise',+ txt2imgMode: 'qwen_image_txt2img',+ img2imgMode: 'qwen_image_img2img',+ optimizedDenoising: false,+ },+ {+ model: zImageModel,+ encodeType: 'z_image_i2l',+ outputType: 'z_image_l2i',+ denoiseType: 'z_image_denoise',+ txt2imgMode: 'z_image_txt2img',+ img2imgMode: 'z_image_img2img',+ optimizedDenoising: false,+ },+ {+ model: animaModel,+ encodeType: 'anima_i2l',+ outputType: 'anima_l2i',+ denoiseType: 'anima_denoise',+ txt2imgMode: 'anima_txt2img',+ img2imgMode: 'anima_img2img',+ optimizedDenoising: false,+ },+];++describe('compileCanvasGraph', () => {+ describe('txt2img per base', () => {+ it.each(BASE_CASES)(+ 'builds a $model.base txt2img graph sized to the bbox',+ ({ model, outputType, txt2imgMode }) => {+ const { backendGraph, graph, mode } = compile(model, 'txt2img');++ // No img2img encode node in a pure txt2img graph.+ expect(getNodeByType(backendGraph, 'i2l')).toBeUndefined();+ expect(getNodeByType(backendGraph, `${model.base}_i2l`)).toBeUndefined();+ expect(getNodeByType(backendGraph, `${model.base}_vae_encode`)).toBeUndefined();++ // Canvas destination: intermediate output of the base builder's decode type.+ expect(backendGraph.nodes.canvas_output?.type).toBe(outputType);+ expect(backendGraph.nodes.canvas_output?.is_intermediate).toBe(true);++ // Deterministic prompt/seed node ids are present.+ expect(backendGraph.nodes.positive_prompt).toBeDefined();+ expect(backendGraph.nodes.seed).toBeDefined();++ // Dimensions come from the bbox, not the settings.+ expect(getNodeByType(backendGraph, 'core_metadata')?.width).toBe(bbox.width);+ expect(getNodeByType(backendGraph, 'core_metadata')?.height).toBe(bbox.height);+ expect(getNodeByType(backendGraph, 'core_metadata')?.generation_mode).toBe(txt2imgMode);++ expect(mode).toBe('txt2img');+ expect(graph.label).toBe(`${model.name} txt2img`);+ }+ );++ it('applies bbox dimensions to the SD noise node', () => {+ const { backendGraph } = compile(sd1Model, 'txt2img');++ expect(backendGraph.nodes.noise?.width).toBe(bbox.width);+ expect(backendGraph.nodes.noise?.height).toBe(bbox.height);+ });++ it('produces a durable (non-intermediate) output for a Gallery destination', () => {+ // Canvas destination stages an intermediate; Gallery must be a durable image.+ expect(compile(sd1Model, 'txt2img').backendGraph.nodes.canvas_output?.is_intermediate).toBe(true);+ expect(+ compile(sd1Model, 'txt2img', { destination: 'gallery' }).backendGraph.nodes.canvas_output?.is_intermediate+ ).toBe(false);+ });++ it('applies bbox dimensions to a flow-model denoise node', () => {+ const { backendGraph } = compile(fluxModel, 'txt2img');++ expect(backendGraph.nodes.denoise_latents?.width).toBe(bbox.width);+ expect(backendGraph.nodes.denoise_latents?.height).toBe(bbox.height);+ });+ });++ describe('img2img per base', () => {+ it.each(BASE_CASES)(+ 'grafts a $model.base image-to-latents encode node',+ ({ model, encodeType, denoiseType, img2imgMode, optimizedDenoising }) => {+ const { backendGraph, mode } = compile(model, 'img2img', { strength: 0.6 });++ const encode = getNodeByType(backendGraph, encodeType);+ expect(encode).toBeDefined();+ expect(encode?.image).toEqual({ image_name: 'canvas-composite.png' });++ // image → encode → denoise.latents+ expect(getEdge(backendGraph, encode!.id, 'vae')).toBeDefined();+ expect(getEdge(backendGraph, 'denoise_latents', 'latents')?.source.node_id).toBe(encode?.id);++ // denoising_start follows the base's strength curve (linear, or the+ // exponent-0.2 optimized curve for sd-3 / flux / flux2).+ expect(backendGraph.nodes.denoise_latents?.type).toBe(denoiseType);+ expect(backendGraph.nodes.denoise_latents?.denoising_start).toBeCloseTo(+ expectedDenoisingStart(0.6, optimizedDenoising),+ 10+ );+ expect(backendGraph.nodes.denoise_latents?.denoising_end).toBe(1);++ // metadata reflects the img2img mode + strength.+ const metadata = getNodeByType(backendGraph, 'core_metadata');+ expect(metadata?.generation_mode).toBe(img2imgMode);+ expect(metadata?.strength).toBe(0.6);++ expect(mode).toBe('img2img');+ }+ );++ it('feeds the encode node from the same VAE source as the decode node', () => {+ const { backendGraph } = compile(sd1Model, 'img2img');+ const encode = getNodeByType(backendGraph, 'i2l');+ const decodeVaeSource = getEdge(backendGraph, 'canvas_output', 'vae')?.source.node_id;+ const encodeVaeSource = getEdge(backendGraph, encode!.id, 'vae')?.source.node_id;++ expect(encodeVaeSource).toBe(decodeVaeSource);+ expect(encodeVaeSource).toBe('model_loader');+ });++ it('routes the encode VAE through the seamless node when tiling is enabled', () => {+ const { backendGraph } = compile(sd1Model, 'img2img', { settings: { seamlessXAxis: true } });+ const encode = getNodeByType(backendGraph, 'i2l');++ expect(getEdge(backendGraph, encode!.id, 'vae')?.source.node_id).toBe('seamless');+ });++ it('mirrors the decode precision onto the SD encode node', () => {+ const fp16 = compile(sd1Model, 'img2img', { settings: { vaePrecision: 'fp16' } });+ expect(getNodeByType(fp16.backendGraph, 'i2l')?.fp32).toBe(false);++ const fp32 = compile(sd1Model, 'img2img', { settings: { vaePrecision: 'fp32' } });+ expect(getNodeByType(fp32.backendGraph, 'i2l')?.fp32).toBe(true);+ });++ it('does not attach fp32 to non-SD encode nodes', () => {+ const { backendGraph } = compile(fluxModel, 'img2img');++ expect(getNodeByType(backendGraph, 'flux_vae_encode')?.fp32).toBeUndefined();+ });++ it('threads the composite image name into the encode node', () => {+ const { backendGraph } = compile(sdxlModel, 'img2img', { compositeImageName: 'my-upload.png' });++ expect(getNodeByType(backendGraph, 'i2l')?.image).toEqual({ image_name: 'my-upload.png' });+ });++ it('reflects strength in denoising_start', () => {+ const { backendGraph } = compile(sd1Model, 'img2img', { strength: 0.25 });++ expect(backendGraph.nodes.denoise_latents?.denoising_start).toBeCloseTo(0.75, 10);+ });++ it.each([sd3Model, fluxModel, flux2Model])(+ 'rescales strength with the optimized (exponent-0.2) curve for $base',+ (model) => {+ const { backendGraph } = compile(model, 'img2img', { strength: 0.75 });++ // Legacy parity: 1 - 0.75 ** 0.2 ≈ 0.056 (not the linear 0.25).+ expect(backendGraph.nodes.denoise_latents?.denoising_start).toBeCloseTo(1 - 0.75 ** 0.2, 10);+ }+ );+ });++ describe('unsupported models', () => {+ it('rejects external image generators for txt2img', () => {+ expect(() => compile(externalModel, 'txt2img')).toThrow('does not support canvas generation');+ });++ it('rejects external image generators for img2img', () => {+ expect(() => compile(externalModel, 'img2img')).toThrow('does not support canvas generation');+ });++ it('rejects PiD with an actionable message rather than an internal VAE error', () => {+ // Canvas compilation resolves the VAE from a `canvas_output.vae` edge and renames+ // that node when compositing back; a PiD chain has neither, so without the guard+ // this surfaces as "could not resolve a VAE source in the base graph".+ for (const mode of ['txt2img', 'img2img'] as const) {+ expect(() =>+ compile(sdxlModel, mode, {+ settings: {+ gemma2EncoderModel: { base: 'any', key: 'g', name: 'Gemma 2', type: 'gemma2_encoder' },+ pidDecoderModel: { base: 'sdxl', key: 'pid', name: 'PiD SDXL', type: 'pid_decoder' },+ pidMode: 'fit',+ },+ })+ ).toThrow('PiD decoding is not supported on the canvas yet.');+ }+ });+ });++ describe('validation', () => {+ it('rejects img2img without a composite image', () => {+ expect(() => compile(sd1Model, 'img2img', { compositeImageName: null })).toThrow(+ 'Canvas generation requires a composited source image.'+ );+ });++ it('rejects a strength of zero', () => {+ expect(() => compile(sd1Model, 'img2img', { strength: 0 })).toThrow(+ 'Canvas denoising strength must be greater than 0 and at most 1.'+ );+ });++ it('rejects a strength above one', () => {+ expect(() => compile(sd1Model, 'img2img', { strength: 1.5 })).toThrow(+ 'Canvas denoising strength must be greater than 0 and at most 1.'+ );+ });++ it('accepts a strength of exactly one', () => {+ const { backendGraph } = compile(sd1Model, 'img2img', { strength: 1 });++ expect(backendGraph.nodes.denoise_latents?.denoising_start).toBe(0);+ });++ it('rejects a zero-area bbox', () => {+ expect(() => compile(sd1Model, 'txt2img', { bbox: { height: 0, width: 512, x: 0, y: 0 } })).toThrow(+ 'Canvas bounding box must have a positive area.'+ );+ });++ it('rejects off-grid bbox dimensions', () => {+ expect(() => compile(flux2Model, 'txt2img', { bbox: { height: 888, width: 1024, x: 0, y: 0 } })).toThrow(+ 'Generate height must be a multiple of 16.'+ );+ });++ it('surfaces missing-component validation for the bbox-sized settings', () => {+ // FLUX with no component overrides fails the shared generate validation.+ expect(() =>+ compileCanvasGraph({+ bbox,+ compositeImageName: null,+ destination: 'canvas',+ mode: 'txt2img',+ model: fluxModel,+ projectSettings: PROJECT_SETTINGS,+ settings: settingsFor(fluxModel),+ strength: 0.6,+ })+ ).toThrow('Generate needs a T5 Encoder for FLUX models.');+ });+ });+});++describe('compileCanvasGraph — inpaint per base', () => {+ it.each(BASE_CASES)(+ 'grafts a $model.base inpaint pipeline (encode, gradient mask, blend composite-back)',+ ({ model, encodeType, outputType, denoiseType, txt2imgMode, optimizedDenoising }) => {+ const { backendGraph, mode } = compile(model, 'inpaint', { strength: 0.6 });+ expect(mode).toBe('inpaint');++ // Encode fed by the initial composite image → denoise.latents.+ const encode = getNodeByType(backendGraph, encodeType);+ expect(encode).toBeDefined();+ expect(encode?.image).toEqual({ image_name: 'canvas-composite.png' });+ expect(getEdge(backendGraph, 'denoise_latents', 'latents')?.source.node_id).toBe(encode?.id);++ // create_gradient_mask carries coherence params + the mask image, and feeds denoise_mask.+ const gradient = backendGraph.nodes.create_gradient_mask;+ expect(gradient?.type).toBe('create_gradient_mask');+ expect(gradient?.coherence_mode).toBe('Gaussian Blur');+ expect(gradient?.edge_radius).toBe(16);+ expect(gradient?.minimum_denoise).toBe(0);+ expect(gradient?.image).toEqual({ image_name: 'canvas-composite.png' });+ expect(gradient?.mask).toEqual({ image_name: 'canvas-mask.png' });+ expect(getEdge(backendGraph, 'denoise_latents', 'denoise_mask')?.source.node_id).toBe('create_gradient_mask');++ // fp32 only on the SD gradient mask (mirrors the SD i2l).+ expect(gradient?.fp32).toBe(encodeType === 'i2l');++ // The base decode is demoted to an intermediate canvas_l2i; the blend is canvas_output.+ expect(backendGraph.nodes.canvas_l2i?.type).toBe(outputType);+ expect(backendGraph.nodes.canvas_l2i?.is_intermediate).toBe(true);+ const blend = backendGraph.nodes.canvas_output;+ expect(blend?.type).toBe('invokeai_img_blend');+ expect(blend?.is_intermediate).toBe(true);+ expect(blend?.layer_base).toEqual({ image_name: 'canvas-composite.png' });+ expect(getEdge(backendGraph, 'canvas_output', 'layer_upper')?.source.node_id).toBe('canvas_l2i');++ // expand_mask_with_fade uses the mask blur and feeds the blend mask.+ expect(backendGraph.nodes.expand_mask?.type).toBe('expand_mask_with_fade');+ expect(backendGraph.nodes.expand_mask?.fade_size_px).toBe(16);+ expect(getEdge(backendGraph, 'expand_mask', 'mask')?.source.node_id).toBe('create_gradient_mask');+ expect(getEdge(backendGraph, 'canvas_output', 'mask')?.source.node_id).toBe('expand_mask');++ // Strength curve + metadata mode.+ expect(backendGraph.nodes.denoise_latents?.type).toBe(denoiseType);+ expect(backendGraph.nodes.denoise_latents?.denoising_start).toBeCloseTo(+ expectedDenoisingStart(0.6, optimizedDenoising)+ );+ const metadata = getNodeByType(backendGraph, 'core_metadata');+ expect(metadata?.generation_mode).toBe(txt2imgMode.replace('txt2img', 'inpaint'));+ expect(metadata?.strength).toBe(0.6);+ }+ );++ it('re-points core_metadata onto the final blend output (not the intermediate decode)', () => {+ const { backendGraph } = compile(sd1Model, 'inpaint');+ const metadata = getNodeByType(backendGraph, 'core_metadata')!;+ const metaEdge = backendGraph.edges.find(+ (edge) => edge.source.node_id === metadata.id && edge.destination.field === 'metadata'+ );+ expect(metaEdge?.destination.node_id).toBe('canvas_output');+ });++ it('wires a UNet edge into create_gradient_mask only for SD-family models', () => {+ const sd = compile(sd1Model, 'inpaint').backendGraph;+ expect(getEdge(sd, 'create_gradient_mask', 'unet')).toBeDefined();+ const flux = compile(fluxModel, 'inpaint').backendGraph;+ expect(getEdge(flux, 'create_gradient_mask', 'unet')).toBeUndefined();+ });++ it('inserts an img_noise node before encode when a noise mask is present', () => {+ const { backendGraph } = compile(sd1Model, 'inpaint', { noiseMaskImageName: 'noise.png' });+ const noise = backendGraph.nodes.add_inpaint_noise;+ expect(noise?.type).toBe('img_noise');+ expect(noise?.image).toEqual({ image_name: 'canvas-composite.png' });+ expect(noise?.mask).toEqual({ image_name: 'noise.png' });+ expect(getEdge(backendGraph, 'add_inpaint_noise', 'seed')?.source.node_id).toBe('seed');+ // noise → i2l.image+ expect(getEdge(backendGraph, 'canvas_i2l', 'image')?.source.node_id).toBe('add_inpaint_noise');+ });++ it('feeds the composite directly into i2l when there is no noise mask', () => {+ const { backendGraph } = compile(sd1Model, 'inpaint');+ expect(backendGraph.nodes.add_inpaint_noise).toBeUndefined();+ expect(backendGraph.nodes.canvas_i2l?.image).toEqual({ image_name: 'canvas-composite.png' });+ });++ it('rejects inpaint without a mask image', () => {+ expect(() => compile(sd1Model, 'inpaint', { maskImageName: null })).toThrow(+ 'Canvas inpainting requires an inpaint mask.'+ );+ });++ it('produces a durable blend output for a Gallery destination', () => {+ expect(+ compile(sd1Model, 'inpaint', { destination: 'gallery' }).backendGraph.nodes.canvas_output?.is_intermediate+ ).toBe(false);+ });+});++describe('compileCanvasGraph — outpaint per base', () => {+ it.each(BASE_CASES)('grafts a $model.base outpaint pipeline (infill + alpha mask)', ({ model, txt2imgMode }) => {+ const { backendGraph, mode } = compile(model, 'outpaint', { maskImageName: null });+ expect(mode).toBe('outpaint');++ // Infill applied to the initial image (default method: lama).+ const infill = backendGraph.nodes.infill;+ expect(infill?.type).toBe('infill_lama');+ expect(infill?.image).toEqual({ image_name: 'canvas-composite.png' });++ // Mask derived from the raster alpha (tomask) → gradient mask (no inpaint mask present).+ expect(backendGraph.nodes.image_alpha_to_mask?.type).toBe('tomask');+ expect(getEdge(backendGraph, 'create_gradient_mask', 'mask')?.source.node_id).toBe('image_alpha_to_mask');++ // infill → i2l.image+ expect(getEdge(backendGraph, 'canvas_i2l', 'image')?.source.node_id).toBe('infill');++ // Composite-back blend claims canvas_output.+ expect(backendGraph.nodes.canvas_output?.type).toBe('invokeai_img_blend');+ expect(getNodeByType(backendGraph, 'core_metadata')?.generation_mode).toBe(+ txt2imgMode.replace('txt2img', 'outpaint')+ );+ });++ it('combines the inpaint mask with the raster alpha when a mask image is present', () => {+ const { backendGraph } = compile(sd1Model, 'outpaint', { maskImageName: 'canvas-mask.png' });+ const combine = backendGraph.nodes.mask_combine;+ expect(combine?.type).toBe('mask_combine');+ expect(combine?.mask1).toEqual({ image_name: 'canvas-mask.png' });+ expect(getEdge(backendGraph, 'mask_combine', 'mask2')?.source.node_id).toBe('image_alpha_to_mask');+ expect(getEdge(backendGraph, 'create_gradient_mask', 'mask')?.source.node_id).toBe('mask_combine');+ });++ it.each([+ ['patchmatch', 'infill_patchmatch'],+ ['lama', 'infill_lama'],+ ['cv2', 'infill_cv2'],+ ['tile', 'infill_tile'],+ ['color', 'infill_rgba'],+ ] as const)('uses the %s infill node', (method, nodeType) => {+ const { backendGraph } = compile(sd1Model, 'outpaint', {+ maskImageName: null,+ compositing: { infillMethod: method },+ });+ expect(backendGraph.nodes.infill?.type).toBe(nodeType);+ });++ it('threads infill sub-params (tile size, patchmatch downscale, color)', () => {+ const tile = compile(sd1Model, 'outpaint', {+ maskImageName: null,+ compositing: { infillMethod: 'tile', infillTileSize: 64 },+ }).backendGraph;+ expect(tile.nodes.infill?.tile_size).toBe(64);++ const patch = compile(sd1Model, 'outpaint', {+ maskImageName: null,+ compositing: { infillMethod: 'patchmatch', infillPatchmatchDownscaleSize: 3 },+ }).backendGraph;+ expect(patch.nodes.infill?.downscale).toBe(3);++ const color = compile(sd1Model, 'outpaint', {+ maskImageName: null,+ compositing: { infillMethod: 'color', infillColorValue: { r: 10, g: 20, b: 30, a: 1 } },+ }).backendGraph;+ expect(color.nodes.infill?.color).toEqual({ r: 10, g: 20, b: 30, a: 255 });+ });++ it('threads coherence + mask-blur settings into the outpaint gradient/expand nodes', () => {+ const { backendGraph } = compile(sd1Model, 'outpaint', {+ maskImageName: null,+ compositing: { coherenceMode: 'Staged', coherenceEdgeSize: 8, coherenceMinDenoise: 0.3, maskBlur: 24 },+ });+ expect(backendGraph.nodes.create_gradient_mask?.coherence_mode).toBe('Staged');+ expect(backendGraph.nodes.create_gradient_mask?.edge_radius).toBe(8);+ expect(backendGraph.nodes.create_gradient_mask?.minimum_denoise).toBe(0.3);+ expect(backendGraph.nodes.expand_mask?.fade_size_px).toBe(24);+ });++ it('rejects an external model for every image mode', () => {+ expect(() => compile(externalModel, 'outpaint', { maskImageName: null })).toThrow(+ 'does not support canvas generation'+ );+ });+});++// Review fix (Task 38, finding 2): `addControlLayers` has its own isolated unit+// coverage (addControlLayers.test.ts), but nothing previously drove control+// layers through the REAL `compileCanvasGraph` entry point — so a wiring+// regression at the seam between the two (e.g. the wrong denoise node id, or a+// base graph that no longer exposes `denoise_latents`) could pass every+// existing test here while breaking a real canvas invoke.+describe('compileCanvasGraph — control layers (integration)', () => {+ const controlNetLayer: ControlLayerGraphInput = {+ beginEndStepPct: [0.1, 0.85],+ controlMode: 'more_control',+ id: 'control-layer-1',+ imageName: 'control-composite.png',+ kind: 'controlnet',+ model: { base: 'sd-1', key: 'canny-controlnet', name: 'Canny ControlNet', type: 'controlnet' },+ weight: 0.65,+ };++ it('grafts an enabled control layer through a real compiled canvas graph: control node args, collector → denoise.control wiring, base graph intact', () => {+ const { backendGraph, graph, mode } = compile(sd1Model, 'img2img', { controlLayers: [controlNetLayer] });++ expect(mode).toBe('img2img');++ // The control node carries the resolved model/weight/begin-end/mode args.+ const controlNode = backendGraph.nodes['control_net_control-layer-1'];+ expect(controlNode?.type).toBe('controlnet');+ expect(controlNode?.control_model).toEqual(controlNetLayer.model);+ expect(controlNode?.control_weight).toBe(0.65);+ expect(controlNode?.begin_step_percent).toBe(0.1);+ expect(controlNode?.end_step_percent).toBe(0.85);+ expect(controlNode?.control_mode).toBe('more_control');+ expect(controlNode?.image).toEqual({ image_name: 'control-composite.png' });++ // The control node feeds the collector, whose own output is what+ // `denoise_latents.control` actually reads.+ expect(backendGraph.nodes.control_net_collector?.type).toBe('collect');+ expect(getEdge(backendGraph, 'control_net_collector', 'item')?.source.node_id).toBe('control_net_control-layer-1');+ expect(getEdge(backendGraph, 'denoise_latents', 'control')?.source.node_id).toBe('control_net_collector');++ // The base img2img graph is untouched by the control graft: prompts, seed,+ // the encode → denoise plumbing, and the composite-back output are all+ // still present and wired exactly as they would be with no control layers.+ expect(backendGraph.nodes.positive_prompt).toBeDefined();+ expect(backendGraph.nodes.negative_prompt).toBeDefined();+ expect(backendGraph.nodes.seed).toBeDefined();+ expect(backendGraph.nodes.canvas_i2l?.type).toBe('i2l');+ expect(getEdge(backendGraph, 'denoise_latents', 'latents')?.source.node_id).toBe('canvas_i2l');+ expect(backendGraph.nodes.canvas_output).toBeDefined();+ expect(graph.label).toBe(`${sd1Model.name} img2img`);+ });++ it('grafts a Z-Image control into the real Z-Image base graph', () => {+ const layer: ControlLayerGraphInput = {+ beginEndStepPct: [0, 1],+ controlMode: null,+ id: 'z-control',+ imageName: 'z-control.png',+ kind: 'z_image_control',+ model: { base: 'z-image', key: 'z-control-model', name: 'Z Control', type: 'controlnet' },+ weight: 0.75,+ };++ const { backendGraph } = compile(zImageModel, 'txt2img', { controlLayers: [layer] });++ expect(backendGraph.nodes.denoise_latents?.type).toBe('z_image_denoise');+ expect(backendGraph.nodes['z_image_control_z-control']).toMatchObject({+ control_context_scale: 0.75,+ control_model: layer.model,+ image: { image_name: 'z-control.png' },+ type: 'z_image_control',+ });+ expect(getEdge(backendGraph, 'denoise_latents', 'control')?.source).toEqual({+ field: 'control',+ node_id: 'z_image_control_z-control',+ });+ });+});++describe('compileCanvasGraph — regional guidance', () => {+ const region = (id: string, overrides: Partial<RegionalGuidanceInput> = {}) => ({+ autoNegative: false,+ id,+ maskImageName: `${id}-mask.png`,+ negativePrompt: null,+ positivePrompt: 'a cat',+ referenceImages: [],+ ...overrides,+ });++ it('grafts SD1 regional conditioning into the pos/neg collectors', () => {+ const { backendGraph } = compile(sd1Model, 'txt2img', {+ regionalGuidance: [region('r1', { autoNegative: true })],+ });+ expect(backendGraph.nodes.rg_mask_to_tensor_r1).toBeDefined();+ expect(backendGraph.nodes.rg_pos_cond_r1?.prompt).toBe('a cat');+ // autoNegative inverted-mask node feeding the negative collector.+ expect(backendGraph.nodes.rg_invert_mask_r1).toBeDefined();+ expect(backendGraph.nodes.rg_pos_cond_inverted_r1).toBeDefined();+ });++ it('is a no-op for an unsupported base (sd-2)', () => {+ const { backendGraph } = compile(sd2Model, 'txt2img', { regionalGuidance: [region('r1')] });+ expect(backendGraph.nodes.rg_mask_to_tensor_r1).toBeUndefined();+ });++ it('coexists with control layers in one graph', () => {+ const control: ControlLayerGraphInput = {+ beginEndStepPct: [0, 0.75],+ controlMode: 'balanced',+ id: 'c1',+ imageName: 'control.png',+ kind: 'controlnet',+ model: { base: 'sd-1', key: 'cn', name: 'CN', type: 'controlnet' },+ weight: 1,+ };+ const { backendGraph } = compile(sd1Model, 'txt2img', {+ controlLayers: [control],+ regionalGuidance: [region('r1')],+ });+ expect(backendGraph.nodes.control_net_c1).toBeDefined();+ expect(backendGraph.nodes.rg_pos_cond_r1).toBeDefined();+ });++ it('grafts positive-only regional conditioning into a FLUX.2 graph', () => {+ const { backendGraph } = compile(flux2Model, 'txt2img', { regionalGuidance: [region('r1')] });++ expect(backendGraph.nodes.rg_pos_cond_r1).toMatchObject({ prompt: 'a cat', type: 'flux2_klein_text_encoder' });+ expect(getEdge(backendGraph, 'rg_pos_cond_r1', 'qwen3_encoder')?.source.node_id).toBe('model_loader');+ expect(getEdge(backendGraph, 'pos_cond_collect', 'item')?.source.node_id).toBe('pos_cond');+ });+++ it('grafts FLUX.2 [dev] regions through Mistral conditioning', () => {++ const { backendGraph } = compile(flux2DevModel, 'txt2img', { regionalGuidance: [region('r1')] });++++ expect(backendGraph.nodes.rg_pos_cond_r1).toMatchObject({ prompt: 'a cat', type: 'flux2_dev_text_encoder' });++ expect(getEdge(backendGraph, 'rg_pos_cond_r1', 'mistral_encoder')?.source.node_id).toBe('model_loader');++ expect(getEdge(backendGraph, 'rg_pos_cond_r1', 'max_seq_len')?.source.node_id).toBe('model_loader');++ });+++ it('grafts Krea-2 regions through uniquely named conditioning enhancers into the shared collector', () => {+ const { backendGraph } = compile(krea2Model, 'txt2img', {+ regionalGuidance: [region('r1'), region('r2', { positivePrompt: 'a dog' })],+ settings: {+ krea2RebalanceEnabled: true,+ krea2SeedVarianceEnabled: true,+ krea2SeedVarianceStrength: 0.2,+ },+ });++ expect(backendGraph.nodes.rg_pos_cond_r1).toMatchObject({ prompt: 'a cat', type: 'krea2_text_encoder' });+ expect(backendGraph.nodes.rg_pos_cond_r2).toMatchObject({ prompt: 'a dog', type: 'krea2_text_encoder' });+ expect(getEdge(backendGraph, 'rg_pos_cond_r1', 'qwen3_vl_encoder')?.source.node_id).toBe('model_loader');+ expect(backendGraph.nodes.rg_krea2_r1_rebalance?.type).toBe('krea2_conditioning_rebalance');+ expect(backendGraph.nodes.rg_krea2_r2_rebalance?.type).toBe('krea2_conditioning_rebalance');+ expect(backendGraph.nodes.rg_krea2_r1_seed_variance?.type).toBe('krea2_seed_variance');+ expect(backendGraph.nodes.rg_krea2_r2_seed_variance?.type).toBe('krea2_seed_variance');+ expect(getEdge(backendGraph, 'rg_krea2_r1_seed_variance', 'variance_seed')?.source.node_id).toBe('seed');+ expect(getEdge(backendGraph, 'denoise_latents', 'positive_conditioning')?.source.node_id).toBe('pos_cond_collect');++ const collectedSources = backendGraph.edges+ .filter((edge) => edge.destination.node_id === 'pos_cond_collect' && edge.destination.field === 'item')+ .map((edge) => edge.source.node_id);+ expect(collectedSources).toEqual(['krea2_seed_variance', 'rg_krea2_r1_seed_variance', 'rg_krea2_r2_seed_variance']);+ });+});diff --cc invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.tsindex a676cda5ac,0000000000..5744bedc18mode 100644,000000..100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts@@@ -1,584 -1,0 +1,585 @@@+/**+ * Pure canvas generation-graph compiler.+ *+ * {@link compileCanvasGraph} builds the backend graph a canvas invoke submits by+ * grafting image-to-image plumbing onto the existing per-base txt2img builders+ * (`../graph.ts`). It is deliberately pure: no fetch, no engine imports, no+ * React. The executor (Task 16) has already composited + uploaded the bbox+ * source image and passes its name in; this module only shapes nodes/edges.+ *+ * ## Grafting strategy+ *+ * 1. Build the base txt2img graph via `GRAPH_BUILDERS[model.base]` with the+ * canvas destination (`outputIsIntermediate = true`) and a settings copy whose+ * width/height are the bbox size (builders read dims from settings).+ * 2. For `img2img`, add a base-appropriate image-to-latents encode node fed by+ * the composite image + the graph's VAE source, wire its latents into+ * `denoise_latents.latents`, and set `denoising_start = 1 - strength`.+ * 3. Update `core_metadata` (`generation_mode` → the `img2img` variant, plus+ * `strength`).+ *+ * Every base in `GRAPH_BUILDERS` has a backend image-to-latents node, so all ten+ * families support img2img (see `CANVAS_I2L_NODE_TYPES`). External image+ * generators have no latent img2img path and are rejected for every canvas mode.+ */++import type { SupportedGenerateBase } from '@features/generation/core/baseGenerationPolicies';+import type { BackendGraphContract, BackendInvocationContract } from '@features/generation/core/contracts';+import type { GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';++import { getGenerationValidationReasons } from '@features/generation/core/baseGenerationPolicies';+import { GRAPH_BUILDERS } from '@features/generation/core/graph';+import { addEdge, addNode, toGraphContract } from '@features/generation/core/graphBuilder';+import { addKrea2ConditioningEnhancers } from '@features/generation/core/krea2Conditioning';+import { getIsPidSupportedBase } from '@features/generation/core/pid';++import type {+ CanvasCompositingSettings,+ CanvasInfillMethod,+ CompileCanvasGraphInput,+ CompiledCanvasGraph,+} from './types';++import { addControlLayers } from './addControlLayers';+import { addRegionalGuidance, isRegionalGuidanceSupportedForBase } from './addRegionalGuidance';+import { DEFAULT_CANVAS_COMPOSITING } from './types';++/**+ * The backend image-to-latents (encode) node type per supported base. sd-1 /+ * sd-2 / sdxl share the SD `i2l` node. Evidence: `invokeai/app/invocations/`+ * and the legacy per-base builders under+ * `features/nodes/util/graph/generation/`.+ */+const CANVAS_I2L_NODE_TYPES: Partial<Record<SupportedGenerateBase, string>> = {+ 'sd-1': 'i2l',+ 'sd-2': 'i2l',+ sdxl: 'i2l',+ 'sd-3': 'sd3_i2l',+ flux: 'flux_vae_encode',+ flux2: 'flux2_vae_encode',+ cogview4: 'cogview4_i2l',+ 'qwen-image': 'qwen_image_i2l',+ 'z-image': 'z_image_i2l',+ // Krea-2 shares the Qwen-Image VAE, so it encodes with that family's node too.+ 'krea-2': 'qwen_image_i2l',+ anima: 'anima_i2l',+ wan: 'wan_i2l',+ // Ideogram 4 is deliberately absent: it ships no image-to-latents node, so canvas+ // img2img/inpaint is impossible. requireI2lType turns the missing entry into an+ // actionable "Canvas generation is not supported" error.+};++/**+ * The `denoising_start` for a canvas img2img graft, mirroring legacy+ * `getDenoisingStartAndEnd` (web `graphBuilderUtils.ts`):+ * - sd-3 / flux / flux2 rescale strength with an exponent of 0.2 so the slider's+ * full (0, 1] range is usable — without it nearly all perceptible change is+ * crammed into strength > 0.9 (e.g. strength 0.75 → start 0.056, not 0.25).+ * - A FLUX Fill model (`flux` / `dev_fill`) always denoises fully (start = 0).+ * - Every other base stays linear (`start = 1 - strength`).+ *+ * Legacy gates the exponent on an `optimizedDenoisingEnabled` user setting that+ * defaults to `true`; webv2 exposes no such toggle, so the optimized curve is+ * always applied for the eligible bases.+ */+const canvasDenoisingStart = (model: GenerateModelConfig, strength: number): number => {+ if (model.base === 'flux' && model.variant === 'dev_fill') {+ return 0;+ }+ const usesOptimizedCurve = model.base === 'sd-3' || model.base === 'flux' || model.base === 'flux2';+ return 1 - strength ** (usesOptimizedCurve ? 0.2 : 1);+};++/** True for the image-referencing modes (everything but pure txt2img). */+const isImageMode = (mode: CompileCanvasGraphInput['mode']): boolean => mode !== 'txt2img';++/** Canvas-specific validation reasons layered on top of the shared generate ones. */+const getCanvasValidationReasons = (input: CompileCanvasGraphInput): string[] => {+ const { bbox, compositeImageName, maskImageName, mode, model, strength } = input;+ const reasons: string[] = [];++ if (model.type === 'external_image_generator') {+ reasons.push(`${model.name} does not support canvas generation.`);+ return reasons;+ }++ // PiD is wired for text-to-image only. Canvas compilation finds the VAE by looking for+ // a `canvas_output.vae` edge and renames that node when compositing back; a PiD chain+ // has neither, so without this guard the user would get an internal+ // "could not resolve a VAE source" error instead of an actionable one.+ if (input.settings.pidMode !== 'off' && getIsPidSupportedBase(model.base)) {+ reasons.push('PiD decoding is not supported on the canvas yet. Turn PiD off to generate here.');+ }++ if (!Number.isFinite(bbox.width) || !Number.isFinite(bbox.height) || bbox.width <= 0 || bbox.height <= 0) {+ reasons.push('Canvas bounding box must have a positive area.');+ }++ if (isImageMode(mode)) {+ if (!compositeImageName) {+ reasons.push('Canvas generation requires a composited source image.');+ }++ if (!Number.isFinite(strength) || strength <= 0 || strength > 1) {+ reasons.push('Canvas denoising strength must be greater than 0 and at most 1.');+ }+ }++ // Inpaint always needs a mask (an active inpaint mask defines the region);+ // outpaint derives its mask from the raster alpha, so its mask is optional.+ if (mode === 'inpaint' && !maskImageName) {+ reasons.push('Canvas inpainting requires an inpaint mask.');+ }++ return reasons;+};++/** The settings a base builder sees: identical to the widget's, but sized to the bbox. */+const withBboxDimensions = (settings: GenerateSettings, bbox: CompileCanvasGraphInput['bbox']): GenerateSettings => ({+ ...settings,+ height: bbox.height,+ width: bbox.width,+});++/** Locates the node + field feeding a decode/denoise input edge (e.g. `canvas_output.vae`). */+const findEdgeSource = (+ graph: BackendGraphContract,+ destNodeId: string,+ destField: string+): { node: BackendInvocationContract; field: string } | null => {+ const edge = graph.edges.find(+ (candidate) => candidate.destination.node_id === destNodeId && candidate.destination.field === destField+ );+ const node = edge ? graph.nodes[edge.source.node_id] : undefined;+ return edge && node ? { field: edge.source.field, node } : null;+};++/** Resolves the VAE source feeding the graph's decode node (throws if absent). */+const requireVaeSource = (graph: BackendGraphContract): { node: BackendInvocationContract; field: string } => {+ const source = findEdgeSource(graph, 'canvas_output', 'vae');+ if (!source) {+ throw new Error('Canvas generation could not resolve a VAE source in the base graph.');+ }+ return source;+};++/**+ * Renames a node in place: moves its map key, updates its `id`, and rewires every+ * edge referencing the old id. Used to demote the base `canvas_output` decode to+ * an intermediate `canvas_l2i` so the composite-back node can claim `canvas_output`.+ */+const renameNode = (graph: BackendGraphContract, oldId: string, newId: string): BackendInvocationContract => {+ const node = graph.nodes[oldId];+ if (!node) {+ throw new Error(`Canvas generation could not find the "${oldId}" node to rename.`);+ }+ delete graph.nodes[oldId];+ node.id = newId;+ graph.nodes[newId] = node;+ for (const edge of graph.edges) {+ if (edge.source.node_id === oldId) {+ edge.source.node_id = newId;+ }+ if (edge.destination.node_id === oldId) {+ edge.destination.node_id = newId;+ }+ }+ return node;+};++/** Sets the metadata `generation_mode` variant + strength (legacy parity). */+const setMetadataMode = (graph: BackendGraphContract, mode: string, strength: number): void => {+ const metadata = Object.values(graph.nodes).find((node) => node.type === 'core_metadata');+ if (metadata) {+ if (typeof metadata.generation_mode === 'string') {+ metadata.generation_mode = metadata.generation_mode.replace('txt2img', mode);+ }+ metadata.strength = strength;+ }+};++/** The SD `i2l` node carries fp32; every other family's encode node does not. */+const isSdI2l = (i2lType: string): boolean => i2lType === 'i2l';++/** Adds the base-appropriate image-to-latents encode node fed by `imageName`. */+const addEncodeNode = (+ graph: BackendGraphContract,+ i2lType: string,+ settings: GenerateSettings,+ imageName: string | null+): BackendInvocationContract =>+ addNode(graph, {+ id: 'canvas_i2l',+ ...(imageName ? { image: { image_name: imageName } } : {}),+ type: i2lType,+ ...(isSdI2l(i2lType) ? { fp32: settings.vaePrecision === 'fp32' } : {}),+ });++/** Resolves the encode node type for a supported base (throws otherwise). */+const requireI2lType = (model: GenerateModelConfig): string => {+ if (model.type === 'external_image_generator') {+ throw new Error(`${model.name} does not support canvas generation.`);+ }+ const i2lType = CANVAS_I2L_NODE_TYPES[model.base as SupportedGenerateBase];+ if (!i2lType) {+ throw new Error(`Canvas generation is not supported for ${model.name}.`);+ }+ return i2lType;+};++/** Resolves the base graph's denoise node (throws if absent). */+const requireDenoise = (graph: BackendGraphContract): BackendInvocationContract => {+ const denoise = graph.nodes.denoise_latents;+ if (!denoise) {+ throw new Error('Canvas generation could not find the denoise node in the base graph.');+ }+ return denoise;+};++/** Grafts the image-to-latents encode path onto a freshly built base graph (img2img). */+const graftImageToImage = (+ graph: BackendGraphContract,+ model: GenerateModelConfig,+ settings: GenerateSettings,+ compositeImageName: string,+ strength: number+): void => {+ const i2lType = requireI2lType(model);+ const denoise = requireDenoise(graph);+ const vaeSource = requireVaeSource(graph);+ const encode = addEncodeNode(graph, i2lType, settings, compositeImageName);++ addEdge(graph, vaeSource.node, vaeSource.field, encode, 'vae');+ addEdge(graph, encode, 'latents', denoise, 'latents');+ denoise.denoising_start = canvasDenoisingStart(model, strength);+ denoise.denoising_end = 1;++ setMetadataMode(graph, 'img2img', strength);+};++/** The backend infill node for the selected method (legacy `getInfill`). */+const addInfillNode = (+ graph: BackendGraphContract,+ method: CanvasInfillMethod,+ compositing: CanvasCompositingSettings+): BackendInvocationContract => {+ switch (method) {+ case 'patchmatch':+ return addNode(graph, {+ downscale: compositing.infillPatchmatchDownscaleSize,+ id: 'infill',+ type: 'infill_patchmatch',+ });+ case 'lama':+ return addNode(graph, { id: 'infill', type: 'infill_lama' });+ case 'cv2':+ return addNode(graph, { id: 'infill', type: 'infill_cv2' });+ case 'tile':+ return addNode(graph, { id: 'infill', tile_size: compositing.infillTileSize, type: 'infill_tile' });+ case 'color': {+ const { a, b, g, r } = compositing.infillColorValue;+ return addNode(graph, {+ color: { a: Math.round(a * 255), b, g, r },+ id: 'infill',+ type: 'infill_rgba',+ });+ }+ }+};++/**+ * Shared inpaint/outpaint tail: gradient denoise mask → denoise, expand-with-fade,+ * and the composite-back blend (`canvas_output`). `maskSource` supplies the+ * grayscale mask feeding `create_gradient_mask`; `initialImageName` is the base+ * to paste the decoded result back onto.+ */+const graftMaskTail = (+ graph: BackendGraphContract,+ args: {+ model: GenerateModelConfig;+ settings: GenerateSettings;+ i2lType: string;+ denoise: BackendInvocationContract;+ vaeSource: { node: BackendInvocationContract; field: string };+ initialImageName: string;+ compositing: CanvasCompositingSettings;+ destination: CompileCanvasGraphInput['destination'];+ /** Either a fixed mask image field or an edge-fed source node. */+ gradientMaskImage?: { image_name: string };+ gradientMaskEdge?: { node: BackendInvocationContract; field: string };+ }+): void => {+ const { compositing, denoise, destination, i2lType, initialImageName, settings, vaeSource } = args;++ // Demote the base decode to an intermediate `canvas_l2i`; the blend becomes `canvas_output`.+ const l2i = renameNode(graph, 'canvas_output', 'canvas_l2i');+ l2i.is_intermediate = true;++ const gradientMask = addNode(graph, {+ coherence_mode: compositing.coherenceMode,+ edge_radius: compositing.coherenceEdgeSize,+ fp32: isSdI2l(i2lType) ? settings.vaePrecision === 'fp32' : false,+ id: 'create_gradient_mask',+ image: { image_name: initialImageName },+ minimum_denoise: compositing.coherenceMinDenoise,+ type: 'create_gradient_mask',+ ...(args.gradientMaskImage ? { mask: args.gradientMaskImage } : {}),+ });++ if (args.gradientMaskEdge) {+ addEdge(graph, args.gradientMaskEdge.node, args.gradientMaskEdge.field, gradientMask, 'mask');+ }+ addEdge(graph, vaeSource.node, vaeSource.field, gradientMask, 'vae');+ // The optional UNet edge only applies to SD-family models (legacy `isMainModelWithoutUnet`).+ const unetSource = findEdgeSource(graph, 'denoise_latents', 'unet');+ if (unetSource) {+ addEdge(graph, unetSource.node, unetSource.field, gradientMask, 'unet');+ }+ addEdge(graph, gradientMask, 'denoise_mask', denoise, 'denoise_mask');++ const expandMask = addNode(graph, {+ fade_size_px: compositing.maskBlur,+ id: 'expand_mask',+ type: 'expand_mask_with_fade',+ });+ addEdge(graph, gradientMask, 'expanded_mask_area', expandMask, 'mask');++ const blend = addNode(graph, {+ id: 'canvas_output',+ is_intermediate: destination === 'canvas',+ layer_base: { image_name: initialImageName },+ type: 'invokeai_img_blend',+ use_cache: false,+ });+ addEdge(graph, l2i, 'image', blend, 'layer_upper');+ addEdge(graph, expandMask, 'image', blend, 'mask');++ // The base builder wired core_metadata → the decode's `metadata`; `renameNode`+ // followed it onto the (now intermediate) canvas_l2i. Re-point it to the final+ // blend so the saved image carries generation metadata (invokeai_img_blend is+ // WithMetadata). Board fields, when present, ride the same node.+ const metadataEdge = graph.edges.find(+ (edge) => edge.destination.node_id === 'canvas_l2i' && edge.destination.field === 'metadata'+ );+ if (metadataEdge) {+ metadataEdge.destination.node_id = 'canvas_output';+ }+};++/** Optionally inserts an `img_noise` node before encode; returns the node feeding `i2l.image`. */+const addNoiseBeforeEncode = (+ graph: BackendGraphContract,+ imageName: string,+ noiseMaskImageName: string | null | undefined,+ imageSourceNode: BackendInvocationContract | null+): { imageField?: { image_name: string }; edgeFrom?: BackendInvocationContract } => {+ if (!noiseMaskImageName) {+ // No noise mask: encode reads the (infilled) initial image directly.+ return imageSourceNode ? { edgeFrom: imageSourceNode } : { imageField: { image_name: imageName } };+ }+ const noise = addNode(graph, {+ amount: 1.0,+ id: 'add_inpaint_noise',+ ...(imageSourceNode ? {} : { image: { image_name: imageName } }),+ mask: { image_name: noiseMaskImageName },+ noise_color: true,+ noise_type: 'gaussian',+ type: 'img_noise',+ });+ addEdge(graph, graph.nodes.seed, 'value', noise, 'seed');+ if (imageSourceNode) {+ addEdge(graph, imageSourceNode, 'image', noise, 'image');+ }+ return { edgeFrom: noise };+};++/** Grafts the inpaint pipeline (content covers the bbox, an inpaint mask restricts it). */+const graftInpaint = (+ graph: BackendGraphContract,+ input: CompileCanvasGraphInput,+ compositing: CanvasCompositingSettings+): void => {+ const { model } = input;+ const i2lType = requireI2lType(model);+ const denoise = requireDenoise(graph);+ const vaeSource = requireVaeSource(graph);+ const initialImageName = input.compositeImageName as string;+ const maskImageName = input.maskImageName as string;+ const strength = input.strength;++ denoise.denoising_start = canvasDenoisingStart(model, strength);+ denoise.denoising_end = 1;++ const encode = addEncodeNode(graph, i2lType, input.settings, null);+ const noiseResult = addNoiseBeforeEncode(graph, initialImageName, input.noiseMaskImageName, null);+ if (noiseResult.edgeFrom) {+ addEdge(graph, noiseResult.edgeFrom, 'image', encode, 'image');+ } else if (noiseResult.imageField) {+ encode.image = noiseResult.imageField;+ }+ addEdge(graph, vaeSource.node, vaeSource.field, encode, 'vae');+ addEdge(graph, encode, 'latents', denoise, 'latents');++ graftMaskTail(graph, {+ compositing,+ denoise,+ destination: input.destination,+ gradientMaskImage: { image_name: maskImageName },+ i2lType,+ initialImageName,+ model,+ settings: input.settings,+ vaeSource,+ });++ setMetadataMode(graph, 'inpaint', strength);+};++/** Grafts the outpaint pipeline (bbox extends past content / has transparent holes). */+const graftOutpaint = (+ graph: BackendGraphContract,+ input: CompileCanvasGraphInput,+ compositing: CanvasCompositingSettings+): void => {+ const { model } = input;+ const i2lType = requireI2lType(model);+ const denoise = requireDenoise(graph);+ const vaeSource = requireVaeSource(graph);+ const initialImageName = input.compositeImageName as string;+ const strength = input.strength;++ denoise.denoising_start = canvasDenoisingStart(model, strength);+ denoise.denoising_end = 1;++ // Infill the transparent region before encode (legacy `getInfill`).+ const infill = addInfillNode(graph, compositing.infillMethod, compositing);+ infill.image = { image_name: initialImageName };++ // Derive a mask from the initial image alpha (transparent → generate), combined+ // with the inpaint mask when one exists.+ const alphaToMask = addNode(graph, {+ id: 'image_alpha_to_mask',+ image: { image_name: initialImageName },+ type: 'tomask',+ });++ let gradientMaskEdge: { node: BackendInvocationContract; field: string };+ if (input.maskImageName) {+ const maskCombine = addNode(graph, {+ id: 'mask_combine',+ mask1: { image_name: input.maskImageName },+ type: 'mask_combine',+ });+ addEdge(graph, alphaToMask, 'image', maskCombine, 'mask2');+ gradientMaskEdge = { field: 'image', node: maskCombine };+ } else {+ gradientMaskEdge = { field: 'image', node: alphaToMask };+ }++ const encode = addEncodeNode(graph, i2lType, input.settings, null);+ const noiseResult = addNoiseBeforeEncode(graph, initialImageName, input.noiseMaskImageName, infill);+ if (noiseResult.edgeFrom) {+ addEdge(graph, noiseResult.edgeFrom, 'image', encode, 'image');+ }+ addEdge(graph, vaeSource.node, vaeSource.field, encode, 'vae');+ addEdge(graph, encode, 'latents', denoise, 'latents');++ graftMaskTail(graph, {+ compositing,+ denoise,+ destination: input.destination,+ gradientMaskEdge,+ i2lType,+ initialImageName,+ model,+ settings: input.settings,+ vaeSource,+ });++ setMetadataMode(graph, 'outpaint', strength);+};++/**+ * Compiles a canvas invoke into a backend graph. Throws a validation `Error`+ * (message = first offending reason) for unsupported models/modes or bad+ * geometry, mirroring `compileGenerateGraph`.+ */+export const compileCanvasGraph = (input: CompileCanvasGraphInput): CompiledCanvasGraph => {+ const { bbox, compositeImageName, destination, mode, model, projectSettings, strength } = input;+ const settings = withBboxDimensions(input.settings, bbox);++ const validationReasons = [...getCanvasValidationReasons(input), ...getGenerationValidationReasons(model, settings)];++ if (validationReasons.length > 0) {+ throw new Error(validationReasons[0]);+ }++ const builder = GRAPH_BUILDERS[model.base as SupportedGenerateBase];++ if (!builder || model.type === 'external_image_generator') {+ throw new Error(`${model.name} does not support canvas generation.`);+ }++ // Mirror compileGenerateGraph: only a `canvas` destination stages an+ // intermediate output; `gallery` produces a durable image.+ const outputIsIntermediate = destination === 'canvas';+ const backendGraph = builder(settings, model, outputIsIntermediate, projectSettings);+ const compositing = input.compositing ?? DEFAULT_CANVAS_COMPOSITING;++ // Validation above guarantees the composite/mask images required per mode.+ if (mode === 'img2img') {+ graftImageToImage(backendGraph, model, settings, compositeImageName as string, strength);+ } else if (mode === 'inpaint') {+ graftInpaint(backendGraph, input, compositing);+ } else if (mode === 'outpaint') {+ graftOutpaint(backendGraph, input, compositing);+ }++ // Control layers apply in every mode (legacy allows control with all). The+ // executor already composited + uploaded each layer separately and resolved+ // its model; the caller passes only valid layers.+ if (input.controlLayers && input.controlLayers.length > 0) {+ addControlLayers(backendGraph, {+ base: model.base as SupportedGenerateBase,+ layers: input.controlLayers,+ modelVariant: model.variant ?? undefined,+ });+ }++ // Regional guidance applies in every mode too. The executor already composited+ // + uploaded each region's mask and resolved its reference-image models; it+ // passes only valid regions for a supported base (SD1 / SDXL / FLUX / FLUX.2 / Krea-2).+ if (input.regionalGuidance && input.regionalGuidance.length > 0 && isRegionalGuidanceSupportedForBase(model.base)) {+ addRegionalGuidance(backendGraph, {+ base: model.base,++ modelVariant: model.variant,+ regions: input.regionalGuidance,+ ...(model.base === 'krea-2'+ ? {+ transformRegionalPositiveConditioning: (conditioning: BackendInvocationContract, regionId: string) => {+ const seed = backendGraph.nodes.seed;+ if (!seed) {+ throw new Error('Krea-2 regional guidance requires the base graph seed node.');+ }+ return addKrea2ConditioningEnhancers({+ conditioning,+ graph: backendGraph,+ idPrefix: `rg_krea2_${regionId}`,+ seed,+ settings,+ });+ },+ }+ : {}),+ });+ }++ return {+ backendGraph,+ graph: toGraphContract(backendGraph, `${model.name} ${mode}`),+ mode,+ negativePromptNodeId: 'negative_prompt',+ positivePromptNodeId: 'positive_prompt',+ seedNodeId: 'seed',+ };+};diff --cc invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.tsindex 3ffa2e0587,0000000000..8a00a7d44cmode 100644,000000..100644--- a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.test.ts@@@ -1,85 -1,0 +1,104 @@@+import { describe, expect, it } from 'vitest';++import type { ComponentModelConfig, GenerateModelConfig } from './types';++import {+ getCompatibleSelectedComponentKey,+ isAnimaQwen3Encoder,+ isAnimaVae,+ isFlux2DiffusersSourceForModel,++ isFlux2MistralEncoder,+ isFlux2Qwen3EncoderForModel,+ isNonAnimaQwen3Encoder,+ isVaeCompatibleWithGenerateModel,+ type GenerateComponentCandidate,+} from './componentCompatibility';++const flux2Model = (variant: string): GenerateModelConfig => ({+ base: 'flux2',+ key: `flux2-${variant}`,+ name: `FLUX.2 ${variant}`,+ type: 'main',+ variant,+});++const candidate = (overrides: Partial<GenerateComponentCandidate>): GenerateComponentCandidate => ({+ base: 'any',+ type: 'qwen3_encoder',+ ...overrides,+});++describe('Generate component compatibility', () => {+ it('separates Anima Qwen3 0.6B encoders from other Qwen3 encoders', () => {+ const qwen06b = candidate({ variant: 'qwen3_06b' });+ const qwen4b = candidate({ variant: 'qwen3_4b' });++ expect(isAnimaQwen3Encoder(qwen06b)).toBe(true);+ expect(isAnimaQwen3Encoder(qwen4b)).toBe(false);+ expect(isNonAnimaQwen3Encoder(qwen06b)).toBe(false);+ expect(isNonAnimaQwen3Encoder(qwen4b)).toBe(true);+ });++ it('matches FLUX.2 Klein models to compatible Qwen3 encoder variants', () => {+ const filter = isFlux2Qwen3EncoderForModel(flux2Model('klein_9b'));++ expect(filter(candidate({ variant: 'qwen3_8b' }))).toBe(true);+ expect(filter(candidate({ variant: 'qwen3_4b' }))).toBe(false);+ expect(filter(candidate({ variant: 'qwen3_06b' }))).toBe(false);+ });++ it('matches FLUX.2 component sources by shared Qwen3 encoder variant', () => {+ const filter = isFlux2DiffusersSourceForModel(flux2Model('klein_9b'));++ expect(filter(candidate({ base: 'flux2', format: 'diffusers', type: 'main', variant: 'klein_9b_base' }))).toBe(+ true+ );+ expect(filter(candidate({ base: 'flux2', format: 'diffusers', type: 'main', variant: 'klein_4b' }))).toBe(false);+ expect(filter(candidate({ base: 'flux2', format: 'checkpoint', type: 'main', variant: 'klein_9b' }))).toBe(false);+ expect(filter(candidate({ base: 'flux2', format: 'diffusers', type: 'main' }))).toBe(false);+ });+++ it('uses Mistral components and dev Diffusers sources for FLUX.2 [dev]', () => {++ const model = flux2Model('dev');++++ expect(isFlux2MistralEncoder(candidate({ type: 'mistral_encoder' }))).toBe(true);++ expect(isFlux2MistralEncoder(candidate({ type: 'qwen3_encoder' }))).toBe(false);++ expect(isFlux2Qwen3EncoderForModel(model)(candidate({ variant: 'qwen3_8b' }))).toBe(false);++ expect(++ isFlux2DiffusersSourceForModel(model)(++ candidate({ base: 'flux2', format: 'diffusers', type: 'main', variant: 'dev' })++ )++ ).toBe(true);++ expect(++ isFlux2DiffusersSourceForModel(model)(++ candidate({ base: 'flux2', format: 'diffusers', type: 'main', variant: 'klein_9b' })++ )++ ).toBe(false);++ });+++ it('allows only backend-supported Anima VAE families', () => {+ expect(isAnimaVae(candidate({ base: 'anima', type: 'vae' }))).toBe(true);+ expect(isAnimaVae(candidate({ base: 'qwen-image', type: 'vae' }))).toBe(true);+ expect(isAnimaVae(candidate({ base: 'flux', type: 'vae' }))).toBe(true);+ expect(isAnimaVae(candidate({ base: 'sdxl', type: 'vae' }))).toBe(false);+ });++ it('centralizes generate VAE compatibility for cross-base families', () => {+ const vae = (base: string) => ({ base, key: `${base}-vae`, name: `${base} VAE`, type: 'vae' as const });++ expect(isVaeCompatibleWithGenerateModel(flux2Model('klein_9b'), vae('flux2'))).toBe(true);+ expect(isVaeCompatibleWithGenerateModel(flux2Model('klein_9b'), vae('flux'))).toBe(false);+ expect(+ isVaeCompatibleWithGenerateModel({ base: 'z-image', key: 'z-image', name: 'Z-Image', type: 'main' }, vae('flux'))+ ).toBe(true);+ expect(+ isVaeCompatibleWithGenerateModel({ base: 'anima', key: 'anima', name: 'Anima', type: 'main' }, vae('qwen-image'))+ ).toBe(true);+ });++ it('hides a stale selected component when it no longer passes the picker filter', () => {+ const staleVae: ComponentModelConfig = { base: 'sdxl', key: 'sdxl-vae', name: 'SDXL VAE', type: 'vae' };++ expect(getCompatibleSelectedComponentKey(staleVae, isAnimaVae)).toBeNull();+ });+});diff --cc invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.tsindex 633ea9f978,0000000000..e6e8bbc8dbmode 100644,000000..100644--- a/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/componentCompatibility.ts@@@ -1,129 -1,0 +1,139 @@@+import type { ComponentModelConfig, GenerateModelConfig, VaeModelConfig } from './types';++export type GenerateComponentCandidate = {+ base: string;+ format?: string;+ key?: string;+ type: string;+ variant?: unknown;+};++export type GenerateComponentFilter = (model: GenerateComponentCandidate) => boolean;++export const KLEIN_TO_QWEN3_VARIANT: Record<string, string> = {+ klein_4b: 'qwen3_4b',+ klein_4b_base: 'qwen3_4b',+ klein_9b: 'qwen3_8b',+ klein_9b_base: 'qwen3_8b',+};++export const getCompatibleSelectedComponentKey = (+ value: ComponentModelConfig | null,+ filter?: GenerateComponentFilter+): string | null => (value && (!filter || filter(value)) ? value.key : null);++export const isDiffusersMainForBase =+ (base: string): GenerateComponentFilter =>+ (model) =>+ model.type === 'main' && model.base === base && model.format === 'diffusers';++export const isVaeForBases =+ (bases: readonly string[]): GenerateComponentFilter =>+ (model) =>+ model.type === 'vae' && (bases.length === 0 || bases.includes(model.base));++export const isClipVariant =+ (variant: string): GenerateComponentFilter =>+ (model) =>+ model.type === 'clip_embed' && model.variant === variant;++export const isAnimaQwen3Encoder: GenerateComponentFilter = (model) =>+ model.type === 'qwen3_encoder' && model.variant === 'qwen3_06b';++export const isNonAnimaQwen3Encoder: GenerateComponentFilter = (model) =>+ model.type === 'qwen3_encoder' && model.variant !== 'qwen3_06b';+++export const isFlux2MistralEncoder: GenerateComponentFilter = (model) => model.type === 'mistral_encoder';+++export const isFlux2Qwen3EncoderForModel = (selectedModel: GenerateModelConfig): GenerateComponentFilter => {++ if (selectedModel.variant === 'dev') {++ return () => false;++ }+++ const requiredVariant =+ typeof selectedModel.variant === 'string' ? KLEIN_TO_QWEN3_VARIANT[selectedModel.variant] : null;++ return (model) => {+ if (!isNonAnimaQwen3Encoder(model)) {+ return false;+ }++ return requiredVariant ? model.variant === requiredVariant : true;+ };+};++export const isFlux2DiffusersSourceForModel = (selectedModel: GenerateModelConfig): GenerateComponentFilter => {+ const selectedVariant = typeof selectedModel.variant === 'string' ? selectedModel.variant : null;+ const requiredVariant = selectedVariant ? KLEIN_TO_QWEN3_VARIANT[selectedVariant] : null;++ return (model) => {+ if (!isDiffusersMainForBase('flux2')(model)) {+ return false;+ }+++ const sourceVariant = typeof model.variant === 'string' ? model.variant : null;++++ if (selectedVariant === 'dev') {++ return sourceVariant === 'dev';++ }+++ if (!requiredVariant) {+ return true;+ }+- const sourceVariant = typeof model.variant === 'string' ? model.variant : null;-+ return sourceVariant ? KLEIN_TO_QWEN3_VARIANT[sourceVariant] === requiredVariant : false;+ };+};++export const isCompatibleDiffusersComponentSourceForModel = (+ selectedModel: GenerateModelConfig,+ source: GenerateComponentCandidate+): boolean => {+ if (selectedModel.type === 'external_image_generator') {+ return false;+ }++ if (selectedModel.base === 'flux2') {+ return isFlux2DiffusersSourceForModel(selectedModel)(source);+ }++ return isDiffusersMainForBase(selectedModel.base)(source);+};++export const getCompatibleDiffusersComponentSource = <T extends GenerateComponentCandidate>(+ selectedModel: GenerateModelConfig,+ source: T | null | undefined+): T | undefined =>+ source && isCompatibleDiffusersComponentSourceForModel(selectedModel, source) ? source : undefined;++export const isAnimaVae = isVaeForBases(['anima', 'qwen-image', 'flux']);++/**+ * Krea-2 decodes with the Qwen-Image VAE (16-channel), which is why its graph reuses+ * `qwen_image_l2i`. `anima` is accepted alongside `qwen-image` because the same physical VAE+ * is registered under either base depending on which family it was installed for — matching+ * `krea2_model_loader`'s own `ui_model_base=[QwenImage, Anima]`. Restricting this to+ * `qwen-image` hides a working VAE that the backend would have accepted.+ */+export const isKrea2Vae = isVaeForBases(['qwen-image', 'anima']);++export const isVaeCompatibleWithGenerateModel = (model: GenerateModelConfig, vae: VaeModelConfig): boolean => {+ if (model.type === 'external_image_generator') {+ return false;+ }++ switch (model.base) {+ case 'anima':+ return isAnimaVae(vae);+ case 'z-image':+ return isVaeForBases(['flux'])(vae);+ case 'qwen-image':+ return isVaeForBases(['qwen-image'])(vae);+ case 'krea-2':+ return isKrea2Vae(vae);+ case 'flux2':+ return isVaeForBases(['flux2'])(vae);+ default:+ return vae.type === 'vae' && vae.base === model.base;+ }+};diff --cc invokeai/frontend/webv2/src/features/generation/core/graph.test.tsindex 63c980cfab,0000000000..529d4deb61mode 100644,000000..100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts@@@ -1,994 -1,0 +1,1057 @@@+import { afterEach, describe, expect, it, vi } from 'vitest';++import type {+ ComponentModelConfig,+ GenerateModelConfig,+ GenerateSettings,+ LoraModelConfig,+ MainModelConfig,+ VaeModelConfig,+} from './types';++import { getDefaultGenerateSettings, isSupportedGenerateModel } from './baseGenerationPolicies';+import { compileGenerateGraph, generateSeedSequence, resolveGenerateSeed } from './graph';++const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };+const sd2Model: MainModelConfig = { base: 'sd-2', key: 'sd2-model', name: 'SD 2', type: 'main' };+const sdxlModel: MainModelConfig = { base: 'sdxl', key: 'sdxl-model', name: 'SDXL', type: 'main' };+const sd3Model: MainModelConfig = { base: 'sd-3', key: 'sd3-model', name: 'SD3', type: 'main' };+const fluxModel: MainModelConfig = { base: 'flux', key: 'flux-model', name: 'FLUX dev', type: 'main' };+const flux2Model: MainModelConfig = {+ base: 'flux2',+ format: 'diffusers',+ key: 'flux2-model',+ name: 'FLUX.2',+ type: 'main',+};+const flux2Klein9bModel: MainModelConfig = {+ base: 'flux2',+ format: 'gguf_quantized',+ key: 'flux2-klein-9b',+ name: 'FLUX.2 Klein 9B',+ type: 'main',+ variant: 'klein_9b',+};++const flux2DevModel: MainModelConfig = {++ base: 'flux2',++ format: 'diffusers',++ key: 'flux2-dev',++ name: 'FLUX.2 [dev]',++ type: 'main',++ variant: 'dev',++};++const flux2DevGgufModel: MainModelConfig = {++ ...flux2DevModel,++ format: 'gguf_quantized',++ key: 'flux2-dev-gguf',++};++const flux2DevSource: MainModelConfig = {++ ...flux2DevModel,++ key: 'flux2-dev-source',++};+const fluxKontextModel: MainModelConfig = {+ base: 'flux',+ format: 'diffusers',+ key: 'flux-kontext',+ name: 'FLUX Kontext dev',+ type: 'main',+};+const incompatibleFlux2Source: MainModelConfig = {+ base: 'flux2',+ format: 'diffusers',+ key: 'flux2-klein-4b-source',+ name: 'FLUX.2 Klein 4B Source',+ type: 'main',+ variant: 'klein_4b',+};+const cogView4Model: MainModelConfig = { base: 'cogview4', key: 'cog-model', name: 'CogView4', type: 'main' };+const qwenImageModel: MainModelConfig = {+ base: 'qwen-image',+ format: 'diffusers',+ key: 'qwen-model',+ name: 'Qwen Image',+ type: 'main',+};+const zImageModel: MainModelConfig = {+ base: 'z-image',+ format: 'diffusers',+ key: 'z-model',+ name: 'Z-Image',+ type: 'main',+};+const animaModel: MainModelConfig = { base: 'anima', key: 'anima-model', name: 'Anima', type: 'main' };+const externalModel: GenerateModelConfig = {+ base: 'external',+ capabilities: { modes: ['txt2img'], supports_seed: true },+ format: 'external_api',+ key: 'external-model',+ name: 'OpenAI Image',+ provider_id: 'openai',+ type: 'external_image_generator',+};+const sd1Lora: LoraModelConfig = { base: 'sd-1', key: 'sd1-lora', name: 'SD 1.5 LoRA', type: 'lora' };+const sd2Lora: LoraModelConfig = { base: 'sd-2', key: 'sd2-lora', name: 'SD 2 LoRA', type: 'lora' };+const sdxlLora: LoraModelConfig = { base: 'sdxl', key: 'sdxl-lora', name: 'SDXL LoRA', type: 'lora' };+const fluxLora: LoraModelConfig = { base: 'flux', key: 'flux-lora', name: 'FLUX LoRA', type: 'lora' };++const flux2DevLora: LoraModelConfig = {++ base: 'flux2',++ key: 'flux2-dev-lora',++ name: 'FLUX.2 [dev] LoRA',++ type: 'lora',++ variant: 'dev',++};+const sd1IpAdapter: ComponentModelConfig = {+ base: 'sd-1',+ key: 'sd1-ip-adapter',+ name: 'SD 1 IP Adapter',+ type: 'ip_adapter',+};+const fluxRedux: ComponentModelConfig = {+ base: 'flux',+ key: 'flux-redux',+ name: 'FLUX Redux',+ type: 'flux_redux',+};+const vae: VaeModelConfig = { base: 'sd-1', key: 'vae-model', name: 'Custom VAE', type: 'vae' };+const fluxVae: VaeModelConfig = { base: 'flux', key: 'flux-vae', name: 'FLUX VAE', type: 'vae' };+const flux2Vae: VaeModelConfig = { base: 'flux2', key: 'flux2-vae', name: 'FLUX.2 VAE', type: 'vae' };+const qwenImageVae: VaeModelConfig = { base: 'qwen-image', key: 'qwen-vae', name: 'Qwen VAE', type: 'vae' };+const t5Encoder: ComponentModelConfig = { base: 'any', key: 't5', name: 'T5 Encoder', type: 't5_encoder' };+const clipEmbed: ComponentModelConfig = { base: 'any', key: 'clip', name: 'CLIP Embed', type: 'clip_embed' };++const mistralEncoder: ComponentModelConfig = {++ base: 'any',++ key: 'mistral',++ name: 'Mistral Encoder',++ type: 'mistral_encoder',++};+const qwen3Encoder: ComponentModelConfig = {+ base: 'any',+ key: 'qwen3',+ name: 'Qwen3 Encoder',+ type: 'qwen3_encoder',+ variant: 'qwen3_06b',+};++const createSettings = (model: GenerateModelConfig, overrides: Partial<GenerateSettings> = {}): GenerateSettings => ({+ ...getDefaultGenerateSettings(model),+ seed: 1,+ shouldRandomizeSeed: false,+ ...overrides,+});++const refImage = {+ original: { image: { height: 768, image_name: 'reference.png', width: 512 } },+};++const compile = (model: GenerateModelConfig, 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);++const getNodeByType = (graph: ReturnType<typeof compile>, type: string) =>+ Object.values(graph.nodes).find((node) => node.type === type);++afterEach(() => {+ vi.restoreAllMocks();+});++describe('compileGenerateGraph', () => {+ it('recognizes the legacy-supported generate model families', () => {+ expect(+ [+ sd1Model,+ sdxlModel,+ sd3Model,+ fluxModel,+ flux2Model,+ cogView4Model,+ qwenImageModel,+ zImageModel,+ animaModel,+ externalModel,+ ].every(isSupportedGenerateModel)+ ).toBe(true);+ });++ 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);+ expect(graph.nodes.canvas_output?.color_compensation).toBe('None');+ });++ it('passes SDXL color compensation to the VAE decode node when enabled', () => {+ const graph = compile(sdxlModel, { colorCompensation: true });++ expect(graph.nodes.canvas_output?.color_compensation).toBe('SDXL');+ });++ it('coerces invalid SD schedulers before graph submission', () => {+ const graph = compile(sd1Model, { scheduler: 'not-a-scheduler' });+ const metadata = getNodeByType(graph, 'core_metadata');++ expect(graph.nodes.denoise_latents?.scheduler).toBe('euler_a');+ expect(metadata?.scheduler).toBe('euler_a');+ });++ 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.each([sd1Model, sdxlModel])('passes enabled HiDiffusion settings to $base denoise and metadata', (model) => {+ const graph = compile(model, {+ hiDiffusionEnabled: true,+ hiDiffusionRauNetEnabled: false,+ hiDiffusionT1Ratio: 0.35,+ hiDiffusionT2Ratio: 0.15,+ hiDiffusionWindowAttentionEnabled: true,+ });+ const denoise = graph.nodes.denoise_latents;+ const metadata = getNodeByType(graph, 'core_metadata');++ expect(denoise).toMatchObject({+ hidiffusion: true,+ hidiffusion_raunet: false,+ hidiffusion_t1_ratio: 0.35,+ hidiffusion_t2_ratio: 0.15,+ hidiffusion_window_attn: true,+ });+ expect(metadata).toMatchObject({+ hidiffusion: true,+ hidiffusion_raunet: false,+ hidiffusion_t1_ratio: 0.35,+ hidiffusion_t2_ratio: 0.15,+ hidiffusion_window_attn: true,+ });+ });++ it('omits HiDiffusion ratios from denoise while disabled but records all metadata settings', () => {+ const graph = compile(sd1Model, {+ hiDiffusionEnabled: false,+ hiDiffusionRauNetEnabled: false,+ hiDiffusionT1Ratio: 0.6,+ hiDiffusionT2Ratio: 0.2,+ hiDiffusionWindowAttentionEnabled: true,+ });+ const denoise = graph.nodes.denoise_latents;+ const metadata = getNodeByType(graph, 'core_metadata');++ expect(denoise).toMatchObject({+ hidiffusion: false,+ hidiffusion_raunet: false,+ hidiffusion_window_attn: true,+ });+ expect(denoise).not.toHaveProperty('hidiffusion_t1_ratio');+ expect(denoise).not.toHaveProperty('hidiffusion_t2_ratio');+ expect(metadata).toMatchObject({+ hidiffusion: false,+ hidiffusion_raunet: false,+ hidiffusion_t1_ratio: 0.6,+ hidiffusion_t2_ratio: 0.2,+ hidiffusion_window_attn: true,+ });+ });++ it('omits HiDiffusion inputs and metadata for unsupported SD2 models', () => {+ const graph = compile(sd2Model, {+ hiDiffusionEnabled: true,+ hiDiffusionRauNetEnabled: true,+ hiDiffusionT1Ratio: 0.4,+ hiDiffusionT2Ratio: 0,+ hiDiffusionWindowAttentionEnabled: true,+ });+ const metadata = getNodeByType(graph, 'core_metadata');++ for (const key of [+ 'hidiffusion',+ 'hidiffusion_raunet',+ 'hidiffusion_t1_ratio',+ 'hidiffusion_t2_ratio',+ 'hidiffusion_window_attn',+ ]) {+ expect(graph.nodes.denoise_latents).not.toHaveProperty(key);+ expect(metadata).not.toHaveProperty(key);+ }+ });++ 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');+ });++ it('routes SD LoRAs through the UNet and CLIP conditioning chain', () => {+ const graph = compile(sd1Model, {+ loras: [{ isEnabled: true, model: sd1Lora, weight: 0.5 }],+ });+ const loraLoader = getNodeByType(graph, 'lora_collection_loader');+ const metadata = getNodeByType(graph, 'core_metadata');++ expect(loraLoader).toBeDefined();+ expect(getEdge(graph, 'denoise_latents', 'unet')?.source.node_id).toBe(loraLoader?.id);+ expect(getEdge(graph, 'pos_cond', 'clip')?.source.node_id).toBe(loraLoader?.id);+ expect(getEdge(graph, 'neg_cond', 'clip')?.source.node_id).toBe(loraLoader?.id);+ expect(metadata?.loras).toEqual([+ { model: { base: 'sd-1', key: 'sd1-lora', name: 'SD 1.5 LoRA', type: 'lora' }, weight: 0.5 },+ ]);+ });++ it('routes SDXL LoRAs through both CLIP encoders', () => {+ const graph = compile(sdxlModel, {+ loras: [{ isEnabled: true, model: sdxlLora, weight: 0.65 }],+ });+ const loraLoader = getNodeByType(graph, 'sdxl_lora_collection_loader');++ expect(loraLoader).toBeDefined();+ expect(getEdge(graph, 'denoise_latents', 'unet')?.source.node_id).toBe(loraLoader?.id);+ expect(getEdge(graph, 'pos_cond', 'clip')?.source.node_id).toBe(loraLoader?.id);+ expect(getEdge(graph, 'pos_cond', 'clip2')?.source.node_id).toBe(loraLoader?.id);+ expect(getEdge(graph, 'neg_cond', 'clip2')?.source.node_id).toBe(loraLoader?.id);+ });++ it('ignores disabled and incompatible LoRAs', () => {+ const graph = compile(sd1Model, {+ loras: [+ { isEnabled: true, model: sd2Lora, weight: 1 },+ { isEnabled: false, model: sd1Lora, weight: 1 },+ ],+ });+ const metadata = getNodeByType(graph, 'core_metadata');++ expect(getNodeByType(graph, 'lora_collection_loader')).toBeUndefined();+ expect(getEdge(graph, 'denoise_latents', 'unet')?.source.node_id).toBe('model_loader');+ expect(metadata?.loras).toBeUndefined();+ });++ it('builds a FLUX graph with required components and FLUX LoRAs', () => {+ const graph = compile(fluxModel, {+ clipEmbedModel: clipEmbed,+ loras: [{ isEnabled: true, model: fluxLora, weight: 0.8 }],+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ });+ const loraLoader = getNodeByType(graph, 'flux_lora_collection_loader');++ expect(graph.nodes.model_loader?.type).toBe('flux_model_loader');+ expect(graph.nodes.model_loader?.t5_encoder_model).toEqual(t5Encoder);+ expect(graph.nodes.model_loader?.clip_embed_model).toEqual(clipEmbed);+ expect(graph.nodes.denoise_latents?.type).toBe('flux_denoise');+ expect(graph.nodes.canvas_output?.type).toBe('flux_vae_decode');+ expect(loraLoader).toBeDefined();+ expect(getEdge(graph, 'denoise_latents', 'transformer')?.source.node_id).toBe(loraLoader?.id);+ });++ it('fails early when required FLUX components are missing', () => {+ expect(() => compile(fluxModel)).toThrow('Generate needs a T5 Encoder for FLUX models.');+ });++ it('builds modern Diffusers-family graphs without separate component overrides', () => {+ expect(compile(sd3Model).nodes.model_loader?.type).toBe('sd3_model_loader');+ expect(compile(flux2Model).nodes.model_loader?.type).toBe('flux2_klein_model_loader');++ expect(compile(flux2DevModel).nodes.model_loader?.type).toBe('flux2_dev_model_loader');+ expect(compile(cogView4Model).nodes.model_loader?.type).toBe('cogview4_model_loader');+ expect(compile(qwenImageModel).nodes.model_loader?.type).toBe('qwen_image_model_loader');+ expect(compile(zImageModel).nodes.model_loader?.type).toBe('z_image_model_loader');+ });+++ it('builds FLUX.2 [dev] graphs with standalone components and dev LoRAs', () => {++ const graph = compile(flux2DevGgufModel, {++ loras: [{ isEnabled: true, model: flux2DevLora, weight: 0.75 }],++ mistralEncoderModel: mistralEncoder,++ vae: flux2Vae,++ });++ const loraLoader = getNodeByType(graph, 'flux2_dev_lora_collection_loader');++ const metadata = getNodeByType(graph, 'core_metadata');++++ expect(graph.nodes.model_loader).toMatchObject({++ mistral_encoder_model: mistralEncoder,++ type: 'flux2_dev_model_loader',++ vae_model: flux2Vae,++ });++ expect(graph.nodes.pos_cond?.type).toBe('flux2_dev_text_encoder');++ expect(loraLoader).toBeDefined();++ expect(getEdge(graph, 'pos_cond', 'mistral_encoder')?.source.node_id).toBe(loraLoader?.id);++ expect(getEdge(graph, 'denoise_latents', 'transformer')?.source.node_id).toBe(loraLoader?.id);++ expect(metadata?.mistral_encoder).toEqual(mistralEncoder);++ });++++ it('uses a compatible Diffusers model as the FLUX.2 [dev] component source', () => {++ const graph = compile(flux2DevGgufModel, { componentSourceModel: flux2DevSource });++++ expect(graph.nodes.model_loader).toMatchObject({++ mistral_source_model: flux2DevSource,++ type: 'flux2_dev_model_loader',++ });++ expect(graph.nodes.model_loader?.mistral_encoder_model).toBeUndefined();++ expect(graph.nodes.model_loader?.vae_model).toBeUndefined();++ });+++ it('does not enable FLUX.2 CFG without negative conditioning', () => {+ const graph = compile(flux2Model, { cfgScale: 4 });++ expect(graph.nodes.denoise_latents?.cfg_scale).toBe(1);+ expect(getEdge(graph, 'denoise_latents', 'negative_text_conditioning')).toBeUndefined();+ });++ it('routes FLUX.2 positive conditioning through a stable collector', () => {+ const graph = compile(flux2Model);++ expect(graph.nodes.pos_cond_collect?.type).toBe('collect');+ expect(getEdge(graph, 'pos_cond_collect', 'item')?.source.node_id).toBe('pos_cond');+ expect(getEdge(graph, 'denoise_latents', 'positive_text_conditioning')?.source.node_id).toBe('pos_cond_collect');+ });++ it('rejects a stale incompatible FLUX.2 component source when Qwen3 is missing', () => {+ expect(() => compile(flux2Klein9bModel, { componentSourceModel: incompatibleFlux2Source, vae: flux2Vae })).toThrow(+ 'Generate needs a Qwen3 Encoder for non-Diffusers FLUX.2 models.'+ );+ });++ it('rejects dimensions that are not on the selected model family grid', () => {+ expect(() => compile(flux2Model, { height: 888 })).toThrow('Generate height must be a multiple of 16.');+ });++ it('builds an Anima graph with required components', () => {+ expect(() => compile(animaModel)).toThrow('Generate needs a Qwen3 Encoder for Anima models.');++ const graph = compile(animaModel, { qwen3EncoderModel: qwen3Encoder, vae: qwenImageVae });++ expect(graph.nodes.model_loader?.type).toBe('anima_model_loader');+ expect(graph.nodes.model_loader?.qwen3_encoder_model).toEqual(qwen3Encoder);+ expect(graph.nodes.model_loader?.vae_model).toEqual(qwenImageVae);+ expect(graph.nodes.canvas_output?.type).toBe('anima_l2i');+ });++ it('builds an external provider graph', () => {+ const graph = compile(externalModel);++ expect(graph.nodes.canvas_output?.type).toBe('openai_image_generation');+ expect(graph.nodes.canvas_output?.model).toEqual(externalModel);+ expect(getEdge(graph, 'canvas_output', 'prompt')?.source.node_id).toBe('positive_prompt');+ expect(getEdge(graph, 'canvas_output', 'seed')?.source.node_id).toBe('seed');+ });++ it('does not wire unsupported external provider seed or negative prompt inputs', () => {+ const graph = compile({ ...externalModel, capabilities: { modes: ['txt2img'] } });++ expect(getEdge(graph, 'canvas_output', 'prompt')?.source.node_id).toBe('positive_prompt');+ expect(getEdge(graph, 'canvas_output', 'seed')).toBeUndefined();+ expect(getEdge(graph, 'canvas_output', 'negative_prompt')).toBeUndefined();+ });++ it('wires external negative prompt only when the provider advertises support', () => {+ const graph = compile({+ ...externalModel,+ capabilities: { modes: ['txt2img'], supports_negative_prompt: true, supports_seed: false },+ });++ expect(getEdge(graph, 'canvas_output', 'negative_prompt')?.source.node_id).toBe('negative_prompt');+ expect(getEdge(graph, 'canvas_output', 'seed')).toBeUndefined();+ });++ it('wires external provider reference images when supported', () => {+ const graph = compile(+ { ...externalModel, capabilities: { modes: ['txt2img'], supports_reference_images: true } },+ {+ referenceImages: [+ { id: 'ref-1', isEnabled: true, config: { type: 'external_reference_image', image: refImage } },+ ],+ }+ );++ expect(graph.nodes.canvas_output?.reference_images).toEqual([{ image_name: 'reference.png' }]);+ });++ it('wires SD IP Adapter reference images into denoise', () => {+ const graph = compile(sd1Model, {+ referenceImages: [+ {+ id: 'ref-1',+ isEnabled: true,+ config: {+ beginEndStepPct: [0.1, 0.8],+ clipVisionModel: 'ViT-H',+ image: refImage,+ method: 'style',+ model: sd1IpAdapter,+ type: 'ip_adapter',+ weight: 0.6,+ },+ },+ ],+ });+ const adapter = getNodeByType(graph, 'ip_adapter');++ expect(adapter).toMatchObject({+ begin_step_percent: 0.1,+ clip_vision_model: 'ViT-H',+ end_step_percent: 0.8,+ image: { image_name: 'reference.png' },+ ip_adapter_model: sd1IpAdapter,+ method: 'style',+ weight: 0.6,+ });+ expect(getEdge(graph, 'denoise_latents', 'ip_adapter')?.source.node_id).toContain('ip_adapter_collector');+ });++ it('generates from the crop while serializing complete original and crop metadata', () => {+ const croppedReferenceImage = {+ crop: {+ box: { height: 256, width: 320, x: 40, y: 50 },+ image: { height: 256, image_name: 'reference-crop.png', width: 320 },+ ratio: null,+ },+ original: { image: { height: 768, image_name: 'reference-original.png', width: 512 } },+ };+ const graph = compile(sd1Model, {+ referenceImages: [+ {+ config: {+ beginEndStepPct: [0, 1],+ clipVisionModel: 'ViT-H',+ image: croppedReferenceImage,+ method: 'full',+ model: sd1IpAdapter,+ type: 'ip_adapter',+ weight: 1,+ },+ id: 'cropped-ref',+ isEnabled: true,+ },+ ],+ });+ const metadata = getNodeByType(graph, 'core_metadata');++ expect(getNodeByType(graph, 'ip_adapter')?.image).toEqual({ image_name: 'reference-crop.png' });+ expect(metadata?.ref_images).toMatchObject([+ {+ config: { image: croppedReferenceImage },+ id: 'cropped-ref',+ isEnabled: true,+ },+ ]);+ });++ it('wires FLUX Redux reference images into denoise', () => {+ const graph = compile(fluxModel, {+ clipEmbedModel: clipEmbed,+ referenceImages: [+ {+ id: 'ref-redux',+ isEnabled: true,+ config: { image: refImage, imageInfluence: 'medium', model: fluxRedux, type: 'flux_redux' },+ },+ ],+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ });+ const redux = getNodeByType(graph, 'flux_redux');++ expect(redux).toMatchObject({ image: { image_name: 'reference.png' }, redux_model: fluxRedux });+ expect(getEdge(graph, 'denoise_latents', 'redux_conditioning')?.source.node_id).toContain('flux_redux_collector');+ });++ it('wires FLUX Kontext reference images into denoise', () => {+ const graph = compile(fluxKontextModel, {+ clipEmbedModel: clipEmbed,+ referenceImages: [+ {+ id: 'ref-kontext',+ isEnabled: true,+ config: { image: refImage, model: fluxKontextModel, type: 'flux_kontext_reference_image' },+ },+ ],+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ });++ expect(getNodeByType(graph, 'flux_kontext')).toBeDefined();+ expect(getEdge(graph, 'denoise_latents', 'kontext_conditioning')?.source.node_id).toContain('flux_kontext_collect');+ });++ it('wires FLUX.2 built-in reference images into denoise', () => {+ const graph = compile(flux2Model, {+ referenceImages: [+ { id: 'ref-flux2', isEnabled: true, config: { image: refImage, type: 'flux2_reference_image' } },+ ],+ });++ expect(getNodeByType(graph, 'flux_kontext')).toBeDefined();+ expect(getEdge(graph, 'denoise_latents', 'kontext_conditioning')?.source.node_id).toContain(+ 'flux2_kontext_collect'+ );+ });++ it('wires Qwen Image Edit reference images into text encoder and denoise latents', () => {+ const graph = compile(+ { ...qwenImageModel, variant: 'edit' },+ {+ referenceImages: [+ { id: 'ref-qwen', isEnabled: true, config: { image: refImage, type: 'qwen_image_reference_image' } },+ ],+ }+ );++ expect(getEdge(graph, 'pos_cond', 'reference_images')).toBeDefined();+ expect(getEdge(graph, 'denoise_latents', 'reference_latents')).toBeDefined();+ });+});++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]);+ });+});++describe('Krea-2, Ideogram 4 and Wan graphs', () => {+ const krea2Diffusers: MainModelConfig = {+ base: 'krea-2',+ format: 'diffusers',+ key: 'krea2-diffusers',+ name: 'Krea-2 Turbo',+ type: 'main',+ variant: 'krea2_turbo',+ };+ const krea2Checkpoint: MainModelConfig = {+ base: 'krea-2',+ format: 'checkpoint',+ key: 'krea2-checkpoint',+ name: 'Krea-2 Raw',+ type: 'main',+ variant: 'krea2_base',+ };+ const ideogram4Model: MainModelConfig = {+ base: 'ideogram-4',+ format: 'diffusers',+ key: 'ideogram4',+ name: 'Ideogram 4',+ type: 'main',+ };+ const wanDiffusers: MainModelConfig = {+ base: 'wan',+ format: 'diffusers',+ key: 'wan-diffusers',+ name: 'Wan 2.2 TI2V 5B',+ type: 'main',+ variant: 'ti2v_5b',+ };+ const krea2Vae: VaeModelConfig = { base: 'qwen-image', key: 'krea2-vae', name: 'Qwen VAE', type: 'vae' };+ const qwen3VlEncoder: ComponentModelConfig = {+ base: 'any',+ key: 'qwen3-vl',+ name: 'Qwen3-VL',+ type: 'qwen3_vl_encoder',+ };+ const wanLowNoise: MainModelConfig = {+ base: 'wan',+ format: 'diffusers',+ key: 'wan-low',+ name: 'Wan low noise',+ type: 'main',+ variant: 'i2v_a14b',+ };++ it('decodes Krea-2 with the Qwen-Image VAE node it shares', () => {+ const graph = compile(krea2Diffusers);++ expect(graph.nodes.model_loader?.type).toBe('krea2_model_loader');+ expect(graph.nodes.canvas_output?.type).toBe('qwen_image_l2i');+ expect(graph.nodes.denoise_latents?.type).toBe('krea2_denoise');+ });++ it('omits Krea-2 negative conditioning while CFG is disabled, and adds it when enabled', () => {+ // Krea-2-Turbo runs at cfg_scale 1 by default, where the model takes no negative input.+ expect(compile(krea2Diffusers, { cfgScale: 1 }).nodes.neg_cond).toBeUndefined();++ const withCfg = compile(krea2Diffusers, { cfgScale: 4.5 });++ expect(withCfg.nodes.neg_cond?.type).toBe('krea2_text_encoder');+ expect(getEdge(withCfg, 'denoise_latents', 'negative_conditioning')).toBeDefined();+ });++ it('passes standalone Krea-2 submodels to the loader for a non-diffusers transformer', () => {+ const graph = compile(krea2Checkpoint, { qwen3VLEncoderModel: qwen3VlEncoder, vae: krea2Vae });++ expect(graph.nodes.model_loader).toMatchObject({+ qwen3_vl_encoder_model: qwen3VlEncoder,+ vae_model: krea2Vae,+ });+ });++ it('sends an anima-registered Qwen-Image VAE to the Krea-2 loader', () => {+ // Regression: the builder filtered VAEs to base `qwen-image`, so a Qwen-Image VAE+ // installed under the `anima` base was dropped and the loader got no VAE at all.+ const animaRegisteredVae: VaeModelConfig = {+ base: 'anima',+ key: 'anima-qwen-vae',+ name: 'Qwen VAE (installed for Anima)',+ type: 'vae',+ };+ const graph = compile(krea2Checkpoint, {+ qwen3VLEncoderModel: qwen3VlEncoder,+ vae: animaRegisteredVae,+ });++ expect(graph.nodes.model_loader).toMatchObject({ vae_model: animaRegisteredVae });+ });++ it('refuses to compile a non-diffusers Krea-2 with a missing submodel', () => {+ // Validation runs ahead of the builder, so the user-facing reason surfaces rather than the+ // builder's internal guard. Both layers exist; this pins which one the user actually sees.+ expect(() => compile(krea2Checkpoint, { qwen3VLEncoderModel: qwen3VlEncoder })).toThrow(+ 'Generate needs a VAE for non-Diffusers Krea-2 models.'+ );+ expect(() => compile(krea2Checkpoint, { vae: krea2Vae })).toThrow(+ 'Generate needs a Qwen3-VL Encoder for non-Diffusers Krea-2 models.'+ );+ });++ it('leaves the Krea-2 conditioning path untouched while both enhancers are off', () => {+ const graph = compile(krea2Diffusers);++ expect(getNodeByType(graph, 'krea2_conditioning_rebalance')).toBeUndefined();+ expect(getNodeByType(graph, 'krea2_seed_variance')).toBeUndefined();+ expect(getEdge(graph, 'pos_cond_collect', 'item')?.source.node_id).toBe('pos_cond');+ expect(getEdge(graph, 'denoise_latents', 'positive_conditioning')?.source.node_id).toBe('pos_cond_collect');+ });++ it('chains rebalance then seed variance between the Krea-2 encoder and denoise', () => {+ const graph = compile(krea2Diffusers, {+ krea2RebalanceEnabled: true,+ krea2SeedVarianceEnabled: true,+ krea2SeedVarianceStrength: 0.2,+ });++ expect(getEdge(graph, 'krea2_rebalance', 'conditioning')?.source.node_id).toBe('pos_cond');+ expect(getEdge(graph, 'krea2_seed_variance', 'conditioning')?.source.node_id).toBe('krea2_rebalance');+ expect(getEdge(graph, 'pos_cond_collect', 'item')?.source.node_id).toBe('krea2_seed_variance');+ expect(getEdge(graph, 'denoise_latents', 'positive_conditioning')?.source.node_id).toBe('pos_cond_collect');+ // Seed variance needs the seed to be reproducible run-to-run.+ expect(getEdge(graph, 'krea2_seed_variance', 'variance_seed')?.source.node_id).toBe('seed');+ });++ it('skips Krea-2 seed variance at zero strength, which would be a no-op node', () => {+ const graph = compile(krea2Diffusers, { krea2SeedVarianceEnabled: true, krea2SeedVarianceStrength: 0 });++ expect(getNodeByType(graph, 'krea2_seed_variance')).toBeUndefined();+ });++ it('routes the Ideogram 4 prompt through the caption builder and omits negative conditioning', () => {+ const graph = compile(ideogram4Model);++ expect(getEdge(graph, 'caption_builder', 'prompt')?.source.node_id).toBe('positive_prompt');+ expect(getEdge(graph, 'pos_cond', 'prompt')?.source.node_id).toBe('caption_builder');+ // Ideogram 4's denoise node has no negative conditioning input at all.+ expect(graph.nodes.neg_cond).toBeUndefined();+ expect(getEdge(graph, 'denoise_latents', 'negative_conditioning')).toBeUndefined();+ });++ it('omits unset Ideogram 4 overrides so the sampler preset keeps deciding', () => {+ const graph = compile(ideogram4Model);++ expect(graph.nodes.denoise_latents).toMatchObject({ sampler_preset: 'V4_QUALITY_48' });+ expect(graph.nodes.denoise_latents).not.toHaveProperty('steps');+ expect(graph.nodes.denoise_latents).not.toHaveProperty('guidance_scale');+ expect(graph.nodes.denoise_latents).not.toHaveProperty('mu');+ });++ it('sends Ideogram 4 overrides once set', () => {+ const graph = compile(ideogram4Model, {+ ideogram4GuidanceScale: 6,+ ideogram4Mu: 1.5,+ ideogram4SamplerPreset: 'V4_TURBO_12',+ ideogram4Steps: 12,+ });++ expect(graph.nodes.denoise_latents).toMatchObject({+ guidance_scale: 6,+ mu: 1.5,+ sampler_preset: 'V4_TURBO_12',+ steps: 12,+ });+ });++ it('forwards the Ideogram 4 color palette to the caption builder', () => {+ const graph = compile(ideogram4Model, { ideogram4ColorPalette: ['teal', 'ochre'] });++ expect(graph.nodes.caption_builder).toMatchObject({ color_palette: ['teal', 'ochre'] });+ });++ it('emits a single-frame image output for Wan, not a video', () => {+ const graph = compile(wanDiffusers);++ expect(graph.nodes.model_loader?.type).toBe('wan_model_loader');+ expect(graph.nodes.canvas_output?.type).toBe('wan_l2i');+ expect(getNodeByType(graph, 'wan_l2v')).toBeUndefined();+ });++ it('always gives Wan a negative prompt, which it supports unconditionally', () => {+ const graph = compile(wanDiffusers, { cfgScale: 1 });++ expect(graph.nodes.neg_cond?.type).toBe('wan_text_encoder');+ expect(getEdge(graph, 'denoise_latents', 'negative_conditioning')?.source.node_id).toBe('neg_cond');+ });++ it('passes the optional Wan low-noise expert through and leaves it unset otherwise', () => {+ // Unset optional model fields stay `undefined` here, matching every other builder; they+ // drop out when the graph is serialized rather than reaching the backend as null.+ expect(compile(wanDiffusers).nodes.model_loader?.transformer_low_noise_model).toBeUndefined();+ expect(compile(wanDiffusers, { wanLowNoiseModel: wanLowNoise }).nodes.model_loader).toMatchObject({+ transformer_low_noise_model: wanLowNoise,+ });+ });++ it('omits the Wan low-noise guidance unless overridden, letting the backend reuse guidance_scale', () => {+ expect(compile(wanDiffusers).nodes.denoise_latents).not.toHaveProperty('guidance_scale_low_noise');+ expect(compile(wanDiffusers, { wanGuidanceScaleLowNoise: 2.5 }).nodes.denoise_latents).toMatchObject({+ guidance_scale_low_noise: 2.5,+ });+ });++ it('routes Wan LoRAs through the transformer only, leaving the text encoder unpatched', () => {+ const a14bLora: LoraModelConfig = {+ base: 'wan',+ key: 'wan-lora',+ name: '5B LoRA',+ type: 'lora',+ variant: '5b',+ };+ const graph = compile(wanDiffusers, { loras: [{ isEnabled: true, model: a14bLora, weight: 1 }] });+ const loader = getNodeByType(graph, 'wan_lora_collection_loader');++ expect(loader).toBeDefined();+ expect(getEdge(graph, 'denoise_latents', 'transformer')?.source.node_id).toBe(loader?.id);+ // The Wan encoder is fed straight from the model loader — Wan LoRAs do not touch it.+ expect(getEdge(graph, 'pos_cond', 'wan_t5_encoder')?.source.node_id).toBe('model_loader');+ });+});++describe('PiD decode', () => {+ const pidDecoder = (base: string): ComponentModelConfig => ({+ base,+ key: `pid-${base}`,+ name: `PiD ${base}`,+ type: 'pid_decoder',+ });+ const gemma2: ComponentModelConfig = { base: 'any', key: 'gemma2', name: 'Gemma 2 2B', type: 'gemma2_encoder' };++ const pidSettings = (base: string, overrides: Partial<GenerateSettings> = {}): Partial<GenerateSettings> => ({+ gemma2EncoderModel: gemma2,+ pidDecoderModel: pidDecoder(base),+ pidMode: 'fit',+ ...overrides,+ });++ it('keeps the ordinary VAE decode when PiD is off', () => {+ const graph = compile(fluxModel, { clipEmbedModel: clipEmbed, t5EncoderModel: t5Encoder, vae: fluxVae });++ expect(getNodeByType(graph, 'flux_vae_decode')).toBeDefined();+ expect(getNodeByType(graph, 'flux_pid_decode')).toBeUndefined();+ });++ it('replaces the VAE decode with a PiD decode and downscales in fit mode', () => {+ const graph = compile(fluxModel, {+ clipEmbedModel: clipEmbed,+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ ...pidSettings('flux'),+ height: 1024,+ width: 1024,+ });++ expect(getNodeByType(graph, 'flux_vae_decode')).toBeUndefined();+ const decode = getNodeByType(graph, 'flux_pid_decode');+ expect(decode).toBeDefined();+ // The resize is the output, because the 4x decode must come back to the asked-for size.+ const output = graph.nodes.canvas_output;+ expect(output?.type).toBe('img_resize');+ expect(output).toMatchObject({ height: 1024, width: 1024 });+ expect(getEdge(graph, 'canvas_output', 'image')?.source.node_id).toBe(decode?.id);+ });++ it('generates at the full size in fit mode', () => {+ const graph = compile(fluxModel, {+ clipEmbedModel: clipEmbed,+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ ...pidSettings('flux'),+ height: 1024,+ width: 1024,+ });++ expect(graph.nodes.denoise_latents).toMatchObject({ height: 1024, width: 1024 });+ });++ it('generates at a quarter size in native mode and makes the decode the output', () => {+ const graph = compile(fluxModel, {+ clipEmbedModel: clipEmbed,+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ ...pidSettings('flux', { pidMode: 'native' }),+ height: 2048,+ width: 2048,+ });++ expect(graph.nodes.denoise_latents).toMatchObject({ height: 512, width: 512 });+ // No downscale: PiD's 4x output IS the result.+ expect(graph.nodes.canvas_output?.type).toBe('flux_pid_decode');+ expect(getNodeByType(graph, 'img_resize')).toBeUndefined();+ });++ it('wires the prompt, seed and both loaders into the decode', () => {+ const graph = compile(fluxModel, {+ clipEmbedModel: clipEmbed,+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ ...pidSettings('flux'),+ });+ const decode = getNodeByType(graph, 'flux_pid_decode');++ expect(getEdge(graph, decode!.id, 'prompt')?.source.node_id).toBe('positive_prompt');+ expect(getEdge(graph, decode!.id, 'seed')?.source.node_id).toBe('seed');+ expect(getEdge(graph, decode!.id, 'latents')?.source.node_id).toBe('denoise_latents');+ expect(getNodeByType(graph, 'pid_decoder_loader')).toMatchObject({ pid_decoder_model: pidDecoder('flux') });+ expect(getNodeByType(graph, 'gemma2_encoder_loader')).toMatchObject({ gemma2_model: gemma2 });+ });++ it('does not wire a VAE into decoders that use fixed constants', () => {+ const graph = compile(fluxModel, {+ clipEmbedModel: clipEmbed,+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ ...pidSettings('flux'),+ });+ const decode = getNodeByType(graph, 'flux_pid_decode');++ // FLUX.1 and SD3 use fixed VAE constants and expose no `vae` input.+ expect(getEdge(graph, decode!.id, 'vae')).toBeUndefined();+ });++ it('wires a VAE into decoders that read its constants at runtime', () => {+ const graph = compile(qwenImageModel, { ...pidSettings('qwen-image') });+ const decode = getNodeByType(graph, 'qwen_image_pid_decode');++ expect(getEdge(graph, decode!.id, 'vae')?.source.node_id).toBe('model_loader');+ });++ it('uses a FLUX decoder for Z-Image, which shares its VAE', () => {+ const graph = compile(zImageModel, { ...pidSettings('flux') });++ expect(getNodeByType(graph, 'z_image_pid_decode')).toBeDefined();+ expect(getNodeByType(graph, 'pid_decoder_loader')).toMatchObject({ pid_decoder_model: pidDecoder('flux') });+ });++ it('decodes through PiD for SDXL, sizing the noise node instead of the denoise node', () => {+ const graph = compile(sdxlModel, { ...pidSettings('sdxl', { pidMode: 'native' }), height: 2048, width: 2048 });++ // SDXL is sized via its noise node; its grid is 8, so 2048 / 4 = 512.+ expect(graph.nodes.noise).toMatchObject({ height: 512, width: 512 });+ expect(graph.nodes.canvas_output?.type).toBe('sdxl_pid_decode');+ });++ it('decodes through PiD for SD3', () => {+ const graph = compile(sd3Model, { ...pidSettings('sd-3') });++ expect(getNodeByType(graph, 'sd3_pid_decode')).toBeDefined();+ expect(getNodeByType(graph, 'sd3_l2i')).toBeUndefined();+ });++ it('decodes through PiD for FLUX.2', () => {+ const graph = compile(flux2Model, { ...pidSettings('flux2') });++ expect(getNodeByType(graph, 'flux2_pid_decode')).toBeDefined();+ expect(getNodeByType(graph, 'flux2_vae_decode')).toBeUndefined();+ });++ it('records the PiD settings in metadata', () => {+ const graph = compile(fluxModel, {+ clipEmbedModel: clipEmbed,+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ ...pidSettings('flux'),+ });+ const metadata = getNodeByType(graph, 'core_metadata');++ expect(metadata).toMatchObject({ pid_mode: 'fit', pid_steps: 4 });+ });++ it('refuses to compile PiD on an unsupported base rather than silently ignoring it', () => {+ // CogView4 has no PiD decode node. Falling back to an ordinary decode would leave the+ // user wondering why the output is not 4x.+ expect(() => compile(cogView4Model, { pidMode: 'fit' })).toThrow(/PiD is not supported/);+ });++ it('requires both PiD models before compiling', () => {+ expect(() =>+ compile(fluxModel, {+ clipEmbedModel: clipEmbed,+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ pidMode: 'fit',+ pidDecoderModel: pidDecoder('flux'),+ })+ ).toThrow(/Gemma-2 encoder/);+ expect(() =>+ compile(fluxModel, {+ clipEmbedModel: clipEmbed,+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ pidMode: 'fit',+ gemma2EncoderModel: gemma2,+ })+ ).toThrow(/PiD decoder/);+ });++ it('enforces the 4x grid on the requested size in native mode', () => {+ // FLUX's grid is 16, so native requires multiples of 64.+ expect(() =>+ compile(fluxModel, {+ clipEmbedModel: clipEmbed,+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ ...pidSettings('flux', { pidMode: 'native' }),+ height: 2048,+ width: 2032,+ })+ ).toThrow(/multiple of 64/);+ });+});diff --cc invokeai/frontend/webv2/src/features/generation/core/graph.tsindex 692fb2ae5b,0000000000..0c32d4e395mode 100644,000000..100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts@@@ -1,1432 -1,0 +1,1466 @@@+import type {+ BackendGraphContract,+ BackendInvocationContract,+ GenerationProjectSettings,+ ResultDestination,+} from '@features/generation/core/contracts';++import type {+ CompiledGenerateGraph,+ ComponentModelConfig,+ GenerateLora,+ GenerateModelConfig,+ GenerateReferenceImage,+ GenerateReferenceImageAsset,+ GenerateReferenceImageConfig,+ GenerateSettings,+ MainModelConfig,+} from './types';++import {+ coerceSchedulerForGraph,+ getExternalProviderNodeType,+ getFlux2DiffusersComponentSource,+ getGenerationDimensions,+ getGenerationValidationReasons,+ type SupportedGenerateBase,+} from './baseGenerationPolicies';+import {+ getCompatibleDiffusersComponentSource,+ isAnimaQwen3Encoder,+ isAnimaVae,++ isFlux2MistralEncoder,+ isFlux2Qwen3EncoderForModel,+ isNonAnimaQwen3Encoder,+ isKrea2Vae,+ isVaeForBases,+} from './componentCompatibility';+import {+ addEdge,+ addMetadata,+ addNode,+ createId,+ getActiveCompatibleLoras,+ toModelIdentifier,+ toGraphContract,+} from './graphBuilder';+import { addKrea2ConditioningEnhancers } from './krea2Conditioning';+import { addPidDecode, getPidDenoiseSize, getPidMetadata, shouldUsePidDecode } from './pidGraph';+import { getEffectiveReferenceImage } from './referenceImage';+import { SEED_MAX } from './settings';++const getCompatibleComponentSource = (+ settings: GenerateSettings,+ model: MainModelConfig+): MainModelConfig | undefined => getCompatibleDiffusersComponentSource(model, settings.componentSourceModel);++const getCompatibleVae = (settings: GenerateSettings, bases: readonly string[]) =>+ settings.vae && isVaeForBases(bases)(settings.vae) ? settings.vae : null;++const toImageField = (image: GenerateReferenceImageAsset) => ({+ image_name: getEffectiveReferenceImage(image).image_name,+});++const getEnabledReferenceImages = <T extends GenerateReferenceImageConfig['type']>(+ settings: GenerateSettings,+ type: T+): Array<GenerateReferenceImage & { config: Extract<GenerateReferenceImageConfig, { type: T }> }> =>+ settings.referenceImages.filter(+ (+ referenceImage+ ): referenceImage is GenerateReferenceImage & { config: Extract<GenerateReferenceImageConfig, { type: T }> } =>+ referenceImage.isEnabled && referenceImage.config.type === type && referenceImage.config.image !== null+ );++const addReferenceImageMetadata = (+ graph: BackendGraphContract,+ outputNode: BackendInvocationContract,+ settings: GenerateSettings+) => {+ const enabled = settings.referenceImages.filter(+ (referenceImage) => referenceImage.isEnabled && referenceImage.config.image+ );++ if (enabled.length === 0) {+ return;+ }++ const metadata = Object.values(graph.nodes).find((node) => node.type === 'core_metadata');++ if (metadata) {+ metadata.ref_images = enabled;+ return;+ }++ outputNode.ref_images = enabled;+};++const addIPAdapterReferenceImages = (+ graph: BackendGraphContract,+ settings: GenerateSettings,+ model: MainModelConfig,+ denoise: BackendInvocationContract+) => {+ const refs = getEnabledReferenceImages(settings, 'ip_adapter').filter((ref) => ref.config.model?.base === model.base);++ if (refs.length === 0) {+ return;+ }++ const collector = addNode(graph, { id: createId('ip_adapter_collector'), type: 'collect' });++ for (const ref of refs) {+ const { beginEndStepPct, clipVisionModel, image, method, model: adapterModel, weight } = ref.config;++ if (!image || !adapterModel) {+ continue;+ }++ const node = addNode(graph, {+ begin_step_percent: beginEndStepPct[0],+ clip_vision_model: clipVisionModel,+ end_step_percent: beginEndStepPct[1],+ id: createId('ip_adapter'),+ image: toImageField(image),+ ip_adapter_model: adapterModel,+ method,+ type: model.base === 'flux' ? 'flux_ip_adapter' : 'ip_adapter',+ weight,+ });++ addEdge(graph, node, 'ip_adapter', collector, 'item');+ }++ addEdge(graph, collector, 'collection', denoise, 'ip_adapter');+};++const FLUX_REDUX_INFLUENCE = {+ lowest: { downsampling_factor: 5, weight: 1 },+ low: { downsampling_factor: 4, weight: 1 },+ medium: { downsampling_factor: 3, weight: 1 },+ high: { downsampling_factor: 2, weight: 1 },+ highest: { downsampling_factor: 1, weight: 1 },+} as const;++const addFluxReduxReferenceImages = (+ graph: BackendGraphContract,+ settings: GenerateSettings,+ model: MainModelConfig,+ denoise: BackendInvocationContract+) => {+ const refs = getEnabledReferenceImages(settings, 'flux_redux').filter((ref) => ref.config.model?.base === model.base);++ if (refs.length === 0) {+ return;+ }++ const collector = addNode(graph, { id: createId('flux_redux_collector'), type: 'collect' });++ for (const ref of refs) {+ const { image, imageInfluence, model: reduxModel } = ref.config;++ if (!image || !reduxModel) {+ continue;+ }++ const node = addNode(graph, {+ id: createId('flux_redux'),+ image: toImageField(image),+ redux_model: reduxModel,+ type: 'flux_redux',+ ...FLUX_REDUX_INFLUENCE[imageInfluence],+ });++ addEdge(graph, node, 'redux_cond', collector, 'item');+ }++ addEdge(graph, collector, 'collection', denoise, 'redux_conditioning');+};++const addFluxKontextReferenceImages = (+ graph: BackendGraphContract,+ settings: GenerateSettings,+ denoise: BackendInvocationContract,+ type: 'flux2_reference_image' | 'flux_kontext_reference_image'+) => {+ const refs = getEnabledReferenceImages(settings, type);++ if (refs.length === 0) {+ return;+ }++ let prevCollect: BackendInvocationContract | null = null;++ for (const ref of refs) {+ const { image } = ref.config;++ if (!image) {+ continue;+ }++ const kontext = addNode(graph, {+ id: createId('flux_kontext'),+ image: toImageField(image),+ type: 'flux_kontext',+ });+ const collect = addNode(graph, {+ id: createId(type === 'flux2_reference_image' ? 'flux2_kontext_collect' : 'flux_kontext_collect'),+ type: 'collect',+ });++ addEdge(graph, kontext, 'kontext_cond', collect, 'item');+ if (prevCollect) {+ addEdge(graph, prevCollect, 'collection', collect, 'collection');+ }+ prevCollect = collect;+ }++ if (prevCollect) {+ addEdge(graph, prevCollect, 'collection', denoise, 'kontext_conditioning');+ }+};++const getDiffusersSource = (settings: GenerateSettings, model: MainModelConfig): MainModelConfig | undefined =>+ getCompatibleComponentSource(settings, model) ?? (model.format === 'diffusers' ? model : undefined);++const requireComponent = <T extends ComponentModelConfig | null>(value: T, label: string): NonNullable<T> => {+ if (!value) {+ throw new Error(`${label} is required for this model family.`);+ }++ return value;+};++const addLoraSelectors = (+ graph: BackendGraphContract,+ loras: GenerateLora[],+ loaderType: string+): BackendInvocationContract => {+ const collector = addNode(graph, { id: createId('lora_collector'), type: 'collect' });+ const loader = addNode(graph, { id: createId(loaderType), type: loaderType });++ addEdge(graph, collector, 'collection', loader, 'loras');++ for (const lora of loras) {+ const selector = addNode(graph, {+ id: createId('lora_selector'),+ lora: toModelIdentifier(lora.model),+ type: 'lora_selector',+ weight: lora.weight,+ });++ addEdge(graph, selector, 'lora', collector, 'item');+ }++ return loader;+};++export const addLoraCollectionLoader = (+ graph: BackendGraphContract,+ loras: GenerateLora[],+ model: GenerateModelConfig,+ sources: {+ clip: BackendInvocationContract;+ clip2?: BackendInvocationContract;+ unet: BackendInvocationContract;+ }+): BackendInvocationContract => {+ const loaderType = model.base === 'sdxl' ? 'sdxl_lora_collection_loader' : 'lora_collection_loader';+ const loader = addLoraSelectors(graph, loras, loaderType);++ addEdge(graph, sources.unet, 'unet', loader, 'unet');+ addEdge(graph, sources.clip, 'clip', loader, 'clip');++ if (sources.clip2) {+ addEdge(graph, sources.clip2, 'clip2', loader, 'clip2');+ }++ return loader;+};++const addTransformerLoraCollectionLoader = (+ graph: BackendGraphContract,+ loras: GenerateLora[],+ loaderType: string,+ modelLoader: BackendInvocationContract,+ fields: string[]+): BackendInvocationContract => {+ const loader = addLoraSelectors(graph, loras, loaderType);++ for (const field of fields) {+ addEdge(graph, modelLoader, field, loader, field);+ }++ return loader;+};++const buildSDGraph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: GenerationProjectSettings+): BackendGraphContract => {+ const graph: BackendGraphContract = { edges: [], id: createId(`${model.base}_graph`), nodes: {} };+ const modelLoaderType = model.base === 'sdxl' ? 'sdxl_model_loader' : 'main_model_loader';+ const compelType = model.base === 'sdxl' ? 'sdxl_compel_prompt' : 'compel';+ const activeLoras = getActiveCompatibleLoras(settings, model);+ const scheduler = coerceSchedulerForGraph(model, settings.scheduler);+ const colorCompensation = settings.colorCompensation ? 'SDXL' : 'None';+ const supportsHiDiffusion = model.base === 'sd-1' || model.base === 'sdxl';++ const positivePrompt = addNode(graph, { id: 'positive_prompt', type: 'string' });+ const negativePrompt = addNode(graph, { id: 'negative_prompt', type: 'string' });+ const seed = addNode(graph, { id: 'seed', type: 'integer' });+ const modelLoader = addNode(graph, { id: 'model_loader', model, type: modelLoaderType });+ const posCond = addNode(graph, { id: 'pos_cond', type: compelType });+ const negCond = addNode(graph, { id: 'neg_cond', type: compelType });+ const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });+ const negCondCollect = addNode(graph, { id: 'neg_cond_collect', type: 'collect' });+ const sdDenoiseSize = getDenoiseSize(settings, model);+ const noise = addNode(graph, {+ height: sdDenoiseSize.height,+ id: 'noise',+ type: 'noise',+ use_cpu: projectSettings.useCpuNoise,+ width: sdDenoiseSize.width,+ });+ const denoise = addNode(graph, {+ cfg_rescale_multiplier: settings.cfgRescaleMultiplier,+ cfg_scale: settings.cfgScale,+ denoising_end: 1,+ denoising_start: 0,+ id: 'denoise_latents',+ ...(supportsHiDiffusion+ ? {+ hidiffusion: settings.hiDiffusionEnabled,+ hidiffusion_raunet: settings.hiDiffusionRauNetEnabled,+ hidiffusion_window_attn: settings.hiDiffusionWindowAttentionEnabled,+ ...(settings.hiDiffusionEnabled+ ? {+ hidiffusion_t1_ratio: settings.hiDiffusionT1Ratio,+ hidiffusion_t2_ratio: settings.hiDiffusionT2Ratio,+ }+ : {}),+ }+ : {}),+ scheduler,+ steps: settings.steps,+ type: 'denoise_latents',+ });+ // 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;+ let unetSource: BackendInvocationContract = seamless ?? modelLoader;+ let clipSource: BackendInvocationContract = modelLoader;+ let clip2Source: BackendInvocationContract | undefined;++ if (model.base === 'sdxl') {+ clip2Source = modelLoader;+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, positivePrompt, 'value', posCond, 'style');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ addEdge(graph, negativePrompt, 'value', negCond, 'style');+ } else {+ const clipSkip = addNode(graph, { id: 'clip_skip', skipped_layers: settings.clipSkip, type: 'clip_skip' });++ addEdge(graph, modelLoader, 'clip', clipSkip, 'clip');+ clipSource = clipSkip;+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ }++ if (activeLoras.length > 0) {+ const loraLoader = addLoraCollectionLoader(graph, activeLoras, model, {+ clip: clipSource,+ clip2: clip2Source,+ unet: unetSource,+ });++ unetSource = loraLoader;+ clipSource = loraLoader;+ clip2Source = model.base === 'sdxl' ? loraLoader : undefined;+ }++ if (model.base === 'sdxl') {+ addEdge(graph, clipSource, 'clip', posCond, 'clip');+ addEdge(graph, clip2Source ?? modelLoader, 'clip2', posCond, 'clip2');+ addEdge(graph, clipSource, 'clip', negCond, 'clip');+ addEdge(graph, clip2Source ?? modelLoader, 'clip2', negCond, 'clip2');+ } else {+ addEdge(graph, clipSource, 'clip', posCond, 'clip');+ addEdge(graph, clipSource, 'clip', negCond, 'clip');+ }++ addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');+ addEdge(graph, posCondCollect, 'collection', denoise, 'positive_conditioning');+ addEdge(graph, negCond, 'conditioning', negCondCollect, 'item');+ addEdge(graph, negCondCollect, 'collection', denoise, 'negative_conditioning');+ addEdge(graph, seed, 'value', noise, 'seed');++ // 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, unetSource, 'unet', denoise, 'unet');+ addEdge(graph, noise, 'noise', denoise, 'noise');+ addIPAdapterReferenceImages(graph, settings, model, denoise);+ // Created here rather than with the other nodes because the decode's VAE source is+ // only settled once the seamless / VAE-override nodes above are known.+ const output = addDecodeOutput({+ denoise,+ graph,+ l2iProps: { color_compensation: colorCompensation, fp32: settings.vaePrecision === 'fp32' },+ l2iType: 'l2i',+ model,+ outputIsIntermediate,+ positivePrompt,+ seed,+ settings,+ vaeSource: seamless ?? vaeLoader ?? modelLoader,+ });++ addMetadata(graph, output, settings, model, model.base === 'sdxl' ? 'sdxl_txt2img' : 'txt2img', projectSettings, {+ ...(supportsHiDiffusion+ ? {+ hidiffusion: settings.hiDiffusionEnabled,+ hidiffusion_raunet: settings.hiDiffusionRauNetEnabled,+ hidiffusion_t1_ratio: settings.hiDiffusionT1Ratio,+ hidiffusion_t2_ratio: settings.hiDiffusionT2Ratio,+ hidiffusion_window_attn: settings.hiDiffusionWindowAttentionEnabled,+ }+ : {}),+ scheduler,+ });+ addReferenceImageMetadata(graph, output, settings);++ return graph;+};++const addPromptAndSeedNodes = (graph: BackendGraphContract) => ({+ negativePrompt: addNode(graph, { id: 'negative_prompt', type: 'string' }),+ positivePrompt: addNode(graph, { id: 'positive_prompt', type: 'string' }),+ seed: addNode(graph, { id: 'seed', type: 'integer' }),+});++const addImageOutputNode = (graph: BackendGraphContract, type: string, outputIsIntermediate: boolean) =>+ addNode(graph, { id: 'canvas_output', is_intermediate: outputIsIntermediate, type, use_cache: false });++/**+ * The decode that turns the denoised latents into the output image: either the base's+ * ordinary VAE decode, or PiD's 4x super-resolution decode when PiD is on.+ *+ * Both branches wire `latents` (and the VAE where the node needs it) and return the+ * terminal `canvas_output` node, so callers attach metadata to the result either way.+ */+const addDecodeOutput = ({+ graph,+ settings,+ model,+ l2iType,+ l2iProps,+ denoise,+ positivePrompt,+ seed,+ vaeSource,+ vaeField = 'vae',+ outputIsIntermediate,+}: {+ graph: BackendGraphContract;+ settings: GenerateSettings;+ model: MainModelConfig;+ /** The base's ordinary VAE-decode node type, used when PiD is off. */+ l2iType: string;+ /** Extra props for the ordinary decode node; ignored by the PiD chain, which has its own. */+ l2iProps?: Record<string, unknown>;+ denoise: BackendInvocationContract;+ positivePrompt: BackendInvocationContract;+ seed: BackendInvocationContract;+ vaeSource?: BackendInvocationContract;+ vaeField?: string;+ outputIsIntermediate: boolean;+}): BackendInvocationContract => {+ if (shouldUsePidDecode(settings, model.base)) {+ return addPidDecode({+ base: model.base,+ denoise,+ graph,+ outputIsIntermediate,+ positivePrompt,+ seed,+ settings,+ vaeField,+ vaeSource,+ });+ }++ const output = addNode(graph, {+ id: 'canvas_output',+ is_intermediate: outputIsIntermediate,+ type: l2iType,+ use_cache: false,+ ...l2iProps,+ });++ if (vaeSource) {+ addEdge(graph, vaeSource, vaeField, output, 'vae');+ }+ addEdge(graph, denoise, 'latents', output, 'latents');++ return output;+};++/**+ * The width/height to denoise at. Identical to the requested size unless PiD is in+ * native mode, where the requested size is the 4x decode target and generation runs at+ * a quarter of it.+ */+const getDenoiseSize = (settings: GenerateSettings, model: MainModelConfig): { width: number; height: number } =>+ // Deliberately the model's OWN grid (the default `off` mode), not the PiD-scaled grid+ // the dimension fields present: requested / 4 must land on the model's grid.+ getPidDenoiseSize(settings, model.base, getGenerationDimensions(model).grid);++const buildSD3Graph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: GenerationProjectSettings+): BackendGraphContract => {+ const graph: BackendGraphContract = { edges: [], id: createId('sd3_graph'), nodes: {} };+ const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const modelLoader = addNode(graph, {+ clip_g_model: settings.clipGEmbedModel ?? undefined,+ clip_l_model: settings.clipLEmbedModel ?? undefined,+ id: 'model_loader',+ model,+ t5_encoder_model: settings.t5EncoderModel ?? undefined,+ type: 'sd3_model_loader',+ vae_model: settings.vae ?? undefined,+ });+ const posCond = addNode(graph, { id: 'pos_cond', type: 'sd3_text_encoder' });+ const negCond = addNode(graph, { id: 'neg_cond', type: 'sd3_text_encoder' });+ const sd3DenoiseSize = getDenoiseSize(settings, model);+ const denoise = addNode(graph, {+ cfg_scale: settings.cfgScale,+ denoising_end: 1,+ denoising_start: 0,+ height: sd3DenoiseSize.height,+ id: 'denoise_latents',+ steps: settings.steps,+ type: 'sd3_denoise',+ width: sd3DenoiseSize.width,+ });+ const output = addDecodeOutput({+ denoise,+ graph,+ l2iType: 'sd3_l2i',+ model,+ outputIsIntermediate,+ positivePrompt,+ seed,+ settings,+ vaeSource: modelLoader,+ });++ addEdge(graph, modelLoader, 'transformer', denoise, 'transformer');+ addEdge(graph, modelLoader, 'clip_l', posCond, 'clip_l');+ addEdge(graph, modelLoader, 'clip_l', negCond, 'clip_l');+ addEdge(graph, modelLoader, 'clip_g', posCond, 'clip_g');+ addEdge(graph, modelLoader, 'clip_g', negCond, 'clip_g');+ addEdge(graph, modelLoader, 't5_encoder', posCond, 't5_encoder');+ addEdge(graph, modelLoader, 't5_encoder', negCond, 't5_encoder');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');+ addEdge(graph, negCond, 'conditioning', denoise, 'negative_conditioning');+ addEdge(graph, seed, 'value', denoise, 'seed');+ addMetadata(graph, output, settings, model, 'sd3_txt2img', projectSettings, {+ scheduler: undefined,+ vae: settings.vae ?? undefined,+ ...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),+ });++ return graph;+};++const buildFluxGraph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: GenerationProjectSettings+): BackendGraphContract => {+ if (model.variant === 'dev_fill') {+ throw new Error('FLUX Fill models do not support text-to-image generation.');+ }++ const graph: BackendGraphContract = { edges: [], id: createId('flux_graph'), nodes: {} };+ const { positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const t5EncoderModel = requireComponent(settings.t5EncoderModel, 'T5 Encoder');+ const clipEmbedModel = requireComponent(settings.clipEmbedModel, 'CLIP Embed');+ const vaeModel = requireComponent(getCompatibleVae(settings, ['flux']), 'FLUX VAE');+ const scheduler = coerceSchedulerForGraph(model, settings.scheduler);+ const activeLoras = getActiveCompatibleLoras(settings, model);+ const modelLoader = addNode(graph, {+ clip_embed_model: clipEmbedModel,+ id: 'model_loader',+ model,+ t5_encoder_model: t5EncoderModel,+ type: 'flux_model_loader',+ vae_model: vaeModel,+ });+ const loraSource = activeLoras.length+ ? addTransformerLoraCollectionLoader(graph, activeLoras, 'flux_lora_collection_loader', modelLoader, [+ 'transformer',+ 'clip',+ 't5_encoder',+ ])+ : modelLoader;+ const posCond = addNode(graph, { id: 'pos_cond', type: 'flux_text_encoder' });+ const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });+ const denoiseSize = getDenoiseSize(settings, model);+ const denoise = addNode(graph, {+ denoising_end: 1,+ denoising_start: 0,+ guidance: settings.cfgScale,+ height: denoiseSize.height,+ id: 'denoise_latents',+ num_steps: settings.steps,+ scheduler,+ type: 'flux_denoise',+ width: denoiseSize.width,+ });+ const output = addDecodeOutput({+ denoise,+ graph,+ l2iType: 'flux_vae_decode',+ model,+ outputIsIntermediate,+ positivePrompt,+ seed,+ settings,+ vaeSource: modelLoader,+ });++ addEdge(graph, loraSource, 'clip', posCond, 'clip');+ addEdge(graph, loraSource, 't5_encoder', posCond, 't5_encoder');+ addEdge(graph, modelLoader, 'max_seq_len', posCond, 't5_max_seq_len');+ addEdge(graph, loraSource, 'transformer', denoise, 'transformer');+ addEdge(graph, modelLoader, 'vae', denoise, 'controlnet_vae');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');+ addEdge(graph, posCondCollect, 'collection', denoise, 'positive_text_conditioning');+ addEdge(graph, graph.nodes.seed, 'value', denoise, 'seed');+ if (model.name.toLowerCase().includes('kontext')) {+ addFluxKontextReferenceImages(graph, settings, denoise, 'flux_kontext_reference_image');+ }+ addIPAdapterReferenceImages(graph, settings, model, denoise);+ addFluxReduxReferenceImages(graph, settings, model, denoise);+ addMetadata(graph, output, settings, model, 'flux_txt2img', projectSettings, {+ clip_embed_model: clipEmbedModel,+ guidance: settings.cfgScale,+ scheduler,+ t5_encoder: t5EncoderModel,+ vae: vaeModel,+ ...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),+ });+ addReferenceImageMetadata(graph, output, settings);++ return graph;+};++const buildFlux2Graph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: GenerationProjectSettings+): BackendGraphContract => {++ const isDev = model.variant === 'dev';+ const sourceModel = getFlux2DiffusersComponentSource(model, settings);+ const hasBundledComponents = model.format === 'diffusers' || sourceModel;++ const mistralEncoderModel =++ settings.mistralEncoderModel && isFlux2MistralEncoder(settings.mistralEncoderModel)++ ? settings.mistralEncoderModel++ : null;+ const qwen3EncoderModel =- settings.qwen3EncoderModel && isFlux2Qwen3EncoderForModel(model)(settings.qwen3EncoderModel)++ !isDev && settings.qwen3EncoderModel && isFlux2Qwen3EncoderForModel(model)(settings.qwen3EncoderModel)+ ? settings.qwen3EncoderModel+ : null;++ const encoderModel = isDev ? mistralEncoderModel : qwen3EncoderModel;+ const vaeModel = getCompatibleVae(settings, ['flux2']);+- if (!hasBundledComponents && (!vaeModel || !qwen3EncoderModel)) {- throw new Error('FLUX.2 non-Diffusers models require a VAE and Qwen3 Encoder, or a Diffusers component source.');++ if (!hasBundledComponents && (!vaeModel || !encoderModel)) {++ throw new Error(++ `FLUX.2 non-Diffusers models require a VAE and ${isDev ? 'Mistral' : 'Qwen3'} Encoder, or a compatible Diffusers component source.`++ );+ }++ const graph: BackendGraphContract = { edges: [], id: createId('flux2_graph'), nodes: {} };+ const { positivePrompt } = addPromptAndSeedNodes(graph);+ const scheduler = coerceSchedulerForGraph(model, settings.scheduler);+ const activeLoras = getActiveCompatibleLoras(settings, model);- const modelLoader = addNode(graph, {- id: 'model_loader',- model,- qwen3_encoder_model: qwen3EncoderModel ?? undefined,- qwen3_source_model: sourceModel,- type: 'flux2_klein_model_loader',- vae_model: vaeModel ?? undefined,- });++ const modelLoader = addNode(++ graph,++ isDev++ ? {++ id: 'model_loader',++ mistral_encoder_model: mistralEncoderModel ?? undefined,++ mistral_source_model: sourceModel,++ model,++ type: 'flux2_dev_model_loader',++ vae_model: vaeModel ?? undefined,++ }++ : {++ id: 'model_loader',++ model,++ qwen3_encoder_model: qwen3EncoderModel ?? undefined,++ qwen3_source_model: sourceModel,++ type: 'flux2_klein_model_loader',++ vae_model: vaeModel ?? undefined,++ }++ );+ const loraSource = activeLoras.length- ? addTransformerLoraCollectionLoader(graph, activeLoras, 'flux2_klein_lora_collection_loader', modelLoader, [- 'transformer',- 'qwen3_encoder',- ])++ ? addTransformerLoraCollectionLoader(++ graph,++ activeLoras,++ isDev ? 'flux2_dev_lora_collection_loader' : 'flux2_klein_lora_collection_loader',++ modelLoader,++ ['transformer', isDev ? 'mistral_encoder' : 'qwen3_encoder']++ )+ : modelLoader;- const posCond = addNode(graph, { id: 'pos_cond', type: 'flux2_klein_text_encoder' });++ const posCond = addNode(graph, {++ id: 'pos_cond',++ type: isDev ? 'flux2_dev_text_encoder' : 'flux2_klein_text_encoder',++ });+ const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });+ const flux2DenoiseSize = getDenoiseSize(settings, model);+ const denoise = addNode(graph, {+ cfg_scale: 1,+ denoising_end: 1,+ denoising_start: 0,+ guidance: settings.cfgScale,+ height: flux2DenoiseSize.height,+ id: 'denoise_latents',+ num_steps: settings.steps,+ scheduler,+ type: 'flux2_denoise',+ width: flux2DenoiseSize.width,+ });+ const output = addDecodeOutput({+ denoise,+ graph,+ l2iType: 'flux2_vae_decode',+ model,+ outputIsIntermediate,+ positivePrompt,+ seed: graph.nodes.seed,+ settings,+ vaeSource: modelLoader,+ });+- addEdge(graph, loraSource, 'qwen3_encoder', posCond, 'qwen3_encoder');++ addEdge(++ graph,++ loraSource,++ isDev ? 'mistral_encoder' : 'qwen3_encoder',++ posCond,++ isDev ? 'mistral_encoder' : 'qwen3_encoder'++ );+ addEdge(graph, modelLoader, 'max_seq_len', posCond, 'max_seq_len');+ addEdge(graph, loraSource, 'transformer', denoise, 'transformer');+ addEdge(graph, modelLoader, 'vae', denoise, 'vae');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');+ addEdge(graph, posCondCollect, 'collection', denoise, 'positive_text_conditioning');+ addEdge(graph, graph.nodes.seed, 'value', denoise, 'seed');+ addFluxKontextReferenceImages(graph, settings, denoise, 'flux2_reference_image');+ addMetadata(graph, output, settings, model, 'flux2_txt2img', projectSettings, {- qwen3_encoder: qwen3EncoderModel ?? undefined,- qwen3_source: sourceModel,++ ...(isDev++ ? { mistral_encoder: mistralEncoderModel ?? undefined }++ : { qwen3_encoder: qwen3EncoderModel ?? undefined, qwen3_source: sourceModel }),+ scheduler,+ vae: vaeModel ?? undefined,+ ...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),+ });+ addReferenceImageMetadata(graph, output, settings);++ return graph;+};++const buildCogView4Graph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: GenerationProjectSettings+): BackendGraphContract => {+ const graph: BackendGraphContract = { edges: [], id: createId('cogview4_graph'), nodes: {} };+ const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const modelLoader = addNode(graph, { id: 'model_loader', model, type: 'cogview4_model_loader' });+ const posCond = addNode(graph, { id: 'pos_cond', type: 'cogview4_text_encoder' });+ const negCond = addNode(graph, { id: 'neg_cond', type: 'cogview4_text_encoder' });+ const denoise = addNode(graph, {+ cfg_scale: settings.cfgScale,+ height: settings.height,+ id: 'denoise_latents',+ steps: settings.steps,+ type: 'cogview4_denoise',+ width: settings.width,+ });+ const output = addImageOutputNode(graph, 'cogview4_l2i', outputIsIntermediate);++ addEdge(graph, modelLoader, 'transformer', denoise, 'transformer');+ addEdge(graph, modelLoader, 'glm_encoder', posCond, 'glm_encoder');+ addEdge(graph, modelLoader, 'glm_encoder', negCond, 'glm_encoder');+ addEdge(graph, modelLoader, 'vae', output, 'vae');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');+ addEdge(graph, negCond, 'conditioning', denoise, 'negative_conditioning');+ addEdge(graph, seed, 'value', denoise, 'seed');+ addEdge(graph, denoise, 'latents', output, 'latents');+ addMetadata(graph, output, settings, model, 'cogview4_txt2img', projectSettings, { scheduler: undefined });++ return graph;+};++const buildQwenImageGraph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: GenerationProjectSettings+): BackendGraphContract => {+ const sourceModel = getCompatibleComponentSource(settings, model);+ const hasBundledComponents = model.format === 'diffusers' || sourceModel;+ const vaeModel = getCompatibleVae(settings, ['qwen-image']);++ if (!hasBundledComponents && (!vaeModel || !settings.qwenVLEncoderModel)) {+ throw new Error(+ 'Qwen Image non-Diffusers models require a VAE and Qwen VL Encoder, or a Diffusers component source.'+ );+ }++ const graph: BackendGraphContract = { edges: [], id: createId('qwen_image_graph'), nodes: {} };+ const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const activeLoras = getActiveCompatibleLoras(settings, model);+ const useCfg = settings.cfgScale > 1;+ const modelLoader = addNode(graph, {+ component_source: sourceModel,+ id: 'model_loader',+ model,+ qwen_vl_encoder_model: settings.qwenVLEncoderModel ?? undefined,+ type: 'qwen_image_model_loader',+ vae_model: vaeModel ?? undefined,+ });+ const loraSource = activeLoras.length+ ? addTransformerLoraCollectionLoader(graph, activeLoras, 'qwen_image_lora_collection_loader', modelLoader, [+ 'transformer',+ ])+ : modelLoader;+ const posCond = addNode(graph, { id: 'pos_cond', type: 'qwen_image_text_encoder' });+ const negCond = useCfg ? addNode(graph, { id: 'neg_cond', type: 'qwen_image_text_encoder' }) : null;+ const qwenDenoiseSize = getDenoiseSize(settings, model);+ const denoise = addNode(graph, {+ cfg_scale: settings.cfgScale,+ height: qwenDenoiseSize.height,+ id: 'denoise_latents',+ steps: settings.steps,+ type: 'qwen_image_denoise',+ width: qwenDenoiseSize.width,+ });+ const output = addDecodeOutput({+ denoise,+ graph,+ l2iType: 'qwen_image_l2i',+ model,+ outputIsIntermediate,+ positivePrompt,+ seed,+ settings,+ vaeSource: modelLoader,+ });++ addEdge(graph, loraSource, 'transformer', denoise, 'transformer');+ addEdge(graph, modelLoader, 'qwen_vl_encoder', posCond, 'qwen_vl_encoder');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');++ if (negCond) {+ addEdge(graph, modelLoader, 'qwen_vl_encoder', negCond, 'qwen_vl_encoder');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ addEdge(graph, negCond, 'conditioning', denoise, 'negative_conditioning');+ }++ addEdge(graph, seed, 'value', denoise, 'seed');+ const qwenReferenceImages =+ model.variant === 'edit' ? getEnabledReferenceImages(settings, 'qwen_image_reference_image') : [];++ if (qwenReferenceImages.length > 0) {+ let prevCollect: BackendInvocationContract | null = null;++ for (const { config } of qwenReferenceImages) {+ if (!config.image) {+ continue;+ }++ const imageNode = addNode(graph, {+ id: createId('qwen_ref_img'),+ image: toImageField(config.image),+ type: 'image',+ });+ const collectNode = addNode(graph, { id: createId('qwen_ref_img_collect'), type: 'collect' });++ addEdge(graph, imageNode, 'image', collectNode, 'item');+ if (prevCollect) {+ addEdge(graph, prevCollect, 'collection', collectNode, 'collection');+ }+ prevCollect = collectNode;+ }++ if (prevCollect) {+ addEdge(graph, prevCollect, 'collection', posCond, 'reference_images');+ }++ const firstImage = qwenReferenceImages[0]?.config.image;+ if (firstImage) {+ const refI2l = addNode(graph, { id: createId('qwen_ref_i2l'), type: 'qwen_image_i2l' });+ const refImageNode = addNode(graph, {+ id: createId('qwen_ref_img_for_vae'),+ image: toImageField(firstImage),+ type: 'image',+ });++ addEdge(graph, refImageNode, 'image', refI2l, 'image');+ addEdge(graph, modelLoader, 'vae', refI2l, 'vae');+ addEdge(graph, refI2l, 'latents', denoise, 'reference_latents');+ }+ }+ addMetadata(graph, output, settings, model, 'qwen_image_txt2img', projectSettings, {+ qwen_image_component_source: sourceModel,+ qwen_image_qwen_vl_encoder: settings.qwenVLEncoderModel ?? undefined,+ qwen_image_vae: vaeModel ?? undefined,+ scheduler: undefined,+ ...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),+ });+ addReferenceImageMetadata(graph, output, settings);++ return graph;+};++const buildZImageGraph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: GenerationProjectSettings+): BackendGraphContract => {+ const sourceModel = getDiffusersSource(settings, model);+ const qwen3EncoderModel =+ settings.qwen3EncoderModel && isNonAnimaQwen3Encoder(settings.qwen3EncoderModel)+ ? settings.qwen3EncoderModel+ : null;+ const vaeModel = getCompatibleVae(settings, ['flux']);++ if (!sourceModel && (!vaeModel || !qwen3EncoderModel)) {+ throw new Error('Z-Image models require a VAE and Qwen3 Encoder, or a Diffusers component source.');+ }++ const graph: BackendGraphContract = { edges: [], id: createId('z_image_graph'), nodes: {} };+ const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const scheduler = coerceSchedulerForGraph(model, settings.scheduler);+ const activeLoras = getActiveCompatibleLoras(settings, model);+ const useCfg = settings.cfgScale > 1;+ const modelLoader = addNode(graph, {+ id: 'model_loader',+ model,+ qwen3_encoder_model: qwen3EncoderModel ?? undefined,+ qwen3_source_model: sourceModel,+ type: 'z_image_model_loader',+ vae_model: vaeModel ?? undefined,+ });+ const loraSource = activeLoras.length+ ? addTransformerLoraCollectionLoader(graph, activeLoras, 'z_image_lora_collection_loader', modelLoader, [+ 'transformer',+ 'qwen3_encoder',+ ])+ : modelLoader;+ const posCond = addNode(graph, { id: 'pos_cond', type: 'z_image_text_encoder' });+ const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });+ const negCond = useCfg ? addNode(graph, { id: 'neg_cond', type: 'z_image_text_encoder' }) : null;+ const negCondCollect = useCfg ? addNode(graph, { id: 'neg_cond_collect', type: 'collect' }) : null;+ const zImageDenoiseSize = getDenoiseSize(settings, model);+ const denoise = addNode(graph, {+ denoising_end: 1,+ denoising_start: 0,+ guidance_scale: settings.cfgScale,+ height: zImageDenoiseSize.height,+ id: 'denoise_latents',+ scheduler,+ steps: settings.steps,+ type: 'z_image_denoise',+ width: zImageDenoiseSize.width,+ });+ const output = addDecodeOutput({+ denoise,+ graph,+ l2iType: 'z_image_l2i',+ model,+ outputIsIntermediate,+ positivePrompt,+ seed,+ settings,+ vaeSource: modelLoader,+ });++ addEdge(graph, loraSource, 'transformer', denoise, 'transformer');+ addEdge(graph, loraSource, 'qwen3_encoder', posCond, 'qwen3_encoder');+ addEdge(graph, modelLoader, 'vae', denoise, 'vae');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');+ addEdge(graph, posCondCollect, 'collection', denoise, 'positive_conditioning');++ if (negCond && negCondCollect) {+ addEdge(graph, loraSource, 'qwen3_encoder', negCond, 'qwen3_encoder');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ addEdge(graph, negCond, 'conditioning', negCondCollect, 'item');+ addEdge(graph, negCondCollect, 'collection', denoise, 'negative_conditioning');+ }++ addEdge(graph, seed, 'value', denoise, 'seed');+ addMetadata(graph, output, settings, model, 'z_image_txt2img', projectSettings, {+ qwen3_encoder: qwen3EncoderModel ?? undefined,+ qwen3_source: sourceModel,+ scheduler,+ vae: vaeModel ?? undefined,+ ...(shouldUsePidDecode(settings, model.base) ? getPidMetadata(settings) : {}),+ });++ return graph;+};++const buildAnimaGraph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: GenerationProjectSettings+): BackendGraphContract => {+ const vaeModel = requireComponent(settings.vae && isAnimaVae(settings.vae) ? settings.vae : null, 'Anima VAE');+ const qwen3EncoderModel = requireComponent(+ settings.qwen3EncoderModel && isAnimaQwen3Encoder(settings.qwen3EncoderModel) ? settings.qwen3EncoderModel : null,+ 'Qwen3 Encoder'+ );+ const graph: BackendGraphContract = { edges: [], id: createId('anima_graph'), nodes: {} };+ const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const scheduler = coerceSchedulerForGraph(model, settings.scheduler);+ const activeLoras = getActiveCompatibleLoras(settings, model);+ const useCfg = settings.cfgScale > 1;+ const modelLoader = addNode(graph, {+ id: 'model_loader',+ model,+ qwen3_encoder_model: qwen3EncoderModel,+ type: 'anima_model_loader',+ vae_model: vaeModel,+ });+ const loraSource = activeLoras.length+ ? addTransformerLoraCollectionLoader(graph, activeLoras, 'anima_lora_collection_loader', modelLoader, [+ 'transformer',+ 'qwen3_encoder',+ ])+ : modelLoader;+ const posCond = addNode(graph, { id: 'pos_cond', type: 'anima_text_encoder' });+ const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });+ const negCond = useCfg ? addNode(graph, { id: 'neg_cond', type: 'anima_text_encoder' }) : null;+ const negCondCollect = useCfg ? addNode(graph, { id: 'neg_cond_collect', type: 'collect' }) : null;+ const denoise = addNode(graph, {+ denoising_end: 1,+ denoising_start: 0,+ guidance_scale: settings.cfgScale,+ height: settings.height,+ id: 'denoise_latents',+ scheduler,+ steps: settings.steps,+ type: 'anima_denoise',+ width: settings.width,+ });+ const output = addImageOutputNode(graph, 'anima_l2i', outputIsIntermediate);++ addEdge(graph, loraSource, 'transformer', denoise, 'transformer');+ addEdge(graph, loraSource, 'qwen3_encoder', posCond, 'qwen3_encoder');+ addEdge(graph, modelLoader, 'vae', output, 'vae');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', posCondCollect, 'item');+ addEdge(graph, posCondCollect, 'collection', denoise, 'positive_conditioning');++ if (negCond && negCondCollect) {+ addEdge(graph, loraSource, 'qwen3_encoder', negCond, 'qwen3_encoder');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ addEdge(graph, negCond, 'conditioning', negCondCollect, 'item');+ addEdge(graph, negCondCollect, 'collection', denoise, 'negative_conditioning');+ }++ addEdge(graph, seed, 'value', denoise, 'seed');+ addEdge(graph, denoise, 'latents', output, 'latents');+ addMetadata(graph, output, settings, model, 'anima_txt2img', projectSettings, {+ qwen3_encoder: qwen3EncoderModel,+ scheduler,+ vae: vaeModel,+ });++ return graph;+};++const buildKrea2Graph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: GenerationProjectSettings+): BackendGraphContract => {+ // Krea-2 has no component-source concept: a non-diffusers transformer (single-file checkpoint+ // or GGUF) bundles neither VAE nor encoder, so both must be selected. A diffusers model+ // carries them, and the loader extracts them when these are omitted.+ const isDiffusers = model.format === 'diffusers';+ // Same base set as the picker (`isKrea2Vae`) and the backend loader: a Qwen-Image VAE+ // installed under the `anima` base is still the VAE Krea-2 wants. Narrowing it here would+ // silently drop a VAE the user had legitimately selected.+ const vaeModel = settings.vae && isKrea2Vae(settings.vae) ? settings.vae : null;+ const qwen3VlEncoderModel = settings.qwen3VLEncoderModel;++ if (!isDiffusers) {+ requireComponent(vaeModel, 'Krea-2 VAE');+ requireComponent(qwen3VlEncoderModel, 'Qwen3-VL Encoder');+ }++ const graph: BackendGraphContract = { edges: [], id: createId('krea2_graph'), nodes: {} };+ const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const activeLoras = getActiveCompatibleLoras(settings, model);+ // Krea-2 accepts negative conditioning only with CFG on; Krea-2-Turbo defaults to CFG off.+ const useCfg = settings.cfgScale > 1;+ const modelLoader = addNode(graph, {+ id: 'model_loader',+ model,+ qwen3_vl_encoder_model: qwen3VlEncoderModel ?? undefined,+ type: 'krea2_model_loader',+ vae_model: vaeModel ?? undefined,+ });+ const loraSource = activeLoras.length+ ? addTransformerLoraCollectionLoader(graph, activeLoras, 'krea2_lora_collection_loader', modelLoader, [+ 'transformer',+ 'qwen3_vl_encoder',+ ])+ : modelLoader;+ const posCond = addNode(graph, { id: 'pos_cond', type: 'krea2_text_encoder' });+ const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });+ const negCond = useCfg ? addNode(graph, { id: 'neg_cond', type: 'krea2_text_encoder' }) : null;+ const denoise = addNode(graph, {+ cfg_scale: settings.cfgScale,+ height: settings.height,+ id: 'denoise_latents',+ steps: settings.steps,+ type: 'krea2_denoise',+ width: settings.width,+ });+ // Krea-2 decodes with the Qwen-Image VAE, so it reuses that family's latents-to-image node.+ const output = addImageOutputNode(graph, 'qwen_image_l2i', outputIsIntermediate);++ addEdge(graph, loraSource, 'transformer', denoise, 'transformer');+ addEdge(graph, loraSource, 'qwen3_vl_encoder', posCond, 'qwen3_vl_encoder');+ addEdge(graph, modelLoader, 'vae', output, 'vae');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');++ const positiveConditioningSource = addKrea2ConditioningEnhancers({+ conditioning: posCond,+ graph,+ idPrefix: 'krea2',+ seed,+ settings,+ });+ addEdge(graph, positiveConditioningSource, 'conditioning', posCondCollect, 'item');+ addEdge(graph, posCondCollect, 'collection', denoise, 'positive_conditioning');++ if (negCond) {+ addEdge(graph, loraSource, 'qwen3_vl_encoder', negCond, 'qwen3_vl_encoder');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ addEdge(graph, negCond, 'conditioning', denoise, 'negative_conditioning');+ }++ addEdge(graph, seed, 'value', denoise, 'seed');+ addEdge(graph, denoise, 'latents', output, 'latents');+ addMetadata(graph, output, settings, model, 'krea2_txt2img', projectSettings, {+ krea2_rebalance_enabled: settings.krea2RebalanceEnabled,+ krea2_rebalance_multiplier: settings.krea2RebalanceMultiplier,+ krea2_rebalance_weights: settings.krea2RebalanceWeights,+ krea2_seed_variance_enabled: settings.krea2SeedVarianceEnabled,+ krea2_seed_variance_randomize_percent: settings.krea2SeedVarianceRandomizePercent,+ krea2_seed_variance_strength: settings.krea2SeedVarianceStrength,+ qwen3_vl_encoder: qwen3VlEncoderModel ?? undefined,+ vae: vaeModel ?? undefined,+ });++ return graph;+};++const buildIdeogram4Graph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: GenerationProjectSettings+): BackendGraphContract => {+ const graph: BackendGraphContract = { edges: [], id: createId('ideogram4_graph'), nodes: {} };+ // Ideogram 4 is positive-only: there is no negative conditioning input on its denoise node.+ const { positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const modelLoader = addNode(graph, { id: 'model_loader', model, type: 'ideogram4_model_loader' });+ // The caption builder turns the prompt (plus optional colour terms) into Ideogram's own+ // caption format before encoding.+ const captionBuilder = addNode(graph, {+ color_palette: settings.ideogram4ColorPalette,+ id: 'caption_builder',+ type: 'ideogram4_caption_builder',+ });+ const posCond = addNode(graph, { id: 'pos_cond', type: 'ideogram4_text_encoder' });+ const denoise = addNode(graph, {+ height: settings.height,+ id: 'denoise_latents',+ // Steps, guidance and mu are preset-derived unless explicitly overridden — sending null+ // would override the preset with nothing, so unset values are omitted entirely.+ ...(settings.ideogram4Steps === null ? {} : { steps: settings.ideogram4Steps }),+ ...(settings.ideogram4GuidanceScale === null ? {} : { guidance_scale: settings.ideogram4GuidanceScale }),+ ...(settings.ideogram4Mu === null ? {} : { mu: settings.ideogram4Mu }),+ sampler_preset: settings.ideogram4SamplerPreset,+ type: 'ideogram4_denoise',+ width: settings.width,+ });+ const output = addImageOutputNode(graph, 'ideogram4_l2i', outputIsIntermediate);++ addEdge(graph, modelLoader, 'transformer', denoise, 'transformer');+ addEdge(graph, modelLoader, 'qwen3_encoder', posCond, 'qwen3_encoder');+ addEdge(graph, modelLoader, 'vae', output, 'vae');+ addEdge(graph, positivePrompt, 'value', captionBuilder, 'prompt');+ addEdge(graph, captionBuilder, 'value', posCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');+ addEdge(graph, seed, 'value', denoise, 'seed');+ addEdge(graph, denoise, 'latents', output, 'latents');+ addMetadata(graph, output, settings, model, 'ideogram4_txt2img', projectSettings, {+ ideogram4_color_palette: settings.ideogram4ColorPalette,+ ideogram4_guidance_scale: settings.ideogram4GuidanceScale ?? undefined,+ ideogram4_mu: settings.ideogram4Mu ?? undefined,+ ideogram4_sampler_preset: settings.ideogram4SamplerPreset,+ ideogram4_steps: settings.ideogram4Steps ?? undefined,+ });++ return graph;+};++const buildWanGraph = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: GenerationProjectSettings+): BackendGraphContract => {+ // A GGUF Wan main carries only the transformer, so the VAE and UMT5-XXL encoder come from+ // standalone models or a Diffusers component source.+ const sourceModel = getDiffusersSource(settings, model);+ const vaeModel = getCompatibleVae(settings, ['wan']);+ const wanT5EncoderModel = settings.wanT5EncoderModel;++ if (!sourceModel && (!vaeModel || !wanT5EncoderModel)) {+ throw new Error('Wan models require a VAE and Wan T5 Encoder, or a Diffusers component source.');+ }++ const graph: BackendGraphContract = { edges: [], id: createId('wan_graph'), nodes: {} };+ const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const activeLoras = getActiveCompatibleLoras(settings, model);+ const modelLoader = addNode(graph, {+ component_source: sourceModel,+ id: 'model_loader',+ model,+ // The second A14B expert. Omitted, the high-noise expert covers the whole schedule.+ transformer_low_noise_model: settings.wanLowNoiseModel ?? undefined,+ type: 'wan_model_loader',+ vae_model: vaeModel ?? undefined,+ wan_t5_encoder_model: wanT5EncoderModel ?? undefined,+ });+ // Wan LoRAs patch only the transformer; the text encoder is untouched.+ const loraSource = activeLoras.length+ ? addTransformerLoraCollectionLoader(graph, activeLoras, 'wan_lora_collection_loader', modelLoader, ['transformer'])+ : modelLoader;+ const posCond = addNode(graph, { id: 'pos_cond', type: 'wan_text_encoder' });+ const negCond = addNode(graph, { id: 'neg_cond', type: 'wan_text_encoder' });+ const denoise = addNode(graph, {+ guidance_scale: settings.cfgScale,+ // Null lets the backend reuse guidance_scale for the low-noise half of the schedule.+ ...(settings.wanGuidanceScaleLowNoise === null+ ? {}+ : { guidance_scale_low_noise: settings.wanGuidanceScaleLowNoise }),+ height: settings.height,+ id: 'denoise_latents',+ steps: settings.steps,+ type: 'wan_denoise',+ width: settings.width,+ });+ // Single-frame image output, not video: `wan_l2i` rather than `wan_l2v`.+ const output = addImageOutputNode(graph, 'wan_l2i', outputIsIntermediate);++ addEdge(graph, loraSource, 'transformer', denoise, 'transformer');+ addEdge(graph, modelLoader, 'wan_t5_encoder', posCond, 'wan_t5_encoder');+ addEdge(graph, modelLoader, 'wan_t5_encoder', negCond, 'wan_t5_encoder');+ addEdge(graph, modelLoader, 'vae', output, 'vae');+ addEdge(graph, positivePrompt, 'value', posCond, 'prompt');+ addEdge(graph, negativePrompt, 'value', negCond, 'prompt');+ addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');+ addEdge(graph, negCond, 'conditioning', denoise, 'negative_conditioning');+ addEdge(graph, seed, 'value', denoise, 'seed');+ addEdge(graph, denoise, 'latents', output, 'latents');+ addMetadata(graph, output, settings, model, 'wan_txt2img', projectSettings, {+ guidance_scale_low_noise: settings.wanGuidanceScaleLowNoise ?? undefined,+ transformer_low_noise: settings.wanLowNoiseModel ?? undefined,+ vae: vaeModel ?? undefined,+ wan_component_source: sourceModel,+ wan_t5_encoder: wanT5EncoderModel ?? undefined,+ });++ return graph;+};++const buildExternalGraph = (+ settings: GenerateSettings,+ model: GenerateModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: GenerationProjectSettings+): BackendGraphContract => {+ if (model.type !== 'external_image_generator') {+ throw new Error('Selected model is not an external image generator.');+ }++ if (model.capabilities?.modes && !model.capabilities.modes.includes('txt2img')) {+ throw new Error(`${model.name} does not support text-to-image generation.`);+ }++ const providerId = typeof model.provider_id === 'string' ? model.provider_id : '';+ const nodeType = getExternalProviderNodeType(providerId);++ if (!nodeType) {+ throw new Error(`No invocation node registered for external provider '${providerId}'.`);+ }++ const graph: BackendGraphContract = { edges: [], id: createId('external_graph'), nodes: {} };+ const { negativePrompt, positivePrompt, seed } = addPromptAndSeedNodes(graph);+ const output = addNode(graph, {+ height: settings.height,+ id: 'canvas_output',+ image_size: null,+ is_intermediate: outputIsIntermediate,+ mode: 'txt2img',+ model,+ num_images: 1,+ type: nodeType,+ use_cache: false,+ width: settings.width,+ });++ addEdge(graph, positivePrompt, 'value', output, 'prompt');+ if (model.capabilities?.supports_negative_prompt === true) {+ addEdge(graph, negativePrompt, 'value', output, 'negative_prompt');+ }++ if (model.capabilities?.supports_seed === true) {+ addEdge(graph, seed, 'value', output, 'seed');+ }+ if (model.capabilities?.supports_reference_images === true) {+ const referenceImages = getEnabledReferenceImages(settings, 'external_reference_image')+ .map((referenceImage) => referenceImage.config.image)+ .filter((image): image is GenerateReferenceImageAsset => image !== null)+ .map(toImageField);++ if (referenceImages.length > 0) {+ (output as Record<string, unknown>).reference_images = referenceImages;+ }+ }+ addMetadata(graph, output, settings, model, null, projectSettings, { scheduler: undefined });+ addReferenceImageMetadata(graph, output, settings);++ return graph;+};++type GenerateGraphBuilder = (+ settings: GenerateSettings,+ model: MainModelConfig,+ outputIsIntermediate: boolean,+ projectSettings: GenerationProjectSettings+) => BackendGraphContract;++export const GRAPH_BUILDERS = {+ 'sd-1': buildSDGraph,+ 'sd-2': buildSDGraph,+ sdxl: buildSDGraph,+ 'sd-3': buildSD3Graph,+ flux: buildFluxGraph,+ flux2: buildFlux2Graph,+ cogview4: buildCogView4Graph,+ 'qwen-image': buildQwenImageGraph,+ 'z-image': buildZImageGraph,+ 'ideogram-4': buildIdeogram4Graph,+ 'krea-2': buildKrea2Graph,+ anima: buildAnimaGraph,+ wan: buildWanGraph,+} satisfies Record<SupportedGenerateBase, GenerateGraphBuilder>;++export const compileGenerateGraph = (+ settings: GenerateSettings,+ model: GenerateModelConfig,+ destination: ResultDestination,+ projectSettings: GenerationProjectSettings+): CompiledGenerateGraph => {+ const validationReasons = getGenerationValidationReasons(model, settings);++ if (validationReasons.length > 0) {+ throw new Error(validationReasons[0]);+ }++ const outputIsIntermediate = destination === 'canvas';+ const backendGraph = (() => {+ if (model.type === 'external_image_generator') {+ return buildExternalGraph(settings, model, outputIsIntermediate, projectSettings);+ }++ const builder = GRAPH_BUILDERS[model.base as SupportedGenerateBase];++ if (!builder) {+ const dimensionGrid = getGenerationDimensions(model).grid;++ throw new Error(`${model.name} dimensions must be multiples of ${dimensionGrid}.`);+ }++ return builder(settings, model, outputIsIntermediate, projectSettings);+ })();++ return {+ backendGraph,+ graph: toGraphContract(backendGraph, `${model.name} txt2img`),+ negativePromptNodeId: 'negative_prompt',+ positivePromptNodeId: 'positive_prompt',+ seedNodeId: 'seed',+ };+};++export const resolveGenerateSeed = (settings: GenerateSettings): number =>+ 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 --cc invokeai/frontend/webv2/src/features/generation/core/settings.test.tsindex b0f4e27f41,0000000000..6b79407de2mode 100644,000000..100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts@@@ -1,411 -1,0 +1,427 @@@+import { describe, expect, it } from 'vitest';++import type {+ ComponentModelConfig,+ GenerateLora,+ GenerateWidgetValues,+ LoraModelConfig,+ MainModelConfig,+ VaeModelConfig,+} from './types';++import { getGenerationDimensions } from './baseGenerationPolicies';+import {+ calculateNewSize,+ clampDimension,+ cloneGenerateWidgetValues,+ deriveAspectRatioId,+ getDefaultLoraWeight,+ getModelDefaultVae,+ hasModelDefaultVae,+ isLoraCompatibleWithModel,+ isGenerateSettings,+ normalizeGenerateSettings,+ syncGenerateWidgetValuesWithModels,+ syncGenerateLorasWithModels,+} 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('enforces template view mode only when a valid template remains', () => {+ const validTemplate = {+ id: 'template-1',+ name: 'Cinematic',+ negativePrompt: '',+ positivePrompt: '{prompt}, cinematic',+ };++ expect(+ normalizeGenerateSettings({ ...legacyStoredValues, promptTemplate: null, promptTemplateViewMode: true })+ ?.promptTemplateViewMode+ ).toBe(false);+ expect(+ normalizeGenerateSettings({+ ...legacyStoredValues,+ promptTemplate: { id: '', name: 'Broken' },+ promptTemplateViewMode: true,+ })?.promptTemplateViewMode+ ).toBe(false);+ expect(+ normalizeGenerateSettings({ ...legacyStoredValues, promptTemplate: validTemplate, promptTemplateViewMode: true })+ ?.promptTemplateViewMode+ ).toBe(true);+ expect(isGenerateSettings({ ...legacyStoredValues, promptTemplate: null, promptTemplateViewMode: true })).toBe(+ false+ );+ });++ it('normalizes persisted reference images and drops invalid entries', () => {+ const normalized = normalizeGenerateSettings({+ ...legacyStoredValues,+ referenceImages: [+ {+ id: 'ref-1',+ isEnabled: true,+ config: {+ type: 'qwen_image_reference_image',+ image: {+ height: 768,+ imageName: 'reference.png',+ imageUrl: '/api/v1/images/i/reference.png/full',+ queuedAt: '2026-01-01T00:00:00.000Z',+ sourceQueueItemId: 'backend-gallery',+ thumbnailUrl: '/api/v1/images/i/reference.png/thumbnail',+ width: 512,+ },+ },+ },+ { id: 'broken', isEnabled: true, config: { type: 'qwen_image_reference_image', image: { imageName: 3 } } },+ ],+ });++ expect(normalized?.referenceImages).toHaveLength(1);+ expect(normalized?.referenceImages[0]).toMatchObject({+ id: 'ref-1',+ isEnabled: true,+ config: {+ type: 'qwen_image_reference_image',+ image: { original: { image: { height: 768, image_name: 'reference.png', width: 512 } } },+ },+ });+ expect(normalized && isGenerateSettings(normalized)).toBe(true);+ expect(+ isGenerateSettings({+ ...normalized,+ referenceImages: [+ {+ ...normalized?.referenceImages[0],+ config: {+ ...normalized?.referenceImages[0]?.config,+ image: {+ height: 768,+ imageName: 'reference.png',+ imageUrl: '/full',+ queuedAt: 'now',+ sourceQueueItemId: 'queue',+ thumbnailUrl: '/thumbnail',+ width: 512,+ },+ },+ },+ ],+ })+ ).toBe(false);+ });++ it('keeps more than five valid persisted reference images for provider-specific caps', () => {+ const referenceImages = Array.from({ length: 6 }, (_, index) => ({+ id: `ref-${index}`,+ isEnabled: true,+ config: {+ type: 'external_reference_image',+ image: {+ height: 768,+ imageName: `reference-${index}.png`,+ imageUrl: `/api/v1/images/i/reference-${index}.png/full`,+ queuedAt: '2026-01-01T00:00:00.000Z',+ sourceQueueItemId: 'backend-gallery',+ thumbnailUrl: `/api/v1/images/i/reference-${index}.png/thumbnail`,+ width: 512,+ },+ },+ }));++ const normalized = normalizeGenerateSettings({ ...legacyStoredValues, referenceImages });++ expect(normalized?.referenceImages).toHaveLength(6);+ });++ 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?.colorCompensation).toBe(false);+ expect(normalized?.hiDiffusionEnabled).toBe(false);+ expect(normalized?.hiDiffusionRauNetEnabled).toBe(true);+ expect(normalized?.hiDiffusionWindowAttentionEnabled).toBe(true);+ expect(normalized?.hiDiffusionT1Ratio).toBe(0.4);+ expect(normalized?.hiDiffusionT2Ratio).toBe(0);+ expect(normalized?.loras).toEqual([]);+ expect(normalized?.negativePromptEnabled).toBe(true);+ expect(normalized?.negativePromptHeightPx).toBe(56);+ expect(normalized?.positivePromptHeightPx).toBe(96);+ 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('defaults an omitted batch count to one', () => {+ const { batchCount, ...storedValues } = legacyStoredValues;++ expect(batchCount).toBe(2);+ expect(normalizeGenerateSettings(storedValues)?.batchCount).toBe(1);+ });++ it('drops malformed values for the newer fields back to defaults', () => {+ const normalized = normalizeGenerateSettings({+ ...legacyStoredValues,+ aspectRatioId: 'bogus',+ hiDiffusionEnabled: 'yes',+ hiDiffusionRauNetEnabled: null,+ hiDiffusionT1Ratio: Number.NaN,+ hiDiffusionT2Ratio: 'late',+ hiDiffusionWindowAttentionEnabled: 1,+ loras: [{ isEnabled: true, model: { key: 'k', name: 'n', type: 'main' }, weight: 1 }],+ vae: { key: 'k', name: 'n', type: 'main' },+ vaePrecision: 'fp64',+ });++ expect(normalized?.aspectRatioId).toBe('2:3');+ expect(normalized?.hiDiffusionEnabled).toBe(false);+ expect(normalized?.hiDiffusionRauNetEnabled).toBe(true);+ expect(normalized?.hiDiffusionWindowAttentionEnabled).toBe(true);+ expect(normalized?.hiDiffusionT1Ratio).toBe(0.4);+ expect(normalized?.hiDiffusionT2Ratio).toBe(0);+ expect(normalized?.loras).toEqual([]);+ expect(normalized?.vae).toBeNull();+ expect(normalized?.vaePrecision).toBe('fp32');+ });++ it('drops malformed persisted model identifiers missing a base', () => {+ const normalized = normalizeGenerateSettings({+ ...legacyStoredValues,+ loras: [{ isEnabled: true, model: { key: 'lora', name: 'LoRA', type: 'lora' }, weight: 1 }],++ mistralEncoderModel: { key: 'mistral', name: 'Mistral', type: 'mistral_encoder' },+ qwen3EncoderModel: { key: 'qwen3', name: 'Qwen3', type: 'qwen3_encoder' },+ vae: { key: 'vae', name: 'VAE', type: 'vae' },+ });++ expect(normalized?.loras).toEqual([]);++ expect(normalized?.mistralEncoderModel).toBeNull();+ expect(normalized?.qwen3EncoderModel).toBeNull();+ expect(normalized?.vae).toBeNull();+ });++ it('is idempotent across persisted-value variations', () => {+ for (let index = 0; index < 128; index += 1) {+ const first = normalizeGenerateSettings({+ ...legacyStoredValues,+ aspectRatioId: index % 3 === 0 ? 'bogus' : index % 2 === 0 ? '1:1' : 'Free',+ batchCount: (index % 20) + 1,+ cfgScale: (index % 30) / 2,+ height: 64 + ((index * 8) % 1984),+ negativePromptEnabled: index % 2 === 0,+ seed: index * 7919,+ shouldRandomizeSeed: index % 5 === 0,+ width: 64 + ((index * 16) % 1984),+ });++ expect(first).not.toBeNull();+ expect(normalizeGenerateSettings(first)).toEqual(first);+ }+ });+});++describe('Generate widget value snapshots', () => {+ const model: MainModelConfig = { base: 'flux2', key: 'model', name: 'Old Model', type: 'main' };+ const component: ComponentModelConfig = { base: 'any', key: 'qwen3', name: 'Old Qwen3', type: 'qwen3_encoder' };++ const mistral: ComponentModelConfig = {++ base: 'any',++ key: 'mistral',++ name: 'Old Mistral',++ type: 'mistral_encoder',++ };+ const vae: VaeModelConfig = { base: 'flux2', key: 'vae', name: 'Old VAE', type: 'vae' };+ const lora: LoraModelConfig = { base: 'flux2', key: 'lora', name: 'Old LoRA', type: 'lora' };+ const values: GenerateWidgetValues = {+ ...(normalizeGenerateSettings(legacyStoredValues) as NonNullable<ReturnType<typeof normalizeGenerateSettings>>),+ clipEmbedModel: { base: 'any', key: 'clip', name: 'CLIP', type: 'clip_embed' },+ componentSourceModel: model,+ loras: [{ isEnabled: true, model: lora, weight: 0.5 }],++ mistralEncoderModel: mistral,+ model,+ modelKey: model.key,+ qwen3EncoderModel: component,+ vae,+ };++ it('deep-clones every nested model selection', () => {+ const clone = cloneGenerateWidgetValues(values);++ expect(clone).toEqual(values);+ expect(clone.model).not.toBe(values.model);+ expect(clone.componentSourceModel).not.toBe(values.componentSourceModel);++ expect(clone.mistralEncoderModel).not.toBe(values.mistralEncoderModel);+ expect(clone.qwen3EncoderModel).not.toBe(values.qwen3EncoderModel);+ expect(clone.vae).not.toBe(values.vae);+ expect(clone.loras[0]).not.toBe(values.loras[0]);+ expect(clone.loras[0]?.model).not.toBe(values.loras[0]?.model);+ });++ it('uses current backend model records for same-key stored selections', () => {+ const currentModel = { ...model, format: 'diffusers' as const, name: 'Current Model' };+ const currentComponent = { ...component, name: 'Current Qwen3' };++ const currentMistral = { ...mistral, name: 'Current Mistral' };+ const currentVae = { ...vae, name: 'Current VAE' };+ const currentLora = { ...lora, name: 'Current LoRA' };+ const synced = syncGenerateWidgetValuesWithModels(values, [+ currentModel,+ currentComponent,++ currentMistral,+ currentVae,+ currentLora,+ ]);++ expect(synced.model).toBe(currentModel);+ expect(synced.componentSourceModel).toBe(currentModel);++ expect(synced.mistralEncoderModel).toBe(currentMistral);+ expect(synced.qwen3EncoderModel).toBe(currentComponent);+ expect(synced.vae).toBe(currentVae);+ expect(synced.loras[0]?.model).toBe(currentLora);+ });++ it('does not resync cloned current model snapshots by reference alone', () => {+ const currentModel = { ...model, format: 'diffusers' as const, name: 'Current Model' };+ const currentComponent = { ...component, name: 'Current Qwen3' };++ const currentMistral = { ...mistral, name: 'Current Mistral' };+ const currentVae = { ...vae, name: 'Current VAE' };+ const currentLora = { ...lora, name: 'Current LoRA' };+ const currentValues = {+ ...values,+ componentSourceModel: currentModel,+ loras: [{ isEnabled: true, model: currentLora, weight: 0.5 }],+ model: currentModel,++ mistralEncoderModel: currentMistral,+ qwen3EncoderModel: currentComponent,+ vae: currentVae,+ };+ const clonedValues = cloneGenerateWidgetValues(currentValues);+ const synced = syncGenerateWidgetValuesWithModels(clonedValues, [+ currentModel,+ currentComponent,++ currentMistral,+ currentVae,+ currentLora,+ ]);++ expect(synced).toBe(clonedValues);+ });+});++describe('LoRA settings helpers', () => {+ it('uses current model records when reading selected LoRA defaults', () => {+ const staleModel: LoraModelConfig = {+ base: 'sdxl',+ default_settings: { weight: 0.75 },+ key: 'lora-key',+ name: 'Old LoRA Name',+ type: 'lora',+ };+ const currentModel: LoraModelConfig = {+ ...staleModel,+ default_settings: { weight: 1.25 },+ name: 'Updated LoRA Name',+ trigger_phrases: ['updated trigger'],+ };+ const selectedLora: GenerateLora = { isEnabled: true, model: staleModel, weight: 0.5 };++ const [syncedLora] = syncGenerateLorasWithModels([selectedLora], [currentModel]);++ expect(syncedLora?.model).toBe(currentModel);+ expect(syncedLora?.weight).toBe(0.5);+ expect(getDefaultLoraWeight(syncedLora!.model)).toBe(1.25);+ });+- it('allows FLUX LoRAs for FLUX.2 while preserving FLUX.2 variant checks', () => {++ it('restricts FLUX.2 LoRAs by base and variant', () => {+ const flux2Model: MainModelConfig = { base: 'flux2', key: 'flux2', name: 'FLUX.2', type: 'main' };+- expect(isLoraCompatibleWithModel({ base: 'flux' }, flux2Model)).toBe(true);++ expect(isLoraCompatibleWithModel({ base: 'flux' }, flux2Model)).toBe(false);+ expect(+ isLoraCompatibleWithModel({ base: 'flux2', variant: 'klein_4b' }, { ...flux2Model, variant: 'klein_9b' })+ ).toBe(false);+ });+});++describe('model defaults', () => {+ it('uses shared VAE compatibility for cross-base default VAEs', () => {+ const zImageModel: MainModelConfig = {+ base: 'z-image',+ default_settings: { vae: 'flux-vae' },+ key: 'z-image',+ name: 'Z-Image',+ type: 'main',+ };+ const fluxVae: VaeModelConfig = { base: 'flux', key: 'flux-vae', name: 'FLUX VAE', type: 'vae' };++ expect(getModelDefaultVae(zImageModel, [fluxVae])).toBe(fluxVae);+ });++ it('distinguishes absent VAE defaults from explicit VAE defaults', () => {+ expect(hasModelDefaultVae({ base: 'sdxl', key: 'sdxl', name: 'SDXL', type: 'main' })).toBe(false);+ expect(+ hasModelDefaultVae({ base: 'sdxl', default_settings: { vae: null }, key: 'sdxl', name: 'SDXL', type: 'main' })+ ).toBe(false);+ expect(+ hasModelDefaultVae({ base: 'sdxl', default_settings: { vae: 'vae' }, key: 'sdxl', name: 'SDXL', type: 'main' })+ ).toBe(true);+ });+});++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);+ });++ it('uses larger dimension grids for model families that require them', () => {+ expect(getGenerationDimensions({ base: 'sdxl', type: 'main' }).grid).toBe(8);+ expect(getGenerationDimensions({ base: 'anima', type: 'main' }).grid).toBe(8);+ expect(getGenerationDimensions({ base: 'flux2', type: 'main' }).grid).toBe(16);+ expect(getGenerationDimensions({ base: 'qwen-image', type: 'main' }).grid).toBe(16);+ expect(getGenerationDimensions({ base: 'cogview4', type: 'main' }).grid).toBe(32);+ expect(clampDimension(888, getGenerationDimensions({ base: 'flux2', type: 'main' }).grid)).toBe(896);+ });+});diff --cc invokeai/frontend/webv2/src/features/generation/core/settings.tsindex 928f2d69ff,0000000000..39c3d5f0e9mode 100644,000000..100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts@@@ -1,840 -1,0 +1,843 @@@+import type {+ AspectRatioId,+ ComponentModelConfig,+ GenerateLora,+ GenerateModelConfig,+ GenerateReferenceImage,+ GenerateReferenceImageAsset,+ GenerateReferenceImageConfig,+ GenerateSettings,+ GenerateWidgetValues,+ Ideogram4SamplerPreset,+ LoraModelConfig,+ MainModelConfig,+ VaeModelConfig,+ VaePrecision,+} from './types';++import { sanitizeBatchCount } from './batch';+import { isVaeCompatibleWithGenerateModel } from './componentCompatibility';+import {+ DEFAULT_KREA2_REBALANCE_MULTIPLIER,+ DEFAULT_KREA2_REBALANCE_WEIGHTS,+ isValidKrea2RebalanceWeights,+ KREA2_REBALANCE_WEIGHT_COUNT,+} from './conditioningRebalance';+import { isDynamicPromptsSeedBehaviour, sanitizeMaxPrompts, sanitizeSampleSeed } from './dynamicPrompts';+import { clampPidSteps, DEFAULT_PID_STEPS, isPidMode } from './pid';+import { isCanonicalPromptTemplateSnapshot, sanitizePromptTemplateSnapshot } from './promptTemplates';+import { cloneCroppableImage, isCanonicalCroppableImage, normalizeCroppableImage } from './referenceImage';++/** 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);++export const DIMENSION_GRID = 8;+export const MIN_DIMENSION = 64;+export const MAX_DIMENSION = 4096;++export const SEED_MAX = 4_294_967_295;+export const MIN_NEGATIVE_PROMPT_HEIGHT_PX = 56;+export const MAX_NEGATIVE_PROMPT_HEIGHT_PX = 240;+export const DEFAULT_NEGATIVE_PROMPT_HEIGHT_PX = 56;+export const MIN_POSITIVE_PROMPT_HEIGHT_PX = 96;+export const MAX_POSITIVE_PROMPT_HEIGHT_PX = 360;+export const DEFAULT_POSITIVE_PROMPT_HEIGHT_PX = 96;+export const DEFAULT_HIDIFFUSION_T1_RATIO = 0.4;+export const DEFAULT_HIDIFFUSION_T2_RATIO = 0;+export const MIN_HIDIFFUSION_T1_RATIO = 0.1;+export const MAX_HIDIFFUSION_RATIO = 1;++export const DEFAULT_LORA_WEIGHT_CONFIG = {+ coarseStep: 0.05,+ initial: 0.75,+ numberInputMax: 10,+ numberInputMin: -10,+ sliderMax: 2,+ sliderMin: -1,+};++export const clampDimension = (value: number, grid = DIMENSION_GRID): number =>+ Math.min(MAX_DIMENSION, Math.max(MIN_DIMENSION, Math.round(value / grid) * 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,+ grid = DIMENSION_GRID+): { width: number; height: number } => {+ const exactWidth = Math.sqrt(area * ratio);++ return { height: clampDimension(exactWidth / ratio, grid), width: clampDimension(exactWidth, grid) };+};++/** 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]);++const getClampedNumber = (record: Record<string, unknown>, key: string, min: number, max: number, fallback: number) =>+ hasFiniteNumber(record, key) ? Math.min(Math.max(record[key] as number, min), max) : fallback;++export const isMainModelConfig = (value: unknown): value is MainModelConfig =>+ isRecord(value) &&+ typeof value.key === 'string' &&+ typeof value.name === 'string' &&+ typeof value.base === 'string' &&+ value.type === 'main';++export const isExternalImageGeneratorModelConfig = (value: unknown): value is GenerateModelConfig =>+ isRecord(value) &&+ typeof value.key === 'string' &&+ typeof value.name === 'string' &&+ value.base === 'external' &&+ value.type === 'external_image_generator';++export const isGenerateModelConfig = (value: unknown): value is GenerateModelConfig =>+ isMainModelConfig(value) || isExternalImageGeneratorModelConfig(value);++export const isModelIdentifierConfig = (value: unknown): value is ComponentModelConfig =>+ isRecord(value) &&+ typeof value.key === 'string' &&+ typeof value.name === 'string' &&+ typeof value.base === 'string' &&+ typeof value.type === 'string';++export const isVaeModelConfig = (value: unknown): value is VaeModelConfig =>+ isRecord(value) &&+ typeof value.key === 'string' &&+ typeof value.name === 'string' &&+ typeof value.base === 'string' &&+ value.type === 'vae';++export const isLoraModelConfig = (value: unknown): value is LoraModelConfig =>+ isRecord(value) &&+ typeof value.key === 'string' &&+ typeof value.name === 'string' &&+ typeof value.base === 'string' &&+ value.type === 'lora';++const getModelIdentifierOrNull = (value: unknown): ComponentModelConfig | null =>+ isModelIdentifierConfig(value) ? value : null;++const getMainModelOrNull = (value: unknown): MainModelConfig | null => (isMainModelConfig(value) ? value : null);++const isVaePrecision = (value: unknown): value is VaePrecision => value === 'fp16' || value === 'fp32';++/** Backend defaults from `Ideogram4DenoiseInvocation` / `Krea2*Invocation`. */+export const IDEOGRAM4_SAMPLER_PRESETS: Ideogram4SamplerPreset[] = ['V4_QUALITY_48', 'V4_DEFAULT_20', 'V4_TURBO_12'];+export const DEFAULT_IDEOGRAM4_SAMPLER_PRESET: Ideogram4SamplerPreset = 'V4_QUALITY_48';+export const DEFAULT_KREA2_SEED_VARIANCE_STRENGTH = 0.1;+export const MAX_KREA2_SEED_VARIANCE_STRENGTH = 2;+export const DEFAULT_KREA2_SEED_VARIANCE_RANDOMIZE_PERCENT = 50;++const isIdeogram4SamplerPreset = (value: unknown): value is Ideogram4SamplerPreset =>+ IDEOGRAM4_SAMPLER_PRESETS.includes(value as Ideogram4SamplerPreset);++const getOptionalNumber = (value: unknown): number | null =>+ typeof value === 'number' && Number.isFinite(value) ? value : null;++const getStringArray = (value: unknown): string[] =>+ Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : [];++// Re-exported so existing `core/settings` callers keep one import site; the rebalance+// vector, its presets, and its geometry all live in `conditioningRebalance.ts`.+export {+ DEFAULT_KREA2_REBALANCE_MULTIPLIER,+ DEFAULT_KREA2_REBALANCE_WEIGHTS,+ isValidKrea2RebalanceWeights,+ KREA2_REBALANCE_WEIGHT_COUNT,+};++const isGenerateLora = (value: unknown): value is GenerateLora =>+ isRecord(value) &&+ isLoraModelConfig(value.model) &&+ hasFiniteNumber(value, 'weight') &&+ typeof value.isEnabled === 'boolean';++export const DEFAULT_REFERENCE_IMAGE_LIMIT = 5;++const REFERENCE_IMAGE_CONFIG_TYPES = new Set([+ 'external_reference_image',+ 'flux2_reference_image',+ 'flux_kontext_reference_image',+ 'flux_redux',+ 'ip_adapter',+ 'qwen_image_reference_image',+]);++const isClipVisionModel = (value: unknown): value is 'ViT-H' | 'ViT-G' | 'ViT-L' =>+ value === 'ViT-H' || value === 'ViT-G' || value === 'ViT-L';++const isIPAdapterMethod = (+ value: unknown+): value is 'full' | 'style' | 'composition' | 'style_strong' | 'style_precise' =>+ value === 'full' ||+ value === 'style' ||+ value === 'composition' ||+ value === 'style_strong' ||+ value === 'style_precise';++const isFluxReduxImageInfluence = (value: unknown): value is 'lowest' | 'low' | 'medium' | 'high' | 'highest' =>+ value === 'lowest' || value === 'low' || value === 'medium' || value === 'high' || value === 'highest';++const normalizeReferenceImageAsset = (value: unknown): GenerateReferenceImageAsset | null =>+ value === null ? null : normalizeCroppableImage(value);++const normalizeReferenceImageConfig = (value: unknown): GenerateReferenceImageConfig | null => {+ if (!isRecord(value) || typeof value.type !== 'string' || !REFERENCE_IMAGE_CONFIG_TYPES.has(value.type)) {+ return null;+ }++ const image = normalizeReferenceImageAsset(value.image);++ if (value.image !== null && image === null) {+ return null;+ }++ switch (value.type) {+ case 'external_reference_image':+ case 'flux2_reference_image':+ case 'qwen_image_reference_image':+ return { image, type: value.type };+ case 'flux_kontext_reference_image':+ return { image, model: getMainModelOrNull(value.model), type: value.type };+ case 'flux_redux':+ return {+ image,+ imageInfluence: isFluxReduxImageInfluence(value.imageInfluence) ? value.imageInfluence : 'highest',+ model: getModelIdentifierOrNull(value.model),+ type: value.type,+ };+ case 'ip_adapter':+ return {+ beginEndStepPct:+ Array.isArray(value.beginEndStepPct) &&+ value.beginEndStepPct.length === 2 &&+ value.beginEndStepPct.every((item) => typeof item === 'number' && Number.isFinite(item))+ ? [value.beginEndStepPct[0], value.beginEndStepPct[1]]+ : [0, 1],+ clipVisionModel: isClipVisionModel(value.clipVisionModel) ? value.clipVisionModel : 'ViT-H',+ image,+ method: isIPAdapterMethod(value.method) ? value.method : 'full',+ model: getModelIdentifierOrNull(value.model),+ type: value.type,+ weight: hasFiniteNumber(value, 'weight') ? (value.weight as number) : 1,+ };+ }++ return null;+};++export const normalizeReferenceImages = (value: unknown): GenerateReferenceImage[] => {+ if (!Array.isArray(value)) {+ return [];+ }++ const images: GenerateReferenceImage[] = [];++ for (const item of value) {+ if (!isRecord(item) || typeof item.id !== 'string') {+ continue;+ }++ const config = normalizeReferenceImageConfig(item.config);++ if (!config) {+ continue;+ }++ images.push({ config, id: item.id, isEnabled: item.isEnabled !== false });+ }++ return images;+};++const areReferenceImagesCanonical = (value: unknown): boolean =>+ Array.isArray(value) &&+ value.every(+ (item) =>+ isRecord(item) &&+ isRecord(item.config) &&+ (item.config.image === null || isCanonicalCroppableImage(item.config.image))+ );++const cloneReferenceImageConfig = (config: GenerateReferenceImageConfig): GenerateReferenceImageConfig => {+ switch (config.type) {+ case 'external_reference_image':+ case 'flux2_reference_image':+ case 'qwen_image_reference_image':+ return { ...config, image: config.image ? cloneCroppableImage(config.image) : null };+ case 'flux_kontext_reference_image':+ return {+ ...config,+ image: config.image ? cloneCroppableImage(config.image) : null,+ model: config.model ? { ...config.model } : null,+ };+ case 'flux_redux':+ case 'ip_adapter':+ return {+ ...config,+ image: config.image ? cloneCroppableImage(config.image) : null,+ model: config.model ? { ...config.model } : null,+ };+ }+};++export const cloneReferenceImages = (+ referenceImages: readonly GenerateReferenceImage[] = []+): GenerateReferenceImage[] =>+ referenceImages.map((referenceImage) => ({+ ...referenceImage,+ config: cloneReferenceImageConfig(referenceImage.config),+ }));++export const getDefaultLoraWeight = (model: LoraModelConfig): number => {+ const weight = model.default_settings?.weight;++ return Number.isFinite(weight) && weight !== null && weight !== undefined+ ? weight+ : DEFAULT_LORA_WEIGHT_CONFIG.initial;+};++const areModelSnapshotsEqual = (a: unknown, b: unknown): boolean => {+ if (a === b) {+ return true;+ }++ try {+ return JSON.stringify(a) === JSON.stringify(b);+ } catch {+ return false;+ }+};++export const syncGenerateLorasWithModels = (loras: GenerateLora[], models: readonly unknown[]): GenerateLora[] => {+ const modelsByKey = new Map<string, LoraModelConfig>();++ for (const model of models) {+ if (isLoraModelConfig(model)) {+ modelsByKey.set(model.key, model);+ }+ }++ let didSync = false;+ const syncedLoras = loras.map((lora) => {+ const currentModel = modelsByKey.get(lora.model.key);++ if (!currentModel || areModelSnapshotsEqual(currentModel, lora.model)) {+ return lora;+ }++ didSync = true;+ return { ...lora, model: currentModel };+ });++ return didSync ? syncedLoras : loras;+};++const syncModelIdentifierWithModels = <T extends ComponentModelConfig | null>(+ value: T,+ modelsByKey: Map<string, unknown>+): T => {+ if (!value) {+ return value;+ }++ const currentModel = modelsByKey.get(value.key);++ return isModelIdentifierConfig(currentModel) && !areModelSnapshotsEqual(currentModel, value)+ ? (currentModel as T)+ : value;+};++export const getModelDefaultVae = (+ model: GenerateModelConfig,+ vaeModels: readonly VaeModelConfig[]+): VaeModelConfig | null => {+ const defaultVaeKey = (model.default_settings as { vae?: string | null } | null | undefined)?.vae;++ return defaultVaeKey+ ? (vaeModels.find((vae) => vae.key === defaultVaeKey && isVaeCompatibleWithGenerateModel(model, vae)) ?? null)+ : null;+};++export const hasModelDefaultVae = (model: GenerateModelConfig): boolean =>+ typeof (model.default_settings as { vae?: unknown } | null | undefined)?.vae === 'string';++export const cloneGenerateWidgetValues = (+ values: GenerateWidgetValues+): GenerateWidgetValues & Record<string, unknown> => ({+ ...values,+ clipEmbedModel: values.clipEmbedModel ? { ...values.clipEmbedModel } : null,+ clipGEmbedModel: values.clipGEmbedModel ? { ...values.clipGEmbedModel } : null,+ clipLEmbedModel: values.clipLEmbedModel ? { ...values.clipLEmbedModel } : null,+ componentSourceModel: values.componentSourceModel ? { ...values.componentSourceModel } : null,+ loras: values.loras.map((lora) => ({ ...lora, model: { ...lora.model } })),+ model: { ...values.model },++ mistralEncoderModel: values.mistralEncoderModel ? { ...values.mistralEncoderModel } : null,+ promptTemplate: values.promptTemplate ? { ...values.promptTemplate } : null,+ qwen3EncoderModel: values.qwen3EncoderModel ? { ...values.qwen3EncoderModel } : null,+ qwenVLEncoderModel: values.qwenVLEncoderModel ? { ...values.qwenVLEncoderModel } : null,+ qwen3VLEncoderModel: values.qwen3VLEncoderModel ? { ...values.qwen3VLEncoderModel } : null,+ wanT5EncoderModel: values.wanT5EncoderModel ? { ...values.wanT5EncoderModel } : null,+ wanLowNoiseModel: values.wanLowNoiseModel ? { ...values.wanLowNoiseModel } : null,+ ideogram4ColorPalette: [...values.ideogram4ColorPalette],+ referenceImages: cloneReferenceImages(values.referenceImages),+ t5EncoderModel: values.t5EncoderModel ? { ...values.t5EncoderModel } : null,+ vae: values.vae ? { ...values.vae } : null,+});++const syncReferenceImageConfigWithModels = (+ config: GenerateReferenceImageConfig,+ modelsByKey: Map<string, unknown>+): GenerateReferenceImageConfig => {+ switch (config.type) {+ case 'flux_kontext_reference_image': {+ const model = syncModelIdentifierWithModels(config.model, modelsByKey);++ return model === config.model ? config : { ...config, model: isMainModelConfig(model) ? model : config.model };+ }+ case 'flux_redux':+ case 'ip_adapter': {+ const model = syncModelIdentifierWithModels(config.model, modelsByKey);++ return model === config.model ? config : { ...config, model };+ }+ case 'external_reference_image':+ case 'flux2_reference_image':+ case 'qwen_image_reference_image':+ return config;+ }+};++export const syncReferenceImagesWithModels = (+ referenceImages: GenerateReferenceImage[],+ models: readonly unknown[]+): GenerateReferenceImage[] => {+ const modelsByKey = new Map<string, unknown>();++ for (const model of models) {+ if (isModelIdentifierConfig(model)) {+ modelsByKey.set(model.key, model);+ }+ }++ let didSync = false;+ const synced = referenceImages.map((referenceImage) => {+ const config = syncReferenceImageConfigWithModels(referenceImage.config, modelsByKey);++ if (config === referenceImage.config) {+ return referenceImage;+ }++ didSync = true;+ return { ...referenceImage, config };+ });++ return didSync ? synced : referenceImages;+};++export const syncGenerateWidgetValuesWithModels = (+ values: GenerateWidgetValues,+ models: readonly unknown[]+): GenerateWidgetValues => {+ const modelsByKey = new Map<string, unknown>();++ for (const model of models) {+ if (isModelIdentifierConfig(model)) {+ modelsByKey.set(model.key, model);+ }+ }++ const currentModel = modelsByKey.get(values.model.key);+ const model =+ isGenerateModelConfig(currentModel) && !areModelSnapshotsEqual(currentModel, values.model)+ ? currentModel+ : values.model;+ const vae = syncModelIdentifierWithModels(values.vae, modelsByKey);+ const componentSourceModel = syncModelIdentifierWithModels(values.componentSourceModel, modelsByKey);+ const nextValues: GenerateWidgetValues = {+ ...values,+ clipEmbedModel: syncModelIdentifierWithModels(values.clipEmbedModel, modelsByKey),+ clipGEmbedModel: syncModelIdentifierWithModels(values.clipGEmbedModel, modelsByKey),+ clipLEmbedModel: syncModelIdentifierWithModels(values.clipLEmbedModel, modelsByKey),+ componentSourceModel: isMainModelConfig(componentSourceModel) ? componentSourceModel : values.componentSourceModel,+ loras: syncGenerateLorasWithModels(values.loras, models),+ model,+ modelKey: model.key,++ mistralEncoderModel: syncModelIdentifierWithModels(values.mistralEncoderModel, modelsByKey),+ qwen3EncoderModel: syncModelIdentifierWithModels(values.qwen3EncoderModel, modelsByKey),+ qwenVLEncoderModel: syncModelIdentifierWithModels(values.qwenVLEncoderModel, modelsByKey),+ referenceImages: syncReferenceImagesWithModels(values.referenceImages, models),+ t5EncoderModel: syncModelIdentifierWithModels(values.t5EncoderModel, modelsByKey),+ vae: isVaeModelConfig(vae) ? vae : values.vae,+ };++ return nextValues.model === values.model &&+ nextValues.loras === values.loras &&+ nextValues.vae === values.vae &&+ nextValues.t5EncoderModel === values.t5EncoderModel &&+ nextValues.clipEmbedModel === values.clipEmbedModel &&+ nextValues.clipLEmbedModel === values.clipLEmbedModel &&+ nextValues.clipGEmbedModel === values.clipGEmbedModel &&++ nextValues.mistralEncoderModel === values.mistralEncoderModel &&+ nextValues.qwen3EncoderModel === values.qwen3EncoderModel &&+ nextValues.qwenVLEncoderModel === values.qwenVLEncoderModel &&+ nextValues.referenceImages === values.referenceImages &&+ nextValues.componentSourceModel === values.componentSourceModel &&+ nextValues.modelKey === values.modelKey+ ? values+ : nextValues;+};++export const isLoraCompatibleWithModel = (+ loraModel: Pick<LoraModelConfig, 'base' | 'variant'>,+ mainModel: Pick<GenerateModelConfig, 'base' | 'variant'>+): boolean => {+ if (mainModel.base === 'flux2') {- if (loraModel.base !== 'flux2' && loraModel.base !== 'flux') {++ if (loraModel.base !== 'flux2') {+ return false;+ }+- return (- loraModel.base === 'flux' || !mainModel.variant || !loraModel.variant || loraModel.variant === mainModel.variant- );++ return !mainModel.variant || !loraModel.variant || loraModel.variant === mainModel.variant;+ }++ if (loraModel.base !== mainModel.base) {+ return false;+ }++ if (mainModel.base === 'wan') {+ return isWanLoraTargetingMain(loraModel.variant, mainModel.variant);+ }++ return true;+};++/**+ * Wan 2.2 main-model variants (`t2v_a14b` / `i2v_a14b` / `ti2v_5b`) and LoRA variants+ * (`a14b` / `5b`) name the same families with different strings, so plain variant equality+ * would reject every Wan LoRA. The families are also not interchangeable — A14B LoRAs have+ * `inner_dim=5120` and 5B `inner_dim=3072`, and applying one to the wrong main crashes the+ * layer patcher on a tensor-shape mismatch — so the mapping must be explicit rather than+ * permissive. An unknown variant on either side stays allowed: the backend probe is the+ * authority, and blocking here would hide a LoRA the backend would have accepted.+ */+const WAN_LORA_VARIANT_MAIN_VARIANTS: Record<string, readonly string[]> = {+ '5b': ['ti2v_5b'],+ a14b: ['t2v_a14b', 'i2v_a14b'],+};++export const isWanLoraTargetingMain = (+ loraVariant: string | null | undefined,+ mainVariant: string | null | undefined+): boolean => {+ if (!loraVariant || !mainVariant) {+ return true;+ }++ const compatibleMainVariants = WAN_LORA_VARIANT_MAIN_VARIANTS[loraVariant];++ return compatibleMainVariants ? compatibleMainVariants.includes(mainVariant) : true;+};++/**+ * 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.+ */+/**+ * The fields of `GenerateSettings` that describe how the panel is arranged+ * rather than what will be generated.+ *+ * They live in the same object because they are saved with the project, and+ * separating the two is a change to the persisted shape rather than a+ * rearrangement — worth doing, but not here. What can be stated once is which+ * is which, and this is it: `satisfies` ties the set to the interface, so a key+ * that stops existing, or is spelled wrong, fails to compile.+ *+ * Everything else is generation intent. Changing one of these is not: dragging+ * a prompt box taller or looking at the merged template must not be mistaken+ * for the kind of edit that reroutes the workbench. Applying a template *is*+ * intent, which is why `promptTemplate` is absent and `promptTemplateViewMode`+ * is present.+ */+export const GENERATE_UI_STATE_KEYS = {+ aspectRatioIsLocked: true,+ batchCount: true,+ negativePromptHeightPx: true,+ positivePromptHeightPx: true,+ promptTemplateViewMode: true,+} satisfies Partial<Record<keyof GenerateSettings, true>>;++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' &&+ ['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;++ const promptTemplate = isCanonicalPromptTemplateSnapshot(values.promptTemplate)+ ? values.promptTemplate+ : sanitizePromptTemplateSnapshot(values.promptTemplate);++ 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: sanitizeBatchCount(values.batchCount),+ cfgRescaleMultiplier: values.cfgRescaleMultiplier as number,+ cfgScale: values.cfgScale as number,+ clipSkip: hasFiniteNumber(values, 'clipSkip') ? (values.clipSkip as number) : 0,+ colorCompensation: typeof values.colorCompensation === 'boolean' ? values.colorCompensation : false,+ hiDiffusionEnabled: typeof values.hiDiffusionEnabled === 'boolean' ? values.hiDiffusionEnabled : false,+ hiDiffusionRauNetEnabled:+ typeof values.hiDiffusionRauNetEnabled === 'boolean' ? values.hiDiffusionRauNetEnabled : true,+ hiDiffusionWindowAttentionEnabled:+ typeof values.hiDiffusionWindowAttentionEnabled === 'boolean' ? values.hiDiffusionWindowAttentionEnabled : true,+ hiDiffusionT1Ratio: getClampedNumber(+ values,+ 'hiDiffusionT1Ratio',+ MIN_HIDIFFUSION_T1_RATIO,+ MAX_HIDIFFUSION_RATIO,+ DEFAULT_HIDIFFUSION_T1_RATIO+ ),+ hiDiffusionT2Ratio: getClampedNumber(+ values,+ 'hiDiffusionT2Ratio',+ 0,+ MAX_HIDIFFUSION_RATIO,+ DEFAULT_HIDIFFUSION_T2_RATIO+ ),+ dynamicPromptsCombinatorial:+ typeof values.dynamicPromptsCombinatorial === 'boolean' ? values.dynamicPromptsCombinatorial : true,+ dynamicPromptsMaxPrompts: sanitizeMaxPrompts(values.dynamicPromptsMaxPrompts),+ dynamicPromptsSampleSeed: sanitizeSampleSeed(values.dynamicPromptsSampleSeed),+ dynamicPromptsSeedBehaviour: isDynamicPromptsSeedBehaviour(values.dynamicPromptsSeedBehaviour)+ ? values.dynamicPromptsSeedBehaviour+ : 'per-iteration',+ height,+ loras: Array.isArray(values.loras) ? values.loras.filter(isGenerateLora) : [],+ modelKey: values.modelKey as string,+ negativePromptEnabled: typeof values.negativePromptEnabled === 'boolean' ? values.negativePromptEnabled : true,+ negativePrompt: values.negativePrompt as string,+ negativePromptHeightPx: getClampedNumber(+ values,+ 'negativePromptHeightPx',+ MIN_NEGATIVE_PROMPT_HEIGHT_PX,+ MAX_NEGATIVE_PROMPT_HEIGHT_PX,+ DEFAULT_NEGATIVE_PROMPT_HEIGHT_PX+ ),+ positivePrompt: values.positivePrompt as string,+ positivePromptHeightPx: getClampedNumber(+ values,+ 'positivePromptHeightPx',+ MIN_POSITIVE_PROMPT_HEIGHT_PX,+ MAX_POSITIVE_PROMPT_HEIGHT_PX,+ DEFAULT_POSITIVE_PROMPT_HEIGHT_PX+ ),+ // Reuse the stored object when it is already canonical. Callers diff settings+ // with `Object.is`, so re-sanitizing into a fresh object every pass would make+ // every commit look like a template change and loop the sync in+ // `GenerateWidgetView`.+ promptTemplate,+ promptTemplateViewMode: promptTemplate !== null && values.promptTemplateViewMode === true,+ referenceImages: normalizeReferenceImages(values.referenceImages),+ 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',+ t5EncoderModel: getModelIdentifierOrNull(values.t5EncoderModel),+ clipEmbedModel: getModelIdentifierOrNull(values.clipEmbedModel),+ clipLEmbedModel: getModelIdentifierOrNull(values.clipLEmbedModel),+ clipGEmbedModel: getModelIdentifierOrNull(values.clipGEmbedModel),++ mistralEncoderModel: getModelIdentifierOrNull(values.mistralEncoderModel),+ qwen3EncoderModel: getModelIdentifierOrNull(values.qwen3EncoderModel),+ qwenVLEncoderModel: getModelIdentifierOrNull(values.qwenVLEncoderModel),+ qwen3VLEncoderModel: getModelIdentifierOrNull(values.qwen3VLEncoderModel),+ wanT5EncoderModel: getModelIdentifierOrNull(values.wanT5EncoderModel),+ wanLowNoiseModel: getMainModelOrNull(values.wanLowNoiseModel),+ componentSourceModel: getMainModelOrNull(values.componentSourceModel),+ wanGuidanceScaleLowNoise: getOptionalNumber(values.wanGuidanceScaleLowNoise),+ ideogram4SamplerPreset: isIdeogram4SamplerPreset(values.ideogram4SamplerPreset)+ ? values.ideogram4SamplerPreset+ : DEFAULT_IDEOGRAM4_SAMPLER_PRESET,+ ideogram4Steps: getOptionalNumber(values.ideogram4Steps),+ ideogram4GuidanceScale: getOptionalNumber(values.ideogram4GuidanceScale),+ ideogram4Mu: getOptionalNumber(values.ideogram4Mu),+ ideogram4ColorPalette: getStringArray(values.ideogram4ColorPalette),+ krea2RebalanceEnabled: values.krea2RebalanceEnabled === true,+ krea2RebalanceMultiplier: hasFiniteNumber(values, 'krea2RebalanceMultiplier')+ ? (values.krea2RebalanceMultiplier as number)+ : DEFAULT_KREA2_REBALANCE_MULTIPLIER,+ krea2RebalanceWeights:+ typeof values.krea2RebalanceWeights === 'string' ? values.krea2RebalanceWeights : DEFAULT_KREA2_REBALANCE_WEIGHTS,+ krea2SeedVarianceEnabled: values.krea2SeedVarianceEnabled === true,+ krea2SeedVarianceStrength: getClampedNumber(+ values,+ 'krea2SeedVarianceStrength',+ 0,+ MAX_KREA2_SEED_VARIANCE_STRENGTH,+ DEFAULT_KREA2_SEED_VARIANCE_STRENGTH+ ),+ krea2SeedVarianceRandomizePercent: getClampedNumber(+ values,+ 'krea2SeedVarianceRandomizePercent',+ 0,+ 100,+ DEFAULT_KREA2_SEED_VARIANCE_RANDOMIZE_PERCENT+ ),+ pidMode: isPidMode(values.pidMode) ? values.pidMode : 'off',+ pidDecoderModel: getModelIdentifierOrNull(values.pidDecoderModel),+ gemma2EncoderModel: getModelIdentifierOrNull(values.gemma2EncoderModel),+ pidSteps: clampPidSteps(hasFiniteNumber(values, 'pidSteps') ? (values.pidSteps as number) : DEFAULT_PID_STEPS),+ width,+ };+};++export const normalizeGenerateWidgetValues = (values: unknown): GenerateWidgetValues | null => {+ const settings = normalizeGenerateSettings(values);++ if (!settings || !isRecord(values) || !isGenerateModelConfig(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.colorCompensation === 'boolean' &&+ typeof values.hiDiffusionEnabled === 'boolean' &&+ typeof values.hiDiffusionRauNetEnabled === 'boolean' &&+ typeof values.hiDiffusionWindowAttentionEnabled === 'boolean' &&+ hasFiniteNumber(values, 'hiDiffusionT1Ratio') &&+ (values.hiDiffusionT1Ratio as number) >= MIN_HIDIFFUSION_T1_RATIO &&+ (values.hiDiffusionT1Ratio as number) <= MAX_HIDIFFUSION_RATIO &&+ hasFiniteNumber(values, 'hiDiffusionT2Ratio') &&+ (values.hiDiffusionT2Ratio as number) >= 0 &&+ (values.hiDiffusionT2Ratio as number) <= MAX_HIDIFFUSION_RATIO &&+ typeof values.negativePromptEnabled === 'boolean' &&+ hasFiniteNumber(values, 'negativePromptHeightPx') &&+ hasFiniteNumber(values, 'positivePromptHeightPx') &&+ Array.isArray(values.loras) &&+ values.loras.every(isGenerateLora) &&+ Array.isArray(values.referenceImages) &&+ normalizeReferenceImages(values.referenceImages).length === values.referenceImages.length &&+ areReferenceImagesCanonical(values.referenceImages) &&+ (values.promptTemplate === null || isCanonicalPromptTemplateSnapshot(values.promptTemplate)) &&+ typeof values.promptTemplateViewMode === 'boolean' &&+ (values.promptTemplate !== null || values.promptTemplateViewMode === false) &&+ typeof values.seamlessXAxis === 'boolean' &&+ typeof values.seamlessYAxis === 'boolean' &&+ isVaePrecision(values.vaePrecision) &&+ (values.vae === null || isVaeModelConfig(values.vae)) &&+ (values.t5EncoderModel === null || isModelIdentifierConfig(values.t5EncoderModel)) &&+ (values.clipEmbedModel === null || isModelIdentifierConfig(values.clipEmbedModel)) &&+ (values.clipLEmbedModel === null || isModelIdentifierConfig(values.clipLEmbedModel)) &&+ (values.clipGEmbedModel === null || isModelIdentifierConfig(values.clipGEmbedModel)) &&++ (values.mistralEncoderModel === null || isModelIdentifierConfig(values.mistralEncoderModel)) &&+ (values.qwen3EncoderModel === null || isModelIdentifierConfig(values.qwen3EncoderModel)) &&+ (values.qwenVLEncoderModel === null || isModelIdentifierConfig(values.qwenVLEncoderModel)) &&+ (values.qwen3VLEncoderModel === null || isModelIdentifierConfig(values.qwen3VLEncoderModel)) &&+ (values.wanT5EncoderModel === null || isModelIdentifierConfig(values.wanT5EncoderModel)) &&+ (values.wanLowNoiseModel === null || isMainModelConfig(values.wanLowNoiseModel)) &&+ (values.componentSourceModel === null || isMainModelConfig(values.componentSourceModel)) &&+ isIdeogram4SamplerPreset(values.ideogram4SamplerPreset) &&+ Array.isArray(values.ideogram4ColorPalette) &&+ values.ideogram4ColorPalette.every((entry) => typeof entry === 'string') &&+ typeof values.krea2RebalanceEnabled === 'boolean' &&+ hasFiniteNumber(values, 'krea2RebalanceMultiplier') &&+ typeof values.krea2RebalanceWeights === 'string' &&+ typeof values.krea2SeedVarianceEnabled === 'boolean' &&+ hasFiniteNumber(values, 'krea2SeedVarianceStrength') &&+ hasFiniteNumber(values, 'krea2SeedVarianceRandomizePercent')+ );+};++export const isGenerateWidgetValues = (values: unknown): values is GenerateWidgetValues =>+ isGenerateSettings(values) && isGenerateModelConfig((values as unknown as Record<string, unknown>).model);diff --cc invokeai/frontend/webv2/src/features/generation/core/types.tsindex da52637806,0000000000..996263aa5cmode 100644,000000..100644--- a/invokeai/frontend/webv2/src/features/generation/core/types.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/types.ts@@@ -1,281 -1,0 +1,283 @@@+import type { BackendGraphContract, GraphContract } from '@features/generation/core/contracts';+import type { DynamicPromptsSeedBehaviour } from '@features/generation/core/dynamicPrompts';+import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';++export type ModelIdentifierConfig = {+ key: string;+ name: string;+ base: string;+ type: string;+ format?: string;+ variant?: string | null;+ hash?: string;+ submodel_type?: string;+ [key: string]: unknown;+};++export type MainModelConfig = ModelIdentifierConfig & {+ type: 'main';+ default_settings?: {+ scheduler?: string | null;+ steps?: number | null;+ cfg_scale?: number | null;+ guidance?: number | null;+ cfg_rescale_multiplier?: number | null;+ width?: number | null;+ height?: number | null;+ vae?: string | null;+ vae_precision?: string | null;+ } | null;+};++export type ExternalImageGeneratorModelConfig = ModelIdentifierConfig & {+ base: 'external';+ type: 'external_image_generator';+ format: 'external_api';+ provider_id?: string;+ capabilities?: {+ modes?: string[];+ supports_seed?: boolean;+ supports_negative_prompt?: boolean;+ supports_reference_images?: boolean;+ max_reference_images?: number | null;+ } | null;+ default_settings?: {+ width?: number | null;+ height?: number | null;+ num_images?: number | null;+ } | null;+};++export type GenerateModelConfig = MainModelConfig | ExternalImageGeneratorModelConfig;++export type ComponentModelConfig = ModelIdentifierConfig;++export type VaeModelConfig = ModelIdentifierConfig & {+ type: 'vae';+};++export type LoraModelConfig = ModelIdentifierConfig & {+ type: 'lora';+ trigger_phrases?: string[] | null;+ default_settings?: {+ weight?: number | null;+ } | null;+ variant?: string | null;+};++export interface GenerateLora {+ isEnabled: boolean;+ model: LoraModelConfig;+ weight: number;+}++export interface ImageWithDims {+ image_name: string;+ width: number;+ height: number;+}++export interface CroppableImageWithDims {+ original: { image: ImageWithDims };+ crop?: {+ image: ImageWithDims;+ box: { x: number; y: number; width: number; height: number };+ ratio: number | null;+ };+}++/** Canonical persisted/metadata asset for global Generate reference images. */+export type GenerateReferenceImageAsset = CroppableImageWithDims;++export type ClipVisionModel = 'ViT-H' | 'ViT-G' | 'ViT-L';++export type IPAdapterMethod = 'full' | 'style' | 'composition' | 'style_strong' | 'style_precise';++export type FluxReduxImageInfluence = 'lowest' | 'low' | 'medium' | 'high' | 'highest';++type IPAdapterReferenceImageConfig<TImage> = {+ type: 'ip_adapter';+ image: TImage | null;+ model: ComponentModelConfig | null;+ weight: number;+ beginEndStepPct: [number, number];+ method: IPAdapterMethod;+ clipVisionModel: ClipVisionModel;+};++type FluxReduxReferenceImageConfig<TImage> = {+ type: 'flux_redux';+ image: TImage | null;+ model: ComponentModelConfig | null;+ imageInfluence: FluxReduxImageInfluence;+};++export type GenerateReferenceImageConfig =+ | IPAdapterReferenceImageConfig<GenerateReferenceImageAsset>+ | FluxReduxReferenceImageConfig<GenerateReferenceImageAsset>+ | {+ type: 'flux_kontext_reference_image';+ image: GenerateReferenceImageAsset | null;+ model: MainModelConfig | null;+ }+ | { type: 'flux2_reference_image'; image: GenerateReferenceImageAsset | null }+ | { type: 'qwen_image_reference_image'; image: GenerateReferenceImageAsset | null }+ | { type: 'external_reference_image'; image: GenerateReferenceImageAsset | null };++export interface GenerateReferenceImage {+ id: string;+ isEnabled: boolean;+ config: GenerateReferenceImageConfig;+}++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';++/**+ * Which of the fields below are panel arrangement rather than generation+ * intent is stated once, as `GENERATE_UI_STATE_KEYS` in `./settings` — beside+ * the normalization that already enumerates them, and where it costs no module+ * of its own. This interface stays type-only.+ */+export interface GenerateSettings {+ batchCount: number;+ modelKey: string;+ positivePrompt: string;+ positivePromptHeightPx: number;+ negativePromptEnabled: boolean;+ negativePrompt: string;+ negativePromptHeightPx: number;+ /**+ * The active prompt template, copied rather than referenced by id so the pure+ * submit reducer can resolve prompts with no catalog lookup. See+ * `core/promptTemplates.ts`.+ */+ promptTemplate: PromptTemplateSnapshot | null;+ /** Show the merged prompt read-only instead of the authored text. */+ promptTemplateViewMode: boolean;+ /** Expand `{a|b}` into every combination; otherwise draw a random sample. */+ dynamicPromptsCombinatorial: boolean;+ /** Upper bound on expanded prompts (the sample size when not combinatorial). */+ dynamicPromptsMaxPrompts: number;+ /** Seeds the random sampler so the preview matches what generates. */+ dynamicPromptsSampleSeed: number;+ dynamicPromptsSeedBehaviour: DynamicPromptsSeedBehaviour;+ 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;+ colorCompensation: boolean;+ /** Enables HiDiffusion high-resolution denoising for supported SD models. */+ hiDiffusionEnabled: boolean;+ hiDiffusionRauNetEnabled: boolean;+ hiDiffusionWindowAttentionEnabled: boolean;+ hiDiffusionT1Ratio: number;+ hiDiffusionT2Ratio: 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;+ loras: GenerateLora[];+ referenceImages: GenerateReferenceImage[];+ t5EncoderModel: ComponentModelConfig | null;+ clipEmbedModel: ComponentModelConfig | null;+ clipLEmbedModel: ComponentModelConfig | null;+ clipGEmbedModel: ComponentModelConfig | null;+ qwen3EncoderModel: ComponentModelConfig | null;++ /** FLUX.2 [dev]'s Mistral text encoder. */++ mistralEncoderModel: ComponentModelConfig | null;+ qwenVLEncoderModel: ComponentModelConfig | null;+ /** Krea-2's text encoder. Distinct from `qwenVLEncoderModel` (Qwen2.5-VL). */+ qwen3VLEncoderModel: ComponentModelConfig | null;+ /** Wan 2.2's UMT5-XXL text encoder. */+ wanT5EncoderModel: ComponentModelConfig | null;+ /**+ * The low-noise expert of a Wan 2.2 A14B mixture-of-experts pair. Optional: without it the+ * high-noise expert runs the whole schedule, which still produces an image at lower quality.+ */+ wanLowNoiseModel: MainModelConfig | null;+ /** Optional Diffusers main model used as a component source for split/quantized model families. */+ componentSourceModel: MainModelConfig | null;+ /** Guidance for the low-noise half of a Wan A14B schedule; null reuses `cfgScale`. */+ wanGuidanceScaleLowNoise: number | null;+ ideogram4SamplerPreset: Ideogram4SamplerPreset;+ /** Null lets the sampler preset decide. */+ ideogram4Steps: number | null;+ ideogram4GuidanceScale: number | null;+ ideogram4Mu: number | null;+ /** Free-text colour terms forwarded to the caption builder. */+ ideogram4ColorPalette: string[];+ /** Scales Krea-2 conditioning toward the prompt before denoise. Default off. */+ krea2RebalanceEnabled: boolean;+ krea2RebalanceMultiplier: number;+ /** Comma-separated per-layer weights, forwarded verbatim to the backend parser. */+ krea2RebalanceWeights: string;+ /** Perturbs Krea-2 conditioning for variety between seeds. Default off. */+ krea2SeedVarianceEnabled: boolean;+ krea2SeedVarianceStrength: number;+ krea2SeedVarianceRandomizePercent: number;+ /**+ * PiD (Pixel Diffusion Decoder) replaces the VAE decode with a caption-conditioned+ * 4x super-resolution decode. Off by default; requires a PiD decoder and a Gemma-2+ * caption encoder.+ */+ pidMode: PidMode;+ /** PiD decoder checkpoint. Trained per backbone, so it must match the main model's base. */+ pidDecoderModel: ComponentModelConfig | null;+ /** The shared Gemma-2 caption encoder PiD conditions its decode on. */+ gemma2EncoderModel: ComponentModelConfig | null;+ pidSteps: number;+}++/**+ * - `off`: ordinary VAE decode.+ * - `fit`: generate at the requested size, decode 4x, downscale back to it.+ * - `native`: the requested size IS the 4x target; generate at size / 4 and keep the+ * full 4x output.+ */+export type PidMode = 'off' | 'fit' | 'native';++/**+ * Ideogram 4 sampler presets. Each fixes a step count and guidance schedule; the explicit+ * step / guidance / mu overrides are applied on top when set.+ */+export type Ideogram4SamplerPreset = 'V4_QUALITY_48' | 'V4_DEFAULT_20' | 'V4_TURBO_12';++export interface GenerateWidgetValues extends GenerateSettings {+ model: GenerateModelConfig;+}++export interface CompiledGenerateGraph {+ backendGraph: BackendGraphContract;+ graph: GraphContract;+ negativePromptNodeId: string;+ positivePromptNodeId: string;+ seedNodeId: string;+}diff --cc invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsxindex c2373d904b,0000000000..463b9c4e14mode 100644,000000..100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsx@@@ -1,137 -1,0 +1,138 @@@+import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';+import type { ComponentModelConfig, GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';++import { Stack } from '@chakra-ui/react';+import {+ getComponentSectionPolicy,+ type ComponentPolicyContext,+ type ComponentSlotPolicy,+} from '@features/generation/core/baseGenerationPolicies';+import { isMainModelConfig, isModelIdentifierConfig, isVaeModelConfig } from '@features/generation/core/settings';+import { Field } from '@platform/ui';+import { useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { GenerationModelSelect as ModelSelect } from './GenerationUiContext';+import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';++interface GenerateComponentsSectionProps {+ settings: GenerateSettings;+ selectedModel: GenerateModelConfig | undefined;+ onCommit: (patch: Partial<GenerateSettings>) => void;+}++const toComponentModel = (model: ModelConfig | null): ComponentModelConfig | null =>+ isModelIdentifierConfig(model) ? model : null;++const getComponentPolicyContext = (model: GenerateModelConfig, settings: GenerateSettings): ComponentPolicyContext => ({+ model,+ settings,+ selectedComponents: {+ clipEmbedModel: settings.clipEmbedModel,+ clipGEmbedModel: settings.clipGEmbedModel,+ clipLEmbedModel: settings.clipLEmbedModel,+ componentSourceModel: settings.componentSourceModel,++ mistralEncoderModel: settings.mistralEncoderModel,+ qwen3EncoderModel: settings.qwen3EncoderModel,+ qwenVLEncoderModel: settings.qwenVLEncoderModel,+ qwen3VLEncoderModel: settings.qwen3VLEncoderModel,+ wanT5EncoderModel: settings.wanT5EncoderModel,+ wanLowNoiseModel: settings.wanLowNoiseModel,+ t5EncoderModel: settings.t5EncoderModel,+ pidDecoderModel: settings.pidDecoderModel,+ gemma2EncoderModel: settings.gemma2EncoderModel,+ vae: settings.vae,+ },+});++const ComponentPicker = ({+ ctx,+ onChange,+ slot,+}: {+ ctx: ComponentPolicyContext;+ onChange: (model: ModelConfig | null) => void;+ slot: ComponentSlotPolicy;+}) => {+ const value = ctx.selectedComponents[slot.key];+ const filter = useCallback((model: ModelConfig) => slot.filter?.(model, ctx) ?? false, [ctx, slot]);+ const modelTypes = useMemo(() => [...slot.modelTypes], [slot.modelTypes]);+ const selectedValue = value && (!filter || filter(value as ModelConfig)) ? value.key : null;++ return (+ <Field label={slot.label} helpText={slot.helpText}>+ <ModelSelect+ filter={slot.filter ? filter : undefined}+ isClearable+ modelTypes={modelTypes}+ placeholder={slot.placeholder ?? 'Model default'}+ size="xs"+ value={selectedValue}+ onChange={onChange}+ />+ </Field>+ );+};++export const GenerateComponentsSection = ({ onCommit, selectedModel, settings }: GenerateComponentsSectionProps) => {+ const { t } = useTranslation();+ const ctx = useMemo(+ () => (selectedModel ? getComponentPolicyContext(selectedModel, settings) : null),+ [selectedModel, settings]+ );++ const commitSlotValue = useCallback(+ (slot: ComponentSlotPolicy, model: ModelConfig | null) => {+ if (slot.valueKind === 'main') {+ onCommit({ [slot.key]: isMainModelConfig(model) ? model : null });+ return;+ }++ if (slot.valueKind === 'vae') {+ onCommit({ [slot.key]: isVaeModelConfig(model) ? model : null });+ return;+ }++ onCommit({ [slot.key]: toComponentModel(model) });+ },+ [onCommit]+ );++ if (!selectedModel || selectedModel.type === 'external_image_generator') {+ return null;+ }++ const policy = getComponentSectionPolicy(selectedModel, settings);++ if (policy.slots.length === 0) {+ return null;+ }++ return (+ <GenerateCollapsibleSection+ label={t('widgets.generate.components')}+ defaultOpen={policy.defaultOpen}+ sectionId="components"+ >+ <Stack gap="2" p="2">+ {policy.slots.map((slot) => (+ <ComponentPickerRow key={slot.key} commitSlotValue={commitSlotValue} ctx={ctx!} slot={slot} />+ ))}+ </Stack>+ </GenerateCollapsibleSection>+ );+};++const ComponentPickerRow = ({+ commitSlotValue,+ ctx,+ slot,+}: {+ commitSlotValue: (slot: ComponentSlotPolicy, model: ModelConfig | null) => void;+ ctx: ComponentPolicyContext;+ slot: ComponentSlotPolicy;+}) => {+ const onChange = useCallback((model: ModelConfig | null) => commitSlotValue(slot, model), [commitSlotValue, slot]);++ return <ComponentPicker ctx={ctx} slot={slot} onChange={onChange} />;+};diff --cc invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.tsindex f0288bd793,0000000000..fa1cf21f36mode 100644,000000..100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts@@@ -1,704 -1,0 +1,705 @@@+import type { GalleryImage } from '@features/gallery';+import type { GenerateWidgetValues } from '@features/generation/contracts';+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { CanvasEngine } from '@workbench/canvas-engine/engine';+import type { uploadCanvasImage } from '@workbench/canvas-operations/backend/canvasImages';+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import type { Project, WorkbenchState } from '@workbench/projectContracts';++import { accountLifecycle } from '@platform/state/accountLifecycle';+import {+ createControlLayer,+ createEmptyPaintLayer,+ createInpaintMaskFromImage,+ createRegionalGuidanceFromImage,+ createRegionalGuidanceLayerWithRefImage,+ DEFAULT_INPAINT_MASK_FILL,+ nextRegionalGuidanceFillColor,+} from '@workbench/widgets/layers/layerOps';+import { getProjectWidgetValues } from '@workbench/widgetState';+import { createInitialWorkbenchState, type WorkbenchAction } from '@workbench/workbenchState.testing';+import { describe, expect, it, vi } from 'vitest';++import { importGalleryImagesToCanvas, type GalleryCanvasImportDestination } from './importGalleryImages';++const queriesFor = (getState: () => WorkbenchState) => ({+ getProject: (projectId: string) => getState().projects.find((project) => project.id === projectId) ?? null,+ isActiveProject: (projectId: string) => getState().activeProjectId === projectId,+});++const image = (imageName: string, width = 320, height = 160): GalleryImage => ({+ boardId: 'none',+ height,+ imageCategory: 'general',+ imageName,+ imageUrl: `https://images.example/${imageName}`,+ queuedAt: '2026-01-01T00:00:00.000Z',+ sourceQueueItemId: 'queue-1',+ starred: false,+ thumbnailUrl: `https://images.example/thumb/${imageName}`,+ width,+});++const withProject = (mutate?: (project: Project) => Project): { project: Project; state: WorkbenchState } => {+ const state = createInitialWorkbenchState();+ const current = state.projects.find((candidate) => candidate.id === state.activeProjectId)!;+ const document = {+ ...current.canvas.document,+ bbox: { height: 512, width: 768, x: 31, y: 47 },+ layers: [createEmptyPaintLayer('Existing', 'previous')],+ selectedLayerId: 'previous',+ };+ const base = { ...current, canvas: { ...current.canvas, document } };+ const project = mutate ? mutate(base) : base;+ return { project, state: { ...state, projects: [project] } };+};++const setModel = (project: Project, base: GenerateWidgetValues['model']['base']): Project => {+ const generate = project.widgetInstances.generate;+ if (!generate) {+ throw new Error('Expected generate widget');+ }+ const previous = getProjectWidgetValues(project, 'generate');+ const model = { base, key: 'test-model', name: 'Test Model', type: 'main' } as GenerateWidgetValues['model'];+ const values: GenerateWidgetValues = {+ aspectRatioId: '1:1',+ aspectRatioIsLocked: false,+ aspectRatioValue: 1,+ batchCount: 1,+ cfgRescaleMultiplier: 0,+ cfgScale: 7,+ clipEmbedModel: null,+ clipGEmbedModel: null,+ clipLEmbedModel: null,+ clipSkip: 0,+ colorCompensation: false,+ hiDiffusionEnabled: false,+ hiDiffusionRauNetEnabled: true,+ hiDiffusionT1Ratio: 0.4,+ hiDiffusionT2Ratio: 0,+ hiDiffusionWindowAttentionEnabled: true,+ dynamicPromptsCombinatorial: true,+ dynamicPromptsMaxPrompts: 100,+ dynamicPromptsSampleSeed: 0,+ dynamicPromptsSeedBehaviour: 'per-iteration',+ componentSourceModel: null,+ height: 1024,+ loras: [],+ negativePrompt: '',+ negativePromptEnabled: true,+ negativePromptHeightPx: 56,+ positivePrompt: '',+ positivePromptHeightPx: 96,+ promptTemplate: null,+ promptTemplateViewMode: false,++ mistralEncoderModel: null,+ qwen3EncoderModel: null,+ qwenVLEncoderModel: null,+ qwen3VLEncoderModel: null,+ wanT5EncoderModel: null,+ wanLowNoiseModel: null,+ wanGuidanceScaleLowNoise: null,+ ideogram4SamplerPreset: 'V4_QUALITY_48',+ ideogram4Steps: null,+ ideogram4GuidanceScale: null,+ ideogram4Mu: null,+ ideogram4ColorPalette: [],+ krea2RebalanceEnabled: false,+ krea2RebalanceMultiplier: 4,+ krea2RebalanceWeights: '1.0,1.0,1.0,1.0,1.0,1.0,1.0,2.5,5.0,1.1,4.0,1.0',+ krea2SeedVarianceEnabled: false,+ krea2SeedVarianceStrength: 0.1,+ krea2SeedVarianceRandomizePercent: 50,+ pidMode: 'off',+ pidDecoderModel: null,+ gemma2EncoderModel: null,+ pidSteps: 4,+ referenceImages: [],+ scheduler: 'euler_a',+ seamlessXAxis: false,+ seamlessYAxis: false,+ seed: 1,+ shouldRandomizeSeed: true,+ steps: 30,+ t5EncoderModel: null,+ vae: null,+ vaePrecision: 'fp32',+ width: 1024,+ ...previous,+ model,+ modelKey: model.key,+ };+ return {+ ...project,+ widgetInstances: {+ ...project.widgetInstances,+ generate: {+ ...generate,+ state: { ...generate.state, values: values as unknown as Record<string, unknown> },+ },+ },+ };+};++const engine = (+ projectId: string,+ canCommitStructural: CanvasEngine['layers']['canCommitStructural'] = vi.fn(() => true),+ commitStructural: CanvasEngine['layers']['commitStructural'] = vi.fn(() => true)+): CanvasEngine => ({ layers: { canCommitStructural, commitStructural }, projectId }) as unknown as CanvasEngine;++const getForwardLayers = (action: WorkbenchAction | CanvasProjectMutation): readonly CanvasLayerContract[] => {+ const mutation = action.type === 'applyCanvasProjectMutation' ? action.mutation : action;+ if (mutation.type !== 'applyCanvasLayerStackMutation' || !mutation.add) {+ throw new Error('Expected add stack mutation');+ }+ return mutation.add.layers;+};++const expectedLayer = (+ destination: Exclude<GalleryCanvasImportDestination, 'control-resized'>,+ source: GalleryImage,+ index: number,+ bbox: Project['canvas']['document']['bbox'],+ base: string | null+): CanvasLayerContract => {+ const ref = { height: source.height, imageName: source.imageName, width: source.width };+ switch (destination) {+ case 'raster':+ return {+ blendMode: 'normal',+ id: expect.any(String) as string,+ isEnabled: true,+ isLocked: false,+ name: `Layer ${index + 1}`,+ opacity: 1,+ source: { image: ref, type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: bbox.x, y: bbox.y },+ type: 'raster',+ };+ case 'control':+ return {+ ...createControlLayer(`Control Layer ${index + 1}`, 'expected', base),+ id: expect.any(String) as string,+ source: { image: ref, type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: bbox.x, y: bbox.y },+ };+ case 'inpaint-mask':+ return createInpaintMaskFromImage({+ fill: DEFAULT_INPAINT_MASK_FILL,+ id: expect.any(String) as string,+ image: ref,+ name: `Inpaint Mask ${index + 1}`,+ rect: bbox,+ });+ case 'regional-guidance':+ return createRegionalGuidanceFromImage({+ fill: { color: nextRegionalGuidanceFillColor(index), style: 'solid' },+ id: expect.any(String) as string,+ image: ref,+ name: `Regional Guidance ${index + 1}`,+ rect: bbox,+ });+ case 'regional-reference': {+ const layer = createRegionalGuidanceLayerWithRefImage(`Regional Guidance ${index + 1}`, index, base);+ const reference = layer.referenceImages[0]!;+ return {+ ...layer,+ id: expect.any(String) as string,+ referenceImages: [+ { ...reference, config: { ...reference.config, image: source }, id: expect.any(String) as string },+ ],+ };+ }+ }+};++describe('importGalleryImagesToCanvas', () => {+ it.each<Exclude<GalleryCanvasImportDestination, 'control-resized'>>([+ 'raster',+ 'control',+ 'inpaint-mask',+ 'regional-guidance',+ 'regional-reference',+ ])('builds the %s destination contract in input order and commits one history entry', async (destination) => {+ const { project, state } = withProject((value) => setModel(value, 'z-image'));+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();+ const canvasEngine = engine(project.id);+ const images = [image('first.png'), image('second.png', 640, 480)];++ const result = await importGalleryImagesToCanvas({+ destination,+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),+ engine: canvasEngine,+ ...queriesFor(() => state),+ images,+ project,+ });++ expect(result.status).toBe('imported');+ if (result.status !== 'imported') {+ return;+ }+ expect(result.failedImageNames).toEqual([]);+ expect(dispatch).not.toHaveBeenCalled();+ expect(canvasEngine.layers.commitStructural).toHaveBeenCalledOnce();+ const [, forward, inverse] = vi.mocked(canvasEngine.layers.commitStructural).mock.calls[0]!;+ const layers = getForwardLayers(forward);+ expect(layers).toEqual(+ images.map((source, index) => expectedLayer(destination, source, index, project.canvas.document.bbox, 'z-image'))+ );+ expect(result.layerIds).toEqual(layers.map((layer) => layer.id));+ expect(forward).toMatchObject({+ add: { index: 0 },+ enabledUpdates: [],+ selectedLayerId: layers[1]!.id,+ type: 'applyCanvasLayerStackMutation',+ });+ expect(inverse).toEqual({+ enabledUpdates: [],+ removeIds: layers.map((layer) => layer.id),+ selectedLayerId: 'previous',+ type: 'applyCanvasLayerStackMutation',+ });+ });++ it('seeds new control layers with the default control model for the selected base', async () => {+ const { project, state } = withProject((value) => setModel(value, 'sd-1'));+ const canvasEngine = engine(project.id);+ const models = [+ { base: 'sd-1', key: 'sd1-canny', name: 'Canny', type: 'controlnet' },+ { base: 'sd-1', key: 'sd1-union', name: 'Union Pro', type: 'controlnet' },+ ] as unknown as Parameters<typeof importGalleryImagesToCanvas>[0]['models'];++ const result = await importGalleryImagesToCanvas({+ destination: 'control',+ applyCanvasMutation: vi.fn(),+ engine: canvasEngine,+ ...queriesFor(() => state),+ images: [image('a.png')],+ models,+ project,+ });++ expect(result.status).toBe('imported');+ const [, forward] = vi.mocked(canvasEngine.layers.commitStructural).mock.calls[0]!;+ const layer = getForwardLayers(forward)[0]!;+ expect(layer.type === 'control' ? layer.adapter.model : null).toBe('sd1-union');+ });++ it('fetches and uploads each resized control once with optimal model dimensions and durable hidden policy', async () => {+ const { project, state } = withProject((value) => setModel(value, 'flux2'));+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();+ const fetchImage = vi.fn<typeof fetch>(() => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })));+ const uploadImage = vi.fn<typeof uploadCanvasImage>((_blob, options) =>+ Promise.resolve({+ height: options!.resizeTo!.height,+ imageName: `resized-${options!.fileName}`,+ width: options!.resizeTo!.width,+ })+ );++ const result = await importGalleryImagesToCanvas({+ destination: 'control-resized',+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),+ engine: null,+ fetchImage,+ ...queriesFor(() => state),+ images: [image('wide.png', 1600, 900), image('square.png', 400, 400)],+ project,+ uploadImage,+ });++ expect(result.status).toBe('imported');+ expect(fetchImage.mock.calls.map(([url]) => url)).toEqual([+ 'https://images.example/wide.png',+ 'https://images.example/square.png',+ ]);+ expect(uploadImage).toHaveBeenCalledTimes(2);+ expect(uploadImage.mock.calls.map(([, options]) => options)).toEqual([+ expect.objectContaining({+ fileName: 'wide.png',+ imageCategory: 'other',+ isIntermediate: false,+ resizeTo: { height: 768, width: 1360 },+ }),+ expect.objectContaining({+ fileName: 'square.png',+ imageCategory: 'other',+ isIntermediate: false,+ resizeTo: { height: 1024, width: 1024 },+ }),+ ]);+ expect(dispatch).toHaveBeenCalledOnce();+ const forward = dispatch.mock.calls[0]![0];+ const layers = getForwardLayers(forward);+ expect(layers).toEqual([+ {+ ...createControlLayer('Control Layer 1', 'expected', 'flux2'),+ id: expect.any(String),+ source: { image: { height: 768, imageName: 'resized-wide.png', width: 1360 }, type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 31, y: 47 },+ },+ {+ ...createControlLayer('Control Layer 2', 'expected', 'flux2'),+ id: expect.any(String),+ source: { image: { height: 1024, imageName: 'resized-square.png', width: 1024 }, type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 31, y: 47 },+ },+ ]);+ expect(+ layers.map((layer) => (layer.type === 'control' && layer.source.type === 'image' ? layer.source.image : null))+ ).toEqual([+ { height: 768, imageName: 'resized-wide.png', width: 1360 },+ { height: 1024, imageName: 'resized-square.png', width: 1024 },+ ]);+ expect(forward).toMatchObject({+ mutation: {+ selectedLayerId: layers[1]!.id,+ type: 'applyCanvasLayerStackMutation',+ },+ projectId: project.id,+ type: 'applyCanvasProjectMutation',+ });+ });++ it('returns empty without committing', async () => {+ const { project, state } = withProject();+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();+ const result = await importGalleryImagesToCanvas({+ destination: 'raster',+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),+ engine: null,+ ...queriesFor(() => state),+ images: [],+ project,+ });+ expect(result).toEqual({ status: 'empty' });+ expect(dispatch).not.toHaveBeenCalled();+ });++ it('blocks a locked matching engine before resized preprocessing', async () => {+ const { project, state } = withProject();+ const fetchImage = vi.fn<typeof fetch>();+ const uploadImage = vi.fn<typeof uploadCanvasImage>();+ const result = await importGalleryImagesToCanvas({+ destination: 'control-resized',+ applyCanvasMutation: () => undefined,+ engine: engine(+ project.id,+ vi.fn(() => false)+ ),+ fetchImage,+ ...queriesFor(() => state),+ images: [image('a.png')],+ project,+ uploadImage,+ });+ expect(result).toEqual({ status: 'blocked' });+ expect(fetchImage).not.toHaveBeenCalled();+ expect(uploadImage).not.toHaveBeenCalled();+ });++ it('returns blocked when the matching engine locks during preprocessing', async () => {+ const { project, state } = withProject();+ const fetchImage = vi.fn<typeof fetch>(() => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })));+ const uploadImage = vi.fn<typeof uploadCanvasImage>(() =>+ Promise.resolve({ height: 512, imageName: 'resized', width: 512 })+ );+ const commitStructural = vi.fn<+ (_label: string, _forward: CanvasProjectMutation, _inverse: CanvasProjectMutation) => boolean+ >(() => false);+ const result = await importGalleryImagesToCanvas({+ destination: 'control-resized',+ applyCanvasMutation: () => undefined,+ engine: engine(+ project.id,+ vi.fn(() => true),+ commitStructural+ ),+ fetchImage,+ ...queriesFor(() => state),+ images: [image('a.png')],+ project,+ uploadImage,+ });+ expect(result).toEqual({ status: 'blocked' });+ expect(commitStructural).toHaveBeenCalledOnce();+ const [, forward, inverse] = commitStructural.mock.calls[0]!;+ const layers = getForwardLayers(forward);+ expect(inverse).toEqual({+ enabledUpdates: [],+ removeIds: layers.map((layer) => layer.id),+ selectedLayerId: 'previous',+ type: 'applyCanvasLayerStackMutation',+ });+ });++ it('returns stale-project when the target is deleted during preprocessing', async () => {+ const { project, state } = withProject();+ let current = state;+ const uploadImage = vi.fn<typeof uploadCanvasImage>(() => {+ current = { ...current, projects: [] };+ return Promise.resolve({ height: 512, imageName: 'resized', width: 512 });+ });+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();+ const result = await importGalleryImagesToCanvas({+ destination: 'control-resized',+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),+ engine: null,+ fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),+ ...queriesFor(() => current),+ images: [image('a.png')],+ project,+ uploadImage,+ });+ expect(result).toEqual({ status: 'stale-project' });+ expect(dispatch).not.toHaveBeenCalled();+ });++ it('dispatches to the captured project when the active project changes during preprocessing', async () => {+ const { project, state } = withProject();+ const other = { ...project, id: 'other-project' };+ let current = { ...state, projects: [project, other] };+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();+ const matchingEngine = engine(project.id);+ const uploadImage = vi.fn<typeof uploadCanvasImage>(() => {+ current = { ...current, activeProjectId: other.id };+ return Promise.resolve({ height: 512, imageName: 'resized', width: 512 });+ });+ const result = await importGalleryImagesToCanvas({+ destination: 'control-resized',+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),+ engine: matchingEngine,+ fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),+ ...queriesFor(() => current),+ images: [image('a.png')],+ project,+ uploadImage,+ });+ expect(result.status).toBe('imported');+ expect(matchingEngine.layers.commitStructural).not.toHaveBeenCalled();+ expect(dispatch).toHaveBeenCalledOnce();+ expect(dispatch.mock.calls[0]![0]).toMatchObject({ projectId: project.id });+ });++ it('uses the matching engine final guard when the target project becomes active during preprocessing', async () => {+ const { project, state } = withProject();+ const other = { ...project, id: 'other-project' };+ let current = { ...state, activeProjectId: other.id, projects: [project, other] };+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();+ const commitStructural = vi.fn(() => false);+ const matchingEngine = engine(+ project.id,+ vi.fn(() => true),+ commitStructural+ );+ const uploadImage = vi.fn<typeof uploadCanvasImage>(() => {+ current = { ...current, activeProjectId: project.id };+ return Promise.resolve({ height: 512, imageName: 'resized', width: 512 });+ });++ const result = await importGalleryImagesToCanvas({+ destination: 'control-resized',+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),+ engine: matchingEngine,+ fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),+ ...queriesFor(() => current),+ images: [image('a.png')],+ project,+ uploadImage,+ });++ expect(result).toEqual({ status: 'blocked' });+ expect(commitStructural).toHaveBeenCalledOnce();+ expect(dispatch).not.toHaveBeenCalled();+ });++ it('returns stale-document when the captured target document identity changes', async () => {+ const { project, state } = withProject();+ let current = state;+ const uploadImage = vi.fn<typeof uploadCanvasImage>(() => {+ current = {+ ...current,+ projects: current.projects.map((candidate) =>+ candidate.id === project.id+ ? { ...candidate, canvas: { ...candidate.canvas, document: { ...candidate.canvas.document } } }+ : candidate+ ),+ };+ return Promise.resolve({ height: 512, imageName: 'resized', width: 512 });+ });+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();+ const result = await importGalleryImagesToCanvas({+ destination: 'control-resized',+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),+ engine: null,+ fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),+ ...queriesFor(() => current),+ images: [image('a.png')],+ project,+ uploadImage,+ });+ expect(result).toEqual({ status: 'stale-document' });+ expect(dispatch).not.toHaveBeenCalled();+ });++ it('single-flights imports per project while allowing other projects', async () => {+ const first = withProject();+ const secondProject = { ...first.project, id: 'second-project' };+ const secondState = { ...first.state, activeProjectId: secondProject.id, projects: [secondProject] };+ let release!: () => void;+ const pending = new Promise<void>((resolve) => {+ release = resolve;+ });+ const fetchImage = vi.fn<typeof fetch>(async () => {+ await pending;+ return new Response(new Blob(['pixels']), { status: 200 });+ });+ const uploadImage = vi.fn<typeof uploadCanvasImage>(() =>+ Promise.resolve({ height: 512, imageName: 'resized', width: 512 })+ );+ const firstImport = importGalleryImagesToCanvas({+ destination: 'control-resized',+ applyCanvasMutation: () => undefined,+ engine: null,+ fetchImage,+ ...queriesFor(() => first.state),+ images: [image('a.png')],+ project: first.project,+ uploadImage,+ });+ const overlap = await importGalleryImagesToCanvas({+ destination: 'raster',+ applyCanvasMutation: () => undefined,+ engine: null,+ ...queriesFor(() => first.state),+ images: [image('b.png')],+ project: first.project,+ });+ const independent = await importGalleryImagesToCanvas({+ destination: 'raster',+ applyCanvasMutation: () => undefined,+ engine: null,+ ...queriesFor(() => secondState),+ images: [image('c.png')],+ project: secondProject,+ });+ expect(overlap).toEqual({ status: 'blocked' });+ expect(independent.status).toBe('imported');+ release();+ await firstImport;+ });++ it('does not upload an old account image after local preprocessing crosses an account switch', async () => {+ accountLifecycle.activate('user-a');+ const { project, state } = withProject();+ let resolveFetch: ((response: Response) => void) | undefined;+ const fetchImage = vi.fn<typeof fetch>(+ () =>+ new Promise((resolve) => {+ resolveFetch = resolve;+ })+ );+ const uploadImage = vi.fn<typeof uploadCanvasImage>(() =>+ Promise.resolve({ height: 512, imageName: 'must-not-upload', width: 512 })+ );+ const applyCanvasMutation = vi.fn();++ const oldImport = importGalleryImagesToCanvas({+ destination: 'control-resized',+ applyCanvasMutation,+ engine: null,+ fetchImage,+ ...queriesFor(() => state),+ images: [image('user-a.png')],+ project,+ uploadImage,+ });+ const signal = (fetchImage.mock.calls[0]?.[1] as RequestInit | undefined)?.signal;++ accountLifecycle.invalidate();+ accountLifecycle.activate('user-b');+ resolveFetch?.(new Response(new Blob(['user-a-pixels']), { status: 200 }));++ await expect(oldImport).rejects.toBeInstanceOf(AggregateError);+ expect(signal?.aborted).toBe(true);+ expect(uploadImage).not.toHaveBeenCalled();+ expect(applyCanvasMutation).not.toHaveBeenCalled();+ });++ it('bounds resized work at four, preserves successful order, and reports partial failures once', async () => {+ const { project, state } = withProject();+ let active = 0;+ let maximum = 0;+ const releases: Array<() => void> = [];+ const fetchImage = vi.fn<typeof fetch>(async (_input) => {+ active += 1;+ maximum = Math.max(maximum, active);+ await new Promise<void>((resolve) => {+ releases.push(resolve);+ });+ active -= 1;+ return new Response(new Blob(['pixels']), { status: 200 });+ });+ const uploadImage = vi.fn<typeof uploadCanvasImage>((_blob, options) => {+ if (options!.fileName === '2.png' || options!.fileName === '5.png') {+ return Promise.reject(new Error('resize failed'));+ }+ return Promise.resolve({ height: 512, imageName: `ok-${options!.fileName}`, width: 512 });+ });+ const dispatch = vi.fn<(action: WorkbenchAction) => void>();+ const importing = importGalleryImagesToCanvas({+ destination: 'control-resized',+ applyCanvasMutation: (projectId, mutation) =>+ dispatch({ mutation, projectId, type: 'applyCanvasProjectMutation' }),+ engine: null,+ fetchImage,+ ...queriesFor(() => state),+ images: Array.from({ length: 7 }, (_, index) => image(`${index}.png`)),+ project,+ uploadImage,+ });+ await vi.waitFor(() => expect(fetchImage).toHaveBeenCalledTimes(4));+ expect(maximum).toBe(4);+ releases.splice(0).forEach((resolve) => resolve());+ await vi.waitFor(() => expect(fetchImage).toHaveBeenCalledTimes(7));+ releases.splice(0).forEach((resolve) => resolve());+ const result = await importing;+ expect(result.status).toBe('imported');+ if (result.status !== 'imported') {+ return;+ }+ expect(result.failedImageNames).toEqual(['2.png', '5.png']);+ expect(dispatch).toHaveBeenCalledOnce();+ expect(+ getForwardLayers(dispatch.mock.calls[0]![0]).map((layer) =>+ layer.type === 'control' && layer.source.type === 'image' ? layer.source.image.imageName : null+ )+ ).toEqual(['ok-0.png', 'ok-1.png', 'ok-3.png', 'ok-4.png', 'ok-6.png']);+ });++ it('throws one AggregateError when every resized image fails and releases the project flight', async () => {+ const { project, state } = withProject();+ const options = {+ destination: 'control-resized' as const,+ applyCanvasMutation: () => undefined,+ engine: null,+ fetchImage: () => Promise.resolve(new Response(new Blob(['pixels']), { status: 200 })),+ ...queriesFor(() => state),+ images: [image('a.png'), image('b.png')],+ project,+ uploadImage: vi.fn<typeof uploadCanvasImage>(() => Promise.reject(new Error('failed'))),+ };+ await expect(importGalleryImagesToCanvas(options)).rejects.toBeInstanceOf(AggregateError);+ await expect(importGalleryImagesToCanvas({ ...options, destination: 'raster' })).resolves.toMatchObject({+ status: 'imported',+ });+ });+});diff --cc invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.tsindex bdfe4897a3,0000000000..bee1b8a2fcmode 100644,000000..100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts@@@ -1,673 -1,0 +1,698 @@@+import type { GalleryImage } from '@features/gallery';+import type {+ ComponentModelConfig,+ GenerateWidgetValues,+ MainModelConfig,+ VaeModelConfig,+} from '@features/generation/contracts';++import { describe, expect, it } from 'vitest';++import { buildImageRecallSettings, getImageRecallCapabilities } from './imageRecall';++const sdxlModel: MainModelConfig = { base: 'sdxl', key: 'sdxl-model', name: 'SDXL', type: 'main' };+const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };+const animaModel: MainModelConfig = { base: 'anima', key: 'anima-model', name: 'Anima', type: 'main' };+const krea2Model: MainModelConfig = { base: 'krea-2', key: 'krea2-model', name: 'Krea 2', type: 'main' };+const vaeModel: VaeModelConfig = { base: 'sd-1', key: 'vae-model', name: 'SD 1.5 VAE', type: 'vae' };+const qwenImageVae: VaeModelConfig = { base: 'qwen-image', key: 'qwen-vae', name: 'Qwen VAE', type: 'vae' };+const animaQwen3: ComponentModelConfig = {+ base: 'any',+ key: 'anima-qwen3',+ name: 'Anima Qwen3',+ type: 'qwen3_encoder',+ variant: 'qwen3_06b',+};++const mistralEncoder: ComponentModelConfig = {++ base: 'any',++ key: 'mistral',++ name: 'Mistral Encoder',++ type: 'mistral_encoder',++};+const qwenVLEncoder: ComponentModelConfig = {+ base: 'any',+ key: 'qwen-vl',+ name: 'Qwen VL',+ type: 'qwen_vl_encoder',+};++const createValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWidgetValues => ({+ aspectRatioId: '1:1',+ aspectRatioIsLocked: false,+ aspectRatioValue: 1,+ batchCount: 1,+ pidMode: 'off',+ pidDecoderModel: null,+ gemma2EncoderModel: null,+ pidSteps: 4,+ cfgRescaleMultiplier: 0,+ cfgScale: 7,+ clipEmbedModel: null,+ clipGEmbedModel: null,+ clipLEmbedModel: null,+ clipSkip: 0,+ colorCompensation: false,+ hiDiffusionEnabled: false,+ hiDiffusionRauNetEnabled: true,+ hiDiffusionT1Ratio: 0.4,+ hiDiffusionT2Ratio: 0,+ hiDiffusionWindowAttentionEnabled: true,+ dynamicPromptsCombinatorial: true,+ dynamicPromptsMaxPrompts: 100,+ dynamicPromptsSampleSeed: 0,+ dynamicPromptsSeedBehaviour: 'per-iteration',+ componentSourceModel: null,+ height: 1024,+ loras: [],+ model: sdxlModel,+ modelKey: sdxlModel.key,+ negativePromptEnabled: true,+ negativePrompt: '',+ negativePromptHeightPx: 56,+ positivePrompt: '',+ positivePromptHeightPx: 96,+ promptTemplate: null,+ promptTemplateViewMode: false,++ mistralEncoderModel: null,+ qwen3EncoderModel: null,+ qwenVLEncoderModel: null,+ qwen3VLEncoderModel: null,+ wanT5EncoderModel: null,+ wanLowNoiseModel: null,+ wanGuidanceScaleLowNoise: null,+ ideogram4SamplerPreset: 'V4_QUALITY_48',+ ideogram4Steps: null,+ ideogram4GuidanceScale: null,+ ideogram4Mu: null,+ ideogram4ColorPalette: [],+ krea2RebalanceEnabled: false,+ krea2RebalanceMultiplier: 4,+ krea2RebalanceWeights: '1.0,1.0,1.0,1.0,1.0,1.0,1.0,2.5,5.0,1.1,4.0,1.0',+ krea2SeedVarianceEnabled: false,+ krea2SeedVarianceStrength: 0.1,+ krea2SeedVarianceRandomizePercent: 50,+ referenceImages: [],+ scheduler: 'euler_a',+ seamlessXAxis: false,+ seamlessYAxis: false,+ seed: 123,+ shouldRandomizeSeed: true,+ steps: 30,+ t5EncoderModel: null,+ vae: null,+ vaePrecision: 'fp32',+ width: 1024,+ ...overrides,+});++const image: GalleryImage = {+ boardId: 'none',+ height: 770,+ imageCategory: 'general',+ imageName: 'image.png',+ imageUrl: '/image.png',+ queuedAt: '2026-06-12T00:00:00.000Z',+ sourceQueueItemId: 'backend-gallery',+ starred: false,+ thumbnailUrl: '/thumbnail.png',+ width: 513,+};++const metadata = {+ cfg_rescale_multiplier: 0.25,+ cfg_scale: 8,+ height: 770,+ model: { key: sd1Model.key },+ negative_prompt: null,+ positive_prompt: 'a recalled prompt',+ scheduler: 'euler',+ seamless_x: true,+ seed: 42,+ steps: 25,+ vae: { key: vaeModel.key },+ width: 513,+};++describe('image recall', () => {+ it.each(['all', 'remix', 'prompts'] as const)(+ 'clears the active template and view mode when %s recalls prompt metadata',+ (kind) => {+ const result = buildImageRecallSettings({+ currentValues: createValues({+ promptTemplate: {+ id: 'template-1',+ name: 'Cinematic',+ negativePrompt: 'lowres',+ positivePrompt: '{prompt}, cinematic',+ },+ promptTemplateViewMode: true,+ }),+ image,+ kind,+ metadata: { positive_prompt: 'a recalled prompt' },+ models: [],+ supportedModels: [],+ vaeModels: [],+ });++ expect(result?.values.promptTemplate).toBeNull();+ expect(result?.values.promptTemplateViewMode).toBe(false);+ }+ );++ it.each(['seed', 'dimensions', 'clipSkip'] as const)(+ 'preserves the active template and view mode when %s has no prompt metadata',+ (kind) => {+ const currentValues = createValues({+ ...(kind === 'clipSkip' ? { model: sd1Model, modelKey: sd1Model.key } : {}),+ promptTemplate: {+ id: 'template-1',+ name: 'Cinematic',+ negativePrompt: 'lowres',+ positivePrompt: '{prompt}, cinematic',+ },+ promptTemplateViewMode: true,+ });+ const result = buildImageRecallSettings({+ currentValues,+ image,+ kind,+ metadata: kind === 'seed' ? { seed: 42 } : kind === 'clipSkip' ? { clip_skip: 1 } : null,+ models: [],+ supportedModels: [],+ vaeModels: [],+ });++ expect(result?.values.promptTemplate).toEqual(currentValues.promptTemplate);+ expect(result?.values.promptTemplateViewMode).toBe(true);+ }+ );++ it('recalls supported image metadata into generate settings', () => {+ const result = buildImageRecallSettings({+ currentValues: createValues(),+ image,+ kind: 'all',+ metadata,+ models: [sd1Model, vaeModel],+ supportedModels: [sd1Model],+ vaeModels: [vaeModel],+ });++ expect(result?.values).toMatchObject({+ cfgRescaleMultiplier: 0.25,+ cfgScale: 8,+ clipSkip: 0,+ height: 768,+ modelKey: sd1Model.key,+ negativePrompt: '',+ positivePrompt: 'a recalled prompt',+ scheduler: 'euler',+ seamlessXAxis: true,+ seed: 42,+ shouldRandomizeSeed: false,+ steps: 25,+ width: 512,+ });+ expect(result?.values.vae).toEqual(vaeModel);+ expect(result?.fields).toContain('model');+ expect(result?.fields).toContain('vae');+ expect(result?.fields).toContain('prompts');+ expect(result?.fields).toContain('seed');+ });++ it('recalls reference images from metadata, re-targeting configs to the effective model', () => {+ // The metadata model is not installed, so the current SDXL model stays+ // selected and the Qwen reference config is rebuilt for SDXL.+ const result = buildImageRecallSettings({+ currentValues: createValues(),+ image,+ kind: 'all',+ metadata: {+ ref_images: [+ {+ id: 'ref-1',+ isEnabled: true,+ config: {+ image: {+ height: 770,+ imageName: 'reference.png',+ imageUrl: '/api/v1/images/i/reference.png/full',+ queuedAt: '2026-01-01T00:00:00.000Z',+ sourceQueueItemId: 'backend-gallery',+ thumbnailUrl: '/api/v1/images/i/reference.png/thumbnail',+ width: 513,+ },+ type: 'qwen_image_reference_image',+ },+ },+ ],+ },+ models: [],+ supportedModels: [sdxlModel],+ vaeModels: [],+ });++ expect(result?.values.referenceImages).toHaveLength(1);+ expect(result?.values.referenceImages[0]?.config).toMatchObject({+ image: { original: { image: { height: 770, image_name: 'reference.png', width: 513 } } },+ type: 'ip_adapter',+ });+ expect(result?.fields).toContain('referenceImages');+ });++ it('preserves canonical original and crop provenance from legacy metadata', () => {+ const crop = {+ box: { height: 256, width: 320, x: 12, y: 24 },+ image: { height: 256, image_name: 'crop.png', width: 320 },+ ratio: null,+ };+ const result = buildImageRecallSettings({+ currentValues: createValues(),+ image,+ kind: 'all',+ metadata: {+ ref_images: [+ {+ config: {+ image: {+ crop,+ original: { image: { height: 768, image_name: 'original.png', width: 512 } },+ },+ type: 'qwen_image_reference_image',+ },+ id: 'canonical-ref',+ isEnabled: false,+ },+ ],+ },+ models: [],+ supportedModels: [sdxlModel],+ vaeModels: [],+ });++ expect(result?.values.referenceImages[0]).toMatchObject({+ id: 'canonical-ref',+ isEnabled: false,+ config: {+ image: {+ crop,+ original: { image: { height: 768, image_name: 'original.png', width: 512 } },+ },+ },+ });+ });++ it('falls back to pre-v6 canvas ipAdapter metadata when ref_images has no valid entries', () => {+ const result = buildImageRecallSettings({+ currentValues: createValues(),+ image,+ kind: 'all',+ metadata: {+ canvas_v2_metadata: {+ referenceImages: {+ entities: [+ {+ id: 'legacy-canvas-ref',+ ipAdapter: {+ beginEndStepPct: [0.2, 0.9],+ clipVisionModel: 'ViT-G',+ image: { height: 512, image_name: 'legacy.png', width: 512 },+ method: 'composition',+ model: { base: 'sdxl', key: 'adapter', name: 'Adapter', type: 'ip_adapter' },+ type: 'ip_adapter',+ weight: 0.7,+ },+ isEnabled: false,+ },+ ],+ },+ },+ ref_images: [+ { id: 'invalid' },+ {+ config: { image: null, type: 'qwen_image_reference_image' },+ id: 'incomplete-direct-ref',+ isEnabled: true,+ },+ ],+ },+ models: [],+ supportedModels: [sdxlModel],+ vaeModels: [],+ });++ expect(result?.values.referenceImages).toHaveLength(1);+ expect(result?.values.referenceImages[0]).toMatchObject({+ id: 'legacy-canvas-ref',+ isEnabled: false,+ config: {+ image: { original: { image: { image_name: 'legacy.png' } } },+ type: 'ip_adapter',+ },+ });+ });++ it('prefers valid ref_images over canvas fallback entries', () => {+ const result = buildImageRecallSettings({+ currentValues: createValues(),+ image,+ kind: 'all',+ metadata: {+ canvas_v2_metadata: {+ referenceImages: {+ entities: [+ {+ id: 'fallback',+ ipAdapter: { image: { height: 1, image_name: 'fallback.png', width: 1 }, type: 'flux_redux' },+ },+ ],+ },+ },+ ref_images: [+ {+ config: {+ image: { height: 64, image_name: 'direct.png', width: 64 },+ type: 'qwen_image_reference_image',+ },+ id: 'direct',+ isEnabled: true,+ },+ ],+ },+ models: [],+ supportedModels: [sdxlModel],+ vaeModels: [],+ });++ expect(result?.values.referenceImages.map((referenceImage) => referenceImage.id)).toEqual(['direct']);+ });++ it('drops recalled reference images when the effective model does not support them', () => {+ const result = buildImageRecallSettings({+ currentValues: createValues({ model: animaModel, modelKey: animaModel.key }),+ image,+ kind: 'all',+ metadata: {+ positive_prompt: 'a recalled prompt',+ ref_images: [+ {+ id: 'ref-1',+ isEnabled: true,+ config: {+ image: {+ height: 770,+ imageName: 'reference.png',+ imageUrl: '/api/v1/images/i/reference.png/full',+ queuedAt: '2026-01-01T00:00:00.000Z',+ sourceQueueItemId: 'backend-gallery',+ thumbnailUrl: '/api/v1/images/i/reference.png/thumbnail',+ width: 513,+ },+ type: 'qwen_image_reference_image',+ },+ },+ ],+ },+ models: [],+ supportedModels: [animaModel],+ vaeModels: [],+ });++ expect(result?.fields).toContain('prompts');+ expect(result?.values.referenceImages).toEqual([]);+ expect(result?.fields).not.toContain('referenceImages');+ });++ it('remixes without changing the current seed state', () => {+ const result = buildImageRecallSettings({+ currentValues: createValues({ seed: 999, shouldRandomizeSeed: false }),+ image,+ kind: 'remix',+ metadata,+ models: [sd1Model],+ supportedModels: [sd1Model],+ vaeModels: [],+ });++ expect(result?.values.seed).toBe(999);+ expect(result?.values.shouldRandomizeSeed).toBe(false);+ expect(result?.values.positivePrompt).toBe('a recalled prompt');+ expect(result?.fields).not.toContain('seed');+ });++ it.each(['all', 'remix'] as const)('recalls valid HiDiffusion metadata for supported models with %s', (kind) => {+ const result = buildImageRecallSettings({+ currentValues: createValues(),+ image,+ kind,+ metadata: {+ hidiffusion: true,+ hidiffusion_raunet: false,+ hidiffusion_t1_ratio: 0.35,+ hidiffusion_t2_ratio: 0.15,+ hidiffusion_window_attn: true,+ model: { key: sd1Model.key },+ },+ models: [sd1Model],+ supportedModels: [sd1Model],+ vaeModels: [],+ });++ expect(result?.values).toMatchObject({+ hiDiffusionEnabled: true,+ hiDiffusionRauNetEnabled: false,+ hiDiffusionT1Ratio: 0.35,+ hiDiffusionT2Ratio: 0.15,+ hiDiffusionWindowAttentionEnabled: true,+ });+ expect(result?.fields).toContain('hiDiffusion');+ });++ it('ignores HiDiffusion metadata for unsupported models', () => {+ const result = buildImageRecallSettings({+ currentValues: createValues({ model: animaModel, modelKey: animaModel.key }),+ image,+ kind: 'all',+ metadata: {+ hidiffusion: true,+ hidiffusion_raunet: false,+ hidiffusion_t1_ratio: 0.35,+ hidiffusion_t2_ratio: 0.15,+ hidiffusion_window_attn: true,+ positive_prompt: 'keep the recall non-empty',+ },+ models: [],+ supportedModels: [animaModel],+ vaeModels: [],+ });++ expect(result?.values.hiDiffusionEnabled).toBe(false);+ expect(result?.fields).not.toContain('hiDiffusion');+ });++ it('uses actual image dimensions for Use Size', () => {+ const result = buildImageRecallSettings({+ currentValues: createValues(),+ image,+ kind: 'dimensions',+ metadata: null,+ models: [],+ supportedModels: [],+ vaeModels: [],+ });++ expect(result?.values.width).toBe(512);+ expect(result?.values.height).toBe(768);+ expect(result?.values.aspectRatioId).toBe('2:3');+ });++ it('only enables standalone CLIP skip when the current model supports it', () => {+ const sdxlCapabilities = getImageRecallCapabilities({+ currentValues: createValues({ model: sdxlModel, modelKey: sdxlModel.key }),+ image,+ metadata: { clip_skip: 3 },+ models: [],+ supportedModels: [],+ vaeModels: [],+ });+ const sd1Capabilities = getImageRecallCapabilities({+ currentValues: createValues({ model: sd1Model, modelKey: sd1Model.key }),+ image,+ metadata: { clip_skip: 3 },+ models: [],+ supportedModels: [],+ vaeModels: [],+ });++ expect(sdxlCapabilities.clipSkip).toBe(false);+ expect(sd1Capabilities.clipSkip).toBe(true);+ });++ it('enables recall actions for component-only metadata', () => {+ const capabilities = getImageRecallCapabilities({+ currentValues: createValues(),+ image,+ metadata: { qwen3_encoder: { key: animaQwen3.key } },+ models: [animaQwen3],+ supportedModels: [],+ vaeModels: [],+ });++ expect(capabilities.all).toBe(true);+ expect(capabilities.remix).toBe(true);+ });++ it('recalls required component models for component-based families', () => {+ const result = buildImageRecallSettings({+ currentValues: createValues({ model: sd1Model, modelKey: sd1Model.key }),+ image,+ kind: 'all',+ metadata: {+ height: 1024,+ model: { key: animaModel.key },+ qwen3_encoder: { key: animaQwen3.key },+ vae: { key: qwenImageVae.key },+ width: 1024,+ },+ models: [animaModel, animaQwen3, qwenImageVae],+ supportedModels: [animaModel],+ vaeModels: [qwenImageVae],+ });++ expect(result?.values.model).toBe(animaModel);+ expect(result?.values.qwen3EncoderModel).toBe(animaQwen3);+ expect(result?.values.vae).toBe(qwenImageVae);+ expect(result?.fields).toContain('components');+ });+++ it('recalls FLUX.2 [dev] Mistral encoder metadata', () => {++ const result = buildImageRecallSettings({++ currentValues: createValues(),++ image,++ kind: 'all',++ metadata: { mistral_encoder: { key: mistralEncoder.key } },++ models: [mistralEncoder],++ supportedModels: [],++ vaeModels: [],++ });++++ expect(result?.values.mistralEncoderModel).toBe(mistralEncoder);++ expect(result?.fields).toContain('components');++ });+++ it('clears component models when recalled metadata explicitly stores null', () => {+ const result = buildImageRecallSettings({+ currentValues: createValues({+ componentSourceModel: sd1Model,++ mistralEncoderModel: mistralEncoder,+ qwen3EncoderModel: animaQwen3,+ qwenVLEncoderModel: qwenVLEncoder,+ }),+ image,+ kind: 'all',+ metadata: {++ mistral_encoder: null,+ qwen3_encoder: null,+ qwen3_source: null,+ qwen_image_qwen_vl_encoder: null,+ },- models: [sd1Model, animaQwen3, qwenVLEncoder],++ models: [sd1Model, mistralEncoder, animaQwen3, qwenVLEncoder],+ supportedModels: [],+ vaeModels: [],+ });++ expect(result?.values.componentSourceModel).toBeNull();++ expect(result?.values.mistralEncoderModel).toBeNull();+ expect(result?.values.qwen3EncoderModel).toBeNull();+ expect(result?.values.qwenVLEncoderModel).toBeNull();+ expect(result?.fields).toContain('components');+ });++ describe('krea-2 conditioning rebalance', () => {+ const krea2Metadata = {+ krea2_rebalance_enabled: true,+ krea2_rebalance_multiplier: 6.5,+ krea2_rebalance_weights: '1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0',+ model: { key: krea2Model.key },+ };++ it('restores the curve and gain a Krea-2 image was generated with', () => {+ const result = buildImageRecallSettings({+ currentValues: createValues(),+ image,+ kind: 'all',+ metadata: krea2Metadata,+ models: [],+ supportedModels: [krea2Model],+ vaeModels: [],+ });++ expect(result?.values.krea2RebalanceEnabled).toBe(true);+ expect(result?.values.krea2RebalanceMultiplier).toBe(6.5);+ expect(result?.values.krea2RebalanceWeights).toBe('1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0');+ expect(result?.fields).toContain('krea2Rebalance');+ });++ it('recalls the rebalance on a remix too', () => {+ const result = buildImageRecallSettings({+ currentValues: createValues(),+ image,+ kind: 'remix',+ metadata: krea2Metadata,+ models: [],+ supportedModels: [krea2Model],+ vaeModels: [],+ });++ expect(result?.fields).toContain('krea2Rebalance');+ });++ it('ignores the rebalance when the recalled model is not Krea-2', () => {+ const result = buildImageRecallSettings({+ currentValues: createValues(),+ image,+ kind: 'all',+ metadata: { ...krea2Metadata, model: { key: sdxlModel.key } },+ models: [],+ supportedModels: [sdxlModel],+ vaeModels: [],+ });++ expect(result?.values.krea2RebalanceEnabled).toBe(false);+ expect(result?.fields).not.toContain('krea2Rebalance');+ });++ it('drops a weights string the backend would reject', () => {+ // The string is forwarded to the node verbatim, so a malformed blob must not+ // become a queued item that fails mid-generation.+ const result = buildImageRecallSettings({+ currentValues: createValues(),+ image,+ kind: 'all',+ metadata: { ...krea2Metadata, krea2_rebalance_weights: '0x10,1,1,1,1,1,1,1,1,1,1,1' },+ models: [],+ supportedModels: [krea2Model],+ vaeModels: [],+ });++ expect(result?.values.krea2RebalanceWeights).toBe(createValues().krea2RebalanceWeights);+ // The enabled flag and gain are still sound on their own.+ expect(result?.values.krea2RebalanceMultiplier).toBe(6.5);+ });++ it('offers recall for an image whose only recallable delta is the rebalance', () => {+ const capabilities = getImageRecallCapabilities({+ currentValues: createValues({ model: krea2Model }),+ image,+ metadata: { krea2_rebalance_enabled: true },+ models: [],+ supportedModels: [],+ vaeModels: [],+ });++ expect(capabilities.all).toBe(true);+ expect(capabilities.remix).toBe(true);+ });+ });+});diff --cc invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.tsindex c19cdc1a82,0000000000..4e2c9e0ee9mode 100644,000000..100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts@@@ -1,698 -1,0 +1,702 @@@+import type { GalleryImage } from '@features/gallery';+import type {+ ComponentModelConfig,+ GenerateModelConfig,+ GenerateWidgetValues,+ MainModelConfig,+ VaeModelConfig,+} from '@features/generation/contracts';++import {+ getCompatibleReferenceImages,+ getGenerationDimensions,+ getGenerationUiPolicy,+ getSettingsWithModelDefaults,+ isKnownScheduler,+ isVaeCompatibleWithGenerateModel,+ isValidKrea2RebalanceWeights,+ cloneGenerateWidgetValues,+ getModelDefaultVae,+ hasModelDefaultVae,+ isMainModelConfig,+ isModelIdentifierConfig,+ clampDimension,+ deriveAspectRatioId,+ normalizeReferenceImages,+ MAX_HIDIFFUSION_RATIO,+ MIN_HIDIFFUSION_T1_RATIO,+ SEED_MAX,+} from '@features/generation/settings';++export type ImageRecallKind = 'all' | 'remix' | 'prompts' | 'seed' | 'dimensions' | 'clipSkip';++export interface ImageRecallCapabilities {+ all: boolean;+ remix: boolean;+ prompts: boolean;+ seed: boolean;+ dimensions: boolean;+ clipSkip: boolean;+}++export const EMPTY_IMAGE_RECALL_CAPABILITIES: ImageRecallCapabilities = {+ all: false,+ clipSkip: false,+ dimensions: false,+ prompts: false,+ remix: false,+ seed: false,+};++type RecalledField =+ | 'model'+ | 'vae'+ | 'prompts'+ | 'seed'+ | 'size'+ | 'steps'+ | 'cfg'+ | 'scheduler'+ | 'seamless'+ | 'hiDiffusion'+ | 'clipSkip'+ | 'components'+ | 'referenceImages'+ | 'krea2Rebalance';++export interface ImageRecallResult {+ fields: RecalledField[];+ values: GenerateWidgetValues;+}++const isRecord = (value: unknown): value is Record<string, unknown> =>+ Boolean(value) && typeof value === 'object' && !Array.isArray(value);++const getRecord = (value: unknown, key: string): Record<string, unknown> | null => {+ if (!isRecord(value)) {+ return null;+ }++ const child = value[key];++ return isRecord(child) ? child : null;+};++const getString = (metadata: unknown, key: string): string | null => {+ if (!isRecord(metadata)) {+ return null;+ }++ const value = metadata[key];++ return typeof value === 'string' ? value : null;+};++const getNullableString = (metadata: unknown, key: string): string | null | undefined => {+ if (!isRecord(metadata)) {+ return undefined;+ }++ const value = metadata[key];++ if (value === null) {+ return null;+ }++ return typeof value === 'string' ? value : undefined;+};++const getBoolean = (metadata: unknown, key: string): boolean | null => {+ if (!isRecord(metadata)) {+ return null;+ }++ const value = metadata[key];++ return typeof value === 'boolean' ? value : null;+};++const getNumber = (metadata: unknown, key: string): number | null => {+ if (!isRecord(metadata)) {+ return null;+ }++ const value = metadata[key];++ return typeof value === 'number' && Number.isFinite(value) ? value : null;+};++const getInteger = (metadata: unknown, key: string): number | null => {+ const value = getNumber(metadata, key);++ return value !== null && Number.isInteger(value) ? value : null;+};++const getSeed = (metadata: unknown): number | null => {+ const seed = getInteger(metadata, 'seed');++ return seed !== null && seed >= 0 && seed <= SEED_MAX ? seed : null;+};++const getDimension = (metadata: unknown, key: 'height' | 'width', grid: number): number | null => {+ const dimension = getNumber(metadata, key);++ return dimension !== null && dimension >= 64 ? clampDimension(dimension, grid) : null;+};++const getImageDimension = (image: GalleryImage, key: 'height' | 'width', grid: number): number | null => {+ const dimension = image[key];++ return Number.isFinite(dimension) && dimension >= 64 ? clampDimension(dimension, grid) : null;+};++const getSteps = (metadata: unknown): number | null => {+ const steps = getInteger(metadata, 'steps');++ return steps !== null && steps >= 1 ? steps : null;+};++const getCfgScale = (metadata: unknown): number | null => {+ const cfgScale = getNumber(metadata, 'cfg_scale');++ return cfgScale !== null && cfgScale >= 1 ? cfgScale : null;+};++const getCfgRescaleMultiplier = (metadata: unknown): number | null => {+ const cfgRescaleMultiplier = getNumber(metadata, 'cfg_rescale_multiplier');++ return cfgRescaleMultiplier !== null && cfgRescaleMultiplier >= 0 && cfgRescaleMultiplier < 1+ ? cfgRescaleMultiplier+ : null;+};++const getScheduler = (metadata: unknown): string | null => {+ const scheduler = getString(metadata, 'scheduler');++ return scheduler !== null && isKnownScheduler(scheduler) ? scheduler : null;+};++const getClipSkip = (metadata: unknown): number | null => {+ const clipSkip = getInteger(metadata, 'clip_skip');++ return clipSkip !== null && clipSkip >= 0 ? clipSkip : null;+};++const getClipSkipMax = (model: GenerateModelConfig): number | null =>+ getGenerationUiPolicy(model, { cfgScale: 1 }).clipSkipMax;++const getHiDiffusionPatch = (+ metadata: unknown,+ model: GenerateModelConfig+): Partial<+ Pick<+ GenerateWidgetValues,+ | 'hiDiffusionEnabled'+ | 'hiDiffusionRauNetEnabled'+ | 'hiDiffusionT1Ratio'+ | 'hiDiffusionT2Ratio'+ | 'hiDiffusionWindowAttentionEnabled'+ >+> => {+ if (!getGenerationUiPolicy(model, { cfgScale: 1 }).hiDiffusionVisible) {+ return {};+ }++ const enabled = getBoolean(metadata, 'hidiffusion');+ const rauNetEnabled = getBoolean(metadata, 'hidiffusion_raunet');+ const windowAttentionEnabled = getBoolean(metadata, 'hidiffusion_window_attn');+ const t1Ratio = getNumber(metadata, 'hidiffusion_t1_ratio');+ const t2Ratio = getNumber(metadata, 'hidiffusion_t2_ratio');++ return {+ ...(enabled !== null ? { hiDiffusionEnabled: enabled } : {}),+ ...(rauNetEnabled !== null ? { hiDiffusionRauNetEnabled: rauNetEnabled } : {}),+ ...(windowAttentionEnabled !== null ? { hiDiffusionWindowAttentionEnabled: windowAttentionEnabled } : {}),+ ...(t1Ratio !== null && t1Ratio >= MIN_HIDIFFUSION_T1_RATIO && t1Ratio <= MAX_HIDIFFUSION_RATIO+ ? { hiDiffusionT1Ratio: t1Ratio }+ : {}),+ ...(t2Ratio !== null && t2Ratio >= 0 && t2Ratio <= MAX_HIDIFFUSION_RATIO ? { hiDiffusionT2Ratio: t2Ratio } : {}),+ };+};++const getImageSize = (+ image: GalleryImage,+ model: GenerateModelConfig+): Pick<GenerateWidgetValues, 'height' | 'width'> | null => {+ const grid = getGenerationDimensions(model).grid;+ const width = getImageDimension(image, 'width', grid);+ const height = getImageDimension(image, 'height', grid);++ return width !== null && height !== null ? { height, width } : null;+};++const getMetadataSize = (+ metadata: unknown,+ model: GenerateModelConfig+): Partial<Pick<GenerateWidgetValues, 'height' | 'width'>> => {+ const grid = getGenerationDimensions(model).grid;+ const width = getDimension(metadata, 'width', grid);+ const height = getDimension(metadata, 'height', grid);++ return {+ ...(width !== null ? { width } : {}),+ ...(height !== null ? { height } : {}),+ };+};++const getMetadataModelKey = (metadata: unknown, key: 'model' | 'vae'): string | null => {+ const model = getRecord(metadata, key);++ return typeof model?.key === 'string' ? model.key : null;+};++const getSupportedMetadataModel = (+ metadata: unknown,+ supportedModels: GenerateModelConfig[]+): GenerateModelConfig | null => {+ const modelKey = getMetadataModelKey(metadata, 'model');++ return modelKey ? (supportedModels.find((model) => model.key === modelKey) ?? null) : null;+};++const getModelFromMetadata = <T extends ComponentModelConfig>(+ metadata: unknown,+ key: string,+ models: readonly ComponentModelConfig[],+ guard: (model: unknown) => model is T+): T | null | undefined => {+ if (!isRecord(metadata) || !(key in metadata)) {+ return undefined;+ }++ if (metadata[key] === null) {+ return null;+ }++ const modelKey = getMetadataModelKey(metadata, key as 'model' | 'vae');++ if (!modelKey) {+ return undefined;+ }++ const model = models.find((candidate) => candidate.key === modelKey);++ return guard(model) ? model : undefined;+};++const getMetadataComponent = (+ metadata: unknown,+ key: string,+ models: readonly ComponentModelConfig[]+): ComponentModelConfig | null | undefined => getModelFromMetadata(metadata, key, models, isModelIdentifierConfig);++const getMetadataMainModel = (+ metadata: unknown,+ key: string,+ models: readonly ComponentModelConfig[]+): MainModelConfig | null | undefined => getModelFromMetadata(metadata, key, models, isMainModelConfig);++const getMetadataVae = (+ metadata: unknown,+ model: GenerateModelConfig,+ vaeModels: VaeModelConfig[]+): VaeModelConfig | null | undefined => {+ if (!isRecord(metadata) || !('vae' in metadata)) {+ return undefined;+ }++ if (metadata.vae === null) {+ return null;+ }++ const vaeKey = getMetadataModelKey(metadata, 'vae');++ if (!vaeKey) {+ return undefined;+ }++ const vae = vaeModels.find((vae) => vae.key === vaeKey);++ return vae && isVaeCompatibleWithGenerateModel(model, vae) ? vae : undefined;+};++const getPromptPatch = (+ metadata: unknown+): Partial<+ Pick<GenerateWidgetValues, 'negativePrompt' | 'positivePrompt' | 'promptTemplate' | 'promptTemplateViewMode'>+> => {+ const positivePrompt = getString(metadata, 'positive_prompt');+ const negativePrompt = getNullableString(metadata, 'negative_prompt');+ // Image metadata records the prompt the model was given, so it already has any+ // template baked in. Clearing the active template stops it wrapping the text a+ // second time on the next Invoke.+ const clearTemplate = positivePrompt !== null || negativePrompt !== undefined;++ return {+ ...(positivePrompt !== null ? { positivePrompt } : {}),+ ...(negativePrompt !== undefined ? { negativePrompt: negativePrompt ?? '' } : {}),+ ...(clearTemplate ? { promptTemplate: null, promptTemplateViewMode: false } : {}),+ };+};++const hasPrompt = (metadata: unknown): boolean => Object.keys(getPromptPatch(metadata)).length > 0;++/**+ * The prompts an image was generated with, for seeding a new prompt template.+ * These are the merged prompts — metadata records what the model was given — so+ * the template starts from the text that produced the image.+ */+export const getMetadataPrompts = (metadata: unknown): { negativePrompt: string; positivePrompt: string } => ({+ negativePrompt: getNullableString(metadata, 'negative_prompt') ?? '',+ positivePrompt: getString(metadata, 'positive_prompt') ?? '',+});++const hasMetadataSize = (metadata: unknown, model: GenerateModelConfig): boolean =>+ Object.keys(getMetadataSize(metadata, model)).length > 0;++const hasGenerationSettings = (metadata: unknown): boolean =>+ getSteps(metadata) !== null ||+ getCfgScale(metadata) !== null ||+ getCfgRescaleMultiplier(metadata) !== null ||+ getScheduler(metadata) !== null ||+ getBoolean(metadata, 'seamless_x') !== null ||+ getBoolean(metadata, 'seamless_y') !== null;++/**+ * Krea-2's conditioning rebalance, as written by `buildKrea2Graph`.+ *+ * Gated on the recalled model's base because the settings keys are family-specific, and+ * validated because `krea2RebalanceWeights` is forwarded to the node verbatim — a+ * metadata blob is not a trusted source for a string the backend will parse.+ */+const getMetadataKrea2Rebalance = (+ metadata: unknown,+ model: GenerateModelConfig | undefined+): Partial<GenerateWidgetValues> => {+ if (model?.base !== 'krea-2') {+ return {};+ }++ const enabled = getBoolean(metadata, 'krea2_rebalance_enabled');+ const multiplier = getNumber(metadata, 'krea2_rebalance_multiplier');+ const weights = getString(metadata, 'krea2_rebalance_weights');++ return {+ ...(enabled === null ? {} : { krea2RebalanceEnabled: enabled }),+ ...(multiplier === null ? {} : { krea2RebalanceMultiplier: multiplier }),+ ...(weights !== null && isValidKrea2RebalanceWeights(weights) ? { krea2RebalanceWeights: weights } : {}),+ };+};++const hasKrea2Rebalance = (metadata: unknown, model: GenerateModelConfig | undefined): boolean =>+ Object.keys(getMetadataKrea2Rebalance(metadata, model)).length > 0;++const hasComponentModels = (metadata: unknown, models: readonly ComponentModelConfig[]): boolean =>+ getMetadataMainModel(metadata, 'qwen3_source', models) !== undefined ||+ getMetadataMainModel(metadata, 'qwen_image_component_source', models) !== undefined ||++ getMetadataComponent(metadata, 'mistral_encoder', models) !== undefined ||+ getMetadataComponent(metadata, 'qwen3_encoder', models) !== undefined ||+ getMetadataComponent(metadata, 'qwen_image_qwen_vl_encoder', models) !== undefined;++export const getMetadataReferenceImages = (metadata: unknown) => {+ if (!isRecord(metadata)) {+ return [];+ }++ const direct = normalizeReferenceImages(metadata.ref_images).filter(+ (referenceImage) => referenceImage.config.image !== null+ );+ if (direct.length > 0) {+ return direct;+ }++ const canvasMetadata = getRecord(metadata, 'canvas_v2_metadata');+ const referenceImages = getRecord(canvasMetadata, 'referenceImages');+ const legacyEntities = referenceImages?.entities;+ if (!Array.isArray(legacyEntities)) {+ return [];+ }++ return normalizeReferenceImages(+ legacyEntities.map((entry) =>+ isRecord(entry) && isRecord(entry.ipAdapter)+ ? { config: entry.ipAdapter, id: entry.id, isEnabled: entry.isEnabled }+ : entry+ )+ ).filter((referenceImage) => referenceImage.config.image !== null);+};++const withDimensions = (+ values: GenerateWidgetValues,+ size: Partial<Pick<GenerateWidgetValues, 'height' | 'width'>>+): GenerateWidgetValues => {+ const width = size.width ?? values.width;+ const height = size.height ?? values.height;++ return {+ ...values,+ ...size,+ aspectRatioId: deriveAspectRatioId(width, height),+ aspectRatioValue: height > 0 ? width / height : 1,+ };+};++const getSupportedClipSkip = (metadata: unknown, model: GenerateModelConfig): number | null => {+ const clipSkip = getClipSkip(metadata);+ const clipSkipMax = getClipSkipMax(model);++ return clipSkip !== null && clipSkipMax !== null ? Math.min(clipSkipMax, clipSkip) : null;+};++export const getImageRecallCapabilities = ({+ currentValues,+ image,+ metadata,+ models,+ supportedModels,+ vaeModels,+}: {+ currentValues: GenerateWidgetValues;+ image: GalleryImage;+ metadata: unknown;+ supportedModels: GenerateModelConfig[];+ models: ComponentModelConfig[];+ vaeModels: VaeModelConfig[];+}): ImageRecallCapabilities => {+ const supportedMetadataModel = getSupportedMetadataModel(metadata, supportedModels);+ const clipSkipModel = supportedMetadataModel ?? currentValues.model;+ const hasVae = getMetadataVae(metadata, clipSkipModel, vaeModels) !== undefined;+ const hasClipSkip = getSupportedClipSkip(metadata, clipSkipModel) !== null;+ const hasHiDiffusion = Object.keys(getHiDiffusionPatch(metadata, clipSkipModel)).length > 0;+ const hasSeed = getSeed(metadata) !== null;+ const hasPrompts = hasPrompt(metadata);+ const hasSize = hasMetadataSize(metadata, currentValues.model);+ const hasSettings = hasGenerationSettings(metadata);+ const hasComponents = hasComponentModels(metadata, models);+ const hasReferenceImages = getMetadataReferenceImages(metadata).length > 0;+ const hasModel = supportedMetadataModel !== null;+ const hasRebalance = hasKrea2Rebalance(metadata, clipSkipModel);+ const hasAnyMetadata =+ hasModel ||+ hasVae ||+ hasPrompts ||+ hasSeed ||+ hasSize ||+ hasSettings ||+ hasHiDiffusion ||+ hasClipSkip ||+ hasComponents ||+ hasReferenceImages ||+ hasRebalance;+ const hasNonSeedMetadata =+ hasModel ||+ hasVae ||+ hasPrompts ||+ hasSize ||+ hasSettings ||+ hasHiDiffusion ||+ hasClipSkip ||+ hasComponents ||+ hasReferenceImages ||+ hasRebalance;++ return {+ all: hasAnyMetadata,+ clipSkip: getSupportedClipSkip(metadata, currentValues.model) !== null,+ dimensions: getImageSize(image, currentValues.model) !== null,+ prompts: hasPrompts,+ remix: hasNonSeedMetadata,+ seed: hasSeed,+ };+};++export const buildImageRecallSettings = ({+ currentValues,+ image,+ kind,+ metadata,+ supportedModels,+ models,+ vaeModels,+}: {+ currentValues: GenerateWidgetValues;+ image: GalleryImage;+ kind: ImageRecallKind;+ metadata: unknown;+ supportedModels: GenerateModelConfig[];+ models: ComponentModelConfig[];+ vaeModels: VaeModelConfig[];+}): ImageRecallResult | null => {+ const fields: RecalledField[] = [];+ let values: GenerateWidgetValues = cloneGenerateWidgetValues(currentValues);++ if (kind === 'all' || kind === 'remix') {+ const model = getSupportedMetadataModel(metadata, supportedModels);++ if (model) {+ const valuesWithModelDefaults = getSettingsWithModelDefaults(values, model);+ values = {+ ...valuesWithModelDefaults,+ model,+ ...(hasModelDefaultVae(model) ? { vae: getModelDefaultVae(model, vaeModels) } : {}),+ };+ fields.push('model');+ }++ const qwen3SourceModel = getMetadataMainModel(metadata, 'qwen3_source', models);+ const qwenImageSourceModel = getMetadataMainModel(metadata, 'qwen_image_component_source', models);+ const componentSourceModel = qwen3SourceModel !== undefined ? qwen3SourceModel : qwenImageSourceModel;++ const mistralEncoderModel = getMetadataComponent(metadata, 'mistral_encoder', models);+ const qwen3EncoderModel = getMetadataComponent(metadata, 'qwen3_encoder', models);+ const qwenVLEncoderModel = getMetadataComponent(metadata, 'qwen_image_qwen_vl_encoder', models);+ const componentPatch = {+ componentSourceModel: componentSourceModel !== undefined ? componentSourceModel : values.componentSourceModel,++ mistralEncoderModel: mistralEncoderModel !== undefined ? mistralEncoderModel : values.mistralEncoderModel,+ qwen3EncoderModel: qwen3EncoderModel !== undefined ? qwen3EncoderModel : values.qwen3EncoderModel,+ qwenVLEncoderModel: qwenVLEncoderModel !== undefined ? qwenVLEncoderModel : values.qwenVLEncoderModel,+ };++ if (+ componentPatch.componentSourceModel !== values.componentSourceModel ||++ componentPatch.mistralEncoderModel !== values.mistralEncoderModel ||+ componentPatch.qwen3EncoderModel !== values.qwen3EncoderModel ||+ componentPatch.qwenVLEncoderModel !== values.qwenVLEncoderModel+ ) {+ values = { ...values, ...componentPatch };+ fields.push('components');+ }++ const rebalancePatch = getMetadataKrea2Rebalance(metadata, values.model);++ if (Object.keys(rebalancePatch).length > 0) {+ values = { ...values, ...rebalancePatch };+ fields.push('krea2Rebalance');+ }++ const vae = getMetadataVae(metadata, values.model, vaeModels);++ if (vae !== undefined) {+ values = { ...values, vae };+ fields.push('vae');+ }++ // Recalled reference images must fit the effective model — when the+ // metadata model was not recalled (e.g. uninstalled), `values.model` is+ // still the current one and incompatible configs are re-targeted or dropped.+ const referenceImages = getCompatibleReferenceImages(getMetadataReferenceImages(metadata), values.model, models);++ if (referenceImages.length > 0) {+ values = { ...values, referenceImages };+ fields.push('referenceImages');+ }+ }++ if (kind === 'all' || kind === 'remix' || kind === 'prompts') {+ const promptPatch = getPromptPatch(metadata);++ if (Object.keys(promptPatch).length > 0) {+ values = { ...values, ...promptPatch };+ fields.push('prompts');+ }+ }++ if (kind === 'all' || kind === 'seed') {+ const seed = getSeed(metadata);++ if (seed !== null) {+ values = { ...values, seed, shouldRandomizeSeed: false };+ fields.push('seed');+ }+ }++ if (kind === 'dimensions') {+ const size = getImageSize(image, values.model);++ if (size) {+ values = withDimensions(values, size);+ fields.push('size');+ }+ } else if (kind === 'all' || kind === 'remix') {+ const size = getMetadataSize(metadata, values.model);++ if (Object.keys(size).length > 0) {+ values = withDimensions(values, size);+ fields.push('size');+ }+ }++ if (kind === 'all' || kind === 'remix') {+ const steps = getSteps(metadata);+ const cfgScale = getCfgScale(metadata);+ const cfgRescaleMultiplier = getCfgRescaleMultiplier(metadata);+ const scheduler = getScheduler(metadata);+ const seamlessXAxis = getBoolean(metadata, 'seamless_x');+ const seamlessYAxis = getBoolean(metadata, 'seamless_y');++ if (steps !== null) {+ values = { ...values, steps };+ fields.push('steps');+ }++ if (cfgScale !== null || cfgRescaleMultiplier !== null) {+ values = {+ ...values,+ ...(cfgScale !== null ? { cfgScale } : {}),+ ...(cfgRescaleMultiplier !== null ? { cfgRescaleMultiplier } : {}),+ };+ fields.push('cfg');+ }++ if (scheduler !== null) {+ values = { ...values, scheduler };+ fields.push('scheduler');+ }++ if (seamlessXAxis !== null || seamlessYAxis !== null) {+ values = {+ ...values,+ ...(seamlessXAxis !== null ? { seamlessXAxis } : {}),+ ...(seamlessYAxis !== null ? { seamlessYAxis } : {}),+ };+ fields.push('seamless');+ }++ const hiDiffusionPatch = getHiDiffusionPatch(metadata, values.model);++ if (Object.keys(hiDiffusionPatch).length > 0) {+ values = { ...values, ...hiDiffusionPatch };+ fields.push('hiDiffusion');+ }+ }++ if (kind === 'all' || kind === 'remix' || kind === 'clipSkip') {+ const clipSkip = getSupportedClipSkip(metadata, values.model);++ if (clipSkip !== null) {+ values = { ...values, clipSkip };+ fields.push('clipSkip');+ }+ }++ return fields.length > 0 ? { fields, values } : null;+};++export const getImageRecallTitle = (kind: ImageRecallKind): string => {+ switch (kind) {+ case 'all':+ return 'Recalled image metadata';+ case 'remix':+ return 'Recalled remix settings';+ case 'prompts':+ return 'Recalled prompts';+ case 'seed':+ return 'Recalled seed';+ case 'dimensions':+ return 'Recalled image size';+ case 'clipSkip':+ return 'Recalled CLIP skip';+ }+};++export const getImageRecallMessage = (fields: RecalledField[]): string =>+ `${fields.length} field${fields.length === 1 ? '' : 's'} applied to Generate.`;diff --cc invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex d323951acf,0000000000..4f5c1041ecmode 100644,000000..100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@@ -1,4281 -1,0 +1,4282 @@@+import type { GalleryImageItem, GalleryVideoItem, GeneratedImageContract } from '@features/gallery';+import type { GenerateWidgetValues, MainModelConfig } from '@features/generation/contracts';+import type {+ CanvasControlLayerContract,+ CanvasInpaintMaskLayerContract,+ CanvasLayerContract,+ CanvasRasterLayerContractV2,+ CanvasStagingCandidateContract,+} from '@workbench/canvas-engine/contracts';+import type { GraphContract } from '@workbench/graphContracts';+import type { Project, WorkbenchState } from '@workbench/projectContracts';++import { GALLERY_RECENT_IMAGE_LIMIT, legacyGeneratedImageToGalleryItem } from '@features/gallery/contracts';+import { MAX_PROMPT_HISTORY } from '@features/generation/settings';+import { describe, expect, it, vi } from 'vitest';++import type { CanvasProjectMutation } from './canvasProjectMutations';++import { createEmptyCanvasDocumentV2 } from './canvasMigration';+import { getCanvasStagingCandidateFingerprint, getCanvasStagingSlots } from './canvasStagingView';+import { DEFAULT_PROJECT_SETTINGS } from './settings/store';+import { getProjectWidgetValues } from './widgetState';+import { GRAPH_HISTORY_BYTE_BUDGET, normalizeGraphHistory } from './workbenchState';+import {+ createInitialWorkbenchState,+ nextLayerName,+ type WorkbenchAction,+ workbenchReducer as reduceWorkbench,+} from './workbenchState.testing';++type LegacyCanvasMutation = CanvasProjectMutation & { projectId?: string };+const CANVAS_MUTATION_TYPES = new Set<CanvasProjectMutation['type']>([+ 'commitStagedImage',+ 'addCanvasLayer',+ 'applyCanvasLayerStackMutation',+ 'clearCanvasStaging',+ 'convertCanvasLayer',+ 'cycleStagedImage',+ 'deleteCanvasSnapshot',+ 'discardAllStagedImages',+ 'discardSelectedStagedImage',+ 'duplicateCanvasLayer',+ 'mergeCanvasLayersDown',+ 'removeCanvasLayers',+ 'reorderCanvasLayers',+ 'replaceCanvasDocument',+ 'replaceCanvasLayer',+ 'rollbackStagedImageCommit',+ 'resizeCanvasDocument',+ 'restoreCanvasSnapshot',+ 'saveCanvasSnapshot',+ 'setCanvasBbox',+ 'setCanvasLayersEnabled',+ 'setCanvasLayersHidden',+ 'setCanvasSelectedLayer',+ 'setCanvasStagingAutoSwitch',+ 'setStagedImageIndex',+ 'toggleCanvasStagingThumbnailsVisibility',+ 'toggleCanvasStagingVisibility',+ 'updateCanvasLayer',+ 'updateCanvasLayerConfig',+ 'updateCanvasLayerSource',+]);++const workbenchReducer = (state: WorkbenchState, action: WorkbenchAction | LegacyCanvasMutation): WorkbenchState => {+ if (CANVAS_MUTATION_TYPES.has(action.type as CanvasProjectMutation['type'])) {+ const { projectId = state.activeProjectId, ...mutation } = action as LegacyCanvasMutation;+ return reduceWorkbench(state, {+ mutation: mutation as CanvasProjectMutation,+ projectId,+ type: 'applyCanvasProjectMutation',+ });+ }+ return reduceWorkbench(state, action as WorkbenchAction);+};++const commitSelectedStagedImage = (state: WorkbenchState, projectId = state.activeProjectId): WorkbenchState => {+ const project = state.projects.find((candidate) => candidate.id === projectId);+ const slot = project+ ? getCanvasStagingSlots(project.canvas, project.queue.items)[project.canvas.stagingArea.selectedImageIndex]+ : undefined;+ if (!project || slot?.kind !== 'candidate') {+ return state;+ }+ const candidate = slot.candidate;+ const { placement } = candidate;+ const layer: CanvasRasterLayerContractV2 = {+ blendMode: 'normal',+ id: `accepted-${candidate.imageName}`,+ isEnabled: true,+ isLocked: false,+ name: `Layer ${project.canvas.document.layers.length + 1}`,+ opacity: placement.opacity,+ source: {+ image: { height: candidate.height, imageName: candidate.imageName, width: candidate.width },+ type: 'image',+ },+ transform: {+ rotation: 0,+ scaleX: candidate.width === 0 ? 1 : placement.width / candidate.width,+ scaleY: candidate.height === 0 ? 1 : placement.height / candidate.height,+ x: placement.x,+ y: placement.y,+ },+ type: 'raster',+ };+ return reduceWorkbench(state, {+ mutation: {+ candidateFingerprint: getCanvasStagingCandidateFingerprint(candidate),+ event: {+ createdAt: '2026-07-16T00:00:00.000Z',+ id: `event-${candidate.imageName}`,+ summary: `Accepted ${candidate.imageName} into a new raster layer`,+ type: 'canvas-layer-accepted',+ },+ layer,+ selectedImageIndex: project.canvas.stagingArea.selectedImageIndex,+ type: 'commitStagedImage',+ },+ projectId,+ type: 'applyCanvasProjectMutation',+ });+};++const model: MainModelConfig = {+ base: 'sdxl',+ key: 'test-model',+ name: 'Test Model',+ type: 'main',+};++const createGenerateValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWidgetValues => ({+ aspectRatioId: '1:1',+ aspectRatioIsLocked: false,+ aspectRatioValue: 1,+ batchCount: 1,+ pidMode: 'off',+ pidDecoderModel: null,+ gemma2EncoderModel: null,+ pidSteps: 4,+ cfgRescaleMultiplier: 0,+ cfgScale: 7,+ clipEmbedModel: null,+ clipGEmbedModel: null,+ clipLEmbedModel: null,+ clipSkip: 0,+ colorCompensation: false,+ hiDiffusionEnabled: false,+ hiDiffusionRauNetEnabled: true,+ hiDiffusionT1Ratio: 0.4,+ hiDiffusionT2Ratio: 0,+ hiDiffusionWindowAttentionEnabled: true,+ dynamicPromptsCombinatorial: true,+ dynamicPromptsMaxPrompts: 100,+ dynamicPromptsSampleSeed: 0,+ dynamicPromptsSeedBehaviour: 'per-iteration',+ componentSourceModel: null,+ height: 1024,+ loras: [],+ model,+ modelKey: model.key,+ negativePromptEnabled: true,+ negativePrompt: '',+ negativePromptHeightPx: 56,+ positivePrompt: 'first prompt',+ positivePromptHeightPx: 96,+ promptTemplate: null,+ promptTemplateViewMode: false,++ mistralEncoderModel: null,+ qwen3EncoderModel: null,+ qwenVLEncoderModel: null,+ qwen3VLEncoderModel: null,+ wanT5EncoderModel: null,+ wanLowNoiseModel: null,+ wanGuidanceScaleLowNoise: null,+ ideogram4SamplerPreset: 'V4_QUALITY_48',+ ideogram4Steps: null,+ ideogram4GuidanceScale: null,+ ideogram4Mu: null,+ ideogram4ColorPalette: [],+ krea2RebalanceEnabled: false,+ krea2RebalanceMultiplier: 4,+ krea2RebalanceWeights: '1.0,1.0,1.0,1.0,1.0,1.0,1.0,2.5,5.0,1.1,4.0,1.0',+ krea2SeedVarianceEnabled: false,+ krea2SeedVarianceStrength: 0.1,+ krea2SeedVarianceRandomizePercent: 50,+ referenceImages: [],+ scheduler: 'euler_a',+ seamlessXAxis: false,+ seamlessYAxis: false,+ seed: 123,+ shouldRandomizeSeed: false,+ steps: 30,+ t5EncoderModel: null,+ vae: null,+ vaePrecision: 'fp32',+ width: 1024,+ ...overrides,+});++const createImage = (imageName: string, sourceQueueItemId: string): GeneratedImageContract => ({+ height: 768,+ imageName,+ imageUrl: `/api/v1/images/i/${imageName}/full`,+ queuedAt: '2026-06-09T00:00:00.000Z',+ sourceQueueItemId,+ thumbnailUrl: `/api/v1/images/i/${imageName}/thumbnail`,+ width: 512,+});++const createGalleryImageItem = (name: string, boardId = 'none'): GalleryImageItem => ({+ boardId,+ category: 'general',+ createdAt: '2026-07-30T00:00:00.000Z',+ fullUrl: `/api/v1/images/i/${name}/full`,+ height: 768,+ isIntermediate: false,+ kind: 'image',+ name,+ sourceQueueItemId: 'backend-gallery',+ starred: false,+ thumbnailUrl: `/api/v1/images/i/${name}/thumbnail`,+ width: 512,+});++const createGalleryVideoItem = (name: string, boardId = 'none'): GalleryVideoItem => ({+ ...createGalleryImageItem(name, boardId),+ durationSeconds: 3,+ fullUrl: `/api/v1/videos/i/${name}/full`,+ kind: 'video',+ thumbnailUrl: `/api/v1/videos/i/${name}/thumbnail`,+});++const galleryItemToRecentImage = (item: GalleryImageItem): GeneratedImageContract & { boardId: string } => ({+ boardId: item.boardId,+ height: item.height,+ imageName: item.name,+ imageUrl: item.fullUrl,+ queuedAt: item.createdAt,+ sourceQueueItemId: item.sourceQueueItemId ?? 'backend-gallery',+ thumbnailUrl: item.thumbnailUrl,+ width: item.width,+});++const createStagingCandidate = (+ imageName: string,+ sourceQueueItemId: string,+ placement: CanvasStagingCandidateContract['placement']+): CanvasStagingCandidateContract => ({+ ...createImage(imageName, sourceQueueItemId),+ placement,+});++const getProject = (state: WorkbenchState, projectId: string): Project => {+ const project = state.projects.find((candidate) => candidate.id === projectId);++ expect(project).toBeDefined();++ return project as Project;+};++const getActiveProject = (state: WorkbenchState): Project => getProject(state, state.activeProjectId);++type CanvasLayer = Project['canvas']['document']['layers'][number];++const getRasterLayerImageName = (layer: CanvasLayer | undefined): string | undefined =>+ layer?.type === 'raster' && layer.source.type === 'image' ? layer.source.image.imageName : undefined;++/** Reconstructs a v1-style `{x,y,width,height,opacity}` placement from a v2 raster layer's transform, mirroring `CanvasWidgetView`'s rendering math. */+const getRasterLayerPlacement = (layer: CanvasLayer | undefined) => {+ if (!layer || layer.type !== 'raster' || layer.source.type !== 'image') {+ return undefined;+ }++ const { image } = layer.source;++ return {+ height: image.height * layer.transform.scaleY,+ opacity: layer.opacity,+ width: image.width * layer.transform.scaleX,+ x: layer.transform.x,+ y: layer.transform.y,+ };+};++const createRasterLayer = (id: string, imageName = `${id}.png`): CanvasRasterLayerContractV2 => ({+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ opacity: 1,+ source: { image: { height: 64, imageName, width: 64 }, type: 'image' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+});++const createControlLayer = (id: string): CanvasControlLayerContract => ({+ adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ name: id,+ opacity: 1,+ source: { bitmap: null, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'control',+ withTransparencyEffect: false,+});++const createInpaintMaskLayer = (id: string): CanvasLayerContract =>+ ({+ blendMode: 'normal',+ id,+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: null, fill: { color: '#e07575', style: 'diagonal' } },+ name: id,+ opacity: 1,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'inpaint_mask',+ }) as CanvasLayerContract;++/** Adds layers top-to-bottom in array order (each `addCanvasLayer` inserts at index 0). */+// A new project's canvas now seeds one empty inpaint mask (see+// `createNewCanvasStateV2`). These layer-reducer/staging tests exercise layer+// mechanics where that default mask is incidental, so they start from an empty+// canvas document to keep their expectations focused on the layers under test.+const withEmptyCanvas = (state: WorkbenchState): WorkbenchState =>+ workbenchReducer(state, { document: createEmptyCanvasDocumentV2(), type: 'replaceCanvasDocument' });++const withCanvasLayers = (state: WorkbenchState, layers: Project['canvas']['document']['layers']): WorkbenchState =>+ [...layers]+ .reverse()+ .reduce((next, layer) => workbenchReducer(next, { layer, type: 'addCanvasLayer' }), withEmptyCanvas(state));++const getCanvas = (state: WorkbenchState) => getActiveProject(state).canvas;++const getLayerIds = (state: WorkbenchState): string[] => getCanvas(state).document.layers.map((layer) => layer.id);++const primeGenerate = (state = createInitialWorkbenchState(), overrides: Partial<GenerateWidgetValues> = {}) =>+ workbenchReducer(state, { type: 'setGenerateSettings', values: createGenerateValues(overrides) });++const submitGenerate = (state: WorkbenchState) =>+ workbenchReducer(state, { backendSupportsCancellation: true, type: 'submitInvocationSnapshot' });++describe('workbench widget region defaults', () => {+ it('enables Diagnostics in the right side panel rail', () => {+ const state = createInitialWorkbenchState();++ expect(getActiveProject(state).widgetRegions.right.instanceIds).toContain('diagnostics');+ });++ it('hydrates the old default right rail with Diagnostics while preserving customized rails', () => {+ const initial = createInitialWorkbenchState();+ const legacyDefault = {+ ...initial,+ projects: initial.projects.map((project) => ({+ ...project,+ widgetRegions: {+ ...project.widgetRegions,+ right: { ...project.widgetRegions.right, instanceIds: ['queue', 'gallery', 'layers'] },+ },+ })),+ } satisfies WorkbenchState;+ const customized = {+ ...initial,+ projects: initial.projects.map((project) => ({+ ...project,+ widgetRegions: {+ ...project.widgetRegions,+ right: { ...project.widgetRegions.right, instanceIds: ['gallery', 'layers'] },+ },+ })),+ } satisfies WorkbenchState;++ const hydratedLegacyDefault = workbenchReducer(initial, { state: legacyDefault, type: 'hydrateWorkbench' });+ const hydratedCustomized = workbenchReducer(initial, { state: customized, type: 'hydrateWorkbench' });++ expect(getActiveProject(hydratedLegacyDefault).widgetRegions.right.instanceIds).toEqual([+ 'gallery',+ 'preview',+ 'queue',+ 'layers',+ 'diagnostics',+ 'project',+ ]);+ expect(getActiveProject(hydratedCustomized).widgetRegions.right.instanceIds).toEqual(['gallery', 'layers']);+ });++ it('adds Upscale to untouched legacy left rails while preserving customized rails', () => {+ const initial = createInitialWorkbenchState();+ const withoutUpscaleInstance = Object.fromEntries(+ Object.entries(getActiveProject(initial).widgetInstances).filter(([id]) => id !== 'upscale')+ ) as Project['widgetInstances'];+ const withLeftIds = (instanceIds: Project['widgetRegions']['left']['instanceIds']): WorkbenchState => ({+ ...initial,+ projects: initial.projects.map((project) => ({+ ...project,+ widgetInstances: withoutUpscaleInstance,+ widgetRegions: { ...project.widgetRegions, left: { ...project.widgetRegions.left, instanceIds } },+ })),+ });++ const migrated = workbenchReducer(initial, {+ state: withLeftIds(['generate', 'workflow']),+ type: 'hydrateWorkbench',+ });+ const customized = workbenchReducer(initial, {+ state: withLeftIds(['generate', 'gallery']),+ type: 'hydrateWorkbench',+ });++ expect(getActiveProject(migrated).widgetRegions.left.instanceIds).toEqual(['generate', 'workflow', 'upscale']);+ expect(getActiveProject(migrated).widgetInstances.upscale?.typeId).toBe('upscale');+ expect(getActiveProject(customized).widgetRegions.left.instanceIds).toEqual(['generate', 'gallery']);+ });++ it('migrates a legacy Upscale prompt only when Generate has no prompt content', () => {+ const initial = createInitialWorkbenchState();+ const withPrompts = (generatePrompt: string): WorkbenchState => ({+ ...initial,+ projects: initial.projects.map((project) => {+ const generate = project.widgetInstances.generate!;+ const upscale = project.widgetInstances.upscale!;++ return {+ ...project,+ widgetInstances: {+ ...project.widgetInstances,+ generate: {+ ...generate,+ state: { ...generate.state, values: { ...generate.state.values, positivePrompt: generatePrompt } },+ },+ upscale: {+ ...upscale,+ state: {+ ...upscale.state,+ values: {+ ...upscale.state.values,+ negativePrompt: 'legacy negative',+ negativePromptEnabled: false,+ positivePrompt: 'legacy positive',+ },+ },+ },+ },+ };+ }),+ });++ const migrated = workbenchReducer(initial, { state: withPrompts(''), type: 'hydrateWorkbench' });+ const preserved = workbenchReducer(initial, { state: withPrompts('generate positive'), type: 'hydrateWorkbench' });++ expect(getProjectWidgetValues(getActiveProject(migrated), 'generate')).toMatchObject({+ negativePrompt: 'legacy negative',+ negativePromptEnabled: false,+ positivePrompt: 'legacy positive',+ });+ expect(getProjectWidgetValues(getActiveProject(migrated), 'upscale')).toMatchObject({+ negativePrompt: '',+ negativePromptEnabled: true,+ positivePrompt: '',+ });+ expect(getProjectWidgetValues(getActiveProject(preserved), 'generate')).toMatchObject({+ positivePrompt: 'generate positive',+ });+ });+});++describe('workbench widget region opening', () => {+ it('enables and selects a center widget without toggling it back off', () => {+ let state = createInitialWorkbenchState();+ const activeProject = getActiveProject(state);+ const instanceIds: Project['widgetRegions']['center']['instanceIds'] = ['canvas'];++ state = {+ ...state,+ projects: state.projects.map((project) =>+ project.id === activeProject.id+ ? {+ ...project,+ widgetRegions: {+ ...project.widgetRegions,+ center: {+ ...project.widgetRegions.center,+ activeInstanceId: 'canvas',+ instanceIds,+ },+ },+ }+ : project+ ),+ };++ state = workbenchReducer(state, { region: 'center', type: 'openRegionWidget', widgetId: 'preview' });++ expect(getActiveProject(state).widgetRegions.center.activeInstanceId).toBe('preview');+ expect(getActiveProject(state).widgetRegions.center.instanceIds).toEqual(['canvas', 'preview']);++ state = workbenchReducer(state, { region: 'center', type: 'openRegionWidget', widgetId: 'preview' });++ expect(getActiveProject(state).widgetRegions.center.activeInstanceId).toBe('preview');+ expect(getActiveProject(state).widgetRegions.center.instanceIds).toEqual(['canvas', 'preview']);+ expect(getActiveProject(state).widgetRegions.center.isCollapsed).toBe(false);+ });++ it('opens and uncollapses the target panel region', () => {+ let state = createInitialWorkbenchState();+ const activeProject = getActiveProject(state);+ const instanceIds: Project['widgetRegions']['bottom']['instanceIds'] = ['diagnostics'];++ state = {+ ...state,+ projects: state.projects.map((project) =>+ project.id === activeProject.id+ ? {+ ...project,+ layout: {+ ...project.layout,+ panels: { ...project.layout.panels, isBottomOpen: false },+ },+ widgetRegions: {+ ...project.widgetRegions,+ bottom: {+ ...project.widgetRegions.bottom,+ activeInstanceId: 'diagnostics',+ instanceIds,+ isCollapsed: true,+ },+ },+ }+ : project+ ),+ };++ state = workbenchReducer(state, { region: 'bottom', type: 'openRegionWidget', widgetId: 'queue' });++ expect(getActiveProject(state).layout.panels.isBottomOpen).toBe(true);+ expect(getActiveProject(state).widgetRegions.bottom.activeInstanceId).toBe('queue');+ expect(getActiveProject(state).widgetRegions.bottom.instanceIds).toEqual(['diagnostics', 'queue']);+ expect(getActiveProject(state).widgetRegions.bottom.isCollapsed).toBe(false);+ });+});++describe('workbench widget state updates', () => {+ it('patches a missing undefined widget value key as a real state change', () => {+ const initial = createInitialWorkbenchState();+ const next = workbenchReducer(initial, {+ type: 'patchWidgetValues',+ values: { optionalValue: undefined },+ widgetId: 'diagnostics',+ });+ const values = getProjectWidgetValues(getActiveProject(next), 'diagnostics');++ expect(next).not.toBe(initial);+ expect(Object.prototype.hasOwnProperty.call(values, 'optionalValue')).toBe(true);+ });++ it('can patch a widget instance in a non-active project', () => {+ let state = createInitialWorkbenchState();+ const firstProjectId = state.activeProjectId;++ state = workbenchReducer(state, { type: 'createProject' });+ const secondProjectId = state.activeProjectId;++ expect(secondProjectId).not.toBe(firstProjectId);++ state = workbenchReducer(state, {+ instanceId: 'generate',+ projectId: firstProjectId,+ type: 'patchWidgetInstanceValues',+ values: { projectScoped: true },+ });++ expect(getProject(state, firstProjectId).widgetInstances.generate?.state.values.projectScoped).toBe(true);+ expect(getProject(state, secondProjectId).widgetInstances.generate?.state.values.projectScoped).toBeUndefined();+ });++ it('clones replacement widget instance values before storing them', () => {+ let state = createInitialWorkbenchState();+ const values: Record<string, unknown> = { mutable: 'before' };++ state = workbenchReducer(state, { instanceId: 'generate', type: 'setWidgetInstanceValues', values });+ values.mutable = 'after';++ expect(getActiveProject(state).widgetInstances.generate?.state.values.mutable).toBe('before');+ });++ it('clones patched widget instance values before storing them', () => {+ let state = createInitialWorkbenchState();+ const values: Record<string, unknown> = { nested: { mutable: 'before' } };++ state = workbenchReducer(state, { instanceId: 'generate', type: 'patchWidgetInstanceValues', values });+ (values.nested as { mutable: string }).mutable = 'after';++ expect(getActiveProject(state).widgetInstances.generate?.state.values.nested).toEqual({ mutable: 'before' });+ });+});++describe('workbench layout presets', () => {+ it('applies the Compose preset as a full widget-region layout', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { presetId: 'compose', type: 'applyPreset' });++ const project = getActiveProject(state);++ expect(project.layout.panels).toEqual({ isBottomOpen: false, isLeftOpen: true, isRightOpen: true });+ expect(project.widgetRegions.left).toMatchObject({+ activeInstanceId: 'generate',+ instanceIds: ['generate', 'workflow', 'upscale'],+ isCollapsed: false,+ sizePx: 450,+ });+ expect(project.widgetRegions.center).toMatchObject({+ activeInstanceId: 'preview',+ instanceIds: ['preview', 'canvas', 'gallery:center', 'workflow:center'],+ isCollapsed: false,+ sizePx: 0,+ });+ expect(project.widgetRegions.right).toMatchObject({+ activeInstanceId: 'gallery',+ instanceIds: ['gallery', 'preview', 'queue', 'layers', 'diagnostics', 'project'],+ isCollapsed: false,+ sizePx: 450,+ });+ expect(project.widgetRegions.bottom).toMatchObject({+ activeInstanceId: 'gallery:bottom',+ instanceIds: [+ 'server-status',+ 'diagnostics:bottom',+ 'gallery:bottom',+ 'notifications',+ 'autosave-status',+ 'version-status',+ 'workflow:bottom',+ ],+ isCollapsed: true,+ sizePx: 180,+ });+ });++ it('adds a custom preset from the active project layout and applies it later', () => {+ let state = createInitialWorkbenchState();+ const projectId = state.activeProjectId;++ state = workbenchReducer(state, { region: 'right', sizePx: 336, type: 'setRegionWidgetSize' });+ state = workbenchReducer(state, { region: 'right', type: 'selectRegionWidget', widgetId: 'queue' });+ state = workbenchReducer(state, { region: 'center', type: 'selectRegionWidget', widgetId: 'preview' });+ state = workbenchReducer(state, {+ label: 'Queue review',+ presetId: 'custom-layout-1',+ type: 'addLayoutPreset',+ });++ state = workbenchReducer(state, { presetId: 'canvas', type: 'applyPreset' });+ state = workbenchReducer(state, { presetId: 'custom-layout-1', type: 'applyPreset' });++ const project = getProject(state, projectId);++ expect(state.account.customLayoutPresets).toHaveLength(1);+ expect(state.account.customLayoutPresets?.[0]).toMatchObject({ id: 'custom-layout-1', label: 'Queue review' });+ expect(project.widgetRegions.right).toMatchObject({ activeInstanceId: 'queue', sizePx: 336 });+ expect(project.widgetRegions.center.activeInstanceId).toBe('preview');+ });++ it('renames and deletes only custom layout presets', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, {+ label: 'Original',+ presetId: 'custom-layout-1',+ type: 'addLayoutPreset',+ });+ state = workbenchReducer(state, {+ label: 'Renamed',+ presetId: 'custom-layout-1',+ type: 'renameLayoutPreset',+ });+ state = workbenchReducer(state, { presetId: 'compose', type: 'renameLayoutPreset', label: 'Nope' });+ state = workbenchReducer(state, { presetId: 'custom-layout-1', type: 'deleteLayoutPreset' });++ expect(state.account.customLayoutPresets).toEqual([]);+ });++ it('moves every project off a deleted custom layout preset', () => {+ let state = createInitialWorkbenchState();+ const firstProjectId = state.activeProjectId;++ state = workbenchReducer(state, {+ label: 'Shared custom layout',+ presetId: 'custom-layout-1',+ type: 'addLayoutPreset',+ });+ state = workbenchReducer(state, { presetId: 'custom-layout-1', type: 'applyPreset' });+ state = workbenchReducer(state, { type: 'createProject' });+ const secondProjectId = state.activeProjectId;+ state = workbenchReducer(state, { presetId: 'custom-layout-1', type: 'applyPreset' });++ state = workbenchReducer(state, { presetId: 'custom-layout-1', type: 'deleteLayoutPreset' });++ expect(getProject(state, firstProjectId).layout.presetId).toBe('compose');+ expect(getProject(state, secondProjectId).layout.presetId).toBe('compose');+ expect(state.account.activeLayoutPresetId).toBe('compose');+ });++ // Contract §9.1 of the top-bar redesign. If switching presets loses work,+ // users stop switching them and the whole centre strip becomes dead weight,+ // so this is a correctness requirement rather than polish.+ it('preserves widget state across a Compose to Edit to Compose round trip', () => {+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'compose', type: 'applyPreset' });++ state = workbenchReducer(state, {+ type: 'patchGenerateSettings',+ values: { positivePrompt: 'a lighthouse at dusk', steps: 42 },+ });+ state = workbenchReducer(state, {+ instanceId: 'gallery',+ type: 'patchWidgetInstanceValues',+ values: { scrollOffset: 1280 },+ });++ state = workbenchReducer(state, { presetId: 'edit', type: 'applyPreset' });+ state = workbenchReducer(state, { presetId: 'compose', type: 'applyPreset' });++ const generateValues = getProjectWidgetValues(getActiveProject(state), 'generate');++ expect(generateValues.positivePrompt).toBe('a lighthouse at dusk');+ expect(generateValues.steps).toBe(42);+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').scrollOffset).toBe(1280);+ });++ it('saves the live arrangement onto a built-in preset and restores its shipped default', () => {+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'compose', type: 'applyPreset' });++ state = workbenchReducer(state, { region: 'right', sizePx: 320, type: 'setRegionWidgetSize' });+ state = workbenchReducer(state, { presetId: 'compose', type: 'saveLayoutPreset' });++ expect(state.account.layoutPresetOverrides?.compose?.widgetRegions.right.sizePx).toBe(320);++ // Reverting now lands on the saved edit, not on the shipped arrangement.+ state = workbenchReducer(state, { region: 'right', sizePx: 500, type: 'setRegionWidgetSize' });+ state = workbenchReducer(state, { type: 'resetActiveLayout' });++ expect(getActiveProject(state).widgetRegions.right.sizePx).toBe(320);++ state = workbenchReducer(state, { presetId: 'compose', type: 'restoreLayoutPresetDefault' });+ state = workbenchReducer(state, { type: 'resetActiveLayout' });++ expect(state.account.layoutPresetOverrides?.compose).toBeUndefined();+ expect(getActiveProject(state).widgetRegions.right.sizePx).toBe(450);+ });++ it('resolves retired built-in preset ids onto the three shipped presets', () => {+ const initial = createInitialWorkbenchState();+ const hydrated = workbenchReducer(initial, {+ state: {+ ...initial,+ account: { activeLayoutPresetId: 'workflow' },+ projects: initial.projects.map((project) => ({+ ...project,+ layout: { ...project.layout, presetId: 'canvas' },+ })),+ } as unknown as WorkbenchState,+ type: 'hydrateWorkbench',+ });++ expect(hydrated.account.activeLayoutPresetId).toBe('automate');+ expect(getActiveProject(hydrated).layout.presetId).toBe('edit');+ });+});++describe('workbenchReducer Phase 5 generation flow', () => {+ it('does not notify gallery total subscribers for unchanged or non-finite totals', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { totalImages: 3, type: 'setGalleryPageInfo' });++ const unchanged = workbenchReducer(state, { totalImages: 3, type: 'setGalleryPageInfo' });+ const nonFinite = workbenchReducer(state, { totalImages: Number.NaN, type: 'setGalleryPageInfo' });++ expect(unchanged).toBe(state);+ expect(nonFinite).toBe(state);+ });++ it('routes queue results back to the originating project after the user switches projects', () => {+ let state = submitGenerate(primeGenerate());+ const originProject = getActiveProject(state);+ const queueItem = originProject.queue.items[0];++ expect(queueItem).toBeDefined();++ state = workbenchReducer(state, { type: 'createProject' });+ state = workbenchReducer(state, { projectId: originProject.id, type: 'switchProject' });++ const otherProjectId = state.projects.find((project) => project.id !== originProject.id)?.id;++ expect(otherProjectId).toBeDefined();++ state = workbenchReducer(state, { projectId: otherProjectId as string, type: 'switchProject' });+ state = workbenchReducer(state, {+ backendItemIds: [42],+ projectId: originProject.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });+ state = workbenchReducer(state, {+ images: [createImage('origin-image.png', queueItem.id)],+ projectId: originProject.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });++ const updatedOriginProject = getProject(state, originProject.id);+ const activeProject = getActiveProject(state);++ expect(activeProject.id).toBe(otherProjectId);+ expect(updatedOriginProject.canvas.stagingArea.pendingImageIds).toEqual(['origin-image.png']);+ expect(updatedOriginProject.queue.items[0]?.status).toBe('completed');+ expect(activeProject.canvas.stagingArea.pendingImageIds).toEqual([]);+ expect(activeProject.queue.items).toEqual([]);+ });++ it('appends a workflow candidate to its explicit project and selects its resolved staging slot', () => {+ let state = createInitialWorkbenchState();+ const originProjectId = state.activeProjectId;+ const firstCandidate = createStagingCandidate('first.png', 'layer-workflow:first', {+ height: 100,+ opacity: 1,+ width: 200,+ x: 5,+ y: 7,+ });+ const appendedCandidate = createStagingCandidate('second.png', 'layer-workflow:second', {+ height: 240,+ opacity: 0.45,+ width: 320,+ x: 11,+ y: 17,+ });++ state = workbenchReducer(state, { type: 'createProject' });+ const activeProjectId = state.activeProjectId;+ state = workbenchReducer(state, {+ candidate: firstCandidate,+ projectId: originProjectId,+ type: 'appendCanvasStagingCandidate',+ });+ state = workbenchReducer(state, {+ candidate: appendedCandidate,+ projectId: originProjectId,+ type: 'appendCanvasStagingCandidate',+ });++ const originProject = getProject(state, originProjectId);+ const slots = getCanvasStagingSlots(originProject.canvas, originProject.queue.items);++ expect(state.activeProjectId).toBe(activeProjectId);+ expect(originProject.canvas.stagingArea.pendingImages).toEqual([firstCandidate, appendedCandidate]);+ expect(originProject.canvas.stagingArea.pendingImageIds).toEqual(['first.png', 'second.png']);+ expect(originProject.canvas.stagingArea.isVisible).toBe(true);+ expect(originProject.canvas.stagingArea.selectedImageIndex).toBe(1);+ expect(slots[originProject.canvas.stagingArea.selectedImageIndex]).toMatchObject({+ candidate: { imageName: 'second.png', placement: appendedCandidate.placement },+ kind: 'candidate',+ });+ expect(getProject(state, activeProjectId).canvas.stagingArea.pendingImages).toEqual([]);+ });++ it('accepts a workflow candidate at its own placement, scale, and opacity', () => {+ let state = withEmptyCanvas(createInitialWorkbenchState());+ const projectId = state.activeProjectId;+ const candidate = createStagingCandidate('dimension-changing-result.png', 'layer-workflow:request-1', {+ height: 200,+ opacity: 0.35,+ width: 300,+ x: 31,+ y: 47,+ });++ state = workbenchReducer(state, { candidate, projectId, type: 'appendCanvasStagingCandidate' });+ state = commitSelectedStagedImage(state);++ const acceptedLayer = getActiveProject(state).canvas.document.layers[0];++ expect(getRasterLayerImageName(acceptedLayer)).toBe('dimension-changing-result.png');+ expect(getRasterLayerPlacement(acceptedLayer)).toEqual(candidate.placement);+ });++ it('accepts a staged candidate in the addressed project after another project becomes active', () => {+ let state = withEmptyCanvas(createInitialWorkbenchState());+ const originProjectId = state.activeProjectId;+ const candidate = createStagingCandidate('origin-result.png', 'layer-workflow:origin', {+ height: 64,+ opacity: 0.75,+ width: 96,+ x: 13,+ y: 17,+ });+ state = workbenchReducer(state, {+ candidate,+ projectId: originProjectId,+ type: 'appendCanvasStagingCandidate',+ });+ state = workbenchReducer(state, { type: 'createProject' });+ const activeProjectId = state.activeProjectId;++ state = commitSelectedStagedImage(state, originProjectId);++ expect(state.activeProjectId).toBe(activeProjectId);+ expect(getRasterLayerImageName(getProject(state, originProjectId).canvas.document.layers[0])).toBe(+ 'origin-result.png'+ );+ expect(getProject(state, activeProjectId).canvas.document.layers).not.toContainEqual(+ expect.objectContaining({+ source: expect.objectContaining({ image: expect.objectContaining({ imageName: 'origin-result.png' }) }),+ })+ );+ });++ it('keeps submitted Generate snapshots immutable after later settings changes', () => {+ let state = submitGenerate(primeGenerate(undefined, { positivePrompt: 'first prompt', shouldRandomizeSeed: true }));+ const firstQueueItem = getActiveProject(state).queue.items[0];++ expect(firstQueueItem).toBeDefined();++ state = primeGenerate(state, { positivePrompt: 'second prompt', seed: 999 });+ state = submitGenerate(state);++ const [secondQueueItem, unchangedFirstQueueItem] = getActiveProject(state).queue.items;+ const firstValues = unchangedFirstQueueItem?.snapshot.widgetStates.generate+ .values as unknown as GenerateWidgetValues;+ const secondValues = secondQueueItem?.snapshot.widgetStates.generate.values as unknown as GenerateWidgetValues;++ expect(firstValues.positivePrompt).toBe('first prompt');+ expect(firstValues.shouldRandomizeSeed).toBe(true);+ expect(typeof firstValues.seed).toBe('number');+ expect(secondValues.positivePrompt).toBe('second prompt');+ expect(secondValues.seed).toBe(999);+ });++ it('accepts a staged candidate into a selected raster layer that project undo no longer touches', () => {+ let state = submitGenerate(primeGenerate(withEmptyCanvas(createInitialWorkbenchState())));+ const queueItem = getActiveProject(state).queue.items[0];++ state = workbenchReducer(state, {+ images: [createImage('candidate.png', queueItem.id)],+ projectId: getActiveProject(state).id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });+ state = commitSelectedStagedImage(state);++ let project = getActiveProject(state);+ const acceptedLayerId = project.canvas.document.layers[0]?.id;++ expect(project.canvas.document.layers).toHaveLength(1);+ expect(getRasterLayerImageName(project.canvas.document.layers[0])).toBe('candidate.png');+ expect(project.canvas.document.selectedLayerId).toBe(acceptedLayerId);+ expect(project.canvas.stagingArea.pendingImages).toEqual([]);+ // Deliberate semantic change (P0.2): canvas is engine-owned, so accepting a+ // staged image does not create a project-level undo entry.+ expect(project.undoRedo.past).toHaveLength(0);++ state = commitSelectedStagedImage(state);+ project = getActiveProject(state);++ expect(project.canvas.document.layers).toHaveLength(1);++ // Project undo neither snapshots nor restores canvas: the accepted layer survives.+ state = workbenchReducer(state, { type: 'undoProjectChange' });+ project = getActiveProject(state);++ expect(project.canvas.document.layers).toHaveLength(1);+ expect(getRasterLayerImageName(project.canvas.document.layers[0])).toBe('candidate.png');+ });++ it('discards selected and all staged canvas candidates without touching accepted document layers', () => {+ let state = submitGenerate(primeGenerate(withEmptyCanvas(createInitialWorkbenchState())));+ const queueItem = getActiveProject(state).queue.items[0];++ state = workbenchReducer(state, {+ images: [createImage('candidate-1.png', queueItem.id), createImage('candidate-2.png', queueItem.id)],+ projectId: getActiveProject(state).id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });+ state = workbenchReducer(state, { imageIndex: 1, type: 'setStagedImageIndex' });+ state = workbenchReducer(state, { type: 'discardSelectedStagedImage' });++ let project = getActiveProject(state);++ expect(project.canvas.document.layers).toEqual([]);+ expect(project.canvas.stagingArea.pendingImageIds).toEqual(['candidate-1.png']);+ expect(project.canvas.stagingArea.selectedImageIndex).toBe(0);+ expect(project.canvas.stagingArea.isVisible).toBe(true);++ state = workbenchReducer(state, { type: 'discardAllStagedImages' });+ project = getActiveProject(state);++ expect(project.canvas.stagingArea.pendingImages).toEqual([]);+ expect(project.canvas.stagingArea.pendingImageIds).toEqual([]);+ expect(project.canvas.stagingArea.isVisible).toBe(false);+ });++ it('normalizes ordinary queue results to the queued bbox origin and native image size', () => {+ let state = submitGenerate(primeGenerate());+ const queueItem = getActiveProject(state).queue.items[0];++ state = workbenchReducer(state, { bbox: { height: 256, width: 256, x: 40, y: 24 }, type: 'setCanvasBbox' });+ state = workbenchReducer(state, {+ images: [createImage('candidate-1.png', queueItem.id), createImage('candidate-2.png', queueItem.id)],+ projectId: getActiveProject(state).id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });+ state = workbenchReducer(state, { direction: -1, type: 'cycleStagedImage' });++ expect(getActiveProject(state).canvas.stagingArea.selectedImageIndex).toBe(1);+ expect(getActiveProject(state).canvas.stagingArea.pendingImages[1]?.placement).toEqual({+ height: 768,+ opacity: 1,+ width: 512,+ x: 0,+ y: 0,+ });++ state = commitSelectedStagedImage(state);++ let project = getActiveProject(state);+ const acceptedLayer = project.canvas.document.layers[0];++ expect(getRasterLayerImageName(acceptedLayer)).toBe('candidate-2.png');+ expect(getRasterLayerPlacement(acceptedLayer)).toEqual({ height: 768, opacity: 1, width: 512, x: 0, y: 0 });++ // Project undo/redo leaves the engine-owned canvas alone.+ state = workbenchReducer(state, { type: 'undoProjectChange' });+ project = getActiveProject(state);++ expect(getRasterLayerImageName(project.canvas.document.layers[0])).toBe('candidate-2.png');+ });++ it('cycles pending canvas placeholder slots before results complete', () => {+ let state = submitGenerate(primeGenerate(undefined, { batchCount: 2 }));+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, {+ backendItemIds: [11, 12],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });++ expect(+ getCanvasStagingSlots(getCanvas(state), getActiveProject(state).queue.items).map((slot) => slot.kind)+ ).toEqual(['placeholder', 'placeholder']);++ state = workbenchReducer(state, { direction: 1, type: 'cycleStagedImage' });++ expect(getActiveProject(state).canvas.stagingArea.selectedImageIndex).toBe(1);+ });++ it('stages canvas partial results while the rest of the batch keeps placeholders', () => {+ let state = submitGenerate(primeGenerate(undefined, { batchCount: 2 }));+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, {+ backendItemIds: [11, 12],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });+ state = workbenchReducer(state, {+ backendItemId: 11,+ images: [createImage('candidate-1.png', queueItem.id)],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemPartialResults',+ });++ const updatedProject = getActiveProject(state);+ const slots = getCanvasStagingSlots(updatedProject.canvas, updatedProject.queue.items);++ expect(updatedProject.queue.items[0]).toMatchObject({ completedBackendItemIds: [11], status: 'running' });+ expect(updatedProject.canvas.stagingArea.pendingImageIds).toEqual(['candidate-1.png']);+ expect(slots.map((slot) => slot.kind)).toEqual(['candidate', 'placeholder']);+ expect(slots[0]).toMatchObject({ itemIndex: 1, kind: 'candidate', queueItemId: queueItem.id });+ expect(updatedProject.canvas.stagingArea.pendingImages[0]).toMatchObject({ sourceBackendItemId: 11 });+ expect(updatedProject.canvas.stagingArea.pendingImages[0]?.placement).toEqual({+ height: 768,+ opacity: 1,+ width: 512,+ x: updatedProject.canvas.document.bbox.x,+ y: updatedProject.canvas.document.bbox.y,+ });+ expect(slots[1]).toMatchObject({ itemIndex: 2, queueItemId: queueItem.id });+ });++ it('preserves the selected staged candidate when final results duplicate partial results', () => {+ let state = submitGenerate(primeGenerate(undefined, { batchCount: 2 }));+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];+ const firstImage = createImage('candidate-1.png', queueItem.id);+ const secondImage = createImage('candidate-2.png', queueItem.id);++ state = workbenchReducer(state, {+ backendItemIds: [11, 12],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });+ state = workbenchReducer(state, {+ backendItemId: 11,+ images: [firstImage],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemPartialResults',+ });+ state = workbenchReducer(state, {+ backendItemId: 12,+ images: [secondImage],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemPartialResults',+ });+ state = workbenchReducer(state, { imageIndex: 1, type: 'setStagedImageIndex' });+ state = workbenchReducer(state, {+ images: [firstImage, secondImage],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });++ expect(getActiveProject(state).canvas.stagingArea.pendingImageIds).toEqual(['candidate-1.png', 'candidate-2.png']);+ expect(getActiveProject(state).canvas.stagingArea.pendingImages).toMatchObject([+ { sourceBackendItemId: 11 },+ { sourceBackendItemId: 12 },+ ]);+ expect(getActiveProject(state).canvas.stagingArea.selectedImageIndex).toBe(1);+ });++ it('clamps the selected staging slot when backend cancellation removes the selected placeholder', () => {+ let state = submitGenerate(primeGenerate(undefined, { batchCount: 3 }));+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, {+ backendItemIds: [11, 12, 13],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });+ state = workbenchReducer(state, { imageIndex: 2, type: 'setStagedImageIndex' });+ state = workbenchReducer(state, {+ backendItemId: 13,+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendCancelled',+ });++ expect(getCanvasStagingSlots(getCanvas(state), getActiveProject(state).queue.items)).toHaveLength(2);+ expect(getActiveProject(state).canvas.stagingArea.selectedImageIndex).toBe(1);+ });++ it('accepts the selected candidate when placeholders precede it in the staging strip', () => {+ let state = submitGenerate(primeGenerate(undefined, { batchCount: 1 }));+ const firstProject = getActiveProject(state);+ const firstQueueItem = firstProject.queue.items[0];++ state = workbenchReducer(state, {+ backendItemIds: [11],+ projectId: firstProject.id,+ queueItemId: firstQueueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });+ state = submitGenerate(primeGenerate(state, { positivePrompt: 'second prompt' }));++ const secondProject = getActiveProject(state);+ const secondQueueItem = secondProject.queue.items[0];++ state = workbenchReducer(state, {+ images: [createImage('candidate-2.png', secondQueueItem.id)],+ projectId: secondProject.id,+ queueItemId: secondQueueItem.id,+ type: 'routeQueueItemResults',+ });++ expect(+ getCanvasStagingSlots(getCanvas(state), getActiveProject(state).queue.items).map((slot) => slot.kind)+ ).toEqual(['placeholder', 'candidate']);+ expect(getCanvas(state).stagingArea.selectedImageIndex).toBe(1);++ state = commitSelectedStagedImage(state);++ expect(getRasterLayerImageName(getActiveProject(state).canvas.document.layers[0])).toBe('candidate-2.png');+ });++ it('discards the selected candidate when placeholders precede it in the staging strip', () => {+ let state = submitGenerate(primeGenerate(undefined, { batchCount: 1 }));+ const firstProject = getActiveProject(state);+ const firstQueueItem = firstProject.queue.items[0];++ state = workbenchReducer(state, {+ backendItemIds: [11],+ projectId: firstProject.id,+ queueItemId: firstQueueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });+ state = submitGenerate(primeGenerate(state, { positivePrompt: 'second prompt' }));++ const secondProject = getActiveProject(state);+ const secondQueueItem = secondProject.queue.items[0];++ state = workbenchReducer(state, {+ images: [createImage('candidate-2.png', secondQueueItem.id)],+ projectId: secondProject.id,+ queueItemId: secondQueueItem.id,+ type: 'routeQueueItemResults',+ });+ state = workbenchReducer(state, { type: 'discardSelectedStagedImage' });++ expect(getActiveProject(state).canvas.stagingArea.pendingImages).toEqual([]);+ expect(+ getCanvasStagingSlots(getCanvas(state), getActiveProject(state).queue.items).map((slot) => slot.kind)+ ).toEqual(['placeholder']);+ expect(getCanvas(state).stagingArea.isVisible).toBe(true);+ });++ it('keeps thumbnail strip visibility separate from staged result preview visibility', () => {+ let state = submitGenerate(primeGenerate());+ const queueItem = getActiveProject(state).queue.items[0];++ state = workbenchReducer(state, {+ images: [createImage('candidate-1.png', queueItem.id), createImage('candidate-2.png', queueItem.id)],+ projectId: getActiveProject(state).id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });++ expect(getActiveProject(state).canvas.stagingArea.pendingImageIds).toEqual(['candidate-1.png', 'candidate-2.png']);+ expect(getActiveProject(state).canvas.stagingArea.areThumbnailsVisible).toBe(true);+ expect(getActiveProject(state).canvas.stagingArea.isVisible).toBe(true);++ state = workbenchReducer(state, { type: 'toggleCanvasStagingThumbnailsVisibility' });+ expect(getActiveProject(state).canvas.stagingArea.areThumbnailsVisible).toBe(false);+ expect(getActiveProject(state).canvas.stagingArea.isVisible).toBe(true);++ state = workbenchReducer(state, { type: 'toggleCanvasStagingVisibility' });+ expect(getActiveProject(state).canvas.stagingArea.areThumbnailsVisible).toBe(false);+ expect(getActiveProject(state).canvas.stagingArea.isVisible).toBe(false);+ });++ it('appends later canvas results to the active staging session instead of replacing candidates', () => {+ let state = submitGenerate(primeGenerate());+ const firstQueueItem = getActiveProject(state).queue.items[0];++ state = workbenchReducer(state, {+ images: [createImage('candidate-1.png', firstQueueItem.id)],+ projectId: getActiveProject(state).id,+ queueItemId: firstQueueItem.id,+ type: 'routeQueueItemResults',+ });+ state = submitGenerate(primeGenerate(state, { positivePrompt: 'second prompt' }));++ const secondQueueItem = getActiveProject(state).queue.items[0];++ state = workbenchReducer(state, {+ images: [createImage('candidate-2.png', secondQueueItem.id)],+ projectId: getActiveProject(state).id,+ queueItemId: secondQueueItem.id,+ type: 'routeQueueItemResults',+ });++ expect(getActiveProject(state).canvas.stagingArea.pendingImageIds).toEqual(['candidate-1.png', 'candidate-2.png']);+ expect(getActiveProject(state).canvas.stagingArea.selectedImageIndex).toBe(1);+ });++ it('keeps staged canvas candidates isolated per project when switching projects', () => {+ let state = submitGenerate(primeGenerate());+ const originProject = getActiveProject(state);+ const queueItem = originProject.queue.items[0];++ state = workbenchReducer(state, { type: 'createProject' });+ state = workbenchReducer(state, { projectId: originProject.id, type: 'switchProject' });++ const otherProjectId = state.projects.find((project) => project.id !== originProject.id)?.id;++ expect(otherProjectId).toBeDefined();++ state = workbenchReducer(state, {+ images: [createImage('origin-candidate.png', queueItem.id)],+ projectId: originProject.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });+ state = workbenchReducer(state, { projectId: otherProjectId as string, type: 'switchProject' });++ expect(getActiveProject(state).canvas.stagingArea.pendingImages).toEqual([]);++ state = workbenchReducer(state, { projectId: originProject.id, type: 'switchProject' });++ expect(getActiveProject(state).canvas.stagingArea.pendingImageIds).toEqual(['origin-candidate.png']);+ });++ it('marks cancellable running queue items cancelled for backend cancellation', () => {+ let state = submitGenerate(primeGenerate());+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, {+ backendItemIds: [42],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });+ state = workbenchReducer(state, { queueItemId: queueItem.id, type: 'cancelQueueItem' });++ expect(getActiveProject(state).queue.items[0]?.status).toBe('cancelled');+ });++ it('cancels queue items from inactive projects when a project id is provided', () => {+ let state = submitGenerate(primeGenerate());+ const originProject = getActiveProject(state);+ const queueItem = originProject.queue.items[0];++ state = workbenchReducer(state, { type: 'createProject' });+ expect(getActiveProject(state).id).not.toBe(originProject.id);++ state = workbenchReducer(state, {+ projectId: originProject.id,+ queueItemId: queueItem.id,+ type: 'cancelQueueItem',+ });++ expect(getProject(state, originProject.id).queue.items[0]?.status).toBe('cancelled');+ });++ it('cancels all active cancellable queue items from the queue actions menu', () => {+ let state = submitGenerate(primeGenerate());++ state = workbenchReducer(state, { type: 'createProject' });+ state = submitGenerate(primeGenerate(state));+ state = workbenchReducer(state, { type: 'cancelAllQueueItems' });++ expect(state.projects.flatMap((project) => project.queue.items.map((item) => item.status))).toEqual([+ 'cancelled',+ 'cancelled',+ ]);+ });++ it('cancels active queue items except the current one', () => {+ let state = submitGenerate(primeGenerate());+ const firstQueueItemId = getActiveProject(state).queue.items[0].id;++ state = submitGenerate(primeGenerate(state));+ state = workbenchReducer(state, {+ currentQueueItemId: firstQueueItemId,+ type: 'cancelAllQueueItemsExceptCurrent',+ });++ expect(getActiveProject(state).queue.items.map((item) => ({ id: item.id, status: item.status }))).toEqual([+ { id: getActiveProject(state).queue.items[0].id, status: 'cancelled' },+ { id: firstQueueItemId, status: 'pending' },+ ]);+ });++ it('records backend item cancellation without cancelling the whole local batch', () => {+ let state = submitGenerate(primeGenerate(undefined, { batchCount: 3 }));+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, {+ backendItemIds: [11, 12, 13],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });+ state = workbenchReducer(state, {+ backendItemId: 12,+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendCancelled',+ });++ expect(getActiveProject(state).queue.items[0]).toMatchObject({+ cancelledBackendItemIds: [12],+ status: 'running',+ });+ });++ it('marks a local queue item cancelled only when all backend items were cancelled', () => {+ let state = submitGenerate(primeGenerate(undefined, { batchCount: 2 }));+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, {+ backendItemIds: [11, 12],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });+ state = workbenchReducer(state, {+ backendItemId: 11,+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendCancelled',+ });+ state = workbenchReducer(state, {+ backendItemId: 12,+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendCancelled',+ });++ expect(getActiveProject(state).queue.items[0]).toMatchObject({+ cancelledBackendItemIds: [11, 12],+ status: 'cancelled',+ });+ });++ it('scopes cancel all queue items to a project when requested', () => {+ let state = submitGenerate(primeGenerate());+ const originProject = getActiveProject(state);++ state = workbenchReducer(state, { type: 'createProject' });+ state = submitGenerate(primeGenerate(state));+ state = workbenchReducer(state, { projectId: originProject.id, type: 'cancelAllQueueItems' });++ expect(getProject(state, originProject.id).queue.items.map((item) => item.status)).toEqual(['cancelled']);+ expect(getActiveProject(state).queue.items.map((item) => item.status)).toEqual(['pending']);+ });++ it('clears completed and failed queue items while preserving active and cancelled items', () => {+ let state = submitGenerate(primeGenerate());+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, {+ images: [createImage('completed-result.png', queueItem.id)],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });+ state = submitGenerate(primeGenerate(state));+ const activeQueueItem = getActiveProject(state).queue.items[0];+ state = workbenchReducer(state, { queueItemId: activeQueueItem.id, type: 'cancelQueueItem' });+ state = submitGenerate(primeGenerate(state));+ const failedQueueItem = getActiveProject(state).queue.items[0];+ state = workbenchReducer(state, {+ error: 'failed',+ projectId: project.id,+ queueItemId: failedQueueItem.id,+ status: 'failed',+ type: 'setQueueItemStatus',+ });++ state = workbenchReducer(state, { type: 'clearCompletedQueueItems' });++ expect(getActiveProject(state).queue.items.map((item) => item.status)).toEqual(['cancelled']);+ });++ it('can mark stale reconciled queue items failed without creating notifications', () => {+ let state = submitGenerate(primeGenerate());+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];+ const notificationCount = state.notifications.length;++ state = workbenchReducer(state, {+ error: 'This run is no longer on the backend queue.',+ notify: false,+ projectId: project.id,+ queueItemId: queueItem.id,+ status: 'failed',+ type: 'setQueueItemStatus',+ });++ expect(getActiveProject(state).queue.items[0]?.status).toBe('failed');+ expect(getActiveProject(state).queue.items[0]?.error).toBe('This run is no longer on the backend queue.');+ expect(state.notifications).toHaveLength(notificationCount);+ });++ it('keeps cancellation terminal when backend item ids arrive late', () => {+ let state = submitGenerate(primeGenerate());+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, { queueItemId: queueItem.id, type: 'cancelQueueItem' });+ state = workbenchReducer(state, {+ backendItemIds: [42],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });+ state = workbenchReducer(state, {+ images: [createImage('late-result.png', queueItem.id)],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });+ state = workbenchReducer(state, {+ error: 'backend cancellation completed',+ projectId: project.id,+ queueItemId: queueItem.id,+ status: 'failed',+ type: 'setQueueItemStatus',+ });++ const cancelledItem = getActiveProject(state).queue.items[0];++ expect(cancelledItem?.status).toBe('cancelled');+ expect(cancelledItem?.backendItemIds).toEqual([42]);+ expect(getActiveProject(state).canvas.stagingArea.pendingImages).toEqual([]);+ expect(state.notifications.map((notification) => notification.title)).toEqual([+ 'Invocation cancellation requested',+ 'Invocation queued',+ ]);+ });++ it('does not report cancellation for completed queue items', () => {+ let state = submitGenerate(primeGenerate());+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, {+ images: [createImage('completed-result.png', queueItem.id)],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });+ state = workbenchReducer(state, { queueItemId: queueItem.id, type: 'cancelQueueItem' });++ expect(getActiveProject(state).queue.items[0]?.status).toBe('completed');+ expect(state.notifications.map((notification) => notification.title)).toEqual([+ 'Invocation completed',+ 'Invocation queued',+ ]);+ });++ it('records notifications for errors and successful operations', () => {+ let state = submitGenerate(primeGenerate());++ expect(state.notifications[0]?.title).toBe('Invocation queued');++ const queueItem = getActiveProject(state).queue.items[0];++ state = workbenchReducer(state, {+ images: [createImage('candidate.png', queueItem.id)],+ projectId: getActiveProject(state).id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });+ state = commitSelectedStagedImage(state);+ state = workbenchReducer(state, { message: 'boom', type: 'recordError' });++ expect(state.notifications.map((notification) => notification.title)).toEqual([+ 'Error',+ 'Invocation completed',+ 'Invocation queued',+ ]);+ expect(state.notifications.every((notification) => !notification.isRead)).toBe(true);++ state = workbenchReducer(state, { type: 'markAllNotificationsRead' });++ expect(state.notifications.every((notification) => notification.isRead)).toBe(true);++ state = workbenchReducer(state, { type: 'clearNotifications' });++ expect(state.notifications).toEqual([]);++ expect(state.notifications).toEqual([]);+ });++ it('accepts the project graph source but does not queue an empty project graph', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });++ expect(getActiveProject(state).invocation.sourceId).toBe('workflow');++ state = workbenchReducer(state, {+ backendSupportsCancellation: true,+ route: { destination: 'canvas', destinationLocked: false, sourceId: 'workflow', sourceLocked: true },+ type: 'submitResolvedInvocationSnapshot',+ });++ expect(getActiveProject(state).queue.items).toEqual([]);+ });++ it('applies workflow edits to the project graph with undo and auto-source', () => {+ let state = createInitialWorkbenchState();++ expect(getActiveProject(state).invocation.sourceId).toBe('generate');++ state = workbenchReducer(state, {+ action: {+ node: {+ data: {+ inputs: {},+ isIntermediate: true,+ isOpen: true,+ label: '',+ nodePack: 'invokeai',+ notes: '',+ type: 'add',+ useCache: true,+ version: '1.0.0',+ },+ id: 'node-1',+ position: { x: 0, y: 0 },+ type: 'invocation',+ },+ type: 'addNode',+ },+ type: 'applyProjectGraphAction',+ });++ const project = getActiveProject(state);++ // A meaningful graph edit lands in the document, creates an undo entry,+ // and steers the unlocked invocation route to the project graph.+ expect(project.projectGraph.nodes).toHaveLength(1);+ expect(project.undoRedo.past.at(-1)?.label).toBe('Add workflow node');+ expect(project.invocation.sourceId).toBe('workflow');+ expect(project.invocation.destination).toBe('gallery');++ state = workbenchReducer(state, { type: 'undoProjectChange' });++ expect(getActiveProject(state).projectGraph.nodes).toHaveLength(0);+ expect(getActiveProject(state).invocation).toMatchObject({ destination: 'gallery', sourceId: 'workflow' });+ });++ it('replaceProjectGraph snapshots the previous document into graph history', () => {+ let state = createInitialWorkbenchState();+ const originalGraphId = getActiveProject(state).projectGraph.id;++ state = workbenchReducer(state, {+ document: { ...getActiveProject(state).projectGraph, id: 'replacement-graph', name: 'Replacement' },+ label: 'Test replace',+ type: 'replaceProjectGraph',+ });++ const project = getActiveProject(state);++ expect(project.projectGraph.id).toBe('replacement-graph');+ expect(project.invocation).toMatchObject({ destination: 'gallery', sourceId: 'workflow' });+ expect(project.graphHistory[0]?.document?.id).toBe(originalGraphId);+ expect(project.graphHistory[0]?.retainedBytes).toBeGreaterThan(0);+ expect(project.graphHistory[0]?.document).toBe(project.undoRedo.past.at(-1)?.project.projectGraph);++ state = workbenchReducer(state, {+ snapshotId: project.graphHistory[0]?.id ?? '',+ type: 'restoreProjectGraphSnapshot',+ });++ expect(getActiveProject(state).projectGraph.id).toBe(originalGraphId);+ expect(getActiveProject(state).invocation).toMatchObject({ destination: 'gallery', sourceId: 'workflow' });+ });++ it('keeps the newest graph-history entries within the count limit and recomputes retained bytes', () => {+ const entries = Array.from({ length: 50 }, (_, index) => ({+ createdAt: `2026-07-19T00:00:${String(index).padStart(2, '0')}.000Z`,+ document: { edges: [], nodes: [], version: 1 as const },+ id: `snapshot-${index}`,+ label: `Snapshot ${index}`,+ retainedBytes: 0,+ }));+ const normalized = normalizeGraphHistory(entries);++ expect(normalized).toHaveLength(40);+ expect(normalized.map((entry) => entry.id)).toEqual(entries.slice(0, 40).map((entry) => entry.id));+ expect(normalized.every((entry) => (entry.retainedBytes ?? 0) > 0)).toBe(true);+ });++ it('measures loaded graph-history entries instead of trusting forged retained-byte metadata', () => {+ const encode = vi.spyOn(TextEncoder.prototype, 'encode').mockImplementation((input) => {+ const byteLength = String(input).includes('"id":"oversized"') ? GRAPH_HISTORY_BYTE_BUDGET + 1 : 128;++ return Object.defineProperty(new Uint8Array(0), 'byteLength', { value: byteLength });+ });++ try {+ const normalized = normalizeGraphHistory([+ {+ createdAt: '2026-07-19T00:00:00.000Z',+ document: { edges: [], nodes: [], version: 1 as const },+ id: 'oversized',+ label: 'Forged low byte count',+ retainedBytes: 0,+ },+ {+ createdAt: '2026-07-19T00:00:01.000Z',+ document: { edges: [], nodes: [], version: 1 as const },+ id: 'within-budget',+ label: 'Forged high byte count',+ retainedBytes: GRAPH_HISTORY_BYTE_BUDGET + 1,+ },+ ]);++ expect(normalized).toHaveLength(1);+ expect(normalized[0]).toMatchObject({ id: 'within-budget', retainedBytes: 128 });+ } finally {+ encode.mockRestore();+ }+ });++ it('admits newest graph-history entries without exceeding the cumulative byte budget', () => {+ const halfBudgetPlusOne = Math.floor(GRAPH_HISTORY_BYTE_BUDGET / 2) + 1;+ const encode = vi.spyOn(TextEncoder.prototype, 'encode').mockImplementation((input) => {+ const byteLength = String(input).includes('"id":"small"') ? 128 : halfBudgetPlusOne;++ return Object.defineProperty(new Uint8Array(0), 'byteLength', { value: byteLength });+ });++ try {+ const createEntry = (id: string) => ({+ createdAt: '2026-07-19T00:00:00.000Z',+ document: { edges: [], nodes: [], version: 1 as const },+ id,+ label: id,+ retainedBytes: 0,+ });+ const normalized = normalizeGraphHistory([+ createEntry('newest-large'),+ createEntry('older-large'),+ createEntry('small'),+ ]);++ expect(normalized.map((entry) => entry.id)).toEqual(['newest-large', 'small']);+ expect(normalized.reduce((total, entry) => total + (entry.retainedBytes ?? 0), 0)).toBeLessThanOrEqual(+ GRAPH_HISTORY_BYTE_BUDGET+ );+ } finally {+ encode.mockRestore();+ }+ });++ it('does not queue Upscale while its required settings are incomplete', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { sourceId: 'upscale', type: 'setInvocationSource' });++ expect(getActiveProject(state).invocation.sourceId).toBe('upscale');++ state = workbenchReducer(state, {+ backendSupportsCancellation: true,+ route: { destination: 'canvas', destinationLocked: false, sourceId: 'upscale', sourceLocked: true },+ type: 'submitResolvedInvocationSnapshot',+ });++ expect(getActiveProject(state).queue.items).toEqual([]);+ });++ it('does not queue Generate snapshots with non-finite numeric settings', () => {+ let state = primeGenerate(undefined, { seed: Number.NaN });++ state = submitGenerate(state);++ expect(getActiveProject(state).queue.items).toEqual([]);+ });++ describe('expanded positive prompts on the compiled submission', () => {+ const submitResolvedWithPrompts = (positivePrompt: string, positivePrompts?: string[]) =>+ workbenchReducer(primeGenerate(undefined, { positivePrompt }), {+ backendSupportsCancellation: true,+ positivePrompts,+ route: { destination: 'gallery', destinationLocked: false, sourceId: 'generate', sourceLocked: false },+ type: 'submitResolvedInvocationSnapshot',+ });++ // Regression: a one-prompt expansion used to be dropped, falling the submission+ // back to `positivePrompt` — which still holds the unexpanded `{…}` syntax.+ it('records a single expanded prompt rather than falling back to the literal', () => {+ const state = submitResolvedWithPrompts('a {red} cat', ['a red cat']);++ expect(getActiveProject(state).queue.items[0]?.snapshot.backendSubmission).toMatchObject({+ positivePrompt: 'a {red} cat',+ positivePrompts: ['a red cat'],+ });+ });++ it('records every prompt of a multi-prompt expansion', () => {+ const state = submitResolvedWithPrompts('a {red|green} cat', ['a red cat', 'a green cat']);+ const queueItem = getActiveProject(state).queue.items[0];++ expect(queueItem?.snapshot.backendSubmission).toMatchObject({+ positivePrompts: ['a red cat', 'a green cat'],+ });+ // Placeholder sizing multiplies the iterations by the prompt count.+ expect(queueItem?.snapshot.presentation.batchCount).toBe(2);+ });++ it('leaves a prompt with no dynamic syntax alone', () => {+ const state = submitResolvedWithPrompts('a plain cat');++ expect(getActiveProject(state).queue.items[0]?.snapshot.backendSubmission).not.toHaveProperty('positivePrompts');+ });++ // The template is what introduced the `{…}` here, so the gate has to read the+ // merged prompt or the expansion would be discarded and the literal submitted.+ it('keeps an expansion whose dynamic syntax came from the prompt template', () => {+ const state = workbenchReducer(+ primeGenerate(undefined, {+ positivePrompt: 'a cat',+ promptTemplate: {+ id: 't1',+ name: 'Tinted',+ negativePrompt: '',+ positivePrompt: '{prompt}, {red|green} tint',+ },+ }),+ {+ backendSupportsCancellation: true,+ positivePrompts: ['a cat, red tint', 'a cat, green tint'],+ route: { destination: 'gallery', destinationLocked: false, sourceId: 'generate', sourceLocked: false },+ type: 'submitResolvedInvocationSnapshot',+ }+ );++ expect(getActiveProject(state).queue.items[0]?.snapshot.backendSubmission).toMatchObject({+ positivePrompts: ['a cat, red tint', 'a cat, green tint'],+ });+ });+ });++ describe('prompt templates on the compiled submission', () => {+ const template = {+ id: 't1',+ name: 'Cinematic',+ negativePrompt: '{prompt}, lowres',+ positivePrompt: '{prompt}, cinematic',+ };++ it('submits the merged prompts while the widget keeps the authored text', () => {+ const state = submitGenerate(+ primeGenerate(undefined, {+ negativePrompt: 'blurry',+ negativePromptEnabled: true,+ positivePrompt: 'a cat',+ promptTemplate: template,+ })+ );+ const queueItem = getActiveProject(state).queue.items[0];++ expect(queueItem?.snapshot.backendSubmission).toMatchObject({+ negativePrompt: 'blurry, lowres',+ positivePrompt: 'a cat, cinematic',+ });+ expect(queueItem?.snapshot.widgetStates.generate.values.positivePrompt).toBe('a cat');+ });++ // Switching the negative field off must not let a template put one back.+ it('still sends an empty negative prompt when the field is disabled', () => {+ const state = submitGenerate(+ primeGenerate(undefined, {+ negativePrompt: 'blurry',+ negativePromptEnabled: false,+ positivePrompt: 'a cat',+ promptTemplate: template,+ })+ );++ expect(getActiveProject(state).queue.items[0]?.snapshot.backendSubmission).toMatchObject({+ negativePrompt: '',+ });+ });++ // Recall and the history popover both write straight back into the textarea,+ // so history has to hold what the user typed, not what generated.+ it('records the authored prompt in prompt history', () => {+ const state = submitGenerate(+ primeGenerate(undefined, {+ negativePrompt: 'blurry',+ negativePromptEnabled: true,+ positivePrompt: 'a cat',+ promptTemplate: template,+ })+ );++ expect(getActiveProject(state).promptHistory).toEqual([{ negativePrompt: 'blurry', positivePrompt: 'a cat' }]);+ });+ });++ it('records submitted Generate prompt pairs in project prompt history', () => {+ let state = primeGenerate(undefined, { negativePrompt: ' blurry ', positivePrompt: ' a cat ' });++ state = submitGenerate(state);++ expect(getActiveProject(state).promptHistory).toEqual([{ negativePrompt: 'blurry', positivePrompt: 'a cat' }]);+ });++ it('does not record empty Generate prompt pairs', () => {+ let state = primeGenerate(undefined, { negativePrompt: ' ', positivePrompt: ' ' });++ state = submitGenerate(state);++ expect(getActiveProject(state).promptHistory).toEqual([]);+ });++ it('stores disabled negative prompts as null in project prompt history', () => {+ let state = primeGenerate(undefined, {+ negativePrompt: 'ignored negative prompt',+ negativePromptEnabled: false,+ positivePrompt: 'a cat',+ });++ state = submitGenerate(state);++ expect(getActiveProject(state).promptHistory).toEqual([{ negativePrompt: null, positivePrompt: 'a cat' }]);+ });++ it('patches Generate settings without replacing unchanged nested values', () => {+ const loraModel = { base: 'sdxl', key: 'lora-1', name: 'LoRA', type: 'lora' } as const;+ const state = primeGenerate(undefined, {+ loras: [{ isEnabled: true, model: loraModel, weight: 0.75 }],+ positivePrompt: 'before',+ });+ const beforeValues = getProjectWidgetValues(getActiveProject(state), 'generate') as unknown as GenerateWidgetValues;+ const nextState = workbenchReducer(state, {+ type: 'patchGenerateSettings',+ values: { positivePrompt: 'after' },+ });+ const afterValues = getProjectWidgetValues(+ getActiveProject(nextState),+ 'generate'+ ) as unknown as GenerateWidgetValues;++ expect(afterValues.positivePrompt).toBe('after');+ expect(afterValues.model).toBe(beforeValues.model);+ expect(afterValues.loras).toBe(beforeValues.loras);+ });++ it('shares prompt content through Generate without changing Upscale-local textarea sizing', () => {+ const state = createInitialWorkbenchState();+ const beforeUpscale = getProjectWidgetValues(getActiveProject(state), 'upscale');+ const nextState = workbenchReducer(state, {+ sourceId: 'upscale',+ type: 'patchProjectPromptDraft',+ values: { negativePrompt: 'blur', negativePromptEnabled: false, positivePrompt: 'fine detail' },+ });++ expect(getProjectWidgetValues(getActiveProject(nextState), 'generate')).toMatchObject({+ negativePrompt: 'blur',+ negativePromptEnabled: false,+ positivePrompt: 'fine detail',+ });+ expect(getProjectWidgetValues(getActiveProject(nextState), 'upscale')).toBe(beforeUpscale);+ });++ it('deduplicates prompt history by prompt pair and moves the newest submission to the top', () => {+ let state = primeGenerate(undefined, { negativePrompt: 'low quality', positivePrompt: 'a cat' });++ state = submitGenerate(state);+ state = workbenchReducer(state, {+ type: 'setGenerateSettings',+ values: createGenerateValues({ negativePrompt: 'blurry', positivePrompt: 'a dog' }),+ });+ state = submitGenerate(state);+ state = workbenchReducer(state, {+ type: 'setGenerateSettings',+ values: createGenerateValues({ negativePrompt: 'low quality', positivePrompt: 'a cat' }),+ });+ state = submitGenerate(state);++ expect(getActiveProject(state).promptHistory).toEqual([+ { negativePrompt: 'low quality', positivePrompt: 'a cat' },+ { negativePrompt: 'blurry', positivePrompt: 'a dog' },+ ]);+ });++ it('caps project prompt history', () => {+ let state = createInitialWorkbenchState();++ for (let i = 0; i < MAX_PROMPT_HISTORY + 1; i += 1) {+ state = primeGenerate(state, { positivePrompt: `prompt ${i}` });+ state = submitGenerate(state);+ }++ const history = getActiveProject(state).promptHistory;++ expect(history).toHaveLength(MAX_PROMPT_HISTORY);+ expect(history[0]?.positivePrompt).toBe(`prompt ${MAX_PROMPT_HISTORY}`);+ expect(history.at(-1)?.positivePrompt).toBe('prompt 1');+ });++ it('supports explicit prompt history remove and clear actions', () => {+ let state = primeGenerate(undefined, { negativePrompt: 'low quality', positivePrompt: 'a cat' });++ state = submitGenerate(state);+ state = workbenchReducer(state, {+ prompt: { negativePrompt: 'blurry', positivePrompt: 'a dog' },+ type: 'addPromptToHistory',+ });+ state = workbenchReducer(state, {+ prompt: { negativePrompt: 'low quality', positivePrompt: 'a cat' },+ type: 'removePromptFromHistory',+ });++ expect(getActiveProject(state).promptHistory).toEqual([{ negativePrompt: 'blurry', positivePrompt: 'a dog' }]);++ state = workbenchReducer(state, { type: 'clearPromptHistory' });++ expect(getActiveProject(state).promptHistory).toEqual([]);+ });++ it('does not roll back prompt history during project undo and redo', () => {+ let state = primeGenerate(undefined, { positivePrompt: 'history prompt' });++ state = submitGenerate(state);+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = workbenchReducer(state, { type: 'undoProjectChange' });+ state = workbenchReducer(state, { type: 'redoProjectChange' });++ expect(getActiveProject(state).promptHistory).toEqual([{ negativePrompt: null, positivePrompt: 'history prompt' }]);+ });++ it('hydrates older projects with empty prompt history', () => {+ const initial = createInitialWorkbenchState();+ const legacyState = {+ ...initial,+ projects: initial.projects.map(({ promptHistory: _promptHistory, ...project }) => project),+ } as unknown as WorkbenchState;++ const hydrated = workbenchReducer(initial, { state: legacyState, type: 'hydrateWorkbench' });++ expect(getActiveProject(hydrated).promptHistory).toEqual([]);+ });++ it('routes Gallery destination results to Gallery without staging them on Canvas', () => {+ let state = primeGenerate();++ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);++ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, {+ images: [createImage('gallery-image.png', queueItem.id)],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });++ const updatedProject = getActiveProject(state);+ const galleryValues = getProjectWidgetValues(updatedProject, 'gallery');+ const expectedImage = {+ ...createImage('gallery-image.png', queueItem.id),+ boardId: 'none',+ imageCategory: 'general' as const,+ starred: false,+ };++ expect(updatedProject.canvas.stagingArea.pendingImages).toEqual([]);+ expect(galleryValues.recentImages).toEqual([expectedImage]);+ expect(galleryValues.selectedImage).toEqual(legacyGeneratedImageToGalleryItem(expectedImage));+ expect(galleryValues.selectedImageName).toBe('image:gallery-image.png');+ });++ it('preserves the destination board on freshly routed Gallery results', () => {+ let state = primeGenerate();++ state = workbenchReducer(state, { boardId: 'board-1', type: 'selectGalleryBoard' });+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);++ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];+ const image = createImage('board-image.png', queueItem.id);+ state = workbenchReducer(state, {+ images: [image],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });++ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImage).toMatchObject({+ boardId: 'board-1',+ kind: 'image',+ name: image.imageName,+ });+ });++ it('appends Gallery destination results for local fallback while backend owns boards', () => {+ let state = primeGenerate();++ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);++ const firstQueueItem = getActiveProject(state).queue.items[0];++ state = workbenchReducer(state, {+ images: [createImage('gallery-image-1.png', firstQueueItem.id)],+ projectId: getActiveProject(state).id,+ queueItemId: firstQueueItem.id,+ type: 'routeQueueItemResults',+ });+ state = submitGenerate(state);++ const secondQueueItem = getActiveProject(state).queue.items[0];++ state = workbenchReducer(state, {+ images: [createImage('gallery-image-2.png', secondQueueItem.id)],+ projectId: getActiveProject(state).id,+ queueItemId: secondQueueItem.id,+ type: 'routeQueueItemResults',+ });++ const values = getProjectWidgetValues(getActiveProject(state), 'gallery');++ expect((values.recentImages as GeneratedImageContract[]).map((image) => image.imageName)).toEqual([+ 'gallery-image-2.png',+ 'gallery-image-1.png',+ ]);+ expect(values.imageBoards).toBeUndefined();+ });++ it('retains only the newest 60 images after 1,000 routed Gallery results', () => {+ let state = primeGenerate();++ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);++ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ for (let index = 0; index < 1_000; index += 1) {+ state = workbenchReducer(state, {+ images: [createImage(`gallery-image-${index}.png`, queueItem.id)],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });+ }++ const galleryValues = getProjectWidgetValues(getActiveProject(state), 'gallery');+ const recentImageNames = (galleryValues.recentImages as GeneratedImageContract[]).map((image) => image.imageName);++ expect(GALLERY_RECENT_IMAGE_LIMIT).toBe(60);+ expect(recentImageNames).toEqual(+ Array.from({ length: GALLERY_RECENT_IMAGE_LIMIT }, (_, index) => `gallery-image-${999 - index}.png`)+ );+ expect(galleryValues.selectedImageName).toBe('image:gallery-image-999.png');+ expect(galleryValues.selectedImageNames).toEqual(['image:gallery-image-999.png']);+ });++ it('omits transient recent images from immutable queue snapshots', () => {+ let state = primeGenerate();+ const recentImages = Array.from({ length: GALLERY_RECENT_IMAGE_LIMIT }, (_, index) =>+ createImage(`recent-${index}.png`, 'previous-queue-item')+ );++ state = workbenchReducer(state, {+ type: 'patchWidgetValues',+ values: { recentImages },+ widgetId: 'gallery',+ });+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);++ const snapshot = getActiveProject(state).queue.items[0]!.snapshot;+ const galleryInstance = Object.values(snapshot.widgetInstances).find((instance) => instance.typeId === 'gallery');++ expect(snapshot.widgetStates.gallery?.values.recentImages).toBeUndefined();+ expect(galleryInstance?.state.values.recentImages).toBeUndefined();+ });++ it('validates, deduplicates, and truncates persisted recent images during hydration', () => {+ const initial = createInitialWorkbenchState();+ const legacyImages = Array.from({ length: 1_000 }, (_, index) =>+ createImage(`persisted-image-${999 - index}.png`, 'legacy-queue-item')+ );+ const selectedImage = legacyImages.at(-1)!;+ const legacyRecentImages: unknown[] = [+ legacyImages[0],+ null,+ legacyImages[0],+ { imageName: 42 },+ ...legacyImages.slice(1),+ ];+ const persisted: WorkbenchState = {+ ...initial,+ projects: initial.projects.map((project) => {+ const galleryInstance = project.widgetInstances.gallery!;++ return {+ ...project,+ widgetInstances: {+ ...project.widgetInstances,+ gallery: {+ ...galleryInstance,+ state: {+ ...galleryInstance.state,+ values: {+ ...galleryInstance.state.values,+ recentImages: legacyRecentImages,+ selectedImage,+ selectedImageName: selectedImage.imageName,+ },+ },+ },+ },+ };+ }),+ };++ const hydrated = workbenchReducer(initial, { state: persisted, type: 'hydrateWorkbench' });+ const galleryValues = getProjectWidgetValues(getActiveProject(hydrated), 'gallery');+ const recentImageNames = (galleryValues.recentImages as GeneratedImageContract[]).map((image) => image.imageName);++ expect(recentImageNames).toEqual(+ Array.from({ length: GALLERY_RECENT_IMAGE_LIMIT }, (_, index) => `persisted-image-${999 - index}.png`)+ );+ expect(galleryValues.selectedImage).toEqual(selectedImage);+ expect(galleryValues.selectedImageName).toBe(selectedImage.imageName);+ });++ it('routes partial Gallery destination results without completing the local queue item', () => {+ let state = primeGenerate(undefined, { batchCount: 2 });++ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);++ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, {+ backendItemId: 11,+ images: [createImage('gallery-image-1.png', queueItem.id)],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemPartialResults',+ });++ const updatedQueueItem = getActiveProject(state).queue.items[0];+ const galleryValues = getProjectWidgetValues(getActiveProject(state), 'gallery');++ expect(updatedQueueItem.status).toBe('pending');+ expect(updatedQueueItem.completedBackendItemIds).toEqual([11]);+ expect(updatedQueueItem.resultImages).toEqual([createImage('gallery-image-1.png', queueItem.id)]);+ expect((galleryValues.recentImages as GeneratedImageContract[]).map((image) => image.imageName)).toEqual([+ 'gallery-image-1.png',+ ]);+ });++ it('preserves the last partial Gallery result when the final aggregate repeats the batch', () => {+ let state = primeGenerate(undefined, { batchCount: 3 });++ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);++ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];+ const images = ['gallery-image-1.png', 'gallery-image-2.png', 'gallery-image-3.png'].map((name) =>+ createImage(name, queueItem.id)+ );++ state = workbenchReducer(state, {+ backendItemIds: [11, 12, 13],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });++ for (const [index, image] of images.entries()) {+ state = workbenchReducer(state, {+ backendItemId: 11 + index,+ images: [image],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemPartialResults',+ });+ }++ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe(+ 'image:gallery-image-3.png'+ );++ state = workbenchReducer(state, {+ images,+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });++ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe(+ 'image:gallery-image-3.png'+ );+ });++ it('does not reorder existing results when an older batch final aggregate arrives late', () => {+ let state = primeGenerate(undefined, { batchCount: 2 });++ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);++ const projectId = getActiveProject(state).id;+ const olderQueueItem = getActiveProject(state).queue.items[0];+ const olderImage1 = createImage('older-1.png', olderQueueItem.id);+ const olderImage2 = createImage('older-2.png', olderQueueItem.id);++ state = workbenchReducer(state, {+ backendItemId: 11,+ images: [olderImage1],+ projectId,+ queueItemId: olderQueueItem.id,+ type: 'routeQueueItemPartialResults',+ });+ state = submitGenerate(state);++ const newerQueueItem = getActiveProject(state).queue.items[0];+ const newerImage = createImage('newer-1.png', newerQueueItem.id);++ state = workbenchReducer(state, {+ backendItemId: 21,+ images: [newerImage],+ projectId,+ queueItemId: newerQueueItem.id,+ type: 'routeQueueItemPartialResults',+ });+ state = workbenchReducer(state, {+ images: [olderImage1, olderImage2],+ projectId,+ queueItemId: olderQueueItem.id,+ type: 'routeQueueItemResults',+ });++ expect(+ (getProjectWidgetValues(getActiveProject(state), 'gallery').recentImages as GeneratedImageContract[]).map(+ (image) => image.imageName+ )+ ).toEqual(['older-2.png', 'newer-1.png', 'older-1.png']);+ });++ it('selects the last image from a final-only Gallery batch', () => {+ let state = primeGenerate(undefined, { batchCount: 3 });++ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);++ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, {+ images: ['gallery-image-1.png', 'gallery-image-2.png', 'gallery-image-3.png'].map((name) =>+ createImage(name, queueItem.id)+ ),+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });++ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe(+ 'image:gallery-image-3.png'+ );+ });++ it('pauses live-follow when the user selects a saved Gallery image', () => {+ let state = createInitialWorkbenchState();++ expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(true);++ state = workbenchReducer(state, {+ item: createGalleryImageItem('selected.png'),+ type: 'selectGalleryItem',+ });++ expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(false);+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:selected.png');+ });++ it('preserves a manually selected image when later Gallery results arrive', () => {+ let state = primeGenerate();+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);++ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];+ const selectedImage = createGalleryImageItem('selected.png');+ state = workbenchReducer(state, { item: selectedImage, type: 'selectGalleryItem' });+ state = workbenchReducer(state, {+ images: [createImage('completed.png', queueItem.id)],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });++ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:selected.png');+ });++ it('pauses live-follow for saved Gallery multi-selection and comparison intents', () => {+ const primaryImage = createGalleryImageItem('primary.png');+ const compareImage = createGalleryImageItem('compare.png');+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, {+ itemKeys: ['image:primary.png', 'image:compare.png'],+ primaryItem: primaryImage,+ type: 'setGalleryMultiSelection',+ });++ expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(false);++ state = workbenchReducer(state, {+ settings: { showProgressImagesInViewer: true },+ type: 'setActiveProjectSettings',+ });+ state = workbenchReducer(state, { image: compareImage, type: 'setGalleryCompareImage' });++ expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(false);+ });++ it('stores selected backend board id for gallery submissions', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { boardId: 'backend-board-id', type: 'selectGalleryBoard' });+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = primeGenerate(state);+ state = submitGenerate(state);++ const queueItem = getActiveProject(state).queue.items[0];++ expect(queueItem.snapshot.widgetStates.gallery.values.selectedBoardId).toBe('backend-board-id');+ });++ it('stores full selected gallery image data for Preview widget', () => {+ let state = createInitialWorkbenchState();+ const image = createGalleryImageItem('backend-selected.png');++ state = workbenchReducer(state, { item: image, type: 'selectGalleryItem' });++ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe(+ 'image:backend-selected.png'+ );+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImage).toEqual(image);+ });+});++describe('workbench account and project settings', () => {+ it('starts with the default layout preset and legacy-matching project settings', () => {+ const state = createInitialWorkbenchState();++ expect(state.account).toEqual({ activeLayoutPresetId: 'compose' });+ expect(getActiveProject(state).settings).toEqual(DEFAULT_PROJECT_SETTINGS);+ });++ it('drops legacy preferences carried inside persisted accounts on hydrate', () => {+ const initial = createInitialWorkbenchState();+ const legacy = {+ ...initial,+ account: { activeLayoutPresetId: 'gallery', preferences: { themeId: 'forest' } },+ } as unknown as WorkbenchState;++ const state = workbenchReducer(initial, { state: legacy, type: 'hydrateWorkbench' });++ // `gallery` was retired with the three-preset model; it resolves to Compose,+ // the arrangement it was a center-view variant of.+ expect(state.account).toEqual({+ activeLayoutPresetId: 'compose',+ customLayoutPresets: [],+ layoutPresetOverrides: {},+ });+ });++ it('heals hydrated accounts that are missing a layout preset', () => {+ const initial = createInitialWorkbenchState();+ const legacy = { ...initial, account: {} } as unknown as WorkbenchState;++ const state = workbenchReducer(initial, { state: legacy, type: 'hydrateWorkbench' });++ expect(state.account.activeLayoutPresetId).toBe('compose');+ });++ it('updates project settings on the active project only', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, {+ settings: { antialiasProgressImages: true, useCpuNoise: false },+ type: 'setActiveProjectSettings',+ });++ expect(getActiveProject(state).settings).toEqual({+ antialiasProgressImages: true,+ showProgressDetails: false,+ showProgressImagesInViewer: true,+ useCpuNoise: false,+ });+ });+});++describe('workbench backend connection recovery', () => {+ it('tracks backend connection status', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, {+ status: 'disconnected',+ type: 'setBackendConnectionStatus',+ error: 'server down',+ });++ expect(state.backendConnection.status).toBe('disconnected');+ expect(state.backendConnection.error).toBe('server down');+ expect(state.backendConnection.lastDisconnectedAt).toBeDefined();++ state = workbenchReducer(state, { status: 'connected', type: 'setBackendConnectionStatus' });++ expect(state.backendConnection.status).toBe('connected');+ expect(state.backendConnection.error).toBeUndefined();+ expect(state.backendConnection.lastConnectedAt).toBeDefined();+ });++ it('writes canonical mixed selections with ordered qualified keys and clears comparison for video', () => {+ const image = createGalleryImageItem('shared');+ const video = createGalleryVideoItem('shared');+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { image, type: 'setGalleryCompareImage' });+ state = workbenchReducer(state, { item: video, type: 'selectGalleryItem' });++ let values = getProjectWidgetValues(getActiveProject(state), 'gallery');++ expect(values.selectedImage).toBe(video);+ expect(values.selectedImageName).toBe('video:shared');+ expect(values.selectedImageNames).toEqual(['video:shared']);+ expect(values.compareImage).toBeNull();++ state = workbenchReducer(state, { item: image, nextPrimaryItem: null, type: 'toggleGalleryItemInSelection' });+ values = getProjectWidgetValues(getActiveProject(state), 'gallery');++ expect(values.selectedImage).toBe(image);+ expect(values.selectedImageName).toBe('image:shared');+ expect(values.selectedImageNames).toEqual(['video:shared', 'image:shared']);++ state = workbenchReducer(state, {+ itemKeys: ['image:shared', 'video:shared'],+ primaryItem: video,+ type: 'setGalleryMultiSelection',+ });+ values = getProjectWidgetValues(getActiveProject(state), 'gallery');++ expect(values.selectedImage).toBe(video);+ expect(values.selectedImageName).toBe('video:shared');+ expect(values.selectedImageNames).toEqual(['image:shared', 'video:shared']);+ expect(values.compareImage).toBeNull();+ });++ it('atomically promotes the remaining video when the image primary is toggled off', () => {+ const image = createGalleryImageItem('shared');+ const video = createGalleryVideoItem('shared');+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, {+ itemKeys: ['video:shared', 'image:shared'],+ primaryItem: image,+ type: 'setGalleryMultiSelection',+ });+ state = workbenchReducer(state, { image, type: 'setGalleryCompareImage' });+ state = workbenchReducer(state, {+ item: image,+ nextPrimaryItem: video,+ type: 'toggleGalleryItemInSelection',+ });++ expect(getProjectWidgetValues(getActiveProject(state), 'gallery')).toMatchObject({+ compareImage: null,+ selectedImage: video,+ selectedImageName: 'video:shared',+ selectedImageNames: ['video:shared'],+ });+ });++ it('prunes qualified items across projects without treating a same-name video as an image input', () => {+ const image = createGalleryImageItem('shared');+ const video = createGalleryVideoItem('shared');+ const recentImage = galleryItemToRecentImage(image);+ let state = createInitialWorkbenchState();+ const firstProjectId = state.activeProjectId;++ state = workbenchReducer(state, { type: 'createProject' });+ const secondProjectId = state.activeProjectId;+ state = workbenchReducer(state, {+ projectId: firstProjectId,+ type: 'patchWidgetValues',+ values: {+ compareImage: image,+ recentImages: [recentImage],+ selectedImage: image,+ selectedImageName: 'image:shared',+ selectedImageNames: ['image:shared'],+ },+ widgetId: 'gallery',+ });+ state = workbenchReducer(state, {+ projectId: secondProjectId,+ type: 'patchWidgetValues',+ values: {+ recentImages: [recentImage],+ selectedImage: video,+ selectedImageName: 'video:shared',+ selectedImageNames: ['video:shared'],+ },+ widgetId: 'gallery',+ });+ for (const projectId of [firstProjectId, secondProjectId]) {+ state = workbenchReducer(state, {+ projectId,+ type: 'patchWidgetValues',+ values: { inputImage: { height: image.height, image_name: image.name, width: image.width } },+ widgetId: 'upscale',+ });+ }++ state = workbenchReducer(state, {+ itemKeys: ['video:shared'],+ type: 'removeGalleryItems',+ });++ expect(getProjectWidgetValues(getProject(state, firstProjectId), 'gallery')).toMatchObject({+ compareImage: image,+ recentImages: [recentImage],+ selectedImage: image,+ selectedImageName: 'image:shared',+ selectedImageNames: ['image:shared'],+ });+ expect(getProjectWidgetValues(getProject(state, secondProjectId), 'gallery')).toMatchObject({+ recentImages: [recentImage],+ selectedImage: null,+ selectedImageName: null,+ selectedImageNames: [],+ });+ expect(getProjectWidgetValues(getProject(state, firstProjectId), 'upscale').inputImage).not.toBeNull();+ expect(getProjectWidgetValues(getProject(state, secondProjectId), 'upscale').inputImage).not.toBeNull();++ state = workbenchReducer(state, {+ itemKeys: ['image:shared'],+ type: 'removeGalleryItems',+ });++ for (const projectId of [firstProjectId, secondProjectId]) {+ expect(getProjectWidgetValues(getProject(state, projectId), 'gallery').recentImages).toEqual([]);+ expect(getProjectWidgetValues(getProject(state, projectId), 'upscale').inputImage).toBeNull();+ }+ });++ it('reconciles authoritative board outcomes by deleting confirmed media and moving every survivor', () => {+ const boardId = 'deleted-board';+ const deletedImage = createGalleryImageItem('deleted-image', boardId);+ const failedImage = createGalleryImageItem('failed-image', boardId);+ const deletedVideo = createGalleryVideoItem('deleted-video', boardId);+ const failedVideo = createGalleryVideoItem('failed-video', boardId);+ let state = createInitialWorkbenchState();++ while (state.projects.length < 4) {+ state = workbenchReducer(state, { type: 'createProject' });+ }++ const fixtures = [+ {+ item: deletedImage,+ recentImages: [galleryItemToRecentImage(deletedImage)],+ },+ {+ item: failedImage,+ recentImages: [galleryItemToRecentImage(failedImage)],+ },+ { item: deletedVideo, recentImages: [] },+ { item: failedVideo, recentImages: [] },+ ] as const;++ for (const [index, project] of state.projects.entries()) {+ const fixture = fixtures[index]!;+ state = workbenchReducer(state, {+ projectId: project.id,+ type: 'patchWidgetValues',+ values: {+ projectBoardId: index === 0 ? boardId : null,+ recentImages: fixture.recentImages,+ selectedBoardId: boardId,+ selectedImage: fixture.item,+ selectedImageName: `${fixture.item.kind}:${fixture.item.name}`,+ selectedImageNames: [`${fixture.item.kind}:${fixture.item.name}`],+ },+ widgetId: 'gallery',+ });+ }++ state = workbenchReducer(state, {+ outcome: {+ boardId,+ deletedBoardImageNames: [],+ deletedBoardVideoNames: [],+ deletedImageNames: [deletedImage.name],+ deletedVideoNames: [deletedVideo.name],+ failedImageNames: [failedImage.name],+ failedVideoNames: [failedVideo.name],+ },+ type: 'reconcileDeletedGalleryBoard',+ });++ const [deletedImageProject, failedImageProject, deletedVideoProject, failedVideoProject] = state.projects.map(+ (project) => getProjectWidgetValues(project, 'gallery')+ );++ expect(deletedImageProject).toMatchObject({+ projectBoardId: null,+ recentImages: [],+ selectedBoardId: 'none',+ selectedImage: null,+ selectedImageName: null,+ selectedImageNames: [],+ });+ expect(failedImageProject?.selectedImage).toMatchObject({ boardId: 'none', kind: 'image', name: failedImage.name });+ expect(failedImageProject?.recentImages).toEqual([{ ...galleryItemToRecentImage(failedImage), boardId: 'none' }]);+ expect(deletedVideoProject).toMatchObject({+ selectedImage: null,+ selectedImageName: null,+ selectedImageNames: [],+ });+ expect(failedVideoProject?.selectedImage).toMatchObject({ boardId: 'none', kind: 'video', name: failedVideo.name });++ for (const values of [failedImageProject, deletedVideoProject, failedVideoProject]) {+ expect(values?.selectedBoardId).toBe('none');+ }+ });++ it('moves image and video board relationships to Uncategorized when board contents are retained', () => {+ const boardId = 'deleted-board';+ const image = createGalleryImageItem('retained-image', boardId);+ const video = createGalleryVideoItem('retained-video', boardId);+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, {+ type: 'patchWidgetValues',+ values: {+ recentImages: [galleryItemToRecentImage(image)],+ selectedBoardId: boardId,+ selectedImage: video,+ selectedImageName: `video:${video.name}`,+ selectedImageNames: [`image:${image.name}`, `video:${video.name}`],+ },+ widgetId: 'gallery',+ });+ state = workbenchReducer(state, {+ outcome: {+ boardId,+ deletedBoardImageNames: [image.name],+ deletedBoardVideoNames: [video.name],+ deletedImageNames: [],+ deletedVideoNames: [],+ failedImageNames: [],+ failedVideoNames: [],+ },+ type: 'reconcileDeletedGalleryBoard',+ });++ const values = getProjectWidgetValues(getActiveProject(state), 'gallery');++ expect(values).toMatchObject({+ recentImages: [{ ...galleryItemToRecentImage(image), boardId: 'none' }],+ selectedBoardId: 'none',+ selectedImage: { ...video, boardId: 'none' },+ selectedImageName: `video:${video.name}`,+ selectedImageNames: [`image:${image.name}`, `video:${video.name}`],+ });+ });++ it('reconciles moved and starred metadata across every project recent-image overlay', () => {+ let state = createInitialWorkbenchState();+ const image = createImage('patched.png', 'backend-gallery');++ state = workbenchReducer(state, { type: 'createProject' });+ for (const project of state.projects) {+ state = workbenchReducer(state, {+ projectId: project.id,+ type: 'patchWidgetValues',+ values: { compareImage: image, recentImages: [image], selectedImage: image },+ widgetId: 'gallery',+ });+ }+ state = workbenchReducer(state, {+ changes: { boardId: 'board-2', starred: true },+ itemKeys: [`image:${image.imageName}`],+ type: 'patchGalleryItems',+ });++ for (const project of state.projects) {+ const values = getProjectWidgetValues(project, 'gallery');+ const patchedImage = { ...image, boardId: 'board-2', starred: true };++ expect(values.recentImages).toEqual([patchedImage]);+ expect(values.selectedImage).toEqual(legacyGeneratedImageToGalleryItem(patchedImage));+ expect(values.compareImage).toEqual(legacyGeneratedImageToGalleryItem(patchedImage));+ }+ });++ it('removes deleted backend images and upscale references from every project', () => {+ let state = createInitialWorkbenchState();+ const firstProjectId = state.activeProjectId;+ const image = createImage('shared.png', 'backend-gallery');++ state = workbenchReducer(state, { type: 'createProject' });+ const secondProjectId = state.activeProjectId;+ state = workbenchReducer(state, {+ projectId: firstProjectId,+ type: 'patchWidgetValues',+ values: { recentImages: [image], selectedImage: image, selectedImageName: image.imageName },+ widgetId: 'gallery',+ });+ state = workbenchReducer(state, {+ projectId: secondProjectId,+ type: 'patchWidgetValues',+ values: { recentImages: [image], selectedImage: image, selectedImageName: image.imageName },+ widgetId: 'gallery',+ });+ for (const projectId of [firstProjectId, secondProjectId]) {+ state = workbenchReducer(state, {+ projectId,+ type: 'patchWidgetValues',+ values: { inputImage: { height: image.height, image_name: image.imageName, width: image.width } },+ widgetId: 'upscale',+ });+ }++ state = workbenchReducer(state, {+ itemKeys: [`image:${image.imageName}`],+ type: 'removeGalleryItems',+ });++ expect(getProjectWidgetValues(getProject(state, firstProjectId), 'gallery').recentImages).toEqual([]);+ expect(getProjectWidgetValues(getProject(state, secondProjectId), 'gallery').recentImages).toEqual([]);+ expect(getProjectWidgetValues(getProject(state, firstProjectId), 'upscale').inputImage).toBeNull();+ expect(getProjectWidgetValues(getProject(state, secondProjectId), 'upscale').inputImage).toBeNull();+ });++ it('does not hydrate stale persisted backend connection state', () => {+ const initial = createInitialWorkbenchState();+ const persisted = {+ ...initial,+ backendConnection: { lastConnectedAt: '2026-06-10T00:00:00.000Z', status: 'connected' },+ } as WorkbenchState;++ const state = workbenchReducer(initial, { state: persisted, type: 'hydrateWorkbench' });++ expect(state.backendConnection).toEqual({ status: 'connecting' });+ });++ it('preserves live backend connection state when persistence hydrates late', () => {+ const initial = createInitialWorkbenchState();+ const connected = workbenchReducer(initial, { status: 'connected', type: 'setBackendConnectionStatus' });+ const persisted = {+ ...initial,+ backendConnection: { status: 'connecting' },+ } as WorkbenchState;++ const state = workbenchReducer(connected, { state: persisted, type: 'hydrateWorkbench' });++ expect(state.backendConnection.status).toBe('connected');+ expect(state.backendConnection.lastConnectedAt).toBe(connected.backendConnection.lastConnectedAt);+ });++ it('does not hydrate stale notifications that would toast again after reload', () => {+ const initial = createInitialWorkbenchState();+ const persisted = workbenchReducer(initial, {+ kind: 'success',+ message: 'Old success toast',+ title: 'Invocation completed',+ type: 'recordNotice',+ });++ const state = workbenchReducer(initial, { state: persisted, type: 'hydrateWorkbench' });++ expect(persisted.notifications).toHaveLength(1);+ expect(state.notifications).toEqual([]);+ });+});++describe('nextLayerName', () => {+ it('starts at Layer 1 with no existing layers', () => {+ expect(nextLayerName([])).toBe('Layer 1');+ });++ it('picks the next free number above a contiguous run', () => {+ expect(nextLayerName(['Layer 1', 'Layer 2'])).toBe('Layer 3');+ });++ it('fills the lowest gap so names do not collide after a deletion', () => {+ // Deleting "Layer 2" from [Layer 1, Layer 2, Layer 3] must not re-mint the+ // count-derived "Layer 3" (which would collide); the lowest free slot is 2.+ expect(nextLayerName(['Layer 1', 'Layer 3'])).toBe('Layer 2');+ });++ it('ignores custom names and non-matching patterns', () => {+ expect(nextLayerName(['Backdrop', 'Layer 10 copy', 'Layer 1'])).toBe('Layer 2');+ expect(nextLayerName(['Sketch'])).toBe('Layer 1');+ });+});++describe('workbenchReducer canvas v2 layer reducers', () => {+ it('routes a canvas mutation to its bound project after the active project switches', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('origin-layer')]);+ const originProjectId = state.activeProjectId;++ state = workbenchReducer(state, { type: 'createProject' });+ const activeProjectId = state.activeProjectId;+ state = workbenchReducer(state, {+ mutation: { id: 'origin-layer', patch: { opacity: 0.25 }, type: 'updateCanvasLayer' },+ projectId: originProjectId,+ type: 'applyCanvasProjectMutation',+ } as WorkbenchAction);++ expect(getProject(state, originProjectId).canvas.document.layers[0]?.opacity).toBe(0.25);+ expect(getProject(state, activeProjectId).canvas.document.layers[0]?.opacity).not.toBe(0.25);+ });++ it('seeds a new project canvas with a single empty inpaint mask, selected', () => {+ const state = createInitialWorkbenchState();+ const { document } = getActiveProject(state).canvas;++ expect(document.layers).toHaveLength(1);+ const mask = document.layers[0];+ expect(mask?.type).toBe('inpaint_mask');+ // Empty: no bitmap (no strokes) — so it never flips generation-mode detection.+ expect(mask && 'mask' in mask ? mask.mask.bitmap : 'missing').toBeNull();+ expect(document.selectedLayerId).toBe(mask?.id);+ });++ it('adds a layer at the top and selects it, honoring an explicit insert index', () => {+ let state = withEmptyCanvas(createInitialWorkbenchState());++ state = workbenchReducer(state, { layer: createRasterLayer('a'), type: 'addCanvasLayer' });+ state = workbenchReducer(state, { layer: createRasterLayer('b'), type: 'addCanvasLayer' });++ expect(getLayerIds(state)).toEqual(['b', 'a']);+ expect(getCanvas(state).document.selectedLayerId).toBe('b');++ state = workbenchReducer(state, { index: 1, layer: createRasterLayer('c'), type: 'addCanvasLayer' });++ expect(getLayerIds(state)).toEqual(['b', 'c', 'a']);+ expect(getCanvas(state).document.selectedLayerId).toBe('c');+ });++ it('removes layers and repairs selection to the nearest remaining layer (below, then above)', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [+ createRasterLayer('a'),+ createRasterLayer('b'),+ createRasterLayer('c'),+ ]);++ state = workbenchReducer(state, { id: 'b', type: 'setCanvasSelectedLayer' });+ state = workbenchReducer(state, { ids: ['b'], type: 'removeCanvasLayers' });++ // 'b' sat between 'a' and 'c'; the nearest survivor below it is 'c'.+ expect(getLayerIds(state)).toEqual(['a', 'c']);+ expect(getCanvas(state).document.selectedLayerId).toBe('c');++ state = workbenchReducer(state, { id: 'c', type: 'setCanvasSelectedLayer' });+ state = workbenchReducer(state, { ids: ['c'], type: 'removeCanvasLayers' });++ // Nothing remains below 'c', so selection falls back to 'a' above it.+ expect(getCanvas(state).document.selectedLayerId).toBe('a');++ state = workbenchReducer(state, { ids: ['a'], type: 'removeCanvasLayers' });++ expect(getLayerIds(state)).toEqual([]);+ expect(getCanvas(state).document.selectedLayerId).toBeNull();+ });++ it('hides overlay layers without disabling them, so generation is untouched', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createInpaintMaskLayer('m'), createRasterLayer('r')]);++ state = workbenchReducer(state, {+ type: 'setCanvasLayersHidden',+ updates: [+ { id: 'm', isHidden: true },+ { id: 'r', isHidden: true },+ ],+ });++ const layers = getCanvas(state).document.layers;+ const mask = layers.find((layer) => layer.id === 'm')!;+ const raster = layers.find((layer) => layer.id === 'r')!;++ expect(mask).toMatchObject({ isEnabled: true, isHidden: true });+ // Raster layers have no display axis; the update is skipped rather than+ // silently giving them a meaningless field.+ expect(raster).not.toHaveProperty('isHidden');+ expect(raster.isEnabled).toBe(true);+ });++ it('leaves the document untouched when a hide update changes nothing', () => {+ const state = withCanvasLayers(createInitialWorkbenchState(), [createInpaintMaskLayer('m')]);+ const before = getCanvas(state).document;++ const next = workbenchReducer(state, {+ type: 'setCanvasLayersHidden',+ updates: [{ id: 'm', isHidden: false }],+ });++ expect(getCanvas(next).document).toBe(before);+ });++ it('sets many layers visibility in one bulk action, preserving unlisted layers by identity', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [+ createRasterLayer('a'),+ createRasterLayer('b'),+ createRasterLayer('c'),+ ]);+ const before = getCanvas(state).document.layers;++ // Hide 'a' and 'c' in one dispatch; 'b' is unlisted and must keep its object identity.+ state = workbenchReducer(state, {+ type: 'setCanvasLayersEnabled',+ updates: [+ { id: 'a', isEnabled: false },+ { id: 'c', isEnabled: false },+ ],+ });+ const after = getCanvas(state).document.layers;++ expect(after.map((layer) => [layer.id, layer.isEnabled])).toEqual([+ ['a', false],+ ['b', true],+ ['c', false],+ ]);+ // 'b' unchanged ⇒ same reference; 'a'/'c' replaced.+ expect(after[1]).toBe(before[1]);+ expect(after[0]).not.toBe(before[0]);+ });++ it('returns the same document when a bulk visibility action changes nothing', () => {+ const state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]);+ const before = getCanvas(state).document;++ const next = workbenchReducer(state, {+ type: 'setCanvasLayersEnabled',+ updates: [{ id: 'a', isEnabled: true }],+ });++ // 'a' is already enabled ⇒ no change ⇒ document identity preserved (no selector churn).+ expect(getCanvas(next).document).toBe(before);+ });++ it('applies and reverses a layer stack mutation atomically while preserving unrelated layer identity', () => {+ const upper = createRasterLayer('upper');+ const below = createRasterLayer('below');+ const unrelated = { ...createRasterLayer('unrelated'), isEnabled: false };+ const result = createRasterLayer('result');+ const initial = workbenchReducer(withCanvasLayers(createInitialWorkbenchState(), [unrelated, upper, below]), {+ id: unrelated.id,+ type: 'setCanvasSelectedLayer',+ });+ const unrelatedBefore = getCanvas(initial).document.layers[0];++ const applied = workbenchReducer(initial, {+ add: { index: 1, layers: [result] },+ enabledUpdates: [+ { id: upper.id, isEnabled: false },+ { id: below.id, isEnabled: false },+ ],+ selectedLayerId: result.id,+ type: 'applyCanvasLayerStackMutation',+ });++ expect(applied).toBeDefined();+ expect(getCanvas(applied).document.layers.map((layer) => [layer.id, layer.isEnabled])).toEqual([+ ['unrelated', false],+ ['result', true],+ ['upper', false],+ ['below', false],+ ]);+ expect(getCanvas(applied).document.selectedLayerId).toBe(result.id);+ expect(getCanvas(applied).document.layers[0]).toBe(unrelatedBefore);++ const reverted = workbenchReducer(applied, {+ enabledUpdates: [+ { id: upper.id, isEnabled: true },+ { id: below.id, isEnabled: true },+ ],+ removeIds: [result.id],+ selectedLayerId: unrelated.id,+ type: 'applyCanvasLayerStackMutation',+ });++ expect(getCanvas(reverted).document.layers.map((layer) => [layer.id, layer.isEnabled])).toEqual([+ ['unrelated', false],+ ['upper', true],+ ['below', true],+ ]);+ expect(getCanvas(reverted).document.selectedLayerId).toBe(unrelated.id);+ expect(getCanvas(reverted).document.layers[0]).toBe(unrelatedBefore);+ });++ it('inserts a batch in order and selects the exact requested layer', () => {+ const existing = createRasterLayer('existing');+ const layerA = createRasterLayer('a');+ const layerB = createRasterLayer('b');+ const initial = withCanvasLayers(createInitialWorkbenchState(), [existing]);++ const next = workbenchReducer(initial, {+ add: { index: 0, layers: [layerA, layerB] },+ enabledUpdates: [],+ selectedLayerId: layerB.id,+ type: 'applyCanvasLayerStackMutation',+ });++ expect(getCanvas(next).document.layers).toEqual([layerA, layerB, existing]);+ expect(getCanvas(next).document.selectedLayerId).toBe(layerB.id);+ });++ it('targets a non-active project without changing the active project', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('first-existing')]);+ const firstProjectId = state.activeProjectId;+ state = workbenchReducer(state, { type: 'createProject' });+ const secondProjectId = state.activeProjectId;+ const secondProjectBefore = getProject(state, secondProjectId);+ const layerA = createRasterLayer('a');+ const layerB = createRasterLayer('b');++ const next = workbenchReducer(state, {+ add: { index: 0, layers: [layerA, layerB] },+ enabledUpdates: [],+ projectId: firstProjectId,+ selectedLayerId: layerB.id,+ type: 'applyCanvasLayerStackMutation',+ });++ expect(getProject(next, firstProjectId).canvas.document.layers.slice(0, 2)).toEqual([layerA, layerB]);+ expect(getProject(next, firstProjectId).canvas.document.selectedLayerId).toBe(layerB.id);+ expect(getProject(next, secondProjectId)).toBe(secondProjectBefore);+ });++ it('rejects an invalid layer stack mutation without applying any valid fields', () => {+ const initial = workbenchReducer(+ withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]),+ { id: 'b', type: 'setCanvasSelectedLayer' }+ );+ const invalidActions = [+ {+ add: { index: 0, layers: [createRasterLayer('a')] },+ enabledUpdates: [{ id: 'b', isEnabled: false }],+ selectedLayerId: 'b',+ type: 'applyCanvasLayerStackMutation',+ },+ {+ enabledUpdates: [{ id: 'a', isEnabled: false }],+ removeIds: ['missing'],+ selectedLayerId: 'b',+ type: 'applyCanvasLayerStackMutation',+ },+ {+ enabledUpdates: [{ id: 'missing', isEnabled: false }],+ selectedLayerId: 'b',+ type: 'applyCanvasLayerStackMutation',+ },+ {+ enabledUpdates: [],+ selectedLayerId: 'missing',+ type: 'applyCanvasLayerStackMutation',+ },+ {+ enabledUpdates: [{ id: 'a', isEnabled: false }],+ removeIds: ['a'],+ selectedLayerId: 'b',+ type: 'applyCanvasLayerStackMutation',+ },+ {+ add: { index: 0, layers: [createRasterLayer('c')] },+ enabledUpdates: [],+ removeIds: ['a'],+ selectedLayerId: 'b',+ type: 'applyCanvasLayerStackMutation',+ },+ {+ add: { index: 0, layers: [createRasterLayer('c'), createRasterLayer('c')] },+ enabledUpdates: [{ id: 'b', isEnabled: false }],+ selectedLayerId: 'c',+ type: 'applyCanvasLayerStackMutation',+ },+ ] satisfies CanvasProjectMutation[];++ for (const action of invalidActions) {+ expect(workbenchReducer(initial, action)).toBe(initial);+ }+ });++ it('preserves the layers array for a selection-only layer stack mutation', () => {+ const initial = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]);+ const before = getCanvas(initial).document.layers;++ const next = workbenchReducer(initial, {+ enabledUpdates: [],+ selectedLayerId: 'b',+ type: 'applyCanvasLayerStackMutation',+ });++ expect(getCanvas(next).document.layers).toBe(before);+ expect(getCanvas(next).document.selectedLayerId).toBe('b');+ });++ it('duplicates a layer above its source with a copy name and selects the duplicate', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]);++ state = workbenchReducer(state, { newId: 'b-copy', sourceId: 'b', type: 'duplicateCanvasLayer' });++ expect(getLayerIds(state)).toEqual(['a', 'b-copy', 'b']);+ expect(getCanvas(state).document.selectedLayerId).toBe('b-copy');++ const [, duplicate, source] = getCanvas(state).document.layers;++ expect(duplicate?.name).toBe('b copy');+ expect(duplicate).not.toBe(source);+ expect(getRasterLayerImageName(duplicate)).toBe(getRasterLayerImageName(source));+ });++ it('reorders layers only when the id set matches, and preserves layer identity', () => {+ const state = withCanvasLayers(createInitialWorkbenchState(), [+ createRasterLayer('a'),+ createRasterLayer('b'),+ createRasterLayer('c'),+ ]);+ const originalLayerA = getCanvas(state).document.layers.find((layer) => layer.id === 'a');++ const reordered = workbenchReducer(state, { orderedIds: ['c', 'a', 'b'], type: 'reorderCanvasLayers' });++ expect(getLayerIds(reordered)).toEqual(['c', 'a', 'b']);+ // Untouched layer objects are reused, not cloned.+ expect(getCanvas(reordered).document.layers.find((layer) => layer.id === 'a')).toBe(originalLayerA);++ const ignoredMissing = workbenchReducer(state, { orderedIds: ['c', 'a'], type: 'reorderCanvasLayers' });+ const ignoredUnknown = workbenchReducer(state, { orderedIds: ['c', 'a', 'z'], type: 'reorderCanvasLayers' });++ expect(getLayerIds(ignoredMissing)).toEqual(['a', 'b', 'c']);+ expect(getLayerIds(ignoredUnknown)).toEqual(['a', 'b', 'c']);+ });++ it('updates base props with a field-wise transform merge and leaves other layers untouched', () => {+ const state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]);+ const originalLayerB = getCanvas(state).document.layers.find((layer) => layer.id === 'b');++ const updated = workbenchReducer(state, {+ id: 'a',+ patch: { name: 'Renamed', opacity: 0.5, transform: { x: 12 } },+ type: 'updateCanvasLayer',+ });++ const layerA = getCanvas(updated).document.layers.find((layer) => layer.id === 'a');++ expect(layerA?.name).toBe('Renamed');+ expect(layerA?.opacity).toBe(0.5);+ expect(layerA?.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 12, y: 0 });+ expect(getCanvas(updated).document.layers.find((layer) => layer.id === 'b')).toBe(originalLayerB);+ });++ it('replaces one complete layer contract in place and no-ops when the id is missing', () => {+ const state = withCanvasLayers(createInitialWorkbenchState(), [+ createRasterLayer('a'),+ createRasterLayer('b'),+ createRasterLayer('c'),+ ]);+ const beforeDocument = getCanvas(state).document;+ const replacement: CanvasControlLayerContract = {+ adapter: {+ beginEndStepPct: [0.2, 0.8],+ controlMode: 'more_control',+ kind: 'control_lora',+ model: 'control-model',+ weight: 0.65,+ },+ blendMode: 'multiply',+ filter: { settings: { radius: 3 }, type: 'canny' },+ id: 'b',+ isEnabled: false,+ isLocked: true,+ name: 'Complete replacement',+ opacity: 0.4,+ source: {+ bitmap: { contentHash: 'hash', height: 23, imageName: 'replacement.png', width: 17 },+ offset: { x: -4, y: 9 },+ type: 'paint',+ },+ transform: { rotation: 0.75, scaleX: -2, scaleY: 3, x: 12, y: -8 },+ type: 'control',+ withTransparencyEffect: true,+ };++ const replaced = workbenchReducer(state, {+ layer: replacement,+ layerId: 'b',+ type: 'replaceCanvasLayer',+ });+ const afterLayers = getCanvas(replaced).document.layers;++ expect(afterLayers.map((layer) => layer.id)).toEqual(['a', 'b', 'c']);+ expect(afterLayers[1]).toBe(replacement);+ expect(afterLayers[1]).toEqual(replacement);+ expect(afterLayers[0]).toBe(beforeDocument.layers[0]);+ expect(afterLayers[2]).toBe(beforeDocument.layers[2]);++ const missing = workbenchReducer(replaced, {+ layer: replacement,+ layerId: 'missing',+ type: 'replaceCanvasLayer',+ });+ expect(missing).toBe(replaced);+ expect(getCanvas(missing).document).toBe(getCanvas(replaced).document);+ });++ it('swaps a raster/control layer source but ignores mask-only layer types', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);+ const newSource = { image: { height: 10, imageName: 'swapped.png', width: 10 }, type: 'image' } as const;++ state = workbenchReducer(state, { id: 'a', source: newSource, type: 'updateCanvasLayerSource' });++ expect(getRasterLayerImageName(getCanvas(state).document.layers[0])).toBe('swapped.png');+ });++ it('applies per-type config patches and ignores mismatched layer types', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createControlLayer('ctrl')]);++ state = workbenchReducer(state, {+ config: { adapter: { weight: 0.25 }, layerType: 'control', withTransparencyEffect: true },+ id: 'ctrl',+ type: 'updateCanvasLayerConfig',+ });++ const controlLayer = getCanvas(state).document.layers[0];++ expect(controlLayer?.type).toBe('control');++ if (controlLayer?.type === 'control') {+ expect(controlLayer.adapter.weight).toBe(0.25);+ expect(controlLayer.adapter.kind).toBe('controlnet');+ expect(controlLayer.withTransparencyEffect).toBe(true);+ }++ // A raster-shaped config against a control layer is a no-op.+ const unchanged = workbenchReducer(state, {+ config: { isTransparencyLocked: true, layerType: 'raster' },+ id: 'ctrl',+ type: 'updateCanvasLayerConfig',+ });++ expect(getCanvas(unchanged).document.layers[0]).toBe(controlLayer);+ });++ it('persists filter settings on raster layers', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('raster')]);++ state = workbenchReducer(state, {+ config: { filter: { settings: { radius: 4 }, type: 'content_shuffle' }, layerType: 'raster' },+ id: 'raster',+ type: 'updateCanvasLayerConfig',+ });++ const raster = getCanvas(state).document.layers[0];+ expect(raster?.type).toBe('raster');+ if (raster?.type === 'raster') {+ expect(raster.filter).toEqual({ settings: { radius: 4 }, type: 'content_shuffle' });+ }+ });++ it('applies an inpaint-mask config patch: mask bitmap + offset, fill, noise, denoise-limit', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createInpaintMaskLayer('m')]);++ state = workbenchReducer(state, {+ config: {+ denoiseLimit: 0.8,+ layerType: 'inpaint_mask',+ mask: { bitmap: { contentHash: 'h', height: 20, imageName: 'mask.png', width: 30 }, offset: { x: 4, y: 5 } },+ noiseLevel: 0.25,+ },+ id: 'm',+ type: 'updateCanvasLayerConfig',+ });++ const layer = getCanvas(state).document.layers[0];+ expect(layer?.type).toBe('inpaint_mask');+ if (layer?.type === 'inpaint_mask') {+ // Bitmap + content offset persisted; the fill is preserved (merged, not replaced).+ expect(layer.mask.bitmap).toMatchObject({ imageName: 'mask.png', width: 30, height: 20 });+ expect(layer.mask.offset).toEqual({ x: 4, y: 5 });+ expect(layer.mask.fill).toEqual({ color: '#e07575', style: 'diagonal' });+ expect(layer.noiseLevel).toBe(0.25);+ expect(layer.denoiseLimit).toBe(0.8);+ }++ // A fill-only patch replaces the fill while keeping the bitmap.+ const recolored = workbenchReducer(state, {+ config: { layerType: 'inpaint_mask', mask: { fill: { color: '#00ff00', style: 'grid' } } },+ id: 'm',+ type: 'updateCanvasLayerConfig',+ });+ const after = getCanvas(recolored).document.layers[0];+ if (after?.type === 'inpaint_mask') {+ expect(after.mask.fill).toEqual({ color: '#00ff00', style: 'grid' });+ expect(after.mask.bitmap).toMatchObject({ imageName: 'mask.png' });+ }+ });++ it('removes optional config fields when a patch explicitly sets them to undefined', () => {+ const configuredMask: CanvasInpaintMaskLayerContract = {+ blendMode: 'normal',+ denoiseLimit: 0.8,+ id: 'm',+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: null, fill: { color: '#e07575', style: 'diagonal' } },+ name: 'm',+ noiseLevel: 0.25,+ opacity: 1,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'inpaint_mask',+ };+ let state = withCanvasLayers(createInitialWorkbenchState(), [+ configuredMask,+ { ...createControlLayer('ctrl'), filter: { settings: {}, type: 'canny' } },+ ]);++ state = workbenchReducer(state, {+ config: { denoiseLimit: undefined, layerType: 'inpaint_mask', noiseLevel: undefined },+ id: 'm',+ type: 'updateCanvasLayerConfig',+ });+ state = workbenchReducer(state, {+ config: { filter: undefined, layerType: 'control' },+ id: 'ctrl',+ type: 'updateCanvasLayerConfig',+ });++ const mask = getCanvas(state).document.layers[0];+ const control = getCanvas(state).document.layers[1];++ expect(mask?.type).toBe('inpaint_mask');+ if (mask?.type === 'inpaint_mask') {+ expect(mask.noiseLevel).toBeUndefined();+ expect(mask.denoiseLimit).toBeUndefined();+ }+ expect(control?.type).toBe('control');+ if (control?.type === 'control') {+ expect(control.filter).toBeUndefined();+ }+ });++ it('converts a layer in place, preserving its id and z-order', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]);+ const converted = createControlLayer('ignored-id');++ state = workbenchReducer(state, { id: 'b', layer: converted, targetType: 'control', type: 'convertCanvasLayer' });++ expect(getLayerIds(state)).toEqual(['a', 'b']);+ expect(getCanvas(state).document.layers[1]?.type).toBe('control');+ expect(getCanvas(state).document.layers[1]?.id).toBe('b');+ });++ it('merges a layer down: the layer below becomes a raster with the merged paint source', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [+ createRasterLayer('top'),+ createControlLayer('bottom'),+ ]);++ state = workbenchReducer(state, { id: 'bottom', type: 'setCanvasSelectedLayer' });+ const mergedSource = { bitmap: { height: 8, imageName: 'merged.png', width: 8 }, type: 'paint' } as const;++ state = workbenchReducer(state, { source: mergedSource, type: 'mergeCanvasLayersDown', upperLayerId: 'top' });++ const layers = getCanvas(state).document.layers;++ expect(getLayerIds(state)).toEqual(['bottom']);+ expect(layers[0]?.type).toBe('raster');+ expect(layers[0]?.id).toBe('bottom');+ expect(layers[0]?.type === 'raster' && layers[0].source).toEqual(mergedSource);+ expect(getCanvas(state).document.selectedLayerId).toBe('bottom');+ });++ it('clamps and rounds the bbox, and validates the selected layer id', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);++ state = workbenchReducer(state, { bbox: { height: -4, width: 12.6, x: 3.2, y: 9.8 }, type: 'setCanvasBbox' });++ expect(getCanvas(state).document.bbox).toEqual({ height: 1, width: 13, x: 3, y: 10 });++ // 'a' was selected on insert; selecting a non-existent id is ignored, not applied.+ expect(getCanvas(state).document.selectedLayerId).toBe('a');+ state = workbenchReducer(state, { id: 'missing', type: 'setCanvasSelectedLayer' });+ expect(getCanvas(state).document.selectedLayerId).toBe('a');++ state = workbenchReducer(state, { id: null, type: 'setCanvasSelectedLayer' });+ expect(getCanvas(state).document.selectedLayerId).toBeNull();+ });++ it('resizes the document, translating layer transforms and clamping the bbox in-bounds', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);++ state = workbenchReducer(state, {+ height: 256,+ offsetX: 20,+ offsetY: 10,+ type: 'resizeCanvasDocument',+ width: 300,+ });++ const document = getCanvas(state).document;++ expect(document.width).toBe(300);+ expect(document.height).toBe(256);+ expect(document.layers[0]?.transform.x).toBe(20);+ expect(document.layers[0]?.transform.y).toBe(10);+ expect(document.bbox.x + document.bbox.width).toBeLessThanOrEqual(300);+ expect(document.bbox.y + document.bbox.height).toBeLessThanOrEqual(256);+ });++ it('replaces the whole document with a deep copy', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);+ const replacement = {+ ...createEmptyCanvasDocumentV2(),+ layers: [createRasterLayer('fresh')],+ selectedLayerId: 'fresh',+ };++ state = workbenchReducer(state, { document: replacement, type: 'replaceCanvasDocument' });++ expect(getLayerIds(state)).toEqual(['fresh']);+ expect(getCanvas(state).document).not.toBe(replacement);+ expect(getCanvas(state).document.layers[0]).not.toBe(replacement.layers[0]);+ });++ it('clears the staging area on replaceCanvasDocument (staged candidates belong to the outgoing document)', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);+ const staged: Project['canvas']['stagingArea']['pendingImages'][number] = {+ height: 64,+ imageName: 'staged-1',+ imageUrl: 'url',+ placement: { height: 64, opacity: 1, width: 64, x: 0, y: 0 },+ queuedAt: 'now',+ sourceQueueItemId: 'queue-1',+ thumbnailUrl: 'thumb',+ width: 64,+ };+ state = {+ ...state,+ projects: state.projects.map((project) =>+ project.id === state.activeProjectId+ ? {+ ...project,+ canvas: {+ ...project.canvas,+ stagingArea: {+ ...project.canvas.stagingArea,+ isVisible: true,+ pendingImageIds: ['queue-1'],+ pendingImages: [staged],+ selectedImageIndex: 0,+ sourceQueueItemId: 'queue-1',+ },+ },+ }+ : project+ ),+ };++ state = workbenchReducer(state, { document: createEmptyCanvasDocumentV2(), type: 'replaceCanvasDocument' });++ const { stagingArea } = getCanvas(state);+ expect(stagingArea.pendingImages).toEqual([]);+ expect(stagingArea.pendingImageIds).toEqual([]);+ expect(stagingArea.isVisible).toBe(false);+ expect(stagingArea.sourceQueueItemId).toBeUndefined();+ });++ it('repairs a dangling selectedLayerId on replaceCanvasDocument (falls back to the top layer)', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);+ const replacement = {+ ...createEmptyCanvasDocumentV2(),+ layers: [createRasterLayer('top'), createRasterLayer('bottom')],+ selectedLayerId: 'ghost', // names no layer in the incoming document+ };++ state = workbenchReducer(state, { document: replacement, type: 'replaceCanvasDocument' });++ expect(getCanvas(state).document.selectedLayerId).toBe('top');+ });++ it('nulls a dangling selectedLayerId when the replacement document has no layers', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);+ const replacement = { ...createEmptyCanvasDocumentV2(), layers: [], selectedLayerId: 'ghost' };++ state = workbenchReducer(state, { document: replacement, type: 'replaceCanvasDocument' });++ expect(getCanvas(state).document.selectedLayerId).toBeNull();+ });++ it('preserves a valid selectedLayerId on replaceCanvasDocument', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);+ const replacement = {+ ...createEmptyCanvasDocumentV2(),+ layers: [createRasterLayer('top'), createRasterLayer('bottom')],+ selectedLayerId: 'bottom',+ };++ state = workbenchReducer(state, { document: replacement, type: 'replaceCanvasDocument' });++ expect(getCanvas(state).document.selectedLayerId).toBe('bottom');+ });++ it('repairs a dangling selectedLayerId on restoreCanvasSnapshot (defensive against a corrupt snapshot)', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]);+ state = workbenchReducer(state, { createdAt: 'now', id: 'snap-1', name: 'First', type: 'saveCanvasSnapshot' });++ // Corrupt the stored snapshot so its selectedLayerId names no present layer.+ const snapshot = getCanvas(state).snapshots.find((entry) => entry.id === 'snap-1');+ expect(snapshot).toBeDefined();+ snapshot!.document.selectedLayerId = 'ghost';++ state = workbenchReducer(state, { snapshotId: 'snap-1', type: 'restoreCanvasSnapshot' });++ const restored = getCanvas(state).document;+ expect(restored.selectedLayerId).not.toBe('ghost');+ expect(restored.selectedLayerId).toBe(restored.layers[0]?.id);+ });++ it('normalizes a control adapter when restoring a saved canvas snapshot', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createControlLayer('ctrl')]);+ state = workbenchReducer(state, { createdAt: 'now', id: 'snap-1', name: 'First', type: 'saveCanvasSnapshot' });+ const snapshotLayer = getCanvas(state).snapshots[0]!.document.layers[0];+ if (snapshotLayer?.type !== 'control') {+ throw new Error('expected a control layer');+ }+ snapshotLayer.adapter = {+ beginEndStepPct: [Number.NaN, 2],+ controlMode: null,+ kind: 'z_image_control',+ model: null,+ weight: Number.POSITIVE_INFINITY,+ };++ state = workbenchReducer(state, { snapshotId: 'snap-1', type: 'restoreCanvasSnapshot' });++ const restored = getCanvas(state).document.layers[0];+ expect(restored?.type === 'control' ? restored.adapter : null).toEqual({+ beginEndStepPct: [0, 1],+ controlMode: null,+ kind: 'z_image_control',+ model: null,+ weight: 0.75,+ });+ });++ it('saves, restores, and deletes canvas snapshots', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);++ state = workbenchReducer(state, { createdAt: 'now', id: 'snap-1', name: 'First', type: 'saveCanvasSnapshot' });++ expect(getCanvas(state).snapshots).toHaveLength(1);+ expect(getCanvas(state).snapshots[0]?.document.layers.map((layer) => layer.id)).toEqual(['a']);++ // Mutate the live document, then restore the snapshot back over it.+ state = workbenchReducer(state, { layer: createRasterLayer('b'), type: 'addCanvasLayer' });+ expect(getLayerIds(state)).toEqual(['b', 'a']);++ state = workbenchReducer(state, { snapshotId: 'snap-1', type: 'restoreCanvasSnapshot' });+ expect(getLayerIds(state)).toEqual(['a']);++ state = workbenchReducer(state, { snapshotId: 'snap-1', type: 'deleteCanvasSnapshot' });+ expect(getCanvas(state).snapshots).toEqual([]);+ });++ it('bumps documentRevision on wholesale swaps (restore/replace) but not on ordinary edits', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);+ const initialRevision = getCanvas(state).documentRevision;++ // Ordinary incremental edits never bump the revision.+ state = workbenchReducer(state, { id: 'a', patch: { opacity: 0.3 }, type: 'updateCanvasLayer' });+ state = workbenchReducer(state, { layer: createRasterLayer('b'), type: 'addCanvasLayer' });+ state = workbenchReducer(state, { bbox: { height: 32, width: 32, x: 0, y: 0 }, type: 'setCanvasBbox' });+ state = workbenchReducer(state, { height: 256, type: 'resizeCanvasDocument', width: 256 });+ expect(getCanvas(state).documentRevision).toBe(initialRevision);++ // replaceCanvasDocument is a wholesale swap: bump.+ state = workbenchReducer(state, { document: createEmptyCanvasDocumentV2(), type: 'replaceCanvasDocument' });+ expect(getCanvas(state).documentRevision).toBe(initialRevision + 1);++ // restoreCanvasSnapshot is a wholesale swap: bump — even though the restored+ // document reuses the saved layer ids at the same dimensions.+ state = workbenchReducer(state, { createdAt: 'now', id: 'snap-1', name: 'First', type: 'saveCanvasSnapshot' });+ expect(getCanvas(state).documentRevision).toBe(initialRevision + 1);+ state = workbenchReducer(state, { snapshotId: 'snap-1', type: 'restoreCanvasSnapshot' });+ expect(getCanvas(state).documentRevision).toBe(initialRevision + 2);++ // Restoring a nonexistent snapshot is a no-op: no bump.+ state = workbenchReducer(state, { snapshotId: 'missing', type: 'restoreCanvasSnapshot' });+ expect(getCanvas(state).documentRevision).toBe(initialRevision + 2);+ });++ it('never records project undo entries for canvas layer edits', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);++ state = workbenchReducer(state, { id: 'a', patch: { opacity: 0.3 }, type: 'updateCanvasLayer' });+ state = workbenchReducer(state, { layer: createRasterLayer('b'), type: 'addCanvasLayer' });+ state = workbenchReducer(state, { ids: ['a'], type: 'removeCanvasLayers' });++ expect(getActiveProject(state).undoRedo.past).toEqual([]);+ });+});++describe('workbenchReducer canvas staging auto-switch + canvas submission', () => {+ const stageResults = (state: WorkbenchState, imageNames: string[]): WorkbenchState => {+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ return workbenchReducer(state, {+ images: imageNames.map((name) => createImage(name, queueItem.id)),+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });+ };++ it("'latest' selects the newest pending candidate as results arrive", () => {+ let state = submitGenerate(primeGenerate());++ state = workbenchReducer(state, { mode: 'latest', type: 'setCanvasStagingAutoSwitch' });+ state = stageResults(state, ['first.png', 'second.png']);++ expect(getCanvas(state).stagingArea.autoSwitchMode).toBe('latest');+ expect(getCanvas(state).stagingArea.selectedImageIndex).toBe(1);+ });++ it("'progress' selects the active in-progress placeholder", () => {+ let state = submitGenerate(primeGenerate(undefined, { batchCount: 3 }));+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, { mode: 'progress', type: 'setCanvasStagingAutoSwitch' });+ state = workbenchReducer(state, {+ backendItemIds: [11, 12, 13],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });++ expect(getCanvas(state).stagingArea.autoSwitchMode).toBe('progress');+ expect(getCanvas(state).stagingArea.selectedImageIndex).toBe(0);+ });++ it("'progress' advances selection to the next in-progress placeholder as partials land", () => {+ let state = submitGenerate(primeGenerate(undefined, { batchCount: 3 }));+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, { mode: 'progress', type: 'setCanvasStagingAutoSwitch' });+ state = workbenchReducer(state, {+ backendItemIds: [11, 12, 13],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });+ state = workbenchReducer(state, {+ backendItemId: 11,+ images: [createImage('candidate-1.png', queueItem.id)],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemPartialResults',+ });++ expect(+ getCanvasStagingSlots(getCanvas(state), getActiveProject(state).queue.items).map((slot) => slot.kind)+ ).toEqual(['candidate', 'placeholder', 'placeholder']);+ expect(getCanvas(state).stagingArea.selectedImageIndex).toBe(1);+ });++ const createCanvasGenerateSnapshot = () => ({+ negativePromptNodeId: 'negative_prompt',+ positivePromptNodeId: 'positive_prompt',+ seedNodeId: 'seed',+ values: createGenerateValues({ positivePrompt: 'canvas prompt', seed: 101, shouldRandomizeSeed: false }),+ });++ const submitCanvasGeneration = (state: WorkbenchState): { queueItemId: string; state: WorkbenchState } => {+ const graph: GraphContract = {+ edges: [],+ id: 'canvas-graph',+ label: 'Canvas',+ nodes: [],+ updatedAt: '2026-06-09T00:00:00.000Z',+ version: 1,+ };+ const next = workbenchReducer(state, {+ backendSupportsCancellation: true,+ canvas: structuredClone(getCanvas(state)),+ destination: 'canvas',+ generate: createCanvasGenerateSnapshot(),+ graph,+ projectId: state.activeProjectId,+ type: 'submitCanvasInvocationSnapshot',+ });++ return { queueItemId: getActiveProject(next).queue.items[0]!.id, state: next };+ };++ it('routes canvas results into staging when the session (documentRevision) still matches', () => {+ const { queueItemId, state: submitted } = submitCanvasGeneration(createInitialWorkbenchState());++ const state = workbenchReducer(submitted, {+ images: [createImage('fresh.png', queueItemId)],+ projectId: getActiveProject(submitted).id,+ queueItemId,+ type: 'routeQueueItemResults',+ });++ expect(getCanvas(state).stagingArea.pendingImageIds).toEqual(['fresh.png']);+ expect(getCanvas(state).stagingArea.isVisible).toBe(true);+ });++ it('drops mid-flight canvas results after a new-canvas swap so cleared staging is not resurrected (F2)', () => {+ const { queueItemId, state: submitted } = submitCanvasGeneration(createInitialWorkbenchState());++ // The user confirms a new canvas while the generation is still in flight: a+ // wholesale swap that clears staging and bumps documentRevision (new session).+ const swapped = workbenchReducer(submitted, {+ document: createEmptyCanvasDocumentV2(),+ type: 'replaceCanvasDocument',+ });++ // The stale generation's results arrive against the brand-new empty canvas.+ const state = workbenchReducer(swapped, {+ images: [createImage('stale.png', queueItemId)],+ projectId: getActiveProject(swapped).id,+ queueItemId,+ type: 'routeQueueItemResults',+ });++ const { stagingArea } = getCanvas(state);+ expect(stagingArea.pendingImages).toEqual([]);+ expect(stagingArea.pendingImageIds).toEqual([]);+ expect(stagingArea.isVisible).toBe(false);+ // The item still completes — only its staged candidates are dropped.+ expect(getActiveProject(state).queue.items[0]?.status).toBe('completed');+ });++ it('submitCanvasInvocationSnapshot enqueues a pre-compiled graph bound for the canvas', () => {+ const graph: GraphContract = {+ backendGraph: { edges: [], id: 'canvas-backend-graph', nodes: {} },+ edges: [],+ id: 'canvas-graph',+ label: 'Canvas',+ nodes: [],+ updatedAt: '2026-06-09T00:00:00.000Z',+ version: 1,+ };++ const initial = createInitialWorkbenchState();+ const state = workbenchReducer(initial, {+ backendSupportsCancellation: true,+ canvas: structuredClone(getCanvas(initial)),+ destination: 'canvas',+ generate: {+ negativePromptNodeId: 'negative_prompt',+ positivePromptNodeId: 'positive_prompt',+ seedNodeId: 'seed',+ values: createGenerateValues({+ negativePrompt: 'avoid blur',+ positivePrompt: 'inpaint prompt',+ seed: 42,+ shouldRandomizeSeed: false,+ }),+ },+ graph,+ projectId: initial.activeProjectId,+ type: 'submitCanvasInvocationSnapshot',+ });++ const queueItem = getActiveProject(state).queue.items[0];++ expect(queueItem?.snapshot.sourceId).toBe('canvas');+ expect(queueItem?.snapshot.destination).toBe('canvas');+ expect(queueItem?.snapshot.graph.id).toBe('canvas-graph');+ expect(queueItem?.snapshot.generate).toMatchObject({+ negativePromptNodeId: 'negative_prompt',+ positivePromptNodeId: 'positive_prompt',+ seedNodeId: 'seed',+ values: { negativePrompt: 'avoid blur', positivePrompt: 'inpaint prompt', seed: 42, shouldRandomizeSeed: false },+ });+ expect(queueItem?.snapshot.widgetStates.generate.values).toMatchObject({+ negativePrompt: 'avoid blur',+ positivePrompt: 'inpaint prompt',+ seed: 42,+ shouldRandomizeSeed: false,+ });+ expect(queueItem?.snapshot.backendSubmission).toMatchObject({+ batchCount: 1,+ kind: 'generate',+ negativePrompt: 'avoid blur',+ negativePromptNodeId: 'negative_prompt',+ positivePrompt: 'inpaint prompt',+ positivePromptNodeId: 'positive_prompt',+ seed: 42,+ seedNodeId: 'seed',+ shouldRandomizeSeed: false,+ });+ expect(queueItem?.snapshot.resultNodeIds).toEqual(['canvas_output']);+ expect(getActiveProject(state).invocation.sourceId).toBe('canvas');+ });++ it('queues the frozen canvas supplied by an immutable canvas invocation instead of cloning live state', () => {+ const graph: GraphContract = {+ edges: [],+ id: 'frozen-canvas-graph',+ label: 'Canvas',+ nodes: [],+ updatedAt: '2026-06-09T00:00:00.000Z',+ version: 1,+ };+ const initial = createInitialWorkbenchState();+ const liveCanvas = getCanvas(initial);+ const frozenCanvas = structuredClone(liveCanvas);+ frozenCanvas.document.bbox = { height: 48, width: 32, x: 17, y: 23 };++ const state = workbenchReducer(initial, {+ backendSupportsCancellation: true,+ canvas: frozenCanvas,+ destination: 'canvas',+ generate: createCanvasGenerateSnapshot(),+ graph,+ projectId: initial.activeProjectId,+ type: 'submitCanvasInvocationSnapshot',+ });++ expect(getActiveProject(state).queue.items[0]?.snapshot.canvas.document.bbox).toEqual(frozenCanvas.document.bbox);+ expect(getActiveProject(state).queue.items[0]?.snapshot.canvas.document.bbox).not.toEqual(liveCanvas.document.bbox);+ });++ it('places generated candidates at the frozen queue bbox after the live bbox changes', () => {+ const graph: GraphContract = {+ edges: [],+ id: 'frozen-placement-graph',+ label: 'Canvas',+ nodes: [],+ updatedAt: '2026-06-09T00:00:00.000Z',+ version: 1,+ };+ let state = createInitialWorkbenchState();+ const frozenCanvas = structuredClone(getCanvas(state));+ frozenCanvas.document.bbox = { height: 48, width: 32, x: 17, y: 23 };+ state = workbenchReducer(state, {+ backendSupportsCancellation: true,+ canvas: frozenCanvas,+ destination: 'canvas',+ generate: createCanvasGenerateSnapshot(),+ graph,+ projectId: state.activeProjectId,+ type: 'submitCanvasInvocationSnapshot',+ });+ const queueItemId = getActiveProject(state).queue.items[0]!.id;+ state = workbenchReducer(state, {+ bbox: { height: 64, width: 64, x: 101, y: 202 },+ type: 'setCanvasBbox',+ });++ state = workbenchReducer(state, {+ images: [createImage('frozen-placement.png', queueItemId)],+ projectId: state.activeProjectId,+ queueItemId,+ type: 'routeQueueItemResults',+ });++ expect(getCanvas(state).stagingArea.pendingImages[0]?.placement).toMatchObject({ x: 17, y: 23 });+ });++ it('submitCanvasInvocationSnapshot honors a Gallery destination instead of hardcoding canvas', () => {+ const graph: GraphContract = {+ edges: [],+ id: 'canvas-graph',+ label: 'Canvas',+ nodes: [],+ updatedAt: '2026-06-09T00:00:00.000Z',+ version: 1,+ };++ const initial = createInitialWorkbenchState();+ const state = workbenchReducer(initial, {+ backendSupportsCancellation: true,+ canvas: structuredClone(getCanvas(initial)),+ destination: 'gallery',+ generate: createCanvasGenerateSnapshot(),+ graph,+ projectId: initial.activeProjectId,+ type: 'submitCanvasInvocationSnapshot',+ });++ const queueItem = getActiveProject(state).queue.items[0];++ // A Canvas source still runs, but the resolved Gallery destination rides+ // through so `routeQueueItemResults` keeps it out of canvas staging.+ expect(queueItem?.snapshot.sourceId).toBe('canvas');+ expect(queueItem?.snapshot.destination).toBe('gallery');+ expect(getActiveProject(state).invocation.destination).toBe('gallery');+ expect(getActiveProject(state).canvas.stagingArea.pendingImageIds).toHaveLength(0);+ });++ it('submitCanvasInvocationSnapshot targets the project it names, not the active one', () => {+ const graph: GraphContract = {+ edges: [],+ id: 'canvas-graph',+ label: 'Canvas',+ nodes: [],+ updatedAt: '2026-06-09T00:00:00.000Z',+ version: 1,+ };++ let state = createInitialWorkbenchState();+ const originatingProjectId = state.activeProjectId;+ state = workbenchReducer(state, { type: 'createProject' });+ const otherProjectId = state.activeProjectId;++ expect(otherProjectId).not.toBe(originatingProjectId);++ state = workbenchReducer(state, {+ backendSupportsCancellation: true,+ canvas: structuredClone(getProject(state, originatingProjectId).canvas),+ destination: 'canvas',+ generate: createCanvasGenerateSnapshot(),+ graph,+ projectId: originatingProjectId,+ type: 'submitCanvasInvocationSnapshot',+ });++ expect(getProject(state, originatingProjectId).queue.items).toHaveLength(1);+ expect(getProject(state, originatingProjectId).queue.items[0]?.snapshot.graph.id).toBe('canvas-graph');+ expect(getProject(state, otherProjectId).queue.items).toHaveLength(0);+ });++ it('submitCanvasInvocationSnapshot with a stale/unknown projectId is a no-op', () => {+ const graph: GraphContract = {+ edges: [],+ id: 'canvas-graph',+ label: 'Canvas',+ nodes: [],+ updatedAt: '2026-06-09T00:00:00.000Z',+ version: 1,+ };++ const initial = createInitialWorkbenchState();+ const state = workbenchReducer(initial, {+ backendSupportsCancellation: true,+ canvas: structuredClone(getCanvas(initial)),+ destination: 'canvas',+ generate: createCanvasGenerateSnapshot(),+ graph,+ projectId: 'not-a-real-project',+ type: 'submitCanvasInvocationSnapshot',+ });++ expect(state).toBe(initial);+ });+});++describe('auto invocation route switching', () => {+ const getRoute = (state: WorkbenchState) => getActiveProject(state).invocation;++ it('switches to generate with a gallery destination on a high-confidence settings patch', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });+ state = workbenchReducer(state, { type: 'patchGenerateSettings', values: { steps: 25 } });++ expect(getRoute(state)).toMatchObject({ destination: 'gallery', sourceId: 'generate' });+ });++ it('ignores noise-only generate patches and system-originated patches', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });++ const noiseOnly = workbenchReducer(state, {+ type: 'patchGenerateSettings',+ values: { positivePromptHeightPx: 120 },+ });++ expect(getRoute(noiseOnly).sourceId).toBe('workflow');++ const systemOriginated = workbenchReducer(state, {+ origin: 'system',+ type: 'patchGenerateSettings',+ values: { steps: 25 },+ });++ expect(getRoute(systemOriginated).sourceId).toBe('workflow');+ });++ it('switches to upscale on widget-value edits and shared prompt draft edits', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, {+ type: 'patchWidgetValues',+ values: { inputImage: { height: 512, image_name: 'input.png', width: 768 } },+ widgetId: 'upscale',+ });++ expect(getRoute(state)).toMatchObject({ destination: 'gallery', sourceId: 'upscale' });++ let promptState = createInitialWorkbenchState();++ promptState = workbenchReducer(promptState, {+ sourceId: 'upscale',+ type: 'patchProjectPromptDraft',+ values: { positivePrompt: 'crisp detail' },+ });++ expect(getRoute(promptState)).toMatchObject({ destination: 'gallery', sourceId: 'upscale' });+ });++ it('ignores system-originated and non-graph-bearing widget-value patches', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, {+ origin: 'system',+ type: 'patchWidgetValues',+ values: { inputImage: { height: 512, image_name: 'input.png', width: 768 } },+ widgetId: 'upscale',+ });+ state = workbenchReducer(state, {+ type: 'patchWidgetValues',+ values: { selectedImageName: 'result.png' },+ widgetId: 'gallery',+ });++ expect(getRoute(state).sourceId).toBe('generate');+ });++ it('switches to canvas with a canvas destination on content mutations but not selection', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);++ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });++ const selected = workbenchReducer(state, { id: 'a', type: 'setCanvasSelectedLayer' });++ expect(getRoute(selected)).toMatchObject({ destination: 'gallery', sourceId: 'workflow' });++ const edited = workbenchReducer(state, { layer: createRasterLayer('b'), type: 'addCanvasLayer' });++ expect(getRoute(edited)).toMatchObject({ destination: 'canvas', sourceId: 'canvas' });+ });++ it('switches to Canvas for structural and visibility edits', () => {+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);++ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });+ state = workbenchReducer(state, {+ add: { index: 1, layers: [createRasterLayer('b')] },+ enabledUpdates: [],+ selectedLayerId: 'b',+ type: 'applyCanvasLayerStackMutation',+ });++ expect(getRoute(state)).toMatchObject({ destination: 'canvas', sourceId: 'canvas' });++ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });+ state = workbenchReducer(state, {+ type: 'setCanvasLayersEnabled',+ updates: [{ id: 'a', isEnabled: false }],+ });++ expect(getRoute(state)).toMatchObject({ destination: 'canvas', sourceId: 'canvas' });+ });++ it('routes confirmed paint intents but ignores system Canvas mutations', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });+ state = reduceWorkbench(state, {+ intent: { kind: 'paint' },+ projectId: state.activeProjectId,+ type: 'commitCanvasEdit',+ });++ expect(getRoute(state)).toMatchObject({ destination: 'canvas', sourceId: 'canvas' });++ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });+ state = reduceWorkbench(state, {+ mutation: { bbox: { height: 768, width: 768, x: 0, y: 0 }, type: 'setCanvasBbox' },+ origin: 'system',+ projectId: state.activeProjectId,+ type: 'applyCanvasProjectMutation',+ });++ expect(getRoute(state).sourceId).toBe('workflow');+ });++ it('uses the explicit source on shared prompt edits', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });+ state = workbenchReducer(state, {+ sourceId: 'generate',+ type: 'patchProjectPromptDraft',+ values: { positivePrompt: 'generate prompt' },+ });++ expect(getRoute(state)).toMatchObject({ destination: 'gallery', sourceId: 'generate' });++ state = workbenchReducer(state, { sourceId: 'canvas', type: 'setInvocationSource' });+ state = workbenchReducer(state, {+ sourceId: 'generate',+ type: 'patchProjectPromptDraft',+ values: { positivePrompt: 'canvas parameter prompt' },+ });++ expect(getRoute(state)).toMatchObject({ destination: 'gallery', sourceId: 'canvas' });+ });++ it('never lets generate edits steal the route from an active canvas source', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { sourceId: 'canvas', type: 'setInvocationSource' });+ // Canvas compiles from generate values, so the generate panel is also the+ // canvas parameter panel — editing it expresses canvas intent here.+ state = workbenchReducer(state, { type: 'patchGenerateSettings', values: { steps: 25 } });+ state = workbenchReducer(state, { type: 'setGenerateSettings', values: createGenerateValues() });++ expect(getRoute(state)).toMatchObject({ destination: 'canvas', sourceId: 'canvas' });+ });++ it('respects the source and destination locks', () => {+ let sourceLockedState = createInitialWorkbenchState();++ sourceLockedState = workbenchReducer(sourceLockedState, { type: 'toggleSourceLock' });+ sourceLockedState = workbenchReducer(sourceLockedState, {+ layer: createRasterLayer('a'),+ type: 'addCanvasLayer',+ });++ expect(getRoute(sourceLockedState)).toMatchObject({ destination: 'canvas', sourceId: 'generate' });++ let destinationLockedState = createInitialWorkbenchState();++ destinationLockedState = workbenchReducer(destinationLockedState, { type: 'toggleDestinationLock' });+ destinationLockedState = workbenchReducer(destinationLockedState, {+ type: 'patchWidgetValues',+ values: { inputImage: { height: 512, image_name: 'input.png', width: 768 } },+ widgetId: 'upscale',+ });++ expect(getRoute(destinationLockedState)).toMatchObject({ destination: 'canvas', sourceId: 'upscale' });+ });++ it('toggles both routing locks together and normalizes a mixed lock state', () => {+ let unlockedState = createInitialWorkbenchState();++ unlockedState = workbenchReducer(unlockedState, { type: 'toggleRoutingLock' });+ expect(getRoute(unlockedState)).toMatchObject({ destinationLocked: true, sourceLocked: true });++ unlockedState = workbenchReducer(unlockedState, { type: 'toggleRoutingLock' });+ expect(getRoute(unlockedState)).toMatchObject({ destinationLocked: false, sourceLocked: false });++ let mixedState = createInitialWorkbenchState();+ mixedState = workbenchReducer(mixedState, { type: 'toggleSourceLock' });+ expect(getRoute(mixedState)).toMatchObject({ destinationLocked: false, sourceLocked: true });++ mixedState = workbenchReducer(mixedState, { type: 'toggleRoutingLock' });+ expect(getRoute(mixedState)).toMatchObject({ destinationLocked: false, sourceLocked: false });+ });++ it('never remaps the destination on a manual source change or a same-source edit', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });++ // The dropdown is the strongest intent signal: destination stays put.+ expect(getRoute(state)).toMatchObject({ destination: 'canvas', sourceId: 'workflow' });++ state = workbenchReducer(state, { type: 'patchGenerateSettings', values: { steps: 25 } });+ state = workbenchReducer(state, { destination: 'canvas', type: 'setInvocationDestination' });+ state = workbenchReducer(state, { type: 'patchGenerateSettings', values: { steps: 30 } });++ // Editing the surface already routed as the source keeps the manual destination.+ expect(getRoute(state)).toMatchObject({ destination: 'canvas', sourceId: 'generate' });+ });+});diff --cc tests/app/services/image_records/test_image_records_sqlite.pyindex f934616fe3,7408dcf376..073aab42bf--- a/tests/app/services/image_records/test_image_records_sqlite.py+++ b/tests/app/services/image_records/test_image_records_sqlite.py@@@ -273,259 -275,79 +286,337 @@@ class TestOwnershipFilteringOmittedBoarassert result.image_names == ["u1-uncat.png"]+class TestAllReadableBoardsFiltering:+ def _seed_visibility_matrix(+ self,+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],+ ) -> None:+ image_store, board_store, board_image_store = stores++ def add_boarded_image(+ image_name: str,+ *,+ owner: str,+ visibility: BoardVisibility = BoardVisibility.Private,+ archived: bool = False,+ ) -> str:+ _save(image_store, image_name, user_id=owner)+ board = board_store.save(board_name=image_name, user_id=owner)+ board_store.update(+ board.board_id,+ BoardChanges(board_visibility=visibility, archived=archived),+ )+ board_image_store.add_image_to_board(board_id=board.board_id, image_name=image_name)+ return board.board_id++ add_boarded_image("own-private.png", owner="user1")+ shared_private_id = add_boarded_image("explicit-share.png", owner="user2")+ add_boarded_image("shared-visibility.png", owner="user2", visibility=BoardVisibility.Shared)+ add_boarded_image("public-visibility.png", owner="user2", visibility=BoardVisibility.Public)+ add_boarded_image("other-private.png", owner="user2")+ add_boarded_image("own-archived.png", owner="user1", archived=True)+ add_boarded_image("other-archived-public.png", owner="user2", visibility=BoardVisibility.Public, archived=True)+ _save(image_store, "own-uncategorized.png", user_id="user1")+ _save(image_store, "other-uncategorized.png", user_id="user2")++ with image_store._db.transaction() as cursor:+ cursor.execute(+ "INSERT OR IGNORE INTO users (user_id, email, password_hash) VALUES (?, ?, ?)",+ ("user1", "[email protected]", "unused"),+ )+ cursor.execute(+ "INSERT OR IGNORE INTO shared_boards (board_id, user_id) VALUES (?, ?)",+ (shared_private_id, "user1"),+ )++ @pytest.mark.parametrize(+ ("user_id", "is_admin", "expected"),+ [+ (+ "user1",+ False,+ {+ "own-private.png",+ "explicit-share.png",+ "shared-visibility.png",+ "public-visibility.png",+ "own-uncategorized.png",+ },+ ),+ (+ "admin",+ True,+ {+ "own-private.png",+ "explicit-share.png",+ "shared-visibility.png",+ "public-visibility.png",+ "other-private.png",+ "own-uncategorized.png",+ "other-uncategorized.png",+ },+ ),+ ],+ )+ def test_all_scope_authorization_and_counts_are_consistent(+ self,+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],+ user_id: str,+ is_admin: bool,+ expected: set[str],+ ) -> None:+ self._seed_visibility_matrix(stores)+ image_store = stores[0]+ with image_store._db.transaction() as cursor:+ cursor.executemany(+ "UPDATE images SET starred = TRUE WHERE image_name = ?",+ [("own-private.png",), ("other-private.png",)],+ )++ dtos = image_store.get_many(limit=100, board_id="all", user_id=user_id, is_admin=is_admin)+ names = image_store.get_image_names(board_id="all", user_id=user_id, is_admin=is_admin)++ assert {image.image_name for image in dtos.items} == expected+ assert set(names.image_names) == expected+ assert dtos.total == names.total_count == len(expected)+ assert names.starred_count == len(expected & {"own-private.png", "other-private.png"})++ def test_all_scope_combines_with_inclusive_date_filters(+ self,+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],+ ) -> None:+ self._seed_visibility_matrix(stores)+ image_store = stores[0]+ _set_created_at(image_store, "own-private.png", "2026-06-01 00:00:00.000")+ _set_created_at(image_store, "explicit-share.png", "2026-06-01 23:59:59.999")+ _set_created_at(image_store, "public-visibility.png", "2026-06-02 00:00:00.000")++ dtos = image_store.get_many(+ limit=100,+ board_id="all",+ user_id="user1",+ created_from="2026-06-01",+ created_to="2026-06-01",+ )+ names = image_store.get_image_names(+ board_id="all",+ user_id="user1",+ created_from="2026-06-01",+ created_to="2026-06-01",+ )++ assert {image.image_name for image in dtos.items} == {"own-private.png", "explicit-share.png"}+ assert set(names.image_names) == {"own-private.png", "explicit-share.png"}+ assert dtos.total == names.total_count == 2++ @pytest.mark.parametrize(("user_id", "is_admin"), [("user1", False), ("admin", True)])+ def test_all_scope_excludes_dangling_board_associations(+ self,+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],+ user_id: str,+ is_admin: bool,+ ) -> None:+ image_store = stores[0]+ _save(image_store, "dangling.png", user_id="user1")+ # Production foreign keys prevent this state, but imported/legacy DBs+ # may contain it. Seed it deliberately to lock down fail-closed reads.+ image_store._db._conn.execute("PRAGMA foreign_keys = OFF")+ image_store._db._conn.execute(+ "INSERT INTO board_images (board_id, image_name) VALUES (?, ?)",+ ("deleted-board", "dangling.png"),+ )+ image_store._db._conn.commit()+ image_store._db._conn.execute("PRAGMA foreign_keys = ON")++ dtos = image_store.get_many(limit=100, board_id="all", user_id=user_id, is_admin=is_admin)+ names = image_store.get_image_names(board_id="all", user_id=user_id, is_admin=is_admin)++ assert dtos.items == []+ assert dtos.total == 0+ assert names.image_names == []+ assert names.total_count == names.starred_count == 0+++def _set_created_at(store: SqliteImageRecordStorage, name: str, created_at: str) -> None:+ """created_at is written by a SQL column default; tests override it directly."""+ with store._db.transaction() as cursor:+ cursor.execute("UPDATE images SET created_at = ? WHERE image_name = ?", (created_at, name))+++class TestCreatedAtRangeFiltering:+ """get_many()/get_image_names() filter by inclusive created_from/created_to dates.++ Bounds are date-only strings compared lexicographically against the ISO text+ column, which stores both space- and T-separated timestamps.+ """++ def _seed_dated(self, store: SqliteImageRecordStorage) -> None:+ _save(store, "jan30.png")+ _save(store, "jan31-morning.png")+ _save(store, "jan31-last-second.png")+ _save(store, "feb01-midnight.png")+ _save(store, "feb15-t-sep.png")+ _set_created_at(store, "jan30.png", "2026-01-30 12:00:00.000")+ _set_created_at(store, "jan31-morning.png", "2026-01-31 08:30:00.000")+ _set_created_at(store, "jan31-last-second.png", "2026-01-31 23:59:59.999")+ _set_created_at(store, "feb01-midnight.png", "2026-02-01 00:00:00.000")+ _set_created_at(store, "feb15-t-sep.png", "2026-02-15T10:00:00.000")++ def test_created_from_is_inclusive(self, store: SqliteImageRecordStorage) -> None:+ self._seed_dated(store)++ result = store.get_many(limit=10, created_from="2026-01-31")++ assert {r.image_name for r in result.items} == {+ "jan31-morning.png",+ "jan31-last-second.png",+ "feb01-midnight.png",+ "feb15-t-sep.png",+ }++ def test_created_to_includes_end_of_day_and_excludes_next_midnight(self, store: SqliteImageRecordStorage) -> None:+ self._seed_dated(store)++ result = store.get_many(limit=10, created_to="2026-01-31")++ assert {r.image_name for r in result.items} == {+ "jan30.png",+ "jan31-morning.png",+ "jan31-last-second.png",+ }++ def test_created_to_handles_month_rollover(self, store: SqliteImageRecordStorage) -> None:+ """created_to on the last day of a month must not lexicographically leak into the next month."""+ self._seed_dated(store)++ result = store.get_many(limit=10, created_from="2026-01-31", created_to="2026-01-31")++ assert {r.image_name for r in result.items} == {"jan31-morning.png", "jan31-last-second.png"}++ def test_range_matches_t_separated_timestamps(self, store: SqliteImageRecordStorage) -> None:+ self._seed_dated(store)++ result = store.get_many(limit=10, created_from="2026-02-15", created_to="2026-02-15")++ assert {r.image_name for r in result.items} == {"feb15-t-sep.png"}++ def test_range_combines_with_search_term(self, store: SqliteImageRecordStorage) -> None:+ self._seed_dated(store)++ result = store.get_many(limit=10, created_from="2026-01-31", created_to="2026-02-01", search_term="feb01")++ assert {r.image_name for r in result.items} == set()+ # search_term matches metadata/created_at, not names; a created_at match works+ result = store.get_many(limit=10, created_from="2026-01-31", created_to="2026-02-01", search_term="2026-02-01")+ assert {r.image_name for r in result.items} == {"feb01-midnight.png"}++ def test_range_combines_with_board_filter(+ self,+ stores: tuple[SqliteImageRecordStorage, SqliteBoardRecordStorage, SqliteBoardImageRecordStorage],+ ) -> None:+ image_store, board_store, board_image_store = stores+ self._seed_dated(image_store)+ board = board_store.save(board_name="Dated Board", user_id="user1")+ board_image_store.add_image_to_board(board_id=board.board_id, image_name="jan30.png")+ board_image_store.add_image_to_board(board_id=board.board_id, image_name="feb01-midnight.png")++ result = image_store.get_many(limit=10, board_id=board.board_id, created_from="2026-02-01")++ assert {r.image_name for r in result.items} == {"feb01-midnight.png"}++ def test_get_many_total_and_get_image_names_counts_are_consistent(self, store: SqliteImageRecordStorage) -> None:+ self._seed_dated(store)+ with store._db.transaction() as cursor:+ cursor.execute("UPDATE images SET starred = TRUE WHERE image_name = ?", ("jan31-morning.png",))++ dtos = store.get_many(limit=10, created_from="2026-01-31", created_to="2026-02-01")+ names = store.get_image_names(created_from="2026-01-31", created_to="2026-02-01")++ assert dtos.total == names.total_count == 3+ assert set(names.image_names) == {r.image_name for r in dtos.items}+ assert names.starred_count == 1++ def test_no_range_returns_everything(self, store: SqliteImageRecordStorage) -> None:+ self._seed_dated(store)++ result = store.get_many(limit=10)++ assert result.total == 5+++++ class TestGetImageNamesQueryPlans:+ def test_default_category_query_has_no_forced_index(self, store: SqliteImageRecordStorage) -> None:+ _save(store, "image.png", user_id="alice")++ result, statement, _ = _capture_names_plan(+ store,+ categories=[ImageCategory.GENERAL],+ is_intermediate=False,+ is_admin=True,+ )++ assert result.image_names == ["image.png"]+ assert "LEFT JOIN board_images" not in statement+ assert "INDEXED BY" not in statement+ assert "NOT INDEXED" not in statement++ @pytest.mark.parametrize(+ "kwargs",+ [+ {"search_term": "does-not-match"},+ {"user_id": "alice", "is_admin": False},+ {"user_id": "alice", "is_admin": False, "starred_first": False},+ {"user_id": "alice", "is_admin": False, "order_dir": SQLiteDirection.Ascending},+ ],+ )+ def test_query_shapes_do_not_force_indexes(+ self,+ store: SqliteImageRecordStorage,+ kwargs,+ ) -> None:+ _save(store, "image.png", user_id="alice")++ _, statement, _ = _capture_names_plan(+ store,+ categories=[ImageCategory.GENERAL],+ is_intermediate=False,+ **kwargs,+ )++ assert "LEFT JOIN board_images" not in statement+ assert "INDEXED BY" not in statement+ assert "NOT INDEXED" not in statement++ def test_none_board_uses_anti_membership_filter(self, stores) -> None:+ image_store, board_store, board_image_store = stores+ _save(image_store, "boarded.png", user_id="alice")+ _save(image_store, "unboarded.png", user_id="alice")+ board = board_store.save("Board", "alice")+ board_image_store.add_image_to_board(board.board_id, "boarded.png")++ result, statement, _ = _capture_names_plan(+ image_store,+ board_id="none",+ user_id="alice",+ is_admin=False,+ starred_first=False,+ )++ assert result.image_names == ["unboarded.png"]+ assert "NOT EXISTS" in statement+ assert "LEFT JOIN board_images" not in statement++ def test_nonadmin_asset_query_has_no_forced_index(self, store: SqliteImageRecordStorage) -> None:+ _save(store, "asset.png", user_id="alice", category=ImageCategory.CONTROL)++ result, statement, _ = _capture_names_plan(+ store,+ categories=[ImageCategory.CONTROL],+ is_intermediate=False,+ user_id="alice",+ is_admin=False,+ )++ assert result.image_names == ["asset.png"]+ assert "INDEXED BY" not in statement+ assert "NOT INDEXED" not in statement