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(command-palette): deepen and lazy-load palette

joshistoaste98ae9ba3c9a
diff --git a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
index d4646c5aae..44cd4ea57f 100644
--- a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
+++ b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
@@ -3,7 +3,7 @@ import type { WorkbenchSearch } from '@workbench/projects/session';
import { SessionExpiryGuard } from '@features/identity';
import { useSearch } from '@tanstack/react-router';
import { WorkbenchHotkeyRuntime } from '@workbench/hotkeys/WorkbenchHotkeyRuntime';
-import { WorkbenchCommandPalette } from '@workbench/palette';
+import { WorkbenchCommandPalette } from '@workbench/palette/WorkbenchCommandPalette';
import { WorkbenchShell } from '@workbench/shell';
import { WidgetHosts } from '@workbench/widget-frame/WidgetHosts';
import { getWidgetById, getWidgetsForRegion } from '@workbench/widgetRegistry';
diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx
index 8aaf9905cd..46353ef7e9 100644
--- a/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx
+++ b/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.tsx
@@ -4,7 +4,7 @@ import { ModelsPage } from '@features/models';
import { NodesPage } from '@features/nodes';
import { Tabs } from '@platform/ui';
import { useLocation, useNavigate } from '@tanstack/react-router';
-import { LaunchpadCommandPalette } from '@workbench/palette';
+import { LaunchpadCommandPalette } from '@workbench/palette/LaunchpadCommandPalette';
import { BoxIcon, BlocksIcon, FolderIcon, UsersIcon, type LucideIcon } from 'lucide-react';
import { useCallback, useMemo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx
index 9b45b74e4e..f1f8ed754b 100644
--- a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx
+++ b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx
@@ -6,7 +6,7 @@ import { useConnectionStatusSelector } from '@platform/transport/connectionStore
import { Button } from '@platform/ui';
import { InvokeMark } from '@platform/ui/InvokeMark';
import { Link, useSearch } from '@tanstack/react-router';
-import { PaletteButton } from '@workbench/palette';
+import { PaletteButton } from '@workbench/palette/PaletteButton';
import { SettingsButton } from '@workbench/settings/SettingsDialog';
import { ArrowLeftIcon } from 'lucide-react';
import { useMemo } from 'react';
diff --git a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.browser.test.tsx
new file mode 100644
index 0000000000..c1559c51c3
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.browser.test.tsx
@@ -0,0 +1,171 @@
+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, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+import type { PaletteEntry, PaletteSearchProvider } from './entries';
+
+import { CommandPaletteDialog } from './CommandPaletteDialog';
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const entry = (id: string, title: string, run = vi.fn()): PaletteEntry => ({
+ group: 'Commands',
+ id,
+ isPersistentRecent: true,
+ run,
+ showInEmptyState: true,
+ title,
+});
+
+const renderPalette = async ({
+ entries,
+ onClose = vi.fn(),
+ providers,
+}: {
+ entries: PaletteEntry[];
+ onClose?: () => void;
+ providers?: PaletteSearchProvider[];
+}) => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+
+ await act(() => {
+ root?.render(
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={new QueryClient()}>
+ <CommandPaletteDialog
+ entries={entries}
+ isOpen
+ modifierKeyLabel="ctrl"
+ providers={providers}
+ onClose={onClose}
+ />
+ </QueryClientProvider>
+ </ChakraProvider>
+ );
+ });
+
+ const input = await vi.waitFor(() => {
+ const node = document.querySelector<HTMLInputElement>('[name="command-palette-query"]');
+ expect(node).not.toBeNull();
+ return node!;
+ });
+
+ return { input, onClose };
+};
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+ window.localStorage.clear();
+});
+
+describe('CommandPaletteDialog interaction', () => {
+ it('exposes an accessible focused search field and runs the stable highlighted command in bare > mode', async () => {
+ const firstRun = vi.fn();
+ const secondRun = vi.fn();
+ const providerSearch = vi.fn(() => []);
+ const provider: PaletteSearchProvider = {
+ contextKey: 'context',
+ label: 'Entities',
+ providerKey: 'entities',
+ search: providerSearch,
+ };
+ const setting: PaletteEntry = {
+ group: 'Settings',
+ id: 'setting.test',
+ isPersistentRecent: true,
+ run: vi.fn(),
+ title: 'Hidden setting',
+ };
+ const { input, onClose } = await renderPalette({
+ entries: [entry('first', 'First command', firstRun), entry('second', 'Second command', secondRun), setting],
+ providers: [provider],
+ });
+
+ expect(document.activeElement).toBe(input);
+ expect(input.type).toBe('search');
+ expect(input.autocomplete).toBe('off');
+ expect(input.spellcheck).toBe(false);
+ expect(document.querySelector('[role="dialog"]')?.textContent).toContain('Command palette');
+ expect(input.getAttribute('aria-controls')).toBe('command-palette-results');
+
+ await act(() => userEvent.fill(input, '>'));
+ expect(document.body.textContent).toContain('First command');
+ expect(document.body.textContent).toContain('Second command');
+ expect(document.body.textContent).not.toContain('Hidden setting');
+
+ await new Promise((resolve) => {
+ globalThis.setTimeout(resolve, 250);
+ });
+ expect(providerSearch).not.toHaveBeenCalled();
+
+ await act(() => userEvent.keyboard('{ArrowDown}{Enter}'));
+ expect(firstRun).not.toHaveBeenCalled();
+ expect(secondRun).toHaveBeenCalledOnce();
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+
+ it('allows Tab to reach Retry and explicitly returns focus after retrying', async () => {
+ const provider: PaletteSearchProvider = {
+ contextKey: 'context',
+ label: 'Entities',
+ providerKey: 'entities',
+ search: vi.fn(() => Promise.reject(new Error('offline'))),
+ };
+ const { input } = await renderPalette({ entries: [], providers: [provider] });
+
+ await act(() => userEvent.fill(input, 'zz'));
+ await act(() => userEvent.keyboard('{Tab}'));
+ const retry = await vi.waitFor(() => {
+ const node = [...document.querySelectorAll('button')].find((button) => button.textContent === 'Retry');
+ expect(node).toBeDefined();
+ return node!;
+ });
+
+ await act(() => userEvent.tab());
+ expect(document.activeElement).toBe(retry);
+
+ await act(() => userEvent.click(retry));
+ await vi.waitFor(() => expect(document.activeElement).toBe(input));
+ });
+
+ it('drives stage preview from navigation and restores it on Escape and unmount', async () => {
+ const preview = vi.fn();
+ const clearPreview = vi.fn();
+ const staged: PaletteEntry = {
+ ...entry('theme', 'Theme'),
+ stage: {
+ clearPreview,
+ options: [
+ { apply: vi.fn(), id: 'a', isCurrent: false, label: 'Alpha' },
+ { apply: vi.fn(), id: 'b', isCurrent: true, label: 'Beta' },
+ ],
+ preview,
+ title: 'Theme',
+ },
+ };
+ const { input } = await renderPalette({ entries: [staged] });
+
+ await act(() => userEvent.keyboard('{Enter}{ArrowUp}'));
+ expect(preview).toHaveBeenLastCalledWith('a');
+
+ await act(() => userEvent.keyboard('{Escape}'));
+ expect(clearPreview).toHaveBeenCalledOnce();
+ expect(document.activeElement).toBe(input);
+
+ await act(() => userEvent.keyboard('{Enter}'));
+ await act(() => root?.unmount());
+ root = null;
+ expect(clearPreview).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx
index 08d77c19b3..44d6fc7ae0 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx
@@ -1,266 +1,27 @@
-import type { ChangeEvent, KeyboardEvent, ReactNode } from 'react';
+/* eslint-disable react/react-compiler */
+import type { ReactNode } from 'react';
-import { Box, Dialog, HStack, Icon, Kbd, Portal, ScrollArea, Spacer, Text, chakra } from '@chakra-ui/react';
+import { Dialog, HStack, Icon, Kbd, Portal, Spacer, Text, chakra } from '@chakra-ui/react';
import { useMountEffect } from '@platform/react/useMountEffect';
-import { Button } from '@platform/ui';
+import { Button } from '@platform/ui/Button';
import { EmptyState } from '@platform/ui/EmptyState';
-import { useQueries } from '@tanstack/react-query';
-import { dropdownGroupLabel } from '@theme/recipes';
-import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
-import { registerHotkeyModalLayer } from '@workbench/hotkeys/modalLayer';
-import { CheckIcon, SearchIcon } from 'lucide-react';
-import { useCallback, useEffect, useMemo, useState } from 'react';
-import { useVirtualizer } from 'react-hook-tanstack-virtual';
+import { SearchIcon } from 'lucide-react';
+import { useCallback, useMemo, useRef } from 'react';
-import type { PaletteEntry, PaletteRow, PaletteSearchProvider, PaletteStage, ProviderResultSection } from './entries';
+import type { CommandPaletteRowsHandle } from './CommandPaletteRows';
+import type { PaletteEntry, PaletteSearchProvider, PaletteStage } from './entries';
-import {
- buildProviderSectionRows,
- buildScopeRows,
- buildStageEntries,
- PROVIDER_MIN_QUERY_LENGTH,
- searchPaletteRows,
- STAGE_ENTRY_ID_PREFIX,
-} from './entries';
-import { getRecentEntryIds, recordRecentEntry } from './recents';
-
-/**
- * The palette surface: a top-anchored quiet overlay with one input, one mixed
- * virtualized list (fixed section order, fuzzy-ranked within sections), and a
- * footer hint bar. Follows the AddNodeDialog combobox pattern — focus stays on
- * the input, the highlighted row travels via aria-activedescendant, and hover
- * only claims the highlight on real mouse movement (not scroll-under-cursor).
- *
- * Two overlays stack on the root list: a value-picker *stage* (enum settings)
- * and a provider *scope* (deep entity search). Both render as a chip in the
- * input; Esc or Backspace-on-empty pops them before anything closes.
- */
-
-const RESULT_LIST_ID = 'command-palette-results';
-const LABEL_ROW_HEIGHT_PX = 26;
-const ENTRY_ROW_HEIGHT_PX = 40;
-const PAGE_JUMP_ROWS = 8;
-const PROVIDER_DEBOUNCE_MS = 200;
-const VIRTUALIZER_INITIAL_RECT = { height: 384, width: 0 };
+import { CommandPaletteRows, getCommandPaletteRowDomId } from './CommandPaletteRows';
+import { PROVIDER_MIN_QUERY_LENGTH } from './entries';
+import { useCommandPaletteController } from './useCommandPaletteController';
const INPUT_PLACEHOLDER_STYLE = { color: 'fg.subtle' };
+const INPUT_FOCUS_WITHIN_STYLE = { outlineColor: 'accent.focusRing' };
const NO_PROVIDERS: PaletteSearchProvider[] = [];
-
const NAV_HINT_KEYS = ['↑', '↓'];
const ENTER_HINT_KEYS = ['↵'];
const ESC_HINT_KEYS = ['esc'];
const TAB_HINT_KEYS = ['tab'];
-const MOD_ENTER_HINT_KEYS = [formatHotkeyForPlatform('mod')[0] ?? 'ctrl', '↵'];
-
-const getRowDomId = (index: number): string => `${RESULT_LIST_ID}-${index}`;
-
-/** Rows never take focus — mousedown is swallowed so the input keeps the caret through clicks. */
-const preventFocusSteal = (event: { preventDefault: () => void }) => event.preventDefault();
-
-const useDebouncedValue = <Value,>(value: Value, delayMs: number): Value => {
- const [debounced, setDebounced] = useState(value);
-
- useEffect(() => {
- if (Object.is(debounced, value)) {
- return;
- }
-
- const timeoutId = window.setTimeout(() => setDebounced(value), delayMs);
-
- return () => window.clearTimeout(timeoutId);
- }, [debounced, delayMs, value]);
-
- return debounced;
-};
-
-/** Render the entry title with fuzzysort's matched characters subtly emphasized. */
-const renderTitle = (title: string, matchIndexes?: readonly number[]): ReactNode => {
- if (!matchIndexes || matchIndexes.length === 0) {
- return title;
- }
-
- const matched = new Set(matchIndexes);
- const segments: ReactNode[] = [];
- let start = 0;
-
- for (let index = 1; index <= title.length; index += 1) {
- if (index === title.length || matched.has(index) !== matched.has(start)) {
- const text = title.slice(start, index);
-
- segments.push(
- matched.has(start) ? (
- <Text key={start} as="span" fontWeight="600">
- {text}
- </Text>
- ) : (
- text
- )
- );
- start = index;
- }
- }
-
- return segments;
-};
-
-const rowButtonProps = {
- as: 'button',
- cursor: 'pointer',
- gap: '2.5',
- h: `${ENTRY_ROW_HEIGHT_PX}px`,
- px: '3',
- rounded: 'sm',
- tabIndex: -1,
- textAlign: 'start',
- w: 'full',
-} as const;
-
-const EntryRow = ({
- id,
- isActive,
- matchIndexes,
- entry,
- onActive,
- onRun,
-}: {
- id: string;
- isActive: boolean;
- matchIndexes?: readonly number[];
- entry: PaletteEntry;
- onActive: () => void;
- onRun: () => void;
-}) => (
- <HStack
- {...rowButtonProps}
- id={id}
- aria-selected={isActive}
- bg={isActive ? 'bg.emphasized' : undefined}
- role="option"
- onClick={onRun}
- onMouseDown={preventFocusSteal}
- onMouseMove={onActive}
- >
- {entry.thumbnailUrl ? (
- <chakra.img alt="" boxSize="7" flexShrink={0} objectFit="cover" rounded="sm" src={entry.thumbnailUrl} />
- ) : null}
- <Text fontSize="sm" truncate>
- {renderTitle(entry.title, matchIndexes)}
- </Text>
- {entry.subtitle === 'Current' ? (
- <Icon as={CheckIcon} boxSize="3.5" color="fg.muted" flexShrink={0} />
- ) : entry.subtitle ? (
- <Text color="fg.subtle" flexShrink={0} fontSize="xs" maxW="45%" truncate>
- {entry.subtitle}
- </Text>
- ) : null}
- <Spacer />
- {entry.keys ? (
- <HStack flexShrink={0} gap="0.5">
- {entry.keys.map((part) => (
- <Kbd key={part} size="sm" textTransform="lowercase">
- {part}
- </Kbd>
- ))}
- </HStack>
- ) : null}
- </HStack>
-);
-
-const ScopeRow = ({
- id,
- isActive,
- label,
- onActive,
- onRun,
-}: {
- id: string;
- isActive: boolean;
- label: string;
- onActive: () => void;
- onRun: () => void;
-}) => (
- <HStack
- {...rowButtonProps}
- id={id}
- aria-selected={isActive}
- bg={isActive ? 'bg.emphasized' : undefined}
- role="option"
- onClick={onRun}
- onMouseDown={preventFocusSteal}
- onMouseMove={onActive}
- >
- <Text color="fg.muted" fontSize="sm" truncate>
- {label}
- </Text>
- <Spacer />
- <Kbd size="sm" textTransform="lowercase">
- tab
- </Kbd>
- </HStack>
-);
-
-const VirtualPaletteRow = ({
- activeIndex,
- measureElement,
- rows,
- virtualIndex,
- virtualStart,
- onActiveIndexChange,
- onRunRow,
-}: {
- activeIndex: number;
- measureElement: (node: Element | null) => void;
- rows: PaletteRow[];
- virtualIndex: number;
- virtualStart: number;
- onActiveIndexChange: (index: number) => void;
- onRunRow: (row: PaletteRow) => void;
-}) => {
- const row = rows[virtualIndex];
- const onActive = useCallback(() => onActiveIndexChange(virtualIndex), [onActiveIndexChange, virtualIndex]);
- const onRun = useCallback(() => row && onRunRow(row), [onRunRow, row]);
-
- if (!row) {
- return null;
- }
-
- const isActive = virtualIndex === activeIndex;
-
- return (
- <Box
- ref={measureElement}
- data-index={virtualIndex}
- left="0"
- position="absolute"
- top="0"
- transform={`translateY(${virtualStart}px)`}
- w="full"
- >
- {row.kind === 'label' ? (
- <Text css={dropdownGroupLabel} pb="1" pt="2" px="3" role="presentation">
- {row.label}
- </Text>
- ) : row.kind === 'scope' ? (
- <ScopeRow
- id={getRowDomId(virtualIndex)}
- isActive={isActive}
- label={row.label}
- onActive={onActive}
- onRun={onRun}
- />
- ) : (
- <EntryRow
- id={getRowDomId(virtualIndex)}
- entry={row.entry}
- isActive={isActive}
- matchIndexes={row.matchIndexes}
- onActive={onActive}
- onRun={onRun}
- />
- )}
- </Box>
- );
-};
const FooterHint = ({ children, keys }: { children: string; keys: string[] }) => (
<HStack gap="1">
@@ -273,14 +34,22 @@ const FooterHint = ({ children, keys }: { children: string; keys: string[] }) =>
</HStack>
);
+const StagePreviewLifetime = ({ stage }: { stage: PaletteStage }) => {
+ useMountEffect(() => stage.clearPreview);
+
+ return null;
+};
+
export const CommandPaletteDialog = ({
entries,
isOpen,
+ modifierKeyLabel,
onClose,
providers = NO_PROVIDERS,
}: {
entries: PaletteEntry[];
isOpen: boolean;
+ modifierKeyLabel: string;
onClose: () => void;
providers?: PaletteSearchProvider[];
}) => {
@@ -302,368 +71,87 @@ export const CommandPaletteDialog = ({
unmountOnExit
onOpenChange={onDialogOpenChange}
>
- {isOpen ? <CommandPaletteContent entries={entries} providers={providers} onClose={onClose} /> : null}
+ {isOpen ? (
+ <CommandPaletteContent
+ entries={entries}
+ modifierKeyLabel={modifierKeyLabel}
+ providers={providers}
+ onClose={onClose}
+ />
+ ) : null}
</Dialog.Root>
);
};
+export default CommandPaletteDialog;
+
const CommandPaletteContent = ({
entries,
+ modifierKeyLabel,
onClose,
providers,
}: {
entries: PaletteEntry[];
+ modifierKeyLabel: string;
onClose: () => void;
providers: PaletteSearchProvider[];
}) => {
- const [query, setQuery] = useState('');
- const [activeIndex, setActiveIndex] = useState(-1);
- const [stage, setStage] = useState<PaletteStage | null>(null);
- const [scopeProviderId, setScopeProviderId] = useState<string | null>(null);
- // Snapshot at open: recents should not reshuffle while the palette is up.
- const [recentIds] = useState(getRecentEntryIds);
- const [scrollElement, setScrollElement] = useState<HTMLDivElement | null>(null);
- const [inputElement, setInputElement] = useState<HTMLInputElement | null>(null);
-
- // Keyboard flow lives in the input; overlay transitions must never leave
- // focus stranded on an unmounted row or the retry button.
- useEffect(() => {
- inputElement?.focus();
- }, [inputElement, scopeProviderId, stage]);
-
- useMountEffect(() => registerHotkeyModalLayer('command-palette'));
-
- const scopeProvider = scopeProviderId ? (providers.find((p) => p.id === scopeProviderId) ?? null) : null;
- // '>' at position 0 is a courtesy alias for the Commands scope.
- const isCommandsScope = !stage && !scopeProvider && query.startsWith('>');
- const localQuery = isCommandsScope ? query.slice(1) : query;
- const trimmedQuery = localQuery.trim();
-
- const resetHighlight = useCallback(() => setActiveIndex(-1), []);
-
- const popOverlay = useCallback(() => {
- setStage(null);
- setScopeProviderId(null);
- setQuery('');
- setActiveIndex(-1);
- }, []);
-
- // --- Async entity providers -------------------------------------------
- const debouncedQuery = useDebouncedValue(trimmedQuery, PROVIDER_DEBOUNCE_MS);
- const shouldSearchProviders = debouncedQuery.length >= PROVIDER_MIN_QUERY_LENGTH && !stage && !isCommandsScope;
- const activeProviders = useMemo(
- () => (stage || isCommandsScope ? NO_PROVIDERS : scopeProvider ? [scopeProvider] : providers),
- [isCommandsScope, providers, scopeProvider, stage]
- );
- // `combine` output is structurally shared by TanStack Query, so its
- // identity is stable across renders that change nothing — safe memo input.
- const providerResults = useQueries({
- combine: (results) =>
- results.map((result) => ({
- data: result.data,
- isError: result.isError,
- isFetching: result.isFetching,
- refetch: result.refetch,
- })),
- queries: activeProviders.map((provider) => ({
- enabled: shouldSearchProviders,
- queryFn: () => Promise.resolve(provider.search(debouncedQuery)),
- queryKey: ['command-palette', provider.id, debouncedQuery],
- retry: false,
- staleTime: 30_000,
- })),
- });
- const providerSections = useMemo<ProviderResultSection[]>(
- () =>
- activeProviders.map((provider, index) => ({
- entries: providerResults[index]?.data ?? [],
- isFetching: shouldSearchProviders && (providerResults[index]?.isFetching ?? false),
- provider,
- })),
- [activeProviders, providerResults, shouldSearchProviders]
- );
- const scopedQueryResult = scopeProvider ? providerResults[0] : undefined;
-
- // --- Row assembly ------------------------------------------------------
- const onStageApplied = useCallback(() => popOverlay(), [popOverlay]);
-
- const rows = useMemo<PaletteRow[]>(() => {
- if (stage) {
- return searchPaletteRows(buildStageEntries(stage, onStageApplied), query, [], { showAllOnEmpty: true });
- }
-
- if (scopeProvider) {
- return buildProviderSectionRows(providerSections, null);
- }
-
- const localRows = searchPaletteRows(entries, localQuery, recentIds, { commandsOnly: isCommandsScope });
-
- if (trimmedQuery.length === 0 || isCommandsScope) {
- return localRows;
- }
-
- return [
- ...localRows,
- ...(trimmedQuery.length >= PROVIDER_MIN_QUERY_LENGTH ? buildProviderSectionRows(providerSections) : []),
- ...buildScopeRows(providers, trimmedQuery),
- ];
- }, [
- entries,
- isCommandsScope,
- localQuery,
- onStageApplied,
- providers,
- providerSections,
- query,
- recentIds,
- scopeProvider,
- stage,
- trimmedQuery,
- ]);
- const navigableRowIndexes = useMemo(
- () => rows.flatMap((row, index) => (row.kind === 'label' ? [] : [index])),
- [rows]
- );
- // The highlight always lands on a navigable row; -1 (or a stale index after
- // a query change) resolves to the first hit so Enter runs the top result.
- const effectiveActiveIndex = navigableRowIndexes.includes(activeIndex) ? activeIndex : (navigableRowIndexes[0] ?? -1);
- const activeRow = effectiveActiveIndex === -1 ? undefined : rows[effectiveActiveIndex];
-
- // --- Stage preview -----------------------------------------------------
- // Leaving a previewing stage always changes `stage` (pop sets it null, close
- // unmounts), so this cleanup reverts the preview on every exit path. A pick
- // persists first, making the revert an idempotent no-op.
- useEffect(() => {
- if (!stage?.clearPreview) {
- return;
- }
-
- return stage.clearPreview;
- }, [stage]);
-
- // Preview follows the highlight, including the first match while typing.
- useEffect(() => {
- if (!stage?.preview || activeRow?.kind !== 'entry' || !activeRow.entry.id.startsWith(STAGE_ENTRY_ID_PREFIX)) {
- return;
- }
-
- stage.preview(activeRow.entry.id.slice(STAGE_ENTRY_ID_PREFIX.length));
- }, [activeRow, stage]);
-
- const estimateRowSize = useCallback(
- (index: number) => (rows[index]?.kind === 'label' ? LABEL_ROW_HEIGHT_PX : ENTRY_ROW_HEIGHT_PX),
- [rows]
- );
- const getRowKey = useCallback((index: number) => rows[index]?.id ?? index, [rows]);
- const getScrollElement = useCallback(() => scrollElement, [scrollElement]);
-
- const virtualizer = useVirtualizer({
- count: rows.length,
- estimateSize: estimateRowSize,
- getItemKey: getRowKey,
- getScrollElement,
- initialRect: VIRTUALIZER_INITIAL_RECT,
- overscan: 8,
- });
-
- // --- Execution ---------------------------------------------------------
- const enterScope = useCallback((providerId: string) => {
- setScopeProviderId(providerId);
- setActiveIndex(-1);
- }, []);
-
- const runRow = useCallback(
- (row: PaletteRow) => {
- if (row.kind === 'label') {
- return;
- }
-
- if (row.kind === 'scope') {
- enterScope(row.providerId);
- return;
- }
-
- recordRecentEntry(row.entry.id);
-
- if (row.entry.stage) {
- setStage(row.entry.stage);
- setQuery('');
- // Land the highlight on the current value (+1 skips the single group
- // label row) — matches native pickers, and keeps a previewing stage
- // from flashing the first option's preview on open.
- const currentIndex = row.entry.stage.options.findIndex((option) => option.isCurrent);
- setActiveIndex(currentIndex === -1 ? -1 : currentIndex + 1);
- return;
- }
-
- if (row.entry.keepOpen) {
- void row.entry.run();
- return;
- }
-
- // Close first so command side effects (focus, navigation, widget
- // placement) land in a palette-free world.
- onClose();
- void row.entry.run();
- },
- [enterScope, onClose]
- );
-
- const runSecondary = useCallback(
- (entry: PaletteEntry) => {
- if (!entry.secondary) {
- return;
- }
-
- recordRecentEntry(entry.id);
- onClose();
- void entry.secondary.run();
- },
- [onClose]
- );
-
- const moveActive = useCallback(
- (offset: number) => {
- if (navigableRowIndexes.length === 0) {
- return;
- }
-
- const position = navigableRowIndexes.indexOf(effectiveActiveIndex);
- const nextPosition =
- Math.abs(offset) === 1
- ? (position + offset + navigableRowIndexes.length) % navigableRowIndexes.length
- : Math.min(Math.max(position + offset, 0), navigableRowIndexes.length - 1);
- const nextIndex = navigableRowIndexes[nextPosition];
-
- if (nextIndex === undefined) {
- return;
- }
-
- setActiveIndex(nextIndex);
- virtualizer.scrollToIndex(nextIndex, { align: 'auto' });
- },
- [effectiveActiveIndex, navigableRowIndexes, virtualizer]
- );
-
- // The dialog owns Esc entirely (closeOnEscape is off so Ark's dismiss
- // listener cannot race the overlay pop): pop the stage/scope first, close
- // only from the root state.
- const onEscape = useCallback(() => {
- if (stage || scopeProviderId) {
- popOverlay();
- return;
- }
-
- onClose();
- }, [onClose, popOverlay, scopeProviderId, stage]);
-
- const onContentKeyDown = useCallback(
- (event: KeyboardEvent<HTMLDivElement>) => {
- if (event.key === 'Escape') {
- event.preventDefault();
- event.stopPropagation();
- onEscape();
- }
- },
- [onEscape]
- );
-
+ const controller = useCommandPaletteController({ entries, onClose, providers });
+ const rowsRef = useRef<CommandPaletteRowsHandle>(null);
+ const modEnterHintKeys = useMemo(() => [modifierKeyLabel, '↵'], [modifierKeyLabel]);
const onSearchKeyDown = useCallback(
- (event: KeyboardEvent<HTMLInputElement>) => {
- if (event.key === 'ArrowDown') {
- event.preventDefault();
- moveActive(1);
- } else if (event.key === 'ArrowUp') {
- event.preventDefault();
- moveActive(-1);
- } else if (event.key === 'PageDown') {
- event.preventDefault();
- moveActive(PAGE_JUMP_ROWS);
- } else if (event.key === 'PageUp') {
- event.preventDefault();
- moveActive(-PAGE_JUMP_ROWS);
- } else if (event.key === 'Tab') {
- event.preventDefault();
-
- if (activeRow?.kind === 'scope') {
- enterScope(activeRow.providerId);
- }
- } else if (event.key === 'Backspace' && query.length === 0 && (stage || scopeProviderId)) {
- event.preventDefault();
- popOverlay();
- } else if (event.key === 'Enter') {
- event.preventDefault();
-
- if (!activeRow) {
- return;
- }
-
- if ((event.metaKey || event.ctrlKey) && activeRow.kind === 'entry' && activeRow.entry.secondary) {
- runSecondary(activeRow.entry);
- return;
- }
-
- runRow(activeRow);
- }
- },
- [activeRow, enterScope, moveActive, popOverlay, query.length, runRow, runSecondary, scopeProviderId, stage]
- );
-
- const onSearchChange = useCallback(
- (event: ChangeEvent<HTMLInputElement>) => {
- setQuery(event.currentTarget.value);
- resetHighlight();
- },
- [resetHighlight]
+ (event: React.KeyboardEvent<HTMLInputElement>) =>
+ controller.onSearchKeyDown(event, (index) => rowsRef.current?.scrollToIndex(index)),
+ [controller]
);
- // --- Rendering ---------------------------------------------------------
- const retryScopedSearch = useCallback(() => void scopedQueryResult?.refetch(), [scopedQueryResult]);
-
- const chipLabel = stage ? stage.title : (scopeProvider?.label ?? null);
- const placeholder = stage
- ? 'Pick a value…'
- : scopeProvider
- ? `Search ${scopeProvider.label.toLowerCase()}…`
- : 'Search commands, settings, and more…';
-
let emptyState: ReactNode = null;
- if (rows.length === 0) {
- if (scopeProvider && scopedQueryResult?.isError) {
+ if (controller.rows.length === 0) {
+ if (controller.scopeIsError && controller.scopeErrorLabel) {
emptyState = (
- <EmptyState danger py="6" title={`Couldn't search ${scopeProvider.label.toLowerCase()}`}>
- <Button size="xs" variant="subtle" onClick={retryScopedSearch}>
+ <EmptyState danger py="6" title={`Couldn't search ${controller.scopeErrorLabel}`}>
+ <Button size="xs" variant="subtle" onClick={controller.onRetry}>
Retry
</Button>
</EmptyState>
);
- } else if (scopeProvider && trimmedQuery.length < PROVIDER_MIN_QUERY_LENGTH) {
- emptyState = <EmptyState py="6" title={`Keep typing to search ${scopeProvider.label.toLowerCase()}`} />;
- } else if (scopeProvider && scopedQueryResult?.isFetching) {
+ } else if (controller.scopeErrorLabel && controller.trimmedQuery.length < PROVIDER_MIN_QUERY_LENGTH) {
+ emptyState = <EmptyState py="6" title={`Keep typing to search ${controller.scopeErrorLabel}`} />;
+ } else if (controller.scopeErrorLabel && controller.scopeIsFetching) {
emptyState = <EmptyState py="6" title="Searching…" />;
} else {
- emptyState = <EmptyState py="6" title={`No results for “${trimmedQuery}”`} />;
+ emptyState = <EmptyState py="6" title={`No results for “${controller.trimmedQuery}”`} />;
}
}
- const hasScopeRows = rows.some((row) => row.kind === 'scope');
- const secondaryHint = activeRow?.kind === 'entry' ? activeRow.entry.secondary?.label : undefined;
-
return (
<Portal>
+ {controller.stage?.clearPreview ? <StagePreviewLifetime stage={controller.stage} /> : null}
<Dialog.Backdrop bg="blackAlpha.300" />
<Dialog.Positioner alignItems="flex-start" pt="15vh">
<Dialog.Content
maxW="none"
overflow="hidden"
+ overscrollBehavior="contain"
p="0"
w="min(560px, calc(100vw - 32px))"
- onKeyDown={onContentKeyDown}
+ onKeyDown={controller.onContentKeyDown}
>
- <HStack borderBottomWidth="1px" borderColor="border.emphasized" flexShrink={0} gap="2.5" h="12" px="3">
+ <Dialog.Title srOnly>Command palette</Dialog.Title>
+ <HStack
+ borderBottomWidth="1px"
+ borderColor="border.emphasized"
+ flexShrink={0}
+ gap="2.5"
+ h="12"
+ outline="2px solid transparent"
+ outlineOffset="-2px"
+ px="3"
+ _focusWithin={INPUT_FOCUS_WITHIN_STYLE}
+ >
<Icon as={SearchIcon} boxSize="4" color="fg.muted" flexShrink={0} />
- {chipLabel ? (
+ {controller.chipLabel ? (
<Text
bg="bg.emphasized"
borderRadius="sm"
@@ -674,14 +162,20 @@ const CommandPaletteContent = ({
px="1.5"
py="0.5"
>
- {chipLabel}
+ {controller.chipLabel}
</Text>
) : null}
<chakra.input
- ref={setInputElement}
+ ref={controller.setInputElement}
+ autoComplete="off"
autoFocus
- aria-activedescendant={effectiveActiveIndex === -1 ? undefined : getRowDomId(effectiveActiveIndex)}
- aria-controls={RESULT_LIST_ID}
+ name="command-palette-query"
+ spellCheck={false}
+ type="search"
+ aria-activedescendant={
+ controller.activeRowId ? getCommandPaletteRowDomId(controller.activeRowId) : undefined
+ }
+ aria-controls="command-palette-results"
aria-expanded="true"
aria-label="Search commands and settings"
bg="transparent"
@@ -689,41 +183,25 @@ const CommandPaletteContent = ({
flex="1"
fontSize="sm"
outline="none"
- placeholder={placeholder}
+ placeholder={controller.placeholder}
role="combobox"
- value={query}
+ value={controller.query}
w="full"
_placeholder={INPUT_PLACEHOLDER_STYLE}
- onChange={onSearchChange}
+ onChange={controller.onSearchChange}
onKeyDown={onSearchKeyDown}
/>
</HStack>
- {rows.length === 0 ? (
+ {controller.rows.length === 0 ? (
emptyState
) : (
- <ScrollArea.Root maxH="min(400px, 55dvh)" size="xs" variant="hover" w="full">
- <ScrollArea.Viewport ref={setScrollElement} aria-label="Command palette results" maxH="inherit" w="full">
- <ScrollArea.Content id={RESULT_LIST_ID} pb="1.5" role="listbox" w="full">
- <Box h={`${virtualizer.totalSize}px`} position="relative" w="full">
- {virtualizer.virtualItems.map((virtualRow) => (
- <VirtualPaletteRow
- key={virtualRow.key}
- activeIndex={effectiveActiveIndex}
- measureElement={virtualizer.measureElement}
- rows={rows}
- virtualIndex={virtualRow.index}
- virtualStart={virtualRow.start}
- onActiveIndexChange={setActiveIndex}
- onRunRow={runRow}
- />
- ))}
- </Box>
- </ScrollArea.Content>
- </ScrollArea.Viewport>
- <ScrollArea.Scrollbar>
- <ScrollArea.Thumb />
- </ScrollArea.Scrollbar>
- </ScrollArea.Root>
+ <CommandPaletteRows
+ ref={rowsRef}
+ activeRowId={controller.activeRowId}
+ rows={controller.rows}
+ onActive={controller.onRowActive}
+ onRun={controller.onRowRun}
+ />
)}
<HStack
borderColor="border.emphasized"
@@ -737,11 +215,15 @@ const CommandPaletteContent = ({
px="3"
>
<FooterHint keys={NAV_HINT_KEYS}>Navigate</FooterHint>
- <FooterHint keys={ENTER_HINT_KEYS}>{stage ? 'Pick' : 'Run'}</FooterHint>
- {secondaryHint ? <FooterHint keys={MOD_ENTER_HINT_KEYS}>{secondaryHint}</FooterHint> : null}
- {hasScopeRows || activeRow?.kind === 'scope' ? <FooterHint keys={TAB_HINT_KEYS}>Scope</FooterHint> : null}
+ <FooterHint keys={ENTER_HINT_KEYS}>{controller.stage ? 'Pick' : 'Run'}</FooterHint>
+ {controller.secondaryHint ? (
+ <FooterHint keys={modEnterHintKeys}>{controller.secondaryHint}</FooterHint>
+ ) : null}
+ {controller.hasScopeRows || controller.activeRow?.kind === 'scope' ? (
+ <FooterHint keys={TAB_HINT_KEYS}>Scope</FooterHint>
+ ) : null}
<Spacer />
- <FooterHint keys={ESC_HINT_KEYS}>{stage || scopeProviderId ? 'Back' : 'Close'}</FooterHint>
+ <FooterHint keys={ESC_HINT_KEYS}>{controller.isOverlayOpen ? 'Back' : 'Close'}</FooterHint>
</HStack>
</Dialog.Content>
</Dialog.Positioner>
diff --git a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteRows.tsx b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteRows.tsx
new file mode 100644
index 0000000000..af00671334
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteRows.tsx
@@ -0,0 +1,268 @@
+import type { ReactNode, Ref } from 'react';
+
+import { Box, HStack, Icon, Kbd, ScrollArea, Spacer, Text, chakra } from '@chakra-ui/react';
+import { dropdownGroupLabel } from '@theme/recipes';
+import { CheckIcon } from 'lucide-react';
+import { useCallback, useImperativeHandle, useState } from 'react';
+import { useVirtualizer } from 'react-hook-tanstack-virtual';
+
+import type { PaletteEntry, PaletteRow } from './entries';
+
+const RESULT_LIST_ID = 'command-palette-results';
+const LABEL_ROW_HEIGHT_PX = 26;
+const ENTRY_ROW_HEIGHT_PX = 40;
+const VIRTUALIZER_INITIAL_RECT = { height: 384, width: 0 };
+
+export const getCommandPaletteRowDomId = (rowId: string): string => `${RESULT_LIST_ID}-${encodeURIComponent(rowId)}`;
+
+const preventFocusSteal = (event: { preventDefault: () => void }) => event.preventDefault();
+
+const renderTitle = (title: string, matchIndexes?: readonly number[]): ReactNode => {
+ if (!matchIndexes || matchIndexes.length === 0) {
+ return title;
+ }
+
+ const matched = new Set(matchIndexes);
+ const segments: ReactNode[] = [];
+ let start = 0;
+
+ for (let index = 1; index <= title.length; index += 1) {
+ if (index === title.length || matched.has(index) !== matched.has(start)) {
+ const text = title.slice(start, index);
+
+ segments.push(
+ matched.has(start) ? (
+ <Text key={start} as="span" fontWeight="600">
+ {text}
+ </Text>
+ ) : (
+ text
+ )
+ );
+ start = index;
+ }
+ }
+
+ return segments;
+};
+
+const rowButtonProps = {
+ as: 'button',
+ cursor: 'pointer',
+ gap: '2.5',
+ h: `${ENTRY_ROW_HEIGHT_PX}px`,
+ px: '3',
+ rounded: 'sm',
+ tabIndex: -1,
+ textAlign: 'start',
+ w: 'full',
+} as const;
+
+const EntryRow = ({
+ domId,
+ entry,
+ isActive,
+ matchIndexes,
+ onActive,
+ onRun,
+}: {
+ domId: string;
+ entry: PaletteEntry;
+ isActive: boolean;
+ matchIndexes?: readonly number[];
+ onActive: () => void;
+ onRun: () => void;
+}) => (
+ <HStack
+ {...rowButtonProps}
+ id={domId}
+ aria-selected={isActive}
+ bg={isActive ? 'bg.emphasized' : undefined}
+ role="option"
+ onClick={onRun}
+ onMouseDown={preventFocusSteal}
+ onMouseMove={onActive}
+ >
+ {entry.thumbnailUrl ? (
+ <chakra.img alt="" boxSize="7" flexShrink={0} objectFit="cover" rounded="sm" src={entry.thumbnailUrl} />
+ ) : null}
+ <Text fontSize="sm" truncate>
+ {renderTitle(entry.title, matchIndexes)}
+ </Text>
+ {entry.subtitle === 'Current' ? (
+ <Icon as={CheckIcon} boxSize="3.5" color="fg.muted" flexShrink={0} />
+ ) : entry.subtitle ? (
+ <Text color="fg.subtle" flexShrink={0} fontSize="xs" maxW="45%" truncate>
+ {entry.subtitle}
+ </Text>
+ ) : null}
+ <Spacer />
+ {entry.keys ? (
+ <HStack flexShrink={0} gap="0.5">
+ {entry.keys.map((part) => (
+ <Kbd key={part} size="sm" textTransform="lowercase">
+ {part}
+ </Kbd>
+ ))}
+ </HStack>
+ ) : null}
+ </HStack>
+);
+
+const ScopeRow = ({
+ domId,
+ isActive,
+ label,
+ onActive,
+ onRun,
+}: {
+ domId: string;
+ isActive: boolean;
+ label: string;
+ onActive: () => void;
+ onRun: () => void;
+}) => (
+ <HStack
+ {...rowButtonProps}
+ id={domId}
+ aria-selected={isActive}
+ bg={isActive ? 'bg.emphasized' : undefined}
+ role="option"
+ onClick={onRun}
+ onMouseDown={preventFocusSteal}
+ onMouseMove={onActive}
+ >
+ <Text color="fg.muted" fontSize="sm" truncate>
+ {label}
+ </Text>
+ <Spacer />
+ <Kbd size="sm" textTransform="lowercase">
+ tab
+ </Kbd>
+ </HStack>
+);
+
+const VirtualPaletteRow = ({
+ activeRowId,
+ measureElement,
+ row,
+ virtualIndex,
+ virtualStart,
+ onActive,
+ onRun,
+}: {
+ activeRowId: string | null;
+ measureElement: (node: Element | null) => void;
+ row: PaletteRow;
+ virtualIndex: number;
+ virtualStart: number;
+ onActive: (rowId: string) => void;
+ onRun: (row: PaletteRow) => void;
+}) => {
+ const handleActive = useCallback(() => onActive(row.id), [onActive, row.id]);
+ const handleRun = useCallback(() => onRun(row), [onRun, row]);
+ const isActive = row.id === activeRowId;
+
+ return (
+ <Box
+ ref={measureElement}
+ data-index={virtualIndex}
+ left="0"
+ position="absolute"
+ top="0"
+ transform={`translateY(${virtualStart}px)`}
+ w="full"
+ >
+ {row.kind === 'label' ? (
+ <Text css={dropdownGroupLabel} pb="1" pt="2" px="3" role="presentation">
+ {row.label}
+ </Text>
+ ) : row.kind === 'scope' ? (
+ <ScopeRow
+ domId={getCommandPaletteRowDomId(row.id)}
+ isActive={isActive}
+ label={row.label}
+ onActive={handleActive}
+ onRun={handleRun}
+ />
+ ) : (
+ <EntryRow
+ domId={getCommandPaletteRowDomId(row.id)}
+ entry={row.entry}
+ isActive={isActive}
+ matchIndexes={row.matchIndexes}
+ onActive={handleActive}
+ onRun={handleRun}
+ />
+ )}
+ </Box>
+ );
+};
+
+export interface CommandPaletteRowsHandle {
+ scrollToIndex: (index: number) => void;
+}
+
+export const CommandPaletteRows = ({
+ activeRowId,
+ ref,
+ rows,
+ onActive,
+ onRun,
+}: {
+ activeRowId: string | null;
+ ref?: Ref<CommandPaletteRowsHandle>;
+ rows: PaletteRow[];
+ onActive: (rowId: string) => void;
+ onRun: (row: PaletteRow) => void;
+}) => {
+ const [scrollElement, setScrollElement] = useState<HTMLDivElement | null>(null);
+ const estimateRowSize = useCallback(
+ (index: number) => (rows[index]?.kind === 'label' ? LABEL_ROW_HEIGHT_PX : ENTRY_ROW_HEIGHT_PX),
+ [rows]
+ );
+ const getRowKey = useCallback((index: number) => rows[index]?.id ?? index, [rows]);
+ const getScrollElement = useCallback(() => scrollElement, [scrollElement]);
+ const virtualizer = useVirtualizer({
+ count: rows.length,
+ estimateSize: estimateRowSize,
+ getItemKey: getRowKey,
+ getScrollElement,
+ initialRect: VIRTUALIZER_INITIAL_RECT,
+ overscan: 8,
+ });
+
+ useImperativeHandle(ref, () => ({ scrollToIndex: (index) => virtualizer.scrollToIndex(index, { align: 'auto' }) }), [
+ virtualizer,
+ ]);
+
+ return (
+ <ScrollArea.Root maxH="min(400px, 55dvh)" size="xs" variant="hover" w="full">
+ <ScrollArea.Viewport ref={setScrollElement} aria-label="Command palette results" maxH="inherit" w="full">
+ <ScrollArea.Content id={RESULT_LIST_ID} pb="1.5" role="listbox" w="full">
+ <Box h={`${virtualizer.totalSize}px`} position="relative" w="full">
+ {virtualizer.virtualItems.map((virtualRow) => {
+ const row = rows[virtualRow.index];
+
+ return row ? (
+ <VirtualPaletteRow
+ key={virtualRow.key}
+ activeRowId={activeRowId}
+ measureElement={virtualizer.measureElement}
+ row={row}
+ virtualIndex={virtualRow.index}
+ virtualStart={virtualRow.start}
+ onActive={onActive}
+ onRun={onRun}
+ />
+ ) : null;
+ })}
+ </Box>
+ </ScrollArea.Content>
+ </ScrollArea.Viewport>
+ <ScrollArea.Scrollbar>
+ <ScrollArea.Thumb />
+ </ScrollArea.Scrollbar>
+ </ScrollArea.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsx b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsx
index 0c8d23fc4a..2c04ffcabf 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsx
@@ -1,106 +1,40 @@
-import { useCapabilities } from '@features/identity';
-import { useNavigate, useSearch } from '@tanstack/react-router';
-import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';
+import type { WorkbenchPreferences } from '@workbench/settings/contracts';
+
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
import { useWorkbenchPreferences } from '@workbench/settings/store';
-import { useEffect, useMemo } from 'react';
+import { lazy, Suspense } from 'react';
import { tinykeys } from 'tinykeys';
-import type { PaletteEntry } from './entries';
+import type { SettingsEntryDeps } from './entries';
-import { CommandPaletteDialog } from './CommandPaletteDialog';
-import { buildSettingsEntries } from './entries';
import { closeCommandPalette, commandPaletteStore, toggleCommandPalette } from './paletteStore';
import { SETTINGS_ENTRY_DEPS } from './settingsEntryDeps';
-/**
- * Launchpad host: the editor's hotkey runtime is not mounted here, so this
- * host binds mod+K itself. The source set is deliberately reduced — section
- * navigation and settings only; editor commands need an editor mount. A mod+K
- * that works "sometimes" trains users not to trust it.
- */
+const LazyLaunchpadCommandPaletteDialog = lazy(() => import('./LaunchpadCommandPaletteDialog'));
+/** Lightweight Launchpad runtime and lazy dialog host. */
export const LaunchpadCommandPalette = () => {
const isOpen = commandPaletteStore.useSelector((snapshot) => snapshot.isOpen);
- const navigate = useNavigate();
- const search = useSearch({ strict: false }) as { project?: string };
const preferences = useWorkbenchPreferences();
- const { canManageModels, canManageNodes, canManageUsers } = useCapabilities();
-
- useEffect(
- () =>
- tinykeys(window, {
- // preventDefault beats Firefox's Ctrl+K address-bar search; macOS has
- // no browser binding on Cmd+K.
- '$mod+KeyK': (event) => {
- event.preventDefault();
- toggleCommandPalette();
- },
- }),
- []
- );
- const entries = useMemo<PaletteEntry[]>(() => {
- const navigation: PaletteEntry[] = [
- {
- group: 'Navigation',
- id: 'launchpad.openEditor',
- keywords: 'workbench app project',
- run: () => void navigate({ search: search.project ? { project: search.project } : {}, to: '/app' }),
- showInEmptyState: true,
- title: 'Open Editor',
- },
- {
- group: 'Navigation',
- id: 'launchpad.goToProjects',
- run: () => void navigate({ to: '/projects' }),
- showInEmptyState: true,
- title: 'Go to Projects',
+ useMountEffect(() =>
+ tinykeys(window, {
+ '$mod+KeyK': (event) => {
+ event.preventDefault();
+ toggleCommandPalette();
},
- ...(canManageModels
- ? [
- {
- group: 'Navigation',
- id: 'launchpad.goToModels',
- run: () => void navigate({ to: '/models' }),
- showInEmptyState: true,
- title: 'Go to Models',
- },
- ]
- : []),
- ...(canManageNodes
- ? [
- {
- group: 'Navigation',
- id: 'launchpad.goToNodes',
- run: () => void navigate({ to: '/nodes' }),
- showInEmptyState: true,
- title: 'Go to Nodes',
- },
- ]
- : []),
- ...(canManageUsers
- ? [
- {
- group: 'Navigation',
- id: 'launchpad.goToUsers',
- run: () => void navigate({ to: '/users' }),
- showInEmptyState: true,
- title: 'Go to Users',
- },
- ]
- : []),
- {
- group: 'App',
- id: 'app.openSettings',
- keywords: 'preferences options',
- run: () => openWorkbenchSettings(),
- showInEmptyState: true,
- title: 'Open Settings',
- },
- ];
-
- return [...navigation, ...buildSettingsEntries(preferences, SETTINGS_ENTRY_DEPS)];
- }, [canManageModels, canManageNodes, canManageUsers, navigate, preferences, search.project]);
+ })
+ );
- return <CommandPaletteDialog entries={entries} isOpen={isOpen} onClose={closeCommandPalette} />;
+ return isOpen ? (
+ <Suspense fallback={null}>
+ <LazyLaunchpadCommandPaletteDialog
+ preferences={preferences as WorkbenchPreferences}
+ modifierKeyLabel={formatHotkeyForPlatform('mod')[0] ?? 'ctrl'}
+ settingsEntryDeps={SETTINGS_ENTRY_DEPS as SettingsEntryDeps}
+ onClose={closeCommandPalette}
+ />
+ </Suspense>
+ ) : null;
};
diff --git a/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPaletteDialog.tsx b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPaletteDialog.tsx
new file mode 100644
index 0000000000..f646d2c954
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPaletteDialog.tsx
@@ -0,0 +1,101 @@
+import type { WorkbenchPreferences } from '@workbench/settings/contracts';
+
+import { useCapabilities } from '@features/identity';
+import { useNavigate, useSearch } from '@tanstack/react-router';
+import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';
+import { useMemo } from 'react';
+
+import type { PaletteEntry, SettingsEntryDeps } from './entries';
+
+import { CommandPaletteDialog } from './CommandPaletteDialog';
+import { buildSettingsEntries } from './entries';
+
+/** Launchpad-only palette adapter: navigation and settings, no editor providers. */
+const LaunchpadCommandPaletteDialog = ({
+ onClose,
+ modifierKeyLabel,
+ preferences,
+ settingsEntryDeps,
+}: {
+ onClose: () => void;
+ modifierKeyLabel: string;
+ preferences: WorkbenchPreferences;
+ settingsEntryDeps: SettingsEntryDeps;
+}) => {
+ const navigate = useNavigate();
+ const search = useSearch({ strict: false }) as { project?: string };
+ const { canManageModels, canManageNodes, canManageUsers } = useCapabilities();
+
+ const entries = useMemo<PaletteEntry[]>(() => {
+ const navigation: PaletteEntry[] = [
+ {
+ group: 'Navigation',
+ id: 'launchpad.openEditor',
+ isPersistentRecent: true,
+ keywords: 'workbench app project',
+ run: () => void navigate({ search: search.project ? { project: search.project } : {}, to: '/app' }),
+ showInEmptyState: true,
+ title: 'Open Editor',
+ },
+ {
+ group: 'Navigation',
+ id: 'launchpad.goToProjects',
+ isPersistentRecent: true,
+ run: () => void navigate({ to: '/projects' }),
+ showInEmptyState: true,
+ title: 'Go to Projects',
+ },
+ ...(canManageModels
+ ? [
+ {
+ group: 'Navigation',
+ id: 'launchpad.goToModels',
+ isPersistentRecent: true,
+ run: () => void navigate({ to: '/models' }),
+ showInEmptyState: true,
+ title: 'Go to Models',
+ },
+ ]
+ : []),
+ ...(canManageNodes
+ ? [
+ {
+ group: 'Navigation',
+ id: 'launchpad.goToNodes',
+ isPersistentRecent: true,
+ run: () => void navigate({ to: '/nodes' }),
+ showInEmptyState: true,
+ title: 'Go to Nodes',
+ },
+ ]
+ : []),
+ ...(canManageUsers
+ ? [
+ {
+ group: 'Navigation',
+ id: 'launchpad.goToUsers',
+ isPersistentRecent: true,
+ run: () => void navigate({ to: '/users' }),
+ showInEmptyState: true,
+ title: 'Go to Users',
+ },
+ ]
+ : []),
+ {
+ group: 'App',
+ id: 'app.openSettings',
+ isPersistentRecent: true,
+ keywords: 'preferences options',
+ run: () => openWorkbenchSettings(),
+ showInEmptyState: true,
+ title: 'Open Settings',
+ },
+ ];
+
+ return [...navigation, ...buildSettingsEntries(preferences, settingsEntryDeps)];
+ }, [canManageModels, canManageNodes, canManageUsers, navigate, preferences, search.project, settingsEntryDeps]);
+
+ return <CommandPaletteDialog entries={entries} isOpen modifierKeyLabel={modifierKeyLabel} onClose={onClose} />;
+};
+
+export default LaunchpadCommandPaletteDialog;
diff --git a/invokeai/frontend/webv2/src/workbench/palette/PaletteButton.tsx b/invokeai/frontend/webv2/src/workbench/palette/PaletteButton.tsx
index 67590382ea..71460cd3f7 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/PaletteButton.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/PaletteButton.tsx
@@ -1,5 +1,6 @@
import { Icon } from '@chakra-ui/react';
-import { IconButton, Tooltip } from '@platform/ui';
+import { IconButton } from '@platform/ui/Button';
+import { Tooltip } from '@platform/ui/Tooltip';
import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
import { SearchIcon } from 'lucide-react';
diff --git a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsx b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsx
index cd3981aeb0..092769fb9a 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsx
+++ b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsx
@@ -1,194 +1,47 @@
-import { getQueueQueryScope } from '@features/queue/queries';
-import { requestQueueItemReveal } from '@features/queue/react';
-import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';
-import { getWorkbenchPreferences, useWorkbenchPreferences } from '@workbench/settings/store';
+import type { WorkbenchPreferences } from '@workbench/settings/contracts';
+
+import { getQueueQueryScope, getQueueReadModelOptions } from '@features/queue/queries';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { firstPartyHotkeyCatalog } from '@workbench/hotkeys/catalog';
+import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
+import { registerHotkeyModalLayer } from '@workbench/hotkeys/modalLayer';
+import { useWorkbenchPreferences } from '@workbench/settings/store';
import { openWidgetPlacement } from '@workbench/widgetPlacementCommands';
import { getWidgetsForRegion } from '@workbench/widgetRegistry';
-import { getProjectWidgetValues } from '@workbench/widgetState';
-import {
- useActiveProjectSelector,
- useWorkbenchCommands,
- useWorkbenchExtensions,
- useWorkbenchQueries,
-} from '@workbench/WorkbenchContext';
-import { useCallback, useMemo, useSyncExternalStore } from 'react';
+import { lazy, Suspense } from 'react';
-import type { PaletteEntry, PaletteSearchProvider } from './entries';
+import type { SettingsEntryDeps } from './entries';
-import { CommandPaletteDialog } from './CommandPaletteDialog';
-import { buildCatalogCommandEntries, buildSettingsEntries } from './entries';
-import {
- createBoardsProvider,
- createImagesProvider,
- createModelsProvider,
- createPromptHistoryProvider,
- createQueueItemsProvider,
- createWorkflowsProvider,
-} from './paletteProviders';
import { closeCommandPalette, commandPaletteStore } from './paletteStore';
import { SETTINGS_ENTRY_DEPS } from './settingsEntryDeps';
-/**
- * Editor host: aggregates the hotkey catalog, extension palette contributions,
- * and settings into the palette. Widget-scoped commands are filtered to widget
- * types present in the current layout, and execute through the contribution's
- * own source so widget handlers resolve exactly as they do for hotkeys.
- */
-
-const STATIC_APP_ENTRIES: PaletteEntry[] = [
- {
- group: 'App',
- id: 'app.openSettings',
- keywords: 'preferences options',
- run: () => openWorkbenchSettings(),
- showInEmptyState: true,
- title: 'Open Settings',
- },
- {
- group: 'App',
- id: 'app.openHotkeySettings',
- keywords: 'hotkeys keybindings shortcuts',
- run: () => openWorkbenchSettings('hotkeys'),
- title: 'Keyboard Shortcuts',
- },
-];
+const LazyWorkbenchCommandPaletteDialog = lazy(() => import('./WorkbenchCommandPaletteDialog'));
+/** Lightweight route host; the palette implementation is loaded only while open. */
export const WorkbenchCommandPalette = () => {
const isOpen = commandPaletteStore.useSelector((snapshot) => snapshot.isOpen);
- const extensions = useWorkbenchExtensions();
const preferences = useWorkbenchPreferences();
- const projectId = useActiveProjectSelector((project) => project.id);
- const presentWidgetTypeIds = useActiveProjectSelector((project) =>
- [...new Set(Object.values(project.widgetInstances).map((instance) => instance.typeId))].sort()
- );
- const paletteStore = extensions.stores.palette;
- const paletteContributions = useSyncExternalStore(paletteStore.subscribe, paletteStore.list, paletteStore.list);
-
- const executeCommand = useCallback(
- (commandId: string) => {
- // Widget handlers register with a source; reuse it so scoped commands
- // resolve, falling back to the sourceless (global) registration.
- const contribution = extensions.stores.commands.findLatest(
- (candidate) => candidate.id === commandId && (!candidate.source || candidate.source.projectId === projectId)
- );
- return extensions.commands.executeForSource(commandId, contribution?.source ?? null);
- },
- [extensions, projectId]
- );
+ return isOpen ? <OpenWorkbenchCommandPalette preferences={preferences} /> : null;
+};
- const entries = useMemo<PaletteEntry[]>(
- () => [
- ...buildCatalogCommandEntries({
- customHotkeys: preferences.customHotkeys,
- execute: executeCommand,
- presentWidgetTypeIds: new Set(presentWidgetTypeIds),
- }),
- ...paletteContributions.map<PaletteEntry>((contribution) => ({
- group: 'Commands',
- id: `palette:${contribution.commandId}`,
- keywords: contribution.keywords?.join(' '),
- run: () => extensions.commands.executeForSource(contribution.commandId, contribution.source ?? null),
- title: contribution.title,
- })),
- ...STATIC_APP_ENTRIES,
- ...buildSettingsEntries(preferences, SETTINGS_ENTRY_DEPS),
- ],
- [executeCommand, extensions, paletteContributions, preferences, presentWidgetTypeIds]
+const OpenWorkbenchCommandPalette = ({ preferences }: { preferences: WorkbenchPreferences }) => {
+ useMountEffect(() => registerHotkeyModalLayer('command-palette'));
+
+ return (
+ <Suspense fallback={null}>
+ <LazyWorkbenchCommandPaletteDialog
+ catalog={firstPartyHotkeyCatalog}
+ formatHotkey={formatHotkeyForPlatform}
+ modifierKeyLabel={formatHotkeyForPlatform('mod')[0] ?? 'ctrl'}
+ getWidgetsForRegion={getWidgetsForRegion}
+ getQueueQueryScope={getQueueQueryScope}
+ getQueueReadModelOptions={getQueueReadModelOptions}
+ openWidgetPlacement={openWidgetPlacement}
+ preferences={preferences}
+ settingsEntryDeps={SETTINGS_ENTRY_DEPS as SettingsEntryDeps}
+ onClose={closeCommandPalette}
+ />
+ </Suspense>
);
-
- const workbenchCommands = useWorkbenchCommands();
- const queries = useWorkbenchQueries();
- const searchStore = extensions.stores.search;
- const extensionSearchProviders = useSyncExternalStore(searchStore.subscribe, searchStore.list, searchStore.list);
- const providers = useMemo<PaletteSearchProvider[]>(() => {
- const { gallery, widgets } = workbenchCommands;
- const openWidget = (typeId: 'workflow' | 'gallery' | 'generate' | 'preview' | 'queue') =>
- openWidgetPlacement({
- getWidgetsForRegion,
- options:
- typeId === 'workflow'
- ? { preferredRegions: ['center'], requireCenterView: true }
- : typeId === 'generate'
- ? { preferredRegions: ['left'] }
- : typeId === 'queue'
- ? { preferredRegions: ['right'] }
- : { preferredRegions: ['center', 'right'] },
- typeId,
- widgets,
- });
-
- return [
- createWorkflowsProvider({ openWorkflowWidget: () => openWidget('workflow') }),
- createBoardsProvider({
- openGalleryWidget: () => openWidget('gallery'),
- selectBoard: (boardId) => gallery.selectBoard(boardId),
- }),
- createModelsProvider({
- // The same values patch image recall uses for its model fallback; the
- // generate widget's normalize/sync pass reconciles dependent settings.
- applyModel: (model) =>
- widgets.patchValues('generate', { model, modelKey: model.key }, queries.getSnapshot().activeProject.id),
- openGenerateWidget: () => openWidget('generate'),
- openModelManager: () => void executeCommand('app.selectModelsTab'),
- }),
- createImagesProvider({
- getSelectedBoardId: () => {
- const boardId = getProjectWidgetValues(queries.getSnapshot().activeProject, 'gallery').selectedBoardId;
-
- return typeof boardId === 'string' ? boardId : 'none';
- },
- openGalleryWidget: () => openWidget('gallery'),
- openPreviewWidget: () => openWidget('preview'),
- selectBoard: (boardId) => gallery.selectBoard(boardId),
- selectImage: (image) => gallery.selectImage(image),
- }),
- createQueueItemsProvider({
- // Scope must be read at search time — the jobs-scope pref is itself
- // editable from the palette.
- getScope: () =>
- getQueueQueryScope({
- projectId: queries.getSnapshot().activeProject.id,
- queueJobsScope: getWorkbenchPreferences().queueJobsScope,
- }),
- openQueueWidget: () => openWidget('queue'),
- revealItem: (itemId) => requestQueueItemReveal(itemId),
- }),
- createPromptHistoryProvider({
- getPromptHistory: () => queries.getSnapshot().activeProject.promptHistory,
- openGenerateWidget: () => openWidget('generate'),
- recallPrompt: (item) => {
- const project = queries.getSnapshot().activeProject;
- const patch: Record<string, unknown> = { positivePrompt: item.positivePrompt };
-
- if (item.negativePrompt) {
- patch.negativePrompt = item.negativePrompt;
- patch.negativePromptEnabled = true;
- }
-
- widgets.patchValues('generate', patch, project.id);
- },
- }),
- ...extensionSearchProviders.map<PaletteSearchProvider>((provider) => ({
- id: `ext:${provider.id}`,
- label: provider.label,
- search: async (query) => {
- const results = await provider.search(query);
-
- return results.map<PaletteEntry>((result) => ({
- group: provider.label,
- id: `ext:${provider.id}:${result.id}`,
- run: () =>
- result.commandId
- ? extensions.commands.executeForSource(result.commandId, provider.source ?? null, result.id)
- : undefined,
- subtitle: result.subtitle,
- title: result.title,
- }));
- },
- })),
- ];
- }, [executeCommand, extensions, extensionSearchProviders, queries, workbenchCommands]);
-
- return <CommandPaletteDialog entries={entries} isOpen={isOpen} providers={providers} onClose={closeCommandPalette} />;
};
diff --git a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx
new file mode 100644
index 0000000000..e46f7357ff
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPaletteDialog.tsx
@@ -0,0 +1,226 @@
+import type {
+ getQueueQueryScope as GetQueueQueryScope,
+ getQueueReadModelOptions as GetQueueReadModelOptions,
+} from '@features/queue/queries';
+import type { HotkeyDefinition } from '@workbench/hotkeys/types';
+import type { WorkbenchPreferences } from '@workbench/settings/contracts';
+import type { openWidgetPlacement as OpenWidgetPlacement } from '@workbench/widgetPlacementCommands';
+import type { getWidgetsForRegion as GetWidgetsForRegion } from '@workbench/widgetRegistry';
+
+import { getPromptHistoryRecallPatch } from '@features/generation/settings';
+import { useModelsSnapshot } from '@features/models';
+import { requestQueueItemReveal } from '@features/queue/reveal';
+import { queryClient } from '@platform/query/client';
+import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';
+import { getProjectWidgetValues } from '@workbench/widgetState';
+import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchExtensions } from '@workbench/WorkbenchContext';
+import { useCallback, useMemo, useSyncExternalStore } from 'react';
+
+import type { PaletteEntry, PaletteSearchProvider, SettingsEntryDeps } from './entries';
+
+import { CommandPaletteDialog } from './CommandPaletteDialog';
+import { buildCatalogCommandEntries, buildSettingsEntries } from './entries';
+import { buildExtensionPaletteEntry, createExtensionSearchProvider } from './extensionPaletteAdapters';
+import {
+ createBoardsProvider,
+ createImagesProvider,
+ createModelsProvider,
+ createPromptHistoryProvider,
+ createQueueItemsProvider,
+ createWorkflowsProvider,
+} from './paletteProviders';
+
+const STATIC_APP_ENTRIES: PaletteEntry[] = [
+ {
+ group: 'App',
+ id: 'app.openSettings',
+ isPersistentRecent: true,
+ keywords: 'preferences options',
+ run: () => openWorkbenchSettings(),
+ showInEmptyState: true,
+ title: 'Open Settings',
+ },
+ {
+ group: 'App',
+ id: 'app.openHotkeySettings',
+ isPersistentRecent: true,
+ keywords: 'hotkeys keybindings shortcuts',
+ run: () => openWorkbenchSettings('hotkeys'),
+ title: 'Keyboard Shortcuts',
+ },
+];
+
+/** Editor-only palette adapter. This module is absent from the Launchpad chunk. */
+const WorkbenchCommandPaletteDialog = ({
+ catalog,
+ formatHotkey,
+ getQueueQueryScope,
+ getQueueReadModelOptions,
+ getWidgetsForRegion,
+ modifierKeyLabel,
+ onClose,
+ openWidgetPlacement,
+ preferences,
+ settingsEntryDeps,
+}: {
+ catalog: readonly HotkeyDefinition[];
+ formatHotkey: (key: string) => string[];
+ getQueueQueryScope: typeof GetQueueQueryScope;
+ getQueueReadModelOptions: typeof GetQueueReadModelOptions;
+ getWidgetsForRegion: typeof GetWidgetsForRegion;
+ modifierKeyLabel: string;
+ onClose: () => void;
+ openWidgetPlacement: typeof OpenWidgetPlacement;
+ preferences: WorkbenchPreferences;
+ settingsEntryDeps: SettingsEntryDeps;
+}) => {
+ const extensions = useWorkbenchExtensions();
+ 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 selectedBoardId = useActiveProjectSelector((project) => {
+ const boardId = getProjectWidgetValues(project, 'gallery').selectedBoardId;
+
+ return typeof boardId === 'string' ? boardId : 'none';
+ });
+ const presentWidgetTypeIds = useActiveProjectSelector((project) =>
+ [...new Set(Object.values(project.widgetInstances).map((instance) => instance.typeId))].sort()
+ );
+ const paletteStore = extensions.stores.palette;
+ const paletteContributions = useSyncExternalStore(paletteStore.subscribe, paletteStore.list, paletteStore.list);
+
+ const executeCommand = useCallback(
+ (commandId: string) => {
+ const contribution = extensions.stores.commands.findLatest(
+ (candidate) => candidate.id === commandId && (!candidate.source || candidate.source.projectId === projectId)
+ );
+
+ return extensions.commands.executeForSource(commandId, contribution?.source ?? null);
+ },
+ [extensions, projectId]
+ );
+
+ const entries = useMemo<PaletteEntry[]>(
+ () => [
+ ...buildCatalogCommandEntries({
+ customHotkeys: preferences.customHotkeys,
+ execute: executeCommand,
+ catalog,
+ formatHotkey,
+ presentWidgetTypeIds: new Set(presentWidgetTypeIds),
+ }),
+ ...paletteContributions.map((contribution) =>
+ buildExtensionPaletteEntry(contribution, extensions.commands.executeForSource)
+ ),
+ ...STATIC_APP_ENTRIES,
+ ...buildSettingsEntries(preferences, settingsEntryDeps),
+ ],
+ [
+ catalog,
+ executeCommand,
+ extensions,
+ formatHotkey,
+ paletteContributions,
+ preferences,
+ presentWidgetTypeIds,
+ settingsEntryDeps,
+ ]
+ );
+
+ const workbenchCommands = useWorkbenchCommands();
+ const searchStore = extensions.stores.search;
+ const extensionSearchProviders = useSyncExternalStore(searchStore.subscribe, searchStore.list, searchStore.list);
+ const promptRecallContextKey = useMemo(() => JSON.stringify([generateValues, models]), [generateValues, models]);
+ const queueScope = useMemo(
+ () => getQueueQueryScope({ projectId, queueJobsScope: preferences.queueJobsScope }),
+ [getQueueQueryScope, preferences.queueJobsScope, projectId]
+ );
+ const providers = useMemo<PaletteSearchProvider[]>(() => {
+ const { gallery, widgets } = workbenchCommands;
+ const openWidget = (typeId: 'workflow' | 'gallery' | 'generate' | 'preview' | 'queue') =>
+ openWidgetPlacement({
+ getWidgetsForRegion,
+ options:
+ typeId === 'workflow'
+ ? { preferredRegions: ['center'], requireCenterView: true }
+ : typeId === 'generate'
+ ? { preferredRegions: ['left'] }
+ : typeId === 'queue'
+ ? { preferredRegions: ['right'] }
+ : { preferredRegions: ['center', 'right'] },
+ typeId,
+ widgets,
+ });
+
+ return [
+ createWorkflowsProvider({ openWorkflowWidget: () => openWidget('workflow') }),
+ createBoardsProvider({
+ openGalleryWidget: () => openWidget('gallery'),
+ selectBoard: (boardId) => gallery.selectBoard(boardId),
+ }),
+ createModelsProvider({
+ applyModel: (model) => widgets.patchValues('generate', { model, modelKey: model.key }, projectId),
+ openGenerateWidget: () => openWidget('generate'),
+ openModelManager: () => void executeCommand('app.selectModelsTab'),
+ }),
+ createImagesProvider({
+ openGalleryWidget: () => openWidget('gallery'),
+ openPreviewWidget: () => openWidget('preview'),
+ selectedBoardId,
+ selectBoard: (boardId) => gallery.selectBoard(boardId),
+ selectImage: (image) => gallery.selectImage(image),
+ }),
+ createQueueItemsProvider({
+ contextKey: JSON.stringify(queueScope),
+ loadQueue: () => queryClient.fetchQuery(getQueueReadModelOptions(queueScope)),
+ openQueueWidget: () => openWidget('queue'),
+ revealItem: requestQueueItemReveal,
+ }),
+ createPromptHistoryProvider({
+ openGenerateWidget: () => openWidget('generate'),
+ projectId,
+ promptHistory,
+ recallContextKey: promptRecallContextKey,
+ recallPrompt: (item) => {
+ const patch = getPromptHistoryRecallPatch({ item, models, values: generateValues });
+
+ if (patch) {
+ widgets.patchValues('generate', patch, projectId);
+ }
+ },
+ }),
+ ...extensionSearchProviders.map((provider) =>
+ createExtensionSearchProvider(provider, extensions.commands.executeForSource)
+ ),
+ ];
+ }, [
+ executeCommand,
+ extensionSearchProviders,
+ extensions,
+ generateValues,
+ getWidgetsForRegion,
+ getQueueReadModelOptions,
+ models,
+ openWidgetPlacement,
+ projectId,
+ promptHistory,
+ promptRecallContextKey,
+ queueScope,
+ selectedBoardId,
+ workbenchCommands,
+ ]);
+
+ return (
+ <CommandPaletteDialog
+ entries={entries}
+ isOpen
+ modifierKeyLabel={modifierKeyLabel}
+ providers={providers}
+ onClose={onClose}
+ />
+ );
+};
+
+export default WorkbenchCommandPaletteDialog;
diff --git a/invokeai/frontend/webv2/src/workbench/palette/contributionKey.ts b/invokeai/frontend/webv2/src/workbench/palette/contributionKey.ts
new file mode 100644
index 0000000000..a42da7ed84
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/contributionKey.ts
@@ -0,0 +1,20 @@
+import type { WidgetContributionSource } from '@workbench/widgetContracts';
+
+/**
+ * Stable identity for every palette contribution. Widget source identity is
+ * part of the key so two instances may safely contribute the same local id.
+ * The source tuple intentionally mirrors getWidgetContributionSourceKey;
+ * keeping the palette helper self-contained prevents its lazy chunk from
+ * pulling extension registry internals into either route's initial graph.
+ */
+export const getPaletteContributionKey = (
+ kind: 'command' | 'provider' | 'provider-result' | 'provider-row' | 'scope',
+ id: string,
+ source?: WidgetContributionSource | null
+): string =>
+ JSON.stringify([
+ 'palette',
+ kind,
+ id,
+ source ? ['widget', source.projectId, source.region, source.typeId, source.instanceId] : 'global',
+ ]);
diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts
index bc4613502d..9bf6edf9ec 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts
@@ -1,8 +1,11 @@
+import { firstPartyHotkeyCatalog } from '@workbench/hotkeys/catalog';
+import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
import { DEFAULT_PREFERENCES } from '@workbench/settings/store';
import { describe, expect, it, vi } from 'vitest';
import type { PaletteEntry } from './entries';
+import { getPaletteContributionKey } from './contributionKey';
import {
buildCatalogCommandEntries,
buildProviderSectionRows,
@@ -10,6 +13,7 @@ import {
buildSettingsEntries,
buildStageEntries,
searchPaletteRows,
+ resolveActivePaletteRow,
} from './entries';
/**
@@ -20,15 +24,28 @@ import {
*/
const noop = () => undefined;
+const settingsEntryDeps = {
+ languageOptions: [{ label: 'English', value: 'en' as const }],
+ openSettingsSection: vi.fn(),
+ patchPreferences: vi.fn(),
+ themes: [{ id: 'classic' as const, label: 'Classic' }],
+};
const makeEntry = (overrides: Partial<PaletteEntry> & Pick<PaletteEntry, 'id' | 'title' | 'group'>): PaletteEntry => ({
+ isPersistentRecent: true,
run: noop,
...overrides,
});
describe('buildCatalogCommandEntries', () => {
const build = (presentWidgetTypeIds: ReadonlySet<string>, execute: (commandId: string) => unknown = noop) =>
- buildCatalogCommandEntries({ customHotkeys: {}, execute, presentWidgetTypeIds });
+ buildCatalogCommandEntries({
+ catalog: firstPartyHotkeyCatalog,
+ customHotkeys: {},
+ execute,
+ formatHotkey: formatHotkeyForPlatform,
+ presentWidgetTypeIds,
+ });
it('surfaces implemented app commands with palette-facing titles and groups', () => {
const entries = build(new Set());
@@ -60,8 +77,10 @@ describe('buildCatalogCommandEntries', () => {
it('formats the bound hotkey (custom overrides win) and executes by command id', () => {
const execute = vi.fn();
const entries = buildCatalogCommandEntries({
+ catalog: firstPartyHotkeyCatalog,
customHotkeys: { 'app.clearQueue': ['mod+shift+q'] },
execute,
+ formatHotkey: formatHotkeyForPlatform,
presentWidgetTypeIds: new Set(),
});
const invoke = entries.find((entry) => entry.id === 'app.invoke');
@@ -80,7 +99,7 @@ describe('buildSettingsEntries', () => {
const patchPreferences = vi.fn();
const entries = buildSettingsEntries(
{ ...DEFAULT_PREFERENCES, reduceMotion: false },
- { openSettingsSection: vi.fn(), patchPreferences }
+ { ...settingsEntryDeps, openSettingsSection: vi.fn(), patchPreferences }
);
const reduceMotion = entries.find((entry) => entry.id === 'setting.reduceMotion');
@@ -92,7 +111,11 @@ describe('buildSettingsEntries', () => {
it('deep-links enum preferences and sections to the settings dialog', () => {
const openSettingsSection = vi.fn();
- const entries = buildSettingsEntries(DEFAULT_PREFERENCES, { openSettingsSection, patchPreferences: vi.fn() });
+ const entries = buildSettingsEntries(DEFAULT_PREFERENCES, {
+ ...settingsEntryDeps,
+ openSettingsSection,
+ patchPreferences: vi.fn(),
+ });
const theme = entries.find((entry) => entry.id === 'setting.themeId');
const workflowSection = entries.find((entry) => entry.id === 'settings.section.workflow');
@@ -109,7 +132,7 @@ describe('buildSettingsEntries', () => {
const patchPreferences = vi.fn();
const entries = buildSettingsEntries(
{ ...DEFAULT_PREFERENCES, workflowEdgeStyle: 'curved' },
- { openSettingsSection: vi.fn(), patchPreferences }
+ { ...settingsEntryDeps, openSettingsSection: vi.fn(), patchPreferences }
);
const edgeStyle = entries.find((entry) => entry.id === 'setting.workflowEdgeStyle');
@@ -127,6 +150,7 @@ describe('buildSettingsEntries', () => {
const previewTheme = vi.fn();
const clearThemePreview = vi.fn();
const withPreview = buildSettingsEntries(DEFAULT_PREFERENCES, {
+ ...settingsEntryDeps,
clearThemePreview,
openSettingsSection: vi.fn(),
patchPreferences: vi.fn(),
@@ -140,6 +164,7 @@ describe('buildSettingsEntries', () => {
expect(clearThemePreview).toHaveBeenCalled();
const withoutPreview = buildSettingsEntries(DEFAULT_PREFERENCES, {
+ ...settingsEntryDeps,
openSettingsSection: vi.fn(),
patchPreferences: vi.fn(),
});
@@ -173,7 +198,7 @@ describe('provider row assembly', () => {
makeEntry({ group: id, id: `${id}:${index}`, title: `${id} ${index}` })
),
isFetching,
- provider: { id, label: id },
+ provider: { label: id, providerKey: id },
});
it('caps sections in root mode and drops empty settled sections', () => {
@@ -181,9 +206,9 @@ describe('provider row assembly', () => {
expect(rows.map((row) => row.id)).toEqual([
'label:provider:workflows',
- 'workflows:0',
- 'workflows:1',
- 'workflows:2',
+ getPaletteContributionKey('provider-row', 'workflows:workflows:0'),
+ getPaletteContributionKey('provider-row', 'workflows:workflows:1'),
+ getPaletteContributionKey('provider-row', 'workflows:workflows:2'),
]);
});
@@ -195,9 +220,9 @@ describe('provider row assembly', () => {
});
it('builds one trailing scope row per provider', () => {
- const rows = buildScopeRows([{ id: 'boards', label: 'Boards' }], 'sunset');
+ const rows = buildScopeRows([{ label: 'Boards', providerKey: 'boards' }], 'sunset');
- expect(rows[0]).toMatchObject({ kind: 'scope', label: 'Search boards for “sunset”', providerId: 'boards' });
+ expect(rows[0]).toMatchObject({ kind: 'scope', label: 'Search boards for “sunset”', providerKey: 'boards' });
});
});
@@ -256,4 +281,34 @@ describe('searchPaletteRows', () => {
expect(rows.map((row) => row.id)).not.toContain('setting.reduceMotion');
expect(rows.map((row) => row.id)).toContain('app.invoke');
});
+
+ it('lists every non-setting command for a bare commands scope', () => {
+ const rows = searchPaletteRows(entries, '', [], { commandsOnly: true, showAllOnEmpty: true });
+
+ expect(rows.filter((row) => row.kind === 'entry').map((row) => row.entry.id)).toEqual([
+ 'app.invoke',
+ 'app.invokeFront',
+ 'app.selectCanvasTab',
+ ]);
+ });
+});
+
+describe('stable active row identity', () => {
+ it('preserves the selected action when async rows are inserted before it', () => {
+ const selectedRun = vi.fn();
+ const selected = makeEntry({ group: 'Commands', id: 'selected', run: selectedRun, title: 'Selected' });
+ const initial = searchPaletteRows([selected], 'selected', []);
+ const withAsyncInsertion = [
+ { id: 'label:provider', kind: 'label' as const, label: 'Provider' },
+ { entry: makeEntry({ group: 'Provider', id: 'async', title: 'Async' }), id: 'async-row', kind: 'entry' as const },
+ ...initial,
+ ];
+ const active = resolveActivePaletteRow(withAsyncInsertion, 'selected');
+
+ expect(active?.row.id).toBe('selected');
+ if (active?.row.kind === 'entry') {
+ active.row.entry.run();
+ }
+ expect(selectedRun).toHaveBeenCalledOnce();
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.ts
index ac18ca54eb..2d2ab2fd5e 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/entries.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.ts
@@ -2,12 +2,10 @@ import type { CustomHotkeys, HotkeyDefinition } from '@workbench/hotkeys/types';
import type { WorkbenchPreferences } from '@workbench/settings/contracts';
import type { SettingsSectionId } from '@workbench/widgetContracts';
-import { WORKBENCH_LANGUAGE_OPTIONS } from '@platform/i18n/languages';
-import { THEMES, THEMES_BY_ID } from '@theme/themes';
-import { firstPartyHotkeyCatalog } from '@workbench/hotkeys/catalog';
-import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
import fuzzysort from 'fuzzysort';
+import { getPaletteContributionKey } from './contributionKey';
+
/**
* Palette content model: every source (catalog commands, extension palette
* contributions, settings, navigation) normalizes into `PaletteEntry`, and
@@ -50,6 +48,8 @@ export interface PaletteEntry {
keepOpen?: boolean;
/** Show in the empty-query launcher state (navigation entries). */
showInEmptyState?: boolean;
+ /** Durable entry whose stable id may be persisted in palette recents. */
+ isPersistentRecent: boolean;
/** Enter pushes this value-picker stage instead of running the entry. */
stage?: PaletteStage;
/** mod+Enter alternative, advertised in the footer while highlighted. */
@@ -59,7 +59,10 @@ export interface PaletteEntry {
/** An async entity source the palette can query (workflows, boards, …). */
export interface PaletteSearchProvider {
- id: string;
+ /** Globally unique, stable identity (including extension source identity). */
+ providerKey: string;
+ /** Immutable snapshot of every host value that can affect search results. */
+ contextKey: string;
label: string;
search: (query: string) => Promise<PaletteEntry[]> | PaletteEntry[];
}
@@ -67,7 +70,22 @@ export interface PaletteSearchProvider {
export type PaletteRow =
| { kind: 'label'; id: string; label: string }
| { kind: 'entry'; id: string; entry: PaletteEntry; matchIndexes?: readonly number[] }
- | { kind: 'scope'; id: string; providerId: string; label: string };
+ | { kind: 'scope'; id: string; providerKey: string; label: string };
+
+export interface ActivePaletteRow {
+ index: number;
+ row: Exclude<PaletteRow, { kind: 'label' }>;
+}
+
+/** Resolve selection by stable row id, falling back to the first actionable row. */
+export const resolveActivePaletteRow = (
+ rows: readonly PaletteRow[],
+ 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];
+};
/** Max rows an entity section shows in root mode; depth lives behind the scope. */
export const PROVIDER_ROOT_RESULT_CAP = 3;
@@ -165,21 +183,27 @@ const WIDGET_CATEGORY_GROUPS: Record<string, { group: string; typeId: string }>
workflows: { group: 'Workflows', typeId: 'workflow' },
};
-const getEntryKeys = (definition: HotkeyDefinition, customHotkeys: CustomHotkeys): string[] | undefined => {
+const getEntryKeys = (
+ definition: HotkeyDefinition,
+ customHotkeys: CustomHotkeys,
+ formatHotkey: (key: string) => string[]
+): string[] | undefined => {
const keys = customHotkeys[definition.id] ?? definition.defaultKeys;
- return keys[0] ? formatHotkeyForPlatform(keys[0]) : undefined;
+ return keys[0] ? formatHotkey(keys[0]) : undefined;
};
export const buildCatalogCommandEntries = ({
- catalog = firstPartyHotkeyCatalog,
+ catalog,
customHotkeys,
execute,
+ formatHotkey,
presentWidgetTypeIds,
}: {
- catalog?: HotkeyDefinition[];
+ catalog: readonly HotkeyDefinition[];
customHotkeys: CustomHotkeys;
execute: (commandId: string) => unknown;
+ formatHotkey: (key: string) => string[];
presentWidgetTypeIds: ReadonlySet<string>;
}): PaletteEntry[] =>
catalog
@@ -196,7 +220,8 @@ export const buildCatalogCommandEntries = ({
return {
group,
id: definition.commandId,
- keys: getEntryKeys(definition, customHotkeys),
+ isPersistentRecent: true,
+ keys: getEntryKeys(definition, customHotkeys, formatHotkey),
keywords: widgetGroup?.group,
run: () => execute(definition.commandId),
showInEmptyState: group === 'Navigation',
@@ -242,12 +267,15 @@ export interface SettingsEntryDeps {
previewTheme?: (themeId: string) => void;
/** Revert a theme preview to the stored preference. */
clearThemePreview?: () => void;
+ languageOptions: ReadonlyArray<{ label: string; value: WorkbenchPreferences['language'] }>;
+ themes: ReadonlyArray<{ id: WorkbenchPreferences['themeId']; label: string }>;
}
export const buildSettingsEntries = (preferences: WorkbenchPreferences, deps: SettingsEntryDeps): PaletteEntry[] => {
const toggles = SETTING_TOGGLES.map<PaletteEntry>(({ key, keywords, title }) => ({
group: 'Settings',
id: `setting.${key}`,
+ isPersistentRecent: true,
keepOpen: true,
keywords: keywords ? `${keywords} toggle` : 'toggle',
run: () => deps.patchPreferences({ [key]: !preferences[key] }),
@@ -276,6 +304,7 @@ export const buildSettingsEntries = (preferences: WorkbenchPreferences, deps: Se
}): PaletteEntry => ({
group: 'Settings',
id,
+ isPersistentRecent: true,
keywords,
run: () => deps.openSettingsSection(sectionId),
secondary: { label: 'Open in Settings', run: () => deps.openSettingsSection(sectionId) },
@@ -288,7 +317,7 @@ export const buildSettingsEntries = (preferences: WorkbenchPreferences, deps: Se
enumEntry({
id: 'setting.themeId',
keywords: 'appearance color dark light',
- options: THEMES.map((theme) => ({
+ options: deps.themes.map((theme) => ({
apply: () => deps.patchPreferences({ themeId: theme.id }),
id: theme.id,
isCurrent: theme.id === preferences.themeId,
@@ -299,13 +328,13 @@ export const buildSettingsEntries = (preferences: WorkbenchPreferences, deps: Se
deps.previewTheme && deps.clearThemePreview
? { clearPreview: deps.clearThemePreview, preview: deps.previewTheme }
: undefined,
- subtitle: THEMES_BY_ID[preferences.themeId]?.label ?? preferences.themeId,
+ subtitle: deps.themes.find((theme) => theme.id === preferences.themeId)?.label ?? preferences.themeId,
title: 'Theme',
}),
enumEntry({
id: 'setting.language',
keywords: 'locale translation',
- options: WORKBENCH_LANGUAGE_OPTIONS.map((language) => ({
+ options: deps.languageOptions.map((language) => ({
apply: () => deps.patchPreferences({ language: language.value }),
id: language.value,
isCurrent: language.value === preferences.language,
@@ -313,8 +342,7 @@ export const buildSettingsEntries = (preferences: WorkbenchPreferences, deps: Se
})),
sectionId: 'appearance',
subtitle:
- WORKBENCH_LANGUAGE_OPTIONS.find((language) => language.value === preferences.language)?.label ??
- preferences.language,
+ deps.languageOptions.find((language) => language.value === preferences.language)?.label ?? preferences.language,
title: 'Language',
}),
enumEntry({
@@ -348,6 +376,7 @@ export const buildSettingsEntries = (preferences: WorkbenchPreferences, deps: Se
const sections = SETTINGS_SECTIONS.map<PaletteEntry>(({ id, title }) => ({
group: 'Settings',
id: `settings.section.${id}`,
+ isPersistentRecent: true,
keywords: 'settings preferences open',
run: () => deps.openSettingsSection(id),
title: `Settings: ${title}`,
@@ -497,6 +526,7 @@ export const buildStageEntries = (stage: PaletteStage, onApplied: () => void): P
stage.options.map((option) => ({
group: stage.title,
id: `${STAGE_ENTRY_ID_PREFIX}${option.id}`,
+ isPersistentRecent: false,
keepOpen: true,
run: () => {
void option.apply();
@@ -507,7 +537,7 @@ export const buildStageEntries = (stage: PaletteStage, onApplied: () => void): P
}));
export interface ProviderResultSection {
- provider: Pick<PaletteSearchProvider, 'id' | 'label'>;
+ provider: Pick<PaletteSearchProvider, 'providerKey' | 'label'>;
entries: PaletteEntry[];
isFetching: boolean;
}
@@ -531,13 +561,17 @@ export const buildProviderSectionRows = (
}
rows.push({
- id: `label:provider:${section.provider.id}`,
+ id: `label:provider:${section.provider.providerKey}`,
kind: 'label',
label: section.isFetching ? `${section.provider.label} — Searching…` : section.provider.label,
});
for (const entry of visible) {
- rows.push({ entry, id: entry.id, kind: 'entry' });
+ rows.push({
+ entry,
+ id: getPaletteContributionKey('provider-row', `${section.provider.providerKey}:${entry.id}`),
+ kind: 'entry',
+ });
}
}
@@ -546,12 +580,12 @@ export const buildProviderSectionRows = (
/** Trailing escape hatches into scoped mode, one per provider. */
export const buildScopeRows = (
- providers: ReadonlyArray<Pick<PaletteSearchProvider, 'id' | 'label'>>,
+ providers: ReadonlyArray<Pick<PaletteSearchProvider, 'providerKey' | 'label'>>,
query: string
): PaletteRow[] =>
providers.map((provider) => ({
- id: `scope:${provider.id}`,
+ id: getPaletteContributionKey('scope', provider.providerKey),
kind: 'scope',
label: `Search ${provider.label.toLowerCase()} for “${query}”`,
- providerId: provider.id,
+ providerKey: provider.providerKey,
}));
diff --git a/invokeai/frontend/webv2/src/workbench/palette/extensionPaletteAdapters.test.ts b/invokeai/frontend/webv2/src/workbench/palette/extensionPaletteAdapters.test.ts
new file mode 100644
index 0000000000..8ecf95c2f0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/extensionPaletteAdapters.test.ts
@@ -0,0 +1,48 @@
+import type { WidgetContributionSource, WidgetSearchProvider } from '@workbench/widgetContracts';
+
+import { describe, expect, it, vi } from 'vitest';
+
+import { createExtensionSearchProvider } from './extensionPaletteAdapters';
+import { getPaletteProviderQueryKey } from './providerQueryKey';
+
+const source = (instanceId: string): WidgetContributionSource => ({
+ instanceId,
+ projectId: 'project-1',
+ region: 'left',
+ typeId: 'generate',
+});
+
+const extensionProvider = (instanceId: string): WidgetSearchProvider => ({
+ id: 'shared-provider-id',
+ label: 'Shared',
+ search: () => [{ commandId: 'run', id: 'shared-result-id', title: 'Result' }],
+ source: source(instanceId),
+});
+
+describe('extension palette adapters', () => {
+ it('keeps providers, query keys, scopes, and results collision-free per widget source', async () => {
+ const execute = vi.fn();
+ const first = createExtensionSearchProvider(extensionProvider('one'), execute);
+ const second = createExtensionSearchProvider(extensionProvider('two'), execute);
+ const [firstResult] = await first.search('query');
+ const [secondResult] = await second.search('query');
+
+ expect(first.providerKey).not.toBe(second.providerKey);
+ expect(getPaletteProviderQueryKey(first, 'query')).not.toEqual(getPaletteProviderQueryKey(second, 'query'));
+ expect(firstResult?.id).not.toBe(secondResult?.id);
+ });
+
+ it('includes immutable context in provider query keys', () => {
+ const provider = createExtensionSearchProvider(extensionProvider('one'), vi.fn());
+ const changedProject = { ...provider, contextKey: 'project-2' };
+ const changedBoard = { ...provider, contextKey: 'board-2' };
+ const changedQueueScope = { ...provider, contextKey: JSON.stringify({ originPrefix: 'project:2' }) };
+ const changedHistory = { ...provider, contextKey: JSON.stringify([{ positivePrompt: 'new' }]) };
+
+ for (const changed of [changedProject, changedBoard, changedQueueScope, changedHistory]) {
+ expect(getPaletteProviderQueryKey(changed, 'same query')).not.toEqual(
+ getPaletteProviderQueryKey(provider, 'same query')
+ );
+ }
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/palette/extensionPaletteAdapters.ts b/invokeai/frontend/webv2/src/workbench/palette/extensionPaletteAdapters.ts
new file mode 100644
index 0000000000..653a9e5477
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/extensionPaletteAdapters.ts
@@ -0,0 +1,52 @@
+import type {
+ WidgetCommandPaletteContribution,
+ WidgetContributionSource,
+ WidgetSearchProvider,
+} from '@workbench/widgetContracts';
+
+import type { PaletteEntry, PaletteSearchProvider } from './entries';
+
+import { getPaletteContributionKey } from './contributionKey';
+
+type ExecuteExtensionCommand = (
+ commandId: string,
+ source: WidgetContributionSource | null,
+ resultId?: string
+) => unknown;
+
+export const buildExtensionPaletteEntry = (
+ contribution: WidgetCommandPaletteContribution,
+ execute: ExecuteExtensionCommand
+): PaletteEntry => ({
+ group: 'Commands',
+ id: getPaletteContributionKey('command', contribution.commandId, contribution.source),
+ isPersistentRecent: true,
+ keywords: contribution.keywords?.join(' '),
+ run: () => execute(contribution.commandId, contribution.source ?? null),
+ title: contribution.title,
+});
+
+export const createExtensionSearchProvider = (
+ provider: WidgetSearchProvider,
+ execute: ExecuteExtensionCommand
+): PaletteSearchProvider => {
+ const providerKey = getPaletteContributionKey('provider', provider.id, provider.source);
+
+ return {
+ contextKey: providerKey,
+ label: provider.label,
+ providerKey,
+ search: async (query) => {
+ const results = await provider.search(query);
+
+ return results.map<PaletteEntry>((result) => ({
+ group: provider.label,
+ id: getPaletteContributionKey('provider-result', `${providerKey}:${result.id}`, provider.source),
+ isPersistentRecent: false,
+ run: () => (result.commandId ? execute(result.commandId, provider.source ?? null, result.id) : undefined),
+ subtitle: result.subtitle,
+ title: result.title,
+ }));
+ },
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/palette/index.ts b/invokeai/frontend/webv2/src/workbench/palette/index.ts
index 885a8f6a0a..c94390fc56 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/index.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/index.ts
@@ -1,5 +1,2 @@
export type { PaletteEntry, PaletteRow } from './entries';
-export { LaunchpadCommandPalette } from './LaunchpadCommandPalette';
-export { PaletteButton } from './PaletteButton';
export { closeCommandPalette, openCommandPalette, toggleCommandPalette } from './paletteStore';
-export { WorkbenchCommandPalette } from './WorkbenchCommandPalette';
diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts
index c927ef5666..327b27db1a 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts
@@ -1,13 +1,12 @@
import type { GalleryBoard, GalleryImage } from '@features/gallery/contracts';
import type { ModelConfig } from '@features/models';
-import type { QueueItemStatus, QueueQueryScope } from '@features/queue/contracts';
+import type { QueueItemStatus, QueueReadModel } from '@features/queue/contracts';
import type { PromptHistoryItem } from '@workbench/projectContracts';
import { galleryBoardsOptions, galleryImagesOptions } from '@features/gallery/queries';
import { focusPositivePrompt } from '@features/generation/react';
import { ensureModelsLoaded, getModelBaseLabel, getModelsSnapshot } from '@features/models';
import { extractGenerationMeta, getResultImageName } from '@features/queue/contracts';
-import { getQueueReadModelOptions } from '@features/queue/queries';
import { listLibraryWorkflows } from '@features/workflow/queries';
import { requestLibraryWorkflowLoad } from '@features/workflow/react';
import { queryClient } from '@platform/query/client';
@@ -15,6 +14,8 @@ import { absolutizeApiUrl } from '@platform/transport/http';
import type { PaletteEntry, PaletteSearchProvider } from './entries';
+import { getPaletteContributionKey } from './contributionKey';
+
/**
* First-party entity providers behind the palette's scoped search. Each is a
* plain factory taking the workbench callbacks it needs — the host component
@@ -36,8 +37,9 @@ export const createWorkflowsProvider = ({
}: {
openWorkflowWidget: () => void;
}): PaletteSearchProvider => ({
- id: 'workflows',
+ contextKey: 'global',
label: 'Workflows',
+ providerKey: getPaletteContributionKey('provider', 'workflows'),
search: async (query) => {
const [user, defaults] = await Promise.all([
listLibraryWorkflows({ category: 'user', page: 0, perPage: PROVIDER_PAGE_SIZE, query }),
@@ -47,6 +49,7 @@ export const createWorkflowsProvider = ({
return [...user.items, ...defaults.items].map<PaletteEntry>((item) => ({
group: 'Workflows',
id: `workflow:${item.workflow_id}`,
+ isPersistentRecent: false,
keywords: item.tags ?? undefined,
run: () => {
openWorkflowWidget();
@@ -65,8 +68,9 @@ export const createBoardsProvider = ({
openGalleryWidget: () => void;
selectBoard: (boardId: string) => void;
}): PaletteSearchProvider => ({
- id: 'boards',
+ contextKey: 'global',
label: 'Boards',
+ providerKey: getPaletteContributionKey('provider', 'boards'),
search: async (query) => {
const boards = await queryClient.fetchQuery(galleryBoardsOptions({ includeArchived: false }));
@@ -75,6 +79,7 @@ export const createBoardsProvider = ({
.map<PaletteEntry>((board) => ({
group: 'Boards',
id: `board:${board.id}`,
+ isPersistentRecent: false,
run: () => {
openGalleryWidget();
selectBoard(board.id);
@@ -86,21 +91,26 @@ export const createBoardsProvider = ({
});
export const createPromptHistoryProvider = ({
- getPromptHistory,
openGenerateWidget,
+ projectId,
+ promptHistory,
+ recallContextKey,
recallPrompt,
}: {
- getPromptHistory: () => readonly PromptHistoryItem[];
openGenerateWidget: () => void;
+ projectId: string;
+ promptHistory: readonly PromptHistoryItem[];
+ recallContextKey: string;
recallPrompt: (item: PromptHistoryItem) => void;
}): PaletteSearchProvider => ({
- id: 'prompt-history',
+ contextKey: JSON.stringify([projectId, promptHistory, recallContextKey]),
label: 'Prompt history',
+ providerKey: getPaletteContributionKey('provider', 'prompt-history'),
search: (query) => {
const seen = new Set<string>();
const entries: PaletteEntry[] = [];
- for (const [index, item] of getPromptHistory().entries()) {
+ for (const [index, item] of promptHistory.entries()) {
const dedupeKey = `${item.positivePrompt}\n${item.negativePrompt ?? ''}`;
if (seen.has(dedupeKey) || !matchesTerms(`${item.positivePrompt} ${item.negativePrompt ?? ''}`, query)) {
@@ -111,6 +121,7 @@ export const createPromptHistoryProvider = ({
entries.push({
group: 'Prompt history',
id: `prompt:${index}`,
+ isPersistentRecent: false,
run: () => {
openGenerateWidget();
recallPrompt(item);
@@ -136,8 +147,9 @@ export const createModelsProvider = ({
openGenerateWidget: () => void;
openModelManager: () => void;
}): PaletteSearchProvider => ({
- id: 'models',
+ contextKey: 'global',
label: 'Models',
+ providerKey: getPaletteContributionKey('provider', 'models'),
search: async (query) => {
await ensureModelsLoaded();
const snapshot = getModelsSnapshot();
@@ -148,6 +160,7 @@ export const createModelsProvider = ({
.map<PaletteEntry>((model) => ({
group: 'Models',
id: `model:${model.key}`,
+ isPersistentRecent: false,
keywords: model.base,
run: () => {
openGenerateWidget();
@@ -170,20 +183,23 @@ const QUEUE_STATUS_LABELS: Record<QueueItemStatus, string> = {
};
export const createQueueItemsProvider = ({
- getScope,
+ contextKey,
+ loadQueue,
openQueueWidget,
revealItem,
}: {
- getScope: () => QueueQueryScope;
+ contextKey: string;
+ loadQueue: () => Promise<QueueReadModel>;
openQueueWidget: () => void;
revealItem: (itemId: number) => void;
}): PaletteSearchProvider => ({
- id: 'queue-items',
+ contextKey,
label: 'Queue items',
+ providerKey: getPaletteContributionKey('provider', 'queue-items'),
search: async (query) => {
// The queue read model is a recent window with no server-side text search;
// filter the fetched window client-side.
- const model = await queryClient.fetchQuery(getQueueReadModelOptions(getScope()));
+ const model = await loadQueue();
return model.items
.map((item) => ({ item, meta: extractGenerationMeta(item) }))
@@ -199,6 +215,7 @@ export const createQueueItemsProvider = ({
return {
group: 'Queue items',
id: `queue-item:${item.id}`,
+ isPersistentRecent: false,
run: () => {
openQueueWidget();
revealItem(item.id);
@@ -214,26 +231,27 @@ export const createQueueItemsProvider = ({
});
export const createImagesProvider = ({
- getSelectedBoardId,
openGalleryWidget,
openPreviewWidget,
+ selectedBoardId,
selectBoard,
selectImage,
}: {
- getSelectedBoardId: () => string;
openGalleryWidget: () => void;
openPreviewWidget: () => void;
+ selectedBoardId: string;
selectBoard: (boardId: string) => void;
selectImage: (image: GalleryImage) => void;
}): PaletteSearchProvider => ({
- id: 'images',
+ contextKey: selectedBoardId,
label: 'Images',
+ providerKey: getPaletteContributionKey('provider', 'images'),
search: async (query) => {
// The images endpoint is board-scoped; the palette searches the board the
// gallery is currently on.
const page = await queryClient.fetchQuery(
galleryImagesOptions({
- boardId: getSelectedBoardId(),
+ boardId: selectedBoardId,
galleryView: 'images',
limit: 20,
searchTerm: query,
@@ -243,6 +261,7 @@ export const createImagesProvider = ({
return page.images.map<PaletteEntry>((image) => ({
group: 'Images',
id: `image:${image.imageName}`,
+ isPersistentRecent: false,
run: () => {
openPreviewWidget();
selectImage(image);
diff --git a/invokeai/frontend/webv2/src/workbench/palette/providerQueryKey.ts b/invokeai/frontend/webv2/src/workbench/palette/providerQueryKey.ts
new file mode 100644
index 0000000000..0d354e52da
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/providerQueryKey.ts
@@ -0,0 +1,4 @@
+import type { PaletteSearchProvider } from './entries';
+
+export const getPaletteProviderQueryKey = (provider: PaletteSearchProvider, query: string) =>
+ ['command-palette', provider.providerKey, provider.contextKey, query] as const;
diff --git a/invokeai/frontend/webv2/src/workbench/palette/recents.test.ts b/invokeai/frontend/webv2/src/workbench/palette/recents.test.ts
new file mode 100644
index 0000000000..2df304fb0d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/recents.test.ts
@@ -0,0 +1,33 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getRecentEntryIds, recordRecentEntry } from './recents';
+
+const STORAGE_KEY = 'invokeai:v7:webv2:palette-recents';
+const storage = new Map<string, string>();
+
+vi.stubGlobal('window', {
+ localStorage: {
+ getItem: (key: string): string | null => storage.get(key) ?? null,
+ setItem: (key: string, value: string): void => {
+ storage.set(key, value);
+ },
+ },
+});
+
+beforeEach(() => storage.clear());
+
+describe('palette recents', () => {
+ it('persists only explicitly durable entries', () => {
+ recordRecentEntry({ id: 'provider-result', isPersistentRecent: false });
+ expect(storage.has(STORAGE_KEY)).toBe(false);
+
+ recordRecentEntry({ id: 'app.invoke', isPersistentRecent: true });
+ expect(getRecentEntryIds()).toEqual(['app.invoke']);
+ });
+
+ it('continues to read the legacy plain-id ring buffer', () => {
+ storage.set(STORAGE_KEY, JSON.stringify(['legacy.command', 'legacy.setting']));
+
+ expect(getRecentEntryIds()).toEqual(['legacy.command', 'legacy.setting']);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/palette/recents.ts b/invokeai/frontend/webv2/src/workbench/palette/recents.ts
index b1450747ec..d36c94265a 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/recents.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/recents.ts
@@ -86,16 +86,16 @@ export const getRecentEntryIds = (): string[] => {
.map(({ record }) => record.id);
};
-export const recordRecentEntry = (id: string): void => {
- if (!isBrowser()) {
+export const recordRecentEntry = (entry: Pick<PaletteEntry, 'id' | 'isPersistentRecent'>): void => {
+ if (!entry.isPersistentRecent || !isBrowser()) {
return;
}
const records = readRecords();
- const existing = records.find((record) => record.id === id);
+ const existing = records.find((record) => record.id === entry.id);
const next: RecentUse[] = [
- { id, lastUsedAt: Date.now(), uses: (existing?.uses ?? 0) + 1 },
- ...records.filter((record) => record.id !== id),
+ { id: entry.id, lastUsedAt: Date.now(), uses: (existing?.uses ?? 0) + 1 },
+ ...records.filter((record) => record.id !== entry.id),
].slice(0, MAX_RECORDS);
try {
@@ -104,3 +104,4 @@ export const recordRecentEntry = (id: string): void => {
// Quota or private-mode failures are non-fatal; recents are a convenience.
}
};
+import type { PaletteEntry } from './entries';
diff --git a/invokeai/frontend/webv2/src/workbench/palette/settingsEntryDeps.ts b/invokeai/frontend/webv2/src/workbench/palette/settingsEntryDeps.ts
index 96ad020741..52fce73fa6 100644
--- a/invokeai/frontend/webv2/src/workbench/palette/settingsEntryDeps.ts
+++ b/invokeai/frontend/webv2/src/workbench/palette/settingsEntryDeps.ts
@@ -1,4 +1,6 @@
+import { WORKBENCH_LANGUAGE_OPTIONS } from '@platform/i18n/languages';
import { applyThemeToRoot } from '@theme/applyTheme';
+import { THEMES } from '@theme/themes';
import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';
import { getWorkbenchPreferences, patchWorkbenchPreferences } from '@workbench/settings/store';
@@ -12,7 +14,9 @@ import type { SettingsEntryDeps } from './entries';
*/
export const SETTINGS_ENTRY_DEPS: SettingsEntryDeps = {
clearThemePreview: () => applyThemeToRoot(getWorkbenchPreferences().themeId),
+ languageOptions: WORKBENCH_LANGUAGE_OPTIONS,
openSettingsSection: openWorkbenchSettings,
patchPreferences: patchWorkbenchPreferences,
previewTheme: applyThemeToRoot,
+ themes: THEMES,
};
diff --git a/invokeai/frontend/webv2/src/workbench/palette/useCommandPaletteController.ts b/invokeai/frontend/webv2/src/workbench/palette/useCommandPaletteController.ts
new file mode 100644
index 0000000000..096fdfaf32
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/palette/useCommandPaletteController.ts
@@ -0,0 +1,419 @@
+/* eslint-disable react/react-compiler */
+import type { ChangeEvent, KeyboardEvent } from 'react';
+
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { useQueries } from '@tanstack/react-query';
+import { useCallback, useMemo, useRef, useState } from 'react';
+
+import type { PaletteEntry, PaletteRow, PaletteSearchProvider, PaletteStage, ProviderResultSection } from './entries';
+
+import {
+ buildProviderSectionRows,
+ buildScopeRows,
+ buildStageEntries,
+ PROVIDER_MIN_QUERY_LENGTH,
+ resolveActivePaletteRow,
+ searchPaletteRows,
+ STAGE_ENTRY_ID_PREFIX,
+} from './entries';
+import { getPaletteProviderQueryKey } from './providerQueryKey';
+import { getRecentEntryIds, recordRecentEntry } from './recents';
+
+const PAGE_JUMP_ROWS = 8;
+const PROVIDER_DEBOUNCE_MS = 200;
+const NO_PROVIDERS: PaletteSearchProvider[] = [];
+
+type ScrollToIndex = (index: number) => void;
+
+export interface CommandPaletteController {
+ activeRow: PaletteRow | undefined;
+ activeRowId: string | null;
+ chipLabel: string | null;
+ hasScopeRows: boolean;
+ isOverlayOpen: boolean;
+ onContentKeyDown: (event: KeyboardEvent<HTMLDivElement>) => void;
+ onRetry: () => void;
+ onRowActive: (rowId: string) => void;
+ onRowRun: (row: PaletteRow) => void;
+ onSearchChange: (event: ChangeEvent<HTMLInputElement>) => void;
+ onSearchKeyDown: (event: KeyboardEvent<HTMLInputElement>, scrollToIndex: ScrollToIndex) => void;
+ placeholder: string;
+ query: string;
+ rows: PaletteRow[];
+ scopeErrorLabel: string | null;
+ scopeIsError: boolean;
+ scopeIsFetching: boolean;
+ secondaryHint: string | undefined;
+ setInputElement: (node: HTMLInputElement | null) => void;
+ stage: PaletteStage | null;
+ trimmedQuery: string;
+}
+
+export const useCommandPaletteController = ({
+ entries,
+ onClose,
+ providers,
+}: {
+ entries: PaletteEntry[];
+ onClose: () => void;
+ providers: PaletteSearchProvider[];
+}): CommandPaletteController => {
+ const [query, setQuery] = useState('');
+ const [debouncedQuery, setDebouncedQuery] = useState('');
+ const [activeRowId, setActiveRowId] = useState<string | null>(null);
+ const [stage, setStage] = useState<PaletteStage | null>(null);
+ const [scopeProviderKey, setScopeProviderKey] = useState<string | null>(null);
+ const [recentIds] = useState(getRecentEntryIds);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const debounceTimerRef = useRef<number | null>(null);
+
+ useMountEffect(() => () => {
+ if (debounceTimerRef.current !== null) {
+ window.clearTimeout(debounceTimerRef.current);
+ }
+ });
+
+ const setInputElement = useCallback((node: HTMLInputElement | null) => {
+ inputRef.current = node;
+ node?.focus();
+ }, []);
+ const focusInput = useCallback(() => {
+ window.requestAnimationFrame(() => inputRef.current?.focus());
+ }, []);
+ const clearDebounce = useCallback(() => {
+ if (debounceTimerRef.current !== null) {
+ window.clearTimeout(debounceTimerRef.current);
+ debounceTimerRef.current = null;
+ }
+ }, []);
+
+ const scopeProvider = scopeProviderKey
+ ? (providers.find((provider) => provider.providerKey === scopeProviderKey) ?? null)
+ : null;
+ const isCommandsScope = !stage && !scopeProvider && query.startsWith('>');
+ const localQuery = isCommandsScope ? query.slice(1) : query;
+ const trimmedQuery = localQuery.trim();
+ const shouldSearchProviders = debouncedQuery.length >= PROVIDER_MIN_QUERY_LENGTH && !stage && !isCommandsScope;
+ const activeProviders = useMemo(
+ () => (stage || isCommandsScope ? NO_PROVIDERS : scopeProvider ? [scopeProvider] : providers),
+ [isCommandsScope, providers, scopeProvider, stage]
+ );
+
+ const providerResults = useQueries({
+ combine: (results) =>
+ results.map((result) => ({
+ data: result.data,
+ isError: result.isError,
+ isFetching: result.isFetching,
+ refetch: result.refetch,
+ })),
+ queries: activeProviders.map((provider) => ({
+ enabled: shouldSearchProviders,
+ queryFn: () => Promise.resolve(provider.search(debouncedQuery)),
+ queryKey: getPaletteProviderQueryKey(provider, debouncedQuery),
+ retry: false,
+ staleTime: 30_000,
+ })),
+ });
+ const providerSections = useMemo<ProviderResultSection[]>(
+ () =>
+ activeProviders.map((provider, index) => ({
+ entries: providerResults[index]?.data ?? [],
+ isFetching: shouldSearchProviders && (providerResults[index]?.isFetching ?? false),
+ provider,
+ })),
+ [activeProviders, providerResults, shouldSearchProviders]
+ );
+ const scopedQueryResult = scopeProvider ? providerResults[0] : undefined;
+
+ const resetOverlayState = useCallback(() => {
+ clearDebounce();
+ setStage(null);
+ setScopeProviderKey(null);
+ setQuery('');
+ setDebouncedQuery('');
+ setActiveRowId(null);
+ }, [clearDebounce]);
+ const popOverlay = useCallback(() => {
+ resetOverlayState();
+ focusInput();
+ }, [focusInput, resetOverlayState]);
+ const onStageApplied = resetOverlayState;
+
+ const rows = useMemo<PaletteRow[]>(() => {
+ if (stage) {
+ return searchPaletteRows(buildStageEntries(stage, onStageApplied), query, [], { showAllOnEmpty: true });
+ }
+
+ if (scopeProvider) {
+ return buildProviderSectionRows(providerSections, null);
+ }
+
+ const localRows = searchPaletteRows(entries, localQuery, recentIds, {
+ commandsOnly: isCommandsScope,
+ showAllOnEmpty: isCommandsScope && trimmedQuery.length === 0,
+ });
+
+ if (trimmedQuery.length === 0 || isCommandsScope) {
+ return localRows;
+ }
+
+ return [
+ ...localRows,
+ ...(trimmedQuery.length >= PROVIDER_MIN_QUERY_LENGTH ? buildProviderSectionRows(providerSections) : []),
+ ...buildScopeRows(providers, trimmedQuery),
+ ];
+ }, [
+ entries,
+ isCommandsScope,
+ localQuery,
+ onStageApplied,
+ providers,
+ providerSections,
+ query,
+ recentIds,
+ scopeProvider,
+ stage,
+ trimmedQuery,
+ ]);
+ const navigableRows = useMemo(
+ () => rows.flatMap((row, index) => (row.kind === 'label' ? [] : [{ index, row }])),
+ [rows]
+ );
+ const effectiveActive = useMemo(() => resolveActivePaletteRow(rows, activeRowId), [activeRowId, rows]);
+ const effectiveActiveRowId = effectiveActive?.row.id ?? null;
+ const activeRow = effectiveActive?.row;
+
+ const previewRow = useCallback(
+ (row: PaletteRow | undefined) => {
+ if (!stage?.preview) {
+ return;
+ }
+
+ if (row?.kind !== 'entry' || !row.entry.id.startsWith(STAGE_ENTRY_ID_PREFIX)) {
+ stage.clearPreview?.();
+ return;
+ }
+
+ stage.preview(row.entry.id.slice(STAGE_ENTRY_ID_PREFIX.length));
+ },
+ [stage]
+ );
+
+ const enterScope = useCallback(
+ (providerKey: string) => {
+ clearDebounce();
+ setScopeProviderKey(providerKey);
+ setDebouncedQuery(trimmedQuery);
+ setActiveRowId(null);
+ focusInput();
+ },
+ [clearDebounce, focusInput, trimmedQuery]
+ );
+
+ const runRow = useCallback(
+ (row: PaletteRow) => {
+ if (row.kind === 'label') {
+ return;
+ }
+
+ if (row.kind === 'scope') {
+ enterScope(row.providerKey);
+ return;
+ }
+
+ if (row.entry.isPersistentRecent) {
+ recordRecentEntry(row.entry);
+ }
+
+ if (row.entry.stage) {
+ const nextStage = row.entry.stage;
+ const currentOption = nextStage.options.find((option) => option.isCurrent);
+
+ clearDebounce();
+ setStage(nextStage);
+ setQuery('');
+ setDebouncedQuery('');
+ setActiveRowId(currentOption ? `${STAGE_ENTRY_ID_PREFIX}${currentOption.id}` : null);
+ focusInput();
+ return;
+ }
+
+ if (row.entry.keepOpen) {
+ void row.entry.run();
+ focusInput();
+ return;
+ }
+
+ onClose();
+ void row.entry.run();
+ },
+ [clearDebounce, enterScope, focusInput, onClose]
+ );
+
+ const runSecondary = useCallback(
+ (entry: PaletteEntry) => {
+ if (!entry.secondary) {
+ return;
+ }
+
+ if (entry.isPersistentRecent) {
+ recordRecentEntry(entry);
+ }
+ onClose();
+ void entry.secondary.run();
+ },
+ [onClose]
+ );
+
+ const moveActive = useCallback(
+ (offset: number, scrollToIndex: ScrollToIndex) => {
+ if (navigableRows.length === 0) {
+ return;
+ }
+
+ const position = effectiveActive
+ ? navigableRows.findIndex((candidate) => candidate.row.id === effectiveActive.row.id)
+ : -1;
+ const nextPosition =
+ Math.abs(offset) === 1
+ ? (position + offset + navigableRows.length) % navigableRows.length
+ : Math.min(Math.max(position + offset, 0), navigableRows.length - 1);
+ const next = navigableRows[nextPosition];
+
+ if (!next) {
+ return;
+ }
+
+ setActiveRowId(next.row.id);
+ previewRow(next.row);
+ scrollToIndex(next.index);
+ },
+ [effectiveActive, navigableRows, previewRow]
+ );
+
+ const onEscape = useCallback(() => {
+ if (stage || scopeProviderKey) {
+ popOverlay();
+ return;
+ }
+
+ onClose();
+ }, [onClose, popOverlay, scopeProviderKey, stage]);
+
+ const onContentKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLDivElement>) => {
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ event.stopPropagation();
+ onEscape();
+ }
+ },
+ [onEscape]
+ );
+
+ const onSearchKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLInputElement>, scrollToIndex: ScrollToIndex) => {
+ if (event.key === 'ArrowDown') {
+ event.preventDefault();
+ moveActive(1, scrollToIndex);
+ } else if (event.key === 'ArrowUp') {
+ event.preventDefault();
+ moveActive(-1, scrollToIndex);
+ } else if (event.key === 'PageDown') {
+ event.preventDefault();
+ moveActive(PAGE_JUMP_ROWS, scrollToIndex);
+ } else if (event.key === 'PageUp') {
+ event.preventDefault();
+ moveActive(-PAGE_JUMP_ROWS, scrollToIndex);
+ } else if (event.key === 'Tab' && activeRow?.kind === 'scope') {
+ event.preventDefault();
+ enterScope(activeRow.providerKey);
+ } else if (event.key === 'Backspace' && query.length === 0 && (stage || scopeProviderKey)) {
+ event.preventDefault();
+ popOverlay();
+ } else if (event.key === 'Enter') {
+ event.preventDefault();
+
+ if (!activeRow) {
+ return;
+ }
+
+ if ((event.metaKey || event.ctrlKey) && activeRow.kind === 'entry' && activeRow.entry.secondary) {
+ runSecondary(activeRow.entry);
+ return;
+ }
+
+ runRow(activeRow);
+ }
+ },
+ [activeRow, enterScope, moveActive, popOverlay, query.length, runRow, runSecondary, scopeProviderKey, stage]
+ );
+
+ const onSearchChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const nextQuery = event.currentTarget.value;
+ const nextLocalQuery = !stage && !scopeProvider && nextQuery.startsWith('>') ? nextQuery.slice(1) : nextQuery;
+ const nextTrimmedQuery = nextLocalQuery.trim();
+
+ setQuery(nextQuery);
+ setActiveRowId(null);
+ clearDebounce();
+
+ if (stage) {
+ const nextRows = searchPaletteRows(buildStageEntries(stage, onStageApplied), nextQuery, [], {
+ showAllOnEmpty: true,
+ });
+ previewRow(nextRows.find((row) => row.kind !== 'label'));
+ }
+
+ debounceTimerRef.current = window.setTimeout(() => {
+ debounceTimerRef.current = null;
+ setDebouncedQuery(nextTrimmedQuery);
+ }, PROVIDER_DEBOUNCE_MS);
+ },
+ [clearDebounce, onStageApplied, previewRow, scopeProvider, stage]
+ );
+
+ const onRowActive = useCallback(
+ (rowId: string) => {
+ const row = rows.find((candidate) => candidate.id === rowId);
+ setActiveRowId(rowId);
+ previewRow(row);
+ },
+ [previewRow, rows]
+ );
+
+ const onRetry = useCallback(() => {
+ void scopedQueryResult?.refetch();
+ focusInput();
+ }, [focusInput, scopedQueryResult]);
+
+ return {
+ activeRow,
+ activeRowId: effectiveActiveRowId,
+ chipLabel: stage ? stage.title : (scopeProvider?.label ?? null),
+ hasScopeRows: rows.some((row) => row.kind === 'scope'),
+ isOverlayOpen: Boolean(stage || scopeProviderKey),
+ onContentKeyDown,
+ onRetry,
+ onRowActive,
+ onRowRun: runRow,
+ onSearchChange,
+ onSearchKeyDown,
+ placeholder: stage
+ ? 'Pick a value…'
+ : scopeProvider
+ ? `Search ${scopeProvider.label.toLowerCase()}…`
+ : 'Search commands, settings, and more…',
+ query,
+ rows,
+ scopeErrorLabel: scopeProvider?.label.toLowerCase() ?? null,
+ scopeIsError: Boolean(scopeProvider && scopedQueryResult?.isError),
+ scopeIsFetching: Boolean(scopeProvider && scopedQueryResult?.isFetching),
+ secondaryHint: activeRow?.kind === 'entry' ? activeRow.entry.secondary?.label : undefined,
+ setInputElement,
+ stage,
+ trimmedQuery,
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsx
index 97c9fd7dba..f83e18c717 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/TopBar.tsx
@@ -2,7 +2,7 @@ import { Flex, HStack, Separator } from '@chakra-ui/react';
import { AccountMenu, useCapabilities } from '@features/identity';
import { InvokeMark } from '@platform/ui/InvokeMark';
import { Link } from '@tanstack/react-router';
-import { PaletteButton } from '@workbench/palette';
+import { PaletteButton } from '@workbench/palette/PaletteButton';
import { ProjectTabs } from '@workbench/projects/components';
import { SettingsButton } from '@/workbench/settings';