Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat: semantic gallery search over the embedding index
Lincoln Stein09d0745f757b
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.pyindex 858a9dd8c1..c3178f5e82 100644--- a/invokeai/app/api/routers/image_map.py+++ b/invokeai/app/api/routers/image_map.py@@ -5,12 +5,14 @@ from collections import OrderedDictfrom typing import Literal, Optionalimport numpy as np-from fastapi import Query, status+from fastapi import File, HTTPException, Query, UploadFile, statusfrom fastapi.routing import APIRouterfrom pydantic import BaseModel, Fieldfrom invokeai.app.api.auth_dependencies import CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependencies+from invokeai.app.api.routers._access import assert_image_read_access+from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableErrorfrom invokeai.app.services.image_index.image_index_common import ImageIndexStatusfrom invokeai.app.services.image_index.projection import (DEFAULT_CLUSTER_MIN_SAMPLES,@@ -325,6 +327,255 @@ async def get_image_map_points()+class ImageMapSearchResult(BaseModel):+ """One semantic search hit."""++ image_name: str = Field(description="The matching image")+ score: float = Field(description="Cosine similarity to the query; higher is more similar")+++class ImageMapSearchResponse(BaseModel):+ """Semantic search results over the user's embedded images."""++ results: list[ImageMapSearchResult] = Field(description="Ranked results, most similar first")+++@image_map_router.get("/search", operation_id="search_image_map", response_model=ImageMapSearchResponse)+async def search_image_map(+ current_user: CurrentUserOrDefault,+ q: Optional[str] = Query(default=None, max_length=500, description="Text query to embed and search with"),+ image_name: Optional[str] = Query(default=None, description="Reference image for similarity search"),+ limit: int = Query(default=100, ge=1, le=500, description="Maximum number of results"),+) -> ImageMapSearchResponse:+ """Ranks the user's accessible images by semantic similarity.++ Provide exactly one of `q` (text search — requires the embedding model's+ text encoder to be installed) or `image_name` (visual similarity — uses+ the reference image's stored embedding when it exists, and otherwise+ embeds the image file on demand, so unindexed images such as assets can+ be reference images too).+ """+ services = ApiDependencies.invoker.services+ if (q is None) == (image_name is None):+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Provide exactly one of q or image_name"+ )++ model_id = services.image_index.model_id+ if model_id is None:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail="The image index is not enabled; semantic search is unavailable",+ )++ user_id, is_admin = _scope(current_user)+ scope_user = None if is_admin else user_id++ if q is not None:+ try:+ query_embedding = await asyncio.to_thread(services.image_index.embed_text, q)+ except TextSearchUnavailableError as e:+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))+ else:+ assert image_name is not None+ assert_image_read_access(image_name, current_user)+ found, matrix = services.image_index_records.get_embeddings([image_name], model_id)+ if found:+ query_embedding = matrix[0]+ else:+ # Not in the index (assets and intermediates are never indexed) —+ # embed the stored file on demand for this one query.+ def embed_from_file() -> np.ndarray:+ pil = services.images.get_pil_image(image_name)+ return services.image_index.embed_image(pil)++ try:+ query_embedding = await asyncio.to_thread(embed_from_file)+ except Exception:+ services.logger.warning(f"Image search: failed to embed '{image_name}' on demand", exc_info=True)+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail="This image could not be embedded for search (its file may be missing)",+ )++ results = await asyncio.to_thread(services.image_index.search_similar, scope_user, query_embedding, limit)+ return ImageMapSearchResponse(+ results=[ImageMapSearchResult(image_name=name, score=score) for name, score in results]+ )+++# One-off reference images are small; cap what we will buffer from an upload+# or a URL download before decoding, and how many pixels we will decode.+MAX_SEARCH_IMAGE_BYTES = 32 * 1024 * 1024+MAX_SEARCH_IMAGE_PIXELS = 64_000_000+_URL_TIMEOUT_SECONDS = 10.0+_URL_TOTAL_DEADLINE_SECONDS = 30.0+_URL_MAX_REDIRECTS = 5++# Downloads run on the loop's shared default executor; a handful of slow+# remote servers must not be able to park every thread in it.+_download_slots = asyncio.Semaphore(4)+++def _assert_url_host_allowed(url: str) -> None:+ """Reject URLs whose scheme is not http(s) or whose host resolves to any+ non-global address (loopback, RFC1918, link-local, reserved).++ Resolving via getaddrinfo covers hostnames like 'localhost' and the+ non-canonical IP notations (decimal, hex, octal, shortened) that a plain+ ip_address() literal parse misses. DNS rebinding between this check and+ the actual request is accepted residual risk: the endpoint is+ authenticated, and nothing about the response is revealed beyond whether+ it decoded as an image.+ """+ import ipaddress+ import socket+ from urllib.parse import urlparse++ parsed = urlparse(url)+ if parsed.scheme not in ("http", "https") or not parsed.hostname:+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="image_url must be an http(s) URL")++ port = parsed.port or (443 if parsed.scheme == "https" else 80)+ try:+ infos = socket.getaddrinfo(parsed.hostname, port, proto=socket.IPPROTO_TCP)+ except OSError:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="image_url host could not be resolved"+ )+ for info in infos:+ if not ipaddress.ip_address(info[4][0]).is_global:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="image_url must not target a private or loopback address",+ )+++def _download_search_image(url: str) -> bytes:+ """Fetch a reference image for a one-off similarity search.++ Redirects are followed manually so every hop is re-validated by+ _assert_url_host_allowed — requests' automatic redirect handling would+ happily follow a public URL into a private address. The wall-clock+ deadline bounds slow-trickle servers that never trip the per-read+ timeout.+ """+ import time+ from urllib.parse import urljoin++ import requests++ deadline = time.monotonic() + _URL_TOTAL_DEADLINE_SECONDS+ try:+ for _ in range(_URL_MAX_REDIRECTS + 1):+ _assert_url_host_allowed(url)+ with requests.get(url, stream=True, timeout=_URL_TIMEOUT_SECONDS, allow_redirects=False) as response:+ if response.is_redirect:+ location = response.headers.get("location")+ if not location:+ break+ url = urljoin(url, location)+ continue+ response.raise_for_status()+ chunks: list[bytes] = []+ received = 0+ for chunk in response.iter_content(chunk_size=64 * 1024):+ received += len(chunk)+ if received > MAX_SEARCH_IMAGE_BYTES:+ raise HTTPException(+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,+ detail="The reference image is too large",+ )+ if time.monotonic() > deadline:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="The image download took too long",+ )+ chunks.append(chunk)+ return b"".join(chunks)+ except HTTPException:+ raise+ except Exception:+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="The image could not be downloaded from image_url",+ )+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Too many redirects for image_url")+++@image_map_router.post(+ "/search_by_image", operation_id="search_image_map_by_image", response_model=ImageMapSearchResponse+)+async def search_image_map_by_image(+ current_user: CurrentUserOrDefault,+ image: Optional[UploadFile] = File(default=None, description="Reference image file"),+ image_url: Optional[str] = Query(default=None, max_length=2000, description="URL of a reference image"),+ limit: int = Query(default=100, ge=1, le=500, description="Maximum number of results"),+) -> ImageMapSearchResponse:+ """Ranks the user's accessible images by similarity to an arbitrary reference image.++ Provide exactly one of `image` (multipart upload) or `image_url` (the+ server downloads it). The reference is embedded for this query only —+ nothing is stored.+ """+ services = ApiDependencies.invoker.services+ if (image is None) == (image_url is None):+ raise HTTPException(+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Provide exactly one of image or image_url"+ )++ model_id = services.image_index.model_id+ if model_id is None:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail="The image index is not enabled; semantic search is unavailable",+ )++ user_id, is_admin = _scope(current_user)+ scope_user = None if is_admin else user_id++ if image is not None:+ data = await image.read(MAX_SEARCH_IMAGE_BYTES + 1)+ if len(data) > MAX_SEARCH_IMAGE_BYTES:+ raise HTTPException(+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, detail="The reference image is too large"+ )+ else:+ assert image_url is not None+ async with _download_slots:+ data = await asyncio.to_thread(_download_search_image, image_url)++ def embed_bytes() -> np.ndarray:+ from io import BytesIO++ from PIL import Image++ pil = Image.open(BytesIO(data))+ # The encoder downscales to ~224px anyway; refuse decompression bombs+ # before convert() materializes hundreds of MB of RGB.+ if pil.width * pil.height > MAX_SEARCH_IMAGE_PIXELS:+ raise HTTPException(+ status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, detail="The reference image has too many pixels"+ )+ return services.image_index.embed_image(pil)++ try:+ query_embedding = await asyncio.to_thread(embed_bytes)+ except HTTPException:+ raise+ except Exception:+ services.logger.warning("Image search: failed to decode or embed an uploaded reference image", exc_info=True)+ raise HTTPException(+ status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,+ detail="The reference could not be decoded as an image",+ )++ results = await asyncio.to_thread(services.image_index.search_similar, scope_user, query_embedding, limit)+ return ImageMapSearchResponse(+ results=[ImageMapSearchResult(image_name=name, score=score) for name, score in results]+ )++@image_map_router.post("/refresh",operation_id="refresh_image_map",diff --git a/invokeai/app/services/image_index/image_index_base.py b/invokeai/app/services/image_index/image_index_base.pyindex 7c65bf5520..25f9f9e000 100644--- a/invokeai/app/services/image_index/image_index_base.py+++ b/invokeai/app/services/image_index/image_index_base.py@@ -1,9 +1,16 @@from abc import ABC, abstractmethodfrom typing import Optional+import numpy as np+from PIL import Image+from invokeai.app.services.image_index.image_index_common import ImageIndexStatus+class TextSearchUnavailableError(Exception):+ """The configured embedding model has no usable text tower installed."""++class ImageIndexServiceBase(ABC):"""Background service that keeps the semantic image index up to date.@@ -24,6 +31,55 @@ class ImageIndexServiceBase(ABC):"""Get index progress counts, or None if the indexer is not running."""pass+ @abstractmethod+ def embed_text(self, text: str) -> np.ndarray:+ """Embed a text query into the image embedding space (L2-normalized).++ Slow on first call (loads the model's text tower); cheap afterwards.+ Call off the event loop.++ Raises:+ TextSearchUnavailableError: The indexer is not running, or the+ configured model's directory has no text encoder (some+ vision-only CLIP installs, e.g. for IP-Adapter, ship only the+ image tower).+ """+ pass++ @abstractmethod+ def embed_image(self, image: Image.Image) -> np.ndarray:+ """Embed one image with the index's vision encoder (L2-normalized, (D,)).++ Used for one-off similarity queries (assets and external images that+ are not in the index). Call off the event loop — this may load the+ model.++ Raises:+ RuntimeError: The indexer is not running.+ """+ pass++ @abstractmethod+ def get_accessible_embeddings(self, user_id: str | None) -> tuple[list[str], np.ndarray]:+ """Names + L2-normalized embedding matrix of the user's accessible images.++ Served from a small LRU keyed by the accessible-set scope hash (which+ self-invalidates on any set change). Rows align with names. Pass+ user_id=None for the admin scope. Call off the event loop.+ """+ pass++ @abstractmethod+ def search_similar(self, user_id: str | None, query_embedding: np.ndarray, limit: int) -> list[tuple[str, float]]:+ """Rank the user's accessible embedded images by cosine similarity.++ Embeddings are L2-normalized, so similarity is a dot product. Pass+ user_id=None for the admin scope. Returns (image_name, score) pairs,+ best first. Call off the event loop — the accessible embedding matrix+ may be read from the database on a cache miss.+ """+ pass+@abstractmethoddef request_projection(self,diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.pyindex 8e5a56bd02..a90f5eab8c 100644--- a/invokeai/app/services/image_index/image_index_default.py+++ b/invokeai/app/services/image_index/image_index_default.py@@ -7,12 +7,13 @@ import numpy as npimport torchfrom PIL import Image-from invokeai.app.services.image_index.image_index_base import ImageIndexServiceBase+from invokeai.app.services.image_index.image_index_base import ImageIndexServiceBase, TextSearchUnavailableErrorfrom invokeai.app.services.image_index.image_index_common import EMBEDDING_DTYPE, ImageIndexStatusfrom invokeai.app.services.image_index.projection import compute_umap, projection_params, scope_hashfrom invokeai.app.services.image_records.image_records_common import ImageCategoryfrom invokeai.app.services.images.images_common import ImageDTOfrom invokeai.app.services.session_queue.session_queue_common import DEFAULT_QUEUE_ID+from invokeai.backend.model_manager.load.optimizations import skip_torch_weight_initfrom invokeai.backend.model_manager.taxonomy import ModelTypefrom invokeai.backend.util.devices import TorchDevice@@ -138,6 +139,16 @@ class ImageIndexService(ImageIndexServiceBase):# RAM-resident model used only in CPU mode; see _encode_with_model.self._cpu_model: Optional[Any] = Noneself._processor: Optional[Any] = None+ # Lazily-loaded (tokenizer, text_model, is_siglip); None until first text search.+ self._text_encoder: Optional[tuple[Any, Any, bool]] = None+ self._text_encoder_lock = threading.Lock()+ # Guards the lazy _processor/_cpu_model init: embed_image runs on+ # request threads concurrently with the indexer worker.+ self._vision_init_lock = threading.Lock()+ # scope_hash -> (names, matrix): the accessible embedding matrix for+ # similarity search, so repeated queries skip re-reading BLOBs.+ self._search_cache: dict[str, tuple[list[str], np.ndarray]] = {}+ self._search_cache_lock = threading.Lock()@propertydef model_id(self) -> str | None:@@ -149,6 +160,121 @@ class ImageIndexService(ImageIndexServiceBase):status = self._invoker.services.image_index_records.count_index_status(self._model_id)return status.model_copy(update={"failed": len(self._failed)})+ def embed_image(self, image: Image.Image) -> np.ndarray:+ if self._encode_fn is None:+ raise RuntimeError("The image index is not running")+ rgb = image.convert("RGB")+ try:+ matrix = np.asarray(self._encode_fn([rgb]), dtype=EMBEDDING_DTYPE)+ except Exception:+ # The model cache deletes an entry whose load failed precisely so+ # the next attempt rebuilds it from disk (e.g. an entry left in a+ # bad state by VRAM contention with a concurrent generation).+ # One retry is the cache's designed recovery; the worker gets the+ # same effect from its batch retry loop.+ if self._invoker is not None:+ self._invoker.services.logger.warning(+ "Image embed failed; retrying with a fresh model load", exc_info=True+ )+ matrix = np.asarray(self._encode_fn([rgb]), dtype=EMBEDDING_DTYPE)+ if matrix.ndim != 2 or matrix.shape[0] != 1:+ raise RuntimeError(f"Encoder returned shape {matrix.shape}; expected (1, D)")+ norm = float(np.linalg.norm(matrix[0]))+ return matrix[0] / norm if norm > 0 else matrix[0]++ def embed_text(self, text: str) -> np.ndarray:+ if self._model_id is None:+ raise TextSearchUnavailableError("The image index is not running")++ tokenizer, model, is_siglip = self._get_text_encoder()+ with torch.no_grad():+ # SigLIP was trained with pad-to-max-length; pad-to-longest degrades+ # its text embeddings. CLIP uses ordinary longest-padding.+ inputs = tokenizer(+ [text], padding="max_length" if is_siglip else True, return_tensors="pt", truncation=True+ )+ outputs = model(**inputs)+ embedding = outputs.pooler_output[0] if is_siglip else outputs.text_embeds[0]+ vector = embedding.float().cpu().numpy()+ norm = np.linalg.norm(vector)+ return vector / norm if norm > 0 else vector++ def _get_text_encoder(self) -> tuple[Any, Any, bool]:+ with self._text_encoder_lock:+ if self._text_encoder is None:+ if self._model_config is None:+ raise TextSearchUnavailableError("The image index has no embedding model loaded")++ from transformers import AutoTokenizer, CLIPTextModelWithProjection, SiglipTextModel++ model_path = str(self._model_abs_path())+ is_siglip = self._model_config.type is ModelType.SigLIP+ try:+ tokenizer = AutoTokenizer.from_pretrained(model_path, local_files_only=True)+ text_cls = SiglipTextModel if is_siglip else CLIPTextModelWithProjection+ # skip_torch_weight_init serializes torch module construction+ # process-wide; an unserialized from_pretrained racing another+ # thread's model load leaks meta-device parameters.+ with skip_torch_weight_init():+ model = text_cls.from_pretrained(model_path, local_files_only=True)+ except Exception as e:+ # Vision-only or partial installs (e.g. the IP-Adapter image+ # encoder, or a full-CLIP checkpoint shipped without tokenizer+ # files) fail in assorted ways — transformers raises OSError,+ # TypeError, or ValueError depending on which file is missing.+ # Image-similarity search still works either way.+ raise TextSearchUnavailableError(+ "The configured embedding model's text encoder could not be loaded "+ f"({type(e).__name__}: {e}); install the full CLIP model, including its "+ "tokenizer files, to enable semantic text search"+ ) from e+ model.eval()+ self._text_encoder = (tokenizer, model, is_siglip)+ return self._text_encoder++ def get_accessible_embeddings(self, user_id: str | None) -> tuple[list[str], np.ndarray]:+ if self._invoker is None or self._model_id is None:+ return [], np.empty((0, 0), dtype=EMBEDDING_DTYPE)+ records = self._invoker.services.image_index_records++ names = records.list_accessible_embedded_images(user_id, self._model_id)+ if not names:+ return [], np.empty((0, 0), dtype=EMBEDDING_DTYPE)++ # Memory math: one entry is N x dim float32 (~300 MB at 100k x 768),+ # so the LRU holds two entries and evicts oldest-first rather than+ # clearing wholesale. Keys self-invalidate: any change to the+ # accessible set changes the scope hash.+ cache_key = scope_hash(self._model_id, names)+ with self._search_cache_lock:+ cached = self._search_cache.get(cache_key)+ if cached is not None:+ # LRU touch.+ del self._search_cache[cache_key]+ self._search_cache[cache_key] = cached+ if cached is None:+ # Built outside the lock: a concurrent miss for the same scope+ # transiently builds a duplicate, which beats serializing every+ # search behind a multi-second BLOB read.+ cached = records.get_embeddings(names, self._model_id)+ with self._search_cache_lock:+ while len(self._search_cache) >= 2:+ self._search_cache.pop(next(iter(self._search_cache)))+ self._search_cache[cache_key] = cached++ return cached++ def search_similar(self, user_id: str | None, query_embedding: np.ndarray, limit: int) -> list[tuple[str, float]]:+ found_names, matrix = self.get_accessible_embeddings(user_id)+ if matrix.size == 0:+ return []++ scores = matrix @ query_embedding.astype(matrix.dtype)+ top = min(limit, len(found_names))+ order = np.argpartition(-scores, top - 1)[:top]+ order = order[np.argsort(-scores[order])]+ return [(found_names[index], float(scores[index])) for index in order]+def request_projection(self,user_id: str,@@ -895,19 +1021,24 @@ class ImageIndexService(ImageIndexServiceBase):return self._invoker.services.configuration.models_path / model_pathdef _get_processor(self) -> Any:- if self._processor is None:- from transformers import CLIPImageProcessor, SiglipImageProcessor-- assert self._model_config is not None- processor_cls = SiglipImageProcessor if self._model_config.type is ModelType.SigLIP else CLIPImageProcessor- try:- self._processor = processor_cls.from_pretrained(str(self._model_abs_path()), local_files_only=True)- except OSError:- # InvokeAI-published CLIP Vision model dirs ship no- # preprocessor_config.json; IP-Adapter and FLUX construct the- # processor with defaults for the same reason.- self._processor = processor_cls()- return self._processor+ # embed_image runs on request threads concurrently with the worker,+ # so the lazy init must be guarded (like _get_text_encoder).+ with self._vision_init_lock:+ if self._processor is None:+ from transformers import CLIPImageProcessor, SiglipImageProcessor++ assert self._model_config is not None+ processor_cls = (+ SiglipImageProcessor if self._model_config.type is ModelType.SigLIP else CLIPImageProcessor+ )+ try:+ self._processor = processor_cls.from_pretrained(str(self._model_abs_path()), local_files_only=True)+ except OSError:+ # InvokeAI-published CLIP Vision model dirs ship no+ # preprocessor_config.json; IP-Adapter and FLUX construct the+ # processor with defaults for the same reason.+ self._processor = processor_cls()+ return self._processordef _embed(self, model: Any, images: list[Image.Image], device: torch.device) -> np.ndarray:from transformers import CLIPVisionModelWithProjection, SiglipVisionModel@@ -930,17 +1061,24 @@ class ImageIndexService(ImageIndexServiceBase):if self._cpu_mode():# CPU mode exists to avoid touching the model cache (and VRAM) at- # all, so it keeps its own RAM-resident copy of the model.- if self._cpu_model is None:- from transformers import CLIPVisionModelWithProjection, SiglipVisionModel-- model_path = str(self._model_abs_path())- model_cls = (- SiglipVisionModel if self._model_config.type is ModelType.SigLIP else CLIPVisionModelWithProjection- )- model = model_cls.from_pretrained(model_path, local_files_only=True)- model.eval()- self._cpu_model = model+ # all, so it keeps its own RAM-resident copy of the model. The+ # lazy init is guarded: embed_image calls in from request threads.+ with self._vision_init_lock:+ if self._cpu_model is None:+ from transformers import CLIPVisionModelWithProjection, SiglipVisionModel++ model_path = str(self._model_abs_path())+ model_cls = (+ SiglipVisionModel+ if self._model_config.type is ModelType.SigLIP+ else CLIPVisionModelWithProjection+ )+ # skip_torch_weight_init serializes torch module construction+ # process-wide (see _get_text_encoder).+ with skip_torch_weight_init():+ model = model_cls.from_pretrained(model_path, local_files_only=True)+ model.eval()+ self._cpu_model = modelreturn self._embed(self._cpu_model, images, torch.device("cpu"))loaded = self._invoker.services.model_manager.load.load_model(self._model_config)diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex bbe9a71fd1..0914fd5b08 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -6413,6 +6413,173 @@}}},+ "/api/v1/image_map/search": {+ "get": {+ "tags": ["image_map"],+ "summary": "Search Image Map",+ "description": "Ranks the user's accessible images by semantic similarity.\n\nProvide exactly one of `q` (text search \u2014 requires the embedding model's\ntext encoder to be installed) or `image_name` (visual similarity \u2014 uses\nthe reference image's stored embedding when it exists, and otherwise\nembeds the image file on demand, so unindexed images such as assets can\nbe reference images too).",+ "operationId": "search_image_map",+ "security": [+ {+ "HTTPBearer": []+ }+ ],+ "parameters": [+ {+ "name": "q",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string",+ "maxLength": 500+ },+ {+ "type": "null"+ }+ ],+ "description": "Text query to embed and search with",+ "title": "Q"+ },+ "description": "Text query to embed and search with"+ },+ {+ "name": "image_name",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Reference image for similarity search",+ "title": "Image Name"+ },+ "description": "Reference image for similarity search"+ },+ {+ "name": "limit",+ "in": "query",+ "required": false,+ "schema": {+ "type": "integer",+ "maximum": 500,+ "minimum": 1,+ "description": "Maximum number of results",+ "default": 100,+ "title": "Limit"+ },+ "description": "Maximum number of results"+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ImageMapSearchResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/image_map/search_by_image": {+ "post": {+ "tags": ["image_map"],+ "summary": "Search Image Map By Image",+ "description": "Ranks the user's accessible images by similarity to an arbitrary reference image.\n\nProvide exactly one of `image` (multipart upload) or `image_url` (the\nserver downloads it). The reference is embedded for this query only \u2014\nnothing is stored.",+ "operationId": "search_image_map_by_image",+ "security": [+ {+ "HTTPBearer": []+ }+ ],+ "parameters": [+ {+ "name": "image_url",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string",+ "maxLength": 2000+ },+ {+ "type": "null"+ }+ ],+ "description": "URL of a reference image",+ "title": "Image Url"+ },+ "description": "URL of a reference image"+ },+ {+ "name": "limit",+ "in": "query",+ "required": false,+ "schema": {+ "type": "integer",+ "maximum": 500,+ "minimum": 1,+ "description": "Maximum number of results",+ "default": 100,+ "title": "Limit"+ },+ "description": "Maximum number of results"+ }+ ],+ "requestBody": {+ "content": {+ "multipart/form-data": {+ "schema": {+ "$ref": "#/components/schemas/Body_search_image_map_by_image"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ImageMapSearchResponse"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ }+ }+ },"/api/v1/image_map/refresh": {"post": {"tags": ["image_map"],@@ -17038,6 +17205,25 @@"required": ["video_name"],"title": "Body_remove_video_from_board"},+ "Body_search_image_map_by_image": {+ "properties": {+ "image": {+ "anyOf": [+ {+ "type": "string",+ "format": "binary"+ },+ {+ "type": "null"+ }+ ],+ "title": "Image",+ "description": "Reference image file"+ }+ },+ "type": "object",+ "title": "Body_search_image_map_by_image"+ },"Body_set_workflow_thumbnail": {"properties": {"image": {@@ -41636,6 +41822,40 @@"title": "ImageMapRefreshResponse","description": "Result of a projection refresh request."},+ "ImageMapSearchResponse": {+ "properties": {+ "results": {+ "items": {+ "$ref": "#/components/schemas/ImageMapSearchResult"+ },+ "type": "array",+ "title": "Results",+ "description": "Ranked results, most similar first"+ }+ },+ "type": "object",+ "required": ["results"],+ "title": "ImageMapSearchResponse",+ "description": "Semantic search results over the user's embedded images."+ },+ "ImageMapSearchResult": {+ "properties": {+ "image_name": {+ "type": "string",+ "title": "Image Name",+ "description": "The matching image"+ },+ "score": {+ "type": "number",+ "title": "Score",+ "description": "Cosine similarity to the query; higher is more similar"+ }+ },+ "type": "object",+ "required": ["image_name", "score"],+ "title": "ImageMapSearchResult",+ "description": "One semantic search hit."+ },"ImageMapStatusResponse": {"properties": {"enabled": {diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 2a98dc6d58..62cf4f8392 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -1541,6 +1541,56 @@ export type paths = {patch?: never;trace?: never;};+ "/api/v1/image_map/search": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /**+ * Search Image Map+ * @description Ranks the user's accessible images by semantic similarity.+ *+ * Provide exactly one of `q` (text search — requires the embedding model's+ * text encoder to be installed) or `image_name` (visual similarity — uses+ * the reference image's stored embedding when it exists, and otherwise+ * embeds the image file on demand, so unindexed images such as assets can+ * be reference images too).+ */+ get: operations["search_image_map"];+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };+ "/api/v1/image_map/search_by_image": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Search Image Map By Image+ * @description Ranks the user's accessible images by similarity to an arbitrary reference image.+ *+ * Provide exactly one of `image` (multipart upload) or `image_url` (the+ * server downloads it). The reference is embedded for this query only —+ * nothing is stored.+ */+ post: operations["search_image_map_by_image"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/v1/image_map/refresh": {parameters: {query?: never;@@ -5283,6 +5333,14 @@ export type components = {*/video_name: string;};+ /** Body_search_image_map_by_image */+ Body_search_image_map_by_image: {+ /**+ * Image+ * @description Reference image file+ */+ image?: Blob | null;+ };/** Body_set_workflow_thumbnail */Body_set_workflow_thumbnail: {/**@@ -17456,6 +17514,33 @@ export type components = {*/enqueued: boolean;};+ /**+ * ImageMapSearchResponse+ * @description Semantic search results over the user's embedded images.+ */+ ImageMapSearchResponse: {+ /**+ * Results+ * @description Ranked results, most similar first+ */+ results: components["schemas"]["ImageMapSearchResult"][];+ };+ /**+ * ImageMapSearchResult+ * @description One semantic search hit.+ */+ ImageMapSearchResult: {+ /**+ * Image Name+ * @description The matching image+ */+ image_name: string;+ /**+ * Score+ * @description Cosine similarity to the query; higher is more similar+ */+ score: number;+ };/*** ImageMapStatusResponse* @description Combined index + projection status for the current user.@@ -46039,6 +46124,80 @@ export interface operations {};};};+ search_image_map: {+ parameters: {+ query?: {+ /** @description Text query to embed and search with */+ q?: string | null;+ /** @description Reference image for similarity search */+ image_name?: string | null;+ /** @description Maximum number of results */+ limit?: number;+ };+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["ImageMapSearchResponse"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };+ search_image_map_by_image: {+ parameters: {+ query?: {+ /** @description URL of a reference image */+ image_url?: string | null;+ /** @description Maximum number of results */+ limit?: number;+ };+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: {+ content: {+ "multipart/form-data": components["schemas"]["Body_search_image_map_by_image"];+ };+ };+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["ImageMapSearchResponse"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };refresh_image_map: {parameters: {query?: never;diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 4e06c47f62..cbcdc974da 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2742,6 +2742,8 @@"selectAllOnPage": "Select all gallery images on page","toggleStarImage": "Toggle gallery image star"},+ "clearImageSearch": "Clear image similarity search",+ "clearSemanticSearch": "Clear semantic search","createBoard": "Create board","createBoardNamed": "Create board \"{{name}}\"","collapseStarredItems": "Collapse starred items",@@ -2842,7 +2844,11 @@"searchImagesAriaLabel": "Search gallery items","searchImagesPlaceholder": "Search items","searchOrCreateBoards": "Search or create boards",+ "searchSemantically": "Search semantically","selectedBoardFallback": "selected board",+ "semanticSimilarTo": "Similar to {{name}}",+ "semanticTextSearch": "Semantic search: {{name}}",+ "semanticWebImage": "web image","selectImageForPreview": "Select {{name}} for preview","selectionActions": "Selection actions","selectionCount_one": "{{count}} selected",diff --git a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.tsnew file mode 100644index 0000000000..b43eeb9c49--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.test.ts@@ -0,0 +1,125 @@+import { describe, expect, it } from 'vitest';++import {+ gallerySemanticReferenceKey,+ getExternalImageFile,+ parseGallerySemanticReference,+ registerExternalImageFile,+ semanticReferenceFromDataTransfer,+ toGallerySemanticQuery,+} from './semanticImageQuery';++describe('external image registry', () => {+ it('holds a single slot: registering a new file evicts the previous one', () => {+ const firstId = registerExternalImageFile(new Blob(['first']), 'first.png');++ expect(getExternalImageFile(firstId)).toMatchObject({ label: 'first.png' });++ const secondId = registerExternalImageFile(new Blob(['second']), 'second.png');++ expect(secondId).not.toBe(firstId);+ expect(getExternalImageFile(firstId)).toBe(null);+ expect(getExternalImageFile(secondId)).toMatchObject({ label: 'second.png' });+ });+});++describe('semanticReferenceFromDataTransfer', () => {+ const dataTransfer = (files: File[], uriList = '') => ({+ files,+ getData: (format: string) => (format === 'text/uri-list' ? uriList : ''),+ });++ it('registers dropped image files (winning over URLs) and skips non-images', () => {+ const file = new File(['x'], 'photo.png', { type: 'image/png' });+ const reference = semanticReferenceFromDataTransfer(dataTransfer([file], 'https://a.test/i.png'));++ expect(reference).toMatchObject({ kind: 'file', label: 'photo.png' });++ const nonImage = new File(['x'], 'notes.txt', { type: 'text/plain' });++ expect(semanticReferenceFromDataTransfer(dataTransfer([nonImage]))).toBe(null);+ });++ it("converts this app's own image URLs into by-name queries", () => {+ // Dragging the preview image in must not round-trip through the URL+ // downloader (the server would refuse fetching itself).+ const reference = semanticReferenceFromDataTransfer(+ dataTransfer([], 'http://localhost:5174/api/v1/images/i/ab%20c.png/full')+ );++ expect(reference).toEqual({ imageName: 'ab c.png', kind: 'image' });+ });++ it('passes external http(s) URLs through and rejects other schemes', () => {+ expect(semanticReferenceFromDataTransfer(dataTransfer([], 'https://cdn.test/cat.jpg\n# comment'))).toEqual({+ kind: 'url',+ url: 'https://cdn.test/cat.jpg',+ });+ expect(semanticReferenceFromDataTransfer(dataTransfer([], 'data:image/png;base64,xxxx'))).toBe(null);+ expect(semanticReferenceFromDataTransfer(dataTransfer([]))).toBe(null);+ });+});++describe('parseGallerySemanticReference', () => {+ it('parses legacy strings, structured references, and drops dangling file keys', () => {+ expect(parseGallerySemanticReference('a.png')).toEqual({ imageName: 'a.png', kind: 'image' });+ expect(parseGallerySemanticReference({ kind: 'text', query: 'a sunset' })).toEqual({+ kind: 'text',+ query: 'a sunset',+ });+ expect(parseGallerySemanticReference({ kind: 'text', query: '' })).toBe(null);+ expect(parseGallerySemanticReference({ kind: 'url', url: 'https://x.test/i.png' })).toEqual({+ kind: 'url',+ url: 'https://x.test/i.png',+ });++ const fileId = registerExternalImageFile(new Blob(['x']), 'dropped.png');++ expect(parseGallerySemanticReference({ fileId, kind: 'file', label: 'dropped.png' })).toEqual({+ fileId,+ kind: 'file',+ label: 'dropped.png',+ });+ // Registering evicts prior entries, so a stale key reads as no search.+ registerExternalImageFile(new Blob(['y']), 'newer.png');+ expect(parseGallerySemanticReference({ fileId, kind: 'file', label: 'dropped.png' })).toBe(null);++ expect(parseGallerySemanticReference(undefined)).toBe(null);+ expect(parseGallerySemanticReference({ kind: 'nonsense' })).toBe(null);+ expect(parseGallerySemanticReference('')).toBe(null);+ });+});++describe('semantic reference identity', () => {+ it('keys each kind distinctly and identifies file references by registry id, not label', () => {+ expect(gallerySemanticReferenceKey(null)).toBe('');+ expect(gallerySemanticReferenceKey({ imageName: 'a.png', kind: 'image' })).not.toBe(+ gallerySemanticReferenceKey({ kind: 'url', url: 'a.png' })+ );+ expect(gallerySemanticReferenceKey({ kind: 'text', query: 'a.png' })).not.toBe(+ gallerySemanticReferenceKey({ imageName: 'a.png', kind: 'image' })+ );+ expect(gallerySemanticReferenceKey({ fileId: 'external-1', kind: 'file', label: 'a' })).toBe(+ gallerySemanticReferenceKey({ fileId: 'external-1', kind: 'file', label: 'b' })+ );+ });++ it('canonicalizes a file reference to its registry id, dropping the display label', () => {+ expect(toGallerySemanticQuery({ fileId: 'external-9', kind: 'file', label: 'cat.png' })).toEqual({+ fileId: 'external-9',+ kind: 'file',+ });+ expect(toGallerySemanticQuery({ imageName: 'a.png', kind: 'image' })).toEqual({+ imageName: 'a.png',+ kind: 'image',+ });+ expect(toGallerySemanticQuery({ kind: 'url', url: 'https://x.test/i.png' })).toEqual({+ kind: 'url',+ url: 'https://x.test/i.png',+ });+ expect(toGallerySemanticQuery({ kind: 'text', query: 'a sunset' })).toEqual({+ kind: 'text',+ query: 'a sunset',+ });+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.tsnew file mode 100644index 0000000000..80dfcad2bd--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts@@ -0,0 +1,168 @@+/**+ * Identity of a semantic gallery search: a text prompt, a gallery image, a+ * web image URL, or a dropped file held in the external-image registry.+ */+export type GallerySemanticQuery =+ | { kind: 'text'; query: string }+ | { kind: 'image'; imageName: string }+ | { kind: 'url'; url: string }+ | { kind: 'file'; fileId: string };++/** A persisted semantic search: a text prompt, a gallery image, a web URL, or a dropped file. */+export type GallerySemanticReference =+ | { kind: 'text'; query: string }+ | { kind: 'image'; imageName: string }+ | { kind: 'url'; url: string }+ | { kind: 'file'; fileId: string; label: string };++/**+ * Stable identity for equality checks and fetch keys. A file reference is+ * identified by its registry key alone — the label is presentation, not+ * identity, so relabeling must not read as a different query.+ */+export const gallerySemanticReferenceKey = (reference: GallerySemanticReference | null): string => {+ if (reference === null) {+ return '';+ }++ switch (reference.kind) {+ case 'text':+ return `text:${reference.query}`;+ case 'image':+ return `image:${reference.imageName}`;+ case 'url':+ return `url:${reference.url}`;+ case 'file':+ return `file:${reference.fileId}`;+ }+};++/** The label-free shape a reference contributes to query cache keys. */+export const toGallerySemanticQuery = (reference: GallerySemanticReference): GallerySemanticQuery => {+ switch (reference.kind) {+ case 'text':+ return { kind: 'text', query: reference.query };+ case 'image':+ return { imageName: reference.imageName, kind: 'image' };+ case 'url':+ return { kind: 'url', url: reference.url };+ case 'file':+ return { fileId: reference.fileId, kind: 'file' };+ }+};++/*+ * In-memory registry for externally dropped reference images (OS file drops).+ * Blobs cannot live in persisted widget values, so the persisted value keeps a+ * registry key; a key that no longer resolves (e.g. after a reload) reads as a+ * cleared search. Only one external query is active at a time, so registering+ * a new file evicts the previous one.+ */++let nextId = 0;++const files = new Map<string, { blob: Blob; label: string }>();++export const registerExternalImageFile = (blob: Blob, label: string): string => {+ nextId += 1;+ // The counter alone is only unique per JS realm, while the id is persisted+ // in widget values; the random token keeps ids from two realms (another+ // tab, a reload) from colliding into the wrong blob.+ const fileId = `external-${String(nextId)}-${Math.random().toString(36).slice(2, 10)}`;++ files.clear();+ files.set(fileId, { blob, label });++ return fileId;+};++export const getExternalImageFile = (fileId: string): { blob: Blob; label: string } | null => files.get(fileId) ?? null;++/**+ * Parses a persisted widget value into a semantic reference. Tolerates the+ * legacy bare-image-name shape, and reads a file key that no longer resolves+ * in the registry as no search at all.+ */+export const parseGallerySemanticReference = (value: unknown): GallerySemanticReference | null => {+ // Legacy shape: a bare image name.+ if (typeof value === 'string' && value) {+ return { imageName: value, kind: 'image' };+ }++ if (value && typeof value === 'object') {+ const record = value as Record<string, unknown>;++ if (record.kind === 'text' && typeof record.query === 'string' && record.query) {+ return { kind: 'text', query: record.query };+ }++ if (record.kind === 'image' && typeof record.imageName === 'string' && record.imageName) {+ return { imageName: record.imageName, kind: 'image' };+ }++ if (record.kind === 'url' && typeof record.url === 'string' && record.url) {+ return { kind: 'url', url: record.url };+ }++ if (record.kind === 'file' && typeof record.fileId === 'string' && record.fileId) {+ // Dropped files live in an in-memory registry; a persisted key that no+ // longer resolves (e.g. after a reload) reads as no search at all.+ if (getExternalImageFile(record.fileId) === null) {+ return null;+ }++ return {+ fileId: record.fileId,+ kind: 'file',+ label: typeof record.label === 'string' && record.label ? record.label : 'dropped image',+ };+ }+ }++ return null;+};++/** Matches this app's own image URLs so in-app drags become by-name queries. */+const APP_IMAGE_PATH = /\/api\/v\d+\/images\/i\/([^/]+)\//;++/**+ * Interpret a native drop for image-similarity search. Files win over URLs;+ * a URL pointing at this app's own image endpoint becomes a by-name query+ * (dragging the preview image in must not round-trip through the server's+ * URL downloader — it would be refused as a private-address fetch); anything+ * else http(s) is searched as a web image. Returns null for unusable drops.+ */+export const semanticReferenceFromDataTransfer = (dataTransfer: {+ files: ArrayLike<File>;+ getData: (format: string) => string;+}): GallerySemanticReference | null => {+ const file = Array.from(dataTransfer.files).find((candidate) => candidate.type.startsWith('image/'));++ if (file) {+ const label = file.name || 'dropped image';++ return { fileId: registerExternalImageFile(file, label), kind: 'file', label };+ }++ const uri = dataTransfer+ .getData('text/uri-list')+ .split('\n')+ .map((line) => line.trim())+ .find((line) => line && !line.startsWith('#'));++ if (!uri || !/^https?:\/\//i.test(uri)) {+ return null;+ }++ const appImageMatch = APP_IMAGE_PATH.exec(uri);++ if (appImageMatch?.[1]) {+ try {+ return { imageName: decodeURIComponent(appImageMatch[1]), kind: 'image' };+ } catch {+ return null;+ }+ }++ return { kind: 'url', url: uri };+};diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.tsindex 5b25426f77..0b023ed2f1 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts@@ -6,6 +6,7 @@ import type {GalleryItemsPage,GalleryVideoItem,} from '@features/gallery/core/items';+import type { GallerySemanticQuery } from '@features/gallery/core/semanticImageQuery';import type {GalleryBoard,GalleryBoardDeletionResult,@@ -18,6 +19,7 @@ import type {GalleryView,} from '@features/gallery/core/types';+import { getExternalImageFile } from '@features/gallery/core/semanticImageQuery';import { isTimestampInRange } from '@platform/search/dateTokens';import {AccountScopeExpiredError,@@ -778,6 +780,90 @@ export const listGalleryItems = async ({};};+/** The backend caps search results; ranked pagination slices this window. */+export const SEMANTIC_SEARCH_MAX_RESULTS = 500;++export interface GallerySemanticResult {+ imageName: string;+ /** Cosine similarity to the query; higher is more similar. */+ score: number;+}++type SemanticSearchBody = { results: { image_name: string; score: number }[] };++const toSemanticResults = (body: SemanticSearchBody): GallerySemanticResult[] =>+ body.results.map((result) => ({ imageName: result.image_name, score: result.score }));++/**+ * Ranks the caller's accessible images by similarity to the query. Text and+ * gallery-image queries hit the GET endpoint; URLs and dropped files POST to+ * the by-image endpoint (the file as multipart from the external-image+ * registry).+ */+export const searchGallerySemantic = async (+ query: GallerySemanticQuery,+ { limit = SEMANTIC_SEARCH_MAX_RESULTS, signal }: { limit?: number; signal?: AbortSignal } = {}+): Promise<GallerySemanticResult[]> => {+ if (query.kind === 'url') {+ const params = toSearchParams({ image_url: query.url, limit });++ return toSemanticResults(+ await apiFetchJson<SemanticSearchBody>(`/api/v1/image_map/search_by_image?${params}`, {+ method: 'POST',+ signal,+ })+ );+ }++ if (query.kind === 'file') {+ const entry = getExternalImageFile(query.fileId);++ if (!entry) {+ throw new Error('The dropped image is no longer available; drop it again to search.');+ }++ const form = new FormData();++ form.append('image', entry.blob, entry.label || 'image');++ return toSemanticResults(+ await apiFetchJson<SemanticSearchBody>(`/api/v1/image_map/search_by_image?${toSearchParams({ limit })}`, {+ body: form,+ method: 'POST',+ signal,+ })+ );+ }++ const params = toSearchParams(+ query.kind === 'text' ? { limit, q: query.query } : { image_name: query.imageName, limit }+ );++ return toSemanticResults(await apiFetchJson<SemanticSearchBody>(`/api/v1/image_map/search?${params}`, { signal }));+};++/**+ * The ranked result set as item refs, in relevance order. Pages hydrate+ * slices of this list (`hydrateGalleryDateBoardItemPage`), and range+ * selection / deletion neighbors read it directly. Semantic results are+ * image-only and carry no starred information.+ */+export const listSemanticGalleryItemNames = async ({+ query,+ signal,+}: {+ query: GallerySemanticQuery;+ signal?: AbortSignal;+}): Promise<GalleryItemNames> => {+ const results = await searchGallerySemantic(query, { signal });++ return {+ items: results.map((result) => ({ kind: 'image', name: result.imageName })),+ starredCount: 0,+ total: results.length,+ };+};+export const listPaletteImages = async ({boardId,createdFrom,diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.tsindex ca99414242..564637e48c 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts@@ -13,6 +13,7 @@ const backend = vi.hoisted(() => ({listGalleryItemNames: vi.fn(),listGalleryItems: vi.fn(),listPaletteImages: vi.fn(),+ listSemanticGalleryItemNames: vi.fn(),}));vi.mock('./backend', () => backend);@@ -22,6 +23,7 @@ import {GALLERY_MAX_ROWS,GALLERY_PAGE_SIZE,galleryBoardsOptions,+ galleryItemNamesOptions,galleryItemsInfiniteOptions,getGalleryItemListQueries,type GalleryItemsFilter,@@ -86,6 +88,7 @@ describe('Gallery item query read model', () => {backend.listGalleryItemNames.mockReset();backend.listGalleryItems.mockReset();backend.listPaletteImages.mockReset();+ backend.listSemanticGalleryItemNames.mockReset();backend.isDateBoardId.mockImplementation((boardId: string) => boardId.startsWith('by_date:'));backend.listGalleryItems.mockResolvedValue({ items: [], total: 0 });@@ -141,6 +144,55 @@ describe('Gallery item query read model', () => {}});+ it('routes a semantic reference through one shared ranked name list and keys it by label-free identity', async () => {+ const queryClient = createQueryClient();+ const semanticFilter: GalleryItemsFilter = {+ ...baseFilter,+ semanticQuery: { fileId: 'external-3', kind: 'file', label: 'cat.png' },+ };+ const rankedNames = {+ items: [{ kind: 'image', name: 'ranked.png' }],+ starredCount: 0,+ total: 1,+ };++ backend.listSemanticGalleryItemNames.mockResolvedValue(rankedNames);+ backend.hydrateGalleryDateBoardItemPage.mockResolvedValue({ items: [], total: 1 });++ const options = galleryItemsInfiniteOptions(semanticFilter);++ await queryClient.fetchInfiniteQuery(options);+ expect(backend.listSemanticGalleryItemNames).toHaveBeenCalledWith(+ expect.objectContaining({ query: { fileId: 'external-3', kind: 'file' } })+ );+ expect(backend.hydrateGalleryDateBoardItemPage).toHaveBeenCalledWith(+ expect.objectContaining({ items: rankedNames.items, limit: GALLERY_PAGE_SIZE, offset: 0, total: 1 })+ );+ expect(backend.listGalleryItems).not.toHaveBeenCalled();++ // Range selection reads the same cached ranked list: a dropped-file+ // reference must not re-upload its blob once per consumer or per page.+ await expect(queryClient.fetchQuery(galleryItemNamesOptions(semanticFilter))).resolves.toEqual(rankedNames);+ expect(backend.listSemanticGalleryItemNames).toHaveBeenCalledOnce();+ expect(backend.listGalleryItemNames).not.toHaveBeenCalled();++ // The label is presentation, not identity: relabels reuse the cache entry+ // while a different registered file (or no reference at all) does not.+ expect(+ galleryItemsInfiniteOptions({+ ...semanticFilter,+ semanticQuery: { fileId: 'external-3', kind: 'file', label: 'renamed.png' },+ }).queryKey+ ).toEqual(options.queryKey);+ expect(+ galleryItemsInfiniteOptions({+ ...semanticFilter,+ semanticQuery: { fileId: 'external-4', kind: 'file', label: 'cat.png' },+ }).queryKey+ ).not.toEqual(options.queryKey);+ expect(galleryItemsInfiniteOptions(baseFilter).queryKey).not.toEqual(options.queryKey);+ });+it('keeps semantic filters in the key while page params stay inside one cache entry', async () => {const baseKey = galleryItemsInfiniteOptions(baseFilter).queryKey;diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.tsindex 46f577b3ce..e7f1816da4 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts@@ -1,8 +1,10 @@import type { GalleryItem, GalleryItemsPage } from '@features/gallery/core/items';+import type { GallerySemanticQuery, GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';import type { GalleryBoardOrderBy, GalleryOrderDir, GalleryView } from '@features/gallery/core/types';import type { AccountScope } from '@platform/state/accountLifecycle';import { toGalleryItemKey } from '@features/gallery/core/items';+import { toGallerySemanticQuery } from '@features/gallery/core/semanticImageQuery';import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';import {hashKey,@@ -22,6 +24,7 @@ import {listGalleryDateBoards,listGalleryItemNames,listGalleryItems,+ listSemanticGalleryItemNames,} from './backend';export const GALLERY_PAGE_SIZE = 60;@@ -51,6 +54,12 @@ export interface GalleryItemsFilter {galleryView: GalleryView;orderDir?: GalleryOrderDir;searchTerm: string;+ /**+ * When set, items come from semantic image-similarity search (relevance+ * order) instead of the board listing; board/order/starred controls do not+ * apply to a ranked result set.+ */+ semanticQuery?: GallerySemanticReference | null;starredFirst?: boolean;}@@ -61,6 +70,8 @@ export interface CanonicalGalleryItemsFilter {galleryView: GalleryView;orderDir: GalleryOrderDir;searchTerm: string;+ /** Label-free semantic reference: a file query is keyed by its registry id. */+ semantic?: GallerySemanticQuery;starredFirst: boolean;}@@ -97,6 +108,7 @@ export const canonicalizeGalleryItemsFilter = (filter: GalleryItemsFilter): CanogalleryView: filter.galleryView,orderDir: filter.orderDir ?? 'DESC',searchTerm: filter.searchTerm.trim(),+ ...(filter.semanticQuery ? { semantic: toGallerySemanticQuery(filter.semanticQuery) } : {}),starredFirst: filter.starredFirst ?? false,});@@ -136,9 +148,11 @@ const galleryItemNamesOptionsForOwner = (owner: AccountScope, filter: CanonicalGqueryOptions({queryFn: async ({ signal }) => {const requestSignal = AbortSignal.any([signal, owner.signal]);- const result = await (isDateBoardId(filter.boardId)- ? listGalleryDateBoardItemNames({ ...filter, signal: requestSignal })- : listGalleryItemNames({ ...filter, signal: requestSignal }));+ const result = await (filter.semantic+ ? listSemanticGalleryItemNames({ query: filter.semantic, signal: requestSignal })+ : isDateBoardId(filter.boardId)+ ? listGalleryDateBoardItemNames({ ...filter, signal: requestSignal })+ : listGalleryItemNames({ ...filter, signal: requestSignal }));assertAccountScopeCurrent(owner);requestSignal.throwIfAborted();@@ -162,9 +176,10 @@ export const galleryItemNamesOptions = (inputFilter: GalleryItemsFilter) => {const dateBoardNamesConsumers = new WeakMap<QueryClient, Map<string, number>>();/**- * A date-name request is shared by infinite and paginated consumers. One- * consumer may stop waiting immediately without cancelling work still needed- * by another; the final departing consumer owns cancellation.+ * A name-list request (date boards and semantic searches) is shared by+ * infinite and paginated consumers. One consumer may stop waiting immediately+ * without cancelling work still needed by another; the final departing+ * consumer owns cancellation.*/const fetchSharedDateBoardNames = (client: QueryClient,@@ -300,7 +315,13 @@ export const galleryItemsInfiniteOptions = (const requestSignal = AbortSignal.any([signal, owner.signal]);let result: GalleryItemsPage;- if (isDateBoardId(filter.boardId)) {+ // Semantic and date-board queries share one mechanism: the ordered name+ // list is fetched once (shared across pages, both consumers, and the+ // 60s stale window) and every page hydrates a slice of it. For semantic+ // queries this is also what keeps ranks consistent across pages — and+ // what keeps a dropped-file reference from re-uploading its blob on+ // every page fetch.+ if (filter.semantic || isDateBoardId(filter.boardId)) {const namesOptions = galleryItemNamesOptionsForOwner(owner, filter);const names = await fetchSharedDateBoardNames(client, namesOptions.queryKey, requestSignal, () =>client.fetchQuery(namesOptions)diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.tsindex 1a88ff1861..00d6d00128 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts@@ -213,6 +213,37 @@ describe('Gallery item cache patches', () => {}});+ it('keeps moved items in ranked similarity windows regardless of the selected board', () => {+ // A semantic window inherits whatever board happens to be selected, but+ // its membership is similarity, not board: moving an image must update+ // its board in place, never evict it from the ranked list.+ const client = createClient();+ const target = createItem('ranked.png', 'board-1');+ const untouched = createItem('also-ranked.png', 'board-1');+ const semanticKey = galleryKeys.items(+ captureAccountScope(),+ canonicalizeGalleryItemsFilter({+ boardId: 'board-1',+ galleryView: 'images',+ searchTerm: '',+ semanticQuery: { imageName: 'ref.png', kind: 'image' },+ })+ );++ client.setQueryData(semanticKey, createData([[target, untouched]]));++ patchGalleryItemCaches(client, {+ boardId: 'board-2',+ kind: 'move',+ result: getResult([{ kind: 'image', name: target.name }]),+ });++ const after = getData(client, semanticKey);++ expect(after.pages.flatMap((page) => page.items)).toEqual([{ ...target, boardId: 'board-2' }, untouched]);+ expect(after.pages.map((page) => page.total)).toEqual([2]);+ });+it('does not let rollback clobber a later concurrent cache update', () => {const client = createClient();const target = createItem('target.png');diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.tsindex 1603b9b3cb..6b7f2809f0 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts@@ -94,8 +94,13 @@ const patchItemPage = (return mapPageItems(page, (item) => (itemKeys.has(toGalleryItemKey(item)) ? null : item), removedItemCount);}+ // Ranked similarity windows are board-agnostic: moving an image to another+ // board never changes its membership in the result set.const keepsMovedItems =- filter.boardId === ALL_READABLE_BOARDS_ID || filter.boardId === patch.boardId || isDateBoardId(filter.boardId);+ filter.semantic !== undefined ||+ filter.boardId === ALL_READABLE_BOARDS_ID ||+ filter.boardId === patch.boardId ||+ isDateBoardId(filter.boardId);return mapPageItems(page,@@ -123,6 +128,7 @@ const patchItemsInfiniteData = (const removesItems =patch.kind === 'delete' ||(patch.kind === 'move' &&+ filter.semantic === undefined &&filter.boardId !== ALL_READABLE_BOARDS_ID &&filter.boardId !== patch.boardId &&!isDateBoardId(filter.boardId));diff --git a/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.tsnew file mode 100644index 0000000000..f8eb382777--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts@@ -0,0 +1,173 @@+import { registerExternalImageFile } from '@features/gallery/core/semanticImageQuery';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ apiFetchJson: vi.fn(),+}));++vi.mock('@platform/transport/http', () => ({+ absolutizeApiUrl: (url: string) => url,+ ApiError: class ApiError extends Error {},+ apiFetch: vi.fn(),+ apiFetchJson: mocks.apiFetchJson,+ apiFetchRaw: vi.fn(),+ HttpRequestIdentityExpiredError: class HttpRequestIdentityExpiredError extends Error {},+ sleep: vi.fn(),+}));++import { hydrateGalleryDateBoardItemPage, listSemanticGalleryItemNames, searchGallerySemantic } from './backend';+import { canonicalizeGalleryItemsFilter, type GalleryItemsFilter } from './queries';++const backendImage = (name: string) => ({+ created_at: '2026-08-02',+ height: 64,+ image_category: 'general',+ image_name: name,+ image_url: `/img/${name}`,+ is_intermediate: false,+ thumbnail_url: `/thumb/${name}`,+ width: 64,+});++describe('searchGallerySemantic', () => {+ beforeEach(() => {+ mocks.apiFetchJson.mockReset();+ });++ it('builds text queries and maps results', async () => {+ mocks.apiFetchJson.mockResolvedValue({ results: [{ image_name: 'a.png', score: 0.9 }] });++ const results = await searchGallerySemantic({ kind: 'text', query: 'red barn' }, { limit: 50 });++ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/search?limit=50&q=red+barn', {+ signal: undefined,+ });+ expect(results).toEqual([{ imageName: 'a.png', score: 0.9 }]);+ });++ it('builds image-similarity queries with the default result cap', async () => {+ mocks.apiFetchJson.mockResolvedValue({ results: [] });++ await searchGallerySemantic({ imageName: 'ref.png', kind: 'image' });++ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/search?image_name=ref.png&limit=500', {+ signal: undefined,+ });+ });++ it('POSTs url queries to the by-image endpoint', async () => {+ mocks.apiFetchJson.mockResolvedValue({ results: [{ image_name: 'a.png', score: 0.8 }] });++ const results = await searchGallerySemantic({ kind: 'url', url: 'https://example.com/cat.jpg' }, { limit: 25 });++ expect(mocks.apiFetchJson).toHaveBeenCalledWith(+ '/api/v1/image_map/search_by_image?image_url=https%3A%2F%2Fexample.com%2Fcat.jpg&limit=25',+ { method: 'POST', signal: undefined }+ );+ expect(results).toEqual([{ imageName: 'a.png', score: 0.8 }]);+ });++ it('POSTs registered dropped files as multipart and fails clearly when the blob is gone', async () => {+ mocks.apiFetchJson.mockResolvedValue({ results: [] });+ const fileId = registerExternalImageFile(new Blob(['not-really-a-png']), 'cat.png');++ await searchGallerySemantic({ fileId, kind: 'file' }, { limit: 10 });++ const [path, init] = mocks.apiFetchJson.mock.calls[0] as [string, RequestInit];++ expect(path).toBe('/api/v1/image_map/search_by_image?limit=10');+ expect(init.method).toBe('POST');+ expect(init.body).toBeInstanceOf(FormData);+ expect((init.body as FormData).get('image')).toBeInstanceOf(Blob);++ await expect(searchGallerySemantic({ fileId: 'external-unknown', kind: 'file' })).rejects.toThrow(+ /no longer available/+ );+ });+});++describe('semantic page hydration', () => {+ beforeEach(() => {+ mocks.apiFetchJson.mockReset();+ });++ it('slices the ranked name list and hydrates DTOs in rank order, dropping unknown names', async () => {+ mocks.apiFetchJson+ .mockResolvedValueOnce({+ results: [+ { image_name: 'first.png', score: 0.9 },+ { image_name: 'second.png', score: 0.8 },+ { image_name: 'deleted.png', score: 0.7 },+ ],+ })+ // by-names returns DTOs in arbitrary order; rank order must win, and a+ // name the hydration endpoint no longer knows is skipped.+ .mockResolvedValueOnce([backendImage('second.png'), backendImage('first.png')]);++ const names = await listSemanticGalleryItemNames({ query: { kind: 'text', query: 'boats' } });+ const page = await hydrateGalleryDateBoardItemPage({ ...names, limit: 3, offset: 0 });++ expect(page.total).toBe(3);+ expect(page.items.map((item) => item.name)).toEqual(['first.png', 'second.png']);+ expect(page.items.every((item) => item.kind === 'image')).toBe(true);+ });+});++describe('listSemanticGalleryItemNames', () => {+ it('maps the ranked results to image refs in rank order', async () => {+ mocks.apiFetchJson.mockReset();+ mocks.apiFetchJson.mockResolvedValue({+ results: [+ { image_name: 'first.png', score: 0.9 },+ { image_name: 'second.png', score: 0.8 },+ ],+ });++ await expect(listSemanticGalleryItemNames({ query: { imageName: 'x.png', kind: 'image' } })).resolves.toEqual({+ items: [+ { kind: 'image', name: 'first.png' },+ { kind: 'image', name: 'second.png' },+ ],+ starredCount: 0,+ total: 2,+ });+ });+});++describe('semantic filter canonicalization', () => {+ const baseFilter: GalleryItemsFilter = {+ boardId: 'none',+ galleryView: 'images',+ searchTerm: '',+ };++ it('omits the semantic field entirely when no reference is set', () => {+ expect(canonicalizeGalleryItemsFilter(baseFilter)).not.toHaveProperty('semantic');+ expect(canonicalizeGalleryItemsFilter({ ...baseFilter, semanticQuery: null })).not.toHaveProperty('semantic');+ });++ it('discriminates cache identity by kind and keys file references by registry id', () => {+ expect(+ canonicalizeGalleryItemsFilter({ ...baseFilter, semanticQuery: { imageName: 'a.png', kind: 'image' } }).semantic+ ).toEqual({ imageName: 'a.png', kind: 'image' });++ // Same value, different kind: must not collide in the cache.+ expect(+ canonicalizeGalleryItemsFilter({ ...baseFilter, semanticQuery: { kind: 'url', url: 'a.png' } }).semantic+ ).toEqual({ kind: 'url', url: 'a.png' });++ // The label is presentation, not identity: relabeled drops of the same+ // registered file canonicalize identically.+ const withLabelA = canonicalizeGalleryItemsFilter({+ ...baseFilter,+ semanticQuery: { fileId: 'external-7', kind: 'file', label: 'a.png' },+ });+ const withLabelB = canonicalizeGalleryItemsFilter({+ ...baseFilter,+ semanticQuery: { fileId: 'external-7', kind: 'file', label: 'b.png' },+ });++ expect(withLabelA.semantic).toEqual({ fileId: 'external-7', kind: 'file' });+ expect(withLabelA).toEqual(withLabelB);+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.tsxindex 655b7a0c22..e2541cd5be 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardDragMonitor.tsx@@ -1,7 +1,7 @@import { useDndMonitor, type DragEndEvent, type DragStartEvent } from '@dnd-kit/core';import { useCallback, useRef } from 'react';-import { forwardGalleryBoardDrop, isGalleryItemDragData } from './galleryDnd';+import { forwardGalleryBoardDrop, isGalleryItemDragData, resolveGallerySemanticSearchDrop } from './galleryDnd';import { useGalleryWidget } from './GalleryWidgetContext';/**@@ -35,6 +35,16 @@ export const GalleryBoardDragMonitor = () => {const handleDragEnd = useCallback((event: DragEndEvent) => {+ const semanticDrop = resolveGallerySemanticSearchDrop(event.active.data.current, event.over?.id);++ if (semanticDrop) {+ // Dropping a gallery image on the search field ranks the gallery by+ // visual similarity to it.+ actions.setSemanticImageQuery({ imageName: semanticDrop.imageName, kind: 'image' });+ restoreDisclosure();+ return;+ }+forwardGalleryBoardDrop({activeData: event.active.data.current,loadedItems: gallery.items,@@ -43,7 +53,7 @@ export const GalleryBoardDragMonitor = () => {});restoreDisclosure();},- [gallery.items, itemActions, restoreDisclosure]+ [actions, gallery.items, itemActions, restoreDisclosure]);useDndMonitor({diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsxindex 916cadd787..a55a35a7a3 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.browser.test.tsx@@ -79,6 +79,7 @@ const createGallery = (settings: Partial<GallerySettings> = {}): GalleryStateVieprojectBoardId: null,searchTerm: '',selectedBoardId: 'dogs',+ semanticImageQuery: null,selectedItemKey: null,selectedItemKeys: [],settings: { ...DEFAULT_GALLERY_SETTINGS, showArchivedBoards: true, showDateBoards: true, ...settings },diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsxindex 832b42997f..2c1bcab15d 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx@@ -218,6 +218,7 @@ const createGallery = (overrides: Partial<GalleryStateView> = {}): GalleryStateVselectedBoardId: board.id,selectedItemKey: 'image:first.png',selectedItemKeys: ['image:first.png'],+ semanticImageQuery: null,settings: { ...DEFAULT_GALLERY_SETTINGS, imageDensityPercent: 0, paginationMode: 'paginated' },...overrides,};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsxindex e80d1283a1..d961f6c019 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx@@ -1,10 +1,14 @@+import type { GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';+import { Box, Code, HStack, Icon, Popover, Portal, Stack, Text } from '@chakra-ui/react';+import { semanticReferenceFromDataTransfer } from '@features/gallery/core/semanticImageQuery';import { describeDateRange, findInvalidDateToken, formatIsoDate, parseDateTokens } from '@platform/search/dateTokens';import { CloseButton, IconButton } from '@platform/ui/Button';-import { CircleHelpIcon } from 'lucide-react';-import { useCallback, useMemo } from 'react';+import { CircleHelpIcon, ImageIcon, SparklesIcon } from 'lucide-react';+import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';+import { GALLERY_SEMANTIC_SEARCH_DROP_ID, useGalleryImageDroppable } from './galleryDnd';import { GallerySearchField } from './GallerySearchField';import { useGalleryWidget } from './GalleryWidgetContext';@@ -19,11 +23,108 @@ const DATE_TOKEN_EXAMPLES = [{ descriptionKey: 'widgets.gallery.searchHelpRelative', key: 'from:7d' },] as const;+/** The full identity of the reference, surfaced as the chip's hover title. */+const getSemanticReferenceTitle = (reference: GallerySemanticReference): string => {+ switch (reference.kind) {+ case 'text':+ return reference.query;+ case 'image':+ return reference.imageName;+ case 'url':+ return reference.url;+ case 'file':+ return reference.label;+ }+};++/** A short human-readable name for the chip; empty when nothing legible exists. */+const getSemanticReferenceName = (reference: GallerySemanticReference): string => {+ switch (reference.kind) {+ case 'text':+ return reference.query;+ case 'image':+ return reference.imageName;+ case 'file':+ return reference.label;+ case 'url': {+ try {+ const parsed = new URL(reference.url);++ return decodeURIComponent(parsed.pathname.split('/').pop() || parsed.hostname);+ } catch {+ return '';+ }+ }+ }+};+export const GalleryItemSearch = () => {const { i18n, t } = useTranslation();const { actions, gallery } = useGalleryWidget();const handleClearSearch = useCallback(() => actions.setSearchTerm(''), [actions]);+ const handleClearSemantic = useCallback(() => actions.setSemanticImageQuery(null), [actions]);++ // Date tokens are metadata-search grammar; a semantic query is free text,+ // so the whole field content is taken verbatim.+ const semanticQueryText = gallery.searchTerm.trim();+ const handleSemanticSearch = useCallback(() => {+ const query = semanticQueryText;++ if (query) {+ actions.setSemanticImageQuery({ kind: 'text', query });+ }+ }, [actions, semanticQueryText]);++ // In-app drags (dnd-kit) resolve through GalleryBoardDragMonitor; this hook+ // only registers the drop target and reports hover for the highlight.+ const { isOver: isItemDragOver, setNodeRef: setSemanticDropRef } = useGalleryImageDroppable({+ id: GALLERY_SEMANTIC_SEARCH_DROP_ID,+ });++ // Native HTML5 drops reach here for anything dnd-kit does not manage: files+ // from the OS and images dragged in from other pages (URL drags).+ const [isNativeDropOver, setIsNativeDropOver] = useState(false);++ const handleNativeDragOver = useCallback((event: React.DragEvent<HTMLDivElement>) => {+ const types = event.dataTransfer.types;++ if (types.includes('Files') || types.includes('text/uri-list')) {+ event.preventDefault();+ setIsNativeDropOver(true);+ }+ }, []);++ const handleNativeDragLeave = useCallback((event: React.DragEvent<HTMLDivElement>) => {+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {+ setIsNativeDropOver(false);+ }+ }, []);++ const handleNativeDrop = useCallback(+ (event: React.DragEvent<HTMLDivElement>) => {+ const types = event.dataTransfer.types;++ // Only claim drops this feature understands; a plain-text drop must+ // fall through to the browser's default insertion into the input.+ if (!types.includes('Files') && !types.includes('text/uri-list')) {+ setIsNativeDropOver(false);+ return;+ }++ event.preventDefault();+ setIsNativeDropOver(false);++ const reference = semanticReferenceFromDataTransfer(event.dataTransfer);++ if (reference) {+ actions.setSemanticImageQuery(reference);+ }+ },+ [actions]+ );++ const isDropTargetActive = isItemDragOver || isNativeDropOver;// Valid tokens are legible as chips in the field itself, so only the failure// case still needs words — and it is positioned out of flow. As a sibling it@@ -65,26 +166,53 @@ export const GalleryItemSearch = () => {const endElement = useMemo(() => (<HStack flexShrink={0} gap="0">+ {semanticQueryText ? (+ <IconButton+ aria-label={t('widgets.gallery.searchSemantically')}+ color="fg.muted"+ size="2xs"+ title={t('widgets.gallery.searchSemantically')}+ variant="ghost"+ onClick={handleSemanticSearch}+ >+ <Icon as={SparklesIcon} boxSize="3.5" />+ </IconButton>+ ) : null}{gallery.searchTerm ? (<CloseButton aria-label={t('common.clearSearch')} size="2xs" onClick={handleClearSearch} />) : null}<GallerySearchHelp /></HStack>),- [gallery.searchTerm, handleClearSearch, t]+ [gallery.searchTerm, handleClearSearch, handleSemanticSearch, semanticQueryText, t]);return (- <Box minW="0" position="relative" w="full">- <GallerySearchField- ariaLabel={t('widgets.gallery.searchImagesAriaLabel')}- describedById={invalidHint ? SEARCH_DATE_HINT_ID : undefined}- endElement={endElement}- isInvalid={invalidHint !== null}- placeholder={t('widgets.gallery.searchImagesPlaceholder')}- value={gallery.searchTerm}- onChange={actions.setSearchTerm}- />+ <Box+ ref={setSemanticDropRef}+ minW="0"+ outline={isDropTargetActive ? '2px solid' : undefined}+ outlineColor={isDropTargetActive ? 'accent.solid' : undefined}+ position="relative"+ rounded="md"+ w="full"+ onDragLeave={handleNativeDragLeave}+ onDragOver={handleNativeDragOver}+ onDrop={handleNativeDrop}+ >+ {gallery.semanticImageQuery ? (+ <GallerySemanticChip reference={gallery.semanticImageQuery} onClear={handleClearSemantic} />+ ) : (+ <GallerySearchField+ ariaLabel={t('widgets.gallery.searchImagesAriaLabel')}+ describedById={invalidHint ? SEARCH_DATE_HINT_ID : undefined}+ endElement={endElement}+ isInvalid={invalidHint !== null}+ placeholder={t('widgets.gallery.searchImagesPlaceholder')}+ value={gallery.searchTerm}+ onChange={actions.setSearchTerm}+ />+ )}{invalidHint ? (<Textcolor="fg.error"@@ -110,6 +238,42 @@ export const GalleryItemSearch = () => {);};+/**+ * The active semantic query — a text prompt or an image-similarity+ * reference — rendered in place of the search input. Clearing it restores+ * metadata search.+ */+const GallerySemanticChip = ({ onClear, reference }: { onClear: () => void; reference: GallerySemanticReference }) => {+ const { t } = useTranslation();+ const isText = reference.kind === 'text';+ const name = getSemanticReferenceName(reference) || t('widgets.gallery.semanticWebImage');++ return (+ <HStack+ bg="bg"+ borderColor="border.emphasized"+ borderWidth="1px"+ gap="1.5"+ h="8"+ minW="0"+ px="2"+ rounded="md"+ title={getSemanticReferenceTitle(reference)}+ w="full"+ >+ <Icon as={isText ? SparklesIcon : ImageIcon} boxSize="3.5" color="fg.subtle" flexShrink={0} />+ <Text color="fg.muted" flex="1" fontSize="xs" minW="0" truncate>+ {isText ? t('widgets.gallery.semanticTextSearch', { name }) : t('widgets.gallery.semanticSimilarTo', { name })}+ </Text>+ <CloseButton+ aria-label={isText ? t('widgets.gallery.clearSemanticSearch') : t('widgets.gallery.clearImageSearch')}+ size="2xs"+ onClick={onClear}+ />+ </HStack>+ );+};+/** Documents the closed date-token grammar the search box accepts. */const GallerySearchHelp = () => {const { t } = useTranslation();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsxindex 64b9513e4a..a4ee2660f9 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx@@ -1,4 +1,5 @@import type { GalleryImageItem, GalleryItem, GalleryItemRef } from '@features/gallery/contracts';+import type { GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';import type { GallerySettings } from '@features/gallery/core/settings';import type { GalleryView } from '@features/gallery/core/types';import type { GalleryItemsFilter } from '@features/gallery/data/queries';@@ -29,6 +30,8 @@ export interface GalleryActions {selectItemRange: (items: GalleryItemRef[], primaryItem: GalleryItem) => void;setCompareItem: (image: GalleryImageItem | null) => void;setSearchTerm: (searchTerm: string) => void;+ /** Sets (or clears) the image-similarity query shown as a chip in the search field. */+ setSemanticImageQuery: (reference: GallerySemanticReference | null) => void;setView: (galleryView: GalleryView) => void;toggleItemInSelection: (item: GalleryItem, nextPrimaryItem: GalleryItem | null) => void;updateSettings: (settings: Partial<GallerySettings>) => void;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsxindex 33f065f6fc..063c776a2b 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx@@ -17,6 +17,7 @@ import {getGalleryPage,getGallerySearchTerm,getGallerySelectedBoardId,+ getGallerySemanticImageQuery,getGalleryStateView,getGalleryTotalImages,getGalleryView,@@ -62,6 +63,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidggenerateValues,liveFollowEnabled,liveProgressTarget,+ notifications,projectId,projectName,queueItems,@@ -74,15 +76,34 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgconst knownTotalImages = getGalleryTotalImages(galleryValues);const settings = getGallerySettings(galleryValues);const queryClient = useQueryClient();+ const semanticQuery = getGallerySemanticImageQuery(galleryValues);const data = useGalleryData({galleryView,page,recentImages,searchTerm,selectedBoardId: getGallerySelectedBoardId(galleryValues, []),+ semanticQuery,settings,});+ // A failed similarity search renders exactly like an empty one ("no images+ // match"), so the failure must reach the user some other way. Scoped to+ // semantic mode: the board listing kept its pre-existing quiet behavior.+ const semanticError = semanticQuery ? data.queryError : null;++ useEffect(() => {+ if (!semanticError) {+ return;+ }++ notifications.reportError({+ area: 'gallery-semantic-search',+ message: semanticError.message,+ namespace: 'gallery',+ });+ }, [notifications, semanticError]);+const { loadMore, total } = data;const selectedBoardId = getGallerySelectedBoardId(galleryValues, data.boards);const gallery = getGalleryStateView(diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.tsindex d21c06b8c7..2c3cbc2d78 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.test.ts@@ -4,6 +4,7 @@ import { describe, expect, it, vi } from 'vitest';import {forwardGalleryBoardDrop,+ GALLERY_SEMANTIC_SEARCH_DROP_ID,getGalleryBoardDropData,getGalleryItemDragData,getGalleryItemDragId,@@ -11,6 +12,7 @@ import {isGalleryImageDragData,isGalleryItemDragData,resolveGalleryBoardDrop,+ resolveGallerySemanticSearchDrop,} from './galleryDnd';const createItem = (kind: GalleryItem['kind'], name: string, boardId: string): GalleryItem => {@@ -194,3 +196,31 @@ describe('forwardGalleryBoardDrop', () => {expect(moveItemsToBoard).not.toHaveBeenCalled();});});++describe('resolveGallerySemanticSearchDrop', () => {+ it('resolves the first image in a drag released over the search field', () => {+ expect(+ resolveGallerySemanticSearchDrop(+ getGalleryItemDragData([+ { kind: 'video', name: 'clip' },+ { kind: 'image', name: 'ref.png' },+ ]),+ GALLERY_SEMANTIC_SEARCH_DROP_ID+ )+ ).toEqual({ imageName: 'ref.png' });+ });++ it('resolves nothing for video-only drags, other drop targets, or foreign drag data', () => {+ const imageDrag = getGalleryItemDragData([{ kind: 'image', name: 'ref.png' }]);++ expect(+ resolveGallerySemanticSearchDrop(+ getGalleryItemDragData([{ kind: 'video', name: 'clip' }]),+ GALLERY_SEMANTIC_SEARCH_DROP_ID+ )+ ).toBe(null);+ expect(resolveGallerySemanticSearchDrop(imageDrag, 'gallery-board:board-a')).toBe(null);+ expect(resolveGallerySemanticSearchDrop(imageDrag, undefined)).toBe(null);+ expect(resolveGallerySemanticSearchDrop({ kind: 'other' }, GALLERY_SEMANTIC_SEARCH_DROP_ID)).toBe(null);+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.tsindex f2167ee8a2..de131ab965 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts@@ -43,6 +43,27 @@ export const getGalleryItemDragId = (export const getGalleryBoardDropId = (boardId: string): string => `gallery-board:${boardId}`;+/** Droppable id for the search field: dropping a gallery image there searches by similarity. */+export const GALLERY_SEMANTIC_SEARCH_DROP_ID = 'gallery-semantic-search-drop';++/**+ * Resolves an item drag released over the search field to an image-similarity+ * reference. Semantic search is image-only, so a video-only drag resolves to+ * nothing rather than to a broken query.+ */+export const resolveGallerySemanticSearchDrop = (+ activeData: unknown,+ overId: unknown+): { imageName: string } | null => {+ if (overId !== GALLERY_SEMANTIC_SEARCH_DROP_ID || !isGalleryItemDragData(activeData)) {+ return null;+ }++ const image = activeData.items.find((item) => item.kind === 'image');++ return image ? { imageName: image.name } : null;+};+export const getGalleryItemDragData = (items: readonly GalleryItemRef[]): GalleryItemDragData => ({items: [...items],kind: 'gallery-item',diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.tsindex b418d3d906..6352b09bd8 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts@@ -11,6 +11,7 @@ import {getGalleryLiveSlots,getGalleryQueuePlaceholders,getGallerySelectedBoardId,+ getGallerySemanticImageQuery,getGalleryStateView,} from './galleryStateView';@@ -261,6 +262,39 @@ describe('gallery state view', () => {expect(gallery.compareImageKey).toBe('image:shared');});+ it('returns an identity-stable semantic reference while the underlying value is unchanged', () => {+ // An unstable identity here restarts in-flight searches on every+ // unrelated gallery interaction (it feeds memo/effect dependencies).+ const values = { semanticImageQuery: { kind: 'url', url: 'https://x.test/i.png' } };+ const first = getGallerySemanticImageQuery(values);+ const second = getGallerySemanticImageQuery({ ...values });++ expect(first).toEqual({ kind: 'url', url: 'https://x.test/i.png' });+ expect(second).toBe(first);+ expect(getGallerySemanticImageQuery({ semanticImageQuery: 'other.png' })).not.toBe(first);+ });++ it('threads the parsed semantic reference into the view and hides pending placeholders while ranked', () => {+ const queueItems = [createQueueItem({ batchCount: 2, boardId: 'board-1', status: 'pending' })];+ const withSemantic = getGalleryStateView(+ { selectedBoardId: 'board-1', semanticImageQuery: 'ref.png' },+ boards,+ [],+ false,+ queueItems+ );++ // Legacy persisted shape: a bare image name.+ expect(withSemantic.semanticImageQuery).toEqual({ imageName: 'ref.png', kind: 'image' });+ // A ranked result has no chronological insertion point for images-to-come.+ expect(withSemantic.pendingPlaceholders).toEqual([]);++ const withoutSemantic = getGalleryStateView({ selectedBoardId: 'board-1' }, boards, [], false, queueItems);++ expect(withoutSemantic.semanticImageQuery).toBe(null);+ expect(withoutSemantic.pendingPlaceholders.length).toBeGreaterThan(0);+ });+it('creates placeholders for in-flight gallery queue items on the viewed board', () => {const queueItems = [createQueueItem({ batchCount: 2, boardId: 'board-1', status: 'pending' }),diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex f2697eb360..67fc71e382 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -13,6 +13,11 @@ import {getSelectedGalleryImageFromValues,getSelectedGalleryItemFromValues,} from '@features/gallery/core/selection';+import {+ gallerySemanticReferenceKey,+ parseGallerySemanticReference,+ type GallerySemanticReference,+} from '@features/gallery/core/semanticImageQuery';import { getGallerySettings, type GallerySettings } from '@features/gallery/core/settings';import { getQueueItemSnapshotBatchCount, getQueueItemSnapshotDimensions } from '@features/queue/contracts';@@ -80,6 +85,8 @@ export interface GalleryStateView {selectedBoardId: string;selectedItemKey: GalleryItemKey | null;selectedItemKeys: GalleryItemKey[];+ /** Active image-similarity query, rendered as a chip in place of the search text. */+ semanticImageQuery: GallerySemanticReference | null;settings: GallerySettings;}@@ -224,6 +231,23 @@ export const getGalleryView = (values: Record<string, unknown>): GalleryView =>export const getGallerySearchTerm = (values: Record<string, unknown>): string =>typeof values.searchTerm === 'string' ? values.searchTerm : '';+// The parser builds a fresh object per call, but selectors and memo+// dependencies need identity stability: reuse the previous object while its+// key is unchanged. (The gallery widget is single-instance, so one slot is+// enough; a second consumer with a different value would still be correct,+// merely unmemoized.)+let lastSemanticReference: GallerySemanticReference | null = null;++export const getGallerySemanticImageQuery = (values: Record<string, unknown>): GallerySemanticReference | null => {+ const parsed = parseGallerySemanticReference(values.semanticImageQuery);++ if (gallerySemanticReferenceKey(parsed) !== gallerySemanticReferenceKey(lastSemanticReference)) {+ lastSemanticReference = parsed;+ }++ return lastSemanticReference;+};+/*** Where new results land, resolved against the boards this install actually has.*@@ -401,8 +425,12 @@ export const getGalleryStateView = (compareImageKey !== null &&compareImageKey !== visibleSelectedItemKey;const generationSequence = getGalleryGenerationSequence(queueItems, liveTarget);+ // A ranked similarity result has no chronological insertion point, so+ // pending placeholders (which stand in for images-to-come) are hidden while+ // a semantic query is active — exactly as they are for a text search.+ const semanticImageQuery = getGallerySemanticImageQuery(values);const visibleActivePlaceholder =- settings.showPendingItems && galleryView === 'images' && searchTerm.trim() === ''+ settings.showPendingItems && galleryView === 'images' && searchTerm.trim() === '' && semanticImageQuery === null? generationSequence.liveSlot?.boardId === selectedBoardId? generationSequence.liveSlot: null@@ -421,14 +449,15 @@ export const getGalleryStateView = (galleryView,items,isLoading,- pendingPlaceholders: settings.showPendingItems- ? getVisibleGalleryQueuePlaceholders(generationSequence.chronologicalSlots, {- galleryView,- imageOrderDir: settings.imageOrderDir,- searchTerm,- selectedBoardId,- })- : [],+ pendingPlaceholders:+ settings.showPendingItems && semanticImageQuery === null+ ? getVisibleGalleryQueuePlaceholders(generationSequence.chronologicalSlots, {+ galleryView,+ imageOrderDir: settings.imageOrderDir,+ searchTerm,+ selectedBoardId,+ })+ : [],projectBoardId: getGalleryProjectBoardId(values),searchTerm,selectedBoardId,@@ -437,6 +466,7 @@ export const getGalleryStateView = (visibleSelectedItemKey && !selectedItemKeys.includes(visibleSelectedItemKey)? [visibleSelectedItemKey, ...selectedItemKeys]: selectedItemKeys,+ semanticImageQuery,settings,};};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsxindex 90d350f354..fd3bee132f 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.browser.test.tsx@@ -98,6 +98,7 @@ const reconcileDeletedBoardOutcome = vi.fn();const selectBoard = vi.fn();const selectItem = vi.fn();const setItemMultiSelection = vi.fn();+const patchGalleryValues = vi.fn();(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const Probe = ({@@ -183,7 +184,7 @@ const adapter: GalleryUiAdapter = {projectId: 'project-1',projectName: 'Project',queueItems: [],- widgets: { patchGalleryValues: noop },+ widgets: { patchGalleryValues },};let selectedBoardId = 'board-1';@@ -669,3 +670,27 @@ describe('mixed gallery upload', () => {expect(mocks.notificationsReportError).not.toHaveBeenCalled();});});++describe('setSemanticImageQuery', () => {+ it('applies the reference while resetting pagination and clearing the text term', () => {+ // Paginated mode with the user on a later page: applying a semantic query+ // replaces the result set, so the page must snap back to the first one+ // (mirroring setGallerySearchTerm) and the term the chip replaces must not+ // keep filtering invisibly.+ actionsRef.current?.setSemanticImageQuery({ imageName: 'ref.png', kind: 'image' });++ expect(patchGalleryValues).toHaveBeenCalledOnce();+ expect(patchGalleryValues).toHaveBeenCalledWith({+ galleryPage: 0,+ searchTerm: '',+ semanticImageQuery: { imageName: 'ref.png', kind: 'image' },+ });+ });++ it('resets pagination when the semantic query is cleared', () => {+ actionsRef.current?.setSemanticImageQuery(null);++ expect(patchGalleryValues).toHaveBeenCalledOnce();+ expect(patchGalleryValues).toHaveBeenCalledWith({ galleryPage: 0, searchTerm: '', semanticImageQuery: null });+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.tsindex e39fd1f4e1..f98527bc4a 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts@@ -37,7 +37,7 @@ export const useGalleryActions = ({loadMore: () => void;selectedBoardId: string;}): GalleryActions => {- const { exportProject, gallery, notifications } = useGalleryUi();+ const { exportProject, gallery, notifications, widgets } = useGalleryUi();const queryClient = useQueryClient();const { t } = useTranslation();const uploadFiles = useGalleryUploadAction({ boards, getCurrentGalleryLocation, selectedBoardId });@@ -205,6 +205,16 @@ export const useGalleryActions = ({selectItemRange: (items, primaryItem) => gallery.setItemMultiSelection(items.map(toGalleryItemKey), primaryItem),setCompareItem: gallery.setCompareItem,setSearchTerm: gallery.setSearchTerm,+ // The similarity reference is widget state rather than a workbench+ // command: it patches the gallery widget's persisted values, the same+ // surface the parsed query is read back from. Changing the query resets+ // pagination (mirroring setGallerySearchTerm) and clears the text term+ // the chip visually replaces — left behind, a stale term would keep+ // filtering invisibly and poison the preview widget's navigation query.+ // Filmstrip/preview navigation under semantic ranking still follows+ // board chronology, not similarity rank — an inherited limitation.+ setSemanticImageQuery: (reference) =>+ widgets.patchGalleryValues({ galleryPage: 0, searchTerm: '', semanticImageQuery: reference }),setView: gallery.setView,toggleItemInSelection: gallery.toggleItemSelection,updateSettings: gallery.updateSettings,@@ -221,5 +231,6 @@ export const useGalleryActions = ({selectedBoardId,t,uploadFiles,+ widgets,]);};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.tsindex 3fb1244403..fb0c1d6dd0 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.test.ts@@ -103,6 +103,37 @@ describe('mergeGalleryItemWindow', () => {expect(items.slice(0, 60).map((item) => item.name)).toEqual(recentImages.map((image) => image.imageName).reverse());});+ it('preserves backend relevance order and skips the recent overlay while a semantic query is active', () => {+ const createRankedItem = (name: string, createdAt: string): GalleryItem => ({+ boardId: 'none',+ category: 'general',+ createdAt,+ fullUrl: `/images/${name}`,+ height: 64,+ isIntermediate: false,+ kind: 'image',+ name,+ starred: false,+ thumbnailUrl: `/thumbnails/${name}`,+ width: 64,+ });+ // Deliberately out of chronological order: relevance is the order.+ const rankedItems = [+ createRankedItem('oldest.png', '2026-01-01T00:00:00.000Z'),+ createRankedItem('newest.png', '2026-07-01T00:00:00.000Z'),+ createRankedItem('middle.png', '2026-03-01T00:00:00.000Z'),+ ];++ expect(+ mergeGalleryItemWindow({+ backendItems: rankedItems,+ filter: { ...filter, semanticQuery: { imageName: 'ref.png', kind: 'image' } },+ maxRows: 60,+ recentImages: [asGenerated(createImage(1))],+ }).map((item) => item.name)+ ).toEqual(['oldest.png', 'newest.png', 'middle.png']);+ });+it('uses SQLite binary ordering for mixed-case and punctuation name ties in both directions', () => {const createTiedItem = (name: string): GalleryItem => ({boardId: 'none',diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.tsindex ff08aa3cb7..7ac5d695d8 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts@@ -1,4 +1,5 @@import type { GalleryItem } from '@features/gallery/core/items';+import type { GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';import type { GallerySettings } from '@features/gallery/core/settings';import type { GalleryBoard, GalleryView, GeneratedImageContract } from '@features/gallery/core/types';@@ -32,6 +33,8 @@ export interface GalleryData {isWindowTruncated: boolean;items: GalleryItem[] | null;loadMore: () => void;+ /** The current query's failure, or null while it is healthy. */+ queryError: Error | null;total: number | null;}@@ -53,6 +56,7 @@ const isRecentItemVisible = (item: GalleryItem, filter: GalleryItemsFilter): boofilter.searchTerm !== '' ||filter.createdFrom !== undefined ||filter.createdTo !== undefined ||+ Boolean(filter.semanticQuery) ||isDateBoardId(filter.boardId)) {return false;@@ -85,19 +89,25 @@ export const mergeGalleryItemWindow = ({.filter((item) => !backendItemKeys.has(toGalleryItemKey(item)) && isRecentItemVisible(item, filter));const seenItemKeys = new Set<string>();- return [...missingRecentItems, ...backendItems]- .filter((item) => {- const key = toGalleryItemKey(item);+ const mergedItems = [...missingRecentItems, ...backendItems].filter((item) => {+ const key = toGalleryItemKey(item);- if (seenItemKeys.has(key)) {- return false;- }+ if (seenItemKeys.has(key)) {+ return false;+ }- seenItemKeys.add(key);- return true;- })- .sort((a, b) => compareGalleryItems(a, b, filter))- .slice(0, maxRows);+ seenItemKeys.add(key);+ return true;+ });++ // Semantic results arrive in relevance order, which a date re-sort would+ // destroy; the backend order is the meaning of the list. (No recent items+ // are overlaid in that mode, so the merge is the backend window itself.)+ if (!filter.semanticQuery) {+ mergedItems.sort((a, b) => compareGalleryItems(a, b, filter));+ }++ return mergedItems.slice(0, maxRows);};/**@@ -129,6 +139,7 @@ export const useGalleryData = ({recentImages,searchTerm,selectedBoardId,+ semanticQuery = null,settings,}: {galleryView: GalleryView;@@ -136,6 +147,8 @@ export const useGalleryData = ({recentImages: readonly GeneratedImageContract[];searchTerm: string;selectedBoardId: string;+ /** When set, items come from semantic search (similarity order) instead of the board listing. */+ semanticQuery?: GallerySemanticReference | null;settings: GallerySettings;}): GalleryData => {const { boards } = useGalleryBoards({ settings });@@ -151,6 +164,7 @@ export const useGalleryData = ({galleryView,orderDir: settings.imageOrderDir,searchTerm: dateParse.text,+ ...(semanticQuery ? { semanticQuery } : {}),starredFirst: settings.starredFirst,}),[@@ -159,12 +173,14 @@ export const useGalleryData = ({dateParse.range?.to,dateParse.text,galleryView,+ semanticQuery,settings.imageOrderDir,settings.starredFirst,]);const {data: queryData,+ error: queryError,fetchNextPage,hasNextPage,isFetching,@@ -216,5 +232,5 @@ export const useGalleryData = ({void fetchNextPage();}, [fetchNextPage, hasMore, isFetchingNextPage]);- return { boards, filter, hasMore, isLoadingItems: isFetching, isWindowTruncated, items, loadMore, total };+ return { boards, filter, hasMore, isLoadingItems: isFetching, isWindowTruncated, items, loadMore, queryError, total };};diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.pyindex 07bc4adc53..7d9972f32c 100644--- a/tests/app/routers/test_image_map.py+++ b/tests/app/routers/test_image_map.py@@ -34,12 +34,17 @@ class MockApiDependencies(ApiDependencies):class FakeImageIndexService(ImageIndexServiceBase):- """Records projection requests instead of running a worker."""+ """Records projection/search requests instead of running a worker."""def __init__(self, model_id: str | None = MODEL_ID) -> None:self._model_id = model_idself.projection_requests: list[tuple[str, bool]] = []self.spent_failed_scopes: dict[str, str] = {}+ self.search_calls: list[tuple[str | None, int]] = []+ self.search_results: list[tuple[str, float]] = []+ self.text_unavailable = False+ self.embedded_texts: list[str] = []+ self.embedded_images: list = []@propertydef model_id(self) -> str | None:@@ -50,6 +55,29 @@ class FakeImageIndexService(ImageIndexServiceBase):return Nonereturn ImageIndexStatus(total=5, embedded=3)+ def embed_text(self, text: str) -> np.ndarray:+ from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError++ if self.text_unavailable:+ raise TextSearchUnavailableError("no text encoder installed")+ self.embedded_texts.append(text)+ vector = np.zeros(DIM, dtype=np.float32)+ vector[0] = 1.0+ return vector++ def embed_image(self, image) -> np.ndarray:+ self.embedded_images.append(image)+ vector = np.zeros(DIM, dtype=np.float32)+ vector[0] = 1.0+ return vector++ def get_accessible_embeddings(self, user_id: str | None) -> tuple[list[str], np.ndarray]:+ return [], np.empty((0, 0), dtype=np.float32)++ def search_similar(self, user_id: str | None, query_embedding: np.ndarray, limit: int) -> list[tuple[str, float]]:+ self.search_calls.append((user_id, limit))+ return self.search_results[:limit]+def request_projection(self,user_id: str,@@ -157,6 +185,7 @@ def client(monkeypatch, mock_invoker: Invoker) -> TestClient:monkeypatch.setattr("invokeai.app.api.routers.image_map.ApiDependencies", mock_deps)monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", mock_deps)monkeypatch.setattr("invokeai.app.api.routers.auth.ApiDependencies", mock_deps)+ monkeypatch.setattr("invokeai.app.api.routers._access.ApiDependencies", mock_deps)return TestClient(app)@@ -179,6 +208,18 @@ def _seed_embedded_image(mock_invoker: Invoker, image_name: str, user_id: str =_records(mock_invoker).upsert_embedding(image_name, MODEL_ID, vec / np.linalg.norm(vec))+def _save_unembedded_image(mock_invoker: Invoker, image_name: str, user_id: str = SYSTEM_USER_ID) -> None:+ mock_invoker.services.image_records.save(+ image_name=image_name,+ image_origin=ResourceOrigin.INTERNAL,+ image_category=ImageCategory.GENERAL,+ width=16,+ height=16,+ has_workflow=False,+ user_id=user_id,+ )++def _seed_projection(mock_invoker: Invoker, user_id: str, image_names: list[str], coords: np.ndarray) -> None:accessible = _records(mock_invoker).list_accessible_embedded_images(None if user_id == SYSTEM_USER_ID else user_id, MODEL_ID@@ -650,3 +691,204 @@ def test_an_all_non_finite_projection_is_not_permanently_blank(assert body["points"] == []assert body["state"] == "computing", "a row with nothing servable must ask for a recompute"assert [user for user, _ in image_index_service.projection_requests] == [SYSTEM_USER_ID]+++# --- Semantic search ---+++def test_search_requires_exactly_one_query_kind(client: TestClient) -> None:+ assert client.get("/api/v1/image_map/search").status_code == 422+ assert client.get("/api/v1/image_map/search", params={"image_name": "a.png", "q": "cats"}).status_code == 422+++def test_search_disabled_index_conflicts(image_index_service: FakeImageIndexService, client: TestClient) -> None:+ image_index_service._model_id = None+ assert client.get("/api/v1/image_map/search", params={"q": "cats"}).status_code == 409+++def test_text_search_returns_ranked_results(image_index_service: FakeImageIndexService, client: TestClient) -> None:+ image_index_service.search_results = [("a.png", 0.9), ("b.png", 0.5)]++ body = client.get("/api/v1/image_map/search", params={"limit": 10, "q": "a red barn"}).json()++ assert image_index_service.embedded_texts == ["a red barn"]+ # System user is admin in single-user mode -> global (None) scope.+ assert image_index_service.search_calls == [(None, 10)]+ assert body["results"] == [+ {"image_name": "a.png", "score": 0.9},+ {"image_name": "b.png", "score": 0.5},+ ]+++def test_text_search_unavailable_encoder_conflicts_with_message(+ image_index_service: FakeImageIndexService, client: TestClient+) -> None:+ image_index_service.text_unavailable = True++ response = client.get("/api/v1/image_map/search", params={"q": "cats"})++ assert response.status_code == 409+ assert "text encoder" in response.json()["detail"]+++def test_image_search_uses_stored_embedding(+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient+) -> None:+ _seed_embedded_image(mock_invoker, "ref.png")+ image_index_service.search_results = [("ref.png", 1.0), ("close.png", 0.8)]++ body = client.get("/api/v1/image_map/search", params={"image_name": "ref.png"}).json()++ assert [r["image_name"] for r in body["results"]] == ["ref.png", "close.png"]+ # No text was embedded; the stored image embedding was the query.+ assert image_index_service.embedded_texts == []+++def test_image_search_embeds_unindexed_reference_on_demand(+ monkeypatch, mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient+) -> None:+ from PIL import Image++ _save_unembedded_image(mock_invoker, "not-indexed.png")+ monkeypatch.setattr(mock_invoker.services.images, "get_pil_image", lambda name: Image.new("RGB", (4, 4)))+ image_index_service.search_results = [("a.png", 0.7)]++ body = client.get("/api/v1/image_map/search", params={"image_name": "not-indexed.png"}).json()++ # The reference had no stored embedding, so its file was embedded live.+ assert len(image_index_service.embedded_images) == 1+ assert [r["image_name"] for r in body["results"]] == ["a.png"]+++def test_image_search_unembeddable_reference_is_404(mock_invoker: Invoker, client: TestClient) -> None:+ # No stored embedding AND the file cannot be loaded (mock file store).+ _save_unembedded_image(mock_invoker, "not-indexed.png")+ assert client.get("/api/v1/image_map/search", params={"image_name": "not-indexed.png"}).status_code == 404+++def test_search_by_image_upload_returns_ranked_results(+ image_index_service: FakeImageIndexService, client: TestClient+) -> None:+ from io import BytesIO++ from PIL import Image++ buffer = BytesIO()+ Image.new("RGB", (8, 8), color=(200, 30, 30)).save(buffer, format="PNG")+ image_index_service.search_results = [("a.png", 0.9), ("b.png", 0.4)]++ response = client.post(+ "/api/v1/image_map/search_by_image",+ params={"limit": 5},+ files={"image": ("ref.png", buffer.getvalue(), "image/png")},+ )++ assert response.status_code == 200+ assert len(image_index_service.embedded_images) == 1+ assert image_index_service.search_calls == [(None, 5)]+ assert [r["image_name"] for r in response.json()["results"]] == ["a.png", "b.png"]+++def test_search_by_image_requires_exactly_one_source(client: TestClient) -> None:+ assert client.post("/api/v1/image_map/search_by_image").status_code == 422+ assert (+ client.post(+ "/api/v1/image_map/search_by_image",+ params={"image_url": "https://example.com/a.png"},+ files={"image": ("ref.png", b"\x89PNG", "image/png")},+ ).status_code+ == 422+ )+++def test_search_by_image_rejects_bad_inputs(client: TestClient) -> None:+ # Bytes that are not a decodable image.+ response = client.post(+ "/api/v1/image_map/search_by_image", files={"image": ("ref.png", b"not an image", "image/png")}+ )+ assert response.status_code == 415++ # Non-http(s) schemes and private/loopback hosts are refused outright —+ # including hostname and non-canonical IP-literal spellings of loopback,+ # which resolve via getaddrinfo rather than a strict literal parse.+ for bad_url in (+ "ftp://example.com/a.png",+ "http://127.0.0.1/a.png",+ "http://localhost/a.png",+ "http://127.1/a.png",+ "http://2130706433/a.png",+ ):+ assert client.post("/api/v1/image_map/search_by_image", params={"image_url": bad_url}).status_code == 422, (+ bad_url+ )+++def test_search_by_image_revalidates_redirect_targets(monkeypatch, client: TestClient) -> None:+ # A public URL redirecting to a private address must be refused: requests'+ # automatic redirect following is disabled and every hop is re-validated.+ import requests++ class FakeRedirect:+ status_code = 302+ is_redirect = True+ headers = {"location": "http://127.0.0.1:9090/steal"}++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return False++ calls: list[str] = []++ def fake_get(url, **kwargs):+ calls.append(url)+ assert kwargs.get("allow_redirects") is False+ return FakeRedirect()++ monkeypatch.setattr(requests, "get", fake_get)+ monkeypatch.setattr(+ "socket.getaddrinfo",+ lambda host, port, **kw: [+ (None, None, None, None, ("127.0.0.1" if host != "public.example" else "93.184.216.34", port))+ ],+ )++ response = client.post("/api/v1/image_map/search_by_image", params={"image_url": "http://public.example/a.png"})++ assert response.status_code == 422+ # The first (public) hop was fetched; the redirect target failed+ # validation before any second request was issued.+ assert calls == ["http://public.example/a.png"]+++def test_multiuser_image_search_enforces_read_access_and_user_scope(+ multiuser, mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient+) -> None:+ _create_user(mock_invoker, "[email protected]", is_admin=True)+ user1_id = _create_user(mock_invoker, "[email protected]")+ user2_id = _create_user(mock_invoker, "[email protected]")+ user2_headers = _login(client, "[email protected]")++ # user1's private image: user2 cannot use it as a search reference.+ _seed_embedded_image(mock_invoker, "private1.png", user_id=user1_id)+ response = client.get("/api/v1/image_map/search", params={"image_name": "private1.png"}, headers=user2_headers)+ assert response.status_code == 403++ # A text search from a non-admin is scoped to their own user id.+ client.get("/api/v1/image_map/search", params={"q": "boats"}, headers=user2_headers)+ assert image_index_service.search_calls == [(user2_id, 100)]++ # search_by_image must scope identically to /search.+ from io import BytesIO++ from PIL import Image++ buffer = BytesIO()+ Image.new("RGB", (4, 4)).save(buffer, format="PNG")+ client.post(+ "/api/v1/image_map/search_by_image",+ files={"image": ("ref.png", buffer.getvalue(), "image/png")},+ headers=user2_headers,+ )+ assert image_index_service.search_calls[-1] == (user2_id, 100)diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.pyindex 2920dbf76b..efb9bedeb8 100644--- a/tests/app/services/image_index/test_image_index_service.py+++ b/tests/app/services/image_index/test_image_index_service.py@@ -1331,6 +1331,86 @@ def test_systemic_embedding_outage_does_not_starve_projections(service.stop()+# --- Semantic search ---+++def test_search_similar_ranks_by_cosine_and_respects_scope(+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ service.start(_make_invoker(images_service, index_records))+ _wait_until(lambda: not service._backfill_pending.is_set())++ # Overwrite with hand-built vectors so the ranking is deterministic.+ def unit(index: int, mix: float = 0.0) -> np.ndarray:+ v = np.zeros(DIM, dtype=np.float32)+ v[index] = 1.0+ v[0] += mix+ return v / np.linalg.norm(v)++ for name, vec in [("a.png", unit(0)), ("close.png", unit(1, mix=0.9)), ("far.png", unit(2))]:+ _save_image(image_records, name)+ index_records.upsert_embedding(name, MODEL_ID, vec)++ results = service.search_similar(None, unit(0), limit=2)++ assert [name for name, _ in results] == ["a.png", "close.png"]+ assert results[0][1] > results[1][1] > 0.0++ # limit caps the result count; scores are descending.+ assert len(service.search_similar(None, unit(0), limit=1)) == 1+++def test_embed_image_normalizes_and_requires_running_service(+ images_service: ImageService, index_records: ImageIndexRecordsSqlite, service: ImageIndexService+) -> None:+ probe = Image.new("RGB", (4, 4))++ with pytest.raises(RuntimeError):+ service.embed_image(probe) # not started yet++ service.start(_make_invoker(images_service, index_records))+ vector = service.embed_image(probe)++ assert vector.shape == (DIM,)+ assert np.isclose(float(np.linalg.norm(vector)), 1.0)+++def test_embed_image_retries_once_after_a_failed_encode(+ images_service: ImageService, index_records: ImageIndexRecordsSqlite+) -> None:+ # A failed load evicts the model from the RAM cache so the next attempt+ # rebuilds it from disk; embed_image must make that second attempt itself.+ calls = {"count": 0}++ def flaky_encode(images):+ calls["count"] += 1+ if calls["count"] == 1:+ raise RuntimeError("model cache entry was left in a bad state")+ return _fake_encode(images)++ service = ImageIndexService(encode_fn=flaky_encode, model_id=MODEL_ID)+ service.start(_make_invoker(images_service, index_records))++ vector = service.embed_image(Image.new("RGB", (4, 4)))++ try:+ assert calls["count"] == 2+ assert vector.shape == (DIM,)++ # A second consecutive failure propagates.+ def always_failing(images):+ raise RuntimeError("still broken")++ service._encode_fn = always_failing+ with pytest.raises(RuntimeError, match="still broken"):+ service.embed_image(Image.new("RGB", (4, 4)))+ finally:+ service.stop()++def test_projection_request_is_requeued_when_the_database_read_fails(image_records: SqliteImageRecordStorage,images_service: ImageService,@@ -1455,3 +1535,86 @@ def test_projection_job_is_popped_before_running(service: ImageIndexService) ->assert job == ("u1", False)assert service._projection_requests == {}, "the job must be removed when it is taken"assert service._next_projection_job() is None+++def test_embed_text_unavailable_without_model_config(+ images_service: ImageService, index_records: ImageIndexRecordsSqlite, service: ImageIndexService+) -> None:+ from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError++ service.start(_make_invoker(images_service, index_records))++ # Test mode injects encode_fn without a real model config: the text tower+ # cannot exist, and the error must be the typed one the router maps to 409.+ with pytest.raises(TextSearchUnavailableError):+ service.embed_text("a query")+++def test_embed_text_unavailable_when_tokenizer_files_missing(tmp_path) -> None:+ # The InvokeAI-published CLIP model dir ships a full-CLIP config.json but no+ # tokenizer files: AutoTokenizer resolves a tokenizer class from the config+ # and then fails with TypeError (not OSError) on the absent vocab file. The+ # failure must still surface as the typed error the router maps to 409.+ import json++ from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError+ from invokeai.backend.model_manager.taxonomy import ModelType++ (tmp_path / "config.json").write_text(+ json.dumps({"model_type": "clip", "architectures": ["CLIPModel"], "text_config": {}, "vision_config": {}})+ )+ service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)+ service._invoker = SimpleNamespace(services=SimpleNamespace(configuration=SimpleNamespace(models_path=tmp_path))) # type: ignore[assignment]+ service._model_config = SimpleNamespace(type=ModelType.CLIPVision, path=str(tmp_path)) # type: ignore[assignment]++ with pytest.raises(TextSearchUnavailableError):+ service.embed_text("a query")+++def test_search_similar_returns_empty_when_not_running(service: ImageIndexService) -> None:+ assert service.search_similar(None, np.ones(DIM, dtype=np.float32), limit=5) == []+++def test_search_similar_scopes_to_the_requesting_user(+ db: SqliteDatabase,+ image_records: SqliteImageRecordStorage,+ images_service: ImageService,+ index_records: ImageIndexRecordsSqlite,+ service: ImageIndexService,+) -> None:+ from invokeai.app.services.users.users_common import UserCreateRequest+ from invokeai.app.services.users.users_default import UserService++ other_user = UserService(db=db).create(+ UserCreateRequest(email="[email protected]", display_name="Scoped", password="TestPass123", is_admin=False)+ )+ service.start(_make_invoker(images_service, index_records))+ _wait_until(lambda: not service._backfill_pending.is_set())++ def unit(index: int) -> np.ndarray:+ v = np.zeros(DIM, dtype=np.float32)+ v[index] = 1.0+ return v++ # system owns mine.png; the other user owns theirs.png (both unboarded).+ _save_image(image_records, "mine.png")+ index_records.upsert_embedding("mine.png", MODEL_ID, unit(0))+ image_records.save(+ image_name="theirs.png",+ image_origin=ResourceOrigin.INTERNAL,+ image_category=ImageCategory.GENERAL,+ width=16,+ height=16,+ has_workflow=False,+ user_id=other_user.user_id,+ )+ index_records.upsert_embedding("theirs.png", MODEL_ID, unit(0))++ # The other user's scope must exclude the system user's private image+ # even though it scores identically.+ names = [name for name, _ in service.search_similar(other_user.user_id, unit(0), limit=10)]+ assert names == ["theirs.png"]++ # Admin scope (None) sees both.+ admin_names = {name for name, _ in service.search_similar(None, unit(0), limit=10)}+ assert admin_names == {"mine.png", "theirs.png"}