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(webv2): semantic search mode for the gallery search bar
Lincoln Steinc7a98932f72f
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 5c4c296bd2..a6d0b7b070 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -3585,6 +3585,7 @@"clearClusterSearch": "Clear cluster filter","clearImageSearch": "Clear image similarity search","clearSemanticSearch": "Clear semantic search",+ "exitSemanticSearch": "Exit semantic search","createBoard": "Create board","createBoardNamed": "Create board \"{{name}}\"","collapseStarredItems": "Collapse starred items",@@ -3733,6 +3734,11 @@"semanticCluster": "Cluster: {{name}}","semanticSimilarTo": "Similar to {{name}}","semanticTextSearch": "Semantic search: {{name}}",+ "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.",+ "semanticSearchModelMissingTitle": "Embedding model not installed",+ "semanticSearchPlaceholder": "Describe what to find…","semanticWebImage": "web image","selectImageForPreview": "Select {{name}} for preview","selectionActions": "Selection actions",diff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.tsindex 4695193757..2752ec11fe 100644--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts@@ -42,6 +42,7 @@ export {stripSessionScopedGallerySearch,stripUnresolvableGallerySearch,registerImageCluster,+ toGallerySemanticTextReference,type GallerySemanticReference,} from './core/semanticImageQuery';export {diff --git a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.tsindex 6556f463ed..f2aff69513 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/semanticImageQuery.ts@@ -47,6 +47,16 @@ export const gallerySemanticReferenceKey = (reference: GallerySemanticReference}};+/**+ * The reference a semantic-search field commits for its text: whitespace is+ * not a query, so blank text reads as no search at all.+ */+export const toGallerySemanticTextReference = (text: string): GallerySemanticReference | null => {+ const query = text.trim();++ return query ? { kind: 'text', query } : null;+};+/** The label-free shape a reference contributes to query cache keys. */export const toGallerySemanticQuery = (reference: GallerySemanticReference): GallerySemanticQuery => {switch (reference.kind) {diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.tsindex f250b022bd..1d820ad921 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts@@ -845,6 +845,40 @@ export const searchGallerySemantic = async (return toSemanticResults(await apiFetchJson<SemanticSearchBody>(`/api/v1/image_map/search?${params}`, { signal }));};+/**+ * Whether the server can rank a text query: not configured at all, configured+ * but without its embedding model, or ready.+ */+export interface ImageIndexAvailability {+ state: 'disabled' | 'model_missing' | 'ready';+ /** The configured embedding model's name; set only while it is missing. */+ modelName: string | null;+}++interface ImageIndexStatusBody {+ enabled: boolean;+ model_name?: string | null;+}++/**+ * Read from the map's status endpoint, whose `enabled` is "the index has its+ * model": text search needs exactly that and the stored embeddings, and never+ * the map's projection, so the projection half of the response is not read.+ * `model_name` is set only when indexing is configured and the model is+ * missing, which is what separates that case from a disabled index.+ */+export const fetchImageIndexAvailability = async (signal: AbortSignal): Promise<ImageIndexAvailability> => {+ const body = await apiFetchJson<ImageIndexStatusBody>('/api/v1/image_map/status', { signal });++ if (body.enabled) {+ return { modelName: null, state: 'ready' };+ }++ return body.model_name+ ? { modelName: body.model_name, state: 'model_missing' }+ : { modelName: null, state: 'disabled' };+};+/*** The ranked result set as item refs, in relevance order. Pages hydrate* slices of this list (`hydrateGalleryDateBoardItemPage`), and rangediff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.tsindex eed180a5ac..3ac4692d3f 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.test.ts@@ -28,6 +28,8 @@ import {galleryItemsInfiniteOptions,galleryStarredStripOptions,getGalleryItemListQueries,+ IMAGE_INDEX_UNAVAILABLE_POLL_MS,+ imageIndexAvailabilityOptions,getGalleryItemsFilterFromKey,isGalleryStarredStripQueryKey,canonicalizeGalleryItemsFilter,@@ -487,6 +489,28 @@ describe('canonicalizeGalleryItemsFilter under a semantic query', () => {});});+describe('imageIndexAvailabilityOptions', () => {+ const pollFor = (state: { status: 'error' | 'success'; data?: { modelName: string | null; state: string } }) => {+ const { refetchInterval } = imageIndexAvailabilityOptions();++ return typeof refetchInterval === 'function'+ ? refetchInterval({ state } as unknown as Parameters<typeof refetchInterval>[0])+ : refetchInterval;+ };++ it('polls only while the answer can still change on its own', () => {+ // A model the server keeps re-checking for, or a call that failed, are+ // worth asking again; a settled answer is not, so a ready index does not+ // cost a status call every half minute for the whole session.+ expect(pollFor({ data: { modelName: 'clip', state: 'model_missing' }, status: 'success' })).toBe(+ IMAGE_INDEX_UNAVAILABLE_POLL_MS+ );+ expect(pollFor({ status: 'error' })).toBe(IMAGE_INDEX_UNAVAILABLE_POLL_MS);+ expect(pollFor({ data: { modelName: null, state: 'ready' }, status: 'success' })).toBe(false);+ expect(pollFor({ data: { modelName: null, state: 'disabled' }, status: 'success' })).toBe(false);+ });+});+describe('galleryStarredStripOptions', () => {beforeEach(() => {backend.hydrateGalleryDateBoardItemPage.mockReset();diff --git a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts b/invokeai/frontend/webv2/src/features/gallery/data/queries.tsindex b6cb2a8f6a..6b7d0626e1 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/queries.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/queries.ts@@ -23,6 +23,7 @@ import {import {type GalleryItemNames,+ fetchImageIndexAvailability,hydrateGalleryDateBoardItemPage,isDateBoardId,listGalleryBoards,@@ -196,6 +197,7 @@ export const galleryKeys = {itemNamesForAccount: (owner: AccountScope) => [...galleryKeys.itemNamesRoot(), getAccountKey(owner)] as const,itemNames: (owner: AccountScope, filter: CanonicalGalleryItemsFilter) =>[...galleryKeys.itemNamesForAccount(owner), filter] as const,+ imageIndexAvailability: (owner: AccountScope) => [...galleryKeys.all, 'image-index', getAccountKey(owner)] as const,};const galleryItemNamesOptionsForOwner = (owner: AccountScope, filter: CanonicalGalleryItemsFilter) =>@@ -337,6 +339,36 @@ export const fetchGalleryItemsRange = async (return result.items.length <= limit ? result : { ...result, items: result.items.slice(0, limit) };};+/**+ * Polled only while the answer is "not yet": a missing model that the server+ * re-checks for on its own, or a status call that failed outright. A settled+ * answer is re-read only when a fresh consumer mounts after the stale time,+ * so a model removed mid-session is noticed on the next layout change+ * without the field polling a ready index for the whole session.+ */+export const IMAGE_INDEX_UNAVAILABLE_POLL_MS = 30_000;+const IMAGE_INDEX_STALE_MS = 5 * 60_000;++export const imageIndexAvailabilityOptions = () => {+ const owner = captureAccountScope();++ return queryOptions({+ queryFn: async ({ signal }) => {+ const availability = await fetchImageIndexAvailability(AbortSignal.any([signal, owner.signal]));++ assertAccountScopeCurrent(owner);++ return availability;+ },+ queryKey: galleryKeys.imageIndexAvailability(owner),+ refetchInterval: (query) =>+ query.state.status === 'error' || query.state.data?.state === 'model_missing'+ ? IMAGE_INDEX_UNAVAILABLE_POLL_MS+ : false,+ staleTime: IMAGE_INDEX_STALE_MS,+ });+};+export const galleryBoardsOptions = (query: GalleryBoardsQuery = {}) => {const owner = captureAccountScope();const canonicalQuery = canonicalizeBoardsQuery(query);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 0e35d5552b..43897db56c 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@@ -84,6 +84,7 @@ const createGallery = (settings: Partial<GallerySettings> = {}): GalleryStateViesearchTerm: '',selectedBoardId: 'dogs',semanticImageQuery: null,+ semanticSearchText: 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 12ccef0975..09149cf04a 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@@ -254,6 +254,7 @@ const createGallery = (overrides: Partial<GalleryStateView> = {}): GalleryStateVselectedItemKey: 'image:first.png',selectedItemKeys: ['image:first.png'],semanticImageQuery: null,+ semanticSearchText: null,settings: { ...getGallerySettings({ paginationMode: 'paginated' }), imageDensityPercent: 0 },starredOnly: false,...overrides,@@ -691,6 +692,22 @@ describe('GalleryImageGrid mixed item cells', () => {expect(sectionOrder()).toEqual(['regular']);});+ it('reads a ranking that matched nothing as a search result, not an empty board', async () => {+ setStrip([]);+ await renderGallery(+ createGallery({+ items: [],+ searchTerm: '',+ semanticImageQuery: { kind: 'text', query: 'sunset' },+ semanticSearchText: 'sunset',+ settings: DENSE_SETTINGS,+ })+ );++ expect(host?.textContent).toContain('No items');+ expect(host?.textContent).not.toContain('Drop media');+ });+it('keeps showing the strip when every item on the board is starred', async () => {setStrip([starred]);await renderGallery(createGallery({ items: [], settings: DENSE_SETTINGS }));diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsxindex 6ff9f6bb81..865f87ecbd 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx@@ -186,7 +186,9 @@ export const GalleryImageGrid = () => {// The listing is unstarred-only, so a board whose items are all starred// still has the strip to show.const isEmpty = gallery.items.length === 0 && starredStrip.items.length === 0;- const hasActiveSearch = gallery.searchTerm.trim() !== '';+ // A ranking that matched nothing is still a search result, never an empty+ // board inviting an upload.+ const hasActiveSearch = gallery.searchTerm.trim() !== '' || gallery.semanticImageQuery !== null;const isVirtualBoard = isDateBoardId(gallery.selectedBoardId);const rows = useMemo(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 2a0a0ee74a..ba77d1f6d3 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,52 +1,206 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop */+import type { GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';+import type { ImageIndexAvailability } from '@features/gallery/data/backend';+import type { GalleryUiAdapter } from '@features/gallery/react';+import { ChakraProvider } from '@chakra-ui/react';+import { GalleryUiProvider } from '@features/gallery/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';-import { act } from 'react';+import { act, useMemo, useState, type ReactNode } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { page } from 'vitest/browser';import type { GalleryWidgetContextValue } from './GalleryWidgetContext';-import { GalleryItemSearch } from './GalleryItemSearch';+import { GalleryItemSearch, SEMANTIC_SEARCH_COMMIT_DEBOUNCE_MS } from './GalleryItemSearch';import { GalleryWidgetContext } from './GalleryWidgetContext';+const mocks = vi.hoisted(() => ({+ fetchImageIndexAvailability: vi.fn<() => Promise<ImageIndexAvailability>>(),+}));++vi.mock('@features/gallery/data/backend', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ fetchImageIndexAvailability: () => mocks.fetchImageIndexAvailability(),+}));+vi.mock('react-i18next', () => ({useTranslation: () => ({i18n: { language: 'en' },- t: (key: string) => key,+ t: (key: string, options?: Record<string, string>) => (options?.model ? `${key}:${options.model}` : key),}),}));let host: HTMLDivElement | null = null;let root: Root | null = null;+let queryClient: QueryClient | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-const renderSearch = async () => {- const contextValue = {- actions: { setSearchTerm: vi.fn() },- gallery: { searchTerm: '' },- } as unknown as GalleryWidgetContextValue;+const notificationsAdd = vi.fn();+const noop = vi.fn();+const NoopProvider = ({ children }: { children: ReactNode }) => children;+const adapter: GalleryUiAdapter = {+ ItemActionsProvider: NoopProvider,+ ImageContextMenu: () => null,+ antialiasProgressImages: false,+ exportProject: noop,+ gallery: {+ clearSelection: noop,+ reconcileDeletedBoardOutcome: noop,+ selectBoard: noop,+ selectImage: noop,+ selectItem: noop,+ setCompareImage: noop,+ setCompareItem: noop,+ setItemMultiSelection: noop,+ setPage: noop,+ setPageInfo: noop,+ setSearchTerm: noop,+ setStarredOnly: noop,+ setSemanticSearchMode: noop,+ setSemanticSearchText: noop,+ commitSemanticSearch: noop,+ clearSearch: noop,+ setView: noop,+ toggleItemSelection: noop,+ updateSettings: noop,+ },+ galleryValues: {},+ generateValues: {},+ liveFollowEnabled: false,+ progressSessions: [],+ pinnedProgressSessionId: null,+ followProgressSession: noop,+ notifications: { add: notificationsAdd, reportError: noop },+ projectId: 'project-1',+ projectName: 'Project',+ widgets: { openGallery: () => true, patchGalleryValues: noop },+};++const actions = {+ clearSearch: vi.fn(),+ commitSemanticSearch: vi.fn(),+ setSearchTerm: vi.fn(),+ setSemanticImageQuery: vi.fn(),+ setSemanticSearchMode: vi.fn(),+ setSemanticSearchText: vi.fn(),+};++interface HarnessGallery {+ searchTerm: string;+ semanticImageQuery: GallerySemanticReference | null;+ semanticSearchText: string | null;+}++/**+ * Stands in for the workbench store: the two text intents write back into+ * the values the field reads, so a controlled input behaves as it does in the+ * app, while every intent is still recorded on the spies.+ */+const Harness = ({ initial }: { initial: Partial<HarnessGallery> }) => {+ const [gallery, setGallery] = useState<HarnessGallery>({+ searchTerm: '',+ semanticImageQuery: null,+ semanticSearchText: null,+ ...initial,+ });+ const contextValue = useMemo(+ () =>+ ({+ actions: {+ ...actions,+ setSearchTerm: (searchTerm: string) => {+ actions.setSearchTerm(searchTerm);+ setGallery((current) => ({ ...current, searchTerm }));+ },+ setSemanticSearchText: (semanticSearchText: string) => {+ actions.setSemanticSearchText(semanticSearchText);+ setGallery((current) => ({ ...current, semanticSearchText }));+ },+ },+ gallery,+ }) as unknown as GalleryWidgetContextValue,+ [gallery]+ );++ return (+ <GalleryWidgetContext value={contextValue}>+ <GalleryItemSearch />+ </GalleryWidgetContext>+ );+};++const renderSearch = async (+ gallery: Partial<HarnessGallery> = {},+ availability: ImageIndexAvailability | 'unresolved' = { modelName: null, state: 'ready' }+) => {+ if (availability === 'unresolved') {+ mocks.fetchImageIndexAvailability.mockReturnValue(+ new Promise(() => {+ // Never settles: the field renders before availability is known.+ })+ );+ } else {+ mocks.fetchImageIndexAvailability.mockResolvedValue(availability);+ }await act(() => {root?.render(<ChakraProvider value={system}>- <GalleryWidgetContext value={contextValue}>- <GalleryItemSearch />- </GalleryWidgetContext>+ <QueryClientProvider client={queryClient ?? new QueryClient()}>+ <GalleryUiProvider adapter={adapter}>+ <Harness initial={gallery} />+ </GalleryUiProvider>+ </QueryClientProvider></ChakraProvider>);});++ if (availability !== 'unresolved') {+ // The availability query settles after render; the toggle follows it.+ await vi.waitFor(() => expect(queryClient?.getQueryCache().findAll()[0]?.state.status).toBe('success'));+ await act(async () => {+ await Promise.resolve();+ });+ }+};++const getToggle = () =>+ host?.querySelector<HTMLButtonElement>('button[aria-label="widgets.gallery.semanticSearchAriaLabel"]') ?? null;++const getInput = (): HTMLInputElement => {+ const input = host?.querySelector('input');++ if (!input) {+ throw new Error('search input did not render');+ }++ return input;+};++const typeInto = async (value: string) => {+ await page.getByRole('textbox').fill(value);};beforeEach(() => {host = document.createElement('div');+ host.style.cssText = 'left:0;position:fixed;top:0;width:320px;';document.body.append(host);root = createRoot(host);+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ Object.values(actions).forEach((action) => action.mockClear());+ notificationsAdd.mockClear();+ mocks.fetchImageIndexAvailability.mockReset();});afterEach(async () => {+ vi.useRealTimers();await act(() => root?.unmount());document.querySelectorAll('[data-scope="popover"][data-part="positioner"]').forEach((element) => element.remove());+ queryClient?.clear();+ queryClient = null;host?.remove();host = null;root = null;@@ -68,3 +222,179 @@ describe('GalleryItemSearch help', () => {expect(examples).not.toContain('7d');});});++describe('GalleryItemSearch semantic mode', () => {+ it('offers no toggle when indexing is not configured', async () => {+ await renderSearch({}, { modelName: null, state: 'disabled' });++ expect(getToggle()).toBeNull();+ });++ it('offers the toggle when indexing is configured, even without the model installed', async () => {+ await renderSearch({}, { modelName: 'clip', state: 'model_missing' });++ expect(getToggle()).not.toBeNull();+ expect(getToggle()?.getAttribute('aria-pressed')).toBe('false');+ });++ it('keeps the toggle reachable for a field already in semantic mode while availability is unknown', async () => {+ await renderSearch({ semanticSearchText: 'sunset' }, 'unresolved');++ expect(getToggle()?.getAttribute('aria-pressed')).toBe('true');+ });++ it('enters semantic mode from the toggle and hands the field focus', async () => {+ await renderSearch();++ await act(() => getToggle()?.click());++ expect(actions.setSemanticSearchMode).toHaveBeenCalledWith(true);+ expect(document.activeElement).toBe(getInput());+ expect(notificationsAdd).not.toHaveBeenCalled();+ });++ it('tells the user which model to install when the toggle is pressed without one', async () => {+ await renderSearch({}, { modelName: 'DFN2B-CLIP', state: 'model_missing' });++ await act(() => getToggle()?.click());++ expect(actions.setSemanticSearchMode).toHaveBeenCalledWith(true);+ expect(notificationsAdd).toHaveBeenCalledWith({+ kind: 'info',+ message: 'widgets.gallery.semanticSearchInstallModel:DFN2B-CLIP',+ title: 'widgets.gallery.semanticSearchModelMissingTitle',+ });+ });++ it('marks the field, keeps the typed text live, and ranks it only after a typing pause', async () => {+ await renderSearch({ semanticSearchText: '' });+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });++ expect(getInput().closest('[data-mode]')?.getAttribute('data-mode')).toBe('semantic');+ expect(getInput().getAttribute('aria-label')).toBe('widgets.gallery.semanticSearchAriaLabel');+ expect(getToggle()?.getAttribute('aria-pressed')).toBe('true');+ // The metadata grammar help does not apply to a description.+ expect(host?.querySelector('button[aria-label="widgets.gallery.searchHelpTitle"]')).toBeNull();++ await typeInto('su');+ await typeInto('sun');++ expect(actions.setSemanticSearchText.mock.calls).toEqual([['su'], ['sun']]);+ expect(actions.setSearchTerm).not.toHaveBeenCalled();+ expect(actions.commitSemanticSearch).not.toHaveBeenCalled();++ await act(() => vi.advanceTimersByTime(SEMANTIC_SEARCH_COMMIT_DEBOUNCE_MS - 1));++ expect(actions.commitSemanticSearch).not.toHaveBeenCalled();++ await act(() => vi.advanceTimersByTime(1));++ // One commit, for the text the pause ended on.+ expect(actions.commitSemanticSearch.mock.calls).toEqual([['sun']]);+ });++ it('commits at once on Enter and drops the pending timer', async () => {+ await renderSearch({ semanticSearchText: 'sun' });+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });++ await typeInto('sunset');++ expect(getInput().value).toBe('sunset');++ await act(() => getInput().dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' })));++ expect(actions.commitSemanticSearch.mock.calls).toEqual([['sunset']]);++ await act(() => vi.advanceTimersByTime(SEMANTIC_SEARCH_COMMIT_DEBOUNCE_MS));++ expect(actions.commitSemanticSearch).toHaveBeenCalledOnce();+ });++ it('leaves semantic mode from the toggle and clears everything from the clear button', async () => {+ await renderSearch({ semanticSearchText: 'sunset' });++ await act(() => getToggle()?.click());++ expect(actions.setSemanticSearchMode).toHaveBeenCalledWith(false);++ await act(() =>+ host?.querySelector<HTMLButtonElement>('button[aria-label="widgets.gallery.clearSemanticSearch"]')?.click()+ );++ expect(actions.clearSearch).toHaveBeenCalledOnce();+ });++ it('explains a missing model under the field, and still ranks the text so nothing is left to reconcile', async () => {+ await renderSearch({ semanticSearchText: '' }, { modelName: 'DFN2B-CLIP', state: 'model_missing' });+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });++ const hint = host?.querySelector('[role="status"]');++ expect(hint?.textContent).toBe('widgets.gallery.semanticSearchModelMissing:DFN2B-CLIP');+ expect(getInput().getAttribute('aria-describedby')).toBe(hint?.id);++ await typeInto('sun');+ await act(() => vi.advanceTimersByTime(SEMANTIC_SEARCH_COMMIT_DEBOUNCE_MS));++ expect(actions.commitSemanticSearch.mock.calls).toEqual([['sun']]);+ });++ it('shows no hint on a ready index', async () => {+ await renderSearch({ semanticSearchText: 'sun' });++ expect(host?.querySelector('[role="status"]')).toBeNull();+ });++ it('renders a reference as a chip with the toggle beside it, and a text ranking as the field', async () => {+ await renderSearch({ semanticImageQuery: { imageName: 'ref.png', kind: 'image' } });++ expect(host?.querySelector('input')).toBeNull();+ expect(host?.textContent).toContain('widgets.gallery.semanticSimilarTo');+ expect(getToggle()?.getAttribute('aria-pressed')).toBe('false');++ await act(() => getToggle()?.click());++ expect(actions.setSemanticSearchMode).toHaveBeenCalledWith(true);+ });++ it('renders a text ranking saved before the mode existed as a chip', async () => {+ await renderSearch({ semanticImageQuery: { kind: 'text', query: 'old' }, semanticSearchText: null });++ expect(host?.querySelector('input')).toBeNull();+ expect(host?.textContent).toContain('widgets.gallery.semanticTextSearch');+ });++ it('renders a text ranking in semantic mode as the field, not a chip', async () => {+ await renderSearch({ semanticImageQuery: { kind: 'text', query: 'sun' }, semanticSearchText: 'sun' });++ expect(getInput().value).toBe('sun');+ expect(host?.textContent).not.toContain('widgets.gallery.semanticTextSearch');+ });++ it('drops a pending commit when the mode is left', async () => {+ await renderSearch({ semanticSearchText: '' });+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });++ await typeInto('sun');+ await act(() => getToggle()?.click());+ await act(() => vi.advanceTimersByTime(SEMANTIC_SEARCH_COMMIT_DEBOUNCE_MS));++ expect(actions.setSemanticSearchMode).toHaveBeenCalledWith(false);+ expect(actions.commitSemanticSearch).not.toHaveBeenCalled();+ });++ it('searches metadata as before outside semantic mode', async () => {+ await renderSearch({ searchTerm: 'cat' });++ expect(getInput().closest('[data-mode]')?.getAttribute('data-mode')).toBe('metadata');++ await typeInto('cats');++ expect(actions.setSearchTerm).toHaveBeenCalledWith('cats');+ expect(actions.setSemanticSearchText).not.toHaveBeenCalled();++ await act(() => host?.querySelector<HTMLButtonElement>('button[aria-label="common.clearSearch"]')?.click());++ expect(actions.clearSearch).toHaveBeenCalledOnce();+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsxindex 06600d2081..b2e4dd4ab5 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx@@ -2,21 +2,33 @@ import type { GallerySemanticReference } from '@features/gallery/core/semanticImimport { Box, Code, HStack, Icon, Popover, Portal, Stack, Text } from '@chakra-ui/react';import { semanticReferenceFromDataTransfer } from '@features/gallery/core/semanticImageQuery';+import { imageIndexAvailabilityOptions } from '@features/gallery/data/queries';+import { useMountEffect } from '@platform/react/useMountEffect';import { describeDateRange, findInvalidDateToken, formatIsoDate, parseDateTokens } from '@platform/search/dateTokens';-import { CloseButton, IconButton } from '@platform/ui/Button';+import { CloseButton, IconButton, ToggleIconButton } from '@platform/ui/Button';import { InputShell } from '@platform/ui/InputShell';import { PopoverContent } from '@platform/ui/Popover';+import { useQuery } from '@tanstack/react-query';import { CircleHelpIcon, ImageIcon, MapIcon, SparklesIcon } from 'lucide-react';-import { useCallback, useMemo, useState } from 'react';+import { useCallback, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react';+import { flushSync } from 'react-dom';import { useTranslation } from 'react-i18next';import { GALLERY_SEMANTIC_SEARCH_DROP_ID, useGalleryImageDroppable } from './galleryDnd';import { GallerySearchField } from './GallerySearchField';+import { useGalleryUi } from './GalleryUiContext';import { useGalleryWidget } from './GalleryWidgetContext';-const SEARCH_DATE_HINT_ID = 'gallery-search-date-hint';+const SEARCH_HINT_ID = 'gallery-search-hint';const HELP_POSITIONING = { placement: 'bottom-end' } as const;+/**+ * Typing pause before the semantic text becomes the ranking. Each commit is a+ * server-side embedding plus a full re-rank, so keystrokes must coalesce; a+ * pause this short still reads as "live" rather than as a submit.+ */+export const SEMANTIC_SEARCH_COMMIT_DEBOUNCE_MS = 300;+/** The `key:value` forms `parseDateTokens` accepts, as shown in the help popover. */const DATE_TOKEN_EXAMPLES = [{ descriptionKey: 'widgets.gallery.searchHelpFrom', key: 'from:2026-07-14' },@@ -67,20 +79,101 @@ const getSemanticReferenceName = (reference: GallerySemanticReference): string =export const GalleryItemSearch = () => {const { i18n, t } = useTranslation();const { actions, gallery } = useGalleryWidget();+ const { notifications } = useGalleryUi();+ const { data: indexAvailability } = useQuery(imageIndexAvailabilityOptions());+ const isSemanticMode = gallery.semanticSearchText !== null;+ const semanticText = gallery.semanticSearchText ?? '';+ // Offered whenever indexing is configured, model or index present or not:+ // the field is where a user finds out the feature exists, and the hint+ // below it says what is still missing. The toggle also stays reachable+ // for a persisted semantic field on an install without indexing, so the+ // mode can always be left.+ const isIndexConfigured = indexAvailability !== undefined && indexAvailability.state !== 'disabled';+ const showSemanticToggle = isIndexConfigured || isSemanticMode;++ // The commit trails typing on a timer that belongs to this render tree; a+ // timer that outlives the field is cleared, and one that outlives its text+ // is refused by the reducer.+ const inputRef = useRef<HTMLInputElement>(null);+ const commitTimerRef = useRef<number | null>(null);+ const cancelPendingCommit = useCallback(() => {+ if (commitTimerRef.current !== null) {+ window.clearTimeout(commitTimerRef.current);+ commitTimerRef.current = null;+ }+ }, []);- const handleClearSearch = useCallback(() => actions.setSearchTerm(''), [actions]);- const handleClearSemantic = useCallback(() => actions.setSemanticImageQuery(null), [actions]);+ useMountEffect(() => cancelPendingCommit);- // 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;+ const handleChange = useCallback(+ (value: string) => {+ if (!isSemanticMode) {+ actions.setSearchTerm(value);+ return;+ }- if (query) {- actions.setSemanticImageQuery({ kind: 'text', query });- }- }, [actions, semanticQueryText]);+ actions.setSemanticSearchText(value);+ cancelPendingCommit();+ // The ranking always follows the text, model or no model: a search the+ // server cannot run is reported by the listing's own error channel,+ // beside the hint that says why, and there is no text left behind to+ // reconcile once the model arrives.+ commitTimerRef.current = window.setTimeout(() => {+ commitTimerRef.current = null;+ actions.commitSemanticSearch(value);+ }, SEMANTIC_SEARCH_COMMIT_DEBOUNCE_MS);+ },+ [actions, cancelPendingCommit, isSemanticMode]+ );++ // Enter is the explicit form of the same commit: no reason to keep waiting.+ const handleKeyDown = useCallback(+ (event: KeyboardEvent<HTMLInputElement>) => {+ if (!isSemanticMode || event.key !== 'Enter' || event.nativeEvent.isComposing) {+ return;+ }++ event.preventDefault();+ cancelPendingCommit();+ actions.commitSemanticSearch(event.currentTarget.value);+ },+ [actions, cancelPendingCommit, isSemanticMode]+ );++ const handleToggleSemanticMode = useCallback(+ (enabled: boolean) => {+ cancelPendingCommit();+ // Rendered before focus moves, so the field is announced under its+ // semantic name — a name that changes on an already-focused element is+ // not read out again.+ flushSync(() => actions.setSemanticSearchMode(enabled));++ if (!enabled) {+ return;+ }++ // The next keystrokes are what the toggle was for.+ inputRef.current?.focus();++ // The sparkle is offered without the model on purpose, so this click is+ // where a user learns what the feature needs: the hint under the field+ // stays while the mode does, the toast says what to do about it.+ if (indexAvailability?.state === 'model_missing') {+ notifications.add({+ kind: 'info',+ message: t('widgets.gallery.semanticSearchInstallModel', { model: indexAvailability.modelName ?? '' }),+ title: t('widgets.gallery.semanticSearchModelMissingTitle'),+ });+ }+ },+ [actions, cancelPendingCommit, indexAvailability, notifications, t]+ );++ const handleClearSearch = useCallback(() => {+ cancelPendingCommit();+ actions.clearSearch();+ }, [actions, cancelPendingCommit]);+ const handleClearSemantic = useCallback(() => actions.setSemanticImageQuery(null), [actions]);// In-app drags (dnd-kit) resolve through GalleryBoardDragMonitor; this hook// only registers the drop target and reports hover for the highlight.@@ -136,11 +229,24 @@ export const GalleryItemSearch = () => {// case still needs words — and it is positioned out of flow. As a sibling it// grew the field's row and knocked the wide header out of vertical centre.const invalidHint = useMemo(() => {+ if (isSemanticMode) {+ return null;+ }+const parse = parseDateTokens(gallery.searchTerm);const invalid = findInvalidDateToken(gallery.searchTerm, parse);return invalid ? t('widgets.gallery.dateFilterInvalid', { value: invalid.raw }) : null;- }, [gallery.searchTerm, t]);+ }, [gallery.searchTerm, isSemanticMode, t]);++ // The same out-of-flow slot explains a semantic field the server cannot+ // answer, before the first search fails.+ const semanticHint =+ isSemanticMode && indexAvailability?.state === 'model_missing'+ ? t('widgets.gallery.semanticSearchModelMissing', { model: indexAvailability.modelName ?? '' })+ : null;++ const hint = invalidHint ?? semanticHint;// The chips show which text is a filter, not what it resolved to, so the// resolved range stays available to assistive tech.@@ -169,28 +275,40 @@ export const GalleryItemSearch = () => {}}, [gallery.searchTerm, i18n.language, t]);+ // One name in both states — the pressed state says which — and the tooltip+ // names the action a click takes.+ const semanticToggle = useMemo(+ () =>+ showSemanticToggle ? (+ <ToggleIconButton+ checked={isSemanticMode}+ color={isSemanticMode ? 'fg.warning' : 'fg.muted'}+ icon={SparklesIcon}+ label={t('widgets.gallery.semanticSearchAriaLabel')}+ tooltip={isSemanticMode ? t('widgets.gallery.exitSemanticSearch') : t('widgets.gallery.searchSemantically')}+ variant="ghost"+ onCheckedChange={handleToggleSemanticMode}+ />+ ) : null,+ [handleToggleSemanticMode, isSemanticMode, showSemanticToggle, t]+ );+const endElement = useMemo(() => (<HStack flexShrink={0} gap="0">- {semanticQueryText ? (- <IconButton- aria-label={t('widgets.gallery.searchSemantically')}- color="fg.muted"+ {semanticToggle}+ {isSemanticMode || gallery.searchTerm ? (+ <CloseButton+ aria-label={isSemanticMode ? t('widgets.gallery.clearSemanticSearch') : t('common.clearSearch')}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} />+ onClick={handleClearSearch}+ />) : null}- <GallerySearchHelp />+ {/* The help documents metadata grammar, which a semantic description has none of. */}+ {isSemanticMode ? null : <GallerySearchHelp />}</HStack>),- [gallery.searchTerm, handleClearSearch, handleSemanticSearch, semanticQueryText, t]+ [gallery.searchTerm, handleClearSearch, isSemanticMode, semanticToggle, t]);return (@@ -206,24 +324,42 @@ export const GalleryItemSearch = () => {onDragOver={handleNativeDragOver}onDrop={handleNativeDrop}>- {gallery.semanticImageQuery ? (- <GallerySemanticChip reference={gallery.semanticImageQuery} onClear={handleClearSemantic} />+ {/* In semantic mode the field IS the text query; a chip stands for a+ reference the field cannot type (an image, a file, a cluster), and+ every path that sets one leaves semantic mode. A text chip is only a+ project saved before the mode existed. The toggle stays beside the+ chip: pressing it there trades the reference for a typed query. */}+ {!isSemanticMode && gallery.semanticImageQuery ? (+ <GallerySemanticChip+ reference={gallery.semanticImageQuery}+ toggle={semanticToggle}+ onClear={handleClearSemantic}+ />) : (<GallerySearchField- ariaLabel={t('widgets.gallery.searchImagesAriaLabel')}- describedById={invalidHint ? SEARCH_DATE_HINT_ID : undefined}+ ref={inputRef}+ ariaLabel={+ isSemanticMode ? t('widgets.gallery.semanticSearchAriaLabel') : t('widgets.gallery.searchImagesAriaLabel')+ }+ describedById={hint ? SEARCH_HINT_ID : undefined}endElement={endElement}isInvalid={invalidHint !== null}- placeholder={t('widgets.gallery.searchImagesPlaceholder')}- value={gallery.searchTerm}- onChange={actions.setSearchTerm}+ mode={isSemanticMode ? 'semantic' : 'metadata'}+ placeholder={+ isSemanticMode+ ? t('widgets.gallery.semanticSearchPlaceholder')+ : t('widgets.gallery.searchImagesPlaceholder')+ }+ value={isSemanticMode ? semanticText : gallery.searchTerm}+ onChange={handleChange}+ onKeyDown={handleKeyDown}/>)}- {invalidHint ? (+ {hint ? (<Text- color="fg.error"+ color={invalidHint ? 'fg.error' : 'fg.warning'}fontSize="2xs"- id={SEARCH_DATE_HINT_ID}+ id={SEARCH_HINT_ID}insetInlineStart="0"// Out of flow and inert: it must never shift the header row, nor// swallow clicks meant for the grid it now floats over.@@ -232,7 +368,7 @@ export const GalleryItemSearch = () => {role="status"top="100%">- {invalidHint}+ {hint}</Text>) : null}{appliedRange ? (@@ -249,26 +385,37 @@ export const GalleryItemSearch = () => {* reference — rendered in place of the search input. Clearing it restores* metadata search.*/-const GallerySemanticChip = ({ onClear, reference }: { onClear: () => void; reference: GallerySemanticReference }) => {+const GallerySemanticChip = ({+ onClear,+ reference,+ toggle,+}: {+ onClear: () => void;+ reference: GallerySemanticReference;+ toggle: ReactNode;+}) => {const { t } = useTranslation();const isText = reference.kind === 'text';const isCluster = reference.kind === 'cluster';const name = getSemanticReferenceName(reference) || t('widgets.gallery.semanticWebImage');- const clearButton = useMemo(+ const endElement = useMemo(() => (- <CloseButton- aria-label={- isText- ? t('widgets.gallery.clearSemanticSearch')- : isCluster- ? t('widgets.gallery.clearClusterSearch')- : t('widgets.gallery.clearImageSearch')- }- size="2xs"- onClick={onClear}- />+ <HStack flexShrink={0} gap="0">+ {toggle}+ <CloseButton+ aria-label={+ isText+ ? t('widgets.gallery.clearSemanticSearch')+ : isCluster+ ? t('widgets.gallery.clearClusterSearch')+ : t('widgets.gallery.clearImageSearch')+ }+ size="2xs"+ onClick={onClear}+ />+ </HStack>),- [isCluster, isText, onClear, t]+ [isCluster, isText, onClear, t, toggle]);const kindIcon = useMemo(() => (@@ -283,7 +430,7 @@ const GallerySemanticChip = ({ onClear, reference }: { onClear: () => void; refe);return (- <InputShell endElement={clearButton} startElement={kindIcon} title={getSemanticReferenceTitle(reference)}>+ <InputShell endElement={endElement} startElement={kindIcon} title={getSemanticReferenceTitle(reference)}><Text color="fg.muted" flex="1" fontSize="xs" minW="0" truncate>{isText? t('widgets.gallery.semanticTextSearch', { name })diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.browser.test.tsxindex 94eb8858ca..c2b121b28d 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.browser.test.tsx@@ -13,13 +13,14 @@ let root: Root | null = null;const onChange = vi.fn();-const renderField = async (value: string, isInvalid = false) => {+const renderField = async (value: string, isInvalid = false, mode: 'metadata' | 'semantic' = 'metadata') => {await act(() =>root?.render(<ChakraProvider value={system}><GallerySearchFieldariaLabel="Search gallery items"isInvalid={isInvalid}+ mode={mode}placeholder="Search items"value={value}onChange={onChange}@@ -95,6 +96,14 @@ describe('getGallerySearchSegments', () => {});describe('GallerySearchField', () => {+ it('draws no chips in semantic mode, where a token is just words', async () => {+ await renderField('sunset from:7d', false, 'semantic');++ expect(getChips()).toHaveLength(0);+ expect(getMirror().textContent).toBe('sunset from:7d');+ expect(getInput().closest('[data-mode]')?.getAttribute('data-mode')).toBe('semantic');+ });+it('renders a chip for the token and leaves the rest plain', async () => {await renderField('from:7d sunset');diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsxindex 7ac4191377..e9d463208d 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GallerySearchField.tsx@@ -3,7 +3,7 @@ import type { DateTokenParse } from '@platform/search/dateTokens';import { Box, Icon, Input } from '@chakra-ui/react';import { parseDateTokens } from '@platform/search/dateTokens';import { InputShell } from '@platform/ui/InputShell';-import { SearchIcon } from 'lucide-react';+import { SearchIcon, SparklesIcon } from 'lucide-react';import { useCallback, useMemo, useRef, type KeyboardEvent, type ReactNode, type Ref } from 'react';/** `key:value` runs the date grammar recognizes, matched against the raw value. */@@ -55,6 +55,7 @@ export const getGallerySearchSegments = (value: string, parse: DateTokenParse):const PLACEHOLDER_PROPS = { color: 'fg.subtle' } as const;const SEARCH_START_ELEMENT = <Icon as={SearchIcon} boxSize="3.5" color="fg.subtle" flexShrink={0} />;+const SEMANTIC_START_ELEMENT = <Icon as={SparklesIcon} boxSize="3.5" color="fg.warning" flexShrink={0} />;const MIRROR_CHIP_CSS = {borderRadius: 'sm',@@ -66,6 +67,10 @@ const MIRROR_CHIP_CSS = {* Search input that draws date tokens as chips. The mirror and the input share* one zero-padded cell, so they align by construction rather than by matching* padding; the input's own text is transparent and only its caret shows.+ *+ * In semantic mode the text is a free-form description, so no token is a chip,+ * and the frame is tinted so the mode reads at a glance — the tint holds+ * through hover and focus, which recolor only the border.*/export const GallerySearchField = ({ariaLabel,@@ -73,6 +78,7 @@ export const GallerySearchField = ({endElement,inputProps,isInvalid,+ mode = 'metadata',placeholder,ref,value,@@ -85,6 +91,7 @@ export const GallerySearchField = ({/** Listbox wiring (`aria-controls`, `aria-activedescendant`) for hosts that drive a list from the field. */inputProps?: Pick<React.ComponentProps<typeof Input>, 'aria-activedescendant' | 'aria-controls' | 'role'>;isInvalid?: boolean;+ mode?: 'metadata' | 'semantic';placeholder: string;ref?: Ref<HTMLInputElement>;value: string;@@ -92,7 +99,12 @@ export const GallerySearchField = ({onKeyDown?: (event: KeyboardEvent<HTMLInputElement>) => void;}) => {const mirrorRef = useRef<HTMLDivElement>(null);- const segments = useMemo(() => getGallerySearchSegments(value, parseDateTokens(value)), [value]);+ const isSemantic = mode === 'semantic';+ const segments = useMemo(+ () =>+ isSemantic ? [{ kind: 'text', text: value } as const] : getGallerySearchSegments(value, parseDateTokens(value)),+ [isSemantic, value]+ );const handleChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => onChange(event.currentTarget.value),@@ -111,9 +123,12 @@ export const GallerySearchField = ({return (<InputShellaria-invalid={isInvalid || undefined}+ bg={isSemantic ? 'bg.warning' : undefined}+ borderColor={isSemantic ? 'fg.warning' : undefined}+ data-mode={mode}endElement={endElement}position="relative"- startElement={SEARCH_START_ELEMENT}+ startElement={isSemantic ? SEMANTIC_START_ELEMENT : SEARCH_START_ELEMENT}>{/* Flex-centred: Chakra reads a scale number in `lineHeight` as aunitless multiplier, which drops the text out of the field. */}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxindex ab5a8650e1..16d8a9f1b5 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -64,6 +64,10 @@ export interface GalleryCommandsPort {setPageInfo(totalImages: number): void;setSearchTerm(searchTerm: string): void;setStarredOnly(starredOnly: boolean): void;+ setSemanticSearchMode(enabled: boolean): void;+ setSemanticSearchText(text: string): void;+ commitSemanticSearch(text: string): void;+ clearSearch(): void;setView(view: GalleryView): void;toggleItemSelection(item: GalleryItem, nextPrimaryItem: GalleryItem | null): void;updateSettings(settings: Partial<GallerySettings>): void;diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsxindex f4880df489..b5255d7b80 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx@@ -32,8 +32,16 @@ export interface GalleryActions {setSearchTerm: (searchTerm: string) => void;/** Restricts (or releases) the listing to starred items; resets the page like a search. */setStarredOnly: (starredOnly: boolean) => void;+ /** Clears the search field: its text, any ranking, and semantic mode. */+ clearSearch: () => void;+ /** Applies the semantic field's text as the ranking; a no-op once the field has moved on. */+ commitSemanticSearch: (text: string) => void;/** Sets (or clears) the image-similarity query shown as a chip in the search field. */setSemanticImageQuery: (reference: GallerySemanticReference | null) => void;+ /** Switches the search field between metadata and semantic search, keeping its text. */+ setSemanticSearchMode: (enabled: boolean) => void;+ /** The semantic field's live text, ahead of the debounced commit. */+ setSemanticSearchText: (text: string) => 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/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex cccfa8b4ee..399527df39 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -64,6 +64,8 @@ export interface GalleryStateView {selectedItemKeys: GalleryItemKey[];/** Active image-similarity query, rendered as a chip in place of the search text. */semanticImageQuery: GallerySemanticReference | null;+ /** The semantic field's text while the field is in semantic mode; null in metadata mode. */+ semanticSearchText: string | null;settings: GallerySettings;/** The listing is restricted to starred items. */starredOnly: boolean;@@ -81,6 +83,10 @@ export const getGalleryStarredOnly = (values: Record<string, unknown>): booleanexport const getGallerySemanticImageQuery = (values: Record<string, unknown>): GallerySemanticReference | null =>parseGallerySemanticReference(values.semanticImageQuery);+/** Semantic mode is the presence of its text: null means the field searches metadata. */+export const getGallerySemanticSearchText = (values: Record<string, unknown>): string | null =>+ typeof values.semanticSearchText === 'string' ? values.semanticSearchText : null;+/** The saved board choice as persisted, before any resolution against loaded boards. */export const getGalleryRawSelectedBoardId = (values: Record<string, unknown>): string | null =>typeof values.selectedBoardId === 'string' ? values.selectedBoardId : null;@@ -270,6 +276,7 @@ export const getGalleryStateView = (? [visibleSelectedItemKey, ...selectedItemKeys]: selectedItemKeys,semanticImageQuery,+ semanticSearchText: getGallerySemanticSearchText(values),settings,starredOnly,};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 2dd1d3e54c..e731712eb8 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@@ -161,6 +161,10 @@ const adapter: GalleryUiAdapter = {setPageInfo: noop,setSearchTerm: noop,setStarredOnly: noop,+ setSemanticSearchMode: noop,+ setSemanticSearchText: noop,+ commitSemanticSearch: noop,+ clearSearch: noop,setView: noop,toggleItemSelection: noop,updateSettings: noop,@@ -677,6 +681,7 @@ describe('setSemanticImageQuery', () => {galleryPage: 0,searchTerm: '',semanticImageQuery: { imageName: 'ref.png', kind: 'image' },+ semanticSearchText: null,});});@@ -684,6 +689,11 @@ describe('setSemanticImageQuery', () => {actionsRef.current?.setSemanticImageQuery(null);expect(patchGalleryValues).toHaveBeenCalledOnce();- expect(patchGalleryValues).toHaveBeenCalledWith({ galleryPage: 0, searchTerm: '', semanticImageQuery: null });+ expect(patchGalleryValues).toHaveBeenCalledWith({+ galleryPage: 0,+ searchTerm: '',+ semanticImageQuery: null,+ semanticSearchText: null,+ });});});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.tsindex e33ade2aa0..e96a3ba459 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts@@ -206,16 +206,28 @@ export const useGalleryActions = ({setCompareItem: gallery.setCompareItem,setSearchTerm: gallery.setSearchTerm,setStarredOnly: gallery.setStarredOnly,+ setSemanticSearchMode: gallery.setSemanticSearchMode,+ setSemanticSearchText: gallery.setSemanticSearchText,+ commitSemanticSearch: gallery.commitSemanticSearch,+ clearSearch: gallery.clearSearch,// 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.+ // A reference also ends semantic text mode: the chip replaces the+ // field, and the field must not come back holding text for a ranking+ // the chip's clear has just dismissed.// 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 }),+ widgets.patchGalleryValues({+ galleryPage: 0,+ searchTerm: '',+ semanticImageQuery: reference,+ semanticSearchText: null,+ }),setView: gallery.setView,toggleItemInSelection: gallery.toggleItemSelection,updateSettings: gallery.updateSettings,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsxindex f3be59b28f..dd26cc96f0 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.browser.test.tsx@@ -80,6 +80,10 @@ const adapter: GalleryUiAdapter = {setPageInfo: noop,setSearchTerm: noop,setStarredOnly: noop,+ setSemanticSearchMode: noop,+ setSemanticSearchText: noop,+ commitSemanticSearch: noop,+ clearSearch: noop,setView: noop,toggleItemSelection: noop,updateSettings: noop,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/revealGalleryItem.ts b/invokeai/frontend/webv2/src/workbench/image-actions/revealGalleryItem.tsindex e0f55464e0..f96db6382d 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/revealGalleryItem.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/revealGalleryItem.ts@@ -174,7 +174,9 @@ export const revealGalleryItem = (}const currentView: GalleryView = values.galleryView === 'assets' ? 'assets' : 'images';- const hasSearch = typeof values.searchTerm === 'string' && values.searchTerm !== '';+ const hasSearch =+ (typeof values.searchTerm === 'string' && values.searchTerm !== '') ||+ typeof values.semanticSearchText === 'string';// Filters would hide the listing the index was computed against// (the image may not match them), so the reveal clears them and sets@@ -187,6 +189,7 @@ export const revealGalleryItem = (commands.widgets.patchValues('gallery', {searchTerm: '',semanticImageQuery: null,+ semanticSearchText: null,starredOnly: wantsStarredOnly,});}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsxindex 6807e73462..0467e86176 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.browser.test.tsx@@ -421,6 +421,7 @@ describe('useMapSelection', () => {expect(mocks.patchValues).toHaveBeenCalledWith('gallery', {searchTerm: '',semanticImageQuery: null,+ semanticSearchText: null,starredOnly: false,});});@@ -442,10 +443,28 @@ describe('useMapSelection', () => {expect(mocks.patchValues).toHaveBeenCalledWith('gallery', {searchTerm: '',semanticImageQuery: null,+ semanticSearchText: null,starredOnly: true,});});+ it('leaves a semantic field, even an empty one, before revealing', async () => {+ // Semantic mode is a listing of its own even with nothing typed yet:+ // the reveal targets the board listing, so the field returns to it.+ mocks.galleryValues = { searchTerm: '', semanticImageQuery: null, semanticSearchText: '' };+ mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'a.png' });+ await mount();++ await flush(() => handle.click?.({ kind: 'image', name: 'a.png' }));++ expect(mocks.patchValues).toHaveBeenCalledWith('gallery', {+ searchTerm: '',+ semanticImageQuery: null,+ semanticSearchText: null,+ starredOnly: false,+ });+ });+it('leaves the filters alone when none are active', async () => {mocks.resolve.mockResolvedValue({ boardId: 'board-a', category: 'general', kind: 'image', name: 'a.png' });await mount();@@ -532,6 +551,7 @@ describe('useMapSelection', () => {galleryPage: 0,searchTerm: '',semanticImageQuery: { clusterId: 'cluster-key-1', kind: 'cluster', label: 'beaches' },+ semanticSearchText: null,});expect(mocks.selectItem).toHaveBeenCalledTimes(1);expect(mocks.selectItem.mock.calls[0]?.[0]).toEqual({diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.tsindex 0bda170439..164170e3cd 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/useSelectMapImage.ts@@ -73,6 +73,7 @@ export const useMapSelection = (): MapSelectionActions => {galleryPage: 0,searchTerm: '',semanticImageQuery: { clusterId, kind: 'cluster', label },+ semanticSearchText: null,});// The clicked item is the proximity ordering's first entry, so it// is selected at the top of the cluster view; Preview follows. Thediff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex d9ad7f96bb..865ada87b2 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -4741,6 +4741,163 @@ describe('workbenchReducer Phase 5 generation flow', () => {);expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImage).toEqual(image);});+ describe('gallery semantic search mode', () => {+ const galleryValues = (state: WorkbenchState) => getProjectWidgetValues(getActiveProject(state), 'gallery');++ it('entering carries the text across and ranks it at once; leaving carries it back', () => {+ // The sparkle changes what the words mean, not whether they are there.+ // A click is deliberate, so entering applies the ranking immediately+ // rather than waiting for a typing pause; leaving drops the ranking+ // because metadata search has its own listing.+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { searchTerm: ' sunset ', type: 'setGallerySearchTerm' });+ state = workbenchReducer(state, { page: 3, type: 'setGalleryPage' });+ state = workbenchReducer(state, { enabled: true, type: 'setGallerySemanticSearchMode' });++ expect(galleryValues(state)).toMatchObject({+ galleryPage: 0,+ searchTerm: '',+ semanticImageQuery: { kind: 'text', query: 'sunset' },+ semanticSearchText: ' sunset ',+ });++ state = workbenchReducer(state, { page: 2, type: 'setGalleryPage' });+ state = workbenchReducer(state, { enabled: false, type: 'setGallerySemanticSearchMode' });++ expect(galleryValues(state)).toMatchObject({+ galleryPage: 0,+ searchTerm: ' sunset ',+ semanticImageQuery: null,+ semanticSearchText: null,+ });+ });++ it('entering with an empty field ranks nothing, and re-entering changes nothing', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { enabled: true, type: 'setGallerySemanticSearchMode' });++ expect(galleryValues(state)).toMatchObject({ semanticImageQuery: null, semanticSearchText: '' });+ expect(workbenchReducer(state, { enabled: true, type: 'setGallerySemanticSearchMode' })).toBe(state);++ const initial = createInitialWorkbenchState();++ expect(workbenchReducer(initial, { enabled: false, type: 'setGallerySemanticSearchMode' })).toBe(initial);+ });++ it('commits only the text the field still holds', () => {+ // Commits arrive on a timer. One scheduled against text that has since+ // been edited, or a field that has since been cleared, must not apply.+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { enabled: true, type: 'setGallerySemanticSearchMode' });+ state = workbenchReducer(state, { text: 'sun', type: 'setGallerySemanticSearchText' });+ state = workbenchReducer(state, { page: 2, type: 'setGalleryPage' });++ expect(galleryValues(state).semanticSearchText).toBe('sun');+ expect(workbenchReducer(state, { text: 'su', type: 'commitGallerySemanticSearch' })).toBe(state);++ state = workbenchReducer(state, { text: 'sun', type: 'commitGallerySemanticSearch' });++ expect(galleryValues(state)).toMatchObject({+ galleryPage: 0,+ semanticImageQuery: { kind: 'text', query: 'sun' },+ semanticSearchText: 'sun',+ });++ // Blank text is no ranking; a whitespace edit is not a new ranking and+ // so leaves the page where the user has paged to.+ state = workbenchReducer(state, { page: 4, type: 'setGalleryPage' });+ state = workbenchReducer(state, { text: 'sun ', type: 'setGallerySemanticSearchText' });++ const paged = state;++ state = workbenchReducer(state, { text: 'sun ', type: 'commitGallerySemanticSearch' });++ expect(state).toBe(paged);++ state = workbenchReducer(state, { text: ' ', type: 'setGallerySemanticSearchText' });+ state = workbenchReducer(state, { text: ' ', type: 'commitGallerySemanticSearch' });++ expect(galleryValues(state)).toMatchObject({+ galleryPage: 0,+ semanticImageQuery: null,+ semanticSearchText: ' ',+ });+ });++ it('ignores text edits and late commits once semantic mode is left', () => {+ let state = createInitialWorkbenchState();++ expect(workbenchReducer(state, { text: 'sun', type: 'setGallerySemanticSearchText' })).toBe(state);++ state = workbenchReducer(state, { enabled: true, type: 'setGallerySemanticSearchMode' });+ state = workbenchReducer(state, { text: 'sun', type: 'setGallerySemanticSearchText' });+ state = workbenchReducer(state, { enabled: false, type: 'setGallerySemanticSearchMode' });++ expect(workbenchReducer(state, { text: 'sun', type: 'commitGallerySemanticSearch' })).toBe(state);+ expect(galleryValues(state)).toMatchObject({+ searchTerm: 'sun',+ semanticImageQuery: null,+ semanticSearchText: null,+ });+ });++ it('clears text, ranking and mode together; clearing an empty field changes nothing', () => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, { searchTerm: 'sunset', type: 'setGallerySearchTerm' });+ state = workbenchReducer(state, { enabled: true, type: 'setGallerySemanticSearchMode' });+ state = workbenchReducer(state, { page: 2, type: 'setGalleryPage' });+ state = workbenchReducer(state, { type: 'clearGallerySearch' });++ expect(galleryValues(state)).toMatchObject({+ galleryPage: 0,+ searchTerm: '',+ semanticImageQuery: null,+ semanticSearchText: null,+ });+ expect(workbenchReducer(state, { type: 'clearGallerySearch' })).toBe(state);++ state = workbenchReducer(state, { searchTerm: 'plain', type: 'setGallerySearchTerm' });+ state = workbenchReducer(state, { type: 'clearGallerySearch' });++ 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', () => {+ 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' });++ expect(galleryValues(state).semanticSearchText).toBe('beach');++ state = workbenchReducer(state, { galleryView: 'assets', type: 'setGalleryView' });++ expect(galleryValues(state)).toMatchObject({ semanticImageQuery: null, semanticSearchText: null });+ });+ });});describe('workbench account and project settings', () => {diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex ae43e8dcf6..e958d4ce3e 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -55,7 +55,10 @@ import {getPersistedSelectedGalleryItemKeys,stripInfiniteWindowAnchor,stripUnresolvableGallerySearch,+ gallerySemanticReferenceKey,getGallerySettings,+ parseGallerySemanticReference,+ toGallerySemanticTextReference,getSelectedGalleryItemFromValues,legacyGeneratedImageToGalleryItem,normalizeGalleryImage,@@ -369,6 +372,14 @@ type WorkbenchReducerAction =| { type: 'clearGallerySelection'; projectId?: string }| { type: 'setGalleryView'; galleryView: 'images' | 'assets'; projectId?: string }| { type: 'setGallerySearchTerm'; searchTerm: string; projectId?: string }+ /** Toggles the search field between metadata search and semantic search, carrying its text across. */+ | { type: 'setGallerySemanticSearchMode'; enabled: boolean; projectId?: string }+ /** The semantic field's live text; the ranking follows only on commit. */+ | { type: 'setGallerySemanticSearchText'; text: string; projectId?: string }+ /** Applies the semantic text as the ranking, if it is still what the field holds. */+ | { type: 'commitGallerySemanticSearch'; text: string; projectId?: string }+ /** The field's clear button: drops the text, the ranking, and semantic mode together. */+ | { type: 'clearGallerySearch'; projectId?: string }| { type: 'setGalleryStarredOnly'; starredOnly: boolean; projectId?: string }| { type: 'updateGallerySettings'; settings: Partial<GallerySettings>; projectId?: string }| { type: 'setGalleryPage'; page: number; projectId?: string }@@ -2828,7 +2839,9 @@ const reconcileDeletedGalleryBoard = (...values,// Same rule as `selectGalleryBoard`: the view is moving to another// board, so a ranking shown against the old one goes with it.- ...(selectedBoardWasDeleted ? { galleryPage: 0, selectedBoardId: 'none', semanticImageQuery: null } : {}),+ ...(selectedBoardWasDeleted+ ? { galleryPage: 0, selectedBoardId: 'none', semanticImageQuery: null, semanticSearchText: null }+ : {}),...(projectBoardWasDeleted ? { projectBoardId: null } : {}),};});@@ -4647,7 +4660,8 @@ export const __workbenchReducerInternal = (// so it is not a view OF any board: moving to one asks for that// board's listing, and leaving the ranking up would answer with the// same results under a new board name. Dismissed exactly as the- // chip's own clear does it — the query alone. The positions on the+ // chip's own clear does it — the query alone — and the semantic+ // field leaves with its ranking, text and all. The positions on the// selection are NOT rewritten here: a selection made before the// search carries a real board page that the search never touched,// and zeroing it would cost Preview the cursor it still has.@@ -4656,7 +4670,7 @@ export const __workbenchReducerInternal = (// a change of view, and a text or image reference survives a reload,// so treating that click as a dismissal would erase persisted state// (and autosave the loss) on what reads as a no-op.- ...(values.selectedBoardId !== action.boardId ? { semanticImageQuery: null } : {}),+ ...(values.selectedBoardId !== action.boardId ? { semanticImageQuery: null, semanticSearchText: null } : {}),}),action.projectId);@@ -4683,7 +4697,7 @@ export const __workbenchReducerInternal = (// `galleryView` reads as Images, so re-clicking the tab already// shown must stay the no-op it is today....((values.galleryView === 'assets' ? 'assets' : 'images') !== action.galleryView- ? { semanticImageQuery: null }+ ? { semanticImageQuery: null, semanticSearchText: null }: {}),}),action.projectId@@ -4711,6 +4725,90 @@ export const __workbenchReducerInternal = (action.projectId);}+ case 'setGallerySemanticSearchMode': {+ return updateGalleryValues(+ state,+ (values) => {+ const semanticText = typeof values.semanticSearchText === 'string' ? values.semanticSearchText : null;++ if (action.enabled === (semanticText !== null)) {+ return values;+ }++ // The text moves between the two interpretations rather than being+ // lost: the sparkle only changes what the words mean. Entering+ // applies them at once — a click is a deliberate act, not a+ // keystroke to debounce — while leaving drops the ranking, since+ // metadata search has its own listing.+ if (action.enabled) {+ const text = typeof values.searchTerm === 'string' ? values.searchTerm : '';++ return {+ ...values,+ galleryPage: 0,+ searchTerm: '',+ semanticImageQuery: toGallerySemanticTextReference(text),+ semanticSearchText: text,+ };+ }++ return {+ ...values,+ galleryPage: 0,+ searchTerm: semanticText,+ semanticImageQuery: null,+ semanticSearchText: null,+ };+ },+ action.projectId+ );+ }+ case 'setGallerySemanticSearchText': {+ return updateGalleryValues(+ state,+ (values) =>+ typeof values.semanticSearchText === 'string' ? { ...values, semanticSearchText: action.text } : values,+ action.projectId+ );+ }+ case 'commitGallerySemanticSearch': {+ return updateGalleryValues(+ state,+ (values) => {+ // A commit arrives on a timer, after whatever it was scheduled+ // against may have gone: the field emptied, the mode left, the board+ // moved. Applying only what the field still holds makes every late+ // timer harmless without the field having to track them.+ if (values.semanticSearchText !== action.text) {+ return values;+ }++ const reference = toGallerySemanticTextReference(action.text);++ if (+ gallerySemanticReferenceKey(reference) ===+ gallerySemanticReferenceKey(parseGallerySemanticReference(values.semanticImageQuery))+ ) {+ return values;+ }++ return { ...values, galleryPage: 0, semanticImageQuery: reference };+ },+ action.projectId+ );+ }+ case 'clearGallerySearch': {+ return updateGalleryValues(+ state,+ (values) =>+ values.searchTerm === '' &&+ (values.semanticImageQuery === null || values.semanticImageQuery === undefined) &&+ (values.semanticSearchText === null || values.semanticSearchText === undefined)+ ? values+ : { ...values, galleryPage: 0, searchTerm: '', semanticImageQuery: null, semanticSearchText: null },+ action.projectId+ );+ }case 'updateGallerySettings': {const resetsQuery = action.settings.imageOrderDir !== undefined || action.settings.paginationMode !== undefined;diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex 9dc4770d9d..ff2f4b2f19 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -213,6 +213,19 @@ const createCommands = (projectId,starredOnly,})),+ setSemanticSearchMode: command('setGallerySemanticSearchMode', (enabled: boolean, projectId?: string) => ({+ enabled,+ projectId,+ })),+ setSemanticSearchText: command('setGallerySemanticSearchText', (text: string, projectId?: string) => ({+ projectId,+ text,+ })),+ commitSemanticSearch: command('commitGallerySemanticSearch', (text: string, projectId?: string) => ({+ projectId,+ text,+ })),+ clearSearch: command('clearGallerySearch', (projectId?: string) => ({ projectId })),setView: command('setGalleryView',(galleryView: ActionPayload<'setGalleryView'>['galleryView'], projectId?: string) => ({