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(ui): stop treating the any base as a universal wildcard
Josh Corbettbbe1b2c0f88a
diff --git a/invokeai/frontend/webv2/src/features/models/core/library.ts b/invokeai/frontend/webv2/src/features/models/core/library.tsindex 85c7ef6bbc..d71828be2b 100644--- a/invokeai/frontend/webv2/src/features/models/core/library.ts+++ b/invokeai/frontend/webv2/src/features/models/core/library.ts@@ -44,7 +44,7 @@ export interface ModelPickerOptions {excludeKeys?: ReadonlySet<string>;/** Extra predicate supplied by the owning form, e.g. base compatibility. */filter?: (model: ModelConfig) => boolean;- modelTypes: ModelTaxonomyType[];+ modelTypes: readonly ModelTaxonomyType[];/** Models linked to the current selection, floated to the top of their group. */relatedKeys?: ReadonlySet<string>;searchTerm: string;diff --git a/invokeai/frontend/webv2/src/features/models/core/relationships.test.ts b/invokeai/frontend/webv2/src/features/models/core/relationships.test.tsnew file mode 100644index 0000000000..832b5d4fc7--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/core/relationships.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from 'vitest';++import type { RelatableModel } from './relationships';+import type { ModelBase, ModelTaxonomyType } from './types';++import { isBaseCompatible, isLinkableType, LINKABLE_TYPES, NULL_BASE_ALLOWANCES } from './relationships';++const model = (base: ModelBase, type: ModelTaxonomyType = 'lora'): RelatableModel => ({ base, type });++describe('isBaseCompatible', () => {+ it('allows models from the same concrete base', () => {+ expect(isBaseCompatible(model('sdxl', 'main'), model('sdxl'))).toBe(true);+ expect(isBaseCompatible(model('flux', 'main'), model('flux', 'vae'))).toBe(true);+ });++ it('rejects differing concrete bases', () => {+ expect(isBaseCompatible(model('sdxl', 'main'), model('flux'))).toBe(false);+ });++ it('does not treat the null Any base as a universal wildcard', () => {+ expect(isBaseCompatible(model('any'), model('sdxl'))).toBe(false);+ expect(isBaseCompatible(model('sdxl'), model('any'))).toBe(false);+ expect(isBaseCompatible(model('any', 'vae'), model('sdxl', 'main'))).toBe(false);+ });++ it('never links external or unknown bases', () => {+ expect(isBaseCompatible(model('external', 'main'), model('sdxl', 'main'))).toBe(false);+ expect(isBaseCompatible(model('sdxl', 'main'), model('external', 'main'))).toBe(false);+ expect(isBaseCompatible(model('unknown'), model('sdxl'))).toBe(false);+ expect(isBaseCompatible(model('external', 'main'), model('external', 'main'))).toBe(false);+ expect(isBaseCompatible(model('unknown'), model('unknown'))).toBe(false);+ });++ it('allows curated any-based helpers with their consuming bases', () => {+ expect(isBaseCompatible(model('any', 't5_encoder'), model('flux', 'main'))).toBe(true);+ expect(isBaseCompatible(model('any', 't5_encoder'), model('sdxl', 'main'))).toBe(false);+ expect(isBaseCompatible(model('any', 'siglip'), model('flux', 'main'))).toBe(true);+ expect(isBaseCompatible(model('any', 'clip_vision'), model('sdxl', 'main'))).toBe(true);+ expect(isBaseCompatible(model('any', 'mistral_encoder'), model('flux2', 'main'))).toBe(true);+ });++ it('is symmetric for every curated entry', () => {+ for (const [type, bases] of Object.entries(NULL_BASE_ALLOWANCES)) {+ if (!bases) {+ continue;+ }++ const helper = model('any', type as ModelTaxonomyType);++ for (const base of ['sd-1', 'sdxl', 'flux', 'flux2', 'wan', 'qwen-image'] as const) {+ const host = model(base, 'main');++ expect(isBaseCompatible(helper, host)).toBe(bases.has(base));+ expect(isBaseCompatible(host, helper)).toBe(isBaseCompatible(helper, host));+ }+ }+ });++ it('never links two null-base models', () => {+ expect(isBaseCompatible(model('any', 't5_encoder'), model('any', 'clip_embed'))).toBe(false);+ });+});++describe('LINKABLE_TYPES', () => {+ it('includes every curated type', () => {+ for (const type of Object.keys(NULL_BASE_ALLOWANCES)) {+ expect(isLinkableType(type as ModelTaxonomyType)).toBe(true);+ }+ expect(LINKABLE_TYPES).toContain('main');+ expect(isLinkableType('onnx')).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/features/models/core/relationships.ts b/invokeai/frontend/webv2/src/features/models/core/relationships.tsnew file mode 100644index 0000000000..08fe33a048--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/core/relationships.ts@@ -0,0 +1,77 @@+import type { ModelBase, ModelConfig, ModelTaxonomyType } from './types';++/**+ * Compatibility rules for the bidirectional "related models" links. A link is+ * a curation hint ("this LoRA pairs well with this checkpoint"), so the rule+ * only permits pairs that can actually appear in one pipeline.+ */++/** The two fields the compatibility rule reads. */+export type RelatableModel = Pick<ModelConfig, 'base' | 'type'>;++/**+ * Bases that carry no architecture meaning. `any` is the backend's null value+ * for models with no base association (encoders, CLIP, Spandrel, ...), NOT a+ * universal-compatibility wildcard; `external` and `unknown` say nothing+ * about what a model pairs with.+ */+export const NULL_BASES: ReadonlySet<string> = new Set(['any', 'external', 'unknown']);++/**+ * Curated allowances: `any`-based helper types mapped to the concrete bases+ * whose pipelines actually consume them, per the backend model loaders.+ */+export const NULL_BASE_ALLOWANCES: Readonly<Partial<Record<ModelTaxonomyType, ReadonlySet<ModelBase>>>> = {+ /** CLIP text encoders (flux_model_loader, sd3_model_loader). */+ clip_embed: new Set(['flux', 'sd-3']),+ /** IP-adapter image encoders (ip_adapter config bases). */+ clip_vision: new Set(['flux', 'sd-1', 'sd-2', 'sdxl']),+ /** PiD decoder captioning (pid_decoder config bases; prototype). */+ gemma2_encoder: new Set(['flux', 'flux2', 'qwen-image', 'sd-3', 'sdxl']),+ /** FLUX.2 dev text encoder (flux2_dev_model_loader). */+ mistral_encoder: new Set(['flux2']),+ qwen3_encoder: new Set(['anima', 'flux2', 'z-image']),+ qwen3_vl_encoder: new Set(['krea-2']),+ qwen_vl_encoder: new Set(['qwen-image']),+ /** FLUX Redux image encoder (flux_redux). */+ siglip: new Set(['flux']),+ t5_encoder: new Set(['flux', 'sd-3']),+ wan_t5_encoder: new Set(['wan']),+};++/**+ * Types offered when linking related models. The concrete-based helper types,+ * plus every `any`-based type with a curated allowance.+ */+export const LINKABLE_TYPES: readonly ModelTaxonomyType[] = [+ 'main',+ 'lora',+ 'embedding',+ 'vae',+ 'controlnet',+ 't2i_adapter',+ 'ip_adapter',+ ...(Object.keys(NULL_BASE_ALLOWANCES) as ModelTaxonomyType[]),+];++const LINKABLE_TYPE_SET: ReadonlySet<ModelTaxonomyType> = new Set(LINKABLE_TYPES);++export const isLinkableType = (type: ModelTaxonomyType): boolean => LINKABLE_TYPE_SET.has(type);++const isAllowedHelperFor = (helper: RelatableModel, host: RelatableModel): boolean =>+ helper.base === 'any' &&+ !NULL_BASES.has(String(host.base)) &&+ (NULL_BASE_ALLOWANCES[helper.type]?.has(host.base) ?? false);++/**+ * Symmetric base-compatibility for related-model links: concrete bases must+ * match exactly; a null base never wildcards — an `any`-based model links only+ * to concrete bases its type has a curated allowance for.+ */+export const isBaseCompatible = (a: RelatableModel, b: RelatableModel): boolean => {+ if (!NULL_BASES.has(String(a.base)) && !NULL_BASES.has(String(b.base))) {+ return a.base === b.base;+ }++ return isAllowedHelperFor(a, b) || isAllowedHelperFor(b, a);+};diff --git a/invokeai/frontend/webv2/src/features/models/core/types.ts b/invokeai/frontend/webv2/src/features/models/core/types.tsindex 8e53af1402..9b62e905e8 100644--- a/invokeai/frontend/webv2/src/features/models/core/types.ts+++ b/invokeai/frontend/webv2/src/features/models/core/types.ts@@ -45,6 +45,7 @@ export type ModelTaxonomyType =| 'qwen_vl_encoder'| 'qwen3_vl_encoder'| 'wan_t5_encoder'+ | 'mistral_encoder'| 'gemma2_encoder'| 'pid_decoder'| 'siglip'diff --git a/invokeai/frontend/webv2/src/features/models/data/relationshipsStore.test.ts b/invokeai/frontend/webv2/src/features/models/data/relationshipsStore.test.tsnew file mode 100644index 0000000000..7c871af4c5--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/data/relationshipsStore.test.ts@@ -0,0 +1,93 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const api = vi.hoisted(() => ({+ addModelRelationship: vi.fn(),+ getRelatedModelKeys: vi.fn(),+ removeModelRelationship: vi.fn(),+}));++vi.mock('./api', () => api);++describe('relationships store', () => {+ beforeEach(() => {+ vi.resetModules();+ api.addModelRelationship.mockReset().mockResolvedValue(undefined);+ api.getRelatedModelKeys.mockReset();+ api.removeModelRelationship.mockReset().mockResolvedValue(undefined);+ });++ it('caches per key and dedupes concurrent ensures', async () => {+ api.getRelatedModelKeys.mockResolvedValue(['b']);+ const store = await import('./relationshipsStore');++ const first = store.ensureRelatedModelKeysLoaded('a');+ expect(store.ensureRelatedModelKeysLoaded('a')).toBe(first);+ await first;++ await store.ensureRelatedModelKeysLoaded('a');+ expect(api.getRelatedModelKeys).toHaveBeenCalledTimes(1);+ expect(store.getRelationshipsSnapshot().relatedKeysByModelKey).toEqual({ a: ['b'] });+ });++ it('refresh revalidates a cached entry and rejects with an empty fallback on first failure', async () => {+ api.getRelatedModelKeys.mockRejectedValueOnce(new Error('outage')).mockResolvedValueOnce(['c']);+ const store = await import('./relationshipsStore');++ await expect(store.refreshRelatedModelKeys('a')).rejects.toThrow('outage');+ expect(store.getRelationshipsSnapshot().relatedKeysByModelKey).toEqual({ a: [] });++ await store.refreshRelatedModelKeys('a');+ expect(store.getRelationshipsSnapshot().relatedKeysByModelKey).toEqual({ a: ['c'] });+ });++ it('link patches both cached directions and leaves uncached entries absent', async () => {+ const store = await import('./relationshipsStore');+ store.setRelationshipsSnapshotForTests({ relatedKeysByModelKey: { a: [], b: [] } });++ await store.linkModels('a', 'b');+ expect(api.addModelRelationship).toHaveBeenCalledWith('a', 'b', expect.anything());+ expect(store.getRelationshipsSnapshot().relatedKeysByModelKey).toEqual({ a: ['b'], b: ['a'] });++ await store.linkModels('a', 'uncached');+ expect(store.getRelationshipsSnapshot().relatedKeysByModelKey).toEqual({ a: ['b', 'uncached'], b: ['a'] });+ });++ it('unlink removes both cached directions', async () => {+ const store = await import('./relationshipsStore');+ store.setRelationshipsSnapshotForTests({ relatedKeysByModelKey: { a: ['b'], b: ['a', 'c'] } });++ await store.unlinkModels('a', 'b');+ expect(api.removeModelRelationship).toHaveBeenCalledWith('a', 'b', expect.anything());+ expect(store.getRelationshipsSnapshot().relatedKeysByModelKey).toEqual({ a: [], b: ['c'] });+ });++ it('scrubs deleted models from every entry', async () => {+ const store = await import('./relationshipsStore');+ store.setRelationshipsSnapshotForTests({ relatedKeysByModelKey: { a: ['b', 'c'], b: ['a'], c: ['a'] } });++ store.removeModelsFromRelationships(['b']);+ expect(store.getRelationshipsSnapshot().relatedKeysByModelKey).toEqual({ a: ['c'], c: ['a'] });+ });++ it('clears the cache and inflight requests on account switch', async () => {+ const account = await import('@platform/state/accountLifecycle');+ account.accountLifecycle.activate('user-a');+ const store = await import('./relationshipsStore');+ let resolveA: ((keys: string[]) => void) | undefined;+ api.getRelatedModelKeys.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveA = resolve;+ })+ );++ const userAFetch = store.ensureRelatedModelKeysLoaded('a');++ account.accountLifecycle.invalidate();+ account.accountLifecycle.activate('user-b');++ resolveA?.(['stale']);+ await userAFetch;++ expect(store.getRelationshipsSnapshot().relatedKeysByModelKey).toEqual({});+ });+});diff --git a/invokeai/frontend/webv2/src/features/models/data/relationshipsStore.ts b/invokeai/frontend/webv2/src/features/models/data/relationshipsStore.tsnew file mode 100644index 0000000000..beab1961ab--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/data/relationshipsStore.ts@@ -0,0 +1,169 @@+import {+ captureAccountScope,+ isAccountScopeCurrent,+ registerAccountOwnedResource,+} from '@platform/state/accountLifecycle';+import { createExternalStore } from '@platform/state/externalStore';+import { areArraysEqual } from '@platform/state/selectors';++import { addModelRelationship, getRelatedModelKeys, removeModelRelationship } from './api';++/**+ * Shared cache of bidirectional "related model" links, keyed by model key.+ * One store keeps the detail pane and every open picker consistent: link and+ * unlink patch both cached directions instead of refetching.+ *+ * The backend's batch endpoint (`POST /model_relationships/batch`) is+ * deliberately unused — it returns a flat de-duplicated union across the input+ * keys, which cannot populate a per-key cache. Parallel single-key fetches via+ * `ensureManyRelatedModelKeysLoaded` provide batch loading with attributable+ * results.+ */++export interface ModelRelationshipsSnapshot {+ /** Related keys per model key; a missing entry means "not fetched yet". */+ relatedKeysByModelKey: Readonly<Record<string, readonly string[]>>;+}++const EMPTY_RELATIONSHIPS_SNAPSHOT: ModelRelationshipsSnapshot = { relatedKeysByModelKey: {} };+const store = createExternalStore<ModelRelationshipsSnapshot>(EMPTY_RELATIONSHIPS_SNAPSHOT);++const inflightByKey = new Map<string, Promise<void>>();++registerAccountOwnedResource({+ clear: () => {+ inflightByKey.clear();+ store.setSnapshot(EMPTY_RELATIONSHIPS_SNAPSHOT);+ },+ name: 'model-relationships',+});++const setEntry = (modelKey: string, keys: readonly string[]): void => {+ store.patchSnapshot({+ relatedKeysByModelKey: { ...store.getSnapshot().relatedKeysByModelKey, [modelKey]: keys },+ });+};++const fetchRelatedKeys = (modelKey: string): Promise<void> => {+ const existing = inflightByKey.get(modelKey);++ if (existing) {+ return existing;+ }++ const owner = captureAccountScope();+ const fetch = getRelatedModelKeys(modelKey, owner.signal)+ .then((keys) => {+ if (isAccountScopeCurrent(owner)) {+ setEntry(modelKey, keys);+ }+ })+ .catch((error: unknown) => {+ // Leave an empty entry so consumers stop showing a spinner, but still+ // reject so callers that care (the detail pane) can surface the error.+ if (isAccountScopeCurrent(owner) && store.getSnapshot().relatedKeysByModelKey[modelKey] === undefined) {+ setEntry(modelKey, []);+ }+ throw error;+ })+ .finally(() => {+ if (inflightByKey.get(modelKey) === fetch) {+ inflightByKey.delete(modelKey);+ }+ });++ inflightByKey.set(modelKey, fetch);+ return fetch;+};++/** Fetch once per key; concurrent callers share one request. Cache-first. */+export const ensureRelatedModelKeysLoaded = (modelKey: string): Promise<void> => {+ if (store.getSnapshot().relatedKeysByModelKey[modelKey] !== undefined) {+ return inflightByKey.get(modelKey) ?? Promise.resolve();+ }++ return fetchRelatedKeys(modelKey);+};++/** Stale-while-revalidate: any cached entry keeps rendering while it refetches. */+export const refreshRelatedModelKeys = (modelKey: string): Promise<void> => fetchRelatedKeys(modelKey);++/** Parallel per-key ensure for multi-model surfaces; shares the inflight map. */+export const ensureManyRelatedModelKeysLoaded = async (modelKeys: readonly string[]): Promise<void> => {+ await Promise.all(modelKeys.map((key) => ensureRelatedModelKeysLoaded(key)));+};++type EntryPatch = (entry: readonly string[], otherKey: string) => readonly string[];++/** Links are bidirectional: apply the patch to both cached directions. */+const patchBothDirections = (modelKey: string, otherKey: string, patch: EntryPatch): void => {+ const next = { ...store.getSnapshot().relatedKeysByModelKey };+ let changed = false;++ for (const [key, other] of [+ [modelKey, otherKey],+ [otherKey, modelKey],+ ] as const) {+ const entry = next[key];++ if (entry !== undefined) {+ next[key] = patch(entry, other);+ changed = true;+ }+ }++ if (changed) {+ store.patchSnapshot({ relatedKeysByModelKey: next });+ }+};++export const linkModels = async (modelKey: string, otherKey: string): Promise<void> => {+ const owner = captureAccountScope();++ await addModelRelationship(modelKey, otherKey, owner.signal);++ if (isAccountScopeCurrent(owner)) {+ patchBothDirections(modelKey, otherKey, (entry, other) => (entry.includes(other) ? entry : [...entry, other]));+ }+};++export const unlinkModels = async (modelKey: string, otherKey: string): Promise<void> => {+ const owner = captureAccountScope();++ await removeModelRelationship(modelKey, otherKey, owner.signal);++ if (isAccountScopeCurrent(owner)) {+ patchBothDirections(modelKey, otherKey, (entry, other) => entry.filter((key) => key !== other));+ }+};++/** Drop deleted models' entries and scrub their keys from the remaining ones. */+export const removeModelsFromRelationships = (keys: readonly string[]): void => {+ const removed = new Set(keys);+ const next: Record<string, readonly string[]> = {};++ for (const [key, entry] of Object.entries(store.getSnapshot().relatedKeysByModelKey)) {+ if (!removed.has(key)) {+ next[key] = entry.some((related) => removed.has(related))+ ? entry.filter((related) => !removed.has(related))+ : entry;+ }+ }++ store.patchSnapshot({ relatedKeysByModelKey: next });+};++export const getRelationshipsSnapshot = (): ModelRelationshipsSnapshot => store.getSnapshot();++export const useRelationshipsSelector = store.useSelector;++/** Related keys for one model; `null` means not fetched yet (or no model). */+export const useRelatedModelKeys = (modelKey: string | null): readonly string[] | null =>+ store.useSelector(+ (snapshot) => (modelKey === null ? null : (snapshot.relatedKeysByModelKey[modelKey] ?? null)),+ (left, right) => (left === null || right === null ? left === right : areArraysEqual(left, right))+ );++export const setRelationshipsSnapshotForTests = (next: Partial<ModelRelationshipsSnapshot>): void => {+ store.patchSnapshot(next);+};diff --git a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsxindex f1809d1748..40f76650b1 100644--- a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx@@ -6,8 +6,9 @@ import { Badge, Box, HStack, Icon, Image, Popover, Portal, Spacer, Stack, Text }import { getModelBaseColorPalette, getModelBaseLabel, getModelBaseLongLabel } from '@features/models/core/baseIdentity';import { getModelPickerGroups } from '@features/models/core/library';import { formatBytes, getModelTypeLabel, getModelTypePluralLabel } from '@features/models/core/taxonomy';-import { getModelImageUrl, getRelatedModelKeys } from '@features/models/data/api';+import { getModelImageUrl } from '@features/models/data/api';import { ensureModelsLoaded, useModelsSelector } from '@features/models/data/modelsStore';+import { ensureRelatedModelKeysLoaded, useRelatedModelKeys } from '@features/models/data/relationshipsStore';import { useModelsUi } from '@features/models/ui/ModelsUiContext';import { setPickerCompactView, useModelsUiSelector } from '@features/models/ui/uiStore';import { useMountEffect } from '@platform/react/useMountEffect';@@ -54,7 +55,7 @@ export const ModelSelect = ({id?: string;invalid?: boolean;isClearable?: boolean;- modelTypes: ModelTaxonomyType[];+ modelTypes: readonly ModelTaxonomyType[];onChange: (model: ModelConfig | null) => void;placeholder?: string;showManagerButton?: boolean;@@ -71,12 +72,24 @@ export const ModelSelect = ({const pickerId = id ?? `models:${modelTypes.join('+')}`;const isCompact = useModelsUiSelector((snapshot) => snapshot.pickerCompactViews[pickerId] ?? false);- const relatedKeys = useRelatedModelKeys(isOpen ? value : null);+ const relatedKeyList = useRelatedModelKeys(isOpen ? value : null);+ const relatedKeys = useMemo<ReadonlySet<string>>(+ () => (relatedKeyList ? new Set(relatedKeyList) : EMPTY_KEYS),+ [relatedKeyList]+ );useMountEffect(() => {void ensureModelsLoaded();});+ useEffect(() => {+ if (isOpen && value) {+ // A missing relationship list is not worth surfacing; the picker just+ // loses its pinning.+ ensureRelatedModelKeysLoaded(value).catch(() => {});+ }+ }, [isOpen, value]);+if (disabled !== lastDisabled) {setLastDisabled(disabled);@@ -329,34 +342,6 @@ const matchesModel = (model: ModelConfig, searchTerm: string): boolean => {return terms.every((term) => haystack.includes(term));};-const useRelatedModelKeys = (modelKey: string | null): ReadonlySet<string> => {- const [relatedKeys, setRelatedKeys] = useState<ReadonlySet<string>>(EMPTY_KEYS);-- useEffect(() => {- if (!modelKey) {- setRelatedKeys(EMPTY_KEYS);- return;- }-- const controller = new AbortController();-- getRelatedModelKeys(modelKey, controller.signal)- .then((keys) => {- if (!controller.signal.aborted) {- setRelatedKeys(new Set(keys));- }- })- .catch(() => {- // A missing relationship list is not worth surfacing; the picker just- // loses its pinning.- });-- return () => controller.abort();- }, [modelKey]);-- return relatedKeys;-};-const CompactViewToggle = ({ isCompact, pickerId }: { isCompact: boolean; pickerId: string }) => {const label = isCompact ? 'Full rows' : 'Compact rows';const handleClick = useCallback(() => setPickerCompactView(pickerId, !isCompact), [isCompact, pickerId]);diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsxindex f42c5bd204..045843ce97 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx@@ -3,6 +3,7 @@ import type { ModelConfig } from '@features/models/core/types';import { DataList, HStack, Icon, Menu, Portal, Separator, Stack, Text } from '@chakra-ui/react';import { isConvertibleToDiffusers } from '@features/models/core/baseIdentity';+import { isLinkableType } from '@features/models/core/relationships';import { formatBytes } from '@features/models/core/taxonomy';import { useModelsSelector } from '@features/models/data/modelsStore';import { useNotify } from '@features/models/ui/useModelsNotify';@@ -23,7 +24,6 @@ import { useModelActions } from './useModelActions';import { supportsVaeCpuOnlySetting, VaeCpuOnlySetting } from './VaeCpuOnlySetting';const TRIGGER_PHRASE_TYPES = new Set(['main', 'lora', 'embedding']);-const RELATED_MODEL_TYPES = new Set(['main', 'lora']);const EMPTY_TRIGGER_PHRASES: readonly string[] = [];type ModelDetailShellModel = Pick<ModelConfig, 'key' | 'type'>;@@ -153,7 +153,7 @@ export const ModelDetail = ({</>) : null}- {RELATED_MODEL_TYPES.has(model.type) ? (+ {isLinkableType(model.type) ? (<><Separator borderColor="border.subtle" /><RelatedModelsSectionContainer modelKey={model.key} />@@ -415,9 +415,9 @@ const RelatedModelsSectionContainer = memo(function RelatedModelsSectionContaine(snapshot) => {const candidate = snapshot.models.find((model) => model.key === modelKey);- return candidate ? { base: candidate.base, key: candidate.key } : null;+ return candidate ? { base: candidate.base, key: candidate.key, type: candidate.type } : null;},- (left, right) => left?.key === right?.key && left?.base === right?.base+ (left, right) => left?.key === right?.key && left?.base === right?.base && left?.type === right?.type);const handleSectionError = useCallback((message: string) => notify.error(t('models.modelManager'), message),diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.browser.test.tsxnew file mode 100644index 0000000000..50f98c5cb4--- /dev/null+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.browser.test.tsx@@ -0,0 +1,126 @@+import type { ModelConfig } from '@features/models';++import { ChakraProvider } from '@chakra-ui/react';+import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';+import { setRelationshipsSnapshotForTests } from '@features/models/data/relationshipsStore';+import { ModelsUiProvider } from '@features/models/ui/ModelsUiContext';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { RelatedModelsSection } from './RelatedModelsSection';++const api = vi.hoisted(() => ({+ addModelRelationship: vi.fn(),+ getRelatedModelKeys: vi.fn(),+ removeModelRelationship: vi.fn(),+}));++vi.mock('@features/models/data/api', async (importOriginal) => ({+ ...((await importOriginal()) as Record<string, unknown>),+ ...api,+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const createModel = (overrides: Partial<ModelConfig>): ModelConfig =>+ ({+ base: 'sdxl',+ description: null,+ file_size: 1024,+ format: 'checkpoint',+ hash: 'hash',+ key: 'key',+ name: 'Model',+ source: 'model.safetensors',+ type: 'main',+ ...overrides,+ }) as ModelConfig;++const fluxMain = createModel({ base: 'flux', key: 'flux-main', name: 'FLUX Dev', type: 'main' });+const fluxLora = createModel({ base: 'flux', key: 'flux-lora', name: 'FLUX LoRA', type: 'lora' });+const sdxlLora = createModel({ base: 'sdxl', key: 'sdxl-lora', name: 'SDXL LoRA', type: 'lora' });+const t5Encoder = createModel({ base: 'any', key: 't5-xxl', name: 'T5 XXL', type: 't5_encoder' });+const externalMain = createModel({ base: 'external', key: 'gpt-image', name: 'GPT Image', type: 'main' });++const MODELS_UI_ADAPTER = { enableModelDescriptions: false, managerProjectId: null };+const SECTION_MODEL = { base: 'flux', key: 'flux-main', type: 'main' } as const;++describe('RelatedModelsSection', () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ api.addModelRelationship.mockReset().mockResolvedValue(undefined);+ api.getRelatedModelKeys.mockReset().mockResolvedValue([]);+ api.removeModelRelationship.mockReset().mockResolvedValue(undefined);+ accountLifecycle.activate('related-models', ':user:related-models');+ setModelsSnapshotForTests({+ error: null,+ models: [fluxMain, fluxLora, sdxlLora, t5Encoder, externalMain],+ status: 'loaded',+ });+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ document.querySelectorAll('[data-scope="popover"]').forEach((element) => element.remove());+ setModelsSnapshotForTests({ error: null, models: [], status: 'idle' });+ setRelationshipsSnapshotForTests({ relatedKeysByModelKey: {} });+ });++ const renderSection = async () => {+ await act(() => {+ root.render(+ <ChakraProvider value={system}>+ <ModelsUiProvider adapter={MODELS_UI_ADAPTER}>+ <RelatedModelsSection model={SECTION_MODEL} onError={vi.fn()} />+ </ModelsUiProvider>+ </ChakraProvider>+ );+ });++ await act(() => host.querySelector<HTMLButtonElement>('[aria-haspopup="listbox"]')?.click());+ await expect.poll(() => document.querySelectorAll('[role="option"]').length).toBeGreaterThan(0);+ };++ const optionTexts = (): string[] =>+ [...document.querySelectorAll('[role="option"]')].map((option) => option.textContent ?? '');++ it('offers only base-compatible candidates for a flux main', async () => {+ await renderSection();++ const options = optionTexts().join(' ');++ expect(options).toContain('FLUX LoRA');+ // T5 has base `any` but a curated allowance for flux.+ expect(options).toContain('T5 XXL');+ expect(options).not.toContain('SDXL LoRA');+ expect(options).not.toContain('GPT Image');+ // The subject model never offers itself.+ expect(options).not.toContain('FLUX Dev');+ });++ it('links a model and renders it without refetching', async () => {+ await renderSection();++ const t5Option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find((option) =>+ option.textContent?.includes('T5 XXL')+ );++ expect(t5Option).toBeDefined();+ await act(() => t5Option?.click());++ expect(api.addModelRelationship).toHaveBeenCalledWith('flux-main', 't5-xxl', expect.anything());+ // The shared store patch renders the row; no second fetch happens.+ await expect.poll(() => host.textContent).toContain('T5 XXL');+ expect(api.getRelatedModelKeys).toHaveBeenCalledTimes(1);+ });+});diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsxindex ed573e8d01..4105749826 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/RelatedModelsSection.tsx@@ -1,35 +1,26 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { ModelConfig, ModelTaxonomyType } from '@features/models/core/types';+import type { ModelConfig } from '@features/models/core/types';import { Badge, Icon, Spinner, Stack, Text } from '@chakra-ui/react';import { getModelBaseColorPalette, getModelBaseLabel } from '@features/models/core/baseIdentity';+import { isBaseCompatible, LINKABLE_TYPES } from '@features/models/core/relationships';import { getModelTypeLabel } from '@features/models/core/taxonomy';-import { addModelRelationship, getRelatedModelKeys, removeModelRelationship } from '@features/models/data/api';import { useModelsSelector } from '@features/models/data/modelsStore';+import {+ linkModels,+ refreshRelatedModelKeys,+ unlinkModels,+ useRelatedModelKeys,+} from '@features/models/data/relationshipsStore';import { ModelSelect } from '@features/models/ui/components';import { SourceListItem } from '@features/models/ui/shared/SourceListItem';import { useMountEffect } from '@platform/react/useMountEffect';-import {- assertAccountScopeCurrent,- captureAccountScope,- isAccountScopeCurrent,-} from '@platform/state/accountLifecycle';+import { isAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';import { IconButton, FieldLabel, Tooltip } from '@platform/ui';import { Link2OffIcon } from 'lucide-react';import { useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-/** Types offered when linking related models, grouped in one picker. */-const LINKABLE_TYPES: ModelTaxonomyType[] = [- 'main',- 'lora',- 'embedding',- 'vae',- 'controlnet',- 't2i_adapter',- 'ip_adapter',-];-/*** Bidirectional "related models" links — e.g. attach the LoRAs and VAE that* pair well with a checkpoint so other surfaces can suggest them together.@@ -37,7 +28,7 @@ const LINKABLE_TYPES: ModelTaxonomyType[] = [* once; linked models render as rows with an unlink action.*/interface RelatedModelsSectionProps {- model: Pick<ModelConfig, 'base' | 'key'>;+ model: Pick<ModelConfig, 'base' | 'key' | 'type'>;onError: (message: string) => void;}@@ -48,29 +39,17 @@ export const RelatedModelsSection = (props: RelatedModelsSectionProps) => (const RelatedModelsForModel = ({ model, onError }: RelatedModelsSectionProps) => {const { t } = useTranslation();const models = useModelsSelector((snapshot) => snapshot.models);- const [relatedKeys, setRelatedKeys] = useState<string[] | null>(null);+ const relatedKeys = useRelatedModelKeys(model.key);const [isMutating, setIsMutating] = useState(false);useMountEffect(() => {const owner = captureAccountScope();- let isMounted = true;-- getRelatedModelKeys(model.key, owner.signal)- .then((keys) => {- if (isMounted && isAccountScopeCurrent(owner)) {- setRelatedKeys(keys);- }- })- .catch((error: unknown) => {- if (isMounted && isAccountScopeCurrent(owner)) {- setRelatedKeys([]);- onError(error instanceof Error ? error.message : t('models.failedToLoadRelatedModels'));- }- });-- return () => {- isMounted = false;- };++ refreshRelatedModelKeys(model.key).catch((error: unknown) => {+ if (isAccountScopeCurrent(owner)) {+ onError(error instanceof Error ? error.message : t('models.failedToLoadRelatedModels'));+ }+ });});const relatedModels = useMemo(() => {@@ -91,10 +70,7 @@ const RelatedModelsForModel = ({ model, onError }: RelatedModelsSectionProps) =>setIsMutating(true);try {- await addModelRelationship(model.key, target.key, owner.signal);-- assertAccountScopeCurrent(owner);- setRelatedKeys((current) => [...(current ?? []), target.key]);+ await linkModels(model.key, target.key);} catch (error) {if (!isAccountScopeCurrent(owner)) {return;@@ -114,10 +90,7 @@ const RelatedModelsForModel = ({ model, onError }: RelatedModelsSectionProps) =>setIsMutating(true);try {- await removeModelRelationship(model.key, key, owner.signal);-- assertAccountScopeCurrent(owner);- setRelatedKeys((current) => (current ?? []).filter((existing) => existing !== key));+ await unlinkModels(model.key, key);} catch (error) {if (!isAccountScopeCurrent(owner)) {return;@@ -141,7 +114,7 @@ const RelatedModelsForModel = ({ model, onError }: RelatedModelsSectionProps) =></Stack><ModelSelectexcludeKeys={excludeKeys}- filter={(candidate) => candidate.base === model.base || candidate.base === 'any' || model.base === 'any'}+ filter={(candidate) => isBaseCompatible(model, candidate)}modelTypes={LINKABLE_TYPES}placeholder={t('models.searchCompatibleToLink')}showManagerButton={false}diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.ts b/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.tsindex f8a6a86fa1..3e16d06319 100644--- a/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.ts+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/useModelActions.ts@@ -2,6 +2,7 @@ import type { ModelConfig } from '@features/models/core/types';import { convertModelToDiffusers, deleteModel, reidentifyModel } from '@features/models/data/api';import { removeModelsFromStore, replaceModelInStore } from '@features/models/data/modelsStore';+import { removeModelsFromRelationships } from '@features/models/data/relationshipsStore';import { pruneModelsUiKeys } from '@features/models/ui/uiStore';import { useNotify } from '@features/models/ui/useModelsNotify';import {@@ -30,6 +31,7 @@ export const useModelActions = () => {assertAccountScopeCurrent(owner);removeModelsFromStore([model.key]);+ removeModelsFromRelationships([model.key]);pruneModelsUiKeys([model.key]);notify.success('Model deleted', model.name);} catch (error) {diff --git a/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx b/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsxindex e2163bb2ab..d8e28b63dc 100644--- a/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx@@ -3,6 +3,7 @@ import { Box, Flex, HStack, Icon, Separator, Text } from '@chakra-ui/react';import { collectBases, collectTypes } from '@features/models/core/library';import { bulkDeleteModels } from '@features/models/data/api';import { refreshModels, removeModelsFromStore, useModelsSelector } from '@features/models/data/modelsStore';+import { removeModelsFromRelationships } from '@features/models/data/relationshipsStore';import { MaintenanceMenu } from '@features/models/ui/library/MaintenanceMenu';import { ModelFilterBar } from '@features/models/ui/library/ModelFilterBar';import { ModelLibraryList } from '@features/models/ui/library/ModelLibraryList';@@ -59,6 +60,7 @@ export const LibraryColumn = () => {assertAccountScopeCurrent(owner);removeModelsFromStore(result.deleted);+ removeModelsFromRelationships(result.deleted);pruneModelsUiKeys(result.deleted);updateModelsUi({ selectedKeys: new Set(result.failed.map((failure) => failure.key)) });