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
fix(generation): keep FLUX Kontext references after renaming (#10238)
rnshinef40c0c4c0831
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdxindex 5a50f2629d..3f496eb68f 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx@@ -130,9 +130,11 @@ A FLUX.1 model accepts up to **five** reference images. Three kinds are availabl- **Kontext** — when the selected model is FLUX.1 Kontext dev, reference images are passed to Kontext forinstruction-style editing: describe the change you want in the prompt.-:::note[Kontext is recognized by name]-The Generate tab treats a FLUX.1 model as Kontext only if its name contains "kontext". If you rename a-Kontext model in the Model Manager, keep that word in the name.+:::note[Renaming a Kontext model]+Invoke recognizes FLUX.1 Kontext from the official and Starter Model repositories, including local+folders named after those repositories. Renaming an installed model keeps its existing Kontext references+attached, and new references added alongside them also use Kontext. For a custom model from another source,+include **Kontext** in its display name when adding references without an existing Kontext reference.:::## ControlNets and Control LoRAsdiff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.tsindex e95102a41c..726f871ca5 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts@@ -3617,6 +3617,7 @@ describe('isModelFromRepo', () => {expect(isModelFromRepo('google/gemma-4-E4B-it', REPO)).toBe(true);expect(isModelFromRepo('Google/Gemma-4-e4b-IT', REPO)).toBe(true);expect(isModelFromRepo('google/gemma-4-E4B-it::text_encoder', REPO)).toBe(true);+ expect(isModelFromRepo('google/gemma-4-E4B-it:fp16::text_encoder', REPO)).toBe(true);expect(isModelFromRepo('https://huggingface.co/google/gemma-4-E4B-it/tree/main', REPO)).toBe(true);});@@ -3629,6 +3630,8 @@ describe('isModelFromRepo', () => {it('refuses other repos, other folders and a missing source', () => {expect(isModelFromRepo('google/gemma-4-E2B-it', REPO)).toBe(false);expect(isModelFromRepo('someone/gemma-4-E4B-it', REPO)).toBe(false);+ expect(isModelFromRepo('someone/gemma-4-E4B-it:fp16', REPO)).toBe(false);+ expect(isModelFromRepo('https://example.test/google/gemma-4-E4B-it', REPO)).toBe(false);expect(isModelFromRepo('E:/ModelStuffSSD/gemma-4-E4B-it-q4', REPO)).toBe(false);expect(isModelFromRepo('E:/ModelStuffSSD/gemma-4-E4B-it/model.safetensors', REPO)).toBe(false);expect(isModelFromRepo(null, REPO)).toBe(false);diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex 561acb7c37..f62fe5b836 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -118,6 +118,7 @@ import {isGenerateModelConfig,isGenerateSettings,isLoraCompatibleWithModel,+ isSameInstalledModel,isValidKrea2RebalanceWeights,isValidMossImageSkipLayers,KREA2_REBALANCE_WEIGHT_COUNT,@@ -381,12 +382,11 @@ export const getPromptPolicy = (};};-const HF_REPO_ID = /^[A-Za-z0-9][\w.-]*\/[\w.-]+$/;+const HF_REPO_SOURCE = /^([A-Za-z0-9][\w.-]*\/[\w.-]+)(?::[\w.-]+)?$/;/**- * Whether an installed model's source is the Hugging Face repo `repoId`: the repo itself (also `repo::subfolder` or a- * huggingface.co URL), or a local folder named like the repo, as an in-place install of a downloaded copy is.- * Case-insensitive, as Hugging Face repo ids are.+ * Whether an installed model's source is the Hugging Face repo `repoId`: the repo itself (also with a `:variant` or+ * `::subfolder` suffix), a huggingface.co URL, or a local folder named like the repo. Matching is case-insensitive.*/export const isModelFromRepo = (source: string | null | undefined, repoId: string): boolean => {if (!source) {@@ -394,10 +394,15 @@ export const isModelFromRepo = (source: string | null | undefined, repoId: strin}const wanted = repoId.toLowerCase();const withoutSubfolder = source.split('::')[0]!.trim();- const hfPath = /^https?:\/\/(?:www\.)?huggingface\.co\/([^?#]+)/i.exec(withoutSubfolder)?.[1];- const candidate = (hfPath ? hfPath.split('/').slice(0, 2).join('/') : withoutSubfolder).replace(/[/\\]+$/, '');- if (HF_REPO_ID.test(candidate)) {- return candidate.toLowerCase() === wanted;+ if (/^https?:\/\//i.test(withoutSubfolder)) {+ const repo = /^https?:\/\/(?:www\.)?huggingface\.co\/([^/?#]+\/[^/?#]+)/i.exec(withoutSubfolder)?.[1];+ return repo?.toLowerCase() === wanted;+ }++ const candidate = withoutSubfolder.replace(/[/\\]+$/, '');+ const repo = HF_REPO_SOURCE.exec(candidate)?.[1];+ if (repo !== undefined) {+ return repo.toLowerCase() === wanted;}const folder = candidate.split(/[/\\]/).pop() ?? '';return folder.toLowerCase() === wanted.split('/').pop();@@ -1582,13 +1587,22 @@ export const isComponentCompatibleWithModel = (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')- );+// FLUX.1 Kontext starter sources from invokeai/backend/model_manager/starter_models/flux.py.+const FLUX_KONTEXT_REPOS = [+ 'black-forest-labs/flux.1-kontext-dev',+ 'comfy-org/flux1-kontext-dev_comfyui',+ 'unsloth/flux.1-kontext-dev-gguf',+];++const isFluxMainModel = (model: GenerateModelConfig | undefined): model is MainModelConfig =>+ model?.type === 'main' && model.base === 'flux';++const isKnownFluxKontextModel = ({ name, source }: MainModelConfig): boolean =>+ name.toLowerCase().includes('kontext') ||+ (typeof source === 'string' && FLUX_KONTEXT_REPOS.some((repo) => isModelFromRepo(source, repo)));++const isBoundKontextReference = (model: MainModelConfig, config: GenerateReferenceImageConfig): boolean =>+ config.type === 'flux_kontext_reference_image' && config.model !== null && isSameInstalledModel(model, config.model);/*** Families whose Generate graph loads LoRAs. The backend installs no LoRAs for the others, so their concept picker@@ -1790,10 +1804,6 @@ const getFamilyDefaultReferenceImageConfig = (return { image, type: 'qwen_image_2_1_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;@@ -1826,7 +1836,10 @@ const getReferenceImageConfigSupported = (// The encoder decides whether they run (see `isReferenceImageSupported`); the type fits the base alone.return model.type !== 'external_image_generator' && model.base === 'qwen-image-2-1';case 'flux_kontext_reference_image':- return isFluxKontextModel(model);+ return (+ isFluxMainModel(model) &&+ (isBoundKontextReference(model, referenceImage.config) || isKnownFluxKontextModel(model))+ );case 'flux_redux':return model.type !== 'external_image_generator' && model.base === 'flux';case 'ip_adapter':@@ -1873,6 +1886,13 @@ const getDefaultReferenceImageConfigs = (additions: readonly ReferenceImageAddition[],referenceImages: readonly GenerateReferenceImage[]): GenerateReferenceImageConfig[] => {+ if (+ isFluxMainModel(model) &&+ (isKnownFluxKontextModel(model) || referenceImages.some(({ config }) => isBoundKontextReference(model, config)))+ ) {+ return additions.map(({ image }) => ({ image, model, type: 'flux_kontext_reference_image' }));+ }+if (model?.type !== 'main' || model.base !== 'krea-2') {return additions.map(({ image }) => getFamilyDefaultReferenceImageConfig(model, models, image));}diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.tsindex d3256b187b..5b6404a7b7 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@@ -11,8 +11,10 @@ import {architectureCapabilitiesFixture,seedArchitectureCapabilities,} from '@features/generation/core/architectureCapabilities.testing';+import { withAddedReferenceImages } from '@features/generation/core/baseGenerationPolicies';import { getPidDecoderBaseForMainBase } from '@features/generation/core/pid';import { isPidDecodeNodeType } from '@features/generation/core/pidGraph';+import { syncGenerateWidgetValuesWithModels } from '@features/generation/core/settings';import { describe, expect, it, vi } from 'vitest';import type { ControlLayerGraphInput } from './addControlLayers';@@ -256,6 +258,47 @@ const BASE_CASES: BaseCase[] = [seedArchitectureCapabilities();describe('compileCanvasGraph', () => {+ it('uses a local Kontext reference added after a synced Canvas model is renamed', () => {+ const installed = {+ ...fluxModel,+ hash: 'original-file',+ name: 'FLUX.1 Kontext dev',+ source: '/models/portrait.safetensors',+ variant: 'dev',+ };+ const renamed = { ...installed, name: 'Portrait editor' };+ const referenceImages = withAddedReferenceImages(+ installed,+ [],+ [],+ [{ id: 'reference', image: { original: { image: { height: 768, image_name: 'reference.png', width: 512 } } } }]+ );+ const settings = syncGenerateWidgetValuesWithModels(+ { ...settingsFor(installed, { ...COMPONENT_OVERRIDES.flux, referenceImages }), model: installed },+ [renamed]+ );++ const withSecondReference = withAddedReferenceImages(settings.model, [], settings.referenceImages, [+ { id: 'second', image: { original: { image: { height: 768, image_name: 'second.png', width: 512 } } } },+ ]);+ const { backendGraph } = compile(settings.model, 'img2img', {+ settings: { ...settings, referenceImages: withSecondReference },+ });++ expect(settings.model.name).toBe(renamed.name);+ expect(backendGraph.edges).toContainEqual(+ expect.objectContaining({+ destination: { node_id: 'denoise_latents', field: 'kontext_conditioning' },+ })+ );+ expect(Object.values(backendGraph.nodes).filter(({ type }) => type === 'flux_kontext')).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ image: { image_name: 'reference.png' } }),+ expect.objectContaining({ image: { image_name: 'second.png' } }),+ ])+ );+ });+describe('txt2img per base', () => {it.each(BASE_CASES)('builds a $model.base txt2img graph sized to the bbox',diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.tsindex fb46e20dd3..53bee1f3d7 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts@@ -17,6 +17,7 @@ import {getGenerationValidationIssues,isSupportedGenerateModel,type SupportedGenerateBase,+ withAddedReferenceImages,} from './baseGenerationPolicies';import { compileGenerateGraph, getFamilyGraphBuilder, GRAPH_BUILDERS, resolveGenerateSeed } from './graph';import {@@ -28,6 +29,7 @@ import {import { isPidDecodeNodeType } from './pidGraph';import { getReferenceImagePromptTags } from './referenceImage';import { REFINER_DENOISE_NODE_ID } from './sdxlRefinerGraph';+import { syncGenerateWidgetValuesWithModels } from './settings';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' };@@ -1134,6 +1136,102 @@ describe('compileGenerateGraph', () => {expect(getEdge(graph, 'denoise_latents', 'kontext_conditioning')?.source.node_id).toContain('flux_kontext_collect');});+ it.each([+ ['hf_repo_id', 'black-forest-labs/FLUX.1-Kontext-dev:fp16'],+ ['url', 'https://www.huggingface.co/black-forest-labs/FLUX.1-Kontext-dev/tree/main'],+ ['path', '/models/FLUX.1-Kontext-dev/'],+ ['url', 'https://huggingface.co/unsloth/FLUX.1-Kontext-dev-GGUF/resolve/main/flux1-kontext-dev-Q4_K_M.gguf'],+ [+ 'url',+ 'https://huggingface.co/Comfy-Org/flux1-kontext-dev_ComfyUI/resolve/main/split_files/diffusion_models/flux1-dev-kontext_fp8_scaled.safetensors',+ ],+ ])('creates a Kontext reference for a renamed model with %s source %s', (sourceType, source) => {+ const renamed = { ...fluxKontextModel, name: 'Portrait editor', source, source_type: sourceType, variant: 'dev' };+ const referenceImages = withAddedReferenceImages(renamed, [], [], [{ id: 'reference', image: refImage }]);++ expect(referenceImages[0]?.config).toMatchObject({+ model: { key: renamed.key },+ type: 'flux_kontext_reference_image',+ });+ const graph = compile(renamed, {+ clipEmbedModel: clipEmbed,+ referenceImages,+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ });+ expect(getEdge(graph, 'denoise_latents', 'kontext_conditioning')).toBeDefined();+ });++ it.each([+ ['url', 'https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev-preview/resolve/main/flux1-dev.safetensors'],+ ['url', 'https://example.test/black-forest-labs/FLUX.1-Kontext-dev/resolve/main/flux1-dev.safetensors'],+ ['path', '/models/kontext/flux1-dev.safetensors'],+ ])('leaves an ordinary FLUX model with %s source %s on IP-Adapter', (sourceType, source) => {+ const model = { ...fluxModel, source, source_type: sourceType };+ const referenceImages = withAddedReferenceImages(model, [], [], [{ id: 'reference', image: refImage }]);++ expect(referenceImages[0]?.config.type).toBe('ip_adapter');+ });++ it('preserves and adds local Kontext references after a display-only catalog rename', () => {+ const installed = {+ ...fluxKontextModel,+ hash: 'original-file',+ source: '/models/portrait.safetensors',+ variant: 'dev',+ };+ const renamed = { ...installed, name: 'Portrait editor' };+ const settings = {+ ...createSettings(installed, {+ clipEmbedModel: clipEmbed,+ referenceImages: withAddedReferenceImages(installed, [], [], [{ id: 'reference', image: refImage }]),+ t5EncoderModel: t5Encoder,+ vae: fluxVae,+ }),+ model: installed,+ };+ const synced = syncGenerateWidgetValuesWithModels(settings, [renamed]);++ expect(synced.model.name).toBe(renamed.name);+ expect(synced.referenceImages[0]?.config).toMatchObject({+ model: { key: renamed.key, name: renamed.name },+ type: 'flux_kontext_reference_image',+ });+ const second = {+ id: 'second-reference',+ image: { original: { image: { ...refImage.original.image, image_name: 'second.png' } } },+ };+ const referenceImages = withAddedReferenceImages(synced.model, [], synced.referenceImages, [second]);+ const graph = compile(synced.model, { ...synced, referenceImages });++ expect(getEdge(graph, 'denoise_latents', 'kontext_conditioning')).toBeDefined();+ expect(Object.values(graph.nodes).filter(({ type }) => type === 'flux_kontext')).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ image: { image_name: 'reference.png' } }),+ expect.objectContaining({ image: { image_name: 'second.png' } }),+ ])+ );++ const anotherModel = { ...renamed, key: 'different-install', name: 'FLUX dev' };+ expect(() => compile(anotherModel, synced)).toThrow(/cannot use reference image/i);+ expect(withAddedReferenceImages(anotherModel, [], synced.referenceImages, [second])[1]?.config.type).toBe(+ 'ip_adapter'+ );++ const replacement = { ...renamed, hash: 'replacement-file', name: 'FLUX dev' };+ const replaced = syncGenerateWidgetValuesWithModels(synced, [replacement]);+ expect(() => compile(replaced.model, replaced)).toThrow(/cannot use reference image/i);+ expect(withAddedReferenceImages(replaced.model, [], replaced.referenceImages, [second])[1]?.config.type).toBe(+ 'ip_adapter'+ );++ const otherVariant = { ...renamed, variant: 'schnell' };+ const updated = syncGenerateWidgetValuesWithModels(synced, [otherVariant]);+ expect(withAddedReferenceImages(updated.model, [], updated.referenceImages, [second])[1]?.config.type).toBe(+ 'ip_adapter'+ );+ });+it('wires FLUX.2 built-in reference images into denoise', () => {const graph = compile(flux2Model, {referenceImages: [diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.tsindex 2f0ab39783..e7d1dcaf76 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts@@ -759,9 +759,8 @@ const buildFluxGraph = (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');- }+ // Generation validation has checked that the enabled Kontext references belong to this model.+ addFluxKontextReferenceImages(graph, settings, denoise, 'flux_kontext_reference_image');const ipAdapterCollector = addIPAdapterReferenceImages(graph, settings, model, denoise);const fluxReduxCollector = addFluxReduxReferenceImages(graph, settings, model, denoise);addMetadata(graph, output, settings, model, 'flux_txt2img', projectSettings, {diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.tsindex 4aac923623..8b8fa8acbd 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts@@ -583,17 +583,24 @@ const areModelSnapshotsEqual = (a: unknown, b: unknown): boolean => {}};+const hasSameModelKind = (candidate: ModelIdentifierConfig, saved: ModelIdentifierConfig): boolean =>+ candidate.type === saved.type &&+ candidate.base === saved.base &&+ (saved.variant === undefined || saved.variant === null || candidate.variant === saved.variant);+/*** Whether an installed model is the same file as a saved choice that is no longer installed: a reinstall gives the* file a new key but keeps its hash. Type, base and (where the saved choice names one) variant must agree as well, so* a file registered differently is not taken for it.*/export const isSameModelFile = (candidate: ModelIdentifierConfig, saved: ModelIdentifierConfig): boolean =>- Boolean(saved.hash) &&- candidate.hash === saved.hash &&- candidate.type === saved.type &&- candidate.base === saved.base &&- (saved.variant === undefined || saved.variant === null || candidate.variant === saved.variant);+ Boolean(saved.hash) && candidate.hash === saved.hash && hasSameModelKind(candidate, saved);++/** Match an existing installation, comparing the file hashes when both are available. */+export const isSameInstalledModel = (candidate: ModelIdentifierConfig, saved: ModelIdentifierConfig): boolean =>+ candidate.key === saved.key &&+ hasSameModelKind(candidate, saved) &&+ (!candidate.hash || !saved.hash || candidate.hash === saved.hash);/** Refreshes each concept from the catalog, finding a reinstalled LoRA again by its file hash. */export const syncGenerateLorasWithModels = (loras: GenerateLora[], models: readonly unknown[]): GenerateLora[] => {@@ -699,9 +706,19 @@ const syncReferenceImageConfigWithModels = (): GenerateReferenceImageConfig => {switch (config.type) {case 'flux_kontext_reference_image': {- const model = syncModelIdentifierWithModels(config.model, modelsByKey);+ const boundModel = config.model;+ const model = syncModelIdentifierWithModels(boundModel, modelsByKey);+ // Keep the original binding if the catalog record points to a different model.+ if (+ !boundModel ||+ model === boundModel ||+ !isMainModelConfig(model) ||+ !isSameInstalledModel(model, boundModel)+ ) {+ return config;+ }- return model === config.model ? config : { ...config, model: isMainModelConfig(model) ? model : config.model };+ return { ...config, model };}case 'flux_redux':case 'ip_adapter': {