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
perf(ui): index the model library by key
joshistoastdb9b772906c8
diff --git a/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts b/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.tsindex a93b3ca95f..ffa25b2545 100644--- a/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts+++ b/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts@@ -45,6 +45,24 @@ describe('models store loading', () => {expect(api.listModels).toHaveBeenCalledTimes(2);});+ it('keeps the by-key index in lockstep with every models write', async () => {+ api.listModels.mockResolvedValueOnce([+ { base: 'sdxl', key: 'a', name: 'A', type: 'main' },+ { base: 'sdxl', key: 'b', name: 'B', type: 'main' },+ ]);+ const store = await import('./modelsStore');++ await store.refreshModels();+ expect(store.getModelsSnapshot().modelsByKey.get('b')?.name).toBe('B');++ store.patchModelInStore('a', { name: 'A2' });+ expect(store.getModelsSnapshot().modelsByKey.get('a')?.name).toBe('A2');++ store.removeModelsFromStore(['b']);+ expect(store.getModelsSnapshot().modelsByKey.has('b')).toBe(false);+ expect(store.getModelsSnapshot().models.map((model) => model.key)).toEqual(['a']);+ });+it('unwraps FastAPI detail bodies into the snapshot error', async () => {const { ApiError } = await import('@platform/transport/http');api.listModels.mockRejectedValueOnce(new ApiError('{"detail":"Model records unavailable"}', 500));diff --git a/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts b/invokeai/frontend/webv2/src/features/models/data/modelsStore.tsindex 7677843542..67b148e8fa 100644--- a/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts+++ b/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts@@ -23,6 +23,8 @@ import { getModelsDir, listMissingModels, listModels } from './api';export interface ModelsSnapshot {models: ModelConfig[];+ /** Same models keyed for point lookups; always derived from `models`. */+ modelsByKey: ReadonlyMap<string, ModelConfig>;/** Keys of models whose files are missing on disk. */missingModelKeys: ReadonlySet<string>;/** Bumped when a model's cover image changes; cache-busts thumbnail URLs. */@@ -34,15 +36,23 @@ export interface ModelsSnapshot {}const EMPTY_MISSING_KEYS: ReadonlySet<string> = new Set<string>();+const EMPTY_MODELS_BY_KEY: ReadonlyMap<string, ModelConfig> = new Map<string, ModelConfig>();const EMPTY_MODELS_SNAPSHOT: ModelsSnapshot = {coverImageVersions: {},error: null,missingModelKeys: EMPTY_MISSING_KEYS,models: [],+ modelsByKey: EMPTY_MODELS_BY_KEY,modelsDir: null,status: 'idle',};++/** Every `models` write goes through here so the by-key index never drifts. */+const withModels = (models: ModelConfig[]): Pick<ModelsSnapshot, 'models' | 'modelsByKey'> => ({+ models,+ modelsByKey: new Map(models.map((model) => [model.key, model])),+});const store = createExternalStore<ModelsSnapshot>(EMPTY_MODELS_SNAPSHOT);const refreshFlight = createTrailingSingleFlight();@@ -73,10 +83,10 @@ export const refreshModels = (owner: AccountScope = captureAccountScope()): Prom}store.patchSnapshot({+ ...withModels(models),error: null,missingModelKeys:missingModels.length > 0 ? new Set(missingModels.map((model) => model.key)) : EMPTY_MISSING_KEYS,- models,modelsDir,status: 'loaded',});@@ -111,22 +121,22 @@ export const subscribeModels = (listener: () => void): (() => void) => store.sub/** Patch one model in place after a successful update/convert. */export const replaceModelInStore = (model: ModelConfig): void => {- store.patchSnapshot({- models: store.getSnapshot().models.map((existing) => (existing.key === model.key ? model : existing)),- });+ store.patchSnapshot(+ withModels(store.getSnapshot().models.map((existing) => (existing.key === model.key ? model : existing)))+ );};/** Apply a narrow optimistic model patch without replacing unrelated server fields. */export const patchModelInStore = (key: string, changes: Partial<ModelConfig>): void => {- store.patchSnapshot({- models: store.getSnapshot().models.map((model) => (model.key === key ? { ...model, ...changes } : model)),- });+ store.patchSnapshot(+ withModels(store.getSnapshot().models.map((model) => (model.key === key ? { ...model, ...changes } : model)))+ );};export const removeModelsFromStore = (keys: string[]): void => {const removed = new Set(keys);- store.patchSnapshot({ models: store.getSnapshot().models.filter((model) => !removed.has(model.key)) });+ store.patchSnapshot(withModels(store.getSnapshot().models.filter((model) => !removed.has(model.key))));};/**@@ -138,15 +148,17 @@ export const markCoverImageChanged = (key: string, hasImage: boolean): void => {const { coverImageVersions, models } = store.getSnapshot();store.patchSnapshot({- coverImageVersions: { ...coverImageVersions, [key]: (coverImageVersions[key] ?? 0) + 1 },- models: models.map((model) =>- model.key === key ? { ...model, cover_image: hasImage ? (model.cover_image ?? 'present') : null } : model+ ...withModels(+ models.map((model) =>+ model.key === key ? { ...model, cover_image: hasImage ? (model.cover_image ?? 'present') : null } : model+ )),+ coverImageVersions: { ...coverImageVersions, [key]: (coverImageVersions[key] ?? 0) + 1 },});};export const setModelsSnapshotForTests = (next: Partial<ModelsSnapshot>): void => {- store.patchSnapshot(next);+ store.patchSnapshot(next.models ? { ...next, ...withModels(next.models) } : next);};export const useModelsSelector = store.useSelector;diff --git a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsxindex 338ee36d17..3a2f71c141 100644--- a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx@@ -154,7 +154,7 @@ export const ModelSelect = ({[excludeKeys, filter, isOpen, modelTypes, models, relatedKeys, selectedBases]);- const selectedModel = useMemo(() => models.find((model) => model.key === value) ?? null, [models, value]);+ const selectedModel = useModelsSelector((snapshot) => (value ? (snapshot.modelsByKey.get(value) ?? null) : null));const hasMixedTypes = useMemo(() => new Set(candidates.map((model) => model.type)).size > 1, [candidates]);const scopeLabel =modelTypes.length === 1 ? getModelTypePluralLabel(modelTypes[0] ?? 'main').toLowerCase() : t('models.scopeModels');diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsxindex c9397e05c2..bc01197b65 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx@@ -7,7 +7,7 @@ import { isConvertibleToDiffusers } from '@features/models/core/baseIdentity';import { isLinkableType } from '@features/models/core/relationships';import { isAbsoluteModelPath, resolveModelAbsolutePath } from '@features/models/core/schemas';import { formatBytes, getModelSourceHref } from '@features/models/core/taxonomy';-import { useModelsSelector } from '@features/models/data/modelsStore';+import { useModelsSelector, type ModelsSnapshot } from '@features/models/data/modelsStore';import { useNotify } from '@features/models/ui/useModelsNotify';import { areArraysEqual } from '@platform/state/selectors';import { Button, IconButton, ConfirmDialog, MenuContent } from '@platform/ui';@@ -58,17 +58,17 @@ type ModelIdentityModel = Pick<| 'variant'>;-const findModel = (models: readonly ModelConfig[], modelKey: string): ModelConfig | undefined =>- models.find((candidate) => candidate.key === modelKey);+const findModel = (snapshot: ModelsSnapshot, modelKey: string): ModelConfig | undefined =>+ snapshot.modelsByKey.get(modelKey);-const selectModelShell = (models: readonly ModelConfig[], modelKey: string): ModelDetailShellModel | null => {- const model = findModel(models, modelKey);+const selectModelShell = (snapshot: ModelsSnapshot, modelKey: string): ModelDetailShellModel | null => {+ const model = findModel(snapshot, modelKey);return model ? { key: model.key, type: model.type } : null;};-const selectModelIdentity = (models: readonly ModelConfig[], modelKey: string): ModelIdentityModel | null => {- const model = findModel(models, modelKey);+const selectModelIdentity = (snapshot: ModelsSnapshot, modelKey: string): ModelIdentityModel | null => {+ const model = findModel(snapshot, modelKey);return model? {@@ -96,8 +96,8 @@ const selectModelIdentity = (models: readonly ModelConfig[], modelKey: string):: null;};-const selectDefaultSettingsModel = (models: readonly ModelConfig[], modelKey: string): DefaultSettingsModel | null => {- const model = findModel(models, modelKey);+const selectDefaultSettingsModel = (snapshot: ModelsSnapshot, modelKey: string): DefaultSettingsModel | null => {+ const model = findModel(snapshot, modelKey);// `base` is projected too: the FP8 storage default is unavailable for Z-Image.return model@@ -105,14 +105,14 @@ const selectDefaultSettingsModel = (models: readonly ModelConfig[], modelKey: st: null;};-const selectTriggerPhrasesModel = (models: readonly ModelConfig[], modelKey: string): TriggerPhrasesModel | null => {- const model = findModel(models, modelKey);+const selectTriggerPhrasesModel = (snapshot: ModelsSnapshot, modelKey: string): TriggerPhrasesModel | null => {+ const model = findModel(snapshot, modelKey);return model ? { key: model.key, trigger_phrases: model.trigger_phrases } : null;};-const selectCpuOnlyModel = (models: readonly ModelConfig[], modelKey: string): CpuOnlyModel | null => {- const model = findModel(models, modelKey);+const selectCpuOnlyModel = (snapshot: ModelsSnapshot, modelKey: string): CpuOnlyModel | null => {+ const model = findModel(snapshot, modelKey);return model ? { cpu_only: model.cpu_only, key: model.key, name: model.name, type: model.type } : null;};@@ -128,7 +128,7 @@ const areTriggerPhrasesModelsEqual = (left: TriggerPhrasesModel | null, right: T*/export const ModelDetail = ({ modelKey, onDeleted }: { modelKey: string; onDeleted: () => void }) => {const { t } = useTranslation();- const model = useModelsSelector((snapshot) => selectModelShell(snapshot.models, modelKey));+ const model = useModelsSelector((snapshot) => selectModelShell(snapshot, modelKey));if (!model) {return (@@ -188,7 +188,7 @@ const ModelIdentitySectionContainer = memo(function ModelIdentitySectionContainemodelKey: string;onDeleted: () => void;}) {- const model = useModelsSelector((snapshot) => selectModelIdentity(snapshot.models, modelKey));+ const model = useModelsSelector((snapshot) => selectModelIdentity(snapshot, modelKey));const isMissing = useModelsSelector((snapshot) => snapshot.missingModelKeys.has(modelKey));if (!model) {@@ -358,7 +358,7 @@ const DefaultSettingsSectionContainer = memo(function DefaultSettingsSectionCont}) {const notify = useNotify();const { t } = useTranslation();- const model = useModelsSelector((snapshot) => selectDefaultSettingsModel(snapshot.models, modelKey));+ const model = useModelsSelector((snapshot) => selectDefaultSettingsModel(snapshot, modelKey));if (!model || !supportsDefaultSettings(model)) {return null;@@ -376,7 +376,7 @@ const DefaultSettingsSectionContainer = memo(function DefaultSettingsSectionContconst CpuOnlySettingContainer = memo(function CpuOnlySettingContainer({ modelKey }: { modelKey: string }) {const notify = useNotify();const { t } = useTranslation();- const model = useModelsSelector((snapshot) => selectCpuOnlyModel(snapshot.models, modelKey));+ const model = useModelsSelector((snapshot) => selectCpuOnlyModel(snapshot, modelKey));if (!model || !supportsCpuOnlySetting(model)) {return null;@@ -396,7 +396,7 @@ const TriggerPhrasesEditorContainer = memo(function TriggerPhrasesEditorContaineconst { t } = useTranslation();const handleError = useCallback((message: string) => notify.error(t('models.triggerPhrases'), message), [notify, t]);const model = useModelsSelector(- (snapshot) => selectTriggerPhrasesModel(snapshot.models, modelKey),+ (snapshot) => selectTriggerPhrasesModel(snapshot, modelKey),areTriggerPhrasesModelsEqual);@@ -418,7 +418,7 @@ const RelatedModelsSectionContainer = memo(function RelatedModelsSectionContaineconst { t } = useTranslation();const model = useModelsSelector((snapshot) => {- const candidate = snapshot.models.find((model) => model.key === modelKey);+ const candidate = snapshot.modelsByKey.get(modelKey);return candidate ? { base: candidate.base, key: candidate.key, type: candidate.type } : null;},diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelSettingsMenuItems.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelSettingsMenuItems.tsxindex b2bee85b65..658d3e82e6 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelSettingsMenuItems.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelSettingsMenuItems.tsx@@ -29,7 +29,7 @@ export const ModelSettingsMenuItems = ({ modelKey }: { modelKey: string }) => {const fileInputRef = useRef<HTMLInputElement>(null);const { run } = useScopedAction();- const findModel = () => getModelsSnapshot().models.find((candidate) => candidate.key === modelKey);+ const findModel = () => getModelsSnapshot().modelsByKey.get(modelKey);const handleExport = async () => {const model = findModel();diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsxindex e063ad6367..cbb4fe4e32 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsx@@ -39,7 +39,7 @@ export const RelatedModelsSection = (props: RelatedModelsSectionProps) => (const RelatedModelsForModel = ({ model, onError }: RelatedModelsSectionProps) => {const { t } = useTranslation();- const models = useModelsSelector((snapshot) => snapshot.models);+ const modelsByKey = useModelsSelector((snapshot) => snapshot.modelsByKey);const relatedKeys = useRelatedModelKeys(model.key);const [isMutating, setIsMutating] = useState(false);@@ -58,11 +58,10 @@ const RelatedModelsForModel = ({ model, onError }: RelatedModelsSectionProps) =>};});- const relatedModels = useMemo(() => {- const byKey = new Map(models.map((candidate) => [candidate.key, candidate]));-- return (relatedKeys ?? []).map((key) => ({ key, model: byKey.get(key) ?? null }));- }, [models, relatedKeys]);+ const relatedModels = useMemo(+ () => (relatedKeys ?? []).map((key) => ({ key, model: modelsByKey.get(key) ?? null })),+ [modelsByKey, relatedKeys]+ );const excludeKeys = useMemo(() => new Set([model.key, ...(relatedKeys ?? [])]), [model.key, relatedKeys]);diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/ModelRowContextMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/ModelRowContextMenu.tsxindex bb6a8f61fd..fec6dbd1ce 100644--- a/invokeai/frontend/webv2/src/features/models/ui/library/ModelRowContextMenu.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/library/ModelRowContextMenu.tsx@@ -32,9 +32,7 @@ export const ModelRowContextMenu = ({const { t } = useTranslation();const { convert, reidentify, remove } = useModelActions();const [pendingConfirm, setPendingConfirm] = useState<{ kind: 'delete' | 'convert'; model: ModelConfig } | null>(null);- const model = useModelsSelector((snapshot) =>- target ? (snapshot.models.find((candidate) => candidate.key === target.modelKey) ?? null) : null- );+ const model = useModelsSelector((snapshot) => (target ? (snapshot.modelsByKey.get(target.modelKey) ?? null) : null));return (<>diff --git a/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.tsx b/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.tsxindex 4c45b86145..b3a08ebdc5 100644--- a/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/manager/DetailPane.tsx@@ -21,7 +21,7 @@ export const DetailPane = () => {(left, right) => left.activeModelKey === right.activeModelKey && left.activeTab === right.activeTab);const detailLabel = useModelsSelector(- (snapshot) => snapshot.models.find((model) => model.key === activeModelKey)?.name ?? t('models.details')+ (snapshot) => (activeModelKey ? snapshot.modelsByKey.get(activeModelKey)?.name : undefined) ?? t('models.details'));return (