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.

perf: reduce command palette render and search churn

joshistoaste59017640f00
diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
index 019ea2ef3b..62690aa2e9 100644
--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
@@ -88,7 +88,7 @@
"canvasStagingView.ts": "workbench",
"controlAdapters.ts": "workbench",
"focusRegions.tsx": "workbench",
- "generationModelSelection.ts": "workbench",
+ "generationSettingsOrchestration.ts": "workbench",
"graphPreviewInvocation.ts": "workbench",
"graphSurfaces.ts": "workbench",
"graphContracts.ts": "workbench",
diff --git a/invokeai/frontend/webv2/src/workbench/generationModelSelection.ts b/invokeai/frontend/webv2/src/workbench/generationModelSelection.ts
deleted file mode 100644
index f61733f5f4..0000000000
--- a/invokeai/frontend/webv2/src/workbench/generationModelSelection.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import type { GenerateModelConfig, GenerationModelCatalogItem } from '@features/generation/contracts';
-import type { GenerateModelSelectionResult } from '@features/generation/settings';
-import type { WorkbenchGenerationCommands } from '@workbench/workbenchStore';
-
-import { getGenerateModelSelectionResult } from '@features/generation/settings';
-
-export const selectProjectGenerateModel = ({
- currentValues,
- generation,
- model,
- models,
- projectId,
-}: {
- currentValues: unknown;
- generation: Pick<WorkbenchGenerationCommands, 'setSettings'>;
- model: GenerateModelConfig;
- models: readonly GenerationModelCatalogItem[];
- projectId: string;
-}): GenerateModelSelectionResult => {
- const result = getGenerateModelSelectionResult({ currentValues, model, models });
-
- generation.setSettings({ ...result.settings, model }, projectId);
-
- return result;
-};
diff --git a/invokeai/frontend/webv2/src/workbench/generationModelSelection.test.ts b/invokeai/frontend/webv2/src/workbench/generationSettingsOrchestration.test.ts
similarity index 57%
rename from invokeai/frontend/webv2/src/workbench/generationModelSelection.test.ts
rename to invokeai/frontend/webv2/src/workbench/generationSettingsOrchestration.test.ts
index 8cda829437..887cfdf109 100644
--- a/invokeai/frontend/webv2/src/workbench/generationModelSelection.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/generationSettingsOrchestration.test.ts
@@ -8,7 +8,7 @@ import type {
import { getDefaultGenerateSettings } from '@features/generation/settings';
import { describe, expect, it, vi } from 'vitest';
-import { selectProjectGenerateModel } from './generationModelSelection';
+import { recallProjectPromptHistoryItem, selectProjectGenerateModel } from './generationSettingsOrchestration';
const createModel = (base: string, key = `${base}-model`): GenerateModelConfig => ({
base,
@@ -82,3 +82,55 @@ describe('selectProjectGenerateModel', () => {
);
});
});
+
+describe('recallProjectPromptHistoryItem', () => {
+ it('patches the selected project once when current settings are valid', () => {
+ const model = createModel('sdxl');
+ const patchSettings = vi.fn();
+
+ const didRecall = recallProjectPromptHistoryItem({
+ currentValues: createSettings(model),
+ generation: { patchSettings },
+ item: { negativePrompt: 'low quality', positivePrompt: 'a lighthouse' },
+ models: [model],
+ projectId: 'project-recall',
+ });
+
+ expect(didRecall).toBe(true);
+ expect(patchSettings).toHaveBeenCalledOnce();
+ expect(patchSettings).toHaveBeenCalledWith(
+ { negativePrompt: 'low quality', negativePromptEnabled: true, positivePrompt: 'a lighthouse' },
+ 'project-recall'
+ );
+ });
+
+ it('preserves model-aware negative-prompt policy', () => {
+ const model = createModel('flux');
+ const patchSettings = vi.fn();
+
+ recallProjectPromptHistoryItem({
+ currentValues: createSettings(model, { negativePrompt: 'keep hidden value' }),
+ generation: { patchSettings },
+ item: { negativePrompt: 'history negative', positivePrompt: 'recalled prompt' },
+ models: [model],
+ projectId: 'project-flux',
+ });
+
+ expect(patchSettings).toHaveBeenCalledWith({ positivePrompt: 'recalled prompt' }, 'project-flux');
+ });
+
+ it('does not mutate invalid Generate state', () => {
+ const patchSettings = vi.fn();
+
+ const didRecall = recallProjectPromptHistoryItem({
+ currentValues: { invalid: true },
+ generation: { patchSettings },
+ item: { negativePrompt: null, positivePrompt: 'recalled prompt' },
+ models: undefined,
+ projectId: 'project-invalid',
+ });
+
+ expect(didRecall).toBe(false);
+ expect(patchSettings).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/generationSettingsOrchestration.ts b/invokeai/frontend/webv2/src/workbench/generationSettingsOrchestration.ts
new file mode 100644
index 0000000000..f63e37f403
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/generationSettingsOrchestration.ts
@@ -0,0 +1,60 @@
+import type {
+ GenerateModelConfig,
+ GenerationModelCatalogItem,
+ PromptHistoryItem,
+} from '@features/generation/contracts';
+import type { GenerateModelSelectionResult } from '@features/generation/settings';
+import type { WorkbenchGenerationCommands } from '@workbench/workbenchStore';
+
+import { getGenerateModelSelectionResult, getPromptHistoryRecallPatch } from '@features/generation/settings';
+
+export const selectProjectGenerateModel = ({
+ currentValues,
+ generation,
+ model,
+ models,
+ projectId,
+}: {
+ currentValues: unknown;
+ generation: Pick<WorkbenchGenerationCommands, 'setSettings'>;
+ model: GenerateModelConfig;
+ models: readonly GenerationModelCatalogItem[];
+ projectId: string;
+}): GenerateModelSelectionResult => {
+ const result = getGenerateModelSelectionResult({ currentValues, model, models });
+
+ generation.setSettings({ ...result.settings, model }, projectId);
+
+ return result;
+};
+
+export const recallProjectPromptHistoryItem = ({
+ currentValues,
+ generation,
+ item,
+ models,
+ projectId,
+}: {
+ currentValues: unknown;
+ generation: Pick<WorkbenchGenerationCommands, 'patchSettings'>;
+ item: PromptHistoryItem;
+ models: readonly GenerationModelCatalogItem[] | undefined;
+ projectId: string;
+}): boolean => {
+ if (typeof currentValues !== 'object' || currentValues === null || Array.isArray(currentValues)) {
+ return false;
+ }
+
+ const patch = getPromptHistoryRecallPatch({
+ item,
+ models,
+ values: currentValues as Record<string, unknown>,
+ });
+
+ if (!patch) {
+ return false;
+ }
+
+ generation.patchSettings(patch, projectId);
+ return true;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx
index 9256e6dbf5..b251a3cc2e 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx
@@ -5,11 +5,10 @@ import type { getWidgetsForRegion as GetWidgetsForRegion } from '@workbench/widg
import type { TFunction } from 'i18next';
import { flushGenerateDrafts, notifyGenerateModelSelectionCleared } from '@features/generation/react';
-import { getPromptHistoryRecallPatch } from '@features/generation/settings';
-import { useModelsSnapshot } from '@features/models';
+import { getModelsSnapshot } from '@features/models';
import { getQueueQueryScope, getQueueReadModelOptions } from '@features/queue/queries';
import { queryClient } from '@platform/query/client';
-import { selectProjectGenerateModel } from '@workbench/generationModelSelection';
+import { recallProjectPromptHistoryItem, selectProjectGenerateModel } from '@workbench/generationSettingsOrchestration';
import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';
import { useNotify } from '@workbench/useNotify';
import { getProjectWidgetValues } from '@workbench/widgetState';
@@ -27,7 +26,6 @@ import type { PaletteEntry, PaletteSearchProvider, SettingsEntryDeps } from './e
import { CommandPaletteDialog } from './CommandPaletteDialog';
import { buildCatalogCommandEntries, buildOpenSettingsEntry, buildSettingsEntries } from './entries';
import { buildExtensionPaletteEntry, createExtensionSearchProvider } from './extensionPaletteAdapters';
-import { getObjectIdentity } from './objectIdentity';
import {
createBoardsProvider,
createImagesProvider,
@@ -76,11 +74,8 @@ const WorkbenchCommandPaletteDialog = ({
const extensions = useWorkbenchExtensions();
const notify = useNotify();
const workbenchQueries = useWorkbenchQueries();
- const modelsSnapshot = useModelsSnapshot();
- const models = modelsSnapshot.status === 'loaded' ? modelsSnapshot.models : undefined;
const projectId = useActiveProjectSelector((project) => project.id);
const promptHistory = useActiveProjectSelector((project) => project.promptHistory);
- const generateValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'generate'));
const presentWidgetTypeIds = useActiveProjectSelector((project) =>
[...new Set(Object.values(project.widgetInstances).map((instance) => instance.typeId))].sort()
);
@@ -130,7 +125,15 @@ const WorkbenchCommandPaletteDialog = ({
const workbenchCommands = useWorkbenchCommands();
const searchStore = extensions.stores.search;
const extensionSearchProviders = useSyncExternalStore(searchStore.subscribe, searchStore.list, searchStore.list);
- const promptRecallContextKey = `${getObjectIdentity(generateValues, 'generation')}:${getObjectIdentity(models, 'models')}`;
+ const readCurrentGenerateContext = useCallback(() => {
+ flushGenerateDrafts();
+ const project = workbenchQueries.getSnapshot().activeProject;
+
+ return {
+ currentValues: getProjectWidgetValues(project, 'generate'),
+ projectId: project.id,
+ };
+ }, [workbenchQueries]);
const queueScope = useMemo(
() => getQueueQueryScope({ projectId, queueJobsScope: preferences.queueJobsScope }),
[preferences.queueJobsScope, projectId]
@@ -161,14 +164,13 @@ const WorkbenchCommandPaletteDialog = ({
}),
createModelsProvider({
applyModel: (model, catalogModels) => {
- flushGenerateDrafts();
- const project = workbenchQueries.getSnapshot().activeProject;
+ const { currentValues, projectId } = readCurrentGenerateContext();
const result = selectProjectGenerateModel({
- currentValues: getProjectWidgetValues(project, 'generate'),
+ currentValues,
generation,
model,
models: catalogModels,
- projectId: project.id,
+ projectId,
});
notifyGenerateModelSelectionCleared({
@@ -202,13 +204,17 @@ const WorkbenchCommandPaletteDialog = ({
openGenerateWidget: () => openWidget('generate'),
projectId,
promptHistory,
- recallContextKey: promptRecallContextKey,
recallPrompt: (item) => {
- const patch = getPromptHistoryRecallPatch({ item, models, values: generateValues });
+ const { currentValues, projectId } = readCurrentGenerateContext();
+ const modelsSnapshot = getModelsSnapshot();
- if (patch) {
- widgets.patchValues('generate', patch, projectId);
- }
+ recallProjectPromptHistoryItem({
+ currentValues,
+ generation,
+ item,
+ models: modelsSnapshot.status === 'loaded' ? modelsSnapshot.models : undefined,
+ projectId,
+ });
},
t,
}),
@@ -220,20 +226,17 @@ const WorkbenchCommandPaletteDialog = ({
executeCommand,
extensionSearchProviders,
extensions,
- generateValues,
i18n.resolvedLanguage,
- models,
notify,
getWidgetsForRegion,
openWidgetPlacement,
projectId,
promptHistory,
- promptRecallContextKey,
queueScope,
+ readCurrentGenerateContext,
requestQueueItemReveal,
t,
workbenchCommands,
- workbenchQueries,
]);
return (
diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts
index 1e1fc856c6..a043306703 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts
@@ -16,6 +16,7 @@ import {
buildStageEntries,
SEARCH_SCOPE_GROUP,
searchPaletteRows,
+ getNavigablePaletteRows,
resolveActivePaletteRow,
} from './entries';
@@ -405,7 +406,7 @@ describe('stable active row identity', () => {
{ entry: makeEntry({ group: 'Provider', id: 'async', title: 'Async' }), id: 'async-row', kind: 'entry' as const },
...initial,
];
- const active = resolveActivePaletteRow(withAsyncInsertion, 'selected');
+ const active = resolveActivePaletteRow(getNavigablePaletteRows(withAsyncInsertion), 'selected');
expect(active?.row.id).toBe('selected');
if (active?.row.kind === 'entry') {
diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.ts
index 76ba6dd6d5..2534782779 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/entries.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.ts
@@ -101,15 +101,15 @@ export interface ActivePaletteRow {
row: Exclude<PaletteRow, { kind: 'label' }>;
}
+export const getNavigablePaletteRows = (rows: readonly PaletteRow[]): ActivePaletteRow[] =>
+ rows.flatMap((row, index): ActivePaletteRow[] => (row.kind === 'label' ? [] : [{ index, row }]));
+
/** Resolve selection by stable row id, falling back to the first actionable row. */
export const resolveActivePaletteRow = (
- rows: readonly PaletteRow[],
+ navigableRows: readonly ActivePaletteRow[],
activeRowId: string | null
-): ActivePaletteRow | undefined => {
- const navigable = rows.flatMap((row, index): ActivePaletteRow[] => (row.kind === 'label' ? [] : [{ index, row }]));
-
- return (activeRowId ? navigable.find((candidate) => candidate.row.id === activeRowId) : undefined) ?? navigable[0];
-};
+): ActivePaletteRow | undefined =>
+ (activeRowId ? navigableRows.find((candidate) => candidate.row.id === activeRowId) : undefined) ?? navigableRows[0];
/** Max rows an entity section shows in root mode; depth lives behind the scope. */
export const PROVIDER_ROOT_RESULT_CAP = 3;
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts
index a4196b37d6..c4039f3f33 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.test.ts
@@ -15,7 +15,9 @@ vi.mock('@features/models', () => ({
getModelsSnapshot,
}));
-import { createModelsProvider } from './paletteProviders';
+vi.mock('@features/generation/react', () => ({ focusPositivePrompt: vi.fn() }));
+
+import { createModelsProvider, createPromptHistoryProvider } from './paletteProviders';
const model = (key: string, base: string, type = 'main'): ModelConfig =>
({ base, key, name: key, type }) as unknown as ModelConfig;
@@ -73,5 +75,50 @@ describe('createModelsProvider', () => {
expect((await provider.search({ text: 'flux' }, searchContext())).map((entry) => entry.title)).toEqual([
'fast-flux',
]);
+ expect((await provider.search({ text: 'SDXL CINEMATIC' }, searchContext())).map((entry) => entry.title)).toEqual([
+ 'cinematic-xl',
+ ]);
+ expect(await provider.search({ text: 'cinematic flux' }, searchContext())).toEqual([]);
+ });
+});
+
+describe('createPromptHistoryProvider', () => {
+ const history = [
+ { negativePrompt: 'fog', positivePrompt: 'Red Mountain' },
+ { negativePrompt: 'fog', positivePrompt: 'Red Mountain' },
+ { negativePrompt: null, positivePrompt: 'Blue Ocean' },
+ ];
+
+ it('deduplicates results, preserves AND matching, and executes the selected item', async () => {
+ const openGenerateWidget = vi.fn();
+ const recallPrompt = vi.fn();
+ const provider = createPromptHistoryProvider({
+ openGenerateWidget,
+ projectId: 'project-1',
+ promptHistory: history,
+ recallPrompt,
+ t,
+ });
+
+ const entries = await provider.search({ text: 'MoUnTaIn ReD' }, searchContext());
+
+ expect(entries).toHaveLength(1);
+ expect(entries[0]?.title).toBe('Red Mountain');
+ vi.stubGlobal('window', { requestAnimationFrame: vi.fn() });
+ entries[0]?.run();
+ expect(openGenerateWidget).toHaveBeenCalledOnce();
+ expect(recallPrompt).toHaveBeenCalledWith(history[0]);
+ vi.unstubAllGlobals();
+ });
+
+ it('keys search results only by project and prompt-history identity', () => {
+ const createProvider = (projectId: string, promptHistory: typeof history, recallPrompt = vi.fn()) =>
+ createPromptHistoryProvider({ openGenerateWidget: vi.fn(), projectId, promptHistory, recallPrompt, t });
+
+ const first = createProvider('project-1', history, vi.fn());
+
+ expect(createProvider('project-1', history, vi.fn()).contextKey).toBe(first.contextKey);
+ expect(createProvider('project-2', history).contextKey).not.toBe(first.contextKey);
+ expect(createProvider('project-1', [...history]).contextKey).not.toBe(first.contextKey);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts
index 2b78f13fd5..d5d69d85d2 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts
@@ -39,11 +39,14 @@ const PROVIDER_PAGE_SIZE = 8;
const loadActiveBoards = (): Promise<GalleryBoard[]> =>
queryClient.fetchQuery(galleryBoardsOptions({ includeArchived: false }));
-const matchesTerms = (haystack: string, query: string): boolean => {
+const createTermsMatcher = (query: string): ((haystack: string) => boolean) => {
const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
- const lower = haystack.toLowerCase();
- return terms.every((term) => lower.includes(term));
+ return (haystack) => {
+ const lower = haystack.toLowerCase();
+
+ return terms.every((term) => lower.includes(term));
+ };
};
export const createWorkflowsProvider = ({
@@ -96,13 +99,14 @@ export const createBoardsProvider = ({
supportsCreatedAtRange: true,
search: async (query, { signal }) => {
const boards = await loadActiveBoards();
+ const matchesQuery = createTermsMatcher(query.text);
signal.throwIfAborted();
return boards
.filter(
(board: GalleryBoard) =>
- matchesTerms(board.name, query.text) &&
+ matchesQuery(board.name) &&
// Boards without a creation date (uncategorized, date virtual
// boards) are excluded only while a date range is active.
(query.range === undefined || isTimestampInRange(board.createdAt ?? '', query.range))
@@ -126,31 +130,30 @@ export const createPromptHistoryProvider = ({
openGenerateWidget,
projectId,
promptHistory,
- recallContextKey,
recallPrompt,
t,
}: {
openGenerateWidget: () => void;
projectId: string;
promptHistory: readonly PromptHistoryItem[];
- recallContextKey: string;
recallPrompt: (item: PromptHistoryItem) => void;
t: TFunction;
}): PaletteSearchProvider => ({
- contextKey: `${projectId}:${getObjectIdentity(promptHistory, 'history')}:${recallContextKey}`,
+ contextKey: `${projectId}:${getObjectIdentity(promptHistory, 'history')}`,
label: t('commandPalette.providers.promptHistory'),
providerKey: getPaletteContributionKey('provider', 'prompt-history'),
search: (query, { signal }) => {
signal.throwIfAborted();
const seen = new Set<string>();
const entries: PaletteEntry[] = [];
+ const matchesQuery = createTermsMatcher(query.text);
for (const [index, item] of promptHistory.entries()) {
const dedupeKey = `${item.positivePrompt}\n${item.negativePrompt ?? ''}`;
// Prompt history items carry no timestamp, so this provider is text-only
// (not range-capable); it never sees pure-date queries.
- if (seen.has(dedupeKey) || !matchesTerms(`${item.positivePrompt} ${item.negativePrompt ?? ''}`, query.text)) {
+ if (seen.has(dedupeKey) || !matchesQuery(`${item.positivePrompt} ${item.negativePrompt ?? ''}`)) {
continue;
}
@@ -195,10 +198,11 @@ export const createModelsProvider = ({
signal.throwIfAborted();
const snapshot = getModelsSnapshot();
const models = snapshot.status === 'loaded' ? snapshot.models : [];
+ const matchesQuery = createTermsMatcher(query.text);
return models
.filter(isSupportedGenerateModel)
- .filter((model) => matchesTerms(`${model.name} ${model.base}`, query.text))
+ .filter((model) => matchesQuery(`${model.name} ${model.base}`))
.map<PaletteEntry>((model) => ({
group: 'Models',
groupLabel: t('commandPalette.groups.models'),
@@ -239,15 +243,15 @@ export const createQueueItemsProvider = ({
// closed while a date range is active.
signal.throwIfAborted();
const model = await loadQueue();
+ const matchesQuery = createTermsMatcher(query.text);
signal.throwIfAborted();
return model.items
.map((item) => ({ item, meta: extractGenerationMeta(item) }))
.filter(
({ item, meta }) =>
- matchesTerms(
- `${meta.positivePrompt ?? ''} ${meta.negativePrompt ?? ''} ${t(`commandPalette.queueStatuses.${item.status}`)} ${item.userDisplayName ?? ''}`,
- query.text
+ matchesQuery(
+ `${meta.positivePrompt ?? ''} ${meta.negativePrompt ?? ''} ${t(`commandPalette.queueStatuses.${item.status}`)} ${item.userDisplayName ?? ''}`
) &&
(query.range === undefined || isTimestampInRange(item.createdAt, query.range))
)
@@ -287,60 +291,62 @@ export const createImagesProvider = ({
selectImage: (image: GalleryImage) => void;
locale?: string;
t: TFunction;
-}): PaletteSearchProvider => ({
- contextKey: 'global',
- label: t('commandPalette.providers.images'),
- providerKey: getPaletteContributionKey('provider', 'images'),
- supportsCreatedAtRange: true,
- search: async (query, { signal }) => {
- // Search the explicit all-readable scope. The endpoint excludes archived
- // and inaccessible boards; the active board list supplies display labels.
- const [page, boards] = await Promise.all([
- listGalleryImages({
- boardId: ALL_READABLE_BOARDS_ID,
- createdFrom: query.range?.from,
- createdTo: query.range?.to,
- galleryView: 'images',
- limit: 20,
- searchTerm: query.text,
- signal,
- }),
- loadActiveBoards(),
- ]);
- const boardNames = new Map(boards.map((board: GalleryBoard) => [board.id, board.name]));
- // Images carry no prompt, so the creation date+time is the title; the time
- // keeps same-day results (the common case for 20 recents) distinguishable.
- const titleFormatter = new Intl.DateTimeFormat(locale, {
- day: 'numeric',
- hour: 'numeric',
- minute: 'numeric',
- month: 'short',
- });
+}): PaletteSearchProvider => {
+ const titleFormatter = new Intl.DateTimeFormat(locale, {
+ day: 'numeric',
+ hour: 'numeric',
+ minute: 'numeric',
+ month: 'short',
+ });
- return page.images.map<PaletteEntry>((image) => {
- const createdAt = new Date(normalizeServerTimestamp(image.queuedAt));
+ return {
+ contextKey: 'global',
+ label: t('commandPalette.providers.images'),
+ providerKey: getPaletteContributionKey('provider', 'images'),
+ supportsCreatedAtRange: true,
+ search: async (query, { signal }) => {
+ // Search the explicit all-readable scope. The endpoint excludes archived
+ // and inaccessible boards; the active board list supplies display labels.
+ const [page, boards] = await Promise.all([
+ listGalleryImages({
+ boardId: ALL_READABLE_BOARDS_ID,
+ createdFrom: query.range?.from,
+ createdTo: query.range?.to,
+ galleryView: 'images',
+ limit: 20,
+ searchTerm: query.text,
+ signal,
+ }),
+ loadActiveBoards(),
+ ]);
+ const boardNames = new Map(boards.map((board: GalleryBoard) => [board.id, board.name]));
+ // Images carry no prompt, so the creation date+time is the title; the time
+ // keeps same-day results (the common case for 20 recents) distinguishable.
+ return page.images.map<PaletteEntry>((image) => {
+ const createdAt = new Date(normalizeServerTimestamp(image.queuedAt));
- return {
- group: 'Images',
- groupLabel: t('commandPalette.groups.images'),
- id: `image:${image.imageName}`,
- isPersistentRecent: false,
- run: () => {
- openPreviewWidget();
- selectImage(image);
- },
- secondary: {
- label: t('commandPalette.actions.revealInGallery'),
+ return {
+ group: 'Images',
+ groupLabel: t('commandPalette.groups.images'),
+ id: `image:${image.imageName}`,
+ isPersistentRecent: false,
run: () => {
- openGalleryWidget();
- selectBoard(image.boardId);
+ openPreviewWidget();
selectImage(image);
},
- },
- subtitle: `${boardNames.get(image.boardId) ?? t('commandPalette.providers.uncategorized')} · ${image.width}×${image.height}`,
- thumbnailUrl: image.thumbnailUrl,
- title: Number.isNaN(createdAt.getTime()) ? image.imageName : titleFormatter.format(createdAt),
- };
- });
- },
-});
+ secondary: {
+ label: t('commandPalette.actions.revealInGallery'),
+ run: () => {
+ openGalleryWidget();
+ selectBoard(image.boardId);
+ selectImage(image);
+ },
+ },
+ subtitle: `${boardNames.get(image.boardId) ?? t('commandPalette.providers.uncategorized')} · ${image.width}×${image.height}`,
+ thumbnailUrl: image.thumbnailUrl,
+ title: Number.isNaN(createdAt.getTime()) ? image.imageName : titleFormatter.format(createdAt),
+ };
+ });
+ },
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteQueryModel.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteQueryModel.ts
index bd33e5088a..b49820796f 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/paletteQueryModel.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteQueryModel.ts
@@ -33,7 +33,7 @@ export const derivePaletteQueryModel = ({
state,
}: {
providers: PaletteSearchProvider[];
- state: PaletteState;
+ state: Pick<PaletteState, 'debouncedQuery' | 'mode' | 'query'>;
}): PaletteQueryModel => {
const requestedScopeProviderKey = state.mode.kind === 'scoped' ? state.mode.providerKey : null;
const scopeProvider = requestedScopeProviderKey
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteState.test.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteState.test.ts
index eb96db9437..a1ddf5d489 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/paletteState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteState.test.ts
@@ -39,4 +39,10 @@ describe('palette state transitions', () => {
it('returns to a fresh root state', () => {
expect(returnPaletteToRoot()).toEqual(createInitialPaletteState());
});
+
+ it('preserves state identity when the requested row is already selected', () => {
+ const state = changePaletteSelection(createInitialPaletteState(), 'row-1');
+
+ expect(changePaletteSelection(state, 'row-1')).toBe(state);
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteState.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteState.ts
index 51b02bc4b6..594545d200 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/paletteState.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteState.ts
@@ -46,7 +46,5 @@ export const enterPaletteStage = (stage: PaletteStage, activeRowId: string | nul
export const returnPaletteToRoot = (): PaletteState => createInitialPaletteState();
-export const changePaletteSelection = (state: PaletteState, activeRowId: string | null): PaletteState => ({
- ...state,
- activeRowId,
-});
+export const changePaletteSelection = (state: PaletteState, activeRowId: string | null): PaletteState =>
+ state.activeRowId === activeRowId ? state : { ...state, activeRowId };
diff --git a/invokeai/frontend/webv2/src/workbench/palette/useCommandPaletteController.ts b/invokeai/frontend/webv2/src/workbench/palette/useCommandPaletteController.ts
index 7ed7dcd800..b8c23bcc7b 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/useCommandPaletteController.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/useCommandPaletteController.ts
@@ -82,9 +82,10 @@ export const useCommandPaletteController = ({
window.requestAnimationFrame(() => document.getElementById(COMMAND_PALETTE_INPUT_ID)?.focus());
}, []);
const clearDebounce = debouncer.cancel;
+ const { activeRowId, debouncedQuery, mode, query } = paletteState;
const queryModel = useMemo(
- () => derivePaletteQueryModel({ providers, state: paletteState }),
- [paletteState, providers]
+ () => derivePaletteQueryModel({ providers, state: { debouncedQuery, mode, query } }),
+ [debouncedQuery, mode, providers, query]
);
const {
activeProviders,
@@ -99,8 +100,6 @@ export const useCommandPaletteController = ({
stage,
trimmedQuery,
} = queryModel;
- const { activeRowId, query } = paletteState;
-
const { results: providerResults, sections: providerSections } = usePaletteProviderSections({
enabled: shouldSearchProviders && !isWaitingForDebounce,
isWaitingForDebounce: shouldSearchProviders && isWaitingForDebounce,
diff --git a/invokeai/frontend/webv2/src/workbench/palette/usePaletteNavigation.ts b/invokeai/frontend/webv2/src/workbench/palette/usePaletteNavigation.ts
index 980e612590..f066c43f4e 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/usePaletteNavigation.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/usePaletteNavigation.ts
@@ -5,7 +5,7 @@ import { useCallback, useMemo } from 'react';
import type { PaletteEntry, PaletteRow, PaletteStage } from './entries';
import type { PaletteState } from './paletteState';
-import { resolveActivePaletteRow, STAGE_ENTRY_ID_PREFIX } from './entries';
+import { getNavigablePaletteRows, resolveActivePaletteRow, STAGE_ENTRY_ID_PREFIX } from './entries';
import { changePaletteSelection, enterPaletteStage } from './paletteState';
import { recordRecentEntry } from './recents';
@@ -40,11 +40,11 @@ export const usePaletteNavigation = ({
setPaletteState: Dispatch<SetStateAction<PaletteState>>;
stage: PaletteStage | null;
}) => {
- const navigableRows = useMemo(
- () => rows.flatMap((row, index) => (row.kind === 'label' ? [] : [{ index, row }])),
- [rows]
+ const navigableRows = useMemo(() => getNavigablePaletteRows(rows), [rows]);
+ const effectiveActive = useMemo(
+ () => resolveActivePaletteRow(navigableRows, activeRowId),
+ [activeRowId, navigableRows]
);
- const effectiveActive = useMemo(() => resolveActivePaletteRow(rows, activeRowId), [activeRowId, rows]);
const activeRow = effectiveActive?.row;
const runRow = useCallback(
@@ -193,11 +193,15 @@ export const usePaletteNavigation = ({
const onRowActive = useCallback(
(rowId: string) => {
+ if (rowId === effectiveActive?.row.id) {
+ return;
+ }
+
const row = rows.find((candidate) => candidate.id === rowId);
setPaletteState((current) => changePaletteSelection(current, rowId));
previewRow(row);
},
- [previewRow, rows, setPaletteState]
+ [effectiveActive, previewRow, rows, setPaletteState]
);
return {