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.

refactor(ui): store external provider configs

Josh Corbettacdb14b1e282
diff --git a/invokeai/frontend/webv2/src/features/models/data/externalProvidersStore.test.ts b/invokeai/frontend/webv2/src/features/models/data/externalProvidersStore.test.ts
new file mode 100644
index 0000000000..55cbe47f41
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/data/externalProvidersStore.test.ts
@@ -0,0 +1,76 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const api = vi.hoisted(() => ({
+ getExternalProviderConfigs: vi.fn(),
+ resetExternalProviderConfig: vi.fn(),
+ setExternalProviderConfig: vi.fn(),
+}));
+
+vi.mock('./api', () => api);
+
+const config = (providerId: string, configured = false) => ({
+ api_key_configured: configured,
+ base_url: null,
+ provider_id: providerId,
+});
+
+describe('external providers store', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ api.getExternalProviderConfigs.mockReset();
+ api.resetExternalProviderConfig.mockReset();
+ api.setExternalProviderConfig.mockReset();
+ });
+
+ it('shares one request and retries after an initial failure', async () => {
+ api.getExternalProviderConfigs
+ .mockRejectedValueOnce(new Error('temporary outage'))
+ .mockResolvedValueOnce([config('openai')]);
+ const store = await import('./externalProvidersStore');
+
+ const first = store.ensureExternalProvidersLoaded();
+ expect(store.ensureExternalProvidersLoaded()).toBe(first);
+ await expect(first).rejects.toThrow('temporary outage');
+ expect(store.getExternalProvidersSnapshot()).toMatchObject({ error: 'temporary outage', status: 'error' });
+
+ await store.ensureExternalProvidersLoaded();
+ expect(store.getExternalProvidersSnapshot()).toMatchObject({
+ configs: [config('openai')],
+ error: null,
+ status: 'loaded',
+ });
+ expect(api.getExternalProviderConfigs).toHaveBeenCalledTimes(2);
+ });
+
+ it('patches the snapshot when a config is saved or cleared', async () => {
+ api.getExternalProviderConfigs.mockResolvedValue([config('openai'), config('gemini')]);
+ api.setExternalProviderConfig.mockResolvedValue(config('openai', true));
+ api.resetExternalProviderConfig.mockResolvedValue(config('openai'));
+ const store = await import('./externalProvidersStore');
+
+ await store.ensureExternalProvidersLoaded();
+
+ await expect(store.saveExternalProviderConfig('openai', { api_key: 'sk-test' })).resolves.toMatchObject({
+ api_key_configured: true,
+ });
+ expect(store.getExternalProvidersSnapshot().configs).toEqual([config('openai', true), config('gemini')]);
+
+ await store.clearExternalProviderConfig('openai');
+ expect(store.getExternalProvidersSnapshot().configs).toEqual([config('openai'), config('gemini')]);
+ });
+
+ it('clears the cache on account switch', async () => {
+ const account = await import('@platform/state/accountLifecycle');
+ account.accountLifecycle.activate('user-a');
+ api.getExternalProviderConfigs.mockResolvedValue([config('openai')]);
+ const store = await import('./externalProvidersStore');
+
+ await store.ensureExternalProvidersLoaded();
+ expect(store.getExternalProvidersSnapshot().status).toBe('loaded');
+
+ account.accountLifecycle.invalidate();
+ account.accountLifecycle.activate('user-b');
+
+ expect(store.getExternalProvidersSnapshot()).toMatchObject({ configs: null, status: 'idle' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/models/data/externalProvidersStore.ts b/invokeai/frontend/webv2/src/features/models/data/externalProvidersStore.ts
new file mode 100644
index 0000000000..6f51a299c5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/data/externalProvidersStore.ts
@@ -0,0 +1,131 @@
+import {
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+} from '@platform/state/accountLifecycle';
+import { createExternalStore } from '@platform/state/externalStore';
+
+import {
+ getExternalProviderConfigs,
+ resetExternalProviderConfig,
+ setExternalProviderConfig,
+ type ExternalProviderConfig,
+} from './api';
+
+/**
+ * Shared cache of external image-provider configs. One store keeps every
+ * consumer consistent: saving a key on the Keys tab immediately flips the
+ * Configure/Installed affordances in the add-models starter list, with no
+ * remount or refetch.
+ */
+
+export interface ExternalProvidersSnapshot {
+ /** null = not fetched yet. */
+ configs: ExternalProviderConfig[] | null;
+ status: 'idle' | 'loading' | 'loaded' | 'error';
+ error: string | null;
+}
+
+const EMPTY_EXTERNAL_PROVIDERS_SNAPSHOT: ExternalProvidersSnapshot = { configs: null, error: null, status: 'idle' };
+const store = createExternalStore<ExternalProvidersSnapshot>(EMPTY_EXTERNAL_PROVIDERS_SNAPSHOT);
+
+let inflightRefresh: Promise<void> | null = null;
+
+registerAccountOwnedResource({
+ clear: () => {
+ inflightRefresh = null;
+ store.setSnapshot(EMPTY_EXTERNAL_PROVIDERS_SNAPSHOT);
+ },
+ name: 'external-providers',
+});
+
+/** Re-fetch the configs; rejects on failure (after recording it) so callers can toast. */
+export const refreshExternalProviders = (): Promise<void> => {
+ if (inflightRefresh) {
+ return inflightRefresh;
+ }
+
+ const owner = captureAccountScope();
+
+ store.patchSnapshot({ status: store.getSnapshot().configs ? 'loaded' : 'loading' });
+
+ const refresh = getExternalProviderConfigs(owner.signal)
+ .then((configs) => {
+ if (isAccountScopeCurrent(owner)) {
+ store.patchSnapshot({ configs, error: null, status: 'loaded' });
+ }
+ })
+ .catch((error: unknown) => {
+ if (isAccountScopeCurrent(owner)) {
+ store.patchSnapshot({
+ error: error instanceof Error ? error.message : 'Failed to load external providers.',
+ status: store.getSnapshot().configs ? 'loaded' : 'error',
+ });
+ }
+ throw error;
+ })
+ .finally(() => {
+ if (inflightRefresh === refresh) {
+ inflightRefresh = null;
+ }
+ });
+
+ inflightRefresh = refresh;
+ return inflightRefresh;
+};
+
+/** Fetch on first use; callers share the request and can catch its failure. */
+export const ensureExternalProvidersLoaded = (): Promise<void> => {
+ const { status } = store.getSnapshot();
+
+ if (status === 'idle' || status === 'error') {
+ return refreshExternalProviders();
+ }
+
+ return inflightRefresh ?? Promise.resolve();
+};
+
+const replaceConfigInStore = (next: ExternalProviderConfig): void => {
+ const { configs } = store.getSnapshot();
+
+ if (configs) {
+ store.patchSnapshot({
+ configs: configs.map((config) => (config.provider_id === next.provider_id ? next : config)),
+ });
+ }
+};
+
+/** Persist changes, then patch the shared snapshot; returns the new config. */
+export const saveExternalProviderConfig = async (
+ providerId: string,
+ changes: { api_key?: string; base_url?: string | null }
+): Promise<ExternalProviderConfig> => {
+ const owner = captureAccountScope();
+ const next = await setExternalProviderConfig(providerId, changes, owner.signal);
+
+ if (isAccountScopeCurrent(owner)) {
+ replaceConfigInStore(next);
+ }
+
+ return next;
+};
+
+/** Clear the provider's key and base URL, then patch the shared snapshot. */
+export const clearExternalProviderConfig = async (providerId: string): Promise<ExternalProviderConfig> => {
+ const owner = captureAccountScope();
+ const next = await resetExternalProviderConfig(providerId, owner.signal);
+
+ if (isAccountScopeCurrent(owner)) {
+ replaceConfigInStore(next);
+ }
+
+ return next;
+};
+
+export const getExternalProvidersSnapshot = (): ExternalProvidersSnapshot => store.getSnapshot();
+
+export const useExternalProvidersSelector = store.useSelector;
+
+export const setExternalProvidersSnapshotForTests = (next: Partial<ExternalProvidersSnapshot>): void => {
+ store.patchSnapshot(next);
+};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx
index c05ac197a4..48352107dd 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.tsx
@@ -5,8 +5,13 @@ import type { StarterModel } from '@features/models/core/types';
import { Box, Checkbox, Flex, HStack, Icon, Input, InputGroup, Stack, Text } from '@chakra-ui/react';
import { getModelBaseLabel } from '@features/models/core/baseIdentity';
import { collectBases, collectTypes } from '@features/models/core/library';
-import { getExternalProviderConfigs, getHuggingFaceModels, scanFolderForModels } from '@features/models/data/api';
+import { getHuggingFaceModels, scanFolderForModels } from '@features/models/data/api';
+import {
+ ensureExternalProvidersLoaded,
+ useExternalProvidersSelector,
+} from '@features/models/data/externalProvidersStore';
import { ensureStartersLoaded, useStartersSelector } from '@features/models/data/startersStore';
+import { useScopedAction } from '@features/models/ui/shared/useScopedAction';
import { updateModelsUi, useModelsUiSelector } from '@features/models/ui/uiStore';
import { useNotify } from '@features/models/ui/useModelsNotify';
import { useMountEffect } from '@platform/react/useMountEffect';
@@ -77,45 +82,24 @@ export const AddModelsView = () => {
const [accessToken, setAccessToken] = useState('');
const [inplace, setInplace] = useState(true);
const [selectedBundleName, setSelectedBundleName] = useState<string | null>(null);
- const [isPulling, setIsPulling] = useState(false);
- const [isScanning, setIsScanning] = useState(false);
+ const { isBusy: isPulling, run: runPull } = useScopedAction();
+ const { isBusy: isScanning, run: runScan } = useScopedAction();
const [installingBundle, setInstallingBundle] = useState<string | null>(null);
- const [configuredExternalProviders, setConfiguredExternalProviders] = useState<ReadonlySet<string>>(() => new Set());
+ const providerConfigs = useExternalProvidersSelector((snapshot) => snapshot.configs);
+ const configuredExternalProviders = useMemo<ReadonlySet<string>>(
+ () =>
+ new Set(
+ (providerConfigs ?? []).filter((config) => config.api_key_configured).map((config) => config.provider_id)
+ ),
+ [providerConfigs]
+ );
const [starterFilters, setStarterFilters] = useState<StarterModelFilters>(DEFAULT_STARTER_MODEL_FILTERS);
useMountEffect(() => {
ensureStartersLoaded();
- });
-
- useMountEffect(() => {
- const owner = captureAccountScope();
- let isMounted = true;
-
- getExternalProviderConfigs(owner.signal)
- .then((configs) => {
- if (!isMounted || !isAccountScopeCurrent(owner)) {
- return;
- }
-
- setConfiguredExternalProviders(
- new Set(configs.filter((config) => config.api_key_configured).map((config) => config.provider_id))
- );
- })
- .catch((error) => {
- if (!isMounted || !isAccountScopeCurrent(owner)) {
- return;
- }
-
- setConfiguredExternalProviders(new Set());
- notify.error(
- t('models.externalProviderKeysUnavailable'),
- error instanceof Error ? error.message : String(error)
- );
- });
-
- return () => {
- isMounted = false;
- };
+ ensureExternalProvidersLoaded().catch((error: unknown) => {
+ notify.error(t('models.externalProviderKeysUnavailable'), error instanceof Error ? error.message : String(error));
+ });
});
const trimmed = query.trim();
@@ -237,90 +221,68 @@ export const AddModelsView = () => {
return;
}
- const owner = captureAccountScope();
+ await runPull(
+ async (owner) => {
+ if (kind.looksRepo) {
+ const lookup = await getHuggingFaceModels(trimmed, owner.signal);
- setIsPulling(true);
+ assertAccountScopeCurrent(owner);
+ if (lookup.is_diffusers) {
+ updateModelsUi({ hfLookup: null });
- try {
- if (kind.looksRepo) {
- const lookup = await getHuggingFaceModels(trimmed, owner.signal);
-
- assertAccountScopeCurrent(owner);
- if (lookup.is_diffusers) {
- updateModelsUi({ hfLookup: null });
+ if ((await install({ accessToken: token, source: trimmed })) && isAccountScopeCurrent(owner)) {
+ setQuery('');
+ }
- if ((await install({ accessToken: token, source: trimmed })) && isAccountScopeCurrent(owner)) {
- setQuery('');
+ return;
}
- return;
- }
+ if (!lookup.urls || lookup.urls.length === 0) {
+ notify.error(t('models.noModelFilesFoundTitle'), t('models.noInstallableModelFiles'));
- if (!lookup.urls || lookup.urls.length === 0) {
- notify.error(t('models.noModelFilesFoundTitle'), t('models.noInstallableModelFiles'));
+ return;
+ }
- return;
- }
+ // A single-file repo has nothing to choose from — install it directly,
+ // mirroring the diffusers path, instead of showing a one-row list.
+ const [onlyUrl] = lookup.urls;
- // A single-file repo has nothing to choose from — install it directly,
- // mirroring the diffusers path, instead of showing a one-row list.
- const [onlyUrl] = lookup.urls;
+ if (lookup.urls.length === 1 && onlyUrl) {
+ updateModelsUi({ hfLookup: null });
- if (lookup.urls.length === 1 && onlyUrl) {
- updateModelsUi({ hfLookup: null });
+ if ((await install({ accessToken: token, source: onlyUrl })) && isAccountScopeCurrent(owner)) {
+ setQuery('');
+ }
- if ((await install({ accessToken: token, source: onlyUrl })) && isAccountScopeCurrent(owner)) {
- setQuery('');
+ return;
}
+ updateModelsUi({ hfLookup: { repo: trimmed, urls: lookup.urls } });
+
return;
}
- updateModelsUi({ hfLookup: { repo: trimmed, urls: lookup.urls } });
-
- return;
- }
-
- if (
- (await install({ accessToken: token, inplace: kind.looksLocal ? inplace : undefined, source: trimmed })) &&
- isAccountScopeCurrent(owner)
- ) {
- setQuery('');
- }
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
-
- notify.error(t('models.installFailed'), error instanceof Error ? error.message : String(error));
- } finally {
- if (isAccountScopeCurrent(owner)) {
- setIsPulling(false);
- }
- }
+ if (
+ (await install({ accessToken: token, inplace: kind.looksLocal ? inplace : undefined, source: trimmed })) &&
+ isAccountScopeCurrent(owner)
+ ) {
+ setQuery('');
+ }
+ },
+ (message) => notify.error(t('models.installFailed'), message)
+ );
};
const handleScan = async () => {
- const owner = captureAccountScope();
-
- setIsScanning(true);
-
- try {
- const results = await scanFolderForModels(trimmed, owner.signal);
-
- assertAccountScopeCurrent(owner);
- updateModelsUi({ scan: { path: trimmed, results } });
- } catch (error) {
- if (!isAccountScopeCurrent(owner)) {
- return;
- }
+ await runScan(
+ async (owner) => {
+ const results = await scanFolderForModels(trimmed, owner.signal);
- notify.error(t('models.scanFailed'), error instanceof Error ? error.message : String(error));
- } finally {
- if (isAccountScopeCurrent(owner)) {
- setIsScanning(false);
- }
- }
+ assertAccountScopeCurrent(owner);
+ updateModelsUi({ scan: { path: trimmed, results } });
+ },
+ (message) => notify.error(t('models.scanFailed'), message)
+ );
};
return (