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.

fix(image-map): correct the indexing-unavailable messages and pick up a late model install

Lincoln Stein3b0018ba288b
diff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.json
index e05f773a4b..90439d01d0 100644
--- a/docs/src/generated/settings.json
+++ b/docs/src/generated/settings.json
@@ -855,7 +855,7 @@
},
{
"category": "IMAGE INDEX",
- "default": false,
+ "default": true,
"description": "Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.",
"env_var": "INVOKEAI_IMAGE_INDEX_ENABLED",
"literal_values": [],
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.py
index 204ebc07b1..9811fe848f 100644
--- a/invokeai/app/api/routers/image_map.py
+++ b/invokeai/app/api/routers/image_map.py
@@ -194,6 +194,22 @@ def _cluster_cache_put(user_id: str, key: _ClusterCacheKey, labels: np.ndarray,
_cluster_cache.popitem(last=False)
+def _active_model_id(services) -> Optional[str]:
+ """The running indexer's model id, activating it if the encoder was installed since startup.
+
+ The encoder is often installed *after* the server came up — the image map's
+ own message links the starter install — and `start()` resolved the model
+ only once. Retrying here (throttled by the service) means opening or
+ refreshing the map picks the model up, rather than reporting
+ `model_missing` until the next restart.
+ """
+ model_id = services.image_index.model_id
+ if model_id is None and services.configuration.image_index_enabled:
+ services.image_index.try_activate()
+ model_id = services.image_index.model_id
+ return model_id
+
+
@image_map_router.get("/points", operation_id="get_image_map_points", response_model=ImageMapPointsResponse)
async def get_image_map_points(
current_user: CurrentUserOrDefault,
@@ -207,7 +223,8 @@ async def get_image_map_points(
or stale, a recompute is enqueued and reflected in `state`/`stale`.
"""
services = ApiDependencies.invoker.services
- model_id = services.image_index.model_id
+ # Off the loop: the retry queries the model store.
+ model_id = await asyncio.to_thread(_active_model_id, services)
if model_id is None:
# The service is also inert when indexing is enabled but the
# configured model is not installed; tell the client which case
@@ -876,6 +893,9 @@ async def get_image_map_image_labels(
)
def refresh_image_map(current_user: CurrentUserOrDefault) -> ImageMapRefreshResponse:
"""Requests a recompute of the current user's image map projection."""
+ # The Retry the map offers alongside its "model not installed" message
+ # lands here, so give the install a chance to have landed too.
+ _active_model_id(ApiDependencies.invoker.services)
user_id, is_admin = _scope(current_user)
if not _claim_refresh_slot(user_id):
# Throttled, not failed: `enqueued` already means "was this accepted",
@@ -971,7 +991,7 @@ def update_image_map_vocab(update: ImageMapVocabUpdate, current_user: AdminUserO
def get_image_map_status(current_user: CurrentUserOrDefault) -> ImageMapStatusResponse:
"""Gets embedding index progress and the user's projection cache status."""
services = ApiDependencies.invoker.services
- model_id = services.image_index.model_id
+ model_id = _active_model_id(services)
if model_id is None:
model_missing = services.configuration.image_index_enabled
return ImageMapStatusResponse(
diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.py
index 5bfe0fe936..dbb7538e4f 100644
--- a/invokeai/app/services/config/config_default.py
+++ b/invokeai/app/services/config/config_default.py
@@ -260,7 +260,7 @@ class InvokeAIAppConfig(BaseSettings):
strict_password_checking: bool = Field(default=False, description="Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.")
# IMAGE INDEX
- image_index_enabled: bool = Field(default=False, description="Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.")
+ image_index_enabled: bool = Field(default=True, description="Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.")
image_index_model: str = Field(default="DFN2B-CLIP-ViT-L-14-39B", description="Name of the installed CLIP Vision or SigLIP model used to embed gallery images. Changing the model discards embeddings computed by the previous model.")
image_index_device: Optional[str] = Field(default=None, description="Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.")
image_index_batch_size: int = Field(default=8, gt=0, description="Number of images embedded per batch by the image index worker.")
diff --git a/invokeai/app/services/image_index/image_index_base.py b/invokeai/app/services/image_index/image_index_base.py
index c912ccf3af..41ce558a00 100644
--- a/invokeai/app/services/image_index/image_index_base.py
+++ b/invokeai/app/services/image_index/image_index_base.py
@@ -34,6 +34,18 @@ class ImageIndexServiceBase(ABC):
"""Content hash of the active embedding model, or None if the indexer is not running."""
pass
+ def try_activate(self) -> bool:
+ """Start indexing if the configured embedding model has since been installed.
+
+ Concrete when the base's other methods are abstract because the answer
+ for an inert implementation is simply "whatever it already was": only
+ the real service can pick a model up mid-run. Callers use this on
+ request paths that would otherwise report `model_missing` for the rest
+ of the process. Returns True if the indexer is running on return; may
+ touch the model store, so call it off the event loop.
+ """
+ return self.model_id is not None
+
@abstractmethod
def get_status(self) -> ImageIndexStatus | None:
"""Get index progress counts, or None if the indexer is not running."""
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index 1a36d360ba..4715f52e11 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -1,5 +1,6 @@
import os
import threading
+import time
from pathlib import Path
from queue import Empty, Queue
from typing import TYPE_CHECKING, Any, Callable, Optional
@@ -196,6 +197,12 @@ def warm_up_attention(config: "InvokeAIAppConfig", logger: "Logger") -> None:
logger.warning("Attention warm-up failed", exc_info=True)
+# Minimum gap between re-resolutions of a missing embedding model. The map's
+# status endpoint is polled, and each attempt is a model-store query, so the
+# retry is throttled rather than run per request.
+_ACTIVATION_RETRY_INTERVAL_S = 5.0
+
+
class ImageIndexService(ImageIndexServiceBase):
"""Embeds gallery images on a daemon worker thread.
@@ -249,6 +256,14 @@ class ImageIndexService(ImageIndexServiceBase):
self._invoker: Optional["Invoker"] = None
self._model_config: Optional["AnyModelConfig"] = None
self._model_id: Optional[str] = None
+ # Serializes late activation (try_activate) against itself and stop():
+ # it registers image callbacks and starts the worker, and two concurrent
+ # map requests must not do either twice.
+ self._activation_lock = threading.Lock()
+ self._last_activation_attempt: float = 0.0
+ # Set by stop() so a request that raced shutdown cannot start a worker
+ # the invoker will never join.
+ self._stopped = False
self._encode_fn: Optional[EncodeFn] = None
# RAM-resident model used only in CPU mode; see _encode_with_model.
self._cpu_model: Optional[Any] = None
@@ -699,18 +714,109 @@ class ImageIndexService(ImageIndexServiceBase):
"only 'cpu' selects CPU mode"
)
- if self._encode_fn_override is not None:
- self._encode_fn = self._encode_fn_override
- self._model_id = self._model_id_override
- else:
- model_config = self._resolve_model_config(config.image_index_model)
- if model_config is None:
- invoker.services.logger.warning(self._model_not_installed_message(config.image_index_model))
+ # The whole activation under the same lock the late-activation path
+ # takes: `self._invoker` is assigned above, so a map request arriving
+ # mid-start can reach try_activate, and two unsynchronized activations
+ # would register the image callbacks twice and leave a second worker
+ # that stop() never joins.
+ with self._activation_lock:
+ if self._model_id is not None:
+ # A request beat the invoker to it; that path did the whole job.
return
+ self._last_activation_attempt = time.monotonic()
+ if self._encode_fn_override is not None:
+ self._encode_fn = self._encode_fn_override
+ self._model_id = self._model_id_override
+ else:
+ model_config = self._resolve_model_config(config.image_index_model)
+ if model_config is None:
+ # Not fatal: the model can be installed while the server runs
+ # (the image map offers exactly that), and try_activate picks
+ # it up from the next map request.
+ invoker.services.logger.warning(self._model_not_installed_message(config.image_index_model))
+ return
+ # `_model_id` last: it is what every other thread reads as
+ # "the indexer is running", and embed_image/embed_text raise if
+ # they see it before the encoder behind it.
+ self._model_config = model_config
+ self._encode_fn = self._encode_with_model
+ self._model_id = model_config.hash
+
+ # Unguarded, unlike try_activate's: a failure here aborts the
+ # invoker's start and the server fails to boot, loudly, rather
+ # than serving with a half-started indexer.
+ self._launch_worker(invoker)
+
+ def try_activate(self) -> bool:
+ """Resolve the configured encoder again and start indexing if it is now installed.
+
+ `start()` resolves the model once, at server start, and leaves the
+ service inert when it is missing — so a model installed afterwards (the
+ image map's own message offers that install) would not be indexed until
+ the next restart. The image map endpoints call this, so opening the
+ panel is enough to pick the model up. Throttled, because those
+ endpoints are polled.
+ """
+ # Fast path, unlocked: the overwhelmingly common case is a running
+ # indexer, and every map request would otherwise queue on the lock.
+ if self._model_id is not None:
+ return True
+ invoker = self._invoker
+ if invoker is None or not invoker.services.configuration.image_index_enabled:
+ return False
+
+ with self._activation_lock:
+ if self._model_id is not None:
+ return True
+ if self._stopped or (self._worker is not None and self._worker.is_alive()):
+ return False
+ now = time.monotonic()
+ if now - self._last_activation_attempt < _ACTIVATION_RETRY_INTERVAL_S:
+ return False
+ self._last_activation_attempt = now
+
+ config = invoker.services.configuration
+ try:
+ model_config = self._resolve_model_config(config.image_index_model)
+ except Exception:
+ # Unlike start(), this runs on a request thread: a model-store
+ # failure must degrade the map to `model_missing`, which is
+ # what these endpoints reported before they resolved anything,
+ # rather than turning three read endpoints into 500s.
+ invoker.services.logger.warning("Image index: could not resolve the embedding model", exc_info=True)
+ return False
+ if model_config is None:
+ # Silent: start() already logged the diagnosis once, and this
+ # runs on a polled endpoint.
+ return False
+
+ invoker.services.logger.info(
+ f"Image index: embedding model '{config.image_index_model}' is now installed; starting the indexer"
+ )
+ # `_model_id` last, and rolled back as a set: it is the flag every
+ # other thread reads as "the indexer is running". Published before
+ # the worker exists, a failed launch would wedge the service there
+ # permanently — the fast path above would answer True forever while
+ # nothing consumed the queue, and no later request would retry.
self._model_config = model_config
- self._model_id = model_config.hash
self._encode_fn = self._encode_with_model
+ self._model_id = model_config.hash
+ try:
+ self._launch_worker(invoker)
+ except Exception:
+ self._model_config = None
+ self._encode_fn = None
+ self._model_id = None
+ invoker.services.logger.warning(
+ "Image index: could not start the indexer after the model became available; "
+ "the next image map request will retry",
+ exc_info=True,
+ )
+ return False
+ return True
+ def _launch_worker(self, invoker: "Invoker") -> None:
+ """Wire the image callbacks and start the worker thread. Runs once per active model."""
discarded = invoker.services.image_index_records.delete_embeddings_for_other_models(self._model_id)
if discarded:
invoker.services.logger.info(
@@ -726,6 +832,10 @@ class ImageIndexService(ImageIndexServiceBase):
self._worker.start()
def stop(self, invoker: Optional["Invoker"] = None) -> None:
+ # Under the lock so a map request cannot be midway through starting a
+ # worker that this stop would then never see.
+ with self._activation_lock:
+ self._stopped = True
self._stop_event.set()
if self._worker is not None and self._worker.is_alive():
self._worker.join(timeout=10)
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 2e75b0f056..14a9684363 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -52249,7 +52249,7 @@
"type": "boolean",
"title": "Image Index Enabled",
"description": "Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.",
- "default": false
+ "default": true
},
"image_index_model": {
"type": "string",
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index ed1d063ce1..12d3d46e6f 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -20527,7 +20527,7 @@ export type components = {
/**
* Image Index Enabled
* @description Maintain a semantic embedding index of gallery images, used by the image map and semantic search features.
- * @default false
+ * @default true
*/
image_index_enabled?: boolean;
/**
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx
index 3754ab3e16..14a5e9feec 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.browser.test.tsx
@@ -15,6 +15,74 @@ vi.mock('@workbench/WorkbenchContext', () => ({
// sibling, not its child, so a stand-in is enough.
vi.mock('./ImageMapPlot', () => ({ default: () => <div data-testid="plot" /> }));
+// The install link resolves the configured encoder against the starter
+// catalog and queues it; both come from the models feature, so the catalog is
+// pinned here and the queueing spied on.
+const models = vi.hoisted(() => {
+ // A real subscribable store, like the one behind `useActiveInstallSources`:
+ // putting the encoder into (and out of) an in-flight install has to re-render
+ // whoever read it, which is exactly the path the widget depends on.
+ const listeners = new Set<() => void>();
+ let active: ReadonlySet<string> = new Set<string>();
+
+ return {
+ activeSources: {
+ get: (): ReadonlySet<string> => active,
+ set: (next: Iterable<string>): void => {
+ active = new Set(next);
+ for (const listener of listeners) {
+ listener();
+ }
+ },
+ subscribe: (listener: () => void): (() => void) => {
+ listeners.add(listener);
+
+ return () => listeners.delete(listener);
+ },
+ },
+ ensureStartersLoaded: vi.fn(),
+ install: vi.fn((_request: { config?: unknown; source: string }) => Promise.resolve(true)),
+ };
+});
+
+vi.mock('@features/models', async (importOriginal) => {
+ const { useSyncExternalStore } = await import('react');
+
+ return {
+ ...(await importOriginal<Record<string, unknown>>()),
+ ensureStartersLoaded: models.ensureStartersLoaded,
+ useActiveInstallSources: () =>
+ useSyncExternalStore(models.activeSources.subscribe, models.activeSources.get, models.activeSources.get),
+ useInstallActions: () => ({ install: models.install, installMany: vi.fn(), pendingSources: EMPTY_SOURCES }),
+ useStartersSelector: (selector: (snapshot: unknown) => unknown) =>
+ selector({ response: { starter_models: STARTERS } }),
+ };
+});
+
+const EMPTY_SOURCES: ReadonlySet<string> = new Set<string>();
+const ENCODER_SOURCE = 'apple/DFN2B-CLIP-ViT-L-14-39B';
+const ENCODER_DEPENDENCY_SOURCE = 'InvokeAI/encoder-preprocessor';
+const STARTERS = [
+ {
+ base: 'any',
+ dependencies: [
+ {
+ base: 'any',
+ description: 'Preprocessor',
+ is_installed: false,
+ name: 'encoder-preprocessor',
+ source: ENCODER_DEPENDENCY_SOURCE,
+ type: 'clip_vision',
+ },
+ ],
+ description: 'DFN2B CLIP ViT-L Image Encoder',
+ is_installed: false,
+ name: 'DFN2B-CLIP-ViT-L-14-39B',
+ source: ENCODER_SOURCE,
+ type: 'clip_vision',
+ },
+];
+
vi.mock('@workbench/image-map/imageMapStore', async (importOriginal) => {
const original = (await importOriginal()) as object;
@@ -27,7 +95,7 @@ vi.mock('@workbench/image-map/imageMapStore', async (importOriginal) => {
};
});
-import { imageMapStore } from '@workbench/image-map/imageMapStore';
+import { imageMapStore, refreshImageIndexStatus, refreshImageMapPoints } from '@workbench/image-map/imageMapStore';
import { ImageMapWidgetView } from './ImageMapWidgetView';
@@ -35,9 +103,12 @@ let host: HTMLDivElement | null = null;
let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-const dataFor = (state: Extract<ImageMapState, 'disabled' | 'model_missing'>) => ({
+const dataFor = (
+ state: Extract<ImageMapState, 'disabled' | 'model_missing'>,
+ modelName = 'clip-vit-large-patch14'
+) => ({
clusterEps: null,
- modelName: state === 'model_missing' ? 'clip-vit-large-patch14' : null,
+ modelName: state === 'model_missing' ? modelName : null,
pointCount: 0,
points: [],
stale: false,
@@ -46,11 +117,11 @@ const dataFor = (state: Extract<ImageMapState, 'disabled' | 'model_missing'>) =>
visibleHash: null,
});
-const renderState = async (state: Extract<ImageMapState, 'disabled' | 'model_missing'>) => {
+const renderState = async (state: Extract<ImageMapState, 'disabled' | 'model_missing'>, modelName?: string) => {
imageMapStore.setSnapshot({
clusterLabels: null,
clusterLabelsHash: null,
- data: dataFor(state),
+ data: dataFor(state, modelName),
error: null,
indexCounts: null,
indexUpdatedAt: null,
@@ -67,7 +138,20 @@ const renderState = async (state: Extract<ImageMapState, 'disabled' | 'model_mis
);
};
+/** Every button the message currently offers, in DOM order. */
+const buttonLabels = (): string[] =>
+ Array.from(host?.querySelectorAll('button') ?? []).map((button) => button.textContent ?? '');
+
+/** The install jobs the app currently has in flight, as the widget sees them. */
+const setActiveInstalls = async (sources: string[]) => {
+ await act(() => {
+ models.activeSources.set(sources);
+ });
+};
+
beforeEach(() => {
+ vi.clearAllMocks();
+ models.activeSources.set([]);
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
@@ -82,22 +166,138 @@ afterEach(async () => {
describe('Image Map unavailable states', () => {
it.each([
- ['model_missing', 'Embedding model not installed'],
- ['disabled', 'Image indexing is off'],
- ] as const)('keeps the %s diagnosis visible while exposing a failed refresh', async (state, title) => {
- await renderState(state);
+ [
+ 'model_missing',
+ 'Embedding model not installed',
+ 'To enable image indexing, install the image encoder model',
+ // A standing action: nothing polls while the indexer is inert, so the
+ // message has to offer its own way to ask the server again.
+ ['Check again'],
+ ],
+ [
+ 'disabled',
+ 'Image indexing is off',
+ 'To enable image indexing, set `image_index_enabled: true` in the server configuration file and restart the server to build a semantic index of your gallery.',
+ [],
+ ],
+ ] as const)(
+ 'keeps the %s diagnosis visible while exposing a failed refresh',
+ async (state, title, detail, actions) => {
+ await renderState(state);
+
+ expect(host?.textContent).toContain(title);
+ expect(host?.textContent).toContain(detail);
+ expect(buttonLabels()).toEqual(actions);
+
+ await act(() => {
+ imageMapStore.patchSnapshot({ error: 'The server could not be reached.', loadState: 'error' });
+ });
+
+ expect(host?.textContent).toContain(title);
+ expect(host?.textContent).toContain('The server could not be reached.');
+ expect(host?.querySelector('[role="alert"]')?.textContent).toBe('The server could not be reached.');
+ expect(buttonLabels()).toEqual(['Retry']);
+ }
+ );
+});
+
+describe('Image Map missing-model install link', () => {
+ it('queues the starter install for the configured encoder', async () => {
+ await renderState('model_missing', 'DFN2B-CLIP-ViT-L-14-39B');
+
+ expect(host?.textContent).toContain(
+ 'To enable image indexing, install the image encoder model DFN2B-CLIP-ViT-L-14-39B from the Model Manager to build a semantic index of your gallery.'
+ );
+
+ const link = host?.querySelector('button');
- expect(host?.textContent).toContain(title);
- expect(host?.querySelector('button')).toBeNull();
+ expect(link?.textContent).toBe('DFN2B-CLIP-ViT-L-14-39B');
+ await act(async () => {
+ link?.click();
+ await Promise.resolve();
+ });
+
+ expect(models.install).toHaveBeenCalledWith(expect.objectContaining({ source: 'apple/DFN2B-CLIP-ViT-L-14-39B' }));
+ });
+
+ it('queues the starter dependencies ahead of the model itself', async () => {
+ await renderState('model_missing', 'DFN2B-CLIP-ViT-L-14-39B');
+
+ await act(async () => {
+ host?.querySelector('button')?.click();
+ await Promise.resolve();
+ });
+
+ expect(models.install.mock.calls.map(([request]) => request.source)).toEqual([
+ ENCODER_DEPENDENCY_SOURCE,
+ ENCODER_SOURCE,
+ ]);
+ // The curated metadata rides along, so the model registers under its
+ // starter identity instead of whatever probing guesses.
+ expect(models.install).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ config: expect.objectContaining({ name: 'DFN2B-CLIP-ViT-L-14-39B', type: 'clip_vision' }),
+ source: ENCODER_SOURCE,
+ })
+ );
+ });
+
+ it('reports an in-flight download instead of offering the install again', async () => {
+ models.activeSources.set([ENCODER_SOURCE]);
+ await renderState('model_missing', 'DFN2B-CLIP-ViT-L-14-39B');
+
+ expect(host?.textContent).toContain('DFN2B-CLIP-ViT-L-14-39B (installing…)');
+ expect(buttonLabels()).toEqual(['Check again']);
+ });
+
+ it('asks the server again as soon as the download lands', async () => {
+ models.activeSources.set([ENCODER_SOURCE]);
+ await renderState('model_missing', 'DFN2B-CLIP-ViT-L-14-39B');
+
+ expect(refreshImageMapPoints).not.toHaveBeenCalled();
+
+ await setActiveInstalls([]);
+
+ // The server picks the encoder up on the next request, so this refresh is
+ // what starts indexing without a restart.
+ expect(refreshImageMapPoints).toHaveBeenCalledTimes(1);
+ expect(refreshImageIndexStatus).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the message and the in-flight install mounted while a refresh runs', async () => {
+ models.activeSources.set([ENCODER_SOURCE]);
+ await renderState('model_missing', 'DFN2B-CLIP-ViT-L-14-39B');
+
+ // A refresh flips loadState to `loading`; a spinner here would unmount the
+ // link and lose both the download's pending state and the watcher that
+ // refreshes when it lands.
await act(() => {
- imageMapStore.patchSnapshot({ error: 'The server could not be reached.', loadState: 'error' });
+ imageMapStore.patchSnapshot({ loadState: 'loading' });
});
- expect(host?.textContent).toContain(title);
- expect(host?.textContent).toContain('The server could not be reached.');
- expect(host?.querySelector('[role="alert"]')?.textContent).toBe('The server could not be reached.');
- expect(host?.querySelector('button')?.textContent).toBe('Retry');
+ expect(host?.textContent).toContain('DFN2B-CLIP-ViT-L-14-39B (installing…)');
+
+ await setActiveInstalls([]);
+
+ expect(refreshImageMapPoints).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls back to the default encoder name when the server reports none', async () => {
+ await renderState('model_missing', '');
+
+ expect(host?.textContent).toContain(
+ 'install the image encoder model DFN2B-CLIP-ViT-L-14-39B from the Model Manager'
+ );
+ });
+
+ it('leaves a model the starter catalog does not carry as plain text', async () => {
+ await renderState('model_missing');
+
+ expect(host?.textContent).toContain(
+ 'install the image encoder model clip-vit-large-patch14 from the Model Manager'
+ );
+ expect(buttonLabels()).toEqual(['Check again']);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
index 26dc7cf2f0..4023e5814e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
@@ -1,6 +1,16 @@
+import type { StarterModel } from '@features/models';
import type { WidgetViewProps } from '@workbench/widgetContracts';
+import type { ReactNode } from 'react';
-import { Box, Button, Center, Spinner, Stack, Text } from '@chakra-ui/react';
+import { Box, Button, Center, Link, Spinner, Stack, Text } from '@chakra-ui/react';
+import {
+ ensureStartersLoaded,
+ getStarterModelInstallSources,
+ useActiveInstallSources,
+ useInstallActions,
+ useStartersSelector,
+} from '@features/models';
+import { useMountEffect } from '@platform/react/useMountEffect';
import { getImageMapClickSelectsCluster, getImageMapShowClusterLabels } from '@workbench/image-map/imageMapSettings';
import {
ensureImageMapLoaded,
@@ -11,7 +21,7 @@ import {
} from '@workbench/image-map/imageMapStore';
import { isIndexing } from '@workbench/image-map/indexProgress';
import { useWidgetValuesSelector } from '@workbench/WorkbenchContext';
-import { lazy, Suspense, useEffect } from 'react';
+import { lazy, Suspense, useCallback, useEffect, useMemo, useRef } from 'react';
import { ImageIndexActivityBadge, ImageIndexProgressPanel } from './ImageIndexProgress';
@@ -26,6 +36,18 @@ const handleRefresh = () => {
refreshImageIndexStatus();
};
+// The backend reports the configured model name with `model_missing`, but a
+// response that predates that field, a server that could not read the config,
+// or an `image_index_model: ""` would otherwise leave the sentence with a hole
+// where the model belongs; the config default is the right guess for all three.
+const DEFAULT_IMAGE_INDEX_MODEL = 'DFN2B-CLIP-ViT-L-14-39B';
+
+const EMPTY_STARTERS: readonly StarterModel[] = [];
+
+const selectStarterModels = (snapshot: {
+ response: { starter_models: StarterModel[] } | null;
+}): readonly StarterModel[] => snapshot.response?.starter_models ?? EMPTY_STARTERS;
+
// Module scope: an inline element would be a new value on every render, which
// is both what react-perf/jsx-no-jsx-as-prop forbids and pointless here — the
// fallback never varies.
@@ -94,6 +116,35 @@ export const ImageMapWidgetView = (_props: WidgetViewProps) => {
);
}
+ const retainedDataError = loadState === 'error' ? (error ?? 'Failed to load the image map.') : null;
+
+ // Ahead of the loading spinner, unlike every other message: a refresh from
+ // this state flips `loadState` to `loading`, and flashing a spinner over the
+ // message would unmount the install link — losing the in-flight download's
+ // pending state and the "refresh when it lands" watcher with it. The
+ // diagnosis is also what a refresh is least likely to change.
+ if (data?.state === 'model_missing') {
+ return (
+ <CenteredMessage
+ // A standing action, not just an error retry: the server picks a newly
+ // installed encoder up on a request, and nothing else polls while the
+ // indexer is inert, so this button is the user's only way to ask again
+ // without closing the widget.
+ actionLabel={retainedDataError ? 'Retry' : 'Check again'}
+ detail={
+ <>
+ To enable image indexing, install the image encoder model{' '}
+ <ImageIndexModelInstallLink modelName={data.modelName?.trim() || DEFAULT_IMAGE_INDEX_MODEL} /> from the
+ Model Manager to build a semantic index of your gallery.
+ </>
+ }
+ errorDetail={retainedDataError}
+ onAction={handleRefresh}
+ title="Embedding model not installed"
+ />
+ );
+ }
+
if (loadState === 'idle' || loadState === 'loading') {
return (
<Center h="full">
@@ -113,27 +164,11 @@ export const ImageMapWidgetView = (_props: WidgetViewProps) => {
);
}
- const retainedDataError = loadState === 'error' ? (error ?? 'Failed to load the image map.') : null;
-
- if (data?.state === 'model_missing') {
- const model = data.modelName ?? 'the model named by `image_index_model`';
-
- return (
- <CenteredMessage
- actionLabel={retainedDataError ? 'Retry' : undefined}
- detail={`Image indexing is enabled, but the embedding model '${model}' is not installed. Install the CLIP Vision model with this name, then restart the server.`}
- errorDetail={retainedDataError}
- onAction={retainedDataError ? handleRefresh : undefined}
- title="Embedding model not installed"
- />
- );
- }
-
if (!data || data.state === 'disabled') {
return (
<CenteredMessage
actionLabel={retainedDataError ? 'Retry' : undefined}
- detail="Enable `image_index_enabled` in the server configuration and restart the server to build a semantic index of your gallery."
+ detail="To enable image indexing, set `image_index_enabled: true` in the server configuration file and restart the server to build a semantic index of your gallery."
errorDetail={retainedDataError}
onAction={retainedDataError ? handleRefresh : undefined}
title="Image indexing is off"
@@ -207,7 +242,7 @@ const CenteredMessage = ({
title,
}: {
title: string;
- detail: string;
+ detail: ReactNode;
actionLabel?: string;
errorDetail?: string | null;
onAction?: () => void;
@@ -231,3 +266,76 @@ const CenteredMessage = ({
</Stack>
</Center>
);
+
+/**
+ * The configured encoder's name, as a one-click install when the starter
+ * catalog carries it. Naming a model the user then has to go find by hand is
+ * what made this message unactionable: the starter entry knows the source, so
+ * the message can queue the download (and its dependencies) itself. Falls back
+ * to plain text when the catalog has not loaded, does not know the name (a
+ * hand-configured `image_index_model`), or the download is already running.
+ */
+const ImageIndexModelInstallLink = ({ modelName }: { modelName: string }) => {
+ const starterModels = useStartersSelector(selectStarterModels);
+ const activeInstallSources = useActiveInstallSources();
+ const { install, pendingSources } = useInstallActions();
+
+ useMountEffect(() => {
+ ensureStartersLoaded();
+ });
+
+ const sources = useMemo(() => {
+ const starter = starterModels.find((candidate) => candidate.name === modelName);
+
+ return starter ? getStarterModelInstallSources(starter) : [];
+ }, [modelName, starterModels]);
+
+ const installing = sources.some(
+ (entry) => pendingSources.has(entry.source) || activeInstallSources.has(entry.source)
+ );
+ const wasInstalling = useRef(false);
+
+ // The server picks a freshly installed encoder up on the next map request,
+ // so ask for one as soon as the download lands: without it the panel keeps
+ // saying "not installed" until someone reopens it.
+ useEffect(() => {
+ if (wasInstalling.current && !installing) {
+ handleRefresh();
+ }
+
+ wasInstalling.current = installing;
+ }, [installing]);
+
+ const handleInstall = useCallback(() => {
+ void (async () => {
+ // Sequential, matching the Add Models starter path: the install queue is
+ // ordered anyway, and a dependency must not race the model that needs it.
+ for (const entry of sources) {
+ // Re-checked here rather than trusted from the render that drew the
+ // link: an install of the same source may have started elsewhere (the
+ // Models page, another tab) in between, and queueing it twice
+ // downloads it twice.
+ if (pendingSources.has(entry.source) || activeInstallSources.has(entry.source)) {
+ continue;
+ }
+
+ await install(entry);
+ }
+ })();
+ }, [activeInstallSources, install, pendingSources, sources]);
+
+ if (sources.length === 0 || installing) {
+ return (
+ <Text as="span" fontWeight="medium">
+ {modelName}
+ {installing ? ' (installing…)' : ''}
+ </Text>
+ );
+ }
+
+ return (
+ <Link as="button" colorPalette="accent" onClick={handleInstall} type="button" variant="underline">
+ {modelName}
+ </Link>
+ );
+};
diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.py
index e760eff26c..a267d117b5 100644
--- a/tests/app/routers/test_image_map.py
+++ b/tests/app/routers/test_image_map.py
@@ -267,6 +267,8 @@ def test_points_disabled_when_indexer_not_running(
monkeypatch, mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
) -> None:
image_index_service._model_id = None
+ # Indexing is on by default, so "disabled" has to be asked for explicitly.
+ mock_invoker.services.configuration.image_index_enabled = False
response = client.get("/api/v1/image_map/points")
assert response.status_code == 200
body = response.json()
@@ -385,8 +387,59 @@ def test_status_model_missing_when_enabled_without_model(
assert body["projection"]["state"] == "model_missing"
-def test_status_disabled(image_index_service: FakeImageIndexService, client: TestClient) -> None:
+ "call_endpoint",
+ [
+ pytest.param(lambda client: client.get("/api/v1/image_map/points"), id="points"),
+ pytest.param(lambda client: client.get("/api/v1/image_map/status"), id="status"),
+ pytest.param(lambda client: client.post("/api/v1/image_map/refresh"), id="refresh"),
+ ],
+)
+def test_endpoints_activate_a_model_installed_since_startup(
+ call_endpoint, mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ # The map's own message links the encoder install, so the next request has
+ # to pick the model up rather than repeating "not installed" until a restart.
+ # Asserted per endpoint: each one has to make the attempt on its own, and a
+ # request that found the model already active proves nothing.
+ image_index_service._model_id = None
+ mock_invoker.services.configuration.image_index_enabled = True
+ activations = 0
+
+ def activate() -> bool:
+ nonlocal activations
+ activations += 1
+ image_index_service._model_id = MODEL_ID
+ return True
+
+ image_index_service.try_activate = activate # type: ignore[method-assign]
+
+ response = call_endpoint(client)
+
+ assert response.status_code in (200, 202)
+ assert activations == 1
+ assert image_index_service.model_id == MODEL_ID
+
+
+def test_points_serve_the_index_once_it_is_activated(
+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ image_index_service._model_id = None
+ mock_invoker.services.configuration.image_index_enabled = True
+
+ def activate() -> bool:
+ image_index_service._model_id = MODEL_ID
+ return True
+
+ image_index_service.try_activate = activate # type: ignore[method-assign]
+
+ assert client.get("/api/v1/image_map/points").json()["state"] == "empty"
+ assert client.get("/api/v1/image_map/status").json()["enabled"] is True
+
+
+def test_status_disabled(mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient) -> None:
image_index_service._model_id = None
+ mock_invoker.services.configuration.image_index_enabled = False
body = client.get("/api/v1/image_map/status").json()
assert body["enabled"] is False
assert body["model_name"] is None
diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.py
index cca2dba944..0b7811ed71 100644
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@ -18,6 +18,7 @@ from invokeai.app.services.events.events_common import ImageIndexStatusEvent, Im
from invokeai.app.services.image_index import image_index_default
from invokeai.app.services.image_index.image_index_common import EMBEDDING_DTYPE
from invokeai.app.services.image_index.image_index_default import (
+ _ACTIVATION_RETRY_INTERVAL_S,
_MAX_ATTEMPTS,
_MAX_BACKOFF_SECONDS,
_POLL_SECONDS,
@@ -316,6 +317,131 @@ def test_model_not_installed_message_flags_same_name_wrong_type() -> None:
assert "is not installed" in message
+def test_try_activate_picks_up_a_model_installed_after_startup(
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # The encoder is usually installed from the image map itself, long after
+ # the server came up; that must not need a restart.
+ from invokeai.backend.model_manager.taxonomy import ModelType
+
+ installed: list[object] = []
+ resolutions = 0
+
+ def resolve(self, model_name: str):
+ nonlocal resolutions
+ resolutions += 1
+ return installed[0] if installed else None
+
+ monkeypatch.setattr(ImageIndexService, "_resolve_model_config", resolve)
+ store = SimpleNamespace(search_by_attr=lambda **kwargs: [])
+ invoker = _make_invoker(images_service, index_records, model_manager=SimpleNamespace(store=store))
+ service = ImageIndexService()
+ try:
+ service.start(invoker)
+ assert service.model_id is None
+
+ # Throttled: start() has just resolved, so a poll cannot re-query the
+ # model store on its heels.
+ assert service.try_activate() is False
+ assert resolutions == 1
+
+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
+ assert service.try_activate() is False
+ assert resolutions == 2
+
+ installed.append(SimpleNamespace(hash=MODEL_ID, type=ModelType.CLIPVision, path="/models/encoder"))
+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
+
+ assert service.try_activate() is True
+ assert service.model_id == MODEL_ID
+ _wait_until(lambda: service._worker is not None and service._worker.is_alive())
+ # The fast path: no further model-store queries once it is running.
+ assert service.try_activate() is True
+ assert resolutions == 3
+ finally:
+ service.stop()
+
+ # A request racing shutdown must not start a worker the invoker will never join.
+ service._worker = None
+ service._model_id = None
+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
+ assert service.try_activate() is False
+
+
+def test_failed_late_activation_rolls_back_rather_than_wedging_the_service(
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Publishing the model before the worker exists would leave the service
+ # claiming to run with nothing consuming the queue — and try_activate's
+ # fast path would answer True forever, so no later request would retry.
+ from invokeai.backend.model_manager.taxonomy import ModelType
+
+ resolved = SimpleNamespace(hash=MODEL_ID, type=ModelType.CLIPVision, path="/models/encoder")
+ monkeypatch.setattr(ImageIndexService, "_resolve_model_config", lambda self, model_name: resolved)
+ launches = 0
+
+ def launch(self, invoker):
+ nonlocal launches
+ launches += 1
+ if launches == 1:
+ raise RuntimeError("sqlite write failed")
+ return original_launch(self, invoker)
+
+ original_launch = ImageIndexService._launch_worker
+ store = SimpleNamespace(search_by_attr=lambda **kwargs: [])
+ invoker = _make_invoker(images_service, index_records, model_manager=SimpleNamespace(store=store))
+ service = ImageIndexService()
+ try:
+ # Inert at start: the encoder was not installed yet.
+ monkeypatch.setattr(ImageIndexService, "_resolve_model_config", lambda self, model_name: None)
+ service.start(invoker)
+ assert service.model_id is None
+
+ monkeypatch.setattr(ImageIndexService, "_resolve_model_config", lambda self, model_name: resolved)
+ monkeypatch.setattr(ImageIndexService, "_launch_worker", launch)
+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
+
+ assert service.try_activate() is False
+ # Rolled back, so the state a request reads still says "not running".
+ assert service.model_id is None
+ assert service._encode_fn is None
+ assert service.get_status() is None
+
+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
+
+ assert service.try_activate() is True
+ assert service.model_id == MODEL_ID
+ _wait_until(lambda: service._worker is not None and service._worker.is_alive())
+ finally:
+ service.stop()
+
+
+def test_late_activation_survives_a_model_store_failure(
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # These endpoints reported `model_missing` before they resolved anything;
+ # a model-store failure must not turn them into 500s.
+ def explode(self, model_name):
+ raise RuntimeError("model store unavailable")
+
+ store = SimpleNamespace(search_by_attr=lambda **kwargs: [])
+ invoker = _make_invoker(images_service, index_records, model_manager=SimpleNamespace(store=store))
+ service = ImageIndexService()
+ monkeypatch.setattr(ImageIndexService, "_resolve_model_config", lambda self, model_name: None)
+ service.start(invoker)
+ monkeypatch.setattr(ImageIndexService, "_resolve_model_config", explode)
+ service._last_activation_attempt = time.monotonic() - _ACTIVATION_RETRY_INTERVAL_S - 1
+
+ assert service.try_activate() is False
+ assert service.model_id is None
+
+
def test_broken_encoder_leaves_images_pending_rather_than_quarantined(
image_records: SqliteImageRecordStorage,
images_service: ImageService,
diff --git a/tests/conftest.py b/tests/conftest.py
index 8987001b71..dc7de96b48 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -43,7 +43,10 @@ from tests.test_nodes import TestEventService
@pytest.fixture
def mock_services() -> InvocationServices:
- configuration = InvokeAIAppConfig(use_memory_db=True, node_cache_size=0)
+ # Image indexing is on by default, but `model_manager` below is None: starting
+ # the indexer against these stub services would fail while resolving the
+ # embedding model. Tests that exercise the index enable it themselves.
+ configuration = InvokeAIAppConfig(use_memory_db=True, node_cache_size=0, image_index_enabled=False)
logger = InvokeAILogger.get_logger()
db = create_mock_sqlite_database(configuration, logger)