Skip to content

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

fix(recall): restore concepts when recalling images

Josh Corbette33fee8f89ef
diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx
index 85cf0b3822..01392a248d 100644
--- a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx
+++ b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx
@@ -66,7 +66,7 @@ The **Advanced** section appears for models with extra options, and its header c
Each model has recommended settings, which you can change in the Model Manager. **Reset all to model defaults**, the ↺ button in the Generate panel's title bar, applies them: size, steps, CFG or guidance, scheduler and VAE settings. Your prompts are left alone. The button is disabled when your settings already match the defaults.
-To return to the settings of an earlier image instead, right-click it in the Gallery or Preview and open **Recall Metadata**. **Recall All** restores its model, prompts, seed, size and render settings; **Remix Image** does the same but keeps a new seed; and **Use Prompt**, **Use Seed** and **Use Size** recall one thing at a time.
+To return to the settings of an earlier image instead, right-click it in the Gallery or Preview and open **Recall Metadata**. **Recall All** restores its model, concepts, prompts, seed, size and render settings; **Remix Image** does the same but keeps a new seed; and **Use Prompt**, **Use Seed** and **Use Size** recall one thing at a time. Recalled concepts replace the ones in the panel at the weights the image used; any that are not installed or do not fit the model are listed in a notice. If the image's model is not installed, or the image was saved from the canvas, your current concepts are kept.
To keep a combination of settings for later, use **Presets** in the panel's title bar to save the current settings under a name and apply them again.
diff --git a/docs/src/content/docs/development/Architecture/media-metadata.mdx b/docs/src/content/docs/development/Architecture/media-metadata.mdx
index 66b633f7a4..f9f37dcc2e 100644
--- a/docs/src/content/docs/development/Architecture/media-metadata.mdx
+++ b/docs/src/content/docs/development/Architecture/media-metadata.mdx
@@ -80,7 +80,7 @@ The current value is `CORE_METADATA_VERSION` in `invokeai/app/invocations/metada
| `width`, `height` | integer |
| `model` | `ModelIdentifier`: the main (transformer) model |
| `vae` | `ModelIdentifier`: a standalone VAE override |
-| `loras` | `LoRA[]` |
+| `loras` | `LoRA[]`: the LoRAs the graph loaded, in order; absent when none ran |
### Video profile
@@ -120,8 +120,9 @@ graph builders write only the canonical ones.
by `name` + `base` + `type`. Keys are minted per install, so a record that travelled with a file
names keys the receiving catalog has never seen; the BLAKE3 hash is the content identity and
resolves the same weights wherever they are installed. The name step is the last resort and the
- only one that can pick a different file of the same model. Image recall still resolves by key
- only.
+ only one that can pick a different file of the same model. Image recall resolves its main model
+ and components by key only; its **LoRAs** resolve by `key`, then by `hash` when one was recorded,
+ otherwise by `name` + `base`, and skip any portable identifier that matches more than one install.
- **Media references** (`image_name`, `video_name`) are names in the originating gallery, exactly
as an image record's `init_image` is. Recall restores everything else and clears media it
cannot find rather than substituting.
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphBuilder.ts b/invokeai/frontend/webv2/src/features/generation/core/graphBuilder.ts
index 40685d4f27..9dfc8d0449 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graphBuilder.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graphBuilder.ts
@@ -57,6 +57,15 @@ export const toModelIdentifier = (
...(typeof model.submodel_type === 'string' ? { submodel_type: model.submodel_type } : {}),
});
+/**
+ * The LoRAs a graph loads, as metadata records them. Read from the graph rather than the settings, so a record names
+ * only concepts that reached inference; a family whose graph has no LoRA loader loads none.
+ */
+export const getLoadedLoras = (graph: BackendGraphContract) =>
+ Object.values(graph.nodes)
+ .filter((node) => node.type === 'lora_selector')
+ .map((node) => ({ model: node.lora, weight: node.weight }));
+
export const addMetadata = (
graph: BackendGraphContract,
outputNode: BackendInvocationContract,
@@ -66,7 +75,7 @@ export const addMetadata = (
projectSettings: GenerationProjectSettings & { randDevice?: string },
extras: Record<string, unknown> = {}
) => {
- const activeLoras = getActiveCompatibleLoras(settings, model);
+ const loadedLoras = getLoadedLoras(graph);
const scheduler = coerceSchedulerForGraph(model, settings.scheduler);
const metadata = addNode(graph, {
cfg_scale: settings.cfgScale,
@@ -84,14 +93,7 @@ export const addMetadata = (
vae: settings.vae ?? undefined,
width: settings.width,
...extras,
- ...(activeLoras.length
- ? {
- loras: activeLoras.map((lora) => ({
- model: toModelIdentifier(lora.model),
- weight: lora.weight,
- })),
- }
- : {}),
+ ...(loadedLoras.length ? { loras: loadedLoras } : {}),
...(model.base === 'sdxl' ? {} : { clip_skip: settings.clipSkip }),
});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts
index d825794bee..aabaa2ea2a 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.test.ts
@@ -118,6 +118,35 @@ describe('generate graph coverage', () => {
);
});
+ // An image's metadata is what recall restores, so it must name exactly the LoRAs that reached inference.
+ it.each(generateGraphCases)('$label records only the concepts its graph loads', ({ base, shape }) => {
+ const { model, settings } = satisfiedSettingsFor(base, shape);
+ const lora = (key: string) => ({ base, key, name: key, type: 'lora' as const });
+ const { backendGraph } = compileGenerateGraph(
+ {
+ ...settings,
+ loras: [
+ { isEnabled: true, model: lora('first'), weight: 0.4 },
+ { isEnabled: false, model: lora('disabled'), weight: 1 },
+ { isEnabled: true, model: lora('second'), weight: -0.8 },
+ ],
+ },
+ model,
+ 'gallery',
+ { useCpuNoise: true }
+ );
+ const nodes = Object.values(backendGraph.nodes);
+ const loaded = nodes
+ .filter((node) => node.type === 'lora_selector')
+ .map((node) => [(node.lora as { key: string }).key, node.weight]);
+ const recorded = (nodes.find((node) => node.type === 'core_metadata')?.loras ?? []) as {
+ model: { key: string };
+ weight: number;
+ }[];
+
+ expect(recorded.map((entry) => [entry.model.key, entry.weight])).toEqual(loaded);
+ });
+
it('emits the node types and fields the backend has to provide', async () => {
const byBase: Record<string, { componentsFilled: Record<string, string[]>; nodeTypes: string[] }> = {};
const fields: Record<
diff --git a/invokeai/frontend/webv2/src/features/generation/graph.ts b/invokeai/frontend/webv2/src/features/generation/graph.ts
index c09ff43859..43d827220c 100644
--- a/invokeai/frontend/webv2/src/features/generation/graph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/graph.ts
@@ -10,6 +10,7 @@ export {
addNode,
createId,
getActiveCompatibleLoras,
+ getLoadedLoras,
toGraphContract,
toModelIdentifier,
} from './core/graphBuilder';
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts
index d2228ee3ac..76258d1e8e 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts
@@ -203,3 +203,33 @@ describe('compileUpscaleGraph for FLUX.1', () => {
).toThrow(/T5 encoder/);
});
});
+
+describe('upscale metadata', () => {
+ it.each([
+ ['sd-1', () => createValues('sd-1')],
+ ['sdxl', () => createValues('sdxl')],
+ ['flux', () => createFluxValues()],
+ ] as const)('records exactly the concepts the %s pass loads', (_base, createBaseValues) => {
+ const values = createBaseValues();
+ const { nodes } = compileUpscaleGraph(
+ {
+ ...values,
+ loras: [
+ ...values.loras,
+ { isEnabled: false, model: { ...values.loras[0]!.model, key: 'disabled' }, weight: 1 },
+ { isEnabled: true, model: { ...model('other', 'lora', 'sd-3'), type: 'lora' }, weight: 1 },
+ ],
+ },
+ 'gallery',
+ { useCpuNoise: true }
+ ).backendGraph;
+ const loaded = Object.values(nodes)
+ .filter((node) => node.type === 'lora_selector')
+ .map((node) => [(node.lora as { key: string }).key, node.weight]);
+ const recordedLoras = (nodes.core_metadata?.loras ?? []) as { model: { key: string }; weight: number }[];
+ const recorded = recordedLoras.map((entry) => [entry.model.key, entry.weight]);
+
+ expect(loaded).toEqual([[values.loras[0]!.model.key, 0.7]]);
+ expect(recorded).toEqual(loaded);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.ts
index 0b41d230c2..f0da060db7 100644
--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts
+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.ts
@@ -12,6 +12,7 @@ import {
addNode,
addTransformerLoraCollectionLoader,
getActiveCompatibleLoras,
+ getLoadedLoras,
toGraphContract,
toModelIdentifier,
} from '@features/generation/graph';
@@ -52,8 +53,6 @@ const addUpscaleMetadata = (
return;
}
- // Pass only loras; fabricating unrelated GenerateSettings fields would obscure the helper's actual dependency.
- const activeLoras = getActiveCompatibleLoras({ loras: settings.loras }, settings.model);
const architecture = upscaleArchitectureFor(settings.model);
// FLUX calls this guidance, not CFG, and its encoders have to be recalled with the rest.
const guidanceField = architecture?.usesNegativePrompt
@@ -65,7 +64,8 @@ const addUpscaleMetadata = (
...(settings.clipEmbedModel ? { clip_embed_model: toModelIdentifier(settings.clipEmbedModel) } : {}),
creativity: settings.creativity,
id: 'core_metadata',
- loras: activeLoras.map((lora) => ({ model: toModelIdentifier(lora.model), weight: lora.weight })),
+ // Runs after the path builder, so the graph already holds the LoRAs this architecture loads.
+ loras: getLoadedLoras(graph),
model: toModelIdentifier(settings.model),
rand_device: randDevice,
scheduler: coerceSchedulerForGraph(settings.model, settings.scheduler),
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts
index 4b4fa240aa..70aa1aeda3 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts
@@ -100,6 +100,72 @@ describe('executeImageRecall', () => {
expect(add).toHaveBeenCalledWith(expect.objectContaining({ kind: 'success', title: 'Recalled remix settings' }));
});
+ it.each([
+ { label: 'restores every recorded concept', recorded: ['ink-lora'], skipNotice: false },
+ { label: 'reports concepts it could not restore', recorded: ['ink-lora', 'deleted-lora'], skipNotice: true },
+ ])('$label', async ({ recorded, skipNotice }) => {
+ const { add, commands, setSettings } = createCommands();
+ const inkLora = { base: 'sdxl', key: 'ink-lora', name: 'Ink', type: 'lora' } as ModelConfig;
+
+ galleryApi.galleryImages.metadata.mockResolvedValue({
+ loras: recorded.map((key) => ({ model: { base: 'sdxl', key, name: key, type: 'lora' }, weight: 0.6 })),
+ model: { key: model.key },
+ });
+
+ await expect(
+ executeImageRecall({
+ t,
+ commands,
+ generateValues: { modelKey: model.key },
+ image: { ...image, imageName: `concepts-${recorded.length}.png` },
+ kind: 'all',
+ models: [model, inkLora],
+ projectId: 'project-1',
+ })
+ ).resolves.toBe(true);
+
+ expect(setSettings).toHaveBeenCalledWith(
+ expect.objectContaining({ loras: [{ isEnabled: true, model: inkLora, weight: 0.6 }] }),
+ 'project-1'
+ );
+ expect(add).toHaveBeenCalledWith(expect.objectContaining({ kind: 'success', title: 'Recalled image metadata' }));
+ expect(add).toHaveBeenCalledTimes(skipNotice ? 2 : 1);
+ if (skipNotice) {
+ expect(add).toHaveBeenCalledWith({
+ kind: 'info',
+ message: 'Concepts not restored: deleted-lora (not installed).',
+ title: 'Some image data was not recalled',
+ });
+ }
+ });
+
+ it('explains why nothing was recalled when no recorded concept can be restored', async () => {
+ const { add, commands, setSettings } = createCommands();
+
+ galleryApi.galleryImages.metadata.mockResolvedValue({
+ loras: [{ model: { base: 'sdxl', key: 'deleted-lora', name: 'Deleted', type: 'lora' }, weight: 1 }],
+ });
+
+ await expect(
+ executeImageRecall({
+ t,
+ commands,
+ generateValues: { modelKey: model.key },
+ image: { ...image, imageName: 'unrestorable-concepts.png' },
+ kind: 'remix',
+ models: [model],
+ projectId: 'project-1',
+ })
+ ).resolves.toBe(false);
+
+ expect(setSettings).not.toHaveBeenCalled();
+ expect(add).toHaveBeenCalledWith({
+ kind: 'info',
+ message: 'Concepts not restored: Deleted (not installed).',
+ title: 'No recallable image data',
+ });
+ });
+
it('persists no remix until model capabilities load, and says why', async () => {
const { add, commands, setSettings } = createCommands();
// Initialised while the table is present, so only the recall itself is gated.
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts
index 4c4c3ffe9b..a489e08e16 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts
@@ -30,6 +30,7 @@ import {
import {
buildImageRecallSettings,
getImageRecallMessage,
+ getImageRecallSkipMessage,
getImageRecallTitle,
isImageRecallKindAvailable,
type ImageRecallKind,
@@ -276,10 +277,12 @@ export const executeImageRecall = async ({
}
}
+ const skipMessage = result.skipped.length > 0 ? getImageRecallSkipMessage(result.skipped) : null;
+
if (result.fields.length === 0) {
commands.notifications.add({
kind: 'info',
- message: 'This image does not include supported Generate metadata.',
+ message: skipMessage ?? 'This image does not include supported Generate metadata.',
title: 'No recallable image data',
});
return false;
@@ -291,6 +294,9 @@ export const executeImageRecall = async ({
message: getImageRecallMessage(result.fields),
title: getImageRecallTitle(kind),
});
+ if (skipMessage) {
+ commands.notifications.add({ kind: 'info', message: skipMessage, title: 'Some image data was not recalled' });
+ }
return true;
} catch (error: unknown) {
if (!isAccountScopeCurrent(owner)) {
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
index b96af23f17..f1e7a53682 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
@@ -2,6 +2,7 @@ import type { GalleryImage } from '@features/gallery';
import type {
ComponentModelConfig,
GenerateWidgetValues,
+ LoraModelConfig,
MainModelConfig,
VaeModelConfig,
} from '@features/generation/contracts';
@@ -14,7 +15,11 @@ import {
architectureCapabilitiesFixture,
seedArchitectureCapabilities,
} from '@features/generation/core/architectureCapabilities.testing';
-import { fullyFilledSettingsFor, generateGraphCases } from '@features/generation/core/graphCoverage.testing';
+import {
+ fullyFilledSettingsFor,
+ generateGraphCases,
+ satisfiedSettingsFor,
+} from '@features/generation/core/graphCoverage.testing';
import { compileGenerateGraph } from '@features/generation/graph';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -67,6 +72,23 @@ const qwenVLEncoder: ComponentModelConfig = {
type: 'qwen_vl_encoder',
};
+const inkLora: LoraModelConfig = { base: 'sdxl', hash: 'blake3:ink', key: 'ink-lora', name: 'Ink', type: 'lora' };
+const grainLora: LoraModelConfig = {
+ base: 'sdxl',
+ hash: 'blake3:grain',
+ key: 'grain-lora',
+ name: 'Grain',
+ type: 'lora',
+};
+const staleLora: LoraModelConfig = { base: 'sdxl', key: 'stale-lora', name: 'Stale', type: 'lora' };
+const sd1Lora: LoraModelConfig = { base: 'sd-1', key: 'sd1-lora', name: 'Pixel', type: 'lora' };
+
+/** A recorded `ModelIdentifierField`, as the generation graph writes it. */
+const recordedLora = (lora: LoraModelConfig, weight: number) => ({
+ model: { base: lora.base, hash: lora.hash, key: lora.key, name: lora.name, type: lora.type },
+ weight,
+});
+
const createValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWidgetValues => ({
aspectRatioId: '1:1',
aspectRatioIsLocked: false,
@@ -789,6 +811,286 @@ describe('image recall', () => {
expect(result?.fields).toContain('components');
});
+ describe('concepts', () => {
+ const loraMetadata = {
+ loras: [recordedLora(grainLora, 0.35), recordedLora(inkLora, 1.4)],
+ model: { key: sdxlModel.key },
+ positive_prompt: 'ink and grain',
+ steps: 30,
+ };
+ const recallConcepts = (
+ kind: ImageRecallKind,
+ recordedMetadata: unknown,
+ overrides: Partial<GenerateWidgetValues> = {},
+ models: ComponentModelConfig[] = [sdxlModel, inkLora, grainLora, staleLora, sd1Lora]
+ ) =>
+ buildImageRecallSettings({
+ currentValues: createValues({ loras: [{ isEnabled: true, model: staleLora, weight: 0.9 }], ...overrides }),
+ image,
+ kind,
+ metadata: recordedMetadata,
+ models,
+ supportedModels: models.filter((model): model is MainModelConfig => model.type === 'main'),
+ vaeModels: [],
+ });
+
+ it.each(['all', 'remix'] as const)('%s replaces the selected concepts with the recorded ones', (kind) => {
+ const result = recallConcepts(kind, loraMetadata);
+
+ expect(result?.values.loras).toEqual([
+ { isEnabled: true, model: grainLora, weight: 0.35 },
+ { isEnabled: true, model: inkLora, weight: 1.4 },
+ ]);
+ expect(result?.fields).toContain('loras');
+ expect(result?.skipped).toEqual([]);
+ });
+
+ it('clears stale concepts when a generation record lists none', () => {
+ const result = recallConcepts('all', {
+ generation_mode: 'sdxl_txt2img',
+ model: { key: sdxlModel.key },
+ steps: 30,
+ });
+
+ expect(result?.values.loras).toEqual([]);
+ expect(result?.fields).toContain('loras');
+ });
+
+ it('keeps the selected concepts for a canvas save, which names a model but never records concepts', () => {
+ const result = recallConcepts('all', {
+ height: 1024,
+ model: { base: 'sdxl', key: sdxlModel.key, name: sdxlModel.name, type: 'main' },
+ positive_prompt: 'saved from canvas',
+ seed: 9,
+ width: 1024,
+ });
+
+ expect(result?.values.loras).toEqual([{ isEnabled: true, model: staleLora, weight: 0.9 }]);
+ expect(result?.fields).not.toContain('loras');
+ });
+
+ it('keeps the selected concepts and reports the recorded ones when the image model is not installed', () => {
+ const result = recallConcepts('all', {
+ ...loraMetadata,
+ generation_mode: 'sdxl_txt2img',
+ model: { base: 'sdxl', key: 'uninstalled-model', name: 'Gone', type: 'main' },
+ });
+
+ expect(result?.values.loras).toEqual([{ isEnabled: true, model: staleLora, weight: 0.9 }]);
+ expect(result?.fields).not.toContain('loras');
+ expect(result?.skipped).toEqual([
+ { name: 'Grain', reason: 'modelUnavailable' },
+ { name: 'Ink', reason: 'modelUnavailable' },
+ ]);
+ });
+
+ it('keeps the selected concepts when the image model is the uninstalled one the panel still names', () => {
+ const uninstalled: MainModelConfig = { base: 'sdxl', key: 'uninstalled-model', name: 'Gone', type: 'main' };
+ const result = recallConcepts(
+ 'all',
+ { generation_mode: 'sdxl_txt2img', model: { key: uninstalled.key }, positive_prompt: 'from the old model' },
+ { model: uninstalled, modelKey: uninstalled.key }
+ );
+
+ expect(result?.values.loras).toEqual([{ isEnabled: true, model: staleLora, weight: 0.9 }]);
+ expect(result?.fields).not.toContain('loras');
+ });
+
+ it('restores weights beyond the panel input range exactly', () => {
+ const result = recallConcepts('all', {
+ loras: [recordedLora(inkLora, 12), recordedLora(grainLora, -10.5)],
+ model: { key: sdxlModel.key },
+ });
+
+ expect(result?.values.loras.map((lora) => lora.weight)).toEqual([12, -10.5]);
+ expect(result?.skipped).toEqual([]);
+ });
+
+ it('restores concepts from records that name the LoRA under `lora`', () => {
+ const result = recallConcepts('remix', {
+ loras: [{ lora: { key: inkLora.key }, weight: 0.45 }],
+ model: { key: sdxlModel.key },
+ });
+
+ expect(result?.values.loras).toEqual([{ isEnabled: true, model: inkLora, weight: 0.45 }]);
+ });
+
+ it('keeps the selected concepts when the metadata does not record a generation', () => {
+ const result = recallConcepts('remix', { positive_prompt: 'prompt only' });
+
+ expect(result?.values.loras).toEqual([{ isEnabled: true, model: staleLora, weight: 0.9 }]);
+ expect(result?.fields).not.toContain('loras');
+ });
+
+ it.each(['prompts', 'seed', 'dimensions'] as const)('%s recall leaves the selected concepts alone', (kind) => {
+ const result = recallConcepts(kind, { ...loraMetadata, seed: 7 });
+
+ expect(result?.values.loras).toEqual([{ isEnabled: true, model: staleLora, weight: 0.9 }]);
+ expect(result?.fields).not.toContain('loras');
+ expect(result?.skipped).toEqual([]);
+ });
+
+ it('restores zero and negative weights as recorded, enabled', () => {
+ const result = recallConcepts('all', {
+ loras: [recordedLora(inkLora, 0), recordedLora(grainLora, -0.75)],
+ model: { key: sdxlModel.key },
+ });
+
+ expect(result?.values.loras).toEqual([
+ { isEnabled: true, model: inkLora, weight: 0 },
+ { isEnabled: true, model: grainLora, weight: -0.75 },
+ ]);
+ });
+
+ it('skips missing, incompatible, malformed, and duplicate entries and reports each', () => {
+ const result = recallConcepts('all', {
+ loras: [
+ recordedLora(inkLora, 0.5),
+ { model: { base: 'sdxl', key: 'deleted-lora', name: 'Deleted', type: 'lora' }, weight: 1 },
+ recordedLora(sd1Lora, 0.8),
+ { model: { key: grainLora.key } },
+ 'not an entry',
+ recordedLora(inkLora, 0.9),
+ ],
+ model: { key: sdxlModel.key },
+ });
+
+ expect(result?.values.loras).toEqual([{ isEnabled: true, model: inkLora, weight: 0.5 }]);
+ expect(result?.skipped).toEqual([
+ { name: 'Deleted', reason: 'unresolved' },
+ { name: 'Pixel', reason: 'incompatible' },
+ { name: null, reason: 'invalid' },
+ { name: null, reason: 'invalid' },
+ { name: 'Ink', reason: 'duplicate' },
+ ]);
+ });
+
+ it('keeps the selected concepts and reports a concept list it cannot read', () => {
+ const result = recallConcepts('all', { loras: 'ink', model: { key: sdxlModel.key }, steps: 20 });
+
+ expect(result?.values.loras).toEqual([{ isEnabled: true, model: staleLora, weight: 0.9 }]);
+ expect(result?.skipped).toEqual([{ name: null, reason: 'invalid' }]);
+ expect(result?.fields).toContain('steps');
+ });
+
+ it('judges compatibility against the recalled model, not the one it replaces', () => {
+ const result = recallConcepts(
+ 'all',
+ {
+ loras: [recordedLora(sd1Lora, 0.6), recordedLora(inkLora, 0.4)],
+ model: { key: sd1Model.key },
+ },
+ {},
+ [sd1Model, sdxlModel, sd1Lora, inkLora, staleLora]
+ );
+
+ expect(result?.values.model).toEqual(sd1Model);
+ expect(result?.values.loras).toEqual([{ isEnabled: true, model: sd1Lora, weight: 0.6 }]);
+ expect(result?.skipped).toEqual([{ name: 'Ink', reason: 'incompatible' }]);
+ });
+
+ it('resolves a reinstalled LoRA by its content hash, or by name and base when no hash was recorded', () => {
+ const reinstalledInk = { ...inkLora, key: 'reinstalled-ink' };
+ const result = recallConcepts(
+ 'all',
+ {
+ loras: [
+ { model: { ...recordedLora(inkLora, 1).model, key: 'old-ink-key' }, weight: 0.3 },
+ { model: { base: 'sdxl', key: 'old-grain-key', name: 'Grain', type: 'lora' }, weight: 0.7 },
+ ],
+ model: { key: sdxlModel.key },
+ },
+ {},
+ [sdxlModel, reinstalledInk, grainLora]
+ );
+
+ expect(result?.values.loras).toEqual([
+ { isEnabled: true, model: reinstalledInk, weight: 0.3 },
+ { isEnabled: true, model: grainLora, weight: 0.7 },
+ ]);
+ });
+
+ it('does not pick between installed LoRAs a portable identifier matches equally', () => {
+ const result = recallConcepts(
+ 'all',
+ {
+ loras: [{ model: { ...recordedLora(inkLora, 1).model, key: 'old-ink-key' }, weight: 1 }],
+ model: { key: sdxlModel.key },
+ },
+ {},
+ [sdxlModel, { ...inkLora, key: 'ink-copy-1' }, { ...inkLora, key: 'ink-copy-2' }]
+ );
+
+ expect(result?.values.loras).toEqual([]);
+ expect(result?.skipped).toEqual([{ name: 'Ink', reason: 'ambiguous' }]);
+ });
+
+ it('does not substitute a same-named LoRA whose content differs from the recorded hash', () => {
+ const result = recallConcepts(
+ 'all',
+ {
+ loras: [{ model: { ...recordedLora(inkLora, 1).model, key: 'old-ink-key' }, weight: 1 }],
+ model: { key: sdxlModel.key },
+ },
+ {},
+ [sdxlModel, { ...inkLora, hash: 'blake3:retrained', key: 'retrained-ink' }]
+ );
+
+ expect(result?.skipped).toEqual([{ name: 'Ink', reason: 'unresolved' }]);
+ });
+
+ it('offers Recall All and Remix for metadata that records only concepts it can restore', () => {
+ const capabilitiesFor = (models: ComponentModelConfig[]) =>
+ getImageRecallCapabilities({
+ currentValues: createValues(),
+ image,
+ metadata: { loras: [recordedLora(inkLora, 0.5)] },
+ models,
+ supportedModels: [],
+ vaeModels: [],
+ });
+
+ expect(capabilitiesFor([inkLora])).toMatchObject({ all: true, remix: true });
+ expect(capabilitiesFor([sd1Lora])).toMatchObject({ all: false, remix: false });
+ });
+
+ it('submits the restored concepts at their recorded weights', () => {
+ const { model, settings } = satisfiedSettingsFor('sdxl', {
+ label: 'diffusers',
+ overrides: { format: 'diffusers' },
+ });
+ const generatedWith = {
+ ...settings,
+ loras: [
+ { isEnabled: true, model: grainLora, weight: -0.4 },
+ { isEnabled: false, model: staleLora, weight: 1 },
+ { isEnabled: true, model: inkLora, weight: 1.25 },
+ ],
+ };
+ const loraWeights = (backendGraph: { nodes: Record<string, Record<string, unknown>> }) =>
+ Object.values(backendGraph.nodes)
+ .filter((node) => node.type === 'lora_selector')
+ .map((node) => [(node.lora as { key: string }).key, node.weight]);
+ const generated = compileGenerateGraph(generatedWith, model, 'gallery', { useCpuNoise: true }).backendGraph;
+ const result = buildImageRecallSettings({
+ currentValues: createValues({ loras: [{ isEnabled: true, model: staleLora, weight: 0.9 }], model: sd1Model }),
+ image,
+ kind: 'all',
+ metadata: Object.values(generated.nodes).find((node) => node.type === 'core_metadata'),
+ models: [model, inkLora, grainLora, staleLora],
+ supportedModels: [model],
+ vaeModels: [],
+ });
+ const recalled = compileGenerateGraph(result!.values, result!.values.model, 'gallery', { useCpuNoise: true });
+
+ expect(loraWeights(recalled.backendGraph)).toEqual([
+ [grainLora.key, -0.4],
+ [inkLora.key, 1.25],
+ ]);
+ expect(loraWeights(recalled.backendGraph)).toEqual(loraWeights(generated));
+ });
+ });
+
describe('krea-2 conditioning rebalance', () => {
const krea2Metadata = {
krea2_rebalance_enabled: true,
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
index ea297e0f8c..3aa819da84 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts
@@ -1,8 +1,10 @@
import type { GalleryImage } from '@features/gallery';
import type {
ComponentModelConfig,
+ GenerateLora,
GenerateModelConfig,
GenerateWidgetValues,
+ LoraModelConfig,
MainModelConfig,
VaeModelConfig,
} from '@features/generation/contracts';
@@ -21,6 +23,8 @@ import {
hasArchitectureCapabilities,
hasModelDefaultVae,
isKnownScheduler,
+ isLoraCompatibleWithModel,
+ isLoraModelConfig,
isMainModelConfig,
isModelIdentifierConfig,
isVaeCompatibleWithGenerateModel,
@@ -67,11 +71,27 @@ type RecalledField =
| 'hiDiffusion'
| 'clipSkip'
| 'components'
+ | 'loras'
| 'referenceImages'
| 'krea2Rebalance';
+export type ImageRecallSkipReason =
+ | 'ambiguous'
+ | 'duplicate'
+ | 'incompatible'
+ | 'invalid'
+ | 'modelUnavailable'
+ | 'unresolved';
+
+/** A recorded concept recall could not restore; `name` is the best label the record or catalog offers. */
+export interface ImageRecallSkip {
+ name: string | null;
+ reason: ImageRecallSkipReason;
+}
+
export interface ImageRecallResult {
fields: RecalledField[];
+ skipped: ImageRecallSkip[];
values: GenerateWidgetValues;
}
@@ -476,6 +496,133 @@ const getComponentPatch = (
const hasComponentModels = (metadata: unknown, models: readonly ComponentModelConfig[]): boolean =>
Object.keys(getComponentPatch(metadata, models)).length > 0;
+/** A recorded `ModelIdentifierField` — `{ key, hash, name, base }` — with every field optional on read. */
+interface RecordedModelRef {
+ base: string | null;
+ hash: string | null;
+ key: string | null;
+ name: string | null;
+}
+
+const toRecordedModelRef = (value: unknown): RecordedModelRef | null => {
+ if (!isRecord(value)) {
+ return null;
+ }
+
+ const ref = {
+ base: getString(value, 'base'),
+ hash: getString(value, 'hash'),
+ key: getString(value, 'key'),
+ name: getString(value, 'name'),
+ };
+
+ return ref.key || ref.hash || (ref.name && ref.base) ? ref : null;
+};
+
+/**
+ * Resolve the install-local key first, then a portable identifier: the content hash when one was recorded, otherwise
+ * name and base. A recorded hash never falls back to a same-named file, and a portable identifier counts only when
+ * exactly one installed LoRA matches it.
+ */
+const resolveRecordedLora = (
+ ref: RecordedModelRef,
+ loraModels: readonly LoraModelConfig[]
+): LoraModelConfig | 'ambiguous' | null => {
+ const byKey = ref.key ? loraModels.find((model) => model.key === ref.key) : undefined;
+
+ if (byKey) {
+ return byKey;
+ }
+
+ const matches = ref.hash
+ ? loraModels.filter((model) => model.hash === ref.hash)
+ : ref.name && ref.base
+ ? loraModels.filter((model) => model.name === ref.name && model.base === ref.base)
+ : [];
+
+ return matches.length > 1 ? 'ambiguous' : (matches[0] ?? null);
+};
+
+/**
+ * Generation graphs stamp `generation_mode` and omit `loras` when no concept was active, so on such a record a
+ * missing list means "none". Other records that name a model, such as canvas saves, never record concepts.
+ */
+const isGenerationRecord = (metadata: unknown): boolean => getString(metadata, 'generation_mode') !== null;
+
+interface ConceptRecall {
+ /** The concept list to apply, or null when the metadata says nothing reliable about concepts. */
+ loras: GenerateLora[] | null;
+ skipped: ImageRecallSkip[];
+}
+
+/**
+ * Concepts the image was generated with, resolved against installed LoRAs that fit `model`, the model recall settles
+ * on. `sourceModel` is the recorded main model as resolved from the installed catalog. The metadata lists only the
+ * LoRAs that ran, so every restored concept is enabled at its recorded weight.
+ */
+const getMetadataConcepts = (
+ metadata: unknown,
+ models: readonly ComponentModelConfig[],
+ model: GenerateModelConfig,
+ sourceModel: GenerateModelConfig | null
+): ConceptRecall => {
+ const recorded = isRecord(metadata) ? metadata.loras : undefined;
+
+ // Matching keys alone are not enough: persisted settings can still name a model that is no longer installed.
+ if (getRecord(metadata, 'model') && sourceModel?.key !== model.key) {
+ // Concepts belong to the model they ran on. Without it the current set stays, rather than being judged against
+ // a model recall did not choose.
+ const entries = Array.isArray(recorded) ? recorded : [];
+
+ return {
+ loras: null,
+ skipped: entries.map((entry) => ({
+ name: toRecordedModelRef(getRecord(entry, 'model') ?? getRecord(entry, 'lora'))?.name ?? null,
+ reason: 'modelUnavailable',
+ })),
+ };
+ }
+
+ if (recorded === undefined || recorded === null) {
+ return { loras: isGenerationRecord(metadata) ? [] : null, skipped: [] };
+ }
+
+ if (!Array.isArray(recorded)) {
+ return { loras: null, skipped: [{ name: null, reason: 'invalid' }] };
+ }
+
+ const loraModels = models.filter(isLoraModelConfig);
+ const loras: GenerateLora[] = [];
+ const skipped: ImageRecallSkip[] = [];
+
+ for (const entry of recorded) {
+ // Records from before LoRA identifiers were `ModelIdentifierField`s name the LoRA under `lora`.
+ const ref = toRecordedModelRef(getRecord(entry, 'model') ?? getRecord(entry, 'lora'));
+ const weight = getNumber(entry, 'weight');
+ const recordedName = ref?.name ?? null;
+
+ if (!ref || weight === null) {
+ skipped.push({ name: recordedName, reason: 'invalid' });
+ continue;
+ }
+
+ const installed = resolveRecordedLora(ref, loraModels);
+
+ if (installed === null || installed === 'ambiguous') {
+ skipped.push({ name: recordedName, reason: installed === 'ambiguous' ? 'ambiguous' : 'unresolved' });
+ } else if (!isLoraCompatibleWithModel(installed, model)) {
+ skipped.push({ name: installed.name, reason: 'incompatible' });
+ } else if (loras.some((lora) => lora.model.key === installed.key)) {
+ skipped.push({ name: installed.name, reason: 'duplicate' });
+ } else {
+ // Kept exactly: graphs and model defaults accept weights beyond the panel's typed range, which bounds only edits.
+ loras.push({ isEnabled: true, model: installed, weight });
+ }
+ }
+
+ return { loras, skipped };
+};
+
export const getMetadataReferenceImages = (metadata: unknown) => {
if (!isRecord(metadata)) {
return [];
@@ -561,6 +708,8 @@ export const getImageRecallCapabilities = ({
const hasReferenceImages = getMetadataReferenceImages(metadata).length > 0;
const hasModel = supportedMetadataModel !== null;
const hasRebalance = hasKrea2Rebalance(metadata, clipSkipModel);
+ const hasConcepts =
+ (getMetadataConcepts(metadata, models, clipSkipModel, supportedMetadataModel).loras?.length ?? 0) > 0;
const hasAnyMetadata =
hasModel ||
hasVae ||
@@ -572,6 +721,7 @@ export const getImageRecallCapabilities = ({
hasClipSkip ||
hasComponents ||
hasReferenceImages ||
+ hasConcepts ||
hasRebalance;
const hasNonSeedMetadata =
hasModel ||
@@ -583,6 +733,7 @@ export const getImageRecallCapabilities = ({
hasClipSkip ||
hasComponents ||
hasReferenceImages ||
+ hasConcepts ||
hasRebalance;
return {
@@ -618,6 +769,7 @@ export const buildImageRecallSettings = ({
}
const fields: RecalledField[] = [];
+ const skipped: ImageRecallSkip[] = [];
let values: GenerateWidgetValues = cloneGenerateWidgetValues(currentValues);
if (kind === 'all' || kind === 'remix') {
@@ -671,6 +823,16 @@ export const buildImageRecallSettings = ({
fields.push('components');
}
+ // Judged against the model the transition settled on; the recorded concepts replace the list it left.
+ const concepts = getMetadataConcepts(metadata, models, values.model, model);
+
+ skipped.push(...concepts.skipped);
+
+ if (concepts.loras && (concepts.loras.length > 0 || currentValues.loras.length > 0)) {
+ values = { ...values, loras: concepts.loras };
+ fields.push('loras');
+ }
+
// 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.
@@ -769,7 +931,7 @@ export const buildImageRecallSettings = ({
}
}
- return fields.length > 0 ? { fields, values } : null;
+ return fields.length > 0 || skipped.length > 0 ? { fields, skipped, values } : null;
};
export const getImageRecallTitle = (kind: ImageRecallKind): string => {
@@ -791,3 +953,18 @@ export const getImageRecallTitle = (kind: ImageRecallKind): string => {
export const getImageRecallMessage = (fields: RecalledField[]): string =>
`${fields.length} field${fields.length === 1 ? '' : 's'} applied to Generate.`;
+
+const SKIP_REASON_LABELS: Record<ImageRecallSkipReason, string> = {
+ ambiguous: 'matches more than one installed model',
+ duplicate: 'listed more than once',
+ incompatible: 'incompatible with the selected model',
+ invalid: 'unreadable metadata',
+ modelUnavailable: "the image's model is not available",
+ unresolved: 'not installed',
+};
+
+/** One line naming every recorded concept recall left out and why. */
+export const getImageRecallSkipMessage = (skipped: readonly ImageRecallSkip[]): string =>
+ `Concepts not restored: ${skipped
+ .map(({ name, reason }) => `${name ?? 'unnamed concept'} (${SKIP_REASON_LABELS[reason]})`)
+ .join('; ')}.`;