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: rank gallery semantic search within the selected board
Josh Corbett2910b2fb25b4
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.pyindex 7e1799eee7..30f3e8acc0 100644--- a/invokeai/app/api/routers/image_map.py+++ b/invokeai/app/api/routers/image_map.py@@ -2,7 +2,8 @@ import asyncioimport threadingimport timefrom collections import OrderedDict-from typing import Literal, Optional+from datetime import date+from typing import AbstractSet, Literal, Optionalimport numpy as npfrom fastapi import File, HTTPException, Query, UploadFile, status@@ -12,7 +13,11 @@ from pydantic import BaseModel, Fieldfrom invokeai.app.api.auth_dependencies import AdminUserOrDefault, CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependencies-from invokeai.app.api.routers._access import assert_image_read_access, assert_video_read_access+from invokeai.app.api.routers._access import (+ assert_board_read_access,+ assert_image_read_access,+ assert_video_read_access,+)from invokeai.app.services.image_files.image_files_common import ImageFileNotFoundExceptionfrom invokeai.app.services.image_index.cluster_labels import (MAX_CUSTOM_VOCAB_TERM_LENGTH,@@ -294,6 +299,41 @@ def _served_kinds(include_videos: bool) -> tuple[MediaKind, ...]:return ("image", "video") if include_videos else ("image",)+SearchBoardQuery = Query(+ default=None,+ description="Restrict results to this board's items; 'none' selects items on no board. Omit to rank every "+ "accessible item.",+)+SearchCreatedDateQuery = Query(+ default=None,+ description="Restrict results to items created on this ISO date, as the date-based virtual boards list them.",+)+++def _search_scope(+ board_id: Optional[str], created_date: Optional[date], current_user: CurrentUserOrDefault+) -> Optional[AbstractSet[str]]:+ """The item names a scoped search may return, or None when the search covers everything accessible.++ Membership comes from the gallery's own listing, intersected later with the indexed items, so+ items on archived boards (never indexed for search) cannot match. Image and video names never+ collide, so a flat name set is enough.+ """+ if board_id is None and created_date is None:+ return None+ if board_id is not None and board_id != "none":+ assert_board_read_access(board_id, current_user)+ names = ApiDependencies.invoker.services.gallery.get_item_names(+ starred_first=False,+ is_intermediate=False,+ board_id=board_id,+ user_id=current_user.user_id,+ is_admin=current_user.is_admin,+ created_date=created_date.isoformat() if created_date is not None else None,+ )+ return frozenset(names.item_names)++def _search_reference(image_name: Optional[str], video_name: Optional[str]) -> Optional[IndexedItem]:"""The reference item for a similarity search, or None when none was given.@@ -527,6 +567,8 @@ async def search_image_map(video_name: Optional[str] = Query(default=None, description="Reference video for similarity search"),limit: int = Query(default=100, ge=1, le=500, description="Maximum number of results"),include_videos: bool = IncludeVideosQuery,+ board_id: Optional[str] = SearchBoardQuery,+ created_date: Optional[date] = SearchCreatedDateQuery,) -> ImageMapSearchResponse:"""Ranks the user's accessible images and videos by semantic similarity.@@ -554,6 +596,10 @@ async def search_image_map(user_id, is_admin = _scope(current_user)scope_user = None if is_admin else user_id+ # Resolved before embedding so an unreadable or empty scope costs no encoder pass.+ within = await asyncio.to_thread(_search_scope, board_id, created_date, current_user)+ if within is not None and not within:+ return ImageMapSearchResponse(results=[])if q is not None:try:@@ -614,7 +660,12 @@ async def search_image_map()results = await asyncio.to_thread(- services.image_index.search_similar, scope_user, query_embedding, limit, _served_kinds(include_videos)+ services.image_index.search_similar,+ scope_user,+ query_embedding,+ limit,+ _served_kinds(include_videos),+ within,)return ImageMapSearchResponse(results=[ImageMapSearchResult(image_name=item.name, kind=item.kind, score=score) for item, score in results]@@ -746,6 +797,8 @@ async def search_image_map_by_image(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"),include_videos: bool = IncludeVideosQuery,+ board_id: Optional[str] = SearchBoardQuery,+ created_date: Optional[date] = SearchCreatedDateQuery,) -> ImageMapSearchResponse:"""Ranks the user's accessible images by similarity to an arbitrary reference image.@@ -768,6 +821,9 @@ async def search_image_map_by_image(user_id, is_admin = _scope(current_user)scope_user = None if is_admin else user_id+ within = await asyncio.to_thread(_search_scope, board_id, created_date, current_user)+ if within is not None and not within:+ return ImageMapSearchResponse(results=[])if image is not None:data = await image.read(MAX_SEARCH_IMAGE_BYTES + 1)@@ -806,7 +862,12 @@ async def search_image_map_by_image()results = await asyncio.to_thread(- services.image_index.search_similar, scope_user, query_embedding, limit, _served_kinds(include_videos)+ services.image_index.search_similar,+ scope_user,+ query_embedding,+ limit,+ _served_kinds(include_videos),+ within,)return ImageMapSearchResponse(results=[ImageMapSearchResult(image_name=item.name, kind=item.kind, score=score) for item, score in results]diff --git a/invokeai/app/services/image_index/image_index_base.py b/invokeai/app/services/image_index/image_index_base.pyindex 9dea4217d9..d003cf5314 100644--- a/invokeai/app/services/image_index/image_index_base.py+++ b/invokeai/app/services/image_index/image_index_base.py@@ -1,5 +1,5 @@from abc import ABC, abstractmethod-from typing import Literal, Optional+from typing import AbstractSet, Literal, Optionalimport numpy as npfrom PIL import Image@@ -135,14 +135,17 @@ class ImageIndexServiceBase(ABC):query_embedding: np.ndarray,limit: int,kinds: Optional[tuple[MediaKind, ...]] = None,+ within: Optional[AbstractSet[str]] = None,) -> list[tuple[IndexedItem, float]]:"""Rank the user's accessible embedded items by cosine similarity.Embeddings are L2-normalized, so similarity is a dot product. Pass- user_id=None for the admin scope, and `kinds` to restrict results to- those media kinds (None means every kind). Returns (item, score)- pairs, best first. Call off the event loop — the accessible embedding- matrix may be read from the database on a cache miss.+ user_id=None for the admin scope, `kinds` to restrict results to+ those media kinds (None means every kind), and `within` to restrict+ them to those item names, such as one board's listing (None means+ every accessible item). Returns (item, score) pairs, best first.+ Call off the event loop — the accessible embedding matrix may be+ read from the database on a cache miss."""passdiff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.pyindex b10ede6d46..d5ec9cea90 100644--- a/invokeai/app/services/image_index/image_index_default.py+++ b/invokeai/app/services/image_index/image_index_default.py@@ -3,7 +3,7 @@ import threadingimport timefrom pathlib import Pathfrom queue import Empty, Queue-from typing import TYPE_CHECKING, Any, Callable, Optional+from typing import TYPE_CHECKING, AbstractSet, Any, Callable, Optionalimport numpy as npimport torch@@ -697,18 +697,24 @@ class ImageIndexService(ImageIndexServiceBase):query_embedding: np.ndarray,limit: int,kinds: Optional[tuple[MediaKind, ...]] = None,+ within: Optional[AbstractSet[str]] = None,) -> list[tuple[IndexedItem, float]]:found_items, matrix = self.get_accessible_embeddings(user_id)if matrix.size == 0:return []scores = matrix @ query_embedding.astype(matrix.dtype)- # Restricting by kind selects among the SCORES, not among the rows: masking the matrix- # would copy it, and it is the largest array in the process (~300 MB at 100k x 768).+ # Restricting by kind or name selects among the SCORES, not among the rows: masking the+ # matrix would copy it, and it is the largest array in the process (~300 MB at 100k x 768).# The dot product over rows nobody asked for is a rounding error beside that.candidates = np.arange(len(found_items))- if kinds is not None:- candidates = candidates[[found_items[index].kind in kinds for index in candidates]]+ if kinds is not None or within is not None:+ candidates = candidates[+ [+ (kinds is None or item.kind in kinds) and (within is None or item.name in within)+ for item in found_items+ ]+ ]if candidates.size == 0:return []scores = scores[candidates]diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 82b0afffc3..24f75742db 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -7119,6 +7119,43 @@"title": "Include Videos"},"description": "Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names."+ },+ {+ "name": "board_id",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Restrict results to this board's items; 'none' selects items on no board. Omit to rank every accessible item.",+ "title": "Board Id"+ },+ "description": "Restrict results to this board's items; 'none' selects items on no board. Omit to rank every accessible item."+ },+ {+ "name": "created_date",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string",+ "format": "date"+ },+ {+ "type": "null"+ }+ ],+ "description": "Restrict results to items created on this ISO date, as the date-based virtual boards list them.",+ "title": "Created Date"+ },+ "description": "Restrict results to items created on this ISO date, as the date-based virtual boards list them."}],"responses": {@@ -7201,6 +7238,43 @@"title": "Include Videos"},"description": "Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names."+ },+ {+ "name": "board_id",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Restrict results to this board's items; 'none' selects items on no board. Omit to rank every accessible item.",+ "title": "Board Id"+ },+ "description": "Restrict results to this board's items; 'none' selects items on no board. Omit to rank every accessible item."+ },+ {+ "name": "created_date",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string",+ "format": "date"+ },+ {+ "type": "null"+ }+ ],+ "description": "Restrict results to items created on this ISO date, as the date-based virtual boards list them.",+ "title": "Created Date"+ },+ "description": "Restrict results to items created on this ISO date, as the date-based virtual boards list them."}],"requestBody": {diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 281265b050..32c717edb6 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -53947,6 +53947,10 @@ export interface operations {limit?: number;/** @description Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names. */include_videos?: boolean;+ /** @description Restrict results to this board's items; 'none' selects items on no board. Omit to rank every accessible item. */+ board_id?: string | null;+ /** @description Restrict results to items created on this ISO date, as the date-based virtual boards list them. */+ created_date?: string | null;};header?: never;path?: never;@@ -53983,6 +53987,10 @@ export interface operations {limit?: number;/** @description Include indexed videos among the returned items. Leave off unless the client resolves each item through the endpoint its `kind` names. */include_videos?: boolean;+ /** @description Restrict results to this board's items; 'none' selects items on no board. Omit to rank every accessible item. */+ board_id?: string | null;+ /** @description Restrict results to items created on this ISO date, as the date-based virtual boards list them. */+ created_date?: string | null;};header?: never;path?: never;diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 598f52a9cb..f89ebf52ae 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -3925,6 +3925,7 @@"semanticCluster": "Cluster: {{name}}","semanticSimilarTo": "Similar to {{name}}","semanticTextSearch": "Semantic search: {{name}}",+ "semanticSearchArchivedBoard": "Archived boards aren't indexed, so semantic search finds nothing here.","semanticSearchAriaLabel": "Semantic search","semanticSearchInstallModel": "Install the “{{model}}” model to build the image index and enable semantic search.","semanticSearchModelMissing": "Semantic search needs the embedding model “{{model}}”, which is not installed.",diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.tsindex 25a798ef37..5392c69260 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts@@ -775,16 +775,31 @@ const toSemanticResults = (body: SemanticSearchBody): GallerySemanticResult[] =>score: result.score,}));+/** Date boards scope by creation day; no board, or the all-readable scope, ranks everything accessible. */+const toSemanticScopeParams = (boardId: string | undefined): { board_id?: string; created_date?: string } => {+ if (boardId === undefined || boardId === ALL_READABLE_BOARDS_ID) {+ return {};+ }++ return isDateBoardId(boardId) ? { created_date: getDateFromBoardId(boardId) } : { board_id: boardId };+};+/*** Text and gallery-image searches use GET; URLs and registered files use POST. include_videos opts into kind-aware- * result hydration.+ * result hydration. The server ranks within `boardId` before applying the limit.*/export const searchGallerySemantic = async (query: Exclude<GallerySemanticQuery, { kind: 'cluster' }>,- { limit = SEMANTIC_SEARCH_MAX_RESULTS, signal }: { limit?: number; signal?: AbortSignal } = {}+ {+ boardId,+ limit = SEMANTIC_SEARCH_MAX_RESULTS,+ signal,+ }: { boardId?: string; limit?: number; signal?: AbortSignal } = {}): Promise<GallerySemanticResult[]> => {+ const scope = { ...toSemanticScopeParams(boardId), include_videos: true, limit };+if (query.kind === 'url') {- const params = toSearchParams({ image_url: query.url, include_videos: true, limit });+ const params = toSearchParams({ image_url: query.url, ...scope });return toSemanticResults(await apiFetchJson<SemanticSearchBody>(`/api/v1/image_map/search_by_image?${params}`, {@@ -806,21 +821,16 @@ export const searchGallerySemantic = async (form.append('image', entry.blob, entry.label || 'image');return toSemanticResults(- await apiFetchJson<SemanticSearchBody>(- `/api/v1/image_map/search_by_image?${toSearchParams({ include_videos: true, limit })}`,- {- body: form,- method: 'POST',- signal,- }- )+ await apiFetchJson<SemanticSearchBody>(`/api/v1/image_map/search_by_image?${toSearchParams(scope)}`, {+ body: form,+ method: 'POST',+ signal,+ }));}const params = toSearchParams(- query.kind === 'text'- ? { include_videos: true, limit, q: query.query }- : { image_name: query.imageName, include_videos: true, limit }+ query.kind === 'text' ? { ...scope, q: query.query } : { image_name: query.imageName, ...scope });return toSemanticResults(await apiFetchJson<SemanticSearchBody>(`/api/v1/image_map/search?${params}`, { signal }));@@ -855,9 +865,11 @@ export const fetchImageIndexAvailability = async (signal: AbortSignal): Promise</** Kind-qualified refs retain relevance order for page hydration, range selection, and deletion neighbors. */export const listSemanticGalleryItemNames = async ({+ boardId,query,signal,}: {+ boardId?: string;query: GallerySemanticQuery;signal?: AbortSignal;}): Promise<GalleryItemNames> => {@@ -872,7 +884,7 @@ export const listSemanticGalleryItemNames = async ({};}- const results = await searchGallerySemantic(query, { signal });+ const results = await searchGallerySemantic(query, { boardId, signal });return {items: results.map((result) => result.ref),diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.tsindex 449e1f5184..b55cda06b1 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts@@ -1,4 +1,5 @@import type { GalleryItem, GalleryItemsPage } from '@features/gallery/core/items';+import type { GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';import { accountLifecycle } from '@platform/state/accountLifecycle';import { InfiniteQueryObserver, QueryClient, type InfiniteData } from '@tanstack/react-query';@@ -414,8 +415,8 @@ describe('canonicalizeGalleryItemsFilter under a semantic query', () => {const reference = { fileId: 'external-1-abc', kind: 'file', label: 'shot.png' } as const;it('ignores the controls a ranked result set does not answer to', () => {- // Semantic results depend only on the reference; unrelated filters must not repeat blob uploads or remote- // downloads.+ // Semantic results depend only on the reference and its board; unrelated filters must not repeat blob uploads+ // or remote downloads.const base = canonicalizeGalleryItemsFilter({boardId: 'board-a',galleryView: 'images',@@ -424,7 +425,6 @@ describe('canonicalizeGalleryItemsFilter under a semantic query', () => {});for (const variant of [- { boardId: 'board-b' },{ galleryView: 'assets' as const },{ orderDir: 'ASC' as const },{ starred: true },@@ -442,6 +442,15 @@ describe('canonicalizeGalleryItemsFilter under a semantic query', () => {}});+ it('keys a search by the board it ranks within, but a map cluster by its members alone', () => {+ const inBoard = (boardId: string, semanticQuery: GallerySemanticReference) =>+ canonicalizeGalleryItemsFilter({ boardId, galleryView: 'images', searchTerm: '', semanticQuery });+ const cluster = { clusterId: 'cluster-1', kind: 'cluster', label: 'Cats' } as const;++ expect(inBoard('board-b', reference)).not.toEqual(inBoard('board-a', reference));+ expect(inBoard('board-b', cluster)).toEqual(inBoard('board-a', cluster));+ });+it('still distinguishes one reference from another', () => {const other = canonicalizeGalleryItemsFilter({boardId: 'board-a',diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.tsindex 4f372c28bc..9d24f64951 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts@@ -1,5 +1,6 @@import type { GalleryItem, GalleryItemsPage } from '@features/gallery/core/items';import type { GallerySemanticQuery, GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';+import type { GallerySettings } from '@features/gallery/core/settings';import type { GalleryBoardOrderBy, GalleryOrderDir, GalleryView } from '@features/gallery/core/types';import type { AccountScope } from '@platform/state/accountLifecycle';@@ -60,9 +61,9 @@ export interface GalleryItemsFilter {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.+ * When set, items come from semantic image-similarity search over the board+ * (relevance order) instead of the board listing; order/starred controls do+ * not apply to a ranked result set.*/semanticQuery?: GallerySemanticReference | null;/** true = only starred items, false = only unstarred; absent = all. */@@ -121,10 +122,10 @@ export const canonicalizeGalleryItemsFilter = (filter: GalleryItemsFilter): Canoconst semantic = filter.semanticQuery ? toGallerySemanticQuery(filter.semanticQuery) : undefined;if (semantic) {- // Pin irrelevant filter fields to canonical values: semantic rankings depend only on the query, and distinct- // keys would repeat uploads or downloads.+ // Pin irrelevant filter fields to canonical values: rankings depend only on the query and its board (a cluster is+ // a fixed member list with no board), and distinct keys would repeat uploads or downloads.return {- boardId: '',+ boardId: semantic.kind === 'cluster' ? '' : filter.boardId,galleryView: 'images',orderDir: 'DESC',searchTerm: '',@@ -193,7 +194,7 @@ const galleryItemNamesOptionsForOwner = (owner: AccountScope, filter: CanonicalGqueryFn: async ({ signal }) => {const requestSignal = AbortSignal.any([signal, owner.signal]);const result = await (filter.semantic- ? listSemanticGalleryItemNames({ query: filter.semantic, signal: requestSignal })+ ? listSemanticGalleryItemNames({ boardId: filter.boardId, query: filter.semantic, signal: requestSignal }): isDateBoardId(filter.boardId)? listGalleryDateBoardItemNames({ ...filter, signal: requestSignal }): listGalleryItemNames({ ...filter, signal: requestSignal }));@@ -374,6 +375,14 @@ export const galleryBoardsOptions = (query: GalleryBoardsQuery = {}) => {});};+/** The boards query the gallery grid resolves its selected board against. */+export const getGalleryListingBoardsQuery = (settings: GallerySettings): GalleryBoardsQuery => ({+ includeArchived: settings.showArchivedBoards,+ includeDateBoards: settings.showDateBoards,+ orderBy: settings.boardOrderBy,+ orderDir: settings.boardOrderDir,+});+const getNextPageParam = (window: GalleryItemsWindow,lastPage: Pick<GalleryItemsPage, 'total'>,diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.tsindex 5170b3b308..4879ac4926 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.test.ts@@ -1,4 +1,5 @@import type { GalleryItem, GalleryItemMutationResult, GalleryItemsPage } from '@features/gallery/core/items';+import type { GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';import type { GalleryBoard } from '@features/gallery/core/types';import type { AccountScope } from '@platform/state/accountLifecycle';@@ -270,24 +271,21 @@ 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.+ it('evicts moved items from board-scoped similarity windows but keeps them in a map cluster', () => {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' },- })- );+ const getKey = (semanticQuery: GallerySemanticReference) =>+ galleryKeys.items(+ captureAccountScope(),+ canonicalizeGalleryItemsFilter({ boardId: 'board-1', galleryView: 'images', searchTerm: '', semanticQuery })+ );+ const semanticKey = getKey({ imageName: 'ref.png', kind: 'image' });+ // A cluster is a fixed member list from the map, not a board listing.+ const clusterKey = getKey({ clusterId: 'cluster-1', kind: 'cluster', label: 'Cats' });client.setQueryData(semanticKey, createData([[target, untouched]]));+ client.setQueryData(clusterKey, createData([[target, untouched]]));patchGalleryItemCaches(client, {boardId: 'board-2',@@ -295,10 +293,13 @@ describe('Gallery item cache patches', () => {result: getResult([{ kind: 'image', name: target.name }]),});- const after = getData(client, semanticKey);+ const ranked = getData(client, semanticKey);+ const cluster = getData(client, clusterKey);- expect(after.pages.flatMap((page) => page.items)).toEqual([{ ...target, boardId: 'board-2' }, untouched]);- expect(after.pages.map((page) => page.total)).toEqual([2]);+ expect(ranked.pages.flatMap((page) => page.items)).toEqual([untouched]);+ expect(ranked.pages.map((page) => page.total)).toEqual([1]);+ expect(cluster.pages.flatMap((page) => page.items)).toEqual([{ ...target, boardId: 'board-2' }, untouched]);+ expect(cluster.pages.map((page) => page.total)).toEqual([2]);});describe('starred strip entries', () => {diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.tsindex 383209f66a..caddb59d22 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queryCache.ts@@ -97,7 +97,7 @@ const mapPageItems = (};};-/** Ranked windows ignore board moves; starred-only listings lose items immediately when unstarred. */+/** Cluster windows ignore board moves; starred-only listings lose items immediately when unstarred. */const patchRemovesItems = (filter: CanonicalGalleryItemsFilter, patch: GalleryItemCachePatch): boolean => {if (patch.kind === 'delete') {return true;@@ -108,7 +108,7 @@ const patchRemovesItems = (filter: CanonicalGalleryItemsFilter, patch: GalleryIt}return (- filter.semantic === undefined &&+ filter.semantic?.kind !== 'cluster' &&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.tsindex 762099e380..cea8594859 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/semanticSearch.test.ts@@ -110,6 +110,41 @@ describe('searchGallerySemantic', () => {});});+describe('semantic search scope', () => {+ beforeEach(() => {+ mocks.apiFetchJson.mockReset();+ mocks.apiFetchJson.mockResolvedValue({ results: [] });+ });++ it('ranks within the gallery board, a date board by its day, and everything for the all-readable scope', async () => {+ const query = { kind: 'text', query: 'boats' } as const;++ await listSemanticGalleryItemNames({ boardId: 'board-1', query });+ await listSemanticGalleryItemNames({ boardId: 'none', query });+ await listSemanticGalleryItemNames({ boardId: 'by_date:2026-08-02', query });+ await listSemanticGalleryItemNames({ boardId: 'all', query });++ expect(mocks.apiFetchJson.mock.calls.map(([path]) => path)).toEqual([+ '/api/v1/image_map/search?board_id=board-1&include_videos=true&limit=500&q=boats',+ '/api/v1/image_map/search?board_id=none&include_videos=true&limit=500&q=boats',+ '/api/v1/image_map/search?created_date=2026-08-02&include_videos=true&limit=500&q=boats',+ '/api/v1/image_map/search?include_videos=true&limit=500&q=boats',+ ]);+ });++ it('scopes by-image searches the same way', async () => {+ const fileId = registerExternalImageFile(new Blob(['not-really-a-png']), 'cat.png');++ await searchGallerySemantic({ fileId, kind: 'file' }, { boardId: 'board-1', limit: 10 });+ await searchGallerySemantic({ kind: 'url', url: 'https://example.com/cat.jpg' }, { boardId: 'board-1', limit: 10 });++ expect(mocks.apiFetchJson.mock.calls.map(([path]) => path)).toEqual([+ '/api/v1/image_map/search_by_image?board_id=board-1&include_videos=true&limit=10',+ '/api/v1/image_map/search_by_image?image_url=https%3A%2F%2Fexample.com%2Fcat.jpg&board_id=board-1&include_videos=true&limit=10',+ ]);+ });+});+describe('semantic page hydration', () => {beforeEach(() => {mocks.apiFetchJson.mockReset();diff --git a/invokeai/frontend/webv2/src/features/gallery/queries.ts b/invokeai/frontend/webv2/src/features/gallery/queries.tsindex 18f592ce55..63f8f0dc0c 100644--- a/invokeai/frontend/webv2/src/features/gallery/queries.ts+++ b/invokeai/frontend/webv2/src/features/gallery/queries.ts@@ -9,6 +9,7 @@ export {galleryItemsInfiniteOptions,galleryKeys,galleryStarredStripOptions,+ getGalleryListingBoardsQuery,imageIndexAvailabilityOptions,} from './data/queries';export type {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsxindex c8f6b46eae..8a6c333dd9 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.browser.test.tsx@@ -1,5 +1,6 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop */import type { GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';+import type { GalleryBoard } from '@features/gallery/core/types';import type { ImageIndexAvailability } from '@features/gallery/data/backend';import type { GalleryUiAdapter } from '@features/gallery/react';@@ -90,8 +91,12 @@ const actions = {setSemanticSearchText: vi.fn(),};+const archivedBoards = [{ archived: true, id: 'old-board' }];+interface HarnessGallery {+ boards: Array<Pick<GalleryBoard, 'archived' | 'id'>>;searchTerm: string;+ selectedBoardId: string;semanticImageQuery: GallerySemanticReference | null;semanticSearchText: string | null;}@@ -99,7 +104,9 @@ interface HarnessGallery {/** Write text intents back into controlled values to model the workbench while recording calls. */const Harness = ({ initial }: { initial: Partial<HarnessGallery> }) => {const [gallery, setGallery] = useState<HarnessGallery>({+ boards: [],searchTerm: '',+ selectedBoardId: 'none',semanticImageQuery: null,semanticSearchText: null,...initial,@@ -337,6 +344,38 @@ describe('GalleryItemSearch semantic mode', () => {expect(actions.commitSemanticSearch.mock.calls).toEqual([['sun']]);});+ it('explains why a semantic search in an archived board finds nothing', async () => {+ await renderSearch({ boards: archivedBoards, selectedBoardId: 'old-board', semanticSearchText: 'sun' });++ expect(host?.querySelector('[role="status"]')?.textContent).toBe('widgets.gallery.semanticSearchArchivedBoard');+ });++ it('explains why an image similarity search in an archived board finds nothing', async () => {+ await renderSearch({+ boards: archivedBoards,+ selectedBoardId: 'old-board',+ semanticImageQuery: { imageName: 'ref.png', kind: 'image' },+ });++ expect(host?.querySelector('[role="status"]')?.textContent).toBe('widgets.gallery.semanticSearchArchivedBoard');+ });++ it('leaves a cluster in an archived board unexplained, since it lists its members', async () => {+ await renderSearch({+ boards: archivedBoards,+ selectedBoardId: 'old-board',+ semanticImageQuery: { clusterId: 'c1', kind: 'cluster', label: 'Boats' },+ });++ expect(host?.querySelector('[role="status"]')).toBeNull();+ });++ it('leaves a metadata search in an archived board unexplained, since it still matches', async () => {+ await renderSearch({ boards: archivedBoards, searchTerm: 'sun', selectedBoardId: 'old-board' });++ expect(host?.querySelector('[role="status"]')).toBeNull();+ });+it('shows no hint on a ready index', async () => {await renderSearch({ semanticSearchText: 'sun' });diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsxindex b84a68024d..c646b26599 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx@@ -225,10 +225,17 @@ export const GalleryItemSearch = () => {return invalid ? t('widgets.gallery.dateFilterInvalid', { value: invalid.raw }) : null;}, [gallery.searchTerm, isSemanticMode, t]);+ // The index leaves archived boards out, so a ranked search scoped to one can only come back empty. Clusters are+ // explicit member lists, not rankings, so they are exempt.+ const isRankedSearch =+ isSemanticMode || (gallery.semanticImageQuery !== null && gallery.semanticImageQuery.kind !== 'cluster');+ const isArchivedBoard = gallery.boards.some((board) => board.id === gallery.selectedBoardId && board.archived);const semanticHint =isSemanticMode && indexAvailability?.state === 'model_missing'? t('widgets.gallery.semanticSearchModelMissing', { model: indexAvailability.modelName ?? '' })- : null;+ : isRankedSearch && isArchivedBoard+ ? t('widgets.gallery.semanticSearchArchivedBoard')+ : null;const hint = invalidHint ?? semanticHint;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.tsindex 0cce9f773e..2df22f0d85 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts@@ -12,6 +12,7 @@ import {GALLERY_PAGE_SIZE,galleryBoardsOptions,galleryItemsInfiniteOptions,+ getGalleryListingBoardsQuery,type GalleryItemsFilter,} from '@features/gallery/data/queries';import { parseDateTokens } from '@platform/search/dateTokens';@@ -39,14 +40,7 @@ export interface GalleryData {const EMPTY_BOARDS: GalleryBoard[] = [];const useGalleryBoards = ({ settings }: { settings: GallerySettings }) => {- const query = useQuery(- galleryBoardsOptions({- includeArchived: settings.showArchivedBoards,- includeDateBoards: settings.showDateBoards,- orderBy: settings.boardOrderBy,- orderDir: settings.boardOrderDir,- })- );+ const query = useQuery(galleryBoardsOptions(getGalleryListingBoardsQuery(settings)));return { boards: query.data ?? EMPTY_BOARDS };};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsxindex a040655721..f074954e53 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx@@ -183,6 +183,7 @@ vi.mock('@features/gallery/queries', () => ({flattenGalleryItemsData: (data: InfiniteData<GalleryItemsPage, number> | undefined) =>data?.pages.flatMap((page) => page.items) ?? [],galleryBoardsOptions: () => ({ queryFn: () => [], queryKey: ['test-boards'], staleTime: Infinity }),+ getGalleryListingBoardsQuery: () => ({}),galleryStarredStripOptions: (query: { boardId: string; starred?: boolean }) => ({queryFn: () => {mocks.galleryStripFetches.push(query);@@ -532,6 +533,7 @@ beforeEach(() => {delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).imageOrderDir;delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).paginationMode;delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).semanticImageQuery;+ delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).selectedBoardId;delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).selectedImageQuery;delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).starredOnly;mocks.project.widgetInstances.gallery.state.values.recentImages = mocks.recentImages;@@ -1452,6 +1454,36 @@ describe('preview keyboard navigation boundary', () => {);});+ it('ranks the filmstrip within the board the gallery shows, not the board the selection was made in', async () => {+ const galleryValues = mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>;++ // Picked while board A was shown; the gallery has since moved to board B with the search still active.+ galleryValues.selectedBoardId = 'board-b';+ galleryValues.selectedImageQuery = {+ boardId: 'board-a',+ galleryView: 'images',+ imageOrderDir: 'DESC',+ page: 0,+ paginationMode: 'infinite',+ searchTerm: '',+ };+ galleryValues.semanticImageQuery = { kind: 'text', query: 'sunset' };++ await render();++ expect(mocks.galleryItemFilters.at(-1)).toMatchObject({+ boardId: 'board-b',+ semanticQuery: { kind: 'text', query: 'sunset' },+ });++ // Without a search the filmstrip keeps stepping through the listing the item was picked from.+ delete galleryValues.semanticImageQuery;+ await rerender();++ expect(mocks.galleryItemFilters.at(-1)).toMatchObject({ boardId: 'board-a' });+ expect(mocks.galleryItemFilters.at(-1)).not.toHaveProperty('semanticQuery');+ });+it('stamps the top of the board listing for a ranked pick even when the footer paginates the ranking', async () => {const filler = {...mocks.recentImages[0],diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex e0e8eb4ac5..b0e2ba19f6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -17,6 +17,7 @@ import {getGalleryPage,getGallerySelectedImageQuery,getGallerySemanticImageQuery,+ getGallerySelectedBoardId,getGallerySettings,getSelectedGalleryItemFromValues,getBoundedRecentImages,@@ -28,7 +29,7 @@ import {toGalleryItemKey,toGalleryItemRef,} from '@features/gallery/contracts';-import { galleryBoardsOptions } from '@features/gallery/queries';+import { galleryBoardsOptions, getGalleryListingBoardsQuery } from '@features/gallery/queries';import { createGenerateFormValuesSelector } from '@features/generation/react';import {consumeQueueItemSwapProgressImage,@@ -97,6 +98,8 @@ export const getVideoFrameCopyNotice = (? { kind: 'success', title: translate('widgets.preview.copyCurrentFrameSuccess') }: { kind: 'error', title: translate(VIDEO_FRAME_COPY_FAILURE_KEYS[result.reason]) };+const EMPTY_BOARDS: GalleryBoard[] = [];+const fallbackBoards: GalleryBoard[] = [{archived: false,@@ -203,6 +206,13 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {...galleryBoardsOptions(),enabled: hasSelectedItem,});+ // A ranked filmstrip mirrors the grid, which ranks within the board it resolves; share the grid's board list.+ const gallerySettings = getGallerySettings(galleryValues);+ const galleryBoardsQuery = useQuery({+ ...galleryBoardsOptions(getGalleryListingBoardsQuery(gallerySettings)),+ enabled: gallerySemanticQuery !== null,+ });+ const galleryBoardId = getGallerySelectedBoardId(galleryValues, galleryBoardsQuery.data ?? EMPTY_BOARDS);const boards = boardsQuery.data ?? fallbackBoards;const boardName = getBoardName(boards,@@ -239,8 +249,9 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {selectGalleryItem: selectGalleryItemAtPage,selectedImageQuery,selectedItem,+ galleryBoardId,galleryPage: getGalleryPage(galleryValues),- galleryPaginationMode: getGallerySettings(galleryValues).paginationMode,+ galleryPaginationMode: gallerySettings.paginationMode,selectedItemKey,semanticQuery: gallerySemanticQuery,});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.tsindex 7f42710e31..0264eb941e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewNavigation.ts@@ -160,6 +160,7 @@ export const usePreviewNavigation = ({localItems,progressSessions,queueItems,+ galleryBoardId,galleryPage,galleryPaginationMode,selectGalleryItem,@@ -171,6 +172,8 @@ export const usePreviewNavigation = ({/** The live session on screen, when the preview is following one; the cursor sits on it. */followedSessionId: string | null;followSession: (sessionId: string) => void;+ /** The board the gallery grid shows; a ranked list ranks within it, as the grid does. */+ galleryBoardId: string;/** The page the gallery grid is on; a ranked list mirrors it (see below). */galleryPage: number;/** The gallery's own pagination mode, likewise mirrored by a ranked list. */@@ -192,13 +195,13 @@ export const usePreviewNavigation = ({() => parseDateTokens(selectedImageQuery.searchTerm),[selectedImageQuery.searchTerm]);- const navigationBoardId = selectedImageQuery.boardId;+ // A ranked filmstrip follows the gallery's current search, board and paging; a listing follows the selection's.+ const navigationBoardId = semanticQuery ? galleryBoardId : selectedImageQuery.boardId;const navigationGalleryView = selectedImageQuery.galleryView;const navigationOrderDir = selectedImageQuery.imageOrderDir;// The grid partitions: its listing is unstarred-only, with the starred// items in the strip above it, unless the starred filter is on.const navigationStarredOnly = selectedImageQuery.starredOnly;- // A ranked filmstrip follows the gallery's current search.const navigationSemanticQuery = semanticQuery;const navigationSemanticKey = gallerySemanticReferenceKey(navigationSemanticQuery);// Following live has a cursor too, so the listing loads for the step off it.diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex d42484a1b4..b35ccd3247 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -5068,13 +5068,13 @@ describe('workbenchReducer Phase 5 generation flow', () => {});});- it('exits a similarity search when the view moves to another board', () => {+ it('carries a similarity search to another board, which it then ranks within, from the first page', () => {let state = createInitialWorkbenchState();state = workbenchReducer(state, { boardId: 'board-a', type: 'selectGalleryBoard' });state = workbenchReducer(state, {type: 'patchWidgetValues',- values: { galleryPage: 4, semanticImageQuery: { kind: 'text', query: 'sunset' } },+ values: { galleryPage: 4, semanticImageQuery: { kind: 'text', query: 'sunset' }, semanticSearchText: 'sunset' },widgetId: 'gallery',});@@ -5082,7 +5082,8 @@ describe('workbenchReducer Phase 5 generation flow', () => {const values = getProjectWidgetValues(getActiveProject(state), 'gallery');- expect(values.semanticImageQuery).toBeNull();+ expect(values.semanticImageQuery).toEqual({ kind: 'text', query: 'sunset' });+ expect(values.semanticSearchText).toBe('sunset');expect(values.selectedBoardId).toBe('board-b');expect(values.galleryPage).toBe(0);});@@ -5106,8 +5107,9 @@ describe('workbenchReducer Phase 5 generation flow', () => {});});- it('leaves the page stamped on the selection alone when a search is dismissed by a board move', () => {- // This selection predates search; its board page remains valid and must not be reset with ranking pages.+ it('leaves the page stamped on the selection alone when a map cluster is dismissed by a board move', () => {+ // This selection predates the cluster; its board page remains valid and must not be reset with ranking pages.+ // The cluster id is deliberately unregistered: a stale cluster ends with the board all the same.let state = createInitialWorkbenchState();state = workbenchReducer(state, { boardId: 'board-a', type: 'selectGalleryBoard' });@@ -5118,7 +5120,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {});state = workbenchReducer(state, {type: 'patchWidgetValues',- values: { semanticImageQuery: { kind: 'text', query: 'sunset' } },+ values: { semanticImageQuery: { clusterId: 'cluster-gone', kind: 'cluster', label: 'Cats' } },widgetId: 'gallery',});@@ -5444,27 +5446,9 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(galleryValues(state).searchTerm).toBe('');});- it('leaves semantic mode with the ranking on a board move or a tab switch, not on a re-click', () => {+ it('leaves semantic mode on a tab switch, not on a re-click of the current tab', () => {let state = createInitialWorkbenchState();- state = workbenchReducer(state, { boardId: 'board-a', type: 'selectGalleryBoard' });- state = workbenchReducer(state, { searchTerm: 'sunset', type: 'setGallerySearchTerm' });- state = workbenchReducer(state, { enabled: true, type: 'setGallerySemanticSearchMode' });- state = workbenchReducer(state, { boardId: 'board-a', type: 'selectGalleryBoard' });-- expect(galleryValues(state)).toMatchObject({- semanticImageQuery: { kind: 'text', query: 'sunset' },- semanticSearchText: 'sunset',- });-- state = workbenchReducer(state, { boardId: 'board-b', type: 'selectGalleryBoard' });-- expect(galleryValues(state)).toMatchObject({- searchTerm: '',- semanticImageQuery: null,- semanticSearchText: null,- });-state = workbenchReducer(state, { enabled: true, type: 'setGallerySemanticSearchMode' });state = workbenchReducer(state, { text: 'beach', type: 'setGallerySemanticSearchText' });state = workbenchReducer(state, { galleryView: 'images', type: 'setGalleryView' });diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 9e21393332..5991b47020 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -4724,9 +4724,12 @@ export const __workbenchReducerInternal = (galleryPage: 0,selectedBoardId: action.boardId,selectedImageNames: [],- // Only actual board changes clear similarity ranking and semantic text. Preserve selection pages: they- // may still describe the pre-search board listing.- ...(values.selectedBoardId !== action.boardId ? { semanticImageQuery: null, semanticSearchText: null } : {}),+ // A semantic search ranks within the board, so it follows the switch; a map cluster is a fixed member+ // list and ends with an actual board change.+ ...(values.selectedBoardId !== action.boardId &&+ (values.semanticImageQuery as { kind?: unknown } | null | undefined)?.kind === 'cluster'+ ? { semanticImageQuery: null, semanticSearchText: null }+ : {}),}),action.projectId);@@ -4823,7 +4826,7 @@ export const __workbenchReducerInternal = (return updateGalleryValues(state,(values) => {- // Apply delayed commits only when they still match the current field, mode, and board.+ // Apply delayed commits only when they still match the current field and mode; a board switch keeps both.if (values.semanticSearchText !== action.text) {return values;}diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.pyindex 614071483b..4af3b92ae6 100644--- a/tests/app/routers/test_image_map.py+++ b/tests/app/routers/test_image_map.py@@ -2,8 +2,10 @@import loggingimport time+from io import BytesIOfrom pathlib import Pathfrom types import SimpleNamespace+from typing import AbstractSetimport numpy as npimport pytest@@ -14,6 +16,7 @@ from invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.api_app import appfrom invokeai.app.services.board_video_records.board_video_records_sqlite import SqliteBoardVideoRecordStoragefrom invokeai.app.services.config.config_default import InvokeAIAppConfig+from invokeai.app.services.gallery.gallery_default import SqliteGalleryServicefrom invokeai.app.services.image_index.image_index_base import ImageIndexServiceBasefrom invokeai.app.services.image_index.image_index_common import (ImageIndexStatus,@@ -57,6 +60,7 @@ class FakeImageIndexService(ImageIndexServiceBase):self.spent_failed_scopes: dict[str, str] = {}self.search_calls: list[tuple[str | None, int]] = []self.search_kinds: list[tuple[str, ...] | None] = []+ self.search_within: list[AbstractSet[str] | None] = []self.search_results: list[tuple[str, float]] = []self.text_unavailable = Falseself.embedded_texts: list[str] = []@@ -103,10 +107,16 @@ class FakeImageIndexService(ImageIndexServiceBase):query_embedding: np.ndarray,limit: int,kinds: tuple[str, ...] | None = None,+ within: AbstractSet[str] | None = None,) -> list[tuple[IndexedItem, float]]:self.search_calls.append((user_id, limit))self.search_kinds.append(kinds)- results = [(item, score) for item, score in self.search_results if kinds is None or item.kind in kinds]+ self.search_within.append(within)+ results = [+ (item, score)+ for item, score in self.search_results+ if (kinds is None or item.kind in kinds) and (within is None or item.name in within)+ ]return results[:limit]def get_vocab_embeddings(self) -> tuple[list[str], np.ndarray]:@@ -237,7 +247,7 @@ def mock_services(image_index_service: FakeImageIndexService, tmp_path: Path) ->video_files=None, # type: ignorevideo_records=video_records,board_video_records=SqliteBoardVideoRecordStorage(db=db),- gallery=None, # type: ignore+ gallery=SqliteGalleryService(db=db),image_index_records=(index_records := ImageIndexRecordsSqlite(db=db)),image_index=image_index_service,intermediates=None, # type: ignore@@ -1287,6 +1297,68 @@ def test_multiuser_image_search_enforces_read_access_and_user_scope(assert image_index_service.search_calls[-1] == (user2_id, 100)+def test_search_can_be_scoped_to_a_board_the_uncategorized_items_or_a_date(+ image_index_service: FakeImageIndexService, mock_invoker: Invoker, client: TestClient+) -> None:+ _seed_embedded_image(mock_invoker, "on-board.png")+ _seed_embedded_video(mock_invoker, "on-board.mp4")+ _seed_embedded_image(mock_invoker, "loose.png")+ board = mock_invoker.services.board_records.save("Cats", SYSTEM_USER_ID).board_id+ mock_invoker.services.board_image_records.add_image_to_board(board, "on-board.png")+ mock_invoker.services.board_video_records.add_video_to_board(board, "on-board.mp4")+ image_index_service.search_results = [+ (IndexedItem("image", "loose.png"), 0.9),+ (IndexedItem("video", "on-board.mp4"), 0.8),+ (IndexedItem("image", "on-board.png"), 0.7),+ ]+ today = str(mock_invoker.services.image_records.get("loose.png").created_at)[:10]++ def names(**params: object) -> list[str]:+ response = client.get("/api/v1/image_map/search", params={"q": "cat", "include_videos": True, **params})+ assert response.status_code == 200, response.text+ return [result["image_name"] for result in response.json()["results"]]++ assert names() == ["loose.png", "on-board.mp4", "on-board.png"]+ assert names(board_id=board) == ["on-board.mp4", "on-board.png"]+ assert names(board_id="none") == ["loose.png"]+ assert names(created_date=today) == ["loose.png", "on-board.mp4", "on-board.png"]+ assert names(created_date="2001-01-01") == []+ # An empty scope answers without embedding the query.+ assert image_index_service.embedded_texts == ["cat"] * 4+ # The scope reaches the service, which ranks within it before applying the limit.+ assert image_index_service.search_within[0] is None+ assert image_index_service.search_within[1] == {"on-board.png", "on-board.mp4"}+ assert client.get("/api/v1/image_map/search", params={"q": "cat", "created_date": "not-a-date"}).status_code == 422++ buffer = BytesIO()+ Image.new("RGB", (4, 4)).save(buffer, format="PNG")+ by_image = client.post(+ "/api/v1/image_map/search_by_image",+ params={"board_id": board},+ files={"image": ("ref.png", buffer.getvalue(), "image/png")},+ )+ assert [result["image_name"] for result in by_image.json()["results"]] == ["on-board.png"]+++def test_multiuser_board_scoped_search_requires_read_access(+ 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]")+ _create_user(mock_invoker, "[email protected]")+ user2_headers = _login(client, "[email protected]")+ _seed_embedded_image(mock_invoker, "private1.png", user_id=user1_id)+ board = mock_invoker.services.board_records.save("Private", user1_id).board_id+ mock_invoker.services.board_image_records.add_image_to_board(board, "private1.png")++ response = client.get("/api/v1/image_map/search", params={"q": "boats", "board_id": board}, headers=user2_headers)++ assert response.status_code == 403+ # Refused before the query is embedded or ranked.+ assert image_index_service.embedded_texts == []+ assert image_index_service.search_calls == []++# --- Cluster labels ---diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.pyindex 53dba09219..3126bc7757 100644--- a/tests/app/services/image_index/test_image_index_service.py+++ b/tests/app/services/image_index/test_image_index_service.py@@ -1636,6 +1636,12 @@ def test_search_similar_ranks_by_cosine_and_respects_scope(# limit caps the result count; scores are descending.assert len(service.search_similar(None, unit(0), limit=1)) == 1+ # A name restriction applies before the limit, so a narrow scope still gets its best matches.+ assert [item for item, _ in service.search_similar(None, unit(0), limit=1, within={"far.png"})] == imgs("far.png")+ assert service.search_similar(None, unit(0), limit=5, within=set()) == []+ # Kind and name restrictions both apply.+ assert service.search_similar(None, unit(0), limit=5, kinds=("video",), within={"a.png"}) == []+def test_embed_image_normalizes_and_requires_running_service(images_service: ImageService, index_records: ImageIndexRecordsSqlite, service: ImageIndexService