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.

feat(webv2): add model manager widget

joshistoast502437a537df
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index a8398f8936..07016a19d4 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -25,7 +25,9 @@
"lucide-react": "^1.17.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
- "socket.io-client": "^4.8.3"
+ "react-icons": "^5.6.0",
+ "socket.io-client": "^4.8.3",
+ "zod": "^4.4.3"
},
"devDependencies": {
"@types/node": "^25.9.3",
diff --git a/invokeai/frontend/webv2/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yaml
index a61fa5771d..5e50431961 100644
--- a/invokeai/frontend/webv2/pnpm-lock.yaml
+++ b/invokeai/frontend/webv2/pnpm-lock.yaml
@@ -29,9 +29,15 @@ importers:
react-dom:
specifier: ^19.2.7
version: 19.2.7([email protected])
+ react-icons:
+ specifier: ^5.6.0
+ version: 5.6.0([email protected])
socket.io-client:
specifier: ^4.8.3
version: 4.8.3
+ zod:
+ specifier: ^4.4.3
+ version: 4.4.3
devDependencies:
'@types/node':
specifier: ^25.9.3
@@ -1306,6 +1312,11 @@ packages:
peerDependencies:
react: ^19.2.7
+ resolution: {integrity: sha512-RH93p5ki6LfOiIt0UtDyNg/cee+HLVR6cHHtW3wALfo+eOHTp8RnU2kRkI6E+H19zMIs03DyxUG/GfZMOGvmiA==}
+ peerDependencies:
+ react: '*'
+
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
@@ -1504,6 +1515,9 @@ packages:
resolution: {integrity: sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==}
engines: {node: '>= 6'}
+ resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}
+
snapshots:
@@ -2962,6 +2976,10 @@ snapshots:
react: 19.2.7
scheduler: 0.27.0
+ dependencies:
+ react: 19.2.7
+
@@ -3100,3 +3118,5 @@ snapshots:
+
diff --git a/invokeai/frontend/webv2/src/App.tsx b/invokeai/frontend/webv2/src/App.tsx
index 7d94366678..3204dd064a 100644
--- a/invokeai/frontend/webv2/src/App.tsx
+++ b/invokeai/frontend/webv2/src/App.tsx
@@ -3,6 +3,7 @@ import { ChakraProvider } from '@chakra-ui/react';
import { system } from './theme/system';
import { AppToaster } from './workbench/components/ui/toaster';
import { ThemeController } from './workbench/ThemeController';
+import { ModelsRuntime } from './workbench/widgets/models/ModelsRuntime';
import { WorkbenchProvider } from './workbench/WorkbenchContext';
import { WorkbenchRuntime } from './workbench/WorkbenchRuntime';
import { WorkbenchShell } from './workbench/WorkbenchShell';
@@ -13,6 +14,7 @@ export const App = () => (
<WorkbenchProvider>
<ThemeController />
<WorkbenchRuntime />
+ <ModelsRuntime />
<WorkbenchShell />
</WorkbenchProvider>
</ChakraProvider>
diff --git a/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.ts b/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.ts
index adef549b12..3fe2b198c8 100644
--- a/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.ts
+++ b/invokeai/frontend/webv2/src/workbench/backend/queueCoordinator.ts
@@ -9,6 +9,7 @@ import {
listAllQueueItems,
} from '../generation/api';
import type { EnqueueGenerateRequest, EnqueueGenerateResult, ImageDTO, QueueItemDTO } from '../generation/types';
+import { handleModelInstallSocketEvent, MODEL_INSTALL_SOCKET_EVENTS } from '../models/installsStore';
import type { BackendConnectionStatus } from '../types';
import {
isTerminalBackendStatus,
@@ -326,6 +327,16 @@ export const createQueueCoordinator = (
});
socket.on('queue_item_status_changed', handleStatusChanged);
socket.on('invocation_progress', handleProgress);
+
+ // Model install lifecycle events are broadcast to every connected client
+ // (no room subscription needed); forward them to the installs store so the
+ // model manager tracks downloads without a second socket.
+ for (const modelInstallEvent of MODEL_INSTALL_SOCKET_EVENTS) {
+ socket.on(modelInstallEvent, (payload: never) => {
+ handleModelInstallSocketEvent(modelInstallEvent, payload);
+ });
+ }
+
socket.connect();
sweepTimer = setInterval(() => {
diff --git a/invokeai/frontend/webv2/src/workbench/components/ModelSelect.tsx b/invokeai/frontend/webv2/src/workbench/components/ModelSelect.tsx
new file mode 100644
index 0000000000..c0589228f7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/components/ModelSelect.tsx
@@ -0,0 +1,178 @@
+import { Badge, Combobox, createListCollection, HStack, Portal, Text } from '@chakra-ui/react';
+import { useEffect, useMemo, useState } from 'react';
+
+import { ensureModelsLoaded, useModelsSnapshot } from '../models/modelsStore';
+import {
+ formatBytes,
+ getModelBaseColorPalette,
+ getModelBaseLabel,
+ getModelCategoryRank,
+ getModelTypePluralLabel,
+} from '../models/taxonomy';
+import type { ModelConfig, ModelTaxonomyType } from '../models/types';
+
+/**
+ * Universal single-model picker: a searchable combobox over the installed
+ * library. Scope it with `modelTypes` — one type for dedicated pickers (a
+ * LoRA picker, a main-model picker) or several for cross-type pickers, in
+ * which case results are grouped by type.
+ */
+export const ModelSelect = ({
+ excludeKeys,
+ filter,
+ modelTypes,
+ onChange,
+ placeholder,
+ size = 'sm',
+ value,
+}: {
+ /** Hide specific models (e.g. the current model and already-linked ones). */
+ excludeKeys?: ReadonlySet<string>;
+ /** Extra predicate, e.g. base-architecture compatibility. */
+ filter?: (model: ModelConfig) => boolean;
+ /** The model types this instance searches. */
+ modelTypes: ModelTaxonomyType[];
+ onChange: (model: ModelConfig | null) => void;
+ placeholder?: string;
+ size?: 'xs' | 'sm' | 'md';
+ /** Selected model key, or null. */
+ value: string | null;
+}) => {
+ const { models } = useModelsSnapshot();
+ const [searchTerm, setSearchTerm] = useState('');
+
+ useEffect(() => {
+ ensureModelsLoaded();
+ }, []);
+
+ const candidates = useMemo(() => {
+ const allowedTypes = new Set(modelTypes);
+
+ return models.filter(
+ (model) => allowedTypes.has(model.type) && !excludeKeys?.has(model.key) && (filter ? filter(model) : true)
+ );
+ }, [excludeKeys, filter, modelTypes, models]);
+
+ const visibleItems = useMemo(() => {
+ const terms = searchTerm.trim().toLowerCase().split(/\s+/).filter(Boolean);
+ const matches =
+ terms.length === 0
+ ? candidates
+ : candidates.filter((model) => {
+ const haystack = `${model.name} ${model.base} ${model.type}`.toLowerCase();
+
+ return terms.every((term) => haystack.includes(term));
+ });
+
+ return [...matches].sort(
+ (a, b) =>
+ getModelCategoryRank(a.type) - getModelCategoryRank(b.type) ||
+ a.name.localeCompare(b.name, undefined, { sensitivity: 'base' })
+ );
+ }, [candidates, searchTerm]);
+
+ /** Items grouped by type, preserving the canonical category order. */
+ const groups = useMemo(() => {
+ const byType = new Map<ModelTaxonomyType, ModelConfig[]>();
+
+ for (const model of visibleItems) {
+ const group = byType.get(model.type);
+
+ if (group) {
+ group.push(model);
+ } else {
+ byType.set(model.type, [model]);
+ }
+ }
+
+ return [...byType.entries()];
+ }, [visibleItems]);
+
+ const collection = useMemo(
+ () =>
+ createListCollection({
+ itemToString: (item: ModelConfig) => item.name,
+ itemToValue: (item: ModelConfig) => item.key,
+ items: visibleItems,
+ }),
+ [visibleItems]
+ );
+
+ const scopeLabel =
+ modelTypes.length === 1 ? getModelTypePluralLabel(modelTypes[0] ?? 'main').toLowerCase() : 'models';
+
+ return (
+ <Combobox.Root
+ collection={collection}
+ openOnClick
+ placeholder={placeholder ?? `Search ${scopeLabel}…`}
+ selectionBehavior="replace"
+ size={size}
+ value={value === null ? [] : [value]}
+ w="full"
+ onInputValueChange={(details) => setSearchTerm(details.inputValue)}
+ onValueChange={(details) => {
+ onChange(details.items[0] ?? null);
+ }}
+ >
+ <Combobox.Control>
+ <Combobox.Input />
+ <Combobox.IndicatorGroup>
+ <Combobox.ClearTrigger />
+ <Combobox.Trigger />
+ </Combobox.IndicatorGroup>
+ </Combobox.Control>
+ <Portal>
+ <Combobox.Positioner>
+ <Combobox.Content
+ bg="bg.surfaceRaised"
+ borderColor="border.emphasis"
+ borderWidth="1px"
+ color="fg.default"
+ maxH="18rem"
+ rounded="lg"
+ shadow="lg"
+ zIndex="popover"
+ >
+ <Combobox.Empty color="fg.subtle" fontSize="2xs" p="2">
+ {candidates.length === 0
+ ? `No compatible ${scopeLabel} installed.`
+ : `No ${scopeLabel} match your search.`}
+ </Combobox.Empty>
+ {groups.map(([type, groupModels]) => (
+ <Combobox.ItemGroup key={type}>
+ {modelTypes.length > 1 ? (
+ <Combobox.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">
+ {getModelTypePluralLabel(type)}
+ </Combobox.ItemGroupLabel>
+ ) : null}
+ {groupModels.map((model) => (
+ <Combobox.Item key={model.key} item={model}>
+ <HStack flex="1" gap="2" minW="0">
+ <Text flex="1" fontSize="xs" minW="0" truncate>
+ {model.name}
+ </Text>
+ <Badge
+ colorPalette={getModelBaseColorPalette(model.base)}
+ flexShrink={0}
+ fontSize="2xs"
+ size="sm"
+ variant="surface"
+ >
+ {getModelBaseLabel(model.base)}
+ </Badge>
+ <Text color="fg.subtle" flexShrink={0} fontSize="2xs">
+ {formatBytes(model.file_size)}
+ </Text>
+ </HStack>
+ <Combobox.ItemIndicator />
+ </Combobox.Item>
+ ))}
+ </Combobox.ItemGroup>
+ ))}
+ </Combobox.Content>
+ </Combobox.Positioner>
+ </Portal>
+ </Combobox.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/iconResolver.tsx b/invokeai/frontend/webv2/src/workbench/iconResolver.tsx
index 6f8f2566ae..68e4d27081 100644
--- a/invokeai/frontend/webv2/src/workbench/iconResolver.tsx
+++ b/invokeai/frontend/webv2/src/workbench/iconResolver.tsx
@@ -7,6 +7,7 @@ import type { WidgetIconId } from './types';
type IconImporter = () => Promise<{ default: ComponentType }>;
const iconImporters = {
+ 'lucide-react:box': () => import('lucide-react/dist/esm/icons/box.mjs'),
'lucide-react:bug': () => import('lucide-react/dist/esm/icons/bug.mjs'),
'lucide-react:cloud-check': () => import('lucide-react/dist/esm/icons/cloud-check.mjs'),
'lucide-react:bell': () => import('lucide-react/dist/esm/icons/bell.mjs'),
diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.ts
index 5efc6bfbcf..7977d23ac3 100644
--- a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts
+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.ts
@@ -41,6 +41,16 @@ export const layoutPresets: LayoutPreset[] = [
},
label: 'Linear UI',
},
+ {
+ description: 'Full-width model library, installs, and download queue.',
+ id: 'model-manager',
+ initialLayout: {
+ centerViewId: 'models',
+ panels: { isBottomOpen: true, isLeftOpen: false, isRightOpen: false },
+ presetId: 'model-manager',
+ },
+ label: 'Model Manager',
+ },
];
export const defaultLayoutPreset = layoutPresets[0];
diff --git a/invokeai/frontend/webv2/src/workbench/models/api.ts b/invokeai/frontend/webv2/src/workbench/models/api.ts
new file mode 100644
index 0000000000..4f43c5c1cf
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/models/api.ts
@@ -0,0 +1,209 @@
+import { apiFetch, apiFetchJson, buildApiUrl } from '../backend/http';
+import type {
+ BulkDeleteModelsResponse,
+ DeleteOrphanedModelsResponse,
+ FoundModel,
+ HFTokenStatus,
+ HuggingFaceModels,
+ ModelConfig,
+ ModelInstallJob,
+ ModelRecordChanges,
+ OrphanedModelInfo,
+ StarterModelResponse,
+} from './types';
+
+/** REST client for the backend model manager (`/api/v2/models`). */
+
+const MODELS_BASE = '/api/v2/models';
+
+export const listModels = async (): Promise<ModelConfig[]> => {
+ const body = await apiFetchJson<{ models?: ModelConfig[] }>(`${MODELS_BASE}/`);
+
+ return body.models ?? [];
+};
+
+/** Models whose database record points at a file that no longer exists. */
+export const listMissingModels = async (): Promise<ModelConfig[]> => {
+ const body = await apiFetchJson<{ models?: ModelConfig[] }>(`${MODELS_BASE}/missing`);
+
+ return body.models ?? [];
+};
+
+/** Absolute server path of the models directory; relative model `path`s resolve against it. */
+export const getModelsDir = (): Promise<string> => apiFetchJson<string>(`${MODELS_BASE}/models_dir`);
+
+export const getModel = (key: string): Promise<ModelConfig> =>
+ apiFetchJson<ModelConfig>(`${MODELS_BASE}/i/${encodeURIComponent(key)}`);
+
+export const updateModel = (key: string, changes: ModelRecordChanges): Promise<ModelConfig> =>
+ apiFetchJson<ModelConfig>(`${MODELS_BASE}/i/${encodeURIComponent(key)}`, {
+ body: JSON.stringify(changes),
+ method: 'PATCH',
+ });
+
+export const deleteModel = async (key: string): Promise<void> => {
+ await apiFetch(`${MODELS_BASE}/i/${encodeURIComponent(key)}`, { method: 'DELETE' });
+};
+
+export const bulkDeleteModels = (keys: string[]): Promise<BulkDeleteModelsResponse> =>
+ apiFetchJson<BulkDeleteModelsResponse>(`${MODELS_BASE}/i/bulk_delete`, {
+ body: JSON.stringify({ keys }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ });
+
+/** Re-probe the model files to refresh auto-detected base/type/format. */
+export const reidentifyModel = (key: string): Promise<ModelConfig> =>
+ apiFetchJson<ModelConfig>(`${MODELS_BASE}/i/${encodeURIComponent(key)}/reidentify`, { method: 'POST' });
+
+export const convertModelToDiffusers = (key: string): Promise<ModelConfig> =>
+ apiFetchJson<ModelConfig>(`${MODELS_BASE}/convert/${encodeURIComponent(key)}`, { method: 'PUT' });
+
+/** Stable URL for a model's cover image; cache-busted via updated marker. */
+export const getModelImageUrl = (key: string, cacheKey?: string): string =>
+ buildApiUrl(
+ `${MODELS_BASE}/i/${encodeURIComponent(key)}/image${cacheKey ? `?t=${encodeURIComponent(cacheKey)}` : ''}`
+ );
+
+export const updateModelImage = async (key: string, image: Blob): Promise<void> => {
+ const formData = new FormData();
+
+ formData.append('image', image);
+ await apiFetch(`${MODELS_BASE}/i/${encodeURIComponent(key)}/image`, { body: formData, method: 'PATCH' });
+};
+
+export const deleteModelImage = async (key: string): Promise<void> => {
+ await apiFetch(`${MODELS_BASE}/i/${encodeURIComponent(key)}/image`, { method: 'DELETE' });
+};
+
+export interface InstallModelRequest {
+ source: string;
+ inplace?: boolean;
+ /** Access token for protected remote sources (e.g. Civitai API key). */
+ accessToken?: string;
+ /** Overrides for auto-probed config fields (name, base, type, ...). */
+ config?: ModelRecordChanges;
+}
+
+export const installModel = ({
+ accessToken,
+ config,
+ inplace,
+ source,
+}: InstallModelRequest): Promise<ModelInstallJob> => {
+ const params = new URLSearchParams({ source });
+
+ if (inplace !== undefined) {
+ params.set('inplace', String(inplace));
+ }
+
+ if (accessToken) {
+ params.set('access_token', accessToken);
+ }
+
+ return apiFetchJson<ModelInstallJob>(`${MODELS_BASE}/install?${params.toString()}`, {
+ body: JSON.stringify(config ?? {}),
+ method: 'POST',
+ });
+};
+
+export const listModelInstalls = (): Promise<ModelInstallJob[]> =>
+ apiFetchJson<ModelInstallJob[]>(`${MODELS_BASE}/install`);
+
+export const cancelModelInstall = async (id: number): Promise<void> => {
+ await apiFetch(`${MODELS_BASE}/install/${id}`, { method: 'DELETE' });
+};
+
+export const pauseModelInstall = (id: number): Promise<ModelInstallJob> =>
+ apiFetchJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/pause`, { method: 'POST' });
+
+export const resumeModelInstall = (id: number): Promise<ModelInstallJob> =>
+ apiFetchJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/resume`, { method: 'POST' });
+
+export const restartFailedModelInstall = (id: number): Promise<ModelInstallJob> =>
+ apiFetchJson<ModelInstallJob>(`${MODELS_BASE}/install/${id}/restart_failed`, { method: 'POST' });
+
+export const pruneCompletedModelInstalls = async (): Promise<void> => {
+ await apiFetch(`${MODELS_BASE}/install`, { method: 'DELETE' });
+};
+
+export const scanFolderForModels = (scanPath: string): Promise<FoundModel[]> =>
+ apiFetchJson<FoundModel[]>(`${MODELS_BASE}/scan_folder?scan_path=${encodeURIComponent(scanPath)}`);
+
+export const getHuggingFaceModels = (repo: string): Promise<HuggingFaceModels> =>
+ apiFetchJson<HuggingFaceModels>(`${MODELS_BASE}/hugging_face?hugging_face_repo=${encodeURIComponent(repo)}`);
+
+export const getStarterModels = (): Promise<StarterModelResponse> =>
+ apiFetchJson<StarterModelResponse>(`${MODELS_BASE}/starter_models`);
+
+export const getHFTokenStatus = (): Promise<HFTokenStatus> => apiFetchJson<HFTokenStatus>(`${MODELS_BASE}/hf_login`);
+
+export const setHFToken = (token: string): Promise<HFTokenStatus> =>
+ apiFetchJson<HFTokenStatus>(`${MODELS_BASE}/hf_login`, { body: JSON.stringify({ token }), method: 'POST' });
+
+export const resetHFToken = (): Promise<HFTokenStatus> =>
+ apiFetchJson<HFTokenStatus>(`${MODELS_BASE}/hf_login`, { method: 'DELETE' });
+
+export const getOrphanedModels = (): Promise<OrphanedModelInfo[]> =>
+ apiFetchJson<OrphanedModelInfo[]>(`${MODELS_BASE}/sync/orphaned`);
+
+export const deleteOrphanedModels = (paths: string[]): Promise<DeleteOrphanedModelsResponse> =>
+ apiFetchJson<DeleteOrphanedModelsResponse>(`${MODELS_BASE}/sync/orphaned`, {
+ body: JSON.stringify({ paths }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'DELETE',
+ });
+
+export const emptyModelCache = async (): Promise<void> => {
+ await apiFetch(`${MODELS_BASE}/empty_model_cache`, { method: 'POST' });
+};
+
+/** Model relationships: bidirectional "related model" links between configs. */
+
+const RELATIONSHIPS_BASE = '/api/v1/model_relationships';
+
+export const getRelatedModelKeys = (key: string): Promise<string[]> =>
+ apiFetchJson<string[]>(`${RELATIONSHIPS_BASE}/i/${encodeURIComponent(key)}`);
+
+export const addModelRelationship = async (modelKey1: string, modelKey2: string): Promise<void> => {
+ await apiFetch(`${RELATIONSHIPS_BASE}/`, {
+ body: JSON.stringify({ model_key_1: modelKey1, model_key_2: modelKey2 }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ });
+};
+
+export const removeModelRelationship = async (modelKey1: string, modelKey2: string): Promise<void> => {
+ await apiFetch(`${RELATIONSHIPS_BASE}/`, {
+ body: JSON.stringify({ model_key_1: modelKey1, model_key_2: modelKey2 }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'DELETE',
+ });
+};
+
+/** External image-provider credentials (OpenAI, Gemini, ...). */
+
+const EXTERNAL_PROVIDERS_BASE = '/api/v1/app/external_providers';
+
+export interface ExternalProviderConfig {
+ provider_id: string;
+ api_key_configured: boolean;
+ base_url: string | null;
+}
+
+export const getExternalProviderConfigs = (): Promise<ExternalProviderConfig[]> =>
+ apiFetchJson<ExternalProviderConfig[]>(`${EXTERNAL_PROVIDERS_BASE}/config`);
+
+export const setExternalProviderConfig = (
+ providerId: string,
+ config: { api_key?: string; base_url?: string | null }
+): Promise<ExternalProviderConfig> =>
+ apiFetchJson<ExternalProviderConfig>(`${EXTERNAL_PROVIDERS_BASE}/config/${encodeURIComponent(providerId)}`, {
+ body: JSON.stringify(config),
+ method: 'POST',
+ });
+
+export const resetExternalProviderConfig = (providerId: string): Promise<ExternalProviderConfig> =>
+ apiFetchJson<ExternalProviderConfig>(`${EXTERNAL_PROVIDERS_BASE}/config/${encodeURIComponent(providerId)}`, {
+ method: 'DELETE',
+ });
diff --git a/invokeai/frontend/webv2/src/workbench/models/apiKeys.ts b/invokeai/frontend/webv2/src/workbench/models/apiKeys.ts
new file mode 100644
index 0000000000..546d0c3211
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/models/apiKeys.ts
@@ -0,0 +1,46 @@
+/**
+ * Client-side API key storage for remote model sources. The HuggingFace token
+ * lives on the backend (`/api/v2/models/hf_login`); the Civitai key has no
+ * backend home, so it is kept in this browser's localStorage and passed as the
+ * `access_token` query param when installing from a matching URL.
+ */
+
+const CIVITAI_KEY_STORAGE_KEY = 'invokeai-webv2-civitai-api-key';
+
+export const getCivitaiApiKey = (): string | null => {
+ try {
+ return window.localStorage.getItem(CIVITAI_KEY_STORAGE_KEY);
+ } catch {
+ return null;
+ }
+};
+
+export const setCivitaiApiKey = (key: string): void => {
+ try {
+ window.localStorage.setItem(CIVITAI_KEY_STORAGE_KEY, key);
+ } catch {
+ // Storage unavailable (private mode/quota) — the key just is not persisted.
+ }
+};
+
+export const clearCivitaiApiKey = (): void => {
+ try {
+ window.localStorage.removeItem(CIVITAI_KEY_STORAGE_KEY);
+ } catch {
+ // Ignore: nothing to clear if storage is unavailable.
+ }
+};
+
+export const isCivitaiUrl = (source: string): boolean => {
+ try {
+ const host = new URL(source).hostname;
+
+ return host === 'civitai.com' || host.endsWith('.civitai.com');
+ } catch {
+ return false;
+ }
+};
+
+/** The access token to use for a given install source, if any is saved. */
+export const getAccessTokenForSource = (source: string): string | undefined =>
+ isCivitaiUrl(source) ? (getCivitaiApiKey() ?? undefined) : undefined;
diff --git a/invokeai/frontend/webv2/src/workbench/models/installsStore.ts b/invokeai/frontend/webv2/src/workbench/models/installsStore.ts
new file mode 100644
index 0000000000..6c4e56c130
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/models/installsStore.ts
@@ -0,0 +1,262 @@
+import { useSyncExternalStore } from 'react';
+
+import { createExternalStore, createListenerChannel } from '../externalStore';
+import { listModelInstalls } from './api';
+import { refreshModels } from './modelsStore';
+import { refreshStartersIfLoaded } from './startersStore';
+import type { ModelInstallJob, ModelInstallStatus } from './types';
+
+/**
+ * Live store for model install jobs. The job list itself is REST-owned
+ * (`/api/v2/models/install`) and refreshed on lifecycle socket events;
+ * download progress is high-frequency transient data that bypasses the list
+ * (and the workbench reducer) entirely — each queue row subscribes to its own
+ * job id and only re-renders when that job's bytes move. This mirrors the
+ * generation `progressStore` pattern.
+ */
+
+export interface InstallsSnapshot {
+ jobs: ModelInstallJob[];
+ status: 'idle' | 'loading' | 'loaded' | 'error';
+ error: string | null;
+}
+
+export interface InstallDownloadProgress {
+ bytes: number;
+ totalBytes: number;
+}
+
+/** A just-settled install, surfaced so the UI can toast success/failure. */
+export interface InstallOutcome {
+ id: number;
+ jobId: number;
+ kind: 'completed' | 'error' | 'cancelled';
+ modelName: string | null;
+ source: string;
+ error: string | null;
+}
+
+const REFRESH_COALESCE_MS = 250;
+const OUTCOME_LIMIT = 16;
+
+const store = createExternalStore<InstallsSnapshot>({ error: null, jobs: [], status: 'idle' });
+
+let outcomes: InstallOutcome[] = [];
+let nextOutcomeId = 1;
+
+const progressByJobId = new Map<number, InstallDownloadProgress>();
+
+const progressChannel = createListenerChannel();
+const outcomesChannel = createListenerChannel();
+
+let inflightRefresh: Promise<void> | null = null;
+let refreshTimer: ReturnType<typeof setTimeout> | null = null;
+
+export const refreshInstalls = (): Promise<void> => {
+ if (inflightRefresh) {
+ return inflightRefresh;
+ }
+
+ store.patchSnapshot({ status: store.getSnapshot().status === 'loaded' ? 'loaded' : 'loading' });
+
+ inflightRefresh = listModelInstalls()
+ .then((jobs) => {
+ const activeJobIds = new Set(jobs.map((job) => job.id));
+
+ for (const jobId of progressByJobId.keys()) {
+ if (!activeJobIds.has(jobId)) {
+ progressByJobId.delete(jobId);
+ }
+ }
+
+ store.patchSnapshot({ error: null, jobs, status: 'loaded' });
+ progressChannel.notify();
+ })
+ .catch((error: unknown) => {
+ store.patchSnapshot({
+ error: error instanceof Error ? error.message : 'Failed to load install queue.',
+ status: store.getSnapshot().jobs.length > 0 ? 'loaded' : 'error',
+ });
+ })
+ .finally(() => {
+ inflightRefresh = null;
+ });
+
+ return inflightRefresh;
+};
+
+export const ensureInstallsLoaded = (): void => {
+ if (store.getSnapshot().status === 'idle') {
+ void refreshInstalls();
+ }
+};
+
+const scheduleRefresh = (): void => {
+ if (refreshTimer !== null) {
+ return;
+ }
+
+ refreshTimer = setTimeout(() => {
+ refreshTimer = null;
+ void refreshInstalls();
+ }, REFRESH_COALESCE_MS);
+};
+
+/** Optimistically replace one job (e.g. after pause/resume API calls). */
+export const replaceInstallJob = (job: ModelInstallJob): void => {
+ store.patchSnapshot({
+ jobs: store.getSnapshot().jobs.map((existing) => (existing.id === job.id ? job : existing)),
+ });
+};
+
+/** Optimistically add a freshly created job so the queue updates instantly. */
+export const addInstallJob = (job: ModelInstallJob): void => {
+ if (store.getSnapshot().jobs.some((existing) => existing.id === job.id)) {
+ replaceInstallJob(job);
+ return;
+ }
+
+ store.patchSnapshot({ jobs: [job, ...store.getSnapshot().jobs], status: 'loaded' });
+};
+
+const recordOutcome = (outcome: Omit<InstallOutcome, 'id'>): void => {
+ outcomes = [{ ...outcome, id: nextOutcomeId }, ...outcomes].slice(0, OUTCOME_LIMIT);
+ nextOutcomeId += 1;
+ outcomesChannel.notify();
+};
+
+interface ModelInstallSocketPayload {
+ id: number;
+ bytes?: number;
+ total_bytes?: number;
+ source?: unknown;
+ error?: string | null;
+ error_type?: string | null;
+ config?: { name?: string } | null;
+}
+
+const describeSource = (source: unknown): string => {
+ if (typeof source === 'string') {
+ return source;
+ }
+
+ if (source && typeof source === 'object') {
+ const record = source as Record<string, unknown>;
+
+ for (const field of ['repo_id', 'url', 'path']) {
+ if (typeof record[field] === 'string') {
+ return record[field];
+ }
+ }
+ }
+
+ return 'model';
+};
+
+export const MODEL_INSTALL_SOCKET_EVENTS = [
+ 'model_install_started',
+ 'model_install_download_started',
+ 'model_install_download_progress',
+ 'model_install_downloads_complete',
+ 'model_install_complete',
+ 'model_install_error',
+ 'model_install_cancelled',
+] as const;
+
+export type ModelInstallSocketEvent = (typeof MODEL_INSTALL_SOCKET_EVENTS)[number];
+
+/** Socket sink — wired into the backend socket by the queue coordinator. */
+export const handleModelInstallSocketEvent = (event: ModelInstallSocketEvent, payload: unknown): void => {
+ const data = payload as ModelInstallSocketPayload;
+
+ if (typeof data?.id !== 'number') {
+ return;
+ }
+
+ if (event === 'model_install_download_progress') {
+ progressByJobId.set(data.id, { bytes: data.bytes ?? 0, totalBytes: data.total_bytes ?? 0 });
+ progressChannel.notify();
+
+ const job = store.getSnapshot().jobs.find((candidate) => candidate.id === data.id);
+
+ if (!job) {
+ // The first progress tick may arrive for a job created in another
+ // client; make sure the row exists without refetching on every tick.
+ scheduleRefresh();
+ } else if (job.status === 'waiting') {
+ // Bytes are flowing, so the REST snapshot's `waiting` is stale. Patch
+ // locally so download controls (pause/cancel) appear immediately.
+ replaceInstallJob({ ...job, status: 'downloading' });
+ }
+
+ return;
+ }
+
+ if (event === 'model_install_complete') {
+ recordOutcome({
+ error: null,
+ jobId: data.id,
+ kind: 'completed',
+ modelName: data.config?.name ?? null,
+ source: describeSource(data.source),
+ });
+ void refreshModels();
+ refreshStartersIfLoaded();
+ } else if (event === 'model_install_error') {
+ recordOutcome({
+ error: data.error ?? data.error_type ?? 'Unknown install error.',
+ jobId: data.id,
+ kind: 'error',
+ modelName: null,
+ source: describeSource(data.source),
+ });
+ } else if (event === 'model_install_cancelled') {
+ recordOutcome({
+ error: null,
+ jobId: data.id,
+ kind: 'cancelled',
+ modelName: null,
+ source: describeSource(data.source),
+ });
+ }
+
+ scheduleRefresh();
+};
+
+const ACTIVE_STATUSES: ModelInstallStatus[] = ['waiting', 'downloading', 'downloads_done', 'running'];
+
+export const isActiveInstallStatus = (status: ModelInstallStatus): boolean => ACTIVE_STATUSES.includes(status);
+
+export const useInstallsSnapshot = (): InstallsSnapshot => store.useSnapshot();
+
+/**
+ * Source strings (URL, repo id, or path) of jobs currently in flight, cached
+ * per jobs-array so list rows can show an "installing" state by source.
+ */
+let activeSourcesCache: { jobs: ModelInstallJob[]; sources: ReadonlySet<string> } | null = null;
+
+const getActiveInstallSources = (): ReadonlySet<string> => {
+ const { jobs } = store.getSnapshot();
+
+ if (activeSourcesCache?.jobs !== jobs) {
+ activeSourcesCache = {
+ jobs,
+ sources: new Set(
+ jobs
+ .filter((job) => isActiveInstallStatus(job.status) || job.status === 'paused')
+ .map((job) => describeSource(job.source))
+ ),
+ };
+ }
+
+ return activeSourcesCache.sources;
+};
+
+export const useActiveInstallSources = (): ReadonlySet<string> =>
+ useSyncExternalStore(store.subscribe, getActiveInstallSources);
+
+export const useInstallProgress = (jobId: number): InstallDownloadProgress | null =>
+ useSyncExternalStore(progressChannel.subscribe, () => progressByJobId.get(jobId) ?? null);
+
+export const useInstallOutcomes = (): InstallOutcome[] =>
+ useSyncExternalStore(outcomesChannel.subscribe, () => outcomes);
diff --git a/invokeai/frontend/webv2/src/workbench/models/library.test.ts b/invokeai/frontend/webv2/src/workbench/models/library.test.ts
new file mode 100644
index 0000000000..16bd1161ed
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/models/library.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ collectBases,
+ collectTypes,
+ DEFAULT_LIBRARY_FILTERS,
+ filterModels,
+ flattenGroupsToRows,
+ groupModelsByType,
+} from './library';
+import type { ModelConfig } from './types';
+
+const createModel = (overrides: Partial<ModelConfig>): ModelConfig => ({
+ base: 'sdxl',
+ file_size: 1024,
+ format: 'checkpoint',
+ hash: 'hash',
+ key: 'key',
+ name: 'Model',
+ path: '/models/model.safetensors',
+ source: '/models/model.safetensors',
+ source_type: 'path',
+ type: 'main',
+ ...overrides,
+});
+
+const library: ModelConfig[] = [
+ createModel({ base: 'sdxl', file_size: 300, key: 'a', name: 'Juggernaut XL', type: 'main' }),
+ createModel({ base: 'flux', file_size: 100, key: 'b', name: 'FLUX dev', type: 'main' }),
+ createModel({
+ base: 'sd-1',
+ file_size: 200,
+ key: 'c',
+ name: 'Detail Tweaker',
+ trigger_phrases: ['detail'],
+ type: 'lora',
+ }),
+ createModel({ base: 'any', file_size: 50, key: 'd', name: 'Some VAE', type: 'vae' }),
+];
+
+const NO_MISSING: ReadonlySet<string> = new Set();
+
+describe('filterModels', () => {
+ it('matches search terms against name, taxonomy, and trigger phrases', () => {
+ expect(
+ filterModels(library, { ...DEFAULT_LIBRARY_FILTERS, searchTerm: 'flux' }, NO_MISSING).map((m) => m.key)
+ ).toEqual(['b']);
+ expect(
+ filterModels(library, { ...DEFAULT_LIBRARY_FILTERS, searchTerm: 'detail' }, NO_MISSING).map((m) => m.key)
+ ).toEqual(['c']);
+ });
+
+ it('filters by type and base independently', () => {
+ expect(
+ filterModels(library, { ...DEFAULT_LIBRARY_FILTERS, typeFilter: 'lora' }, NO_MISSING).map((m) => m.key)
+ ).toEqual(['c']);
+ expect(
+ filterModels(library, { ...DEFAULT_LIBRARY_FILTERS, baseFilter: 'sdxl' }, NO_MISSING).map((m) => m.key)
+ ).toEqual(['a']);
+ });
+
+ it('filters to missing models only', () => {
+ const missing = new Set(['d']);
+
+ expect(filterModels(library, { ...DEFAULT_LIBRARY_FILTERS, missingOnly: true }, missing).map((m) => m.key)).toEqual(
+ ['d']
+ );
+ });
+
+ it('sorts by size descending', () => {
+ const sorted = filterModels(
+ library,
+ { ...DEFAULT_LIBRARY_FILTERS, sortDirection: 'desc', sortField: 'size' },
+ NO_MISSING
+ );
+
+ expect(sorted.map((m) => m.key)).toEqual(['a', 'c', 'b', 'd']);
+ });
+});
+
+describe('groupModelsByType', () => {
+ it('groups in canonical category order with headers flattened for virtualization', () => {
+ const groups = groupModelsByType(filterModels(library, DEFAULT_LIBRARY_FILTERS, NO_MISSING));
+
+ expect(groups.map((group) => group.type)).toEqual(['main', 'lora', 'vae']);
+
+ const rows = flattenGroupsToRows(groups);
+
+ expect(rows[0]).toMatchObject({ kind: 'header' });
+ expect(rows).toHaveLength(groups.length + library.length);
+ });
+});
+
+describe('collect helpers', () => {
+ it('collects distinct bases alphabetically and types in category order', () => {
+ expect(collectBases(library)).toEqual(['any', 'flux', 'sd-1', 'sdxl']);
+ expect(collectTypes(library)).toEqual(['main', 'lora', 'vae']);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/models/library.ts b/invokeai/frontend/webv2/src/workbench/models/library.ts
new file mode 100644
index 0000000000..b349a1ac47
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/models/library.ts
@@ -0,0 +1,119 @@
+import { getModelBaseLabel, getModelCategoryRank, getModelTypePluralLabel } from './taxonomy';
+import type { ModelConfig, ModelTaxonomyType } from './types';
+
+/**
+ * Pure filtering/grouping/sorting for the model library. Kept free of React so
+ * the list views stay thin and this logic is unit-testable.
+ */
+
+export type ModelSortField = 'default' | 'name' | 'base' | 'size' | 'format';
+
+export interface ModelLibraryFilters {
+ searchTerm: string;
+ /** null = all types. */
+ typeFilter: ModelTaxonomyType | null;
+ /** null = all bases. */
+ baseFilter: string | null;
+ /** Only models whose files are missing on disk. */
+ missingOnly: boolean;
+ sortField: ModelSortField;
+ sortDirection: 'asc' | 'desc';
+}
+
+export const DEFAULT_LIBRARY_FILTERS: ModelLibraryFilters = {
+ baseFilter: null,
+ missingOnly: false,
+ searchTerm: '',
+ sortDirection: 'asc',
+ sortField: 'default',
+ typeFilter: null,
+};
+
+export interface ModelGroup {
+ type: ModelTaxonomyType;
+ label: string;
+ models: ModelConfig[];
+}
+
+const matchesSearch = (model: ModelConfig, searchTerm: string): boolean => {
+ if (!searchTerm) {
+ return true;
+ }
+
+ const haystack =
+ `${model.name} ${model.description ?? ''} ${model.base} ${model.type} ${model.format} ${(model.trigger_phrases ?? []).join(' ')}`.toLowerCase();
+
+ return searchTerm
+ .toLowerCase()
+ .split(/\s+/)
+ .every((term) => haystack.includes(term));
+};
+
+const compareBySortField = (a: ModelConfig, b: ModelConfig, field: ModelSortField): number => {
+ switch (field) {
+ case 'name':
+ case 'default':
+ return a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });
+ case 'base':
+ return getModelBaseLabel(a.base).localeCompare(getModelBaseLabel(b.base));
+ case 'size':
+ return a.file_size - b.file_size;
+ case 'format':
+ return String(a.format).localeCompare(String(b.format));
+ }
+};
+
+export const filterModels = (
+ models: ModelConfig[],
+ filters: ModelLibraryFilters,
+ missingModelKeys: ReadonlySet<string>
+): ModelConfig[] => {
+ const searchTerm = filters.searchTerm.trim();
+ const directionFactor = filters.sortDirection === 'desc' ? -1 : 1;
+
+ return models
+ .filter(
+ (model) =>
+ (!filters.missingOnly || missingModelKeys.has(model.key)) &&
+ (filters.typeFilter === null || model.type === filters.typeFilter) &&
+ (filters.baseFilter === null || model.base === filters.baseFilter) &&
+ matchesSearch(model, searchTerm)
+ )
+ .sort((a, b) => compareBySortField(a, b, filters.sortField) * directionFactor);
+};
+
+/** Group filtered models by category in canonical category order. */
+export const groupModelsByType = (models: ModelConfig[]): ModelGroup[] => {
+ const groupsByType = new Map<ModelTaxonomyType, ModelConfig[]>();
+
+ for (const model of models) {
+ const group = groupsByType.get(model.type);
+
+ if (group) {
+ group.push(model);
+ } else {
+ groupsByType.set(model.type, [model]);
+ }
+ }
+
+ return [...groupsByType.entries()]
+ .sort(([a], [b]) => getModelCategoryRank(a) - getModelCategoryRank(b))
+ .map(([type, groupModels]) => ({ label: getModelTypePluralLabel(type), models: groupModels, type }));
+};
+
+/** Distinct bases present in a model list, for base filter menus. */
+export const collectBases = (models: Pick<ModelConfig, 'base'>[]): string[] =>
+ [...new Set(models.map((model) => String(model.base)))].sort();
+
+/** Distinct types present in a model list, in canonical order. */
+export const collectTypes = (models: Pick<ModelConfig, 'type'>[]): ModelTaxonomyType[] =>
+ [...new Set(models.map((model) => model.type))].sort((a, b) => getModelCategoryRank(a) - getModelCategoryRank(b));
+
+/** Rows for a virtualized flat list: group headers interleaved with models. */
+export type LibraryRow = { kind: 'header'; group: ModelGroup } | { kind: 'model'; model: ModelConfig };
+
+export const flattenGroupsToRows = (groups: ModelGroup[]): LibraryRow[] =>
+ groups.flatMap<LibraryRow>((group) => [
+ { group, kind: 'header' },
+ ...group.models.map<LibraryRow>((model) => ({ kind: 'model', model })),
+ ]);
diff --git a/invokeai/frontend/webv2/src/workbench/models/modelsStore.ts b/invokeai/frontend/webv2/src/workbench/models/modelsStore.ts
new file mode 100644
index 0000000000..1204490d99
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/models/modelsStore.ts
@@ -0,0 +1,113 @@
+import { createExternalStore } from '../externalStore';
+import { getModelsDir, listMissingModels, listModels } from './api';
+import type { ModelConfig } from './types';
+
+/**
+ * Shared library store for installed model configs. Lives outside the
+ * workbench reducer because the list is backend-owned server state shared by
+ * every surface of the models widget (panel, center view, pickers); a single
+ * module store keeps them consistent and avoids re-fetch storms. Mutations go
+ * through the API layer and then either patch the snapshot in place (fast
+ * path) or trigger a refresh.
+ */
+
+export interface ModelsSnapshot {
+ models: 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. */
+ coverImageVersions: Readonly<Record<string, number>>;
+ /** Absolute server path of the models directory (resolves relative model paths). */
+ modelsDir: string | null;
+ status: 'idle' | 'loading' | 'loaded' | 'error';
+ error: string | null;
+}
+
+const EMPTY_MISSING_KEYS: ReadonlySet<string> = new Set<string>();
+
+const store = createExternalStore<ModelsSnapshot>({
+ coverImageVersions: {},
+ error: null,
+ missingModelKeys: EMPTY_MISSING_KEYS,
+ models: [],
+ modelsDir: null,
+ status: 'idle',
+});
+
+let inflightRefresh: Promise<void> | null = null;
+
+/** Re-fetch the library; concurrent calls share one request. */
+export const refreshModels = (): Promise<void> => {
+ if (inflightRefresh) {
+ return inflightRefresh;
+ }
+
+ store.patchSnapshot({ status: store.getSnapshot().status === 'loaded' ? 'loaded' : 'loading' });
+
+ inflightRefresh = Promise.all([
+ listModels(),
+ // Missing-file detection is best-effort; never fail the whole library.
+ listMissingModels().catch(() => [] as ModelConfig[]),
+ // Static server config: fetched once, best-effort.
+ store.getSnapshot().modelsDir ?? getModelsDir().catch(() => null),
+ ])
+ .then(([models, missingModels, modelsDir]) => {
+ store.patchSnapshot({
+ error: null,
+ missingModelKeys:
+ missingModels.length > 0 ? new Set(missingModels.map((model) => model.key)) : EMPTY_MISSING_KEYS,
+ models,
+ modelsDir,
+ status: 'loaded',
+ });
+ })
+ .catch((error: unknown) => {
+ store.patchSnapshot({
+ error: error instanceof Error ? error.message : 'Failed to load models.',
+ status: store.getSnapshot().models.length > 0 ? 'loaded' : 'error',
+ });
+ })
+ .finally(() => {
+ inflightRefresh = null;
+ });
+
+ return inflightRefresh;
+};
+
+/** Fetch once on first use; later callers get the cached snapshot. */
+export const ensureModelsLoaded = (): void => {
+ if (store.getSnapshot().status === 'idle') {
+ void refreshModels();
+ }
+};
+
+/** 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)),
+ });
+};
+
+export const removeModelsFromStore = (keys: string[]): void => {
+ const removed = new Set(keys);
+
+ store.patchSnapshot({ models: store.getSnapshot().models.filter((model) => !removed.has(model.key)) });
+};
+
+/**
+ * Record a cover image upload/removal without refetching: keeps the truthy
+ * `cover_image` marker in sync for thumbnails and bumps the version that
+ * cache-busts their URLs (the backend serves the image at a stable URL).
+ */
+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
+ ),
+ });
+};
+
+export const useModelsSnapshot = (): ModelsSnapshot => store.useSnapshot();
diff --git a/invokeai/frontend/webv2/src/workbench/models/schemas.ts b/invokeai/frontend/webv2/src/workbench/models/schemas.ts
new file mode 100644
index 0000000000..c6c1f4ae3a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/models/schemas.ts
@@ -0,0 +1,102 @@
+import { z } from 'zod';
+
+/**
+ * Zod schemas backing every model-manager form. All user input is validated
+ * through these before touching the API, so error states are consistent and
+ * the API layer can assume well-formed values.
+ */
+
+const trimmed = z.string().trim();
+
+/** URL, HuggingFace repo id, or absolute local path. */
+export const installSourceSchema = z.object({
+ accessToken: trimmed.optional(),
+ inplace: z.boolean(),
+ source: trimmed
+ .min(1, 'Enter a URL, HuggingFace repo id, or local path.')
+ .refine(
+ (value) => !value.includes(' ') || value.startsWith('/') || /^[A-Za-z]:[\\/]/.test(value),
+ 'URLs and repo ids cannot contain spaces.'
+ ),
+});
+
+export type InstallSourceFormValues = z.infer<typeof installSourceSchema>;
+
+/** `owner/name` with optional `:variant[:path]` qualifiers. */
+export const huggingFaceRepoSchema = z.object({
+ repo: trimmed
+ .min(1, 'Enter a HuggingFace repo id.')
+ .regex(/^[\w.-]+\/[\w.-]+(:[\w./-]*)*$/, 'Expected an owner/repo id, e.g. black-forest-labs/FLUX.1-dev.'),
+});
+
+export type HuggingFaceRepoFormValues = z.infer<typeof huggingFaceRepoSchema>;
+
+export const scanFolderSchema = z.object({
+ path: trimmed.min(1, 'Enter an absolute folder path on the server.'),
+});
+
+export type ScanFolderFormValues = z.infer<typeof scanFolderSchema>;
+
+export const hfTokenSchema = z.object({
+ token: trimmed.min(1, 'Paste a HuggingFace access token.'),
+});
+
+export type HFTokenFormValues = z.infer<typeof hfTokenSchema>;
+
+export const civitaiKeySchema = z.object({
+ key: trimmed.min(1, 'Paste a Civitai API key.'),
+});
+
+export type CivitaiKeyFormValues = z.infer<typeof civitaiKeySchema>;
+
+export const modelEditSchema = z.object({
+ base: trimmed.min(1, 'Base architecture is required.'),
+ description: trimmed.max(2000, 'Keep the description under 2000 characters.'),
+ name: trimmed.min(1, 'Name is required.').max(200, 'Keep the name under 200 characters.'),
+ predictionType: z.union([z.literal(''), z.enum(['epsilon', 'v_prediction', 'sample'])]),
+ sourceUrl: z.union([z.literal(''), z.url({ error: 'Must be a valid http(s) URL.' })]),
+ type: trimmed.min(1, 'Model type is required.'),
+ variant: trimmed,
+});
+
+export type ModelEditFormValues = z.infer<typeof modelEditSchema>;
+
+const optionalBoundedNumber = (min: number, max: number, label: string) =>
+ z
+ .number({ message: `${label} must be a number.` })
+ .min(min, `${label} must be at least ${min}.`)
+ .max(max, `${label} must be at most ${max}.`)
+ .nullable();
+
+/**
+ * Per-model generation defaults. Every field is nullable — null means "no
+ * default, use the app-level setting" and maps to an unchecked toggle.
+ */
+export const mainDefaultSettingsSchema = z.object({
+ cfgRescaleMultiplier: optionalBoundedNumber(0, 0.99, 'CFG rescale multiplier'),
+ cfgScale: optionalBoundedNumber(1, 200, 'CFG scale'),
+ guidance: optionalBoundedNumber(1, 20, 'Guidance'),
+ height: optionalBoundedNumber(64, 8192, 'Height').refine(
+ (value) => value === null || value % 8 === 0,
+ 'Height must be a multiple of 8.'
+ ),
+ scheduler: trimmed.nullable(),
+ steps: optionalBoundedNumber(1, 10000, 'Steps'),
+ vaePrecision: z.enum(['fp16', 'fp32']).nullable(),
+ width: optionalBoundedNumber(64, 8192, 'Width').refine(
+ (value) => value === null || value % 8 === 0,
+ 'Width must be a multiple of 8.'
+ ),
+});
+
+export type MainDefaultSettingsFormValues = z.infer<typeof mainDefaultSettingsSchema>;
+
+export const loraDefaultSettingsSchema = z.object({
+ weight: optionalBoundedNumber(-10, 10, 'Weight'),
+});
+
+export type LoraDefaultSettingsFormValues = z.infer<typeof loraDefaultSettingsSchema>;
+
+export const triggerPhraseSchema = trimmed
+ .min(1, 'Trigger phrase cannot be empty.')
+ .max(200, 'Keep trigger phrases under 200 characters.');
diff --git a/invokeai/frontend/webv2/src/workbench/models/startersStore.ts b/invokeai/frontend/webv2/src/workbench/models/startersStore.ts
new file mode 100644
index 0000000000..5334a7b62e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/models/startersStore.ts
@@ -0,0 +1,58 @@
+import { createExternalStore } from '../externalStore';
+import { getStarterModels } from './api';
+import type { StarterModelResponse } from './types';
+
+/**
+ * Cached starter-models catalog. The list is large and rarely changes, so it
+ * is fetched once and served from memory on revisits; installs revalidate it
+ * in the background (the `is_installed` flags shift) without blanking the UI.
+ */
+
+export interface StartersSnapshot {
+ response: StarterModelResponse | null;
+ status: 'idle' | 'loading' | 'loaded' | 'error';
+ error: string | null;
+}
+
+const store = createExternalStore<StartersSnapshot>({ error: null, response: null, status: 'idle' });
+
+let inflightRefresh: Promise<void> | null = null;
+
+export const refreshStarters = (): Promise<void> => {
+ if (inflightRefresh) {
+ return inflightRefresh;
+ }
+
+ store.patchSnapshot({ status: store.getSnapshot().response ? 'loaded' : 'loading' });
+
+ inflightRefresh = getStarterModels()
+ .then((response) => {
+ store.patchSnapshot({ error: null, response, status: 'loaded' });
+ })
+ .catch((error: unknown) => {
+ store.patchSnapshot({
+ error: error instanceof Error ? error.message : 'Failed to load starter models.',
+ status: store.getSnapshot().response ? 'loaded' : 'error',
+ });
+ })
+ .finally(() => {
+ inflightRefresh = null;
+ });
+
+ return inflightRefresh;
+};
+
+export const ensureStartersLoaded = (): void => {
+ if (store.getSnapshot().status === 'idle') {
+ void refreshStarters();
+ }
+};
+
+/** Revalidate installed flags after an install lands, if already loaded. */
+export const refreshStartersIfLoaded = (): void => {
+ if (store.getSnapshot().status === 'loaded') {
+ void refreshStarters();
+ }
+};
+
+export const useStartersSnapshot = (): StartersSnapshot => store.useSnapshot();
diff --git a/invokeai/frontend/webv2/src/workbench/models/taxonomy.ts b/invokeai/frontend/webv2/src/workbench/models/taxonomy.ts
new file mode 100644
index 0000000000..cf6692fcf9
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/models/taxonomy.ts
@@ -0,0 +1,148 @@
+import type { ModelBase, ModelConfig, ModelFileFormat, ModelInstallJob, ModelTaxonomyType } from './types';
+
+/**
+ * Display metadata for the model taxonomy. Open-union friendly: unknown bases,
+ * types, and formats fall back to readable generic labels so a backend that
+ * ships a new architecture never renders a blank or broken library.
+ */
+
+interface CategoryDefinition {
+ type: ModelTaxonomyType;
+ label: string;
+ pluralLabel: string;
+}
+
+/** Library grouping order — most-used categories first, mirroring legacy web. */
+export const MODEL_CATEGORIES: CategoryDefinition[] = [
+ { label: 'Main Model', pluralLabel: 'Main Models', type: 'main' },
+ { label: 'LoRA', pluralLabel: 'LoRAs', type: 'lora' },
+ { label: 'Embedding', pluralLabel: 'Embeddings', type: 'embedding' },
+ { label: 'ControlNet', pluralLabel: 'ControlNets', type: 'controlnet' },
+ { label: 'Control LoRA', pluralLabel: 'Control LoRAs', type: 'control_lora' },
+ { label: 'IP Adapter', pluralLabel: 'IP Adapters', type: 'ip_adapter' },
+ { label: 'T2I Adapter', pluralLabel: 'T2I Adapters', type: 't2i_adapter' },
+ { label: 'VAE', pluralLabel: 'VAEs', type: 'vae' },
+ { label: 'T5 Encoder', pluralLabel: 'T5 Encoders', type: 't5_encoder' },
+ { label: 'Qwen3 Encoder', pluralLabel: 'Qwen3 Encoders', type: 'qwen3_encoder' },
+ { label: 'Qwen VL Encoder', pluralLabel: 'Qwen VL Encoders', type: 'qwen_vl_encoder' },
+ { label: 'CLIP Embed', pluralLabel: 'CLIP Embeds', type: 'clip_embed' },
+ { label: 'CLIP Vision', pluralLabel: 'CLIP Visions', type: 'clip_vision' },
+ { label: 'SigLIP', pluralLabel: 'SigLIPs', type: 'siglip' },
+ { label: 'FLUX Redux', pluralLabel: 'FLUX Reduxes', type: 'flux_redux' },
+ { label: 'Image-to-Image', pluralLabel: 'Image-to-Image Models', type: 'spandrel_image_to_image' },
+ { label: 'LLaVA OneVision', pluralLabel: 'LLaVA OneVision Models', type: 'llava_onevision' },
+ { label: 'Text LLM', pluralLabel: 'Text LLMs', type: 'text_llm' },
+ { label: 'External Generator', pluralLabel: 'External Generators', type: 'external_image_generator' },
+ { label: 'ONNX', pluralLabel: 'ONNX Models', type: 'onnx' },
+ { label: 'Unknown', pluralLabel: 'Unknown Models', type: 'unknown' },
+];
+
+const categoryByType = new Map(MODEL_CATEGORIES.map((category) => [category.type, category]));
+
+const toTitleCase = (value: string): string =>
+ value.replaceAll(/[_-]+/g, ' ').replace(/\w\S*/g, (word) => word.charAt(0).toUpperCase() + word.slice(1));
+
+export const getModelTypeLabel = (type: ModelTaxonomyType): string =>
+ categoryByType.get(type)?.label ?? toTitleCase(type);
+
+export const getModelTypePluralLabel = (type: ModelTaxonomyType): string =>
+ categoryByType.get(type)?.pluralLabel ?? `${toTitleCase(type)} Models`;
+
+/** Sort rank of a category for grouped views; unknown types sort last. */
+export const getModelCategoryRank = (type: ModelTaxonomyType): number => {
+ const index = MODEL_CATEGORIES.findIndex((category) => category.type === type);
+
+ return index === -1 ? MODEL_CATEGORIES.length : index;
+};
+
+const BASE_LABELS: Record<string, string> = {
+ anima: 'Anima',
+ any: 'Any',
+ cogview4: 'CogView4',
+ external: 'External',
+ flux: 'FLUX',
+ flux2: 'FLUX.2',
+ 'qwen-image': 'Qwen Image',
+ 'sd-1': 'SD 1.x',
+ 'sd-2': 'SD 2.x',
+ 'sd-3': 'SD 3.x',
+ sdxl: 'SDXL',
+ 'sdxl-refiner': 'SDXL Refiner',
+ unknown: 'Unknown',
+ 'z-image': 'Z-Image',
+};
+
+export const getModelBaseLabel = (base: ModelBase): string => BASE_LABELS[base] ?? toTitleCase(base);
+
+/** Chakra color palette per base, so architecture is scannable at a glance. */
+const BASE_COLOR_PALETTES: Record<string, string> = {
+ anima: 'pink',
+ any: 'gray',
+ cogview4: 'red',
+ external: 'gray',
+ flux: 'yellow',
+ flux2: 'orange',
+ 'qwen-image': 'cyan',
+ 'sd-1': 'green',
+ 'sd-2': 'teal',
+ 'sd-3': 'purple',
+ sdxl: 'blue',
+ 'sdxl-refiner': 'blue',
+ unknown: 'gray',
+ 'z-image': 'pink',
+};
+
+export const getModelBaseColorPalette = (base: ModelBase): string => BASE_COLOR_PALETTES[base] ?? 'gray';
+
+const FORMAT_LABELS: Record<string, string> = {
+ bnb_quantized_int8b: 'BnB int8',
+ bnb_quantized_nf4b: 'BnB nf4',
+ checkpoint: 'Checkpoint',
+ diffusers: 'Diffusers',
+ embedding_file: 'Embedding File',
+ embedding_folder: 'Embedding Folder',
+ external_api: 'External API',
+ gguf_quantized: 'GGUF',
+ invokeai: 'InvokeAI',
+ lycoris: 'LyCORIS',
+ olive: 'Olive',
+ omi: 'OMI',
+ onnx: 'ONNX',
+ qwen3_encoder: 'Qwen3 Encoder',
+ qwen_vl_encoder: 'Qwen VL Encoder',
+ t5_encoder: 'T5 Encoder',
+ unknown: 'Unknown',
+};
+
+export const getModelFormatLabel = (format: ModelFileFormat): string => FORMAT_LABELS[format] ?? toTitleCase(format);
+
+/** Checkpoint→diffusers conversion is only supported for these bases. */
+export const isConvertibleToDiffusers = (model: ModelConfig): boolean =>
+ model.format === 'checkpoint' && model.type === 'main' && ['sd-1', 'sd-2', 'sdxl'].includes(model.base);
+
+const BYTE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB'] as const;
+
+export const formatBytes = (bytes: number | null | undefined): string => {
+ if (bytes === null || bytes === undefined || !Number.isFinite(bytes) || bytes < 0) {
+ return '—';
+ }
+
+ let value = bytes;
+ let unitIndex = 0;
+
+ while (value >= 1024 && unitIndex < BYTE_UNITS.length - 1) {
+ value /= 1024;
+ unitIndex += 1;
+ }
+
+ return `${unitIndex === 0 ? value : value.toFixed(1)} ${BYTE_UNITS[unitIndex]}`;
+};
+
+/** Human-readable source for an install job (string or structured source). */
+export const getInstallSourceLabel = (source: ModelInstallJob['source']): string => {
+ if (typeof source === 'string') {
+ return source;
+ }
+
+ return source.repo_id ?? source.url ?? source.path ?? JSON.stringify(source);
+};
diff --git a/invokeai/frontend/webv2/src/workbench/models/types.ts b/invokeai/frontend/webv2/src/workbench/models/types.ts
new file mode 100644
index 0000000000..edfef733b9
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/models/types.ts
@@ -0,0 +1,236 @@
+/**
+ * Contracts for the backend model manager (`/api/v2/models/*`). Shapes mirror
+ * the pydantic models in `invokeai/backend/model_manager` and
+ * `invokeai/app/services/model_install` (serialized as snake_case). Unions are
+ * kept open (`| (string & {})`) so new backend architectures appear in the UI
+ * without a frontend release — unknown values fall back to generic labels.
+ */
+
+/** Known model base architectures. Open union: new bases still render. */
+export type ModelBase =
+ | 'any'
+ | 'sd-1'
+ | 'sd-2'
+ | 'sd-3'
+ | 'sdxl'
+ | 'sdxl-refiner'
+ | 'flux'
+ | 'flux2'
+ | 'cogview4'
+ | 'qwen-image'
+ | 'z-image'
+ | 'anima'
+ | 'external'
+ | 'unknown'
+ | (string & {});
+
+/** Known model types. Open union: new types still render. */
+export type ModelTaxonomyType =
+ | 'main'
+ | 'vae'
+ | 'lora'
+ | 'control_lora'
+ | 'controlnet'
+ | 't2i_adapter'
+ | 'ip_adapter'
+ | 'embedding'
+ | 'clip_embed'
+ | 'clip_vision'
+ | 't5_encoder'
+ | 'qwen3_encoder'
+ | 'qwen_vl_encoder'
+ | 'siglip'
+ | 'spandrel_image_to_image'
+ | 'flux_redux'
+ | 'llava_onevision'
+ | 'text_llm'
+ | 'external_image_generator'
+ | 'onnx'
+ | 'unknown'
+ | (string & {});
+
+export type ModelFileFormat =
+ | 'checkpoint'
+ | 'diffusers'
+ | 'lycoris'
+ | 'omi'
+ | 'onnx'
+ | 'olive'
+ | 'embedding_file'
+ | 'embedding_folder'
+ | 'invokeai'
+ | 't5_encoder'
+ | 'qwen3_encoder'
+ | 'qwen_vl_encoder'
+ | 'bnb_quantized_int8b'
+ | 'bnb_quantized_nf4b'
+ | 'gguf_quantized'
+ | 'external_api'
+ | 'unknown'
+ | (string & {});
+
+export type PredictionType = 'epsilon' | 'v_prediction' | 'sample';
+
+/** Per-model defaults applied when the model is selected for generation. */
+export interface MainModelDefaultSettings {
+ vae?: string | null;
+ vae_precision?: 'fp16' | 'fp32' | null;
+ scheduler?: string | null;
+ steps?: number | null;
+ cfg_scale?: number | null;
+ cfg_rescale_multiplier?: number | null;
+ width?: number | null;
+ height?: number | null;
+ guidance?: number | null;
+ fp8_storage?: boolean | null;
+}
+
+export interface LoraModelDefaultSettings {
+ weight?: number | null;
+}
+
+export interface ControlAdapterDefaultSettings {
+ preprocessor?: string | null;
+ fp8_storage?: boolean | null;
+}
+
+export type AnyModelDefaultSettings = MainModelDefaultSettings &
+ LoraModelDefaultSettings &
+ ControlAdapterDefaultSettings;
+
+/**
+ * A model config record. This is the union of fields across all backend config
+ * classes; fields not applicable to a given type/format are absent.
+ */
+export interface ModelConfig {
+ key: string;
+ hash: string;
+ path: string;
+ file_size: number;
+ name: string;
+ description?: string | null;
+ source: string;
+ source_type: 'path' | 'url' | 'hf_repo_id' | (string & {});
+ source_url?: string | null;
+ cover_image?: string | null;
+ base: ModelBase;
+ type: ModelTaxonomyType;
+ format: ModelFileFormat;
+ variant?: string | null;
+ prediction_type?: PredictionType | null;
+ upcast_attention?: boolean;
+ config_path?: string | null;
+ trigger_phrases?: string[] | null;
+ default_settings?: AnyModelDefaultSettings | null;
+ submodels?: Record<string, unknown> | null;
+ [key: string]: unknown;
+}
+
+/** Body for PATCH `/api/v2/models/i/{key}` — all fields optional. */
+export interface ModelRecordChanges {
+ name?: string;
+ description?: string | null;
+ source_url?: string | null;
+ base?: ModelBase;
+ type?: ModelTaxonomyType;
+ format?: ModelFileFormat;
+ variant?: string | null;
+ prediction_type?: PredictionType | null;
+ upcast_attention?: boolean;
+ config_path?: string | null;
+ trigger_phrases?: string[] | null;
+ default_settings?: AnyModelDefaultSettings | null;
+}
+
+export type ModelInstallStatus =
+ | 'waiting'
+ | 'downloading'
+ | 'downloads_done'
+ | 'running'
+ | 'paused'
+ | 'completed'
+ | 'error'
+ | 'cancelled';
+
+export interface ModelInstallDownloadPart {
+ source?: string;
+ url?: string;
+ local_path?: string;
+ bytes: number;
+ total_bytes: number;
+ status?: string;
+}
+
+/** A model install job as returned by `/api/v2/models/install`. */
+export interface ModelInstallJob {
+ id: number;
+ status: ModelInstallStatus;
+ /** Local path, URL, or HF repo id — may be a string or a structured source. */
+ source: string | { repo_id?: string; url?: string; path?: string; type?: string; [key: string]: unknown };
+ error?: string | null;
+ error_reason?: string | null;
+ error_traceback?: string | null;
+ bytes?: number;
+ total_bytes?: number;
+ local_path?: string | null;
+ inplace?: boolean;
+ config_in?: ModelRecordChanges | null;
+ config_out?: ModelConfig | null;
+ download_parts?: ModelInstallDownloadPart[];
+ [key: string]: unknown;
+}
+
+/** A model file found by `/api/v2/models/scan_folder`. */
+export interface FoundModel {
+ path: string;
+ is_installed: boolean;
+}
+
+/** Result of `/api/v2/models/hugging_face` metadata lookup. */
+export interface HuggingFaceModels {
+ urls: string[] | null;
+ is_diffusers: boolean;
+}
+
+export interface StarterModel {
+ name: string;
+ description: string;
+ source: string;
+ base: ModelBase;
+ type: ModelTaxonomyType;
+ format?: ModelFileFormat | null;
+ variant?: string | null;
+ is_installed: boolean;
+ dependencies?: Omit<StarterModel, 'dependencies'>[] | null;
+ previous_names?: string[];
+}
+
+export interface StarterModelBundle {
+ name: string;
+ models: StarterModel[];
+}
+
+export interface StarterModelResponse {
+ starter_models: StarterModel[];
+ starter_bundles: Record<string, StarterModelBundle>;
+}
+
+export type HFTokenStatus = 'valid' | 'invalid' | 'unknown';
+
+/** A model directory on disk with no matching database record. */
+export interface OrphanedModelInfo {
+ path: string;
+ absolute_path: string;
+ files: string[];
+ size_bytes: number;
+}
+
+export interface BulkDeleteModelsResponse {
+ deleted: string[];
+ failed: { key: string; error: string }[];
+}
+
+export interface DeleteOrphanedModelsResponse {
+ deleted: string[];
+ errors: Record<string, string>;
+}
diff --git a/invokeai/frontend/webv2/src/workbench/models/uiStore.ts b/invokeai/frontend/webv2/src/workbench/models/uiStore.ts
new file mode 100644
index 0000000000..3f4b866e55
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/models/uiStore.ts
@@ -0,0 +1,97 @@
+import { createExternalStore } from '../externalStore';
+import { DEFAULT_LIBRARY_FILTERS, type ModelLibraryFilters } from './library';
+import type { FoundModel } from './types';
+
+/**
+ * Session-lived UI state for the model manager. Widget views unmount whenever
+ * the user switches tabs, regions, or center views; keeping selection,
+ * filters, and in-progress source forms here means nothing is forgotten when
+ * they come back. Deliberately not persisted to localStorage — it resets with
+ * the page, like a scroll position.
+ */
+
+export type ModelsCenterTab = 'library' | 'add' | 'queue';
+export type AddModelsTab = 'starter' | 'url' | 'huggingface' | 'scan' | 'keys';
+
+/** A resolved HuggingFace checkpoint-repo lookup, kept across tab switches. */
+export interface HFLookupState {
+ repo: string;
+ urls: string[];
+}
+
+export interface ModelsUiSnapshot {
+ centerTab: ModelsCenterTab;
+ addTab: AddModelsTab;
+ /** Model focused in the center library's detail pane. */
+ activeModelKey: string | null;
+ /** Model drilled into from the side panel. */
+ panelModelKey: string | null;
+ selectedKeys: ReadonlySet<string>;
+ filters: ModelLibraryFilters;
+ /** Last folder-scan query and its results, kept across tab switches. */
+ scan: { path: string; results: FoundModel[] } | null;
+ /** Last HuggingFace repo lookup, kept across tab switches. */
+ hfLookup: HFLookupState | null;
+ /** Scroll offsets per library-list instance, restored on remount. */
+ libraryScrollOffsets: Record<string, number>;
+}
+
+const store = createExternalStore<ModelsUiSnapshot>({
+ activeModelKey: null,
+ addTab: 'starter',
+ centerTab: 'library',
+ filters: DEFAULT_LIBRARY_FILTERS,
+ hfLookup: null,
+ libraryScrollOffsets: {},
+ panelModelKey: null,
+ scan: null,
+ selectedKeys: new Set(),
+});
+
+export const updateModelsUi = (next: Partial<ModelsUiSnapshot>): void => {
+ store.patchSnapshot(next);
+};
+
+export const toggleModelSelection = (key: string): void => {
+ const selectedKeys = new Set(store.getSnapshot().selectedKeys);
+
+ if (selectedKeys.has(key)) {
+ selectedKeys.delete(key);
+ } else {
+ selectedKeys.add(key);
+ }
+
+ updateModelsUi({ selectedKeys });
+};
+
+/** Drop deleted models from selection/active slots so stale keys never linger. */
+export const pruneModelsUiKeys = (deletedKeys: string[]): void => {
+ const { activeModelKey, panelModelKey, selectedKeys } = store.getSnapshot();
+ const deleted = new Set(deletedKeys);
+
+ updateModelsUi({
+ activeModelKey: activeModelKey !== null && deleted.has(activeModelKey) ? null : activeModelKey,
+ panelModelKey: panelModelKey !== null && deleted.has(panelModelKey) ? null : panelModelKey,
+ selectedKeys: new Set([...selectedKeys].filter((key) => !deleted.has(key))),
+ });
+};
+
+/** Jump the center view to a specific model manager tab (used by the panel). */
+export const openModelsCenterTab = (centerTab: ModelsCenterTab, addTab?: AddModelsTab): void => {
+ updateModelsUi({ centerTab, ...(addTab ? { addTab } : {}) });
+};
+
+export const saveLibraryScrollOffset = (instanceId: string, offset: number): void => {
+ const snapshot = store.getSnapshot();
+
+ // Silent: scroll offsets are read on mount, never subscribed to.
+ store.setSnapshotSilently({
+ ...snapshot,
+ libraryScrollOffsets: { ...snapshot.libraryScrollOffsets, [instanceId]: offset },
+ });
+};
+
+export const getLibraryScrollOffset = (instanceId: string): number =>
+ store.getSnapshot().libraryScrollOffsets[instanceId] ?? 0;
+
+export const useModelsUi = (): ModelsUiSnapshot => store.useSnapshot();
diff --git a/invokeai/frontend/webv2/src/workbench/models/useZodForm.ts b/invokeai/frontend/webv2/src/workbench/models/useZodForm.ts
new file mode 100644
index 0000000000..f0e8568850
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/models/useZodForm.ts
@@ -0,0 +1,119 @@
+import { useCallback, useRef, useState } from 'react';
+import type { z } from 'zod';
+
+/**
+ * Minimal zod-backed form state. Validation runs on submit; editing a field
+ * that shows an error clears that error immediately (optimistic — the next
+ * submit re-validates), so users are not nagged mid-correction.
+ */
+
+export interface ZodFormField<Value> {
+ value: Value;
+ error: string | null;
+}
+
+export interface ZodForm<Schema extends z.ZodType<Record<string, unknown>>> {
+ values: z.infer<Schema>;
+ errors: Partial<Record<keyof z.infer<Schema>, string>>;
+ /** Form-level error (refinements that do not map to a single field). */
+ formError: string | null;
+ isSubmitting: boolean;
+ setValue: <Key extends keyof z.infer<Schema>>(key: Key, value: z.infer<Schema>[Key]) => void;
+ setValues: (values: z.infer<Schema>) => void;
+ /** Validate and run `onValid`; submission errors land in `formError`. */
+ handleSubmit: (onValid: (values: z.infer<Schema>) => Promise<void> | void) => Promise<void>;
+ reset: (values?: z.infer<Schema>) => void;
+}
+
+export const useZodForm = <Schema extends z.ZodType<Record<string, unknown>>>(
+ schema: Schema,
+ initialValues: z.infer<Schema>
+): ZodForm<Schema> => {
+ type Values = z.infer<Schema>;
+
+ const [values, setValuesState] = useState<Values>(initialValues);
+ const initialValuesRef = useRef(initialValues);
+ const [errors, setErrors] = useState<Partial<Record<keyof Values, string>>>({});
+ const [formError, setFormError] = useState<string | null>(null);
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const validate = useCallback(
+ (candidate: Values): { ok: true; data: Values } | { ok: false } => {
+ const result = schema.safeParse(candidate);
+
+ if (result.success) {
+ setErrors({});
+ setFormError(null);
+
+ return { data: result.data as Values, ok: true };
+ }
+
+ const nextErrors: Partial<Record<keyof Values, string>> = {};
+ let nextFormError: string | null = null;
+
+ for (const issue of result.error.issues) {
+ const key = issue.path[0];
+
+ if (typeof key === 'string' && nextErrors[key as keyof Values] === undefined) {
+ nextErrors[key as keyof Values] = issue.message;
+ } else if (issue.path.length === 0 && nextFormError === null) {
+ nextFormError = issue.message;
+ }
+ }
+
+ setErrors(nextErrors);
+ setFormError(nextFormError);
+
+ return { ok: false };
+ },
+ [schema]
+ );
+
+ const setValue = useCallback(<Key extends keyof Values>(key: Key, value: Values[Key]) => {
+ setValuesState((currentValues) => ({ ...currentValues, [key]: value }));
+ // Editing an errored field clears its error; the next submit re-validates.
+ setErrors((currentErrors) => {
+ if (currentErrors[key] === undefined) {
+ return currentErrors;
+ }
+
+ const { [key]: _removed, ...rest } = currentErrors;
+
+ return rest as Partial<Record<keyof Values, string>>;
+ });
+ }, []);
+
+ const setValues = useCallback((nextValues: Values) => {
+ setValuesState(nextValues);
+ }, []);
+
+ const reset = useCallback((nextValues?: Values) => {
+ setValuesState(nextValues ?? initialValuesRef.current);
+ setErrors({});
+ setFormError(null);
+ }, []);
+
+ const handleSubmit = useCallback(
+ async (onValid: (validValues: Values) => Promise<void> | void) => {
+ const result = validate(values);
+
+ if (!result.ok) {
+ return;
+ }
+
+ setIsSubmitting(true);
+ setFormError(null);
+
+ try {
+ await onValid(result.data);
+ } catch (error) {
+ setFormError(error instanceof Error ? error.message : 'Something went wrong.');
+ } finally {
+ setIsSubmitting(false);
+ }
+ },
+ [validate, values]
+ );
+
+ return { errors, formError, handleSubmit, isSubmitting, reset, setValue, setValues, values };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.ts
index 7c75f49b7f..9b21e99d9a 100644
--- a/invokeai/frontend/webv2/src/workbench/types.ts
+++ b/invokeai/frontend/webv2/src/workbench/types.ts
@@ -2,7 +2,7 @@ import type { ComponentType } from 'react';
export type LayoutPresetId = 'canvas-default' | 'gallery' | 'workflow' | 'linear' | 'model-manager';
-export type CenterViewId = 'canvas' | 'gallery' | 'preview' | 'workflow';
+export type CenterViewId = 'canvas' | 'gallery' | 'preview' | 'workflow' | 'models';
export type GraphId = string;
@@ -15,6 +15,7 @@ export type WidgetId =
| 'history-controls'
| 'layout-actions'
| 'layers'
+ | 'models'
| 'notifications'
| 'preview'
| 'queue'
diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts b/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts
index 11bbc10689..38c73d8cb2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts
@@ -8,6 +8,7 @@ import { generateWidgetManifest } from './widgets/generate';
import { historyControlsWidgetManifest } from './widgets/history-controls';
import { layoutActionsWidgetManifest } from './widgets/layout-actions';
import { layersWidgetManifest } from './widgets/layers';
+import { modelsWidgetManifest } from './widgets/models';
import { notificationsWidgetManifest } from './widgets/notifications';
import { previewWidgetManifest } from './widgets/preview';
import { queueWidgetManifest } from './widgets/queue';
@@ -23,6 +24,7 @@ const firstPartyWidgetManifests: WidgetManifest[] = [
galleryWidgetManifest,
previewWidgetManifest,
layersWidgetManifest,
+ modelsWidgetManifest,
queueWidgetManifest,
notificationsWidgetManifest,
serverStatusWidgetManifest,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/AddModelsView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/AddModelsView.tsx
new file mode 100644
index 0000000000..378284c6f7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/AddModelsView.tsx
@@ -0,0 +1,60 @@
+import { Stack } from '@chakra-ui/react';
+
+import { Scrollable } from '../../components/ui/Scrollable';
+import { Tabs } from '../../components/ui/Tabs';
+import { updateModelsUi, useModelsUi, type AddModelsTab } from '../../models/uiStore';
+import { ApiKeysSection } from './ApiKeysSection';
+import { HuggingFaceTab } from './HuggingFaceTab';
+import { ScanFolderTab } from './ScanFolderTab';
+import { StarterModelsTab } from './StarterModelsTab';
+import { UrlInstallTab } from './UrlInstallTab';
+import { FolderSearchIcon, KeyIcon, LinkIcon, StarIcon } from 'lucide-react';
+import { SiHuggingface } from 'react-icons/si';
+
+/**
+ * Every way to acquire a model, one tab per source kind, plus credentials.
+ * The active tab lives in the models UI store so it survives navigation.
+ */
+export const AddModelsView = () => {
+ const { addTab } = useModelsUi();
+
+ return (
+ <Stack gap="3" h="full" minH="0">
+ <Tabs.Root
+ size="sm"
+ value={addTab}
+ onValueChange={(event) => updateModelsUi({ addTab: event.value as AddModelsTab })}
+ >
+ <Tabs.List>
+ <Tabs.Trigger fontSize="xs" value="starter">
+ <StarIcon size={12} />
+ Starter Models
+ </Tabs.Trigger>
+ <Tabs.Trigger fontSize="xs" value="url">
+ <LinkIcon size={12} />
+ URL / Local Path
+ </Tabs.Trigger>
+ <Tabs.Trigger fontSize="xs" value="huggingface">
+ <SiHuggingface size={12} />
+ HuggingFace
+ </Tabs.Trigger>
+ <Tabs.Trigger fontSize="xs" value="scan">
+ <FolderSearchIcon size={12} />
+ Scan Folder
+ </Tabs.Trigger>
+ <Tabs.Trigger fontSize="xs" value="keys">
+ <KeyIcon size={12} />
+ API Keys
+ </Tabs.Trigger>
+ </Tabs.List>
+ </Tabs.Root>
+ <Scrollable flex="1" label="Add models" minH="0" pr="1">
+ {addTab === 'starter' ? <StarterModelsTab /> : null}
+ {addTab === 'url' ? <UrlInstallTab /> : null}
+ {addTab === 'huggingface' ? <HuggingFaceTab /> : null}
+ {addTab === 'scan' ? <ScanFolderTab /> : null}
+ {addTab === 'keys' ? <ApiKeysSection /> : null}
+ </Scrollable>
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/ApiKeysSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/ApiKeysSection.tsx
new file mode 100644
index 0000000000..f03c7c0132
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/ApiKeysSection.tsx
@@ -0,0 +1,338 @@
+import { Badge, Flex, Grid, HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';
+import { HexagonIcon } from 'lucide-react';
+import { useEffect, useState, type ElementType } from 'react';
+import { SiAlibabacloud, SiBytedance, SiGooglegemini, SiHuggingface, SiOpenai } from 'react-icons/si';
+
+import { Button } from '../../components/ui/Button';
+import { clearCivitaiApiKey, getCivitaiApiKey, setCivitaiApiKey } from '../../models/apiKeys';
+import {
+ getExternalProviderConfigs,
+ getHFTokenStatus,
+ resetExternalProviderConfig,
+ resetHFToken,
+ setExternalProviderConfig,
+ setHFToken,
+ type ExternalProviderConfig,
+} from '../../models/api';
+import type { HFTokenStatus } from '../../models/types';
+import { useNotify } from '../../useNotify';
+
+/**
+ * Credentials for every model source, as one uniform grid of key cards:
+ * HuggingFace (server-stored, verified), Civitai (browser-local), and the
+ * external image providers (server config). Each card shares the same
+ * edit/display anatomy: icon, status, prefix-hinted input, save/clear.
+ */
+export const ApiKeysSection = () => {
+ const notify = useNotify();
+
+ return (
+ <Stack gap="3">
+ <Text color="fg.subtle" fontSize="2xs">
+ Keys are used when installing protected models and when generating with external API models.
+ </Text>
+ <Grid gap="2.5" templateColumns="repeat(auto-fill, minmax(19rem, 1fr))">
+ <HuggingFaceKeyCard onError={notify.error} />
+ <CivitaiKeyCard onError={(message) => notify.error('Civitai key', message)} />
+ <ExternalProviderKeyCards onError={notify.error} />
+ </Grid>
+ </Stack>
+ );
+};
+
+interface KeyStatusBadge {
+ label: string;
+ palette: string;
+}
+
+/** The shared card: identical anatomy whether the key is set or not. */
+const ApiKeyCard = ({
+ description,
+ icon,
+ isLoading = false,
+ onClear,
+ onError,
+ onSave,
+ placeholder,
+ status,
+ title,
+}: {
+ description: string;
+ icon: ElementType;
+ isLoading?: boolean;
+ /** Absent until a key exists; clears the stored key. */
+ onClear?: () => Promise<void> | void;
+ /** Save/clear failures (network, backend rejection) land here. */
+ onError: (message: string) => void;
+ onSave: (key: string) => Promise<void> | void;
+ /** Hint at the expected shape, e.g. "hf_…" or "sk-…". */
+ placeholder: string;
+ status: KeyStatusBadge | null;
+ title: string;
+}) => {
+ const [draft, setDraft] = useState('');
+ const [isBusy, setIsBusy] = useState(false);
+
+ const runAction = async (action: () => Promise<void> | void): Promise<boolean> => {
+ setIsBusy(true);
+
+ try {
+ await action();
+
+ return true;
+ } catch (error) {
+ onError(error instanceof Error ? error.message : 'Something went wrong.');
+
+ return false;
+ } finally {
+ setIsBusy(false);
+ }
+ };
+
+ const handleSave = async () => {
+ const key = draft.trim();
+
+ if (key.length === 0) {
+ return;
+ }
+
+ // Keep the draft on failure so the key can be corrected and retried.
+ if (await runAction(() => onSave(key))) {
+ setDraft('');
+ }
+ };
+
+ return (
+ <Stack bg="bg.surface" borderColor="border.subtle" borderWidth="1px" gap="2.5" p="3" rounded="lg">
+ <HStack align="start" gap="2.5">
+ <Flex
+ align="center"
+ bg="bg.panel"
+ borderColor="border.subtle"
+ borderWidth="1px"
+ boxSize="8"
+ color="fg.muted"
+ flexShrink={0}
+ justify="center"
+ rounded="md"
+ >
+ <Icon as={icon} boxSize="4" />
+ </Flex>
+ <Stack flex="1" gap="0" minW="0">
+ <HStack gap="1.5">
+ <Text fontSize="xs" fontWeight="700" truncate>
+ {title}
+ </Text>
+ {status ? (
+ <Badge colorPalette={status.palette} flexShrink={0} fontSize="2xs" size="sm" variant="surface">
+ {status.label}
+ </Badge>
+ ) : null}
+ </HStack>
+ <Text color="fg.subtle" fontSize="2xs" lineClamp={2}>
+ {description}
+ </Text>
+ </Stack>
+ </HStack>
+ <HStack gap="1.5">
+ <Input
+ aria-label={`${title} API key`}
+ disabled={isLoading}
+ placeholder={placeholder}
+ size="xs"
+ type="password"
+ value={draft}
+ onChange={(event) => setDraft(event.currentTarget.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ void handleSave();
+ }
+ }}
+ />
+ <Button
+ disabled={draft.trim().length === 0 || isLoading}
+ loading={isBusy && draft.trim().length > 0}
+ size="xs"
+ variant="solid"
+ onClick={() => void handleSave()}
+ >
+ Save
+ </Button>
+ {onClear ? (
+ <Button disabled={isBusy || isLoading} size="sm" variant="ghost" onClick={() => void runAction(onClear)}>
+ Clear
+ </Button>
+ ) : null}
+ </HStack>
+ </Stack>
+ );
+};
+
+const HF_STATUS_BADGES: Record<HFTokenStatus, KeyStatusBadge> = {
+ invalid: { label: 'Invalid', palette: 'red' },
+ unknown: { label: 'Not set', palette: 'gray' },
+ valid: { label: 'Valid', palette: 'green' },
+};
+
+const HuggingFaceKeyCard = ({ onError }: { onError: (title: string, message: string) => void }) => {
+ const [status, setStatus] = useState<HFTokenStatus | null>(null);
+
+ useEffect(() => {
+ let isStale = false;
+
+ getHFTokenStatus()
+ .then((tokenStatus) => {
+ if (!isStale) {
+ setStatus(tokenStatus);
+ }
+ })
+ .catch(() => {
+ if (!isStale) {
+ setStatus('unknown');
+ }
+ });
+
+ return () => {
+ isStale = true;
+ };
+ }, []);
+
+ return (
+ <ApiKeyCard
+ description="For gated repos like FLUX. Stored on the InvokeAI server and verified with HuggingFace."
+ icon={SiHuggingface}
+ isLoading={status === null}
+ placeholder="hf_…"
+ status={status ? HF_STATUS_BADGES[status] : null}
+ title="HuggingFace"
+ onError={(message) => onError('HuggingFace token', message)}
+ onClear={
+ status === 'valid' || status === 'invalid'
+ ? async () => {
+ setStatus(await resetHFToken());
+ }
+ : undefined
+ }
+ onSave={async (key) => {
+ const nextStatus = await setHFToken(key);
+
+ setStatus(nextStatus);
+
+ if (nextStatus === 'invalid') {
+ onError('HuggingFace token', 'HuggingFace rejected this token. Check that it has read access.');
+ }
+ }}
+ />
+ );
+};
+
+const CivitaiKeyCard = ({ onError }: { onError: (message: string) => void }) => {
+ const [hasKey, setHasKey] = useState(() => getCivitaiApiKey() !== null);
+
+ return (
+ <ApiKeyCard
+ description="Attached automatically when installing civitai.com models that require login. Stored in this browser only."
+ icon={HexagonIcon}
+ placeholder="32-character key from civitai.com/user/account"
+ status={hasKey ? { label: 'Saved', palette: 'green' } : { label: 'Not set', palette: 'gray' }}
+ title="Civitai"
+ onError={onError}
+ onClear={
+ hasKey
+ ? () => {
+ clearCivitaiApiKey();
+ setHasKey(false);
+ }
+ : undefined
+ }
+ onSave={(key) => {
+ setCivitaiApiKey(key);
+ setHasKey(true);
+ }}
+ />
+ );
+};
+
+const EXTERNAL_PROVIDER_PRESENTATION: Record<string, { title: string; icon: ElementType; placeholder: string }> = {
+ alibabacloud: { icon: SiAlibabacloud, placeholder: 'sk-…', title: 'Alibaba Cloud (Qwen)' },
+ gemini: { icon: SiGooglegemini, placeholder: 'AIza…', title: 'Google Gemini' },
+ openai: { icon: SiOpenai, placeholder: 'sk-…', title: 'OpenAI' },
+ seedream: { icon: SiBytedance, placeholder: 'API key from BytePlus console', title: 'Seedream' },
+};
+
+const ExternalProviderKeyCards = ({ onError }: { onError: (title: string, message: string) => void }) => {
+ const [configs, setConfigs] = useState<ExternalProviderConfig[] | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+
+ useEffect(() => {
+ let isStale = false;
+
+ getExternalProviderConfigs()
+ .then((providerConfigs) => {
+ if (!isStale) {
+ setConfigs(providerConfigs);
+ }
+ })
+ .catch((error: unknown) => {
+ if (!isStale) {
+ setConfigs([]);
+ setLoadError(error instanceof Error ? error.message : 'Failed to load external providers.');
+ }
+ });
+
+ return () => {
+ isStale = true;
+ };
+ }, []);
+
+ const replaceConfig = (next: ExternalProviderConfig) => {
+ setConfigs((current) => (current ?? []).map((config) => (config.provider_id === next.provider_id ? next : config)));
+ };
+
+ if (loadError) {
+ return (
+ <Text color="red.400" fontSize="2xs">
+ External providers unavailable: {loadError}
+ </Text>
+ );
+ }
+
+ return (
+ <>
+ {(configs ?? []).map((config) => {
+ const presentation = EXTERNAL_PROVIDER_PRESENTATION[config.provider_id] ?? {
+ icon: HexagonIcon,
+ placeholder: 'API key',
+ title: config.provider_id,
+ };
+
+ return (
+ <ApiKeyCard
+ key={config.provider_id}
+ description="External image generator. The key is stored in the InvokeAI server config and used by external API models."
+ icon={presentation.icon}
+ placeholder={presentation.placeholder}
+ status={
+ config.api_key_configured
+ ? { label: 'Configured', palette: 'green' }
+ : { label: 'Not set', palette: 'gray' }
+ }
+ title={presentation.title}
+ onError={(message) => onError(presentation.title, message)}
+ onClear={
+ config.api_key_configured
+ ? async () => {
+ replaceConfig(await resetExternalProviderConfig(config.provider_id));
+ }
+ : undefined
+ }
+ onSave={async (key) => {
+ replaceConfig(await setExternalProviderConfig(config.provider_id, { api_key: key }));
+ }}
+ />
+ );
+ })}
+ </>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/DefaultSettingsSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/DefaultSettingsSection.tsx
new file mode 100644
index 0000000000..57da397ee1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/DefaultSettingsSection.tsx
@@ -0,0 +1,363 @@
+import { Grid, HStack, Icon, NativeSelect, NumberInput, Stack, Switch, Text } from '@chakra-ui/react';
+import { MoveHorizontalIcon } from 'lucide-react';
+import { useMemo, useState, type ReactNode } from 'react';
+
+import { Button } from '../../components/ui/Button';
+import { FieldLabel } from '../../components/ui/Field';
+import { updateModel } from '../../models/api';
+import { replaceModelInStore } from '../../models/modelsStore';
+import { loraDefaultSettingsSchema, mainDefaultSettingsSchema } from '../../models/schemas';
+import type { AnyModelDefaultSettings, ModelConfig } from '../../models/types';
+
+/**
+ * Per-model generation defaults ("use these settings when this model is
+ * selected"). Every field is individually toggleable: off = inherit the app
+ * default (stored as null). Validation runs through zod on save.
+ */
+
+const SCHEDULERS = [
+ 'ddim',
+ 'ddpm',
+ 'deis',
+ 'deis_k',
+ 'dpmpp_2s',
+ 'dpmpp_2s_k',
+ 'dpmpp_2m',
+ 'dpmpp_2m_k',
+ 'dpmpp_2m_sde',
+ 'dpmpp_2m_sde_k',
+ 'dpmpp_3m',
+ 'dpmpp_3m_k',
+ 'dpmpp_sde',
+ 'dpmpp_sde_k',
+ 'euler',
+ 'euler_k',
+ 'euler_a',
+ 'heun',
+ 'heun_k',
+ 'kdpm_2',
+ 'kdpm_2_k',
+ 'kdpm_2_a',
+ 'kdpm_2_a_k',
+ 'lcm',
+ 'lms',
+ 'lms_k',
+ 'pndm',
+ 'tcd',
+ 'unipc',
+ 'unipc_k',
+];
+
+const CONTROL_ADAPTER_TYPES = new Set(['controlnet', 't2i_adapter', 'control_lora']);
+
+const PREPROCESSORS = [
+ 'canny_edge_detection',
+ 'color_map',
+ 'content_shuffle',
+ 'depth_anything_depth_estimation',
+ 'dw_openpose_detection',
+ 'hed_edge_detection',
+ 'lineart_anime_edge_detection',
+ 'lineart_edge_detection',
+ 'mediapipe_face_detection',
+ 'mlsd_detection',
+ 'normal_map',
+ 'pidi_edge_detection',
+ 'tile',
+];
+
+export const supportsDefaultSettings = (model: ModelConfig): boolean =>
+ model.type === 'main' || model.type === 'lora' || CONTROL_ADAPTER_TYPES.has(model.type);
+
+interface FieldSpec {
+ key: keyof AnyModelDefaultSettings;
+ label: string;
+ /** Render the control; disabled (showing the inherited value) until customized. */
+ control: (value: unknown, setValue: (value: unknown) => void, disabled: boolean) => ReactNode;
+ /** Value used when the toggle is switched on; also previewed while off. */
+ defaultValue: unknown;
+ /** What applies while the toggle is off, e.g. "App default: 30 steps". */
+ inheritLabel: string;
+}
+
+const numberControl =
+ (props: { max?: number; min?: number; step?: number }) =>
+ (value: unknown, setValue: (value: unknown) => void, disabled: boolean) => (
+ <NumberInput.Root
+ disabled={disabled}
+ max={props.max}
+ min={props.min}
+ position="relative"
+ size="sm"
+ step={props.step ?? 1}
+ value={typeof value === 'number' ? String(value) : ''}
+ w="full"
+ onValueChange={(details) => {
+ // Empty/partial input is transient; only commit finite numbers so the
+ // field never silently flips back to "off".
+ if (Number.isFinite(details.valueAsNumber)) {
+ setValue(details.valueAsNumber);
+ }
+ }}
+ >
+ <NumberInput.Control />
+ {/* Drag horizontally on the handle to scrub the value. */}
+ <NumberInput.Scrubber
+ alignItems="center"
+ bottom="0"
+ cursor="ew-resize"
+ display="flex"
+ left="2"
+ position="absolute"
+ top="0"
+ zIndex={1}
+ >
+ <Icon as={MoveHorizontalIcon} boxSize="3" color="fg.subtle" />
+ </NumberInput.Scrubber>
+ <NumberInput.Input ps="7" />
+ </NumberInput.Root>
+ );
+
+const selectControl =
+ (options: string[]) => (value: unknown, setValue: (value: unknown) => void, disabled: boolean) => (
+ <NativeSelect.Root disabled={disabled} size="sm">
+ <NativeSelect.Field
+ value={typeof value === 'string' ? value : ''}
+ onChange={(event) => setValue(event.currentTarget.value)}
+ >
+ {options.map((option) => (
+ <option key={option} value={option}>
+ {option}
+ </option>
+ ))}
+ </NativeSelect.Field>
+ <NativeSelect.Indicator />
+ </NativeSelect.Root>
+ );
+
+const MAIN_FIELDS: FieldSpec[] = [
+ {
+ control: selectControl(SCHEDULERS),
+ defaultValue: 'euler_a',
+ inheritLabel: 'App default: euler_a',
+ key: 'scheduler',
+ label: 'Scheduler',
+ },
+ {
+ control: numberControl({ max: 10000, min: 1 }),
+ defaultValue: 30,
+ inheritLabel: 'App default: 30',
+ key: 'steps',
+ label: 'Steps',
+ },
+ {
+ control: numberControl({ max: 200, min: 1, step: 0.5 }),
+ defaultValue: 7,
+ inheritLabel: 'App default: 7',
+ key: 'cfg_scale',
+ label: 'CFG Scale',
+ },
+ {
+ control: numberControl({ max: 0.99, min: 0, step: 0.05 }),
+ defaultValue: 0,
+ inheritLabel: 'App default: 0 (off)',
+ key: 'cfg_rescale_multiplier',
+ label: 'CFG Rescale',
+ },
+ {
+ control: numberControl({ max: 20, min: 1, step: 0.5 }),
+ defaultValue: 4,
+ inheritLabel: 'Uses the generator default',
+ key: 'guidance',
+ label: 'Guidance',
+ },
+ {
+ control: numberControl({ max: 8192, min: 64, step: 8 }),
+ defaultValue: 1024,
+ inheritLabel: 'App default: 1024',
+ key: 'width',
+ label: 'Width',
+ },
+ {
+ control: numberControl({ max: 8192, min: 64, step: 8 }),
+ defaultValue: 1024,
+ inheritLabel: 'App default: 1024',
+ key: 'height',
+ label: 'Height',
+ },
+ {
+ control: selectControl(['fp16', 'fp32']),
+ defaultValue: 'fp16',
+ inheritLabel: 'App default: fp16',
+ key: 'vae_precision',
+ label: 'VAE Precision',
+ },
+];
+
+const LORA_FIELDS: FieldSpec[] = [
+ {
+ control: numberControl({ max: 10, min: -10, step: 0.05 }),
+ defaultValue: 0.75,
+ inheritLabel: 'App default: 0.75',
+ key: 'weight',
+ label: 'Weight',
+ },
+];
+
+const CONTROL_ADAPTER_FIELDS: FieldSpec[] = [
+ {
+ control: selectControl(PREPROCESSORS),
+ defaultValue: 'canny_edge_detection',
+ inheritLabel: 'Chosen automatically per image',
+ key: 'preprocessor',
+ label: 'Preprocessor',
+ },
+];
+
+const getFieldsForModel = (model: ModelConfig): FieldSpec[] => {
+ if (model.type === 'main') {
+ return MAIN_FIELDS;
+ }
+
+ if (model.type === 'lora') {
+ return LORA_FIELDS;
+ }
+
+ return CONTROL_ADAPTER_FIELDS;
+};
+
+const validateDefaults = (model: ModelConfig, settings: AnyModelDefaultSettings): string | null => {
+ if (model.type === 'main') {
+ const result = mainDefaultSettingsSchema.safeParse({
+ cfgRescaleMultiplier: settings.cfg_rescale_multiplier ?? null,
+ cfgScale: settings.cfg_scale ?? null,
+ guidance: settings.guidance ?? null,
+ height: settings.height ?? null,
+ scheduler: settings.scheduler ?? null,
+ steps: settings.steps ?? null,
+ vaePrecision: settings.vae_precision ?? null,
+ width: settings.width ?? null,
+ });
+
+ return result.success ? null : (result.error.issues[0]?.message ?? 'Invalid default settings.');
+ }
+
+ if (model.type === 'lora') {
+ const result = loraDefaultSettingsSchema.safeParse({ weight: settings.weight ?? null });
+
+ return result.success ? null : (result.error.issues[0]?.message ?? 'Invalid default settings.');
+ }
+
+ return null;
+};
+
+export const DefaultSettingsSection = ({
+ model,
+ onError,
+ onSaved,
+}: {
+ model: ModelConfig;
+ onError: (message: string) => void;
+ onSaved: () => void;
+}) => {
+ const fields = useMemo(() => getFieldsForModel(model), [model]);
+ const [settings, setSettings] = useState<AnyModelDefaultSettings>(() => ({ ...model.default_settings }));
+ const [error, setError] = useState<string | null>(null);
+ const [isSaving, setIsSaving] = useState(false);
+
+ const isDirty = useMemo(() => {
+ const saved = model.default_settings ?? {};
+
+ return fields.some((field) => (settings[field.key] ?? null) !== (saved[field.key] ?? null));
+ }, [fields, model.default_settings, settings]);
+
+ const setFieldValue = (key: keyof AnyModelDefaultSettings, value: unknown) => {
+ setSettings((current) => ({ ...current, [key]: value as never }));
+ setError(null);
+ };
+
+ const handleSave = async () => {
+ const validationError = validateDefaults(model, settings);
+
+ if (validationError) {
+ setError(validationError);
+ return;
+ }
+
+ setIsSaving(true);
+
+ try {
+ replaceModelInStore(await updateModel(model.key, { default_settings: settings }));
+ onSaved();
+ } catch (saveError) {
+ onError(saveError instanceof Error ? saveError.message : 'Failed to save default settings.');
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ return (
+ <Stack gap="3">
+ <HStack justify="space-between">
+ <Stack gap="0.5">
+ <FieldLabel>Default Settings</FieldLabel>
+ <Text color="fg.subtle" fontSize="2xs">
+ Applied automatically when this model is selected. Off = use the app default.
+ </Text>
+ </Stack>
+ <Button disabled={!isDirty} loading={isSaving} size="xs" variant="solid" onClick={() => void handleSave()}>
+ Save Defaults
+ </Button>
+ </HStack>
+ {error ? (
+ <Text color="red.400" fontSize="2xs" role="alert">
+ {error}
+ </Text>
+ ) : null}
+ <Grid gap="2.5" templateColumns="repeat(auto-fill, minmax(13rem, 1fr))">
+ {fields.map((field) => {
+ const value = settings[field.key] ?? null;
+ const isEnabled = value !== null && value !== undefined;
+
+ return (
+ <Stack
+ key={field.key}
+ bg="bg.panel"
+ borderColor="border.subtle"
+ borderWidth="1px"
+ gap="2"
+ p="2.5"
+ rounded="md"
+ >
+ <HStack justify="space-between">
+ <Text fontSize="2xs" fontWeight="600" textTransform="uppercase">
+ {field.label}
+ </Text>
+ <Switch.Root
+ checked={isEnabled}
+ colorPalette="theme"
+ size="xs"
+ onCheckedChange={(event) => setFieldValue(field.key, event.checked ? field.defaultValue : null)}
+ >
+ <Switch.HiddenInput />
+ <Switch.Control>
+ <Switch.Thumb />
+ </Switch.Control>
+ <Switch.Label srOnly>{`Customize ${field.label} for this model`}</Switch.Label>
+ </Switch.Root>
+ </HStack>
+ {field.control(
+ isEnabled ? value : field.defaultValue,
+ (nextValue) => setFieldValue(field.key, nextValue),
+ !isEnabled
+ )}
+ <Text color="fg.subtle" fontSize="2xs">
+ {isEnabled ? 'Customized for this model' : field.inheritLabel}
+ </Text>
+ </Stack>
+ );
+ })}
+ </Grid>
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/HuggingFaceTab.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/HuggingFaceTab.tsx
new file mode 100644
index 0000000000..54aa707026
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/HuggingFaceTab.tsx
@@ -0,0 +1,119 @@
+import { HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';
+import { DownloadIcon, KeyRoundIcon } from 'lucide-react';
+
+import { Button } from '../../components/ui/Button';
+import { Field } from '../../components/ui/Field';
+import { getHuggingFaceModels } from '../../models/api';
+import { huggingFaceRepoSchema } from '../../models/schemas';
+import { updateModelsUi, useModelsUi } from '../../models/uiStore';
+import { useZodForm } from '../../models/useZodForm';
+import { InstallSourceButton, SourceListItem } from './SourceListItem';
+import { useInstallActions } from './useInstallActions';
+
+/**
+ * HuggingFace installs: diffusers repos install immediately; checkpoint repos
+ * list their files (kept across tab switches) so the right one can be picked.
+ */
+export const HuggingFaceTab = () => {
+ const { install, pendingSources } = useInstallActions();
+ const { hfLookup } = useModelsUi();
+ const form = useZodForm(huggingFaceRepoSchema, { repo: hfLookup?.repo ?? '' });
+
+ const handleInstall = () =>
+ form.handleSubmit(async ({ repo }) => {
+ const lookup = await getHuggingFaceModels(repo);
+
+ if (lookup.is_diffusers) {
+ // A diffusers repo installs as one unit -- no file picking needed.
+ updateModelsUi({ hfLookup: null });
+
+ const ok = await install({ source: repo });
+
+ if (ok) {
+ form.reset();
+ }
+
+ return;
+ }
+
+ if (!lookup.urls || lookup.urls.length === 0) {
+ throw new Error('No installable model files were found in this repo.');
+ }
+
+ updateModelsUi({ hfLookup: { repo, urls: lookup.urls } });
+ });
+
+ return (
+ <Stack gap="4" maxW="40rem">
+ <Field
+ error={form.errors.repo ?? form.formError}
+ helpText="Diffusers repos install immediately; checkpoint repos list their files below to choose from."
+ label="HuggingFace Repo"
+ >
+ <HStack gap="1.5">
+ <Input
+ aria-invalid={form.errors.repo ? true : undefined}
+ placeholder="owner/repo, e.g. black-forest-labs/FLUX.1-dev"
+ size="sm"
+ value={form.values.repo}
+ onChange={(event) => form.setValue('repo', event.currentTarget.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ void handleInstall();
+ }
+ }}
+ />
+ <Button
+ disabled={form.values.repo.trim().length === 0}
+ loading={form.isSubmitting}
+ size="sm"
+ variant="solid"
+ onClick={() => void handleInstall()}
+ >
+ <Icon as={DownloadIcon} boxSize="3.5" />
+ Install
+ </Button>
+ </HStack>
+ </Field>
+
+ {hfLookup ? (
+ <Stack gap="1.5">
+ <Text color="fg.muted" fontSize="2xs">
+ {hfLookup.urls.length} file{hfLookup.urls.length === 1 ? '' : 's'} in {hfLookup.repo}:
+ </Text>
+ {hfLookup.urls.map((url) => {
+ const fileName = url.split('/').at(-1) ?? url;
+
+ return (
+ <SourceListItem
+ key={url}
+ title={fileName}
+ titleTooltip={url}
+ trailing={
+ <InstallSourceButton
+ isPending={pendingSources.has(url)}
+ source={url}
+ onInstall={() => {
+ void install({ source: url });
+ }}
+ />
+ }
+ />
+ );
+ })}
+ </Stack>
+ ) : null}
+
+ <HStack gap="1.5">
+ <Icon as={KeyRoundIcon} boxSize="3.5" color="fg.subtle" />
+ <Text color="fg.subtle" fontSize="2xs">
+ Gated repos (like FLUX) need a HuggingFace token.
+ </Text>
+ <Button size="2xs" variant="ghost" onClick={() => updateModelsUi({ addTab: 'keys' })}>
+ Manage API keys →
+ </Button>
+ </HStack>
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/InstallQueueSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/InstallQueueSection.tsx
new file mode 100644
index 0000000000..19292c88e5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/InstallQueueSection.tsx
@@ -0,0 +1,270 @@
+import { Badge, Box, Flex, HStack, Icon, Progress, Spinner, Stack, Text } from '@chakra-ui/react';
+import { PauseIcon, PlayIcon, RotateCcwIcon, Trash2Icon, XIcon } from 'lucide-react';
+import { useEffect, useState } from 'react';
+
+import { Button, IconButton } from '../../components/ui/Button';
+import { Scrollable } from '../../components/ui/Scrollable';
+import { Tooltip } from '../../components/ui/Tooltip';
+import {
+ cancelModelInstall,
+ pauseModelInstall,
+ pruneCompletedModelInstalls,
+ restartFailedModelInstall,
+ resumeModelInstall,
+} from '../../models/api';
+import {
+ ensureInstallsLoaded,
+ isActiveInstallStatus,
+ refreshInstalls,
+ replaceInstallJob,
+ useInstallProgress,
+ useInstallsSnapshot,
+} from '../../models/installsStore';
+import { formatBytes, getInstallSourceLabel } from '../../models/taxonomy';
+import type { ModelInstallJob, ModelInstallStatus } from '../../models/types';
+import { useNotify } from '../../useNotify';
+
+const STATUS_BADGES: Record<ModelInstallStatus, { label: string; palette: string }> = {
+ cancelled: { label: 'Cancelled', palette: 'gray' },
+ completed: { label: 'Installed', palette: 'green' },
+ downloading: { label: 'Downloading', palette: 'blue' },
+ downloads_done: { label: 'Downloaded', palette: 'blue' },
+ error: { label: 'Failed', palette: 'red' },
+ paused: { label: 'Paused', palette: 'orange' },
+ running: { label: 'Installing', palette: 'blue' },
+ waiting: { label: 'Waiting', palette: 'gray' },
+};
+
+/**
+ * The model install/download queue: live rows for every install job with
+ * pause/resume/cancel/retry per job and pruning of settled jobs. Download
+ * progress streams in over the socket and bypasses the job list re-render.
+ */
+export const InstallQueueSection = () => {
+ const notify = useNotify();
+ const { error, jobs, status } = useInstallsSnapshot();
+ const [isPruning, setIsPruning] = useState(false);
+
+ useEffect(() => {
+ ensureInstallsLoaded();
+ }, []);
+
+ const settledCount = jobs.filter((job) => !isActiveInstallStatus(job.status) && job.status !== 'paused').length;
+
+ const handlePrune = async () => {
+ setIsPruning(true);
+
+ try {
+ await pruneCompletedModelInstalls();
+ await refreshInstalls();
+ } catch (pruneError) {
+ notify.error('Prune failed', pruneError instanceof Error ? pruneError.message : String(pruneError));
+ } finally {
+ setIsPruning(false);
+ }
+ };
+
+ if (status === 'loading' || status === 'idle') {
+ return (
+ <Flex align="center" justify="center" py="6">
+ <Spinner color="fg.subtle" size="sm" />
+ </Flex>
+ );
+ }
+
+ if (status === 'error') {
+ return (
+ <Stack align="center" gap="1" py="6">
+ <Text color="red.400" fontSize="xs" fontWeight="600">
+ Could not load the install queue
+ </Text>
+ <Text color="fg.subtle" fontSize="2xs">
+ {error}
+ </Text>
+ <Button mt="1" size="xs" variant="outline" onClick={() => void refreshInstalls()}>
+ Retry
+ </Button>
+ </Stack>
+ );
+ }
+
+ if (jobs.length === 0) {
+ return (
+ <Stack align="center" gap="1" py="6">
+ <Text color="fg.muted" fontSize="xs" fontWeight="600">
+ No installs yet
+ </Text>
+ <Text color="fg.subtle" fontSize="2xs">
+ Models you install will download here.
+ </Text>
+ </Stack>
+ );
+ }
+
+ return (
+ <Stack gap="2" h="full" minH="0">
+ <HStack justify="space-between">
+ <Text color="fg.subtle" fontSize="2xs">
+ {jobs.length} job{jobs.length === 1 ? '' : 's'}
+ </Text>
+ <Button
+ disabled={settledCount === 0}
+ loading={isPruning}
+ size="2xs"
+ variant="ghost"
+ onClick={() => void handlePrune()}
+ >
+ <Icon as={Trash2Icon} boxSize="3" />
+ Clear finished
+ </Button>
+ </HStack>
+ <Scrollable flex="1" label="Install jobs" minH="0">
+ <Stack gap="1.5">
+ {jobs.map((job) => (
+ <InstallJobRow key={job.id} job={job} onError={notify.error} />
+ ))}
+ </Stack>
+ </Scrollable>
+ </Stack>
+ );
+};
+
+const InstallJobRow = ({
+ job,
+ onError,
+}: {
+ job: ModelInstallJob;
+ onError: (title: string, message: string) => void;
+}) => {
+ const [isActing, setIsActing] = useState(false);
+ const badge = STATUS_BADGES[job.status] ?? { label: job.status, palette: 'gray' };
+ const sourceLabel = getInstallSourceLabel(job.source);
+ const displayName = job.config_out?.name ?? sourceLabel;
+
+ const runAction = async (action: () => Promise<unknown>, failureTitle: string) => {
+ setIsActing(true);
+
+ try {
+ const result = await action();
+
+ if (result && typeof result === 'object' && 'id' in (result as ModelInstallJob)) {
+ replaceInstallJob(result as ModelInstallJob);
+ } else {
+ await refreshInstalls();
+ }
+ } catch (actionError) {
+ onError(failureTitle, actionError instanceof Error ? actionError.message : String(actionError));
+ } finally {
+ setIsActing(false);
+ }
+ };
+
+ return (
+ <Stack
+ bg="bg.surface"
+ borderColor={job.status === 'error' ? 'red.500' : 'border.subtle'}
+ borderWidth="1px"
+ gap="1.5"
+ p="2"
+ rounded="md"
+ >
+ <HStack gap="2" justify="space-between">
+ <Text flex="1" fontSize="2xs" fontWeight="600" minW="0" truncate title={sourceLabel}>
+ {displayName}
+ </Text>
+ <Badge colorPalette={badge.palette} flexShrink={0} fontSize="2xs" size="sm" variant="surface">
+ {badge.label}
+ </Badge>
+ <HStack flexShrink={0} gap="0.5">
+ {job.status === 'downloading' ? (
+ <Tooltip content="Pause download">
+ <IconButton
+ aria-label="Pause install"
+ disabled={isActing}
+ size="2xs"
+ variant="ghost"
+ onClick={() => void runAction(() => pauseModelInstall(job.id), 'Pause failed')}
+ >
+ <Icon as={PauseIcon} boxSize="3" />
+ </IconButton>
+ </Tooltip>
+ ) : null}
+ {job.status === 'paused' ? (
+ <Tooltip content="Resume download">
+ <IconButton
+ aria-label="Resume install"
+ disabled={isActing}
+ size="2xs"
+ variant="ghost"
+ onClick={() => void runAction(() => resumeModelInstall(job.id), 'Resume failed')}
+ >
+ <Icon as={PlayIcon} boxSize="3" />
+ </IconButton>
+ </Tooltip>
+ ) : null}
+ {job.status === 'error' ? (
+ <Tooltip content="Retry failed download">
+ <IconButton
+ aria-label="Retry install"
+ disabled={isActing}
+ size="2xs"
+ variant="ghost"
+ onClick={() => void runAction(() => restartFailedModelInstall(job.id), 'Retry failed')}
+ >
+ <Icon as={RotateCcwIcon} boxSize="3" />
+ </IconButton>
+ </Tooltip>
+ ) : null}
+ {isActiveInstallStatus(job.status) || job.status === 'paused' ? (
+ <Tooltip content="Cancel install">
+ <IconButton
+ aria-label="Cancel install"
+ disabled={isActing}
+ size="2xs"
+ variant="ghost"
+ onClick={() => void runAction(() => cancelModelInstall(job.id), 'Cancel failed')}
+ >
+ <Icon as={XIcon} boxSize="3" />
+ </IconButton>
+ </Tooltip>
+ ) : null}
+ </HStack>
+ </HStack>
+ {displayName !== sourceLabel ? (
+ <Text color="fg.subtle" fontSize="2xs" truncate>
+ {sourceLabel}
+ </Text>
+ ) : null}
+ {job.status === 'downloading' || job.status === 'waiting' ? <InstallJobProgress job={job} /> : null}
+ {job.status === 'error' && job.error ? (
+ <Text color="red.300" fontSize="2xs" overflowWrap="anywhere">
+ {job.error_reason ? `${job.error_reason}: ` : ''}
+ {job.error}
+ </Text>
+ ) : null}
+ </Stack>
+ );
+};
+
+const InstallJobProgress = ({ job }: { job: ModelInstallJob }) => {
+ const liveProgress = useInstallProgress(job.id);
+ const bytes = liveProgress?.bytes ?? job.bytes ?? 0;
+ const totalBytes = liveProgress?.totalBytes ?? job.total_bytes ?? 0;
+ const hasTotal = totalBytes > 0;
+ const ratio = hasTotal ? Math.min(1, bytes / totalBytes) : null;
+
+ return (
+ <Box>
+ <Progress.Root aria-label="Download progress" max={1} size="xs" value={ratio}>
+ <Progress.Track>
+ <Progress.Range />
+ </Progress.Track>
+ </Progress.Root>
+ <Text color="fg.subtle" fontSize="2xs" mt="1">
+ {hasTotal
+ ? `${Math.round((ratio ?? 0) * 100)}% · ${formatBytes(bytes)} / ${formatBytes(totalBytes)}`
+ : 'Waiting for download to start…'}
+ </Text>
+ </Box>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/MaintenanceMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/MaintenanceMenu.tsx
new file mode 100644
index 0000000000..b007b12b60
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/MaintenanceMenu.tsx
@@ -0,0 +1,252 @@
+import { Checkbox, Dialog, Flex, HStack, Icon, Menu, Portal, Spinner, Stack, Text } from '@chakra-ui/react';
+import { BrushCleaningIcon, FolderSearchIcon, MoreHorizontalIcon, RefreshCcwIcon } from 'lucide-react';
+import { useEffect, useState } from 'react';
+
+import { Button, CloseButton, IconButton } from '../../components/ui/Button';
+import { MenuContent } from '../../components/ui/Menu';
+import { deleteOrphanedModels, emptyModelCache, getOrphanedModels } from '../../models/api';
+import { refreshModels } from '../../models/modelsStore';
+import { formatBytes } from '../../models/taxonomy';
+import type { OrphanedModelInfo } from '../../models/types';
+import { useNotify } from '../../useNotify';
+
+/**
+ * Library maintenance: refresh, clean up orphaned model folders (files on disk
+ * with no database record), and empty the in-memory model cache.
+ */
+export const MaintenanceMenu = () => {
+ const notify = useNotify();
+ const [isSyncDialogOpen, setIsSyncDialogOpen] = useState(false);
+
+ const handleEmptyCache = async () => {
+ try {
+ await emptyModelCache();
+ notify.success('Model cache emptied');
+ } catch (error) {
+ notify.error('Failed to empty model cache', error instanceof Error ? error.message : String(error));
+ }
+ };
+
+ return (
+ <>
+ <Menu.Root positioning={{ placement: 'bottom-end' }}>
+ <Menu.Trigger asChild>
+ <IconButton aria-label="Model library maintenance" size="xs" variant="ghost">
+ <Icon as={MoreHorizontalIcon} boxSize="4" />
+ </IconButton>
+ </Menu.Trigger>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="14rem">
+ <Menu.Item value="refresh" onClick={() => void refreshModels()}>
+ <Icon as={RefreshCcwIcon} boxSize="3.5" />
+ <Menu.ItemText fontSize="xs">Refresh model list</Menu.ItemText>
+ </Menu.Item>
+ <Menu.Item value="sync" onClick={() => setIsSyncDialogOpen(true)}>
+ <Icon as={FolderSearchIcon} boxSize="3.5" />
+ <Menu.ItemText fontSize="xs">Clean up orphaned models…</Menu.ItemText>
+ </Menu.Item>
+ <Menu.Item value="empty-cache" onClick={() => void handleEmptyCache()}>
+ <Icon as={BrushCleaningIcon} boxSize="3.5" />
+ <Menu.ItemText fontSize="xs">Empty model cache</Menu.ItemText>
+ </Menu.Item>
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ {isSyncDialogOpen ? <OrphanedModelsDialog onClose={() => setIsSyncDialogOpen(false)} /> : null}
+ </>
+ );
+};
+
+const OrphanedModelsDialog = ({ onClose }: { onClose: () => void }) => {
+ const notify = useNotify();
+ const [orphans, setOrphans] = useState<OrphanedModelInfo[] | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ // Nothing pre-selected: deleting files on disk must be an explicit choice.
+ const [selectedPaths, setSelectedPaths] = useState<ReadonlySet<string>>(new Set());
+ const [isDeleting, setIsDeleting] = useState(false);
+
+ useEffect(() => {
+ let isStale = false;
+
+ getOrphanedModels()
+ .then((result) => {
+ if (!isStale) {
+ setOrphans(result);
+ }
+ })
+ .catch((error: unknown) => {
+ if (!isStale) {
+ setLoadError(error instanceof Error ? error.message : 'Failed to scan for orphaned models.');
+ }
+ });
+
+ return () => {
+ isStale = true;
+ };
+ }, []);
+
+ const togglePath = (path: string) => {
+ setSelectedPaths((current) => {
+ const next = new Set(current);
+
+ if (next.has(path)) {
+ next.delete(path);
+ } else {
+ next.add(path);
+ }
+
+ return next;
+ });
+ };
+
+ const handleDelete = async () => {
+ setIsDeleting(true);
+
+ try {
+ const result = await deleteOrphanedModels([...selectedPaths]);
+ const errorCount = Object.keys(result.errors).length;
+
+ if (errorCount > 0) {
+ notify.error(
+ 'Orphaned model cleanup',
+ `${result.deleted.length} deleted, ${errorCount} failed: ${Object.values(result.errors)[0]}`
+ );
+ } else {
+ notify.success('Orphaned model cleanup', `${result.deleted.length} orphaned model folder(s) deleted.`);
+ }
+
+ void refreshModels();
+ onClose();
+ } catch (error) {
+ notify.error('Orphaned model cleanup failed', error instanceof Error ? error.message : String(error));
+ } finally {
+ setIsDeleting(false);
+ }
+ };
+
+ const totalSelectedBytes =
+ orphans?.filter((orphan) => selectedPaths.has(orphan.path)).reduce((sum, orphan) => sum + orphan.size_bytes, 0) ??
+ 0;
+
+ return (
+ <Dialog.Root
+ open
+ placement="center"
+ scrollBehavior="inside"
+ size="md"
+ onOpenChange={(event) => {
+ if (!event.open) {
+ onClose();
+ }
+ }}
+ >
+ <Portal>
+ <Dialog.Backdrop />
+ <Dialog.Positioner>
+ <Dialog.Content bg="bg.surface" borderColor="border.subtle" borderWidth="1px" color="fg.default">
+ <Dialog.Header borderBottomWidth="1px" borderColor="border.subtle">
+ <Stack gap="0.5">
+ <Dialog.Title fontSize="sm" fontWeight="700">
+ Orphaned Models
+ </Dialog.Title>
+ <Text color="fg.subtle" fontSize="2xs">
+ Folders in the models directory with no database record — usually leftovers from failed installs or
+ external deletes.
+ </Text>
+ </Stack>
+ </Dialog.Header>
+ <Dialog.Body>
+ {loadError ? (
+ <Text color="red.400" fontSize="xs" py="4">
+ {loadError}
+ </Text>
+ ) : orphans === null ? (
+ <Flex align="center" justify="center" py="8">
+ <Spinner color="fg.subtle" size="sm" />
+ </Flex>
+ ) : orphans.length === 0 ? (
+ <Text color="fg.muted" fontSize="xs" py="4" textAlign="center">
+ No orphaned model folders found — your library is clean.
+ </Text>
+ ) : (
+ <Stack gap="1.5" py="2">
+ <Checkbox.Root
+ checked={
+ selectedPaths.size === 0 ? false : selectedPaths.size === orphans.length ? true : 'indeterminate'
+ }
+ colorPalette="theme"
+ ps="2"
+ size="sm"
+ onCheckedChange={() => {
+ setSelectedPaths(
+ selectedPaths.size === orphans.length
+ ? new Set()
+ : new Set(orphans.map((orphan) => orphan.path))
+ );
+ }}
+ >
+ <Checkbox.HiddenInput />
+ <Checkbox.Control />
+ <Checkbox.Label color="fg.muted" fontSize="2xs">
+ Select all ({orphans.length})
+ </Checkbox.Label>
+ </Checkbox.Root>
+ {orphans.map((orphan) => (
+ <HStack
+ key={orphan.path}
+ bg="bg.panel"
+ borderColor="border.subtle"
+ borderWidth="1px"
+ gap="2"
+ p="2"
+ rounded="md"
+ >
+ <Checkbox.Root
+ checked={selectedPaths.has(orphan.path)}
+ colorPalette="theme"
+ size="sm"
+ onCheckedChange={() => togglePath(orphan.path)}
+ >
+ <Checkbox.HiddenInput />
+ <Checkbox.Control />
+ </Checkbox.Root>
+ <Stack flex="1" gap="0" minW="0">
+ <Text fontSize="2xs" fontWeight="600" overflowWrap="anywhere">
+ {orphan.path}
+ </Text>
+ <Text color="fg.subtle" fontSize="2xs">
+ {orphan.files.length} file{orphan.files.length === 1 ? '' : 's'} ·{' '}
+ {formatBytes(orphan.size_bytes)}
+ </Text>
+ </Stack>
+ </HStack>
+ ))}
+ </Stack>
+ )}
+ </Dialog.Body>
+ <Dialog.Footer gap="2">
+ <Button disabled={isDeleting} size="xs" variant="ghost" onClick={onClose}>
+ Close
+ </Button>
+ <Button
+ colorPalette="red"
+ disabled={selectedPaths.size === 0 || !orphans || orphans.length === 0}
+ loading={isDeleting}
+ size="xs"
+ variant="solid"
+ onClick={() => void handleDelete()}
+ >
+ Delete Selected ({formatBytes(totalSelectedBytes)})
+ </Button>
+ </Dialog.Footer>
+ <Dialog.CloseTrigger asChild>
+ <CloseButton color="fg.muted" size="sm" />
+ </Dialog.CloseTrigger>
+ </Dialog.Content>
+ </Dialog.Positioner>
+ </Portal>
+ </Dialog.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/ModelBadges.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelBadges.tsx
new file mode 100644
index 0000000000..c8b4ac604b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelBadges.tsx
@@ -0,0 +1,30 @@
+import { Badge, HStack } from '@chakra-ui/react';
+
+import { getModelBaseColorPalette, getModelBaseLabel, getModelFormatLabel } from '../../models/taxonomy';
+import type { ModelConfig } from '../../models/types';
+
+export const ModelBaseBadge = ({ base }: { base: ModelConfig['base'] }) => (
+ <Badge colorPalette={getModelBaseColorPalette(base)} flexShrink={0} fontSize="2xs" size="sm" variant="surface">
+ {getModelBaseLabel(base)}
+ </Badge>
+);
+
+export const ModelFormatBadge = ({ format }: { format: ModelConfig['format'] }) => (
+ <Badge colorPalette="gray" flexShrink={0} fontSize="2xs" size="sm" variant="outline">
+ {getModelFormatLabel(format)}
+ </Badge>
+);
+
+export const MissingFileBadge = () => (
+ <Badge colorPalette="red" flexShrink={0} fontSize="2xs" size="sm" variant="surface">
+ Missing file
+ </Badge>
+);
+
+export const ModelBadgeRow = ({ isMissing, model }: { isMissing?: boolean; model: ModelConfig }) => (
+ <HStack gap="1" minW="0" wrap="wrap">
+ <ModelBaseBadge base={model.base} />
+ <ModelFormatBadge format={model.format} />
+ {isMissing ? <MissingFileBadge /> : null}
+ </HStack>
+);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/ModelDetail.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelDetail.tsx
new file mode 100644
index 0000000000..e11f8d040b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelDetail.tsx
@@ -0,0 +1,247 @@
+import { DataList, HStack, Icon, Menu, Portal, Separator, Stack, Text } from '@chakra-ui/react';
+import { ArrowLeftIcon, MoreHorizontalIcon, PencilIcon, RefreshCcwIcon, Trash2Icon } from 'lucide-react';
+import { SiHuggingface } from 'react-icons/si';
+import { useCallback, useState } from 'react';
+
+import { Button, IconButton } from '../../components/ui/Button';
+import { ConfirmDialog } from '../../components/ui/ConfirmDialog';
+import { MenuContent } from '../../components/ui/Menu';
+import { useModelsSnapshot } from '../../models/modelsStore';
+import { formatBytes, isConvertibleToDiffusers } from '../../models/taxonomy';
+import type { ModelConfig } from '../../models/types';
+import { useNotify } from '../../useNotify';
+import { DefaultSettingsSection, supportsDefaultSettings } from './DefaultSettingsSection';
+import { MissingFileBadge, ModelBadgeRow } from './ModelBadges';
+import { ModelEditForm } from './ModelEditForm';
+import { ModelImageUpload } from './ModelImageUpload';
+import { RelatedModelsSection } from './RelatedModelsSection';
+import { TriggerPhrasesEditor } from './TriggerPhrasesEditor';
+import { useModelActions } from './useModelActions';
+
+const TRIGGER_PHRASE_TYPES = new Set(['main', 'lora', 'embedding']);
+const RELATED_MODEL_TYPES = new Set(['main', 'lora']);
+
+/**
+ * Full detail pane for one model: identity (view/edit), per-model default
+ * settings, related models, trigger phrases, and lifecycle actions (convert,
+ * re-identify, delete). Mount keyed by model key so per-model form state never
+ * leaks between models. `density="panel"` tightens the side-panel drill-in.
+ */
+export const ModelDetail = ({
+ density = 'full',
+ modelKey,
+ onBack,
+ onDeleted,
+}: {
+ density?: 'panel' | 'full';
+ modelKey: string;
+ onBack?: () => void;
+ onDeleted: () => void;
+}) => {
+ const notify = useNotify();
+ const { missingModelKeys, models } = useModelsSnapshot();
+ const { convert, reidentify, remove } = useModelActions();
+ const model = models.find((candidate) => candidate.key === modelKey);
+ const [isEditing, setIsEditing] = useState(false);
+ const [pendingAction, setPendingAction] = useState<'delete' | 'convert' | null>(null);
+ const [isActionBusy, setIsActionBusy] = useState(false);
+
+ const handleSectionError = useCallback(
+ (message: string) => {
+ notify.error('Model manager', message);
+ },
+ [notify]
+ );
+
+ if (!model) {
+ return (
+ <Stack align="start" gap="2" p="1">
+ {onBack ? <BackButton onBack={onBack} /> : null}
+ <Text color="fg.subtle" fontSize="xs">
+ This model is no longer in the library.
+ </Text>
+ </Stack>
+ );
+ }
+
+ const handleReidentify = async () => {
+ setIsActionBusy(true);
+
+ try {
+ await reidentify(model);
+ } finally {
+ setIsActionBusy(false);
+ }
+ };
+
+ return (
+ <Stack gap={density === 'panel' ? '3' : '4'} pb="4">
+ {onBack ? <BackButton onBack={onBack} /> : null}
+
+ <HStack align="start" gap="3">
+ <ModelImageUpload
+ model={model}
+ onError={(message) => notify.error('Model image', message)}
+ onUpdated={() => notify.success('Model image updated')}
+ />
+ <Stack flex="1" gap="1" minW="0">
+ <Text fontSize="sm" fontWeight="700" lineClamp={2}>
+ {model.name}
+ </Text>
+ <ModelBadgeRow model={model} />
+ {missingModelKeys.has(model.key) ? (
+ <HStack gap="1.5">
+ <MissingFileBadge />
+ <Text color="fg.subtle" fontSize="2xs">
+ The file for this model was not found on disk.
+ </Text>
+ </HStack>
+ ) : null}
+ {model.description ? (
+ <Text color="fg.muted" fontSize="2xs" lineClamp={3}>
+ {model.description}
+ </Text>
+ ) : null}
+ </Stack>
+ <HStack flexShrink={0} gap="1" wrap="wrap">
+ {isConvertibleToDiffusers(model) ? (
+ <Button size="xs" variant="outline" onClick={() => setPendingAction('convert')}>
+ <Icon as={SiHuggingface} boxSize="3" />
+ Convert to Diffusers
+ </Button>
+ ) : null}
+ <Button
+ size="xs"
+ variant={isEditing ? 'solid' : 'outline'}
+ onClick={() => setIsEditing((editing) => !editing)}
+ >
+ <Icon as={PencilIcon} boxSize="3" />
+ {isEditing ? 'Editing' : 'Edit'}
+ </Button>
+ <Menu.Root positioning={{ placement: 'bottom-end' }}>
+ <Menu.Trigger asChild>
+ <IconButton aria-label="Model actions" loading={isActionBusy} size="xs" variant="ghost">
+ <Icon as={MoreHorizontalIcon} boxSize="4" />
+ </IconButton>
+ </Menu.Trigger>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="12rem">
+ <Menu.Item value="reidentify" onClick={() => void handleReidentify()}>
+ <Icon as={RefreshCcwIcon} boxSize="3.5" />
+ <Menu.ItemText fontSize="xs">Re-identify model</Menu.ItemText>
+ </Menu.Item>
+ <Menu.Separator />
+ <Menu.Item color="red.400" value="delete" onClick={() => setPendingAction('delete')}>
+ <Icon as={Trash2Icon} boxSize="3.5" />
+ <Menu.ItemText fontSize="xs">Delete model</Menu.ItemText>
+ </Menu.Item>
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ </HStack>
+ </HStack>
+
+ {isEditing ? (
+ <ModelEditForm
+ model={model}
+ onCancel={() => setIsEditing(false)}
+ onSaved={() => {
+ setIsEditing(false);
+ notify.success('Model updated', model.name);
+ }}
+ />
+ ) : (
+ <ModelAttributes density={density} model={model} />
+ )}
+
+ {supportsDefaultSettings(model) ? (
+ <>
+ <Separator borderColor="border.subtle" />
+ <DefaultSettingsSection
+ model={model}
+ onError={(message) => notify.error('Default settings', message)}
+ onSaved={() => notify.success('Default settings saved', model.name)}
+ />
+ </>
+ ) : null}
+
+ {RELATED_MODEL_TYPES.has(model.type) ? (
+ <>
+ <Separator borderColor="border.subtle" />
+ <RelatedModelsSection model={model} onError={handleSectionError} />
+ </>
+ ) : null}
+
+ {TRIGGER_PHRASE_TYPES.has(model.type) ? (
+ <>
+ <Separator borderColor="border.subtle" />
+ <TriggerPhrasesEditor model={model} onError={(message) => notify.error('Trigger phrases', message)} />
+ </>
+ ) : null}
+
+ <ConfirmDialog
+ body={`Delete “${model.name}”? The database record is removed, and the model files are deleted if they live inside the InvokeAI models directory.`}
+ confirmLabel="Delete Model"
+ isOpen={pendingAction === 'delete'}
+ title="Delete model"
+ onClose={() => setPendingAction(null)}
+ onConfirm={async () => {
+ await remove(model);
+ onDeleted();
+ }}
+ />
+ {/* Destructive styling: the original checkpoint file is replaced. */}
+ <ConfirmDialog
+ body={`Convert “${model.name}” to the diffusers format in place? The original checkpoint file is replaced by a diffusers folder.`}
+ confirmLabel="Convert"
+ isOpen={pendingAction === 'convert'}
+ title="Convert to diffusers"
+ onClose={() => setPendingAction(null)}
+ onConfirm={() => convert(model)}
+ />
+ </Stack>
+ );
+};
+
+const BackButton = ({ onBack }: { onBack: () => void }) => (
+ <Button alignSelf="start" size="2xs" variant="ghost" onClick={onBack}>
+ <Icon as={ArrowLeftIcon} boxSize="3" />
+ All models
+ </Button>
+);
+
+const isAbsolutePath = (path: string): boolean => path.startsWith('/') || /^[A-Za-z]:[\\/]/.test(path);
+
+const ModelAttributes = ({ density, model }: { density: 'panel' | 'full'; model: ModelConfig }) => {
+ const { modelsDir } = useModelsSnapshot();
+ // Managed models store paths relative to the models directory; show the
+ // resolved absolute path so it can be found on disk.
+ const fullPath =
+ isAbsolutePath(model.path) || !modelsDir ? model.path : `${modelsDir.replace(/\/+$/, '')}/${model.path}`;
+
+ const attributes: { label: string; value: string }[] = [
+ { label: 'File Size', value: formatBytes(model.file_size) },
+ { label: 'Variant', value: model.variant ?? '—' },
+ { label: 'Prediction Type', value: model.prediction_type ?? '—' },
+ { label: 'Hash', value: model.hash },
+ { label: 'Path', value: fullPath },
+ { label: 'Source', value: model.source },
+ ];
+
+ return (
+ <DataList.Root gap="2.5" orientation={density === 'panel' ? 'vertical' : 'horizontal'} size="sm" variant="subtle">
+ {attributes.map((attribute) => (
+ <DataList.Item key={attribute.label}>
+ <DataList.ItemLabel color="fg.subtle" fontSize="2xs" minW="8rem" textTransform="uppercase">
+ {attribute.label}
+ </DataList.ItemLabel>
+ <DataList.ItemValue fontSize="2xs" overflowWrap="anywhere">
+ {attribute.value}
+ </DataList.ItemValue>
+ </DataList.Item>
+ ))}
+ </DataList.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/ModelEditForm.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelEditForm.tsx
new file mode 100644
index 0000000000..49932068bd
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelEditForm.tsx
@@ -0,0 +1,165 @@
+import { HStack, Input, NativeSelect, Stack, Text, Textarea } from '@chakra-ui/react';
+
+import { Button } from '../../components/ui/Button';
+import { Field } from '../../components/ui/Field';
+import { updateModel } from '../../models/api';
+import { replaceModelInStore } from '../../models/modelsStore';
+import { modelEditSchema, type ModelEditFormValues } from '../../models/schemas';
+import { getModelBaseLabel, getModelTypeLabel, MODEL_CATEGORIES } from '../../models/taxonomy';
+import type { ModelConfig, PredictionType } from '../../models/types';
+import { useZodForm } from '../../models/useZodForm';
+
+const KNOWN_BASES = [
+ 'sd-1',
+ 'sd-2',
+ 'sd-3',
+ 'sdxl',
+ 'sdxl-refiner',
+ 'flux',
+ 'flux2',
+ 'cogview4',
+ 'qwen-image',
+ 'z-image',
+ 'anima',
+ 'any',
+ 'unknown',
+];
+
+/** Zod-validated editor for a model's identity fields. */
+export const ModelEditForm = ({
+ model,
+ onCancel,
+ onSaved,
+}: {
+ model: ModelConfig;
+ onCancel: () => void;
+ onSaved: () => void;
+}) => {
+ const form = useZodForm(modelEditSchema, {
+ base: String(model.base),
+ description: model.description ?? '',
+ name: model.name,
+ predictionType: (model.prediction_type ?? '') as ModelEditFormValues['predictionType'],
+ sourceUrl: model.source_url ?? '',
+ type: String(model.type),
+ variant: model.variant ?? '',
+ });
+
+ const bases = KNOWN_BASES.includes(String(model.base)) ? KNOWN_BASES : [String(model.base), ...KNOWN_BASES];
+
+ const handleSave = () =>
+ form.handleSubmit(async (values) => {
+ const updated = await updateModel(model.key, {
+ base: values.base,
+ description: values.description || null,
+ name: values.name,
+ prediction_type: values.predictionType === '' ? null : (values.predictionType as PredictionType),
+ source_url: values.sourceUrl === '' ? null : values.sourceUrl,
+ type: values.type,
+ variant: values.variant === '' ? null : values.variant,
+ });
+
+ replaceModelInStore(updated);
+ onSaved();
+ });
+
+ return (
+ <Stack gap="3">
+ <Field error={form.errors.name} label="Name">
+ <Input
+ aria-invalid={form.errors.name ? true : undefined}
+ size="sm"
+ value={form.values.name}
+ onChange={(event) => form.setValue('name', event.currentTarget.value)}
+ />
+ </Field>
+ <Field error={form.errors.description} label="Description">
+ <Textarea
+ rows={2}
+ size="sm"
+ value={form.values.description}
+ onChange={(event) => form.setValue('description', event.currentTarget.value)}
+ />
+ </Field>
+ <HStack align="start" gap="2">
+ <Field error={form.errors.base} label="Base">
+ <NativeSelect.Root size="sm">
+ <NativeSelect.Field
+ value={form.values.base}
+ onChange={(event) => form.setValue('base', event.currentTarget.value)}
+ >
+ {bases.map((base) => (
+ <option key={base} value={base}>
+ {getModelBaseLabel(base)}
+ </option>
+ ))}
+ </NativeSelect.Field>
+ <NativeSelect.Indicator />
+ </NativeSelect.Root>
+ </Field>
+ <Field error={form.errors.type} label="Type">
+ <NativeSelect.Root size="sm">
+ <NativeSelect.Field
+ value={form.values.type}
+ onChange={(event) => form.setValue('type', event.currentTarget.value)}
+ >
+ {MODEL_CATEGORIES.map((category) => (
+ <option key={category.type} value={category.type}>
+ {getModelTypeLabel(category.type)}
+ </option>
+ ))}
+ </NativeSelect.Field>
+ <NativeSelect.Indicator />
+ </NativeSelect.Root>
+ </Field>
+ </HStack>
+ <HStack align="start" gap="2">
+ <Field error={form.errors.variant} helpText="Architecture variant, e.g. inpaint or dev." label="Variant">
+ <Input
+ size="sm"
+ value={form.values.variant}
+ onChange={(event) => form.setValue('variant', event.currentTarget.value)}
+ />
+ </Field>
+ <Field error={form.errors.predictionType} label="Prediction Type">
+ <NativeSelect.Root size="sm">
+ <NativeSelect.Field
+ value={form.values.predictionType}
+ onChange={(event) =>
+ form.setValue('predictionType', event.currentTarget.value as ModelEditFormValues['predictionType'])
+ }
+ >
+ <option value="">None</option>
+ <option value="epsilon">epsilon</option>
+ <option value="v_prediction">v_prediction</option>
+ <option value="sample">sample</option>
+ </NativeSelect.Field>
+ <NativeSelect.Indicator />
+ </NativeSelect.Root>
+ </Field>
+ </HStack>
+ <Field error={form.errors.sourceUrl} helpText="Model page or download URL." label="Source URL">
+ <Input
+ aria-invalid={form.errors.sourceUrl ? true : undefined}
+ placeholder="https://…"
+ size="sm"
+ value={form.values.sourceUrl}
+ onChange={(event) => form.setValue('sourceUrl', event.currentTarget.value)}
+ />
+ </Field>
+ {form.formError ? (
+ <Text color="red.400" fontSize="2xs" role="alert">
+ {form.formError}
+ </Text>
+ ) : null}
+ <HStack gap="2" justify="flex-end">
+ <Button disabled={form.isSubmitting} size="xs" variant="ghost" onClick={onCancel}>
+ Cancel
+ </Button>
+ <Button loading={form.isSubmitting} size="xs" variant="solid" onClick={() => void handleSave()}>
+ Save Changes
+ </Button>
+ </HStack>
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/ModelFilterBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelFilterBar.tsx
new file mode 100644
index 0000000000..64523c83da
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelFilterBar.tsx
@@ -0,0 +1,180 @@
+import { HStack, Icon, Input, InputGroup, Menu, Portal, ScrollArea, Text } from '@chakra-ui/react';
+import { CheckIcon, SearchIcon, SlidersHorizontalIcon } from 'lucide-react';
+
+import { IconButton } from '../../components/ui/Button';
+import { MenuContent } from '../../components/ui/Menu';
+import type { ModelLibraryFilters, ModelSortField } from '../../models/library';
+import { getModelBaseLabel, getModelTypeLabel } from '../../models/taxonomy';
+import type { ModelTaxonomyType } from '../../models/types';
+
+const SORT_FIELDS: { field: ModelSortField; label: string }[] = [
+ { field: 'default', label: 'Default' },
+ { field: 'name', label: 'Name' },
+ { field: 'base', label: 'Base' },
+ { field: 'size', label: 'Size' },
+ { field: 'format', label: 'Format' },
+];
+
+const isFiltering = (filters: ModelLibraryFilters): boolean =>
+ filters.typeFilter !== null || filters.baseFilter !== null || filters.missingOnly;
+
+/**
+ * Search box plus a combined filter/sort menu. The menu reflects only values
+ * present in the current library so it never offers dead filters.
+ */
+export const ModelFilterBar = ({
+ availableBases,
+ availableTypes,
+ filters,
+ missingCount,
+ onChange,
+}: {
+ availableBases: string[];
+ availableTypes: ModelTaxonomyType[];
+ filters: ModelLibraryFilters;
+ missingCount: number;
+ onChange: (filters: ModelLibraryFilters) => void;
+}) => (
+ <HStack gap="1.5" w="full">
+ <InputGroup startElement={<Icon as={SearchIcon} boxSize="3.5" color="fg.subtle" />}>
+ <Input
+ aria-label="Search models"
+ placeholder="Search models…"
+ size="sm"
+ value={filters.searchTerm}
+ onChange={(event) => onChange({ ...filters, searchTerm: event.currentTarget.value })}
+ />
+ </InputGroup>
+ <Menu.Root closeOnSelect={false} positioning={{ placement: 'bottom-end' }}>
+ <Menu.Trigger asChild>
+ <IconButton
+ aria-label="Filter and sort models"
+ color={isFiltering(filters) ? 'accent.invoke' : 'fg.muted'}
+ size="sm"
+ variant="ghost"
+ >
+ <Icon as={SlidersHorizontalIcon} boxSize="4" />
+ </IconButton>
+ </Menu.Trigger>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent maxH="70vh" minW="13rem" overflow="hidden" p="0">
+ <ScrollArea.Root maxH="inherit" size="xs" variant="hover" w="full">
+ <ScrollArea.Viewport aria-label="Model filters" maxH="inherit" w="full">
+ <ScrollArea.Content py="1">
+ <Menu.ItemGroup>
+ <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">
+ Model Type
+ </Menu.ItemGroupLabel>
+ <FilterMenuItem
+ isChecked={filters.typeFilter === null && !filters.missingOnly}
+ label="All models"
+ value="type-all"
+ onSelect={() => onChange({ ...filters, missingOnly: false, typeFilter: null })}
+ />
+ {missingCount > 0 ? (
+ <FilterMenuItem
+ isChecked={filters.missingOnly}
+ label={`Missing files (${missingCount})`}
+ value="type-missing"
+ onSelect={() => onChange({ ...filters, missingOnly: !filters.missingOnly, typeFilter: null })}
+ />
+ ) : null}
+ {availableTypes.map((type) => (
+ <FilterMenuItem
+ key={type}
+ isChecked={filters.typeFilter === type}
+ label={getModelTypeLabel(type)}
+ value={`type-${type}`}
+ onSelect={() =>
+ onChange({
+ ...filters,
+ missingOnly: false,
+ typeFilter: filters.typeFilter === type ? null : type,
+ })
+ }
+ />
+ ))}
+ </Menu.ItemGroup>
+ <Menu.Separator />
+ <Menu.ItemGroup>
+ <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">
+ Base Architecture
+ </Menu.ItemGroupLabel>
+ <FilterMenuItem
+ isChecked={filters.baseFilter === null}
+ label="All bases"
+ value="base-all"
+ onSelect={() => onChange({ ...filters, baseFilter: null })}
+ />
+ {availableBases.map((base) => (
+ <FilterMenuItem
+ key={base}
+ isChecked={filters.baseFilter === base}
+ label={getModelBaseLabel(base)}
+ value={`base-${base}`}
+ onSelect={() => onChange({ ...filters, baseFilter: filters.baseFilter === base ? null : base })}
+ />
+ ))}
+ </Menu.ItemGroup>
+ <Menu.Separator />
+ <Menu.ItemGroup>
+ <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">
+ Sort By
+ </Menu.ItemGroupLabel>
+ {SORT_FIELDS.map(({ field, label }) => (
+ <FilterMenuItem
+ key={field}
+ isChecked={filters.sortField === field}
+ label={label}
+ value={`sort-${field}`}
+ onSelect={() =>
+ onChange(
+ filters.sortField === field
+ ? { ...filters, sortDirection: filters.sortDirection === 'asc' ? 'desc' : 'asc' }
+ : { ...filters, sortDirection: 'asc', sortField: field }
+ )
+ }
+ trailing={
+ filters.sortField === field ? (filters.sortDirection === 'asc' ? 'Asc' : 'Desc') : undefined
+ }
+ />
+ ))}
+ </Menu.ItemGroup>
+ </ScrollArea.Content>
+ </ScrollArea.Viewport>
+ <ScrollArea.Scrollbar>
+ <ScrollArea.Thumb />
+ </ScrollArea.Scrollbar>
+ </ScrollArea.Root>
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ </HStack>
+);
+
+/** Checkmark-style menu item shared by the model filter menus. */
+export const FilterMenuItem = ({
+ isChecked,
+ label,
+ onSelect,
+ trailing,
+ value,
+}: {
+ isChecked: boolean;
+ label: string;
+ onSelect: () => void;
+ trailing?: string;
+ value: string;
+}) => (
+ <Menu.Item aria-checked={isChecked} closeOnSelect={false} role="menuitemcheckbox" value={value} onClick={onSelect}>
+ <Icon as={CheckIcon} boxSize="3" opacity={isChecked ? 1 : 0} />
+ <Menu.ItemText fontSize="xs">{label}</Menu.ItemText>
+ {trailing ? (
+ <Text color="fg.subtle" fontSize="2xs" ms="auto">
+ {trailing}
+ </Text>
+ ) : null}
+ </Menu.Item>
+);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/ModelImageUpload.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelImageUpload.tsx
new file mode 100644
index 0000000000..fa4c433f9c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelImageUpload.tsx
@@ -0,0 +1,209 @@
+import { Box, Flex, Icon, Image, Stack, Text } from '@chakra-ui/react';
+import { ImageIcon, UploadIcon, XIcon } from 'lucide-react';
+import { useRef, useState, type DragEvent } from 'react';
+
+import { IconButton } from '../../components/ui/Button';
+import { Tooltip } from '../../components/ui/Tooltip';
+import { deleteModelImage, getModelImageUrl, updateModelImage } from '../../models/api';
+import { markCoverImageChanged, useModelsSnapshot } from '../../models/modelsStore';
+import type { ModelConfig } from '../../models/types';
+
+const ACCEPTED_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);
+
+const dragContainsFiles = (event: DragEvent): boolean => Array.from(event.dataTransfer.types).includes('Files');
+
+/**
+ * The model's cover image as one large dropzone: click anywhere on the tile
+ * or drop an image file onto it to upload. The remove button sits in the top
+ * corner and is hover/focus-revealed (and inert while hidden).
+ */
+export const ModelImageUpload = ({
+ model,
+ onError,
+ onUpdated,
+}: {
+ model: ModelConfig;
+ onError: (message: string) => void;
+ onUpdated: () => void;
+}) => {
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const dragDepthRef = useRef(0);
+ const { coverImageVersions } = useModelsSnapshot();
+ const [hasImage, setHasImage] = useState(Boolean(model.cover_image));
+ const [isBusy, setIsBusy] = useState(false);
+ const [isDropActive, setIsDropActive] = useState(false);
+ const imageVersion = coverImageVersions[model.key];
+
+ const handleFile = async (file: File | undefined) => {
+ if (!file) {
+ return;
+ }
+
+ if (!ACCEPTED_TYPES.has(file.type)) {
+ onError('Use a PNG, JPEG, or WebP image.');
+ return;
+ }
+
+ setIsBusy(true);
+
+ try {
+ await updateModelImage(model.key, file);
+ setHasImage(true);
+ // Bumps the cache-bust version so this tile and list thumbnails reload.
+ markCoverImageChanged(model.key, true);
+ onUpdated();
+ } catch (error) {
+ onError(error instanceof Error ? error.message : 'Failed to upload model image.');
+ } finally {
+ setIsBusy(false);
+ }
+ };
+
+ const handleDelete = async () => {
+ setIsBusy(true);
+
+ try {
+ await deleteModelImage(model.key);
+ setHasImage(false);
+ markCoverImageChanged(model.key, false);
+ onUpdated();
+ } catch (error) {
+ onError(error instanceof Error ? error.message : 'Failed to remove model image.');
+ } finally {
+ setIsBusy(false);
+ }
+ };
+
+ return (
+ <Box
+ aria-busy={isBusy || undefined}
+ aria-label={`Upload cover image for ${model.name}`}
+ bg="bg.panel"
+ borderColor={isDropActive ? 'accent.active' : 'border.subtle'}
+ borderStyle={hasImage ? 'solid' : 'dashed'}
+ borderWidth={isDropActive ? '2px' : '1px'}
+ boxSize="24"
+ cursor="pointer"
+ flexShrink={0}
+ overflow="hidden"
+ position="relative"
+ role="button"
+ rounded="lg"
+ tabIndex={0}
+ className="group"
+ _focusVisible={{ outline: '2px solid var(--chakra-colors-accent-active)', outlineOffset: '2px' }}
+ onClick={() => {
+ if (!isBusy) {
+ inputRef.current?.click();
+ }
+ }}
+ onKeyDown={(event) => {
+ if ((event.key === 'Enter' || event.key === ' ') && !isBusy) {
+ event.preventDefault();
+ inputRef.current?.click();
+ }
+ }}
+ onDragEnter={(event) => {
+ if (!dragContainsFiles(event)) {
+ return;
+ }
+
+ event.preventDefault();
+ dragDepthRef.current += 1;
+ setIsDropActive(true);
+ }}
+ onDragLeave={(event) => {
+ if (!dragContainsFiles(event)) {
+ return;
+ }
+
+ dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
+
+ if (dragDepthRef.current === 0) {
+ setIsDropActive(false);
+ }
+ }}
+ onDragOver={(event) => {
+ if (dragContainsFiles(event)) {
+ event.preventDefault();
+ }
+ }}
+ onDrop={(event) => {
+ if (!dragContainsFiles(event)) {
+ return;
+ }
+
+ event.preventDefault();
+ dragDepthRef.current = 0;
+ setIsDropActive(false);
+ void handleFile(event.dataTransfer.files[0]);
+ }}
+ >
+ <input
+ ref={inputRef}
+ accept="image/png,image/jpeg,image/webp"
+ hidden
+ type="file"
+ onChange={(event) => {
+ void handleFile(event.currentTarget.files?.[0] ?? undefined);
+ event.currentTarget.value = '';
+ }}
+ onClick={(event) => event.stopPropagation()}
+ />
+ {hasImage ? (
+ <Image
+ alt={`${model.name} cover`}
+ boxSize="full"
+ fit="cover"
+ src={getModelImageUrl(model.key, imageVersion ? String(imageVersion) : undefined)}
+ onError={() => setHasImage(false)}
+ />
+ ) : (
+ <Stack align="center" boxSize="full" color="fg.subtle" gap="1" justify="center">
+ <Icon as={ImageIcon} boxSize="5" />
+ <Text fontSize="2xs">Add image</Text>
+ </Stack>
+ )}
+ {isDropActive ? (
+ <Flex
+ align="center"
+ bg="bg.surfaceRaised/85"
+ boxSize="full"
+ inset="0"
+ justify="center"
+ pointerEvents="none"
+ position="absolute"
+ >
+ <Icon as={UploadIcon} boxSize="5" color="accent.active" />
+ </Flex>
+ ) : null}
+ {hasImage && !isDropActive ? (
+ <Box
+ opacity={0}
+ pointerEvents="none"
+ position="absolute"
+ right="1"
+ top="1"
+ transition="opacity 0.12s ease"
+ _groupFocusWithin={{ opacity: 1, pointerEvents: 'auto' }}
+ _groupHover={{ opacity: 1, pointerEvents: 'auto' }}
+ >
+ <Tooltip content="Remove image">
+ <IconButton
+ aria-label="Remove model image"
+ colorPalette="red"
+ size="2xs"
+ variant="solid"
+ onClick={(event) => {
+ event.stopPropagation();
+ void handleDelete();
+ }}
+ >
+ <Icon as={XIcon} boxSize="3" />
+ </IconButton>
+ </Tooltip>
+ </Box>
+ ) : null}
+ </Box>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/ModelLibraryList.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelLibraryList.tsx
new file mode 100644
index 0000000000..891444a910
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelLibraryList.tsx
@@ -0,0 +1,305 @@
+import { Box, Checkbox, Flex, HStack, Icon, Image, ScrollArea, Spinner, Stack, Text } from '@chakra-ui/react';
+import { defaultRangeExtractor, useVirtualizer, type Range } from '@tanstack/react-virtual';
+import { BoxIcon } from 'lucide-react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+
+import { getModelImageUrl } from '../../models/api';
+import { filterModels, flattenGroupsToRows, groupModelsByType, type ModelLibraryFilters } from '../../models/library';
+import { useModelsSnapshot } from '../../models/modelsStore';
+import { formatBytes } from '../../models/taxonomy';
+import type { ModelConfig } from '../../models/types';
+import { getLibraryScrollOffset, saveLibraryScrollOffset } from '../../models/uiStore';
+import { ModelBadgeRow } from './ModelBadges';
+import { ModelRowContextMenu, type ModelContextMenuTarget } from './ModelRowContextMenu';
+
+const HEADER_ROW_HEIGHT_PX = 30;
+const MODEL_ROW_HEIGHT_PX = 56;
+
+/**
+ * Virtualized, grouped model library. Group headers and model rows share one
+ * flat virtualized list (smooth at thousands of models). The current group's
+ * header is rendered as a pinned overlay above the scroll viewport — CSS
+ * sticky positioning is unreliable inside ScrollArea's content wrapper — and
+ * the virtual content lives in ScrollArea.Content so the scrollbar thumb is
+ * measured correctly. Rows carry a thumbnail, a right-click action menu, and —
+ * when `onToggleSelected` is provided — bulk-select checkboxes.
+ */
+export const ModelLibraryList = ({
+ activeModelKey,
+ filters,
+ instanceId,
+ onActivate,
+ onToggleSelected,
+ selectedKeys,
+}: {
+ activeModelKey: string | null;
+ filters: ModelLibraryFilters;
+ /** Identifies this list's scroll-offset slot ('panel', 'center', ...). */
+ instanceId: string;
+ onActivate: (model: ModelConfig) => void;
+ /** Present in center view: enables bulk-select checkboxes. */
+ onToggleSelected?: (model: ModelConfig) => void;
+ selectedKeys?: ReadonlySet<string>;
+}) => {
+ const { coverImageVersions, error, missingModelKeys, models, status } = useModelsSnapshot();
+ const scrollRef = useRef<HTMLDivElement | null>(null);
+ const [contextMenuTarget, setContextMenuTarget] = useState<ModelContextMenuTarget | null>(null);
+
+ const rows = useMemo(
+ () => flattenGroupsToRows(groupModelsByType(filterModels(models, filters, missingModelKeys))),
+ [filters, missingModelKeys, models]
+ );
+
+ const headerIndexes = useMemo(() => rows.flatMap((row, index) => (row.kind === 'header' ? [index] : [])), [rows]);
+ const pinnedHeaderIndexRef = useRef<number | null>(null);
+
+ // Track which group the viewport is inside. rangeExtractor sees the exact
+ // visible range on every scroll, before render, so a ref read during render
+ // is always current.
+ const rangeExtractor = useCallback(
+ (range: Range) => {
+ pinnedHeaderIndexRef.current =
+ [...headerIndexes].reverse().find((index) => range.startIndex >= index) ?? headerIndexes[0] ?? null;
+
+ return defaultRangeExtractor(range);
+ },
+ [headerIndexes]
+ );
+
+ const virtualizer = useVirtualizer({
+ count: rows.length,
+ estimateSize: (index) => (rows[index]?.kind === 'header' ? HEADER_ROW_HEIGHT_PX : MODEL_ROW_HEIGHT_PX),
+ getScrollElement: () => scrollRef.current,
+ initialOffset: () => getLibraryScrollOffset(instanceId),
+ overscan: 8,
+ rangeExtractor,
+ });
+ const scrollOffsetRef = useRef(virtualizer.scrollOffset ?? 0);
+
+ scrollOffsetRef.current = virtualizer.scrollOffset ?? scrollOffsetRef.current;
+
+ // Persist the offset so switching tabs/regions and coming back lands here.
+ useEffect(
+ () => () => {
+ saveLibraryScrollOffset(instanceId, scrollOffsetRef.current);
+ },
+ [instanceId]
+ );
+
+ if (status === 'loading' || status === 'idle') {
+ return (
+ <Flex align="center" h="full" justify="center" py="8">
+ <Spinner color="fg.subtle" size="sm" />
+ </Flex>
+ );
+ }
+
+ if (status === 'error') {
+ return (
+ <Stack align="center" gap="1" py="8">
+ <Text color="red.400" fontSize="xs" fontWeight="600">
+ Could not load models
+ </Text>
+ <Text color="fg.subtle" fontSize="2xs" maxW="20rem" textAlign="center">
+ {error}
+ </Text>
+ </Stack>
+ );
+ }
+
+ if (rows.length === 0) {
+ return (
+ <Stack align="center" gap="1" py="8">
+ <Text color="fg.muted" fontSize="xs" fontWeight="600">
+ {models.length === 0 ? 'No models installed' : 'No models match your filters'}
+ </Text>
+ <Text color="fg.subtle" fontSize="2xs">
+ {models.length === 0 ? 'Use Add Models to install your first model.' : 'Try clearing the search or filters.'}
+ </Text>
+ </Stack>
+ );
+ }
+
+ const pinnedHeaderIndex = pinnedHeaderIndexRef.current;
+ const pinnedRow = pinnedHeaderIndex === null ? null : rows[pinnedHeaderIndex];
+
+ return (
+ <Box flex="1" minH="0" position="relative" w="full">
+ <ScrollArea.Root h="full" size="xs" variant="hover" w="full">
+ <ScrollArea.Viewport ref={scrollRef} aria-label="Model library" h="full" w="full">
+ <ScrollArea.Content w="full">
+ <Box h={`${virtualizer.getTotalSize()}px`} position="relative" w="full">
+ {virtualizer.getVirtualItems().map((virtualRow) => {
+ const row = rows[virtualRow.index];
+
+ if (!row) {
+ return null;
+ }
+
+ return (
+ <Box
+ key={virtualRow.key}
+ left="0"
+ position="absolute"
+ top="0"
+ transform={`translateY(${virtualRow.start}px)`}
+ w="full"
+ >
+ {row.kind === 'header' ? (
+ <GroupHeader count={row.group.models.length} label={row.group.label} />
+ ) : (
+ <ModelRow
+ imageVersion={coverImageVersions[row.model.key]}
+ isActive={row.model.key === activeModelKey}
+ isMissing={missingModelKeys.has(row.model.key)}
+ isSelected={selectedKeys?.has(row.model.key) ?? false}
+ model={row.model}
+ onActivate={onActivate}
+ onContextMenu={(model, x, y) => setContextMenuTarget({ model, x, y })}
+ onToggleSelected={onToggleSelected}
+ />
+ )}
+ </Box>
+ );
+ })}
+ </Box>
+ </ScrollArea.Content>
+ </ScrollArea.Viewport>
+ <ScrollArea.Scrollbar>
+ <ScrollArea.Thumb />
+ </ScrollArea.Scrollbar>
+ </ScrollArea.Root>
+ {/* Pinned copy of the current group's header, above the viewport.
+ aria-hidden: it duplicates a header already in the list. */}
+ {pinnedRow?.kind === 'header' ? (
+ <Box aria-hidden bg="bg.shell" left="0" pointerEvents="none" position="absolute" right="0" top="0" zIndex={1}>
+ <GroupHeader count={pinnedRow.group.models.length} label={pinnedRow.group.label} />
+ </Box>
+ ) : null}
+ <ModelRowContextMenu target={contextMenuTarget} onClose={() => setContextMenuTarget(null)} />
+ </Box>
+ );
+};
+
+const GroupHeader = ({ count, label }: { count: number; label: string }) => (
+ <HStack bg="bg.canvas" gap="1.5" h={`${HEADER_ROW_HEIGHT_PX}px`} pt="2" px="1" w="full">
+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">
+ {label}
+ </Text>
+ <Text color="fg.subtle" fontSize="2xs">
+ {count}
+ </Text>
+ </HStack>
+);
+
+const ModelRow = ({
+ imageVersion,
+ isActive,
+ isMissing,
+ isSelected,
+ model,
+ onActivate,
+ onContextMenu,
+ onToggleSelected,
+}: {
+ /** Cover-image cache-bust version from the models store. */
+ imageVersion?: number;
+ isActive: boolean;
+ isMissing: boolean;
+ isSelected: boolean;
+ model: ModelConfig;
+ onActivate: (model: ModelConfig) => void;
+ onContextMenu: (model: ModelConfig, x: number, y: number) => void;
+ onToggleSelected?: (model: ModelConfig) => void;
+}) => (
+ <HStack
+ aria-current={isActive || undefined}
+ bg={isActive ? 'accent.widget' : isSelected ? 'bg.surfaceRaised' : 'transparent'}
+ color={isActive ? 'accent.widgetFg' : 'fg.default'}
+ cursor="pointer"
+ gap="2"
+ h={`${MODEL_ROW_HEIGHT_PX - 4}px`}
+ mb="1"
+ minW="0"
+ px="2"
+ role="button"
+ rounded="md"
+ tabIndex={0}
+ textAlign="start"
+ w="full"
+ _focusVisible={{ boxShadow: 'inset 0 0 0 2px var(--chakra-colors-accent-active)', outline: 'none' }}
+ _hover={{ bg: isActive ? 'accent.widget' : 'bg.surfaceRaised' }}
+ onClick={() => onActivate(model)}
+ onContextMenu={(event) => {
+ event.preventDefault();
+ onContextMenu(model, event.clientX, event.clientY);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ onActivate(model);
+ }
+ }}
+ >
+ {onToggleSelected ? (
+ <Checkbox.Root
+ aria-label={`Select ${model.name}`}
+ checked={isSelected}
+ colorPalette="theme"
+ size="xs"
+ onCheckedChange={() => onToggleSelected(model)}
+ onClick={(event) => event.stopPropagation()}
+ >
+ <Checkbox.HiddenInput />
+ <Checkbox.Control />
+ </Checkbox.Root>
+ ) : null}
+ {/* Keyed by version so a stale load error clears when the image changes. */}
+ <ModelRowThumbnail key={imageVersion ?? 0} imageVersion={imageVersion} model={model} />
+ <Stack flex="1" gap="0.5" minW="0">
+ <Text fontSize="xs" fontWeight="600" truncate>
+ {model.name}
+ </Text>
+ <ModelBadgeRow isMissing={isMissing} model={model} />
+ </Stack>
+ <Text color={isActive ? 'accent.widgetFg' : 'fg.subtle'} flexShrink={0} fontSize="2xs">
+ {formatBytes(model.file_size)}
+ </Text>
+ </HStack>
+);
+
+const ModelRowThumbnail = ({ imageVersion, model }: { imageVersion?: number; model: ModelConfig }) => {
+ // The cover_image marker can be stale; fall back to the icon on load error.
+ const [hasImageError, setHasImageError] = useState(false);
+
+ if (!model.cover_image || hasImageError) {
+ return (
+ <Flex
+ align="center"
+ bg="bg.panel"
+ borderColor="border.subtle"
+ borderWidth="1px"
+ boxSize="9"
+ color="fg.subtle"
+ flexShrink={0}
+ justify="center"
+ rounded="md"
+ >
+ <Icon as={BoxIcon} boxSize="4" />
+ </Flex>
+ );
+ }
+
+ return (
+ <Image
+ alt=""
+ boxSize="9"
+ fit="cover"
+ flexShrink={0}
+ loading="lazy"
+ rounded="md"
+ src={getModelImageUrl(model.key, imageVersion ? String(imageVersion) : undefined)}
+ onError={() => setHasImageError(true)}
+ />
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/ModelRowContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelRowContextMenu.tsx
new file mode 100644
index 0000000000..137f4ef2ab
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelRowContextMenu.tsx
@@ -0,0 +1,103 @@
+import { Icon, Menu, Portal } from '@chakra-ui/react';
+import { RefreshCcwIcon, Trash2Icon } from 'lucide-react';
+import { SiHuggingface } from 'react-icons/si';
+import { useRef, useState } from 'react';
+
+import { ConfirmDialog } from '../../components/ui/ConfirmDialog';
+import { MenuContent } from '../../components/ui/Menu';
+import { isConvertibleToDiffusers } from '../../models/taxonomy';
+import type { ModelConfig } from '../../models/types';
+import { useModelActions } from './useModelActions';
+
+export interface ModelContextMenuTarget {
+ model: ModelConfig;
+ x: number;
+ y: number;
+}
+
+/**
+ * Right-click menu for library rows, anchored to the cursor via a virtual
+ * rect. Mirrors the detail page's action menu (re-identify, convert, delete)
+ * through the shared `useModelActions` hook.
+ */
+export const ModelRowContextMenu = ({
+ onClose,
+ target,
+}: {
+ onClose: () => void;
+ target: ModelContextMenuTarget | null;
+}) => {
+ const { convert, reidentify, remove } = useModelActions();
+ const [pendingConfirm, setPendingConfirm] = useState<{ kind: 'delete' | 'convert'; model: ModelConfig } | null>(null);
+ const targetRef = useRef(target);
+
+ targetRef.current = target;
+
+ const model = target?.model ?? null;
+
+ return (
+ <>
+ <Menu.Root
+ key={target ? target.model.key : 'closed'}
+ lazyMount
+ open={target !== null}
+ positioning={{
+ getAnchorRect: () => {
+ const currentTarget = targetRef.current;
+
+ return currentTarget ? { height: 1, width: 1, x: currentTarget.x, y: currentTarget.y } : null;
+ },
+ placement: 'bottom-start',
+ }}
+ unmountOnExit
+ onOpenChange={(event) => {
+ if (!event.open) {
+ onClose();
+ }
+ }}
+ >
+ <Portal>
+ <Menu.Positioner>
+ {model ? (
+ <MenuContent minW="13rem">
+ <Menu.Item value="reidentify" onClick={() => void reidentify(model)}>
+ <Icon as={RefreshCcwIcon} boxSize="3.5" />
+ <Menu.ItemText fontSize="xs">Re-identify model</Menu.ItemText>
+ </Menu.Item>
+ {isConvertibleToDiffusers(model) ? (
+ <Menu.Item value="convert" onClick={() => setPendingConfirm({ kind: 'convert', model })}>
+ <Icon as={SiHuggingface} boxSize="3.5" />
+ <Menu.ItemText fontSize="xs">Convert to diffusers</Menu.ItemText>
+ </Menu.Item>
+ ) : null}
+ <Menu.Separator />
+ <Menu.Item color="red.400" value="delete" onClick={() => setPendingConfirm({ kind: 'delete', model })}>
+ <Icon as={Trash2Icon} boxSize="3.5" />
+ <Menu.ItemText fontSize="xs">Delete model</Menu.ItemText>
+ </Menu.Item>
+ </MenuContent>
+ ) : null}
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ <ConfirmDialog
+ body={
+ pendingConfirm?.kind === 'convert'
+ ? `Convert “${pendingConfirm.model.name}” to the diffusers format in place? The original checkpoint file is replaced by a diffusers folder.`
+ : `Delete “${pendingConfirm?.model.name}”? The database record is removed, and the model files are deleted if they live inside the InvokeAI models directory.`
+ }
+ confirmLabel={pendingConfirm?.kind === 'convert' ? 'Convert' : 'Delete Model'}
+ isOpen={pendingConfirm !== null}
+ title={pendingConfirm?.kind === 'convert' ? 'Convert to diffusers' : 'Delete model'}
+ onClose={() => setPendingConfirm(null)}
+ onConfirm={async () => {
+ if (!pendingConfirm) {
+ return;
+ }
+
+ await (pendingConfirm.kind === 'convert' ? convert(pendingConfirm.model) : remove(pendingConfirm.model));
+ }}
+ />
+ </>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsCenterView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsCenterView.tsx
new file mode 100644
index 0000000000..05a1d91bda
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsCenterView.tsx
@@ -0,0 +1,211 @@
+import { Badge, Box, Flex, HStack, Icon, Separator, Stack, Text } from '@chakra-ui/react';
+import { BoxIcon, Trash2Icon, XIcon } from 'lucide-react';
+import { useEffect, useMemo, useState } from 'react';
+
+import { Button, IconButton } from '../../components/ui/Button';
+import { ConfirmDialog } from '../../components/ui/ConfirmDialog';
+import { Scrollable } from '../../components/ui/Scrollable';
+import { Tabs } from '../../components/ui/Tabs';
+import { bulkDeleteModels } from '../../models/api';
+import { ensureInstallsLoaded, isActiveInstallStatus, useInstallsSnapshot } from '../../models/installsStore';
+import { collectBases, collectTypes } from '../../models/library';
+import { ensureModelsLoaded, refreshModels, removeModelsFromStore, useModelsSnapshot } from '../../models/modelsStore';
+import {
+ pruneModelsUiKeys,
+ toggleModelSelection,
+ updateModelsUi,
+ useModelsUi,
+ type ModelsCenterTab,
+} from '../../models/uiStore';
+import { useNotify } from '../../useNotify';
+import { AddModelsView } from './AddModelsView';
+import { InstallQueueSection } from './InstallQueueSection';
+import { ModelDetail } from './ModelDetail';
+import { ModelFilterBar } from './ModelFilterBar';
+import { ModelLibraryList } from './ModelLibraryList';
+
+/**
+ * Full model manager: Library (master-detail with bulk actions), Add Models
+ * (every install source), and the install Queue with a live activity badge.
+ * Tab choice, selection, and filters live in the models UI store so nothing
+ * resets when the user moves between tabs or away from the center view.
+ */
+export const ModelsCenterView = () => {
+ const { centerTab } = useModelsUi();
+ const { jobs } = useInstallsSnapshot();
+ const activeInstallCount = jobs.filter((job) => isActiveInstallStatus(job.status)).length;
+
+ useEffect(() => {
+ ensureModelsLoaded();
+ ensureInstallsLoaded();
+ }, []);
+
+ return (
+ <Flex direction="column" gap="3" h="full" minH="0" w="full" px="3">
+ <Tabs.Root
+ size="sm"
+ value={centerTab}
+ onValueChange={(event) => updateModelsUi({ centerTab: event.value as ModelsCenterTab })}
+ >
+ <Tabs.List>
+ <Tabs.Trigger fontSize="xs" value="library">
+ Library
+ </Tabs.Trigger>
+ <Tabs.Trigger fontSize="xs" value="add">
+ Add Models
+ </Tabs.Trigger>
+ <Tabs.Trigger fontSize="xs" value="queue">
+ Queue
+ {activeInstallCount > 0 ? (
+ <Badge colorPalette="blue" fontSize="2xs" ms="1" size="sm" variant="solid">
+ {activeInstallCount}
+ </Badge>
+ ) : null}
+ </Tabs.Trigger>
+ </Tabs.List>
+ </Tabs.Root>
+ <Box flex="1" minH="0">
+ {centerTab === 'library' ? <LibraryMasterDetail /> : null}
+ {centerTab === 'add' ? <AddModelsView /> : null}
+ {centerTab === 'queue' ? (
+ <Box h="full" maxW="48rem" minH="0">
+ <InstallQueueSection />
+ </Box>
+ ) : null}
+ </Box>
+ </Flex>
+ );
+};
+
+const LibraryMasterDetail = () => {
+ const notify = useNotify();
+ const { missingModelKeys, models } = useModelsSnapshot();
+ const { activeModelKey, filters, selectedKeys } = useModelsUi();
+ const [isBulkDeleteOpen, setIsBulkDeleteOpen] = useState(false);
+
+ const availableTypes = useMemo(() => collectTypes(models), [models]);
+ const availableBases = useMemo(() => collectBases(models), [models]);
+
+ const handleBulkDelete = async () => {
+ const keys = [...selectedKeys];
+
+ try {
+ const result = await bulkDeleteModels(keys);
+
+ removeModelsFromStore(result.deleted);
+ pruneModelsUiKeys(result.deleted);
+ updateModelsUi({ selectedKeys: new Set(result.failed.map((failure) => failure.key)) });
+
+ if (result.failed.length > 0) {
+ notify.error(
+ 'Some models could not be deleted',
+ `${result.deleted.length} deleted; ${result.failed.length} failed: ${result.failed[0]?.error ?? ''}`
+ );
+ } else {
+ notify.success(
+ 'Models deleted',
+ `${result.deleted.length} model${result.deleted.length === 1 ? '' : 's'} deleted.`
+ );
+ }
+ } catch (error) {
+ notify.error('Bulk delete failed', error instanceof Error ? error.message : String(error));
+ void refreshModels();
+ }
+ };
+
+ return (
+ <Flex h="full" minH="0" w="full" gap="2">
+ <Stack flexShrink={0} gap="2" h="full" minH="0" position="relative" w="22rem">
+ <ModelFilterBar
+ availableBases={availableBases}
+ availableTypes={availableTypes}
+ filters={filters}
+ missingCount={missingModelKeys.size}
+ onChange={(nextFilters) => updateModelsUi({ filters: nextFilters })}
+ />
+ <ModelLibraryList
+ activeModelKey={activeModelKey}
+ filters={filters}
+ instanceId="center"
+ selectedKeys={selectedKeys}
+ onActivate={(model) => updateModelsUi({ activeModelKey: model.key })}
+ onToggleSelected={(model) => toggleModelSelection(model.key)}
+ />
+ {/* ActionBar-styled, but plain markup: dialog-based action bars
+ dismiss on outside interaction, which would clear the selection on
+ every additional click. Floats over the list, never shifts it. */}
+ {selectedKeys.size > 0 ? (
+ <HStack
+ bg="bg.surfaceRaised"
+ borderColor="border.emphasis"
+ borderWidth="1px"
+ bottom="2"
+ gap="2"
+ insetX="2"
+ p="1.5"
+ position="absolute"
+ rounded="lg"
+ shadow="lg"
+ zIndex={2}
+ >
+ <Text
+ borderColor="border.subtle"
+ borderStyle="dashed"
+ borderWidth="1px"
+ color="fg.muted"
+ fontSize="2xs"
+ fontWeight="600"
+ px="2"
+ py="1"
+ rounded="md"
+ >
+ {selectedKeys.size} selected
+ </Text>
+ <Separator borderColor="border.subtle" h="5" orientation="vertical" />
+ <Button colorPalette="red" size="2xs" variant="solid" onClick={() => setIsBulkDeleteOpen(true)}>
+ <Icon as={Trash2Icon} boxSize="3" />
+ Delete
+ </Button>
+ <Box flex="1" />
+ <IconButton
+ aria-label="Clear selection"
+ size="2xs"
+ variant="ghost"
+ onClick={() => updateModelsUi({ selectedKeys: new Set() })}
+ >
+ <Icon as={XIcon} boxSize="3" />
+ </IconButton>
+ </HStack>
+ ) : null}
+ </Stack>
+ <Scrollable flex="1" h="full" label="Model details" minH="0" minW="0" ps="4" pe="1" borderStartWidth={1}>
+ {activeModelKey !== null ? (
+ <ModelDetail
+ key={activeModelKey}
+ density="full"
+ modelKey={activeModelKey}
+ onDeleted={() => updateModelsUi({ activeModelKey: null })}
+ />
+ ) : (
+ <Flex align="center" direction="column" gap="2" h="full" justify="center">
+ <Icon as={BoxIcon} boxSize="8" color="fg.subtle" />
+ <Text color="fg.muted" fontSize="sm" fontWeight="600">
+ Select a model
+ </Text>
+ <Text color="fg.subtle" fontSize="xs" maxW="22rem" textAlign="center">
+ View details, edit metadata, set per-model defaults, and manage trigger phrases.
+ </Text>
+ </Flex>
+ )}
+ </Scrollable>
+ <ConfirmDialog
+ body={`Delete ${selectedKeys.size} selected model${selectedKeys.size === 1 ? '' : 's'}? Database records are removed, and files inside the InvokeAI models directory are deleted.`}
+ confirmLabel={`Delete ${selectedKeys.size} Model${selectedKeys.size === 1 ? '' : 's'}`}
+ isOpen={isBulkDeleteOpen}
+ title="Delete selected models"
+ onClose={() => setIsBulkDeleteOpen(false)}
+ onConfirm={handleBulkDelete}
+ />
+ </Flex>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsPanelView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsPanelView.tsx
new file mode 100644
index 0000000000..efb457b755
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsPanelView.tsx
@@ -0,0 +1,162 @@
+import { Box, HStack, Icon, Progress, Stack, Text } from '@chakra-ui/react';
+
+import { DownloadIcon, PlusIcon } from 'lucide-react';
+import { useEffect, useMemo } from 'react';
+
+import { Button } from '../../components/ui/Button';
+import { Scrollable } from '../../components/ui/Scrollable';
+import { Tooltip } from '../../components/ui/Tooltip';
+import {
+ ensureInstallsLoaded,
+ isActiveInstallStatus,
+ useInstallProgress,
+ useInstallsSnapshot,
+} from '../../models/installsStore';
+import { collectBases, collectTypes } from '../../models/library';
+import { ensureModelsLoaded, useModelsSnapshot } from '../../models/modelsStore';
+import { openModelsCenterTab, updateModelsUi, useModelsUi } from '../../models/uiStore';
+import { ModelDetail } from './ModelDetail';
+import { ModelFilterBar } from './ModelFilterBar';
+import { ModelLibraryList } from './ModelLibraryList';
+import { useOpenModelManager } from './useOpenModelManager';
+
+/**
+ * Side-panel presentation: a searchable library browser with in-panel
+ * drill-in for quick edits. Installing and bulk work live in the full center
+ * view; the Add button jumps straight to its Add Models tab, the install
+ * footer to its Queue tab. Filters and the drilled-in model persist in the
+ * models UI store across panel/tab switches.
+ */
+export const ModelsPanelView = () => {
+ const { missingModelKeys, models } = useModelsSnapshot();
+ const { filters, panelModelKey } = useModelsUi();
+ const openModelManager = useOpenModelManager();
+
+ useEffect(() => {
+ ensureModelsLoaded();
+ ensureInstallsLoaded();
+ }, []);
+
+ const availableTypes = useMemo(() => collectTypes(models), [models]);
+ const availableBases = useMemo(() => collectBases(models), [models]);
+
+ return (
+ <Box h="full" minH="0" position="relative">
+ {/* Drill-in renders as an overlay so the list below keeps its layout —
+ and therefore its scroll position — for the trip back. */}
+ {panelModelKey !== null ? (
+ <Scrollable bg="bg.shell" inset="0" label="Model details" position="absolute" px="3" zIndex={2}>
+ <ModelDetail
+ key={panelModelKey}
+ density="panel"
+ modelKey={panelModelKey}
+ onBack={() => updateModelsUi({ panelModelKey: null })}
+ onDeleted={() => updateModelsUi({ panelModelKey: null })}
+ />
+ </Scrollable>
+ ) : null}
+ {/* The list stays mounted under the overlay (preserving layout and
+ scroll position) but is inert so it cannot scroll or take focus. */}
+ <Stack gap="2" h="full" inert={panelModelKey !== null} minH="0" px="2">
+ <HStack gap="1.5">
+ <Box flex="1" minW="0">
+ <ModelFilterBar
+ availableBases={availableBases}
+ availableTypes={availableTypes}
+ filters={filters}
+ missingCount={missingModelKeys.size}
+ onChange={(nextFilters) => updateModelsUi({ filters: nextFilters })}
+ />
+ </Box>
+ <Tooltip content="Add models">
+ <Button
+ aria-label="Add models"
+ flexShrink={0}
+ size="sm"
+ variant="solid"
+ onClick={() => {
+ openModelsCenterTab('add');
+ openModelManager();
+ }}
+ >
+ <Icon as={PlusIcon} boxSize="3.5" />
+ Add
+ </Button>
+ </Tooltip>
+ </HStack>
+ <ModelLibraryList
+ activeModelKey={null}
+ filters={filters}
+ instanceId="panel"
+ onActivate={(model) => updateModelsUi({ panelModelKey: model.key })}
+ />
+ <InstallSummaryFooter
+ onOpen={() => {
+ openModelsCenterTab('queue');
+ openModelManager();
+ }}
+ />
+ </Stack>
+ </Box>
+ );
+};
+
+/** Compact live footer: how many installs are running, with progress. */
+const InstallSummaryFooter = ({ onOpen }: { onOpen: () => void }) => {
+ const { jobs } = useInstallsSnapshot();
+ const activeJobs = jobs.filter((job) => isActiveInstallStatus(job.status));
+ const errorCount = jobs.filter((job) => job.status === 'error').length;
+ const firstDownloading = activeJobs.find((job) => job.status === 'downloading');
+
+ if (activeJobs.length === 0 && errorCount === 0) {
+ return null;
+ }
+
+ return (
+ <Stack
+ as="button"
+ bg="bg.surface"
+ borderColor="border.subtle"
+ borderWidth="1px"
+ cursor="pointer"
+ flexShrink={0}
+ gap="1"
+ p="2"
+ rounded="md"
+ textAlign="start"
+ w="full"
+ _hover={{ bg: 'bg.surfaceRaised' }}
+ onClick={onOpen}
+ >
+ <HStack gap="1.5" justify="space-between">
+ <HStack gap="1.5" minW="0">
+ <Icon as={DownloadIcon} boxSize="3" color="fg.muted" />
+ <Text color="fg.muted" fontSize="2xs" fontWeight="600" truncate>
+ {activeJobs.length > 0
+ ? `${activeJobs.length} install${activeJobs.length === 1 ? '' : 's'} in progress`
+ : 'Install queue'}
+ </Text>
+ </HStack>
+ {errorCount > 0 ? (
+ <Text color="red.400" flexShrink={0} fontSize="2xs" fontWeight="600">
+ {errorCount} failed
+ </Text>
+ ) : null}
+ </HStack>
+ {firstDownloading ? <FooterDownloadProgress jobId={firstDownloading.id} /> : null}
+ </Stack>
+ );
+};
+
+const FooterDownloadProgress = ({ jobId }: { jobId: number }) => {
+ const progress = useInstallProgress(jobId);
+ const ratio = progress && progress.totalBytes > 0 ? Math.min(1, progress.bytes / progress.totalBytes) : null;
+
+ return (
+ <Progress.Root aria-label="Install download progress" max={1} size="xs" value={ratio}>
+ <Progress.Track>
+ <Progress.Range />
+ </Progress.Track>
+ </Progress.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsRuntime.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsRuntime.tsx
new file mode 100644
index 0000000000..7e634a83e8
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsRuntime.tsx
@@ -0,0 +1,54 @@
+import { useEffect, useRef } from 'react';
+
+import { refreshInstalls, useInstallOutcomes } from '../../models/installsStore';
+import { refreshModels } from '../../models/modelsStore';
+import { useNotify } from '../../useNotify';
+import { useWorkbench } from '../../WorkbenchContext';
+
+/**
+ * Renders nothing. Keeps the model stores honest across the app lifecycle:
+ * refreshes them when the backend (re)connects, and turns install outcomes
+ * (completed/failed/cancelled) into notifications even when no model manager
+ * surface is mounted — a download that finishes 20 minutes later still toasts.
+ */
+export const ModelsRuntime = () => {
+ const notify = useNotify();
+ const { state } = useWorkbench();
+ const outcomes = useInstallOutcomes();
+ const seenOutcomeIdsRef = useRef<Set<number> | null>(null);
+ const connectionStatus = state.backendConnection.status;
+
+ useEffect(() => {
+ if (connectionStatus === 'connected') {
+ // Reconnects can miss socket events: re-sync both stores.
+ void refreshModels();
+ void refreshInstalls();
+ }
+ }, [connectionStatus]);
+
+ useEffect(() => {
+ if (seenOutcomeIdsRef.current === null) {
+ seenOutcomeIdsRef.current = new Set(outcomes.map((outcome) => outcome.id));
+
+ return;
+ }
+
+ for (const outcome of [...outcomes].reverse()) {
+ if (seenOutcomeIdsRef.current.has(outcome.id)) {
+ continue;
+ }
+
+ seenOutcomeIdsRef.current.add(outcome.id);
+
+ if (outcome.kind === 'completed') {
+ notify.success('Model installed', outcome.modelName ?? outcome.source);
+ } else if (outcome.kind === 'error') {
+ notify.error('Model install failed', `${outcome.source}: ${outcome.error ?? 'Unknown error.'}`);
+ } else {
+ notify.info('Model install cancelled', outcome.source);
+ }
+ }
+ }, [notify, outcomes]);
+
+ return null;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsWidgetView.tsx
new file mode 100644
index 0000000000..32544dac4a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/ModelsWidgetView.tsx
@@ -0,0 +1,16 @@
+import type { WidgetViewProps } from '../../types';
+import { ModelsCenterView } from './ModelsCenterView';
+import { ModelsPanelView } from './ModelsPanelView';
+
+/**
+ * Region router for the models widget: the center region gets the full
+ * manager (library, add models, install queue); side panels get the compact
+ * browser with drill-in detail.
+ */
+export const ModelsWidgetView = ({ region }: WidgetViewProps) => {
+ if (region === 'center') {
+ return <ModelsCenterView />;
+ }
+
+ return <ModelsPanelView />;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/RelatedModelsSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/RelatedModelsSection.tsx
new file mode 100644
index 0000000000..8ef4510bde
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/RelatedModelsSection.tsx
@@ -0,0 +1,172 @@
+import { Badge, Icon, Spinner, Stack, Text } from '@chakra-ui/react';
+import { Link2OffIcon } from 'lucide-react';
+import { useEffect, useMemo, useState } from 'react';
+
+import { ModelSelect } from '../../components/ModelSelect';
+import { IconButton } from '../../components/ui/Button';
+import { FieldLabel } from '../../components/ui/Field';
+import { Tooltip } from '../../components/ui/Tooltip';
+import { addModelRelationship, getRelatedModelKeys, removeModelRelationship } from '../../models/api';
+import { useModelsSnapshot } from '../../models/modelsStore';
+import { getModelBaseColorPalette, getModelBaseLabel, getModelTypeLabel } from '../../models/taxonomy';
+import type { ModelConfig, ModelTaxonomyType } from '../../models/types';
+import { SourceListItem } from './SourceListItem';
+
+/** 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.
+ * One grouped, compatibility-filtered picker searches every linkable type at
+ * once; linked models render as rows with an unlink action.
+ */
+export const RelatedModelsSection = ({
+ model,
+ onError,
+}: {
+ model: ModelConfig;
+ onError: (message: string) => void;
+}) => {
+ const { models } = useModelsSnapshot();
+ const [relatedKeys, setRelatedKeys] = useState<string[] | null>(null);
+ const [isMutating, setIsMutating] = useState(false);
+
+ useEffect(() => {
+ let isStale = false;
+
+ getRelatedModelKeys(model.key)
+ .then((keys) => {
+ if (!isStale) {
+ setRelatedKeys(keys);
+ }
+ })
+ .catch((error: unknown) => {
+ if (!isStale) {
+ setRelatedKeys([]);
+ onError(error instanceof Error ? error.message : 'Failed to load related models.');
+ }
+ });
+
+ return () => {
+ isStale = true;
+ };
+ }, [model.key, onError]);
+
+ 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 excludeKeys = useMemo(() => new Set([model.key, ...(relatedKeys ?? [])]), [model.key, relatedKeys]);
+
+ const handleAdd = async (target: ModelConfig | null) => {
+ if (!target || isMutating) {
+ return;
+ }
+
+ setIsMutating(true);
+
+ try {
+ await addModelRelationship(model.key, target.key);
+ setRelatedKeys((current) => [...(current ?? []), target.key]);
+ } catch (error) {
+ onError(error instanceof Error ? error.message : 'Failed to link models.');
+ } finally {
+ setIsMutating(false);
+ }
+ };
+
+ const handleRemove = async (key: string) => {
+ setIsMutating(true);
+
+ try {
+ await removeModelRelationship(model.key, key);
+ setRelatedKeys((current) => (current ?? []).filter((existing) => existing !== key));
+ } catch (error) {
+ onError(error instanceof Error ? error.message : 'Failed to unlink models.');
+ } finally {
+ setIsMutating(false);
+ }
+ };
+
+ return (
+ <Stack gap="2">
+ <Stack gap="0.5">
+ <FieldLabel>Related Models</FieldLabel>
+ <Text color="fg.subtle" fontSize="2xs">
+ Link the models that pair well with this one — they are suggested together elsewhere in the app.
+ </Text>
+ </Stack>
+ <ModelSelect
+ excludeKeys={excludeKeys}
+ filter={(candidate) => candidate.base === model.base || candidate.base === 'any' || model.base === 'any'}
+ modelTypes={LINKABLE_TYPES}
+ placeholder="Search compatible models to link…"
+ size="sm"
+ value={null}
+ onChange={(target) => {
+ void handleAdd(target);
+ }}
+ />
+ {relatedKeys === null ? (
+ <Spinner color="fg.subtle" size="xs" />
+ ) : relatedModels.length === 0 ? (
+ <Text color="fg.subtle" fontSize="2xs">
+ No related models linked yet.
+ </Text>
+ ) : (
+ <Stack gap="1.5">
+ {relatedModels.map(({ key, model: relatedModel }) => (
+ <SourceListItem
+ key={key}
+ badges={
+ relatedModel ? (
+ <>
+ <Badge
+ colorPalette={getModelBaseColorPalette(relatedModel.base)}
+ flexShrink={0}
+ fontSize="2xs"
+ size="sm"
+ variant="surface"
+ >
+ {getModelBaseLabel(relatedModel.base)}
+ </Badge>
+ <Badge colorPalette="gray" flexShrink={0} fontSize="2xs" size="sm" variant="outline">
+ {getModelTypeLabel(relatedModel.type)}
+ </Badge>
+ </>
+ ) : undefined
+ }
+ title={relatedModel?.name ?? key}
+ trailing={
+ <Tooltip content="Unlink">
+ <IconButton
+ aria-label={`Unlink ${relatedModel?.name ?? key}`}
+ disabled={isMutating}
+ size="2xs"
+ variant="ghost"
+ onClick={() => {
+ void handleRemove(key);
+ }}
+ >
+ <Icon as={Link2OffIcon} boxSize="3" />
+ </IconButton>
+ </Tooltip>
+ }
+ />
+ ))}
+ </Stack>
+ )}
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/ScanFolderTab.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/ScanFolderTab.tsx
new file mode 100644
index 0000000000..a1d2fb753d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/ScanFolderTab.tsx
@@ -0,0 +1,154 @@
+import { Checkbox, HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';
+import { DownloadIcon, FolderSearchIcon } from 'lucide-react';
+import { useState } from 'react';
+
+import { Button } from '../../components/ui/Button';
+import { Field } from '../../components/ui/Field';
+import { Scrollable } from '../../components/ui/Scrollable';
+import { scanFolderForModels } from '../../models/api';
+import { scanFolderSchema } from '../../models/schemas';
+import { updateModelsUi, useModelsUi } from '../../models/uiStore';
+import { useZodForm } from '../../models/useZodForm';
+import { useNotify } from '../../useNotify';
+import { InstallSourceButton, SourceListItem } from './SourceListItem';
+import { useInstallActions } from './useInstallActions';
+
+/**
+ * Recursively scan a server folder for model files and install them
+ * individually or all at once, optionally in place. The query and results
+ * live in the models UI store, so leaving and revisiting the tab keeps them.
+ */
+export const ScanFolderTab = () => {
+ const notify = useNotify();
+ const { install, pendingSources } = useInstallActions();
+ const { scan } = useModelsUi();
+ const [inplace, setInplace] = useState(true);
+ const [isInstallingAll, setIsInstallingAll] = useState(false);
+ const form = useZodForm(scanFolderSchema, { path: scan?.path ?? '' });
+
+ const handleScan = () =>
+ form.handleSubmit(async ({ path }) => {
+ updateModelsUi({ scan: { path, results: await scanFolderForModels(path) } });
+ });
+
+ const notInstalled = scan?.results.filter((result) => !result.is_installed) ?? [];
+
+ const handleInstallAll = async () => {
+ setIsInstallingAll(true);
+
+ try {
+ let queued = 0;
+
+ for (const result of notInstalled) {
+ // Sequential on purpose: each call returns fast (install is a
+ // background job) and ordering keeps the queue readable.
+ if (await install({ inplace, source: result.path }, { silent: true })) {
+ queued += 1;
+ }
+ }
+
+ if (queued > 0) {
+ notify.success('Installs queued', `${queued} model${queued === 1 ? '' : 's'} queued from the scanned folder.`);
+ }
+ } finally {
+ setIsInstallingAll(false);
+ }
+ };
+
+ return (
+ <Stack gap="4" maxW="40rem">
+ <Field
+ error={form.errors.path ?? form.formError}
+ helpText="An absolute folder path on the machine running InvokeAI. Subfolders are scanned too."
+ label="Folder to Scan"
+ >
+ <HStack gap="1.5">
+ <Input
+ aria-invalid={form.errors.path ? true : undefined}
+ placeholder="/path/to/models"
+ size="sm"
+ value={form.values.path}
+ onChange={(event) => form.setValue('path', event.currentTarget.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ void handleScan();
+ }
+ }}
+ />
+ <Button
+ disabled={form.values.path.trim().length === 0}
+ loading={form.isSubmitting}
+ size="sm"
+ variant="solid"
+ onClick={() => void handleScan()}
+ >
+ <Icon as={FolderSearchIcon} boxSize="3.5" />
+ Scan
+ </Button>
+ </HStack>
+ </Field>
+
+ {scan ? (
+ <Stack gap="2">
+ <HStack justify="space-between" wrap="wrap">
+ <Text color="fg.muted" fontSize="2xs">
+ {scan.results.length} model file{scan.results.length === 1 ? '' : 's'} found · {notInstalled.length} not
+ installed
+ </Text>
+ <HStack gap="3">
+ <Checkbox.Root
+ checked={inplace}
+ colorPalette="theme"
+ size="sm"
+ onCheckedChange={(event) => setInplace(event.checked === true)}
+ >
+ <Checkbox.HiddenInput />
+ <Checkbox.Control />
+ <Checkbox.Label fontSize="2xs">Install in place</Checkbox.Label>
+ </Checkbox.Root>
+ <Button
+ disabled={notInstalled.length === 0}
+ loading={isInstallingAll}
+ size="2xs"
+ variant="solid"
+ onClick={() => void handleInstallAll()}
+ >
+ <Icon as={DownloadIcon} boxSize="3" />
+ Install All ({notInstalled.length})
+ </Button>
+ </HStack>
+ </HStack>
+ {scan.results.length === 0 ? (
+ <Text color="fg.subtle" fontSize="2xs">
+ No model files found in {scan.path}.
+ </Text>
+ ) : (
+ <Scrollable label="Scan results" maxH="50vh">
+ <Stack gap="1.5">
+ {scan.results.map((result) => (
+ <SourceListItem
+ key={result.path}
+ description={result.path}
+ title={result.path.split('/').at(-1) ?? result.path}
+ titleTooltip={result.path}
+ trailing={
+ <InstallSourceButton
+ isInstalled={result.is_installed}
+ isPending={pendingSources.has(result.path)}
+ source={result.path}
+ onInstall={() => {
+ void install({ inplace, source: result.path });
+ }}
+ />
+ }
+ />
+ ))}
+ </Stack>
+ </Scrollable>
+ )}
+ </Stack>
+ ) : null}
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/SourceListItem.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/SourceListItem.tsx
new file mode 100644
index 0000000000..fc201681b0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/SourceListItem.tsx
@@ -0,0 +1,94 @@
+import { Badge, HStack, Icon, Spinner, Stack, Text } from '@chakra-ui/react';
+import { DownloadIcon } from 'lucide-react';
+import type { ReactNode } from 'react';
+
+import { Button } from '../../components/ui/Button';
+import { useActiveInstallSources } from '../../models/installsStore';
+import { openModelsCenterTab } from '../../models/uiStore';
+
+/**
+ * The shared row used by every installable-source list (starter models,
+ * HuggingFace files, folder-scan results, related models): title + badges on
+ * top, optional description below, action on the right.
+ */
+export const SourceListItem = ({
+ badges,
+ description,
+ title,
+ titleTooltip,
+ trailing,
+}: {
+ badges?: ReactNode;
+ description?: ReactNode;
+ title: string;
+ titleTooltip?: string;
+ trailing?: ReactNode;
+}) => (
+ <HStack bg="bg.surface" borderColor="border.subtle" borderWidth="1px" gap="3" p="2.5" rounded="md">
+ <Stack flex="1" gap="0.5" minW="0">
+ <HStack gap="1.5" minW="0">
+ <Text fontSize="xs" fontWeight="600" title={titleTooltip} truncate>
+ {title}
+ </Text>
+ {badges}
+ </HStack>
+ {description ? (
+ <Text color="fg.subtle" fontSize="2xs" lineClamp={2}>
+ {description}
+ </Text>
+ ) : null}
+ </Stack>
+ {trailing}
+ </HStack>
+);
+
+/**
+ * Install action with live state: idle → Install button; queuing/active →
+ * disabled "Installing…" with a jump to the install queue; done → badge.
+ */
+export const InstallSourceButton = ({
+ isInstalled = false,
+ isPending = false,
+ onInstall,
+ source,
+}: {
+ /** Already in the library (renders a static badge). */
+ isInstalled?: boolean;
+ /** The install POST is in flight (before a job exists). */
+ isPending?: boolean;
+ onInstall: () => void;
+ /** Source string used to match an active install job. */
+ source: string;
+}) => {
+ const activeSources = useActiveInstallSources();
+ const isInstalling = isPending || activeSources.has(source);
+
+ if (isInstalled) {
+ return (
+ <Badge colorPalette="green" flexShrink={0} fontSize="2xs" size="sm" variant="surface">
+ Installed
+ </Badge>
+ );
+ }
+
+ if (isInstalling) {
+ return (
+ <HStack flexShrink={0} gap="1.5">
+ <Badge colorPalette="blue" fontSize="2xs" size="sm" variant="surface">
+ <Spinner borderWidth="1.5px" boxSize="2.5" />
+ Installing
+ </Badge>
+ <Button size="2xs" variant="ghost" onClick={() => openModelsCenterTab('queue')}>
+ View queue
+ </Button>
+ </HStack>
+ );
+ }
+
+ return (
+ <Button flexShrink={0} size="2xs" variant="outline" onClick={onInstall}>
+ <Icon as={DownloadIcon} boxSize="3" />
+ Install
+ </Button>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/StarterModelsTab.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/StarterModelsTab.tsx
new file mode 100644
index 0000000000..d2cf9b43b0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/StarterModelsTab.tsx
@@ -0,0 +1,392 @@
+import {
+ Badge,
+ Box,
+ Flex,
+ Grid,
+ HoverCard,
+ HStack,
+ Icon,
+ Input,
+ InputGroup,
+ Menu,
+ Portal,
+ Spinner,
+ Stack,
+ Text,
+} from '@chakra-ui/react';
+import { CheckIcon, DownloadIcon, PackageIcon, SearchIcon, SlidersHorizontalIcon } from 'lucide-react';
+import { useEffect, useMemo, useState } from 'react';
+
+import { Button, IconButton } from '../../components/ui/Button';
+import { MenuContent } from '../../components/ui/Menu';
+import { collectBases, collectTypes } from '../../models/library';
+import { ensureStartersLoaded, useStartersSnapshot } from '../../models/startersStore';
+import { getModelBaseColorPalette, getModelBaseLabel, getModelTypeLabel } from '../../models/taxonomy';
+import type { ModelTaxonomyType, StarterModel, StarterModelBundle } from '../../models/types';
+import { useNotify } from '../../useNotify';
+import { FilterMenuItem } from './ModelFilterBar';
+import { InstallSourceButton, SourceListItem } from './SourceListItem';
+import { useInstallActions } from './useInstallActions';
+
+/**
+ * Curated starter models and one-click bundles, served from the cached
+ * starters store (no refetch on revisit; installs revalidate in background).
+ * Bundles queue every missing model and dependency in the bundle.
+ */
+export const StarterModelsTab = () => {
+ const notify = useNotify();
+ const { install, pendingSources } = useInstallActions();
+ const { error: loadError, response, status } = useStartersSnapshot();
+ const [searchTerm, setSearchTerm] = useState('');
+ const [typeFilter, setTypeFilter] = useState<ModelTaxonomyType | null>(null);
+ const [baseFilter, setBaseFilter] = useState<string | null>(null);
+ const [installingBundle, setInstallingBundle] = useState<string | null>(null);
+
+ useEffect(() => {
+ ensureStartersLoaded();
+ }, []);
+
+ const availableTypes = useMemo(() => collectTypes(response?.starter_models ?? []), [response]);
+ const availableBases = useMemo(() => collectBases(response?.starter_models ?? []), [response]);
+
+ const filteredModels = useMemo(() => {
+ if (!response) {
+ return [];
+ }
+
+ const terms = searchTerm.trim().toLowerCase().split(/\s+/).filter(Boolean);
+
+ return response.starter_models.filter((model) => {
+ if (typeFilter !== null && model.type !== typeFilter) {
+ return false;
+ }
+
+ if (baseFilter !== null && String(model.base) !== baseFilter) {
+ return false;
+ }
+
+ if (terms.length === 0) {
+ return true;
+ }
+
+ const haystack = `${model.name} ${model.description} ${model.base} ${model.type}`.toLowerCase();
+
+ return terms.every((term) => haystack.includes(term));
+ });
+ }, [baseFilter, response, searchTerm, typeFilter]);
+
+ /** Queue a starter model plus its uninstalled dependencies; returns how many jobs were queued. */
+ const queueStarter = async (model: StarterModel): Promise<number> => {
+ const sources = [
+ ...(model.dependencies ?? []).filter((dependency) => !dependency.is_installed).map((dep) => dep.source),
+ model.source,
+ ];
+ let queued = 0;
+
+ for (const source of sources) {
+ if (await install({ source }, { silent: true })) {
+ queued += 1;
+ }
+ }
+
+ return queued;
+ };
+
+ const installStarter = async (model: StarterModel) => {
+ const queued = await queueStarter(model);
+
+ if (queued > 0) {
+ notify.success(
+ 'Model install queued',
+ queued > 1 ? `${model.name} and ${queued - 1} dependenc${queued === 2 ? 'y' : 'ies'}` : model.name
+ );
+ }
+ };
+
+ const installBundle = async (bundle: StarterModelBundle) => {
+ setInstallingBundle(bundle.name);
+
+ try {
+ let queued = 0;
+
+ for (const model of bundle.models) {
+ if (!model.is_installed) {
+ queued += await queueStarter(model);
+ }
+ }
+
+ if (queued > 0) {
+ notify.success('Bundle install queued', `${bundle.name}: ${queued} install${queued === 1 ? '' : 's'} queued.`);
+ }
+ } finally {
+ setInstallingBundle(null);
+ }
+ };
+
+ if (status === 'error' && loadError) {
+ return (
+ <Stack align="center" gap="1" py="8">
+ <Text color="red.400" fontSize="xs" fontWeight="600">
+ Could not load starter models
+ </Text>
+ <Text color="fg.subtle" fontSize="2xs">
+ {loadError}
+ </Text>
+ </Stack>
+ );
+ }
+
+ if (!response) {
+ return (
+ <Flex align="center" justify="center" py="10">
+ <Spinner color="fg.subtle" size="sm" />
+ </Flex>
+ );
+ }
+
+ const bundles = Object.values(response.starter_bundles);
+
+ return (
+ <Stack gap="4">
+ {bundles.length > 0 ? (
+ <Stack gap="2">
+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">
+ Bundles
+ </Text>
+ <Grid gap="2" templateColumns="repeat(auto-fill, minmax(15rem, 1fr))">
+ {bundles.map((bundle) => (
+ <BundleCard
+ key={bundle.name}
+ bundle={bundle}
+ isInstalling={installingBundle === bundle.name}
+ onInstall={() => void installBundle(bundle)}
+ />
+ ))}
+ </Grid>
+ </Stack>
+ ) : null}
+
+ <Stack gap="2">
+ <HStack justify="space-between" wrap="wrap">
+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">
+ Starter Models
+ </Text>
+ <HStack gap="1.5">
+ <Box maxW="18rem" w="full">
+ <InputGroup startElement={<Icon as={SearchIcon} boxSize="3.5" color="fg.subtle" />}>
+ <Input
+ aria-label="Search starter models"
+ placeholder="Search starter models…"
+ size="sm"
+ value={searchTerm}
+ onChange={(event) => setSearchTerm(event.currentTarget.value)}
+ />
+ </InputGroup>
+ </Box>
+ <Menu.Root closeOnSelect={false} positioning={{ placement: 'bottom-end' }}>
+ <Menu.Trigger asChild>
+ <IconButton
+ aria-label="Filter starter models"
+ color={typeFilter !== null || baseFilter !== null ? 'accent.invoke' : 'fg.muted'}
+ size="sm"
+ variant="ghost"
+ >
+ <Icon as={SlidersHorizontalIcon} boxSize="4" />
+ </IconButton>
+ </Menu.Trigger>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="13rem">
+ <Menu.ItemGroup>
+ <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">
+ Model Type
+ </Menu.ItemGroupLabel>
+ <FilterMenuItem
+ isChecked={typeFilter === null}
+ label="All types"
+ value="type-all"
+ onSelect={() => setTypeFilter(null)}
+ />
+ {availableTypes.map((type) => (
+ <FilterMenuItem
+ key={type}
+ isChecked={typeFilter === type}
+ label={getModelTypeLabel(type)}
+ value={`type-${type}`}
+ onSelect={() => setTypeFilter((current) => (current === type ? null : type))}
+ />
+ ))}
+ </Menu.ItemGroup>
+ <Menu.Separator />
+ <Menu.ItemGroup>
+ <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">
+ Base Architecture
+ </Menu.ItemGroupLabel>
+ <FilterMenuItem
+ isChecked={baseFilter === null}
+ label="All bases"
+ value="base-all"
+ onSelect={() => setBaseFilter(null)}
+ />
+ {availableBases.map((base) => (
+ <FilterMenuItem
+ key={base}
+ isChecked={baseFilter === base}
+ label={getModelBaseLabel(base)}
+ value={`base-${base}`}
+ onSelect={() => setBaseFilter((current) => (current === base ? null : base))}
+ />
+ ))}
+ </Menu.ItemGroup>
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ </HStack>
+ </HStack>
+ {filteredModels.length === 0 ? (
+ <Text color="fg.subtle" fontSize="2xs" py="4" textAlign="center">
+ No starter models match your search or filters.
+ </Text>
+ ) : (
+ <Stack gap="1.5">
+ {filteredModels.map((model) => {
+ const dependencyCount = model.dependencies?.length ?? 0;
+
+ return (
+ <SourceListItem
+ key={`${model.source}-${model.name}`}
+ badges={
+ <>
+ <Badge
+ colorPalette={getModelBaseColorPalette(model.base)}
+ flexShrink={0}
+ fontSize="2xs"
+ size="sm"
+ variant="surface"
+ >
+ {getModelBaseLabel(model.base)}
+ </Badge>
+ <Badge colorPalette="gray" flexShrink={0} fontSize="2xs" size="sm" variant="outline">
+ {getModelTypeLabel(model.type)}
+ </Badge>
+ </>
+ }
+ description={`${model.description}${
+ dependencyCount > 0
+ ? ` (installs ${dependencyCount} dependenc${dependencyCount === 1 ? 'y' : 'ies'})`
+ : ''
+ }`}
+ title={model.name}
+ trailing={
+ <InstallSourceButton
+ isInstalled={model.is_installed}
+ isPending={pendingSources.has(model.source)}
+ source={model.source}
+ onInstall={() => void installStarter(model)}
+ />
+ }
+ />
+ );
+ })}
+ </Stack>
+ )}
+ </Stack>
+ </Stack>
+ );
+};
+
+/**
+ * Bundle card whose model list previews in a hover card. The whole card is
+ * the hover trigger so the preview also works when the install button is
+ * disabled (all models installed).
+ */
+const BundleCard = ({
+ bundle,
+ isInstalling,
+ onInstall,
+}: {
+ bundle: StarterModelBundle;
+ isInstalling: boolean;
+ onInstall: () => void;
+}) => {
+ const missingCount = bundle.models.filter((model) => !model.is_installed).length;
+
+ return (
+ <HoverCard.Root closeDelay={100} openDelay={250} positioning={{ placement: 'bottom' }}>
+ <HoverCard.Trigger asChild>
+ <Stack bg="bg.surface" borderColor="border.subtle" borderWidth="1px" gap="2" p="3" rounded="lg">
+ <HStack gap="2">
+ <Icon as={PackageIcon} boxSize="4" color="fg.muted" />
+ <Text flex="1" fontSize="xs" fontWeight="700" minW="0" truncate>
+ {bundle.name}
+ </Text>
+ </HStack>
+ <Text color="fg.subtle" fontSize="2xs">
+ {bundle.models.length} models · {missingCount === 0 ? 'all installed' : `${missingCount} to install`}
+ </Text>
+ <Button
+ disabled={missingCount === 0}
+ loading={isInstalling}
+ size="xs"
+ variant={missingCount === 0 ? 'outline' : 'solid'}
+ w="full"
+ onClick={onInstall}
+ >
+ <Icon as={DownloadIcon} boxSize="3" />
+ {missingCount === 0 ? 'Installed' : 'Install Bundle'}
+ </Button>
+ </Stack>
+ </HoverCard.Trigger>
+ <Portal>
+ <HoverCard.Positioner>
+ <HoverCard.Content
+ bg="bg.surfaceRaised"
+ borderColor="border.emphasis"
+ borderWidth="1px"
+ color="fg.default"
+ p="3"
+ rounded="lg"
+ shadow="lg"
+ w="22rem"
+ >
+ <HoverCard.Arrow>
+ <HoverCard.ArrowTip />
+ </HoverCard.Arrow>
+ {/* Plain overflow box: ScrollArea's content grows to fit long
+ unbroken names, which defeats truncation. */}
+ <Box aria-label={`Models in ${bundle.name}`} maxH="18rem" overflowY="auto">
+ <Stack gap="1.5">
+ <Text color="fg.subtle" fontSize="2xs" fontWeight="700" textTransform="uppercase">
+ In this bundle
+ </Text>
+ {bundle.models.map((model) => (
+ <HStack key={`${model.source}-${model.name}`} gap="1.5" minW="0" w="full">
+ <Icon
+ as={model.is_installed ? CheckIcon : DownloadIcon}
+ boxSize="3"
+ color={model.is_installed ? 'green.400' : 'fg.subtle'}
+ flexShrink={0}
+ />
+ <Text flex="1" fontSize="2xs" minW="0" title={model.name} truncate>
+ {model.name}
+ </Text>
+ <Badge
+ colorPalette={getModelBaseColorPalette(model.base)}
+ flexShrink={0}
+ fontSize="2xs"
+ size="sm"
+ variant="surface"
+ >
+ {getModelBaseLabel(model.base)}
+ </Badge>
+ </HStack>
+ ))}
+ </Stack>
+ </Box>
+ </HoverCard.Content>
+ </HoverCard.Positioner>
+ </Portal>
+ </HoverCard.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/TriggerPhrasesEditor.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/TriggerPhrasesEditor.tsx
new file mode 100644
index 0000000000..8dacefaf9c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/TriggerPhrasesEditor.tsx
@@ -0,0 +1,124 @@
+import { HStack, Icon, Input, Tag, Text, Wrap } from '@chakra-ui/react';
+import { PlusIcon } from 'lucide-react';
+import { useState } from 'react';
+
+import { Button } from '../../components/ui/Button';
+import { Field } from '../../components/ui/Field';
+import { updateModel } from '../../models/api';
+import { replaceModelInStore } from '../../models/modelsStore';
+import { triggerPhraseSchema } from '../../models/schemas';
+import type { ModelConfig } from '../../models/types';
+
+/**
+ * Tag-style editor for a model's trigger phrases. Each add/remove persists
+ * immediately — there is no separate save step for phrases.
+ */
+export const TriggerPhrasesEditor = ({
+ model,
+ onError,
+}: {
+ model: ModelConfig;
+ onError: (message: string) => void;
+}) => {
+ const [draft, setDraft] = useState('');
+ const [error, setError] = useState<string | null>(null);
+ const [isSaving, setIsSaving] = useState(false);
+ const phrases = model.trigger_phrases ?? [];
+
+ const persist = async (nextPhrases: string[]): Promise<boolean> => {
+ setIsSaving(true);
+
+ try {
+ replaceModelInStore(await updateModel(model.key, { trigger_phrases: nextPhrases }));
+
+ return true;
+ } catch (persistError) {
+ onError(persistError instanceof Error ? persistError.message : 'Failed to update trigger phrases.');
+
+ return false;
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ const addPhrase = async () => {
+ const parsed = triggerPhraseSchema.safeParse(draft);
+
+ if (!parsed.success) {
+ setError(parsed.error.issues[0]?.message ?? 'Invalid trigger phrase.');
+ return;
+ }
+
+ if (phrases.some((phrase) => phrase.toLowerCase() === parsed.data.toLowerCase())) {
+ setError('That trigger phrase is already on this model.');
+ return;
+ }
+
+ setError(null);
+
+ // Clear the draft only once it is saved, so a failure never eats the text.
+ if (await persist([...phrases, parsed.data])) {
+ setDraft('');
+ }
+ };
+
+ return (
+ <Field
+ error={error}
+ helpText="Phrases that activate this model, surfaced in the prompt editor."
+ label="Trigger Phrases"
+ >
+ <HStack gap="1.5">
+ <Input
+ aria-invalid={error ? true : undefined}
+ placeholder="Add a trigger phrase…"
+ size="sm"
+ value={draft}
+ onChange={(event) => {
+ setDraft(event.currentTarget.value);
+ setError(null);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ void addPhrase();
+ }
+ }}
+ />
+ <Button
+ disabled={draft.trim().length === 0}
+ loading={isSaving}
+ size="sm"
+ variant="outline"
+ onClick={() => {
+ void addPhrase();
+ }}
+ >
+ <Icon as={PlusIcon} boxSize="3.5" />
+ Add
+ </Button>
+ </HStack>
+ {phrases.length > 0 ? (
+ <Wrap gap="1">
+ {phrases.map((phrase) => (
+ <Tag.Root key={phrase} colorPalette="theme" size="sm" variant="surface">
+ <Tag.Label>{phrase}</Tag.Label>
+ <Tag.EndElement>
+ <Tag.CloseTrigger
+ aria-label={`Remove trigger phrase ${phrase}`}
+ onClick={() => {
+ void persist(phrases.filter((existing) => existing !== phrase));
+ }}
+ />
+ </Tag.EndElement>
+ </Tag.Root>
+ ))}
+ </Wrap>
+ ) : (
+ <Text color="fg.subtle" fontSize="2xs">
+ No trigger phrases yet.
+ </Text>
+ )}
+ </Field>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/UrlInstallTab.tsx b/invokeai/frontend/webv2/src/workbench/widgets/models/UrlInstallTab.tsx
new file mode 100644
index 0000000000..c7c0a94d54
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/UrlInstallTab.tsx
@@ -0,0 +1,104 @@
+import { Checkbox, HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';
+import { DownloadIcon } from 'lucide-react';
+
+import { Button } from '../../components/ui/Button';
+import { Field } from '../../components/ui/Field';
+import { isCivitaiUrl } from '../../models/apiKeys';
+import { installSourceSchema } from '../../models/schemas';
+import { useZodForm } from '../../models/useZodForm';
+import { useInstallActions } from './useInstallActions';
+
+/**
+ * Install from a direct URL (Civitai, arbitrary hosts), a HuggingFace repo id,
+ * or a path on the server's filesystem. Local paths can be installed in place
+ * (left where they are) instead of copied into the models directory.
+ */
+export const UrlInstallTab = () => {
+ const { install } = useInstallActions();
+ const form = useZodForm(installSourceSchema, { accessToken: '', inplace: true, source: '' });
+
+ const looksLocal = form.values.source.startsWith('/') || /^[A-Za-z]:[\\/]/.test(form.values.source);
+ const looksCivitai = isCivitaiUrl(form.values.source);
+
+ const handleInstall = () =>
+ form.handleSubmit(async (values) => {
+ const ok = await install({
+ accessToken: values.accessToken === '' ? undefined : values.accessToken,
+ inplace: looksLocal ? values.inplace : undefined,
+ source: values.source,
+ });
+
+ if (ok) {
+ form.reset();
+ }
+ });
+
+ return (
+ <Stack gap="4" maxW="40rem">
+ <Field
+ error={form.errors.source ?? form.formError}
+ helpText="A model file URL, civitai.com model URL, HuggingFace repo id, or a path on the InvokeAI server."
+ label="Model Source"
+ >
+ <Input
+ aria-invalid={form.errors.source ? true : undefined}
+ placeholder="https://civitai.com/… · owner/repo · /path/on/server/model.safetensors"
+ size="sm"
+ value={form.values.source}
+ onChange={(event) => form.setValue('source', event.currentTarget.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ void handleInstall();
+ }
+ }}
+ />
+ </Field>
+ {looksLocal ? (
+ <Checkbox.Root
+ checked={form.values.inplace}
+ colorPalette="theme"
+ size="sm"
+ onCheckedChange={(event) => form.setValue('inplace', event.checked === true)}
+ >
+ <Checkbox.HiddenInput />
+ <Checkbox.Control />
+ <Checkbox.Label fontSize="xs">Install in place (leave the file where it is)</Checkbox.Label>
+ </Checkbox.Root>
+ ) : null}
+ {looksCivitai ? (
+ <Text color="fg.subtle" fontSize="2xs">
+ Your saved Civitai API key is attached automatically if this download requires login.
+ </Text>
+ ) : null}
+ <Field
+ error={form.errors.accessToken}
+ helpText="Optional. Overrides saved keys for this one download."
+ label="Access Token"
+ >
+ <Input
+ placeholder="Only needed for protected URLs"
+ size="sm"
+ type="password"
+ value={form.values.accessToken ?? ''}
+ onChange={(event) => form.setValue('accessToken', event.currentTarget.value)}
+ />
+ </Field>
+ <HStack>
+ <Button
+ disabled={form.values.source.trim().length === 0}
+ loading={form.isSubmitting}
+ size="sm"
+ variant="solid"
+ onClick={() => void handleInstall()}
+ >
+ <Icon as={DownloadIcon} boxSize="3.5" />
+ Install Model
+ </Button>
+ </HStack>
+ <Text color="fg.subtle" fontSize="2xs">
+ Manage HuggingFace, Civitai, and external provider keys in the API Keys tab.
+ </Text>
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/models/index.ts
new file mode 100644
index 0000000000..957777c6e0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/index.ts
@@ -0,0 +1,15 @@
+import type { WidgetManifest } from '../../types';
+import { MaintenanceMenu } from './MaintenanceMenu';
+import { ModelsWidgetView } from './ModelsWidgetView';
+
+export const modelsWidgetManifest: WidgetManifest = {
+ failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
+ headerActions: MaintenanceMenu,
+ icon: 'lucide-react:box',
+ id: 'models',
+ label: 'Models',
+ labelText: 'Models',
+ regions: ['left', 'right', 'center'],
+ version: 1,
+ view: ModelsWidgetView,
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/useInstallActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/models/useInstallActions.ts
new file mode 100644
index 0000000000..27445065e0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/useInstallActions.ts
@@ -0,0 +1,54 @@
+import { useCallback, useState } from 'react';
+
+import { getAccessTokenForSource } from '../../models/apiKeys';
+import { installModel, type InstallModelRequest } from '../../models/api';
+import { addInstallJob } from '../../models/installsStore';
+import { useNotify } from '../../useNotify';
+
+/**
+ * Shared install entry point: queues an install job, optimistically adds it to
+ * the install store, and surfaces a notification. A saved Civitai API key is
+ * attached automatically for civitai.com URLs unless the caller supplies an
+ * explicit token. Bulk flows pass `silent` and emit one summary notice instead
+ * of a toast per model; failures always notify.
+ */
+export const useInstallActions = () => {
+ const notify = useNotify();
+ const [pendingSources, setPendingSources] = useState<ReadonlySet<string>>(new Set());
+
+ const install = useCallback(
+ async (request: InstallModelRequest, options?: { silent?: boolean }): Promise<boolean> => {
+ setPendingSources((current) => new Set(current).add(request.source));
+
+ try {
+ const job = await installModel({
+ ...request,
+ accessToken: request.accessToken ?? getAccessTokenForSource(request.source),
+ });
+
+ addInstallJob(job);
+
+ if (!options?.silent) {
+ notify.success('Model install queued', request.source);
+ }
+
+ return true;
+ } catch (error) {
+ notify.error('Model install failed to start', error instanceof Error ? error.message : String(error));
+
+ return false;
+ } finally {
+ setPendingSources((current) => {
+ const next = new Set(current);
+
+ next.delete(request.source);
+
+ return next;
+ });
+ }
+ },
+ [notify]
+ );
+
+ return { install, pendingSources };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/useModelActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/models/useModelActions.ts
new file mode 100644
index 0000000000..9e44482052
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/useModelActions.ts
@@ -0,0 +1,56 @@
+import { useCallback } from 'react';
+
+import { convertModelToDiffusers, deleteModel, reidentifyModel } from '../../models/api';
+import { removeModelsFromStore, replaceModelInStore } from '../../models/modelsStore';
+import type { ModelConfig } from '../../models/types';
+import { pruneModelsUiKeys } from '../../models/uiStore';
+import { useNotify } from '../../useNotify';
+
+/**
+ * Lifecycle actions for a single model, shared by the detail page and the
+ * library row context menu so behavior and notifications stay identical.
+ * Confirmation UI is the caller's job; these just act and notify.
+ */
+export const useModelActions = () => {
+ const notify = useNotify();
+
+ const remove = useCallback(
+ async (model: ModelConfig) => {
+ try {
+ await deleteModel(model.key);
+ removeModelsFromStore([model.key]);
+ pruneModelsUiKeys([model.key]);
+ notify.success('Model deleted', model.name);
+ } catch (error) {
+ notify.error('Delete failed', error instanceof Error ? error.message : String(error));
+ }
+ },
+ [notify]
+ );
+
+ const convert = useCallback(
+ async (model: ModelConfig) => {
+ try {
+ replaceModelInStore(await convertModelToDiffusers(model.key));
+ notify.success('Converted to diffusers', model.name);
+ } catch (error) {
+ notify.error('Conversion failed', error instanceof Error ? error.message : String(error));
+ }
+ },
+ [notify]
+ );
+
+ const reidentify = useCallback(
+ async (model: ModelConfig) => {
+ try {
+ replaceModelInStore(await reidentifyModel(model.key));
+ notify.success('Model re-identified', model.name);
+ } catch (error) {
+ notify.error('Re-identify failed', error instanceof Error ? error.message : String(error));
+ }
+ },
+ [notify]
+ );
+
+ return { convert, reidentify, remove };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/models/useOpenModelManager.ts b/invokeai/frontend/webv2/src/workbench/widgets/models/useOpenModelManager.ts
new file mode 100644
index 0000000000..3397640320
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/models/useOpenModelManager.ts
@@ -0,0 +1,20 @@
+import { useCallback } from 'react';
+
+import { useWorkbench } from '../../WorkbenchContext';
+
+/**
+ * Bring the full model manager into the center area, enabling it there first
+ * for projects persisted before the widget existed.
+ */
+export const useOpenModelManager = () => {
+ const { activeProject, dispatch } = useWorkbench();
+ const isEnabledInCenter = activeProject.widgetRegions.center.enabledWidgetIds.includes('models');
+
+ return useCallback(() => {
+ if (!isEnabledInCenter) {
+ dispatch({ region: 'center', type: 'toggleRegionWidget', widgetId: 'models' });
+ }
+
+ dispatch({ region: 'center', type: 'selectRegionWidget', widgetId: 'models' });
+ }, [dispatch, isEnabledInCenter]);
+};
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index 8982a328ff..24a5f470a1 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -91,6 +91,7 @@ describe('workbench widget region defaults', () => {
'queue',
'gallery',
'layers',
+ 'models',
'diagnostics',
]);
expect(getActiveProject(hydratedCustomized).widgetRegions.right.enabledWidgetIds).toEqual(['gallery', 'layers']);
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 3631c76593..595bfee0e8 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -308,6 +308,7 @@ const cloneWidgetStates = (
'history-controls': cloneWidgetState(widgetStates['history-controls'] ?? defaultWidgetStates['history-controls']),
'layout-actions': cloneWidgetState(widgetStates['layout-actions'] ?? defaultWidgetStates['layout-actions']),
layers: cloneWidgetState(widgetStates.layers ?? defaultWidgetStates.layers),
+ models: cloneWidgetState(widgetStates.models ?? defaultWidgetStates.models),
notifications: cloneWidgetState(widgetStates.notifications ?? defaultWidgetStates.notifications),
preview: cloneWidgetState(widgetStates.preview ?? defaultWidgetStates.preview),
queue: cloneWidgetState(widgetStates.queue ?? defaultWidgetStates.queue),
@@ -403,6 +404,7 @@ const createWidgetStates = (): Record<WidgetId, WidgetStateContract> => ({
'history-controls': { id: 'history-controls', label: 'History Controls', values: {}, version: 1 },
'layout-actions': { id: 'layout-actions', label: 'Layout Actions', values: {}, version: 1 },
layers: { id: 'layers', label: 'Layers', values: {}, version: 1 },
+ models: { id: 'models', label: 'Models', values: {}, version: 1 },
notifications: { id: 'notifications', label: 'Notifications', values: {}, version: 1 },
preview: { id: 'preview', label: 'Preview', values: {}, version: 1 },
queue: { id: 'queue', label: 'Queue', values: {}, version: 1 },
@@ -420,7 +422,7 @@ const createWidgetRegions = (): Record<WidgetRegion, WidgetRegionState> => ({
},
right: {
activeWidgetId: 'layers',
- enabledWidgetIds: ['queue', 'gallery', 'layers', 'diagnostics'],
+ enabledWidgetIds: ['queue', 'gallery', 'layers', 'models', 'diagnostics'],
isCollapsed: false,
sizePx: 240,
},
@@ -442,7 +444,7 @@ const createWidgetRegions = (): Record<WidgetRegion, WidgetRegionState> => ({
},
center: {
activeWidgetId: 'canvas',
- enabledWidgetIds: ['canvas', 'gallery', 'preview', 'workflow'],
+ enabledWidgetIds: ['canvas', 'gallery', 'preview', 'workflow', 'models'],
isCollapsed: false,
sizePx: 0,
},