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
feat(generation): update a loaded preset from the current settings (#10285)
Lincoln Steinfcfe4131a78e
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.mdxindex 43c94aca8e..bcaeb9db5f 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@@ -118,7 +118,7 @@ Either way your prompts and concepts are left alone, and a notification lists whTo return to the settings of an earlier image instead, open **Use** in the Preview's header, or right-click the image in the Gallery or Preview and open **Reuse from image**. **All settings** restores its model, concepts, prompts, seed, size, render and refiner settings; **Remix image** does the same with 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. When you save, **Include prompts** decides whether the preset keeps your prompts too; the panel remembers your choice. Applying a preset saved without prompts keeps the prompts you have. Applying a preset shows a notification with **Undo**, which restores the settings you had before. Deleting a preset, or a saved Krea-2 conditioning rebalance curve, takes effect immediately; a notification with **Undo** brings it back.+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. When you save, **Include prompts** decides whether the preset keeps your prompts too; the panel remembers your choice. Applying a preset saved without prompts keeps the prompts you have. Applying a preset shows a notification with **Undo**, which restores the settings you had before. After you apply or save a preset and then change the settings, the floppy-disk button beside **Save preset** overwrites that preset with the current settings, keeping its choice about prompts; a notification with **Undo** puts the old settings back. Deleting a preset, or a saved Krea-2 conditioning rebalance curve, takes effect immediately; a notification with **Undo** brings it back.## Adding conceptsdiff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex dbe16173a4..e1a85ace01 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -3365,6 +3365,7 @@"presetsEmpty": "No presets yet. Save the current settings to reuse them later.","presetsNoMatches": "No presets match your search.","presetUnreadable": "This preset could not be read.",+ "presetUpdated": "Updated preset {{name}}","promptHistory": "Prompt history","promptHistoryEntries": "Prompt history entries","promptHistoryKeyboardHelp": "Alt+Up/Down switches between prompts while focused.",@@ -3395,6 +3396,8 @@"savePresetTitle": "Save preset","selectSupportedModelFirst": "Select a supported Generate model first.","searchPresets": "Search presets",+ "updatePreset": "Update the loaded preset with the current settings",+ "updatePresetNamed": "Update preset {{name}} with the current settings","secondsPerRun": "~{{value}}s/run","sectionChanged": "Changed from defaults","sectionMenu": {diff --git a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsxindex c3e5b343e3..ba0a0cd95f 100644--- a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx@@ -446,6 +446,13 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNodesetIncludePrompts: (includePrompts) => {void patchWorkbenchPreferences({ generatePresetsIncludePrompts: includePrompts });},+ update: (presetId, values) => {+ void patchWorkbenchPreferences({+ generatePresets: getWorkbenchPreferences().generatePresets.map((preset) =>+ preset.id === presetId ? { ...preset, values } : preset+ ),+ });+ },}),[generatePresets, generatePresetsIncludePrompts]);diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.browser.test.tsxindex 34f509c19f..f1802405f0 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.browser.test.tsx@@ -219,7 +219,7 @@ describe('GeneratePresetsPopover', () => {});it('saves a preset without prompts when asked, remembers the choice, and keeps the prompts it is applied over', async () => {- const save = vi.fn();+ const save = vi.fn((label: string, values: Record<string, unknown>) => ({ id: 'saved', label, values }));const setIncludePrompts = vi.fn();const patchGenerateSettings = vi.fn();const saved = { ...getDefaultGenerateSettings(model), positivePrompt: 'a castle', steps: 12 };@@ -270,6 +270,130 @@ describe('GeneratePresetsPopover', () => {);});+ it('updates the loaded preset once the settings change, keeping its prompt choice, and Undo restores it', async () => {+ const presetValues: Record<string, unknown> = { ...getDefaultGenerateSettings(model), steps: 12 };+ delete presetValues.positivePrompt;+ delete presetValues.negativePrompt;+ const stored = { current: [{ id: 'p', label: 'Mine', values: presetValues }] as GeneratePresetRecord[] };+ const values = { current: { ...getDefaultGenerateSettings(model), model, steps: 30 } as Record<string, unknown> };+ const undoable = vi.fn();+ const update = vi.fn((id: string, next: Record<string, unknown>) => {+ stored.current = stored.current.map((preset) => (preset.id === id ? { ...preset, values: next } : preset));+ });+ const buildAdapter = () =>+ ({+ ...ADAPTER,+ generateValues: { getSnapshot: () => values.current, subscribe: () => () => {} },+ models: { ...ADAPTER.models, catalog: [model] },+ notifications: { ...ADAPTER.notifications, undoable },+ presets: { ...ADAPTER.presets, presets: stored.current, update },+ settings: {+ ...ADAPTER.settings,+ patchGenerateSettings: (patch: Record<string, unknown>) => {+ values.current = { ...values.current, ...patch };+ },+ },+ }) as unknown as GenerationUiAdapter;+ const updateButton = () =>+ document.querySelector<HTMLButtonElement>('[aria-label^="widgets.generate.updatePreset"]')!;+ await renderAdapter(buildAdapter());+ await openPresets();++ // Nothing loaded yet: the settings differ from the preset, but there is nothing to update.+ expect(updateButton().disabled).toBe(true);++ await clickPreset('Mine');+ await renderAdapter(buildAdapter());+ // The trigger now names the active preset after the section label.+ await act(() => userEvent.click(document.querySelector<HTMLElement>('[aria-label^="widgets.generate.presets"]')!));++ // Just loaded, the settings match it.+ expect(values.current).toMatchObject({ steps: 12 });+ expect(updateButton().disabled).toBe(true);++ values.current = { ...values.current, positivePrompt: 'a castle', steps: 20 };+ await renderAdapter(buildAdapter());++ expect(updateButton().disabled).toBe(false);+ await act(() => userEvent.click(updateButton()));++ expect(update).toHaveBeenCalledOnce();+ expect(stored.current[0]!.values).toMatchObject({ steps: 20 });+ expect(stored.current[0]!.values).not.toHaveProperty('positivePrompt');+ await renderAdapter(buildAdapter());+ expect(updateButton().disabled).toBe(true);++ expect(undoable).toHaveBeenLastCalledWith('widgets.generate.presetUpdated', {+ onUndo: expect.any(Function),+ supersedes: 'generate-preset-update:p',+ });+ undoable.mock.lastCall![1].onUndo();+ expect(stored.current[0]!.values).toBe(presetValues);+ });++ it("puts back the update target an apply's Undo returns to, so Update never overwrites the undone preset", async () => {+ const presetA = { ...getDefaultGenerateSettings(model), steps: 12 };+ const presetB = { ...getDefaultGenerateSettings(model), steps: 20 };+ const values = { current: { ...getDefaultGenerateSettings(model), model, steps: 30 } as Record<string, unknown> };+ const undoable = vi.fn();+ const update = vi.fn();+ const buildAdapter = () =>+ ({+ ...ADAPTER,+ generateValues: { getSnapshot: () => values.current, subscribe: () => () => {} },+ models: { ...ADAPTER.models, catalog: [model] },+ notifications: { ...ADAPTER.notifications, undoable },+ presets: {+ ...ADAPTER.presets,+ presets: [+ { id: 'a', label: 'Alpha', values: presetA },+ { id: 'b', label: 'Beta', values: presetB },+ ],+ update,+ },+ settings: {+ ...ADAPTER.settings,+ patchGenerateSettings: (patch: Record<string, unknown>) => {+ values.current = { ...values.current, ...patch };+ },+ readGenerateValues: () => values.current,+ },+ }) as unknown as GenerationUiAdapter;+ const openTrigger = () =>+ act(() => userEvent.click(document.querySelector<HTMLElement>('[aria-label^="widgets.generate.presets"]')!));+ const updateButton = () =>+ document.querySelector<HTMLButtonElement>('[aria-label^="widgets.generate.updatePreset"]')!;+ const applyAndUndo = async (label: string) => {+ await openTrigger();+ await clickPreset(label);+ await act(() => undoable.mock.lastCall![1].onUndo());+ await renderAdapter(buildAdapter());+ };+ await renderAdapter(buildAdapter());++ // Nothing was loaded before the apply, so after its Undo there is nothing to update, even after an edit.+ await applyAndUndo('Alpha');+ values.current = { ...values.current, steps: 31 };+ await renderAdapter(buildAdapter());+ await openTrigger();+ expect(updateButton().disabled).toBe(true);+ await act(() => userEvent.keyboard('{Escape}'));++ // Apply A, apply B, undo B, edit: Update targets A.+ await openTrigger();+ await clickPreset('Alpha');+ await renderAdapter(buildAdapter());+ await applyAndUndo('Beta');+ expect(values.current).toMatchObject({ steps: 12 });+ values.current = { ...values.current, steps: 13 };+ await renderAdapter(buildAdapter());+ await openTrigger();++ expect(updateButton().getAttribute('aria-label')).toBe('widgets.generate.updatePresetNamed');+ await act(() => userEvent.click(updateButton()));+ expect(update).toHaveBeenCalledExactlyOnceWith('a', expect.objectContaining({ steps: 13 }));+ });+it('deletes a preset at once, and its Undo puts it back where it was, active again while the settings match', async () => {const portrait = { ...getDefaultGenerateSettings(model), steps: 12 };const stored = {diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsxindex 2151ca27cf..8efd7b0206 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GeneratePresetsPopover.tsx@@ -10,7 +10,7 @@ import { GENERATE_TOOL_MODEL_PICK_KEYS, normalizeGenerateSettings } from '@featuimport { resolveGenerateWidgetValues } from '@features/generation/settings';import { useExitRetainedValue } from '@platform/react/useExitRetainedValue';import { Button, IconButton, PopoverContent, RenameDialog, Row, Scrollable, Tooltip } from '@platform/ui';-import { BookmarkIcon, CheckIcon, PencilIcon, PlusIcon, SearchIcon, Trash2Icon } from 'lucide-react';+import { BookmarkIcon, CheckIcon, PencilIcon, PlusIcon, SaveIcon, SearchIcon, Trash2Icon } from 'lucide-react';import { useCallback, useId, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -105,6 +105,19 @@ const getStoredPresetKey = (preset: GeneratePresetRecord): { key: string; keptKereturn settings ? { key: getPresetComparisonKey(settings, keptKeys), keptKeys } : null;};+/** What a preset stores of `settings`: without the prompts unless `includePrompts`. */+const getPresetValues = (settings: GenerateSettings, includePrompts: boolean): Record<string, unknown> => {+ const values: Record<string, unknown> = { ...settings };++ if (!includePrompts) {+ for (const key of PRESET_PROMPT_KEYS) {+ delete values[key];+ }+ }++ return values;+};+const PresetRow = ({isActive,preset,@@ -226,6 +239,15 @@ export const GeneratePresetsPopover = () => {return index >= 0 ? (presets[index] ?? null) : null;}, [presetKeys, presets, settings]);+ // The preset last applied or saved in this project; Update overwrites it once the settings stop matching it. An+ // apply's Undo puts back the one loaded before it.+ const [loaded, setLoaded] = useState<{ presetId: string; projectId: typeof projectId } | null>(null);+ const loadedIndex = loaded?.projectId === projectId ? presets.findIndex((p) => p.id === loaded.presetId) : -1;+ const loadedPreset = presets[loadedIndex] ?? null;+ const loadedKey = presetKeys[loadedIndex];+ const currentLoadedKey = settings && loadedKey ? getPresetComparisonKey(settings, loadedKey.keptKeys) : null;+ const canUpdate = canSave && currentLoadedKey !== null && currentLoadedKey !== loadedKey?.key;+const handleOpenChange = useCallback((event: { open: boolean }) => {setIsOpen(event.open);@@ -274,15 +296,21 @@ export const GeneratePresetsPopover = () => {after: { ...before, ...patch },before,message,+ // Only while this apply's preset is still the target; a Save since keeps its own.+ onUndone: () =>+ setLoaded((current) =>+ current?.presetId === record.id && current.projectId === projectId ? loaded : current+ ),projectId,slot: 'settings',t,title: t('widgets.generate.presetApplied', { name: record.label }),ui,});+ setLoaded({ presetId: record.id, projectId });setIsOpen(false);},- [i18n.resolvedLanguage, models, projectId, supportedModels, t, ui]+ [i18n.resolvedLanguage, loaded, models, projectId, supportedModels, t, ui]);const [includePrompts, setIncludePrompts] = useState(ui.presets.includePrompts);@@ -314,23 +342,44 @@ export const GeneratePresetsPopover = () => {return;}- const values: Record<string, unknown> = { ...snapshot };-- if (!includePrompts) {- for (const key of PRESET_PROMPT_KEYS) {- delete values[key];- }- }+ const saved = ui.presets.save(label, getPresetValues(snapshot, includePrompts));- ui.presets.save(label, values);+ setLoaded({ presetId: saved.id, projectId });if (includePrompts !== ui.presets.includePrompts) {ui.presets.setIncludePrompts(includePrompts);}},- [dialogSubject, includePrompts, ui.generateValues, ui.presets]+ [dialogSubject, includePrompts, projectId, ui.generateValues, ui.presets]);+ // Keeps the preset's choice about prompts; undoable like a delete.+ const updateLoadedPreset = useCallback(() => {+ if (!loadedPreset) {+ return;+ }++ flushGenerateDrafts();+ const snapshot = normalizeGenerateSettings(ui.generateValues.getSnapshot());++ if (!snapshot) {+ return;+ }++ const { id, label, values: previous } = loadedPreset;+ const { update } = ui.presets;++ update(id, getPresetValues(snapshot, 'positivePrompt' in previous));+ ui.notifications.undoable(t('widgets.generate.presetUpdated', { name: label }), {+ onUndo: () => update(id, previous),+ // A later update's Undo withdraws this one, which would discard it.+ supersedes: `generate-preset-update:${id}`,+ });+ }, [loadedPreset, t, ui.generateValues, ui.notifications, ui.presets]);+ const updateLabel = loadedPreset+ ? t('widgets.generate.updatePresetNamed', { name: loadedPreset.label })+ : t('widgets.generate.updatePreset');+// Deleting is undoable, so it asks nothing. The active preset is derived from the settings, which a delete leaves// alone: Undo brings the preset back as active if the settings still match it.const deletePreset = useCallback(@@ -394,16 +443,30 @@ export const GeneratePresetsPopover = () => {<Popover.Body p="2.5"><Stack gap="2"><PromptPanelHeader label={presetsLabel}>- <Button- disabled={!canSave}- h={PANEL_HEADER_CONTROL_HEIGHT}- size="sm"- variant="ghost"- onClick={openSaveDialog}- >- <PlusIcon />- {t('widgets.generate.savePresetTitle')}- </Button>+ <HStack gap="0.5">+ <Tooltip content={updateLabel}>+ <IconButton+ aria-label={updateLabel}+ disabled={!canUpdate}+ h={PANEL_HEADER_CONTROL_HEIGHT}+ size="sm"+ variant="ghost"+ onClick={updateLoadedPreset}+ >+ <SaveIcon />+ </IconButton>+ </Tooltip>+ <Button+ disabled={!canSave}+ h={PANEL_HEADER_CONTROL_HEIGHT}+ size="sm"+ variant="ghost"+ onClick={openSaveDialog}+ >+ <PlusIcon />+ {t('widgets.generate.savePresetTitle')}+ </Button>+ </HStack></PromptPanelHeader>{presets.length >= SEARCH_VISIBLE_MIN_PRESETS ? (<InputGroup startElement={SEARCH_START_ELEMENT}>diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsxindex d0eea8297d..15c214b8a5 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx@@ -178,6 +178,8 @@ export interface GenerationUiAdapter {remove(presetId: string): void;/** Undoes a remove: puts `preset` back at `index` (or last), unless a preset with its id is still there. */restore(preset: GeneratePresetRecord, index: number): void;+ /** Replaces a preset's snapshot, keeping its id and label. */+ update(presetId: string, values: Record<string, unknown>): void;};/*** Insights from the project's recent queue runs. Subscribing keeps the backing queue read observed, so only thediff --git a/invokeai/frontend/webv2/src/features/generation/ui/generateUndo.ts b/invokeai/frontend/webv2/src/features/generation/ui/generateUndo.tsindex da368af5e3..e903f93dfc 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/generateUndo.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/generateUndo.ts@@ -31,6 +31,8 @@ interface GenerateUndoOffer {* Undo does nothing. Otherwise it puts back the keys still holding what the change wrote and leaves the rest.*/isWhole?: boolean;+ /** Runs after an Undo that restored something, for state the caller keeps beside the settings. */+ onUndone?: () => void;}/**@@ -63,6 +65,7 @@ export const offerGenerateUndo = ({before,isWhole = false,message,+ onUndone,projectId,slot,t,@@ -86,6 +89,7 @@ export const offerGenerateUndo = ({(!isWhole || stillApplied.length === Object.keys(revertPatch).length)) {ui.settings.patchGenerateSettings(Object.fromEntries(stillApplied), projectId);+ onUndone?.();} else {ui.notifications.info(t('widgets.generate.undoStale'));}