Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(webv2): image map vocabulary editor in workbench settings

Lincoln Stein5bf60e712d3e
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index db241b746a..6b3b71026c 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1409,7 +1409,27 @@
"project": "Project",
"queue": "Queue",
"workflow": "Workflow",
- "workspace": "Workspace"
+ "workspace": "Workspace",
+ "imageMap": "Image Map"
+ },
+ "imageMapVocabulary": {
+ "title": "Cluster Label Vocabulary",
+ "description": "Supplementary terms the image map can use when labeling clusters, alongside its built-in vocabulary. This is a server-wide list.",
+ "addLabel": "Add terms",
+ "adminOnly": "Only an administrator can change the vocabulary.",
+ "addPlaceholder": "Add terms (comma or newline separated)",
+ "addHelp": "Terms are lowercased and applied the next time labels are computed. Paste a comma- or newline-separated list to add several at once.",
+ "alreadyInList": "Every entered term is already in the list.",
+ "termTooLong": "Terms must be {{max}} characters or fewer.",
+ "tooManyTerms": "The list is limited to {{max}} terms.",
+ "removeTerm": "Remove {{term}}",
+ "noTermsYet": "No supplementary terms yet. The built-in vocabulary is still used.",
+ "count": "{{count}} of {{max}} supplementary terms",
+ "rebuilding": "Updating cluster labels with the new vocabulary…",
+ "buildFailed": "The vocabulary could not be prepared: {{message}}",
+ "indexOff": "The image index is not running. Terms are saved and will apply when it is next enabled.",
+ "saveFailed": "Could not save the vocabulary.",
+ "loadFailed": "Could not load the vocabulary."
}
},
"shell": {
diff --git a/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts b/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts
index f97363d1d4..8c5a3c07b7 100644
--- a/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts
+++ b/invokeai/frontend/webv2/src/features/identity/capabilities.test.ts
@@ -19,6 +19,7 @@ describe('Identity route capabilities', () => {
it.each(['unknown', 'unavailable'] as const)('grants nothing while auth mode is %s', (phase) => {
expect(getCapabilities(session({ multiuserEnabled: false, phase }))).toEqual({
canManageAppConfig: false,
+ canManageImageMapVocabulary: false,
canManageModels: false,
canManageNodes: false,
canManagePromptTemplates: false,
@@ -29,6 +30,7 @@ describe('Identity route capabilities', () => {
it('allows all local management in single-user mode', () => {
expect(getCapabilities(session({ multiuserEnabled: false }))).toEqual({
canManageAppConfig: true,
+ canManageImageMapVocabulary: true,
canManageModels: true,
canManageNodes: true,
canManagePromptTemplates: true,
@@ -49,6 +51,7 @@ describe('Identity route capabilities', () => {
expect(getCapabilities(session({ user: { ...baseUser, is_admin: false } }))).toEqual({
canManageAppConfig: false,
+ canManageImageMapVocabulary: false,
canManageModels: false,
canManageNodes: false,
canManagePromptTemplates: false,
@@ -56,6 +59,7 @@ describe('Identity route capabilities', () => {
});
expect(getCapabilities(session({ user: { ...baseUser, is_admin: true } }))).toEqual({
canManageAppConfig: true,
+ canManageImageMapVocabulary: true,
canManageModels: true,
canManageNodes: true,
canManagePromptTemplates: true,
diff --git a/invokeai/frontend/webv2/src/features/identity/capabilities.ts b/invokeai/frontend/webv2/src/features/identity/capabilities.ts
index 400da06856..dd48493e72 100644
--- a/invokeai/frontend/webv2/src/features/identity/capabilities.ts
+++ b/invokeai/frontend/webv2/src/features/identity/capabilities.ts
@@ -3,6 +3,8 @@ import { useAuthSession, type AuthSession } from './session';
export interface Capabilities {
/** Server-wide runtime config (e.g. which GPUs generate); `PATCH /app/runtime_config` is admin-only. */
canManageAppConfig: boolean;
+ /** The image map's supplementary cluster-label vocabulary; the PUT route is admin-only. */
+ canManageImageMapVocabulary: boolean;
canManageModels: boolean;
canManageNodes: boolean;
/** Bulk import/export of prompt templates; the routes are admin-only. */
@@ -14,6 +16,7 @@ export const getCapabilities = (session: AuthSession): Capabilities => {
if (session.phase !== 'ready') {
return {
canManageAppConfig: false,
+ canManageImageMapVocabulary: false,
canManageModels: false,
canManageNodes: false,
canManagePromptTemplates: false,
@@ -26,6 +29,7 @@ export const getCapabilities = (session: AuthSession): Capabilities => {
return {
canManageAppConfig: isAdmin,
+ canManageImageMapVocabulary: isAdmin,
canManageModels: isAdmin,
canManageNodes: isAdmin,
// Matches the routers' `AdminUserOrDefault`: everyone qualifies in
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
index 5bdb97f730..39633e64a0 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
@@ -227,6 +227,21 @@ const refreshClusterLabels = (data: ImageMapPoints): void => {
});
};
+/**
+ * Re-fetch labels for the currently loaded points. For callers outside the
+ * points-refresh flow whose action changes what the labels *say* without
+ * moving a single point — today that is a supplementary-vocabulary edit, once
+ * the server reports its embedding rebuild finished. A no-op while labels are
+ * toggled off or no points are loaded.
+ */
+export const refetchClusterLabels = (): void => {
+ const { data } = imageMapStore.getSnapshot();
+
+ if (data) {
+ refreshClusterLabels(data);
+ }
+};
+
/**
* Fold one status report into the snapshot.
*
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.ts b/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.ts
new file mode 100644
index 0000000000..b7236cfe92
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/image-map/vocabulary.ts
@@ -0,0 +1,80 @@
+/**
+ * The supplementary cluster-labeling vocabulary: a server-wide term list that
+ * admins maintain and the backend merges with its bundled vocabulary when it
+ * builds the label embeddings.
+ *
+ * Reads are open to every user; the PUT is admin-only (the router's
+ * `AdminUserOrDefault`). The list is replaced whole on save — the editor
+ * always holds the full list, and replace semantics keep the API idempotent.
+ */
+
+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
+import { apiFetchJson } from '@platform/transport/http';
+import { queryOptions } from '@tanstack/react-query';
+
+/** Mirrors the backend's VocabBuildState literal. */
+export type ImageMapVocabState = 'unavailable' | 'idle' | 'building' | 'ready' | 'error';
+
+export interface ImageMapVocab {
+ /** The stored terms, normalized and sorted alphabetically by the server. */
+ terms: string[];
+ /** The label-embedding build's state; 'building' after a save until the worker rebuilds. */
+ state: ImageMapVocabState;
+ /** Why the last embedding build failed; only set when state is 'error'. */
+ error: string | null;
+ maxTerms: number;
+ maxTermLength: number;
+}
+
+interface BackendImageMapVocabResponse {
+ terms: string[];
+ state: ImageMapVocabState;
+ error?: string | null;
+ max_terms: number;
+ max_term_length: number;
+}
+
+const mapVocab = (body: BackendImageMapVocabResponse): ImageMapVocab => ({
+ error: body.error ?? null,
+ maxTerms: body.max_terms,
+ maxTermLength: body.max_term_length,
+ state: body.state,
+ terms: body.terms,
+});
+
+export const imageMapVocabKeys = {
+ all: ['image-map', 'vocab'] as const,
+};
+
+export const imageMapVocabQueryOptions = () =>
+ (() => {
+ const owner = captureAccountScope();
+
+ return queryOptions({
+ queryFn: async ({ signal }): Promise<ImageMapVocab> => {
+ const requestSignal = AbortSignal.any([signal, owner.signal]);
+ const body = await apiFetchJson<BackendImageMapVocabResponse>('/api/v1/image_map/vocab', {
+ signal: requestSignal,
+ });
+
+ assertAccountScopeCurrent(owner);
+ return mapVocab(body);
+ },
+ queryKey: imageMapVocabKeys.all,
+ staleTime: 5_000,
+ });
+ })();
+
+/**
+ * Replace the whole term list. The server normalizes (lowercase, collapsed
+ * whitespace), dedupes, and rejects over-limit input with a 422 whose detail
+ * names the offending term; the response carries the stored list.
+ */
+export const updateImageMapVocab = async (terms: string[]): Promise<ImageMapVocab> => {
+ const body = await apiFetchJson<BackendImageMapVocabResponse>('/api/v1/image_map/vocab', {
+ body: JSON.stringify({ terms }),
+ method: 'PUT',
+ });
+
+ return mapVocab(body);
+};
diff --git a/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.browser.test.tsx
new file mode 100644
index 0000000000..69a3648db5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.browser.test.tsx
@@ -0,0 +1,213 @@
+import type { ImageMapVocab } from '@workbench/image-map/vocabulary';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+const mocks = vi.hoisted(() => ({
+ canManage: true,
+ refetchClusterLabels: vi.fn(),
+ updateImageMapVocab: vi.fn((_terms: string[]) => Promise.resolve(null as unknown as ImageMapVocab)),
+ vocab: null as ImageMapVocab | null,
+}));
+
+vi.mock('@features/identity', () => ({
+ useCapabilities: () => ({ canManageImageMapVocabulary: mocks.canManage }),
+}));
+
+vi.mock('@workbench/image-map/imageMapStore', () => ({
+ refetchClusterLabels: () => mocks.refetchClusterLabels(),
+}));
+
+vi.mock('@workbench/image-map/vocabulary', () => ({
+ imageMapVocabKeys: { all: ['image-map', 'vocab'] },
+ imageMapVocabQueryOptions: () => ({
+ queryFn: () => Promise.resolve(mocks.vocab),
+ queryKey: ['image-map', 'vocab'],
+ staleTime: Infinity,
+ }),
+ updateImageMapVocab: (terms: string[]) => mocks.updateImageMapVocab(terms),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) =>
+ ({
+ 'common.add': 'Add',
+ 'common.retry': 'Retry',
+ 'settings.imageMapVocabulary.addHelp': 'Terms are lowercased and applied the next time labels are computed.',
+ 'settings.imageMapVocabulary.addLabel': 'Add terms',
+ 'settings.imageMapVocabulary.addPlaceholder': 'Add terms (comma or newline separated)',
+ 'settings.imageMapVocabulary.adminOnly': 'Only an administrator can change the vocabulary.',
+ 'settings.imageMapVocabulary.alreadyInList': 'Every entered term is already in the list.',
+ 'settings.imageMapVocabulary.buildFailed': `The vocabulary could not be prepared: ${String(options?.message)}`,
+ 'settings.imageMapVocabulary.count': `${String(options?.count)} of ${String(options?.max)} supplementary terms`,
+ 'settings.imageMapVocabulary.indexOff': 'The image index is not running.',
+ 'settings.imageMapVocabulary.loadFailed': 'Could not load the vocabulary.',
+ 'settings.imageMapVocabulary.noTermsYet': 'No supplementary terms yet.',
+ 'settings.imageMapVocabulary.rebuilding': 'Updating cluster labels with the new vocabulary…',
+ 'settings.imageMapVocabulary.removeTerm': `Remove ${String(options?.term)}`,
+ 'settings.imageMapVocabulary.saveFailed': 'Could not save the vocabulary.',
+ 'settings.imageMapVocabulary.termTooLong': `Terms must be ${String(options?.max)} characters or fewer.`,
+ 'settings.imageMapVocabulary.tooManyTerms': `The list is limited to ${String(options?.max)} terms.`,
+ })[key] ?? key,
+ }),
+}));
+
+import { ImageMapVocabularySettings } from './ImageMapVocabularySettings';
+
+const BASE_VOCAB: ImageMapVocab = {
+ error: null,
+ maxTerms: 500,
+ maxTermLength: 64,
+ state: 'ready',
+ terms: [],
+};
+
+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 flushQueries = async (): Promise<void> => {
+ // The query resolves in a microtask; let effects and state settle.
+ await act(async () => {
+ await Promise.resolve();
+ });
+};
+
+const render = async (vocab: Partial<ImageMapVocab>): Promise<void> => {
+ mocks.vocab = { ...BASE_VOCAB, ...vocab };
+
+ await act(() => {
+ root?.render(
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient!}>
+ <ImageMapVocabularySettings />
+ </QueryClientProvider>
+ </ChakraProvider>
+ );
+ });
+ await flushQueries();
+};
+
+const input = (): HTMLInputElement | null =>
+ host!.querySelector<HTMLInputElement>('input[type="text"], input:not([type])');
+
+const chipCloseTriggers = (): HTMLElement[] =>
+ Array.from(host!.querySelectorAll<HTMLElement>('[aria-label^="Remove "]'));
+
+beforeEach(() => {
+ mocks.canManage = true;
+ mocks.refetchClusterLabels.mockClear();
+ mocks.updateImageMapVocab.mockClear();
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ queryClient?.clear();
+ queryClient = null;
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('ImageMapVocabularySettings', () => {
+ it('lists the stored terms as chips with the count line', async () => {
+ await render({ terms: ['aardvark', 'zebra'] });
+
+ expect(host?.textContent).toContain('aardvark');
+ expect(host?.textContent).toContain('zebra');
+ expect(host?.textContent).toContain('2 of 500 supplementary terms');
+ });
+
+ it('splits a pasted list, normalizes it, and saves the merged terms', async () => {
+ mocks.updateImageMapVocab.mockImplementation((terms: string[]) =>
+ Promise.resolve({ ...BASE_VOCAB, state: 'building' as const, terms })
+ );
+ await render({ terms: ['zebra'] });
+
+ await userEvent.fill(input()!, ' Golden Retriever, OKAPI, zebra');
+ await userEvent.keyboard('{Enter}');
+ await flushQueries();
+
+ // "zebra" is already stored and drops out; the rest arrive normalized.
+ expect(mocks.updateImageMapVocab).toHaveBeenCalledWith(['zebra', 'golden retriever', 'okapi']);
+ // The draft clears only after a successful save.
+ expect(input()?.value).toBe('');
+ // The save's response reports the background rebuild.
+ expect(host?.textContent).toContain('Updating cluster labels with the new vocabulary…');
+ });
+
+ it('refuses a draft that adds nothing new without calling the server', async () => {
+ await render({ terms: ['zebra'] });
+
+ await userEvent.fill(input()!, 'ZEBRA');
+ await userEvent.keyboard('{Enter}');
+ await flushQueries();
+
+ expect(mocks.updateImageMapVocab).not.toHaveBeenCalled();
+ expect(host?.textContent).toContain('Every entered term is already in the list.');
+ expect(input()?.value).toBe('ZEBRA');
+ });
+
+ it('refuses an overlong term locally', async () => {
+ await render({ maxTermLength: 8, terms: [] });
+
+ await userEvent.fill(input()!, 'a far too long term');
+ await userEvent.keyboard('{Enter}');
+ await flushQueries();
+
+ expect(mocks.updateImageMapVocab).not.toHaveBeenCalled();
+ expect(host?.textContent).toContain('Terms must be 8 characters or fewer.');
+ });
+
+ it('removes a chip by saving the list without it', async () => {
+ mocks.updateImageMapVocab.mockImplementation((terms: string[]) =>
+ Promise.resolve({ ...BASE_VOCAB, state: 'building' as const, terms })
+ );
+ await render({ terms: ['aardvark', 'zebra'] });
+
+ await userEvent.click(chipCloseTriggers()[0]!);
+ await flushQueries();
+
+ expect(mocks.updateImageMapVocab).toHaveBeenCalledWith(['zebra']);
+ });
+
+ it('shows a read-only list to a non-admin', async () => {
+ mocks.canManage = false;
+ await render({ terms: ['zebra'] });
+
+ expect(host?.textContent).toContain('zebra');
+ expect(host?.textContent).toContain('Only an administrator can change the vocabulary.');
+ expect(input()).toBeNull();
+ expect(chipCloseTriggers()).toHaveLength(0);
+ });
+
+ it('re-fetches any open map labels when the rebuild lands', async () => {
+ await render({ state: 'building', terms: ['zebra'] });
+
+ expect(mocks.refetchClusterLabels).not.toHaveBeenCalled();
+
+ await act(async () => {
+ queryClient!.setQueryData(['image-map', 'vocab'], { ...BASE_VOCAB, state: 'ready', terms: ['zebra'] });
+ await Promise.resolve();
+ });
+
+ expect(mocks.refetchClusterLabels).toHaveBeenCalledTimes(1);
+ });
+
+ it('surfaces a failed embedding build with its message', async () => {
+ await render({ error: 'no text encoder installed', state: 'error' });
+
+ expect(host?.textContent).toContain('The vocabulary could not be prepared: no text encoder installed');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx
new file mode 100644
index 0000000000..6b8a6d74c2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/settings/ImageMapVocabularySettings.tsx
@@ -0,0 +1,267 @@
+/* eslint-disable react-perf/jsx-no-new-function-as-prop */
+import type { ImageMapVocab } from '@workbench/image-map/vocabulary';
+
+import { HStack, Icon, Input, Spinner, Stack, Tag, Text, Wrap } from '@chakra-ui/react';
+import { useCapabilities } from '@features/identity';
+import { useScopedAction } from '@platform/react/useScopedAction';
+import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import { getApiErrorMessage } from '@platform/transport/http';
+import { Button, Field } from '@platform/ui';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { refetchClusterLabels } from '@workbench/image-map/imageMapStore';
+import { imageMapVocabKeys, imageMapVocabQueryOptions, updateImageMapVocab } from '@workbench/image-map/vocabulary';
+import { PlusIcon } from 'lucide-react';
+import { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+/**
+ * Normalize one draft entry the way the server will, so the chips a save adds
+ * are exactly the chips that come back. Splitting on commas and newlines makes
+ * a pasted list import in one keystroke.
+ */
+const parseDraft = (draft: string): string[] => {
+ const seen = new Set<string>();
+ const terms: string[] = [];
+
+ for (const entry of draft.split(/[\n,]/)) {
+ const term = entry.split(/\s+/).filter(Boolean).join(' ').toLowerCase();
+
+ if (term.length === 0 || seen.has(term)) {
+ continue;
+ }
+
+ seen.add(term);
+ terms.push(term);
+ }
+
+ return terms;
+};
+
+/**
+ * Editor for the supplementary cluster-label vocabulary. Each add/remove
+ * persists immediately (the whole list is replaced server-side); after a save
+ * the server rebuilds the label embeddings in the background, so the query
+ * polls while that runs and re-fetches any open map's labels when it lands.
+ */
+export const ImageMapVocabularySettings = () => {
+ const { t } = useTranslation();
+ const { canManageImageMapVocabulary } = useCapabilities();
+ const queryClient = useQueryClient();
+ const query = useQuery({
+ ...imageMapVocabQueryOptions(),
+ refetchInterval: (current) => (current.state.data?.state === 'building' ? 2_000 : false),
+ });
+ const [draft, setDraft] = useState('');
+ const [inputError, setInputError] = useState<string | null>(null);
+ const [saveError, setSaveError] = useState<string | null>(null);
+ const { isBusy: isSaving, run } = useScopedAction();
+
+ // A vocabulary edit changes what the labels say without moving a single
+ // point, so nothing in the map's own flow would re-fetch them: do it here,
+ // on the rebuild's building -> ready edge.
+ const buildState = query.data?.state;
+ const previousBuildState = useRef(buildState);
+
+ useEffect(() => {
+ if (previousBuildState.current === 'building' && buildState === 'ready') {
+ refetchClusterLabels();
+ }
+
+ previousBuildState.current = buildState;
+ }, [buildState]);
+
+ const persist = (nextTerms: string[]): Promise<boolean> => {
+ setSaveError(null);
+
+ return run(
+ async (owner) => {
+ const updated = await updateImageMapVocab(nextTerms);
+
+ assertAccountScopeCurrent(owner);
+ queryClient.setQueryData(imageMapVocabKeys.all, updated);
+ },
+ (_message, error) => {
+ setSaveError(getApiErrorMessage(error, t('settings.imageMapVocabulary.saveFailed')));
+ }
+ );
+ };
+
+ const addTerms = async (vocab: ImageMapVocab) => {
+ const candidates = parseDraft(draft);
+
+ if (candidates.length === 0) {
+ return;
+ }
+
+ const overlong = candidates.find((term) => term.length > vocab.maxTermLength);
+
+ if (overlong) {
+ setInputError(t('settings.imageMapVocabulary.termTooLong', { max: vocab.maxTermLength }));
+ return;
+ }
+
+ const existing = new Set(vocab.terms);
+ const fresh = candidates.filter((term) => !existing.has(term));
+
+ if (fresh.length === 0) {
+ setInputError(t('settings.imageMapVocabulary.alreadyInList'));
+ return;
+ }
+
+ if (vocab.terms.length + fresh.length > vocab.maxTerms) {
+ setInputError(t('settings.imageMapVocabulary.tooManyTerms', { max: vocab.maxTerms }));
+ return;
+ }
+
+ setInputError(null);
+
+ // Clear the draft only once it is saved, so a failure never eats the text.
+ if (await persist([...vocab.terms, ...fresh])) {
+ setDraft('');
+ }
+ };
+
+ if (query.isPending) {
+ return <Spinner size="sm" />;
+ }
+
+ if (query.isError) {
+ return (
+ <Stack align="flex-start" gap="2">
+ <Text color="fg.error" fontSize="xs">
+ {t('settings.imageMapVocabulary.loadFailed')}
+ </Text>
+ <Button size="xs" variant="outline" onClick={() => void query.refetch()}>
+ {t('common.retry')}
+ </Button>
+ </Stack>
+ );
+ }
+
+ const vocab = query.data;
+
+ return (
+ <Stack gap="3">
+ {canManageImageMapVocabulary ? (
+ <Field
+ error={inputError ?? saveError}
+ helpText={t('settings.imageMapVocabulary.addHelp')}
+ label={t('settings.imageMapVocabulary.addLabel')}
+ >
+ <HStack gap="1.5" w="full">
+ <Input
+ aria-invalid={inputError || saveError ? true : undefined}
+ placeholder={t('settings.imageMapVocabulary.addPlaceholder')}
+ size="xs"
+ value={draft}
+ onChange={(event) => {
+ setDraft(event.currentTarget.value);
+ setInputError(null);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ void addTerms(vocab);
+ }
+ }}
+ onPaste={(event) => {
+ // A single-line input silently flattens pasted newlines, which
+ // would fuse a copied term-per-line list into one bogus term.
+ // Rewrite the paste as the comma-separated form the parser
+ // (and the placeholder) already speak.
+ const text = event.clipboardData.getData('text');
+
+ if (!text.includes('\n')) {
+ return;
+ }
+
+ event.preventDefault();
+ const merged = text
+ .split(/[\n,]/)
+ .map((entry) => entry.trim())
+ .filter(Boolean)
+ .join(', ');
+ const element = event.currentTarget;
+ const start = element.selectionStart ?? element.value.length;
+ const end = element.selectionEnd ?? element.value.length;
+
+ setDraft(element.value.slice(0, start) + merged + element.value.slice(end));
+ setInputError(null);
+ }}
+ />
+ <Button
+ disabled={draft.trim().length === 0}
+ loading={isSaving}
+ size="xs"
+ variant="outline"
+ onClick={() => {
+ void addTerms(vocab);
+ }}
+ >
+ <Icon as={PlusIcon} boxSize="3.5" />
+ {t('common.add')}
+ </Button>
+ </HStack>
+ </Field>
+ ) : (
+ <Text color="fg.subtle" fontSize="xs">
+ {t('settings.imageMapVocabulary.adminOnly')}
+ </Text>
+ )}
+ {vocab.terms.length > 0 ? (
+ <Wrap gap="1">
+ {vocab.terms.map((term) => (
+ <Tag.Root key={term} size="sm" variant="surface">
+ <Tag.Label>{term}</Tag.Label>
+ {canManageImageMapVocabulary ? (
+ <Tag.EndElement>
+ <Tag.CloseTrigger
+ aria-label={t('settings.imageMapVocabulary.removeTerm', { term })}
+ onClick={() => {
+ void persist(vocab.terms.filter((existing) => existing !== term));
+ }}
+ />
+ </Tag.EndElement>
+ ) : null}
+ </Tag.Root>
+ ))}
+ </Wrap>
+ ) : (
+ <Text color="fg.subtle" fontSize="2xs">
+ {t('settings.imageMapVocabulary.noTermsYet')}
+ </Text>
+ )}
+ <VocabularyStatusLine vocab={vocab} />
+ </Stack>
+ );
+};
+
+const VocabularyStatusLine = ({ vocab }: { vocab: ImageMapVocab }) => {
+ const { t } = useTranslation();
+
+ return (
+ <Stack gap="1">
+ <Text color="fg.subtle" fontSize="2xs">
+ {t('settings.imageMapVocabulary.count', { count: vocab.terms.length, max: vocab.maxTerms })}
+ </Text>
+ {vocab.state === 'building' ? (
+ <HStack gap="1.5">
+ <Spinner size="xs" />
+ <Text color="fg.subtle" fontSize="2xs">
+ {t('settings.imageMapVocabulary.rebuilding')}
+ </Text>
+ </HStack>
+ ) : null}
+ {vocab.state === 'error' && vocab.error ? (
+ <Text color="fg.error" fontSize="2xs" role="alert">
+ {t('settings.imageMapVocabulary.buildFailed', { message: vocab.error })}
+ </Text>
+ ) : null}
+ {vocab.state === 'unavailable' ? (
+ <Text color="fg.subtle" fontSize="2xs">
+ {t('settings.imageMapVocabulary.indexOff')}
+ </Text>
+ ) : null}
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx
index 9d1f1bd9b1..9f255fc3a1 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx
@@ -41,6 +41,7 @@ import {
FolderIcon,
KeyboardIcon,
ListOrderedIcon,
+ MapIcon,
PaletteIcon,
RotateCcwIcon,
SettingsIcon,
@@ -54,6 +55,7 @@ import { useTranslation } from 'react-i18next';
import { GenerationDevicesSettings } from './GenerationDevicesSettings';
import { HotkeysSettingsSection } from './HotkeysSettingsSection';
+import { ImageMapVocabularySettings } from './ImageMapVocabularySettings';
import { setWorkbenchSettingsSection, settingsDialogStore } from './settingsDialogStore';
import {
clearWorkbenchSettings,
@@ -209,6 +211,12 @@ const SettingsTabs = () => {
label: t('settings.tabs.workflow'),
value: 'workflow',
},
+ {
+ children: <ImageMapSection />,
+ icon: MapIcon,
+ label: t('settings.tabs.imageMap'),
+ value: 'imageMap',
+ },
{
children: <DeveloperSection />,
icon: Code2Icon,
@@ -596,6 +604,21 @@ const QueueSection = () => {
);
};
+const ImageMapSection = () => {
+ const { t } = useTranslation();
+
+ return (
+ <Stack gap="6">
+ <SettingsSection
+ description={t('settings.imageMapVocabulary.description')}
+ title={t('settings.imageMapVocabulary.title')}
+ >
+ <ImageMapVocabularySettings />
+ </SettingsSection>
+ </Stack>
+ );
+};
+
const DeveloperSection = () => {
const { developerLogEnabled, developerLogLevel, developerLogNamespaces, developerPerformanceTimingsEnabled } =
useWorkbenchPreferences();
diff --git a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts b/invokeai/frontend/webv2/src/workbench/widgetContracts.ts
index f810e800e2..191eac006f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetContracts.ts
@@ -282,6 +282,7 @@ export type SettingsSectionId =
| 'project'
| 'queue'
| 'workflow'
+ | 'imageMap'
| 'developer'
| 'workspace';
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/manifest.ts
index e1399e2184..22648c4d12 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/manifest.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/manifest.ts
@@ -12,5 +12,6 @@ export const imageMapWidgetManifest: WidgetManifest = {
label: (t) => t('widgets.labels.imageMap'),
load: () => import('./implementation').then((module) => module.widgetImplementation),
loadHost: () => import('./ImageMapDataRuntime').then((module) => module.ImageMapDataRuntime),
+ settingsSection: 'imageMap',
version: 1,
};