Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(workbench): palette value pickers, scoped search, entity providers
joshistoastc6b82b404ae9
diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.tsindex 57fec01ccf..c95884cccf 100644--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts@@ -155,13 +155,14 @@ describe('dependency policy rules', () => {describe('feature public-interface registry', () => {it('rejects top-level modules a feature has not registered', () => {- expect(checkDependency('workbench/shell/View.tsx', '@features/workflow/queries')).toMatchObject([+ expect(checkDependency('workbench/shell/View.tsx', '@features/workflow/data')).toMatchObject([{ rule: 'feature-private-interface' },]);expect(checkDependency('workbench/shell/View.tsx', '@features/identity/session')).toMatchObject([{ rule: 'feature-private-interface' },]);expect(checkDependency('workbench/shell/View.tsx', '@features/identity')).toEqual([]);+ expect(checkDependency('workbench/palette/paletteProviders.ts', '@features/workflow/queries')).toEqual([]);expect(checkDependency('features/gallery/ui/View.tsx', '@features/queue/publicApi')).toMatchObject([{ rule: 'feature-public-interface' },]);diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.tsindex ae515744d5..0beae8e8ba 100644--- a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts@@ -12,5 +12,5 @@ export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string[nodes: [],queue: ['contracts', 'menu', 'react', 'utility', 'widget'],upscale: ['widget'],- workflow: ['contracts', 'graph', 'preview', 'react', 'utility', 'widget'],+ workflow: ['contracts', 'graph', 'preview', 'queries', 'react', 'utility', 'widget'],};diff --git a/invokeai/frontend/webv2/src/features/workflow/react.ts b/invokeai/frontend/webv2/src/features/workflow/react.tsindex bfe552ca77..07a80e046b 100644--- a/invokeai/frontend/webv2/src/features/workflow/react.ts+++ b/invokeai/frontend/webv2/src/features/workflow/react.ts@@ -1,3 +1,4 @@export * from './data/templates';+export { clearPendingLibraryWorkflowLoad, requestLibraryWorkflowLoad } from './ui/workflowUiStore';export { WorkflowGraphPreviewProvider, WorkflowUiProvider } from './ui/WorkflowUiContext';export type { WorkflowGraphPreviewPort, WorkflowReadPort, WorkflowUiAdapter } from './ui/WorkflowUiContext';diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsxnew file mode 100644index 0000000000..e689f655aa--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx@@ -0,0 +1,49 @@+import { getLibraryWorkflow, touchLibraryWorkflowOpenedAt } from '@features/workflow/data/api';+import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';+import { useWorkflowNotifications } from '@features/workflow/ui/WorkflowUiContext';+import { clearPendingLibraryWorkflowLoad, workflowUiStore } from '@features/workflow/ui/workflowUiStore';+import { parseWorkflowJson } from '@features/workflow/utility';+import { getApiErrorMessage } from '@platform/transport/http';+import { useEffect, useEffectEvent } from 'react';++/**+ * Consumes `pendingLibraryWorkflowId` requests from shell surfaces (the+ * command palette) that cannot reach the graph context themselves: fetches+ * the library record, parses it, and replaces the project graph — the same+ * load path as WorkflowLibraryDialog, minus the dialog.+ */+export const PendingLibraryWorkflowLoader = () => {+ const { replace } = useProjectGraphCommands();+ const notify = useWorkflowNotifications();+ const pendingWorkflowId = workflowUiStore.useSelector((snapshot) => snapshot.pendingLibraryWorkflowId);++ const loadPendingWorkflow = useEffectEvent(async (workflowId: string) => {+ try {+ const raw = await getLibraryWorkflow(workflowId);+ const { document, warnings } = parseWorkflowJson(raw);+ const name = typeof raw.name === 'string' && raw.name.length > 0 ? raw.name : 'workflow';++ replace(document, `Loaded "${name}" from library`);++ for (const warning of warnings) {+ notify.info('Workflow load warning', warning);+ }++ void touchLibraryWorkflowOpenedAt(workflowId).catch(() => {+ // Recency bookkeeping only; loading already succeeded.+ });+ } catch (error) {+ notify.error('Failed to load workflow', getApiErrorMessage(error, 'Could not load the workflow.'));+ } finally {+ clearPendingLibraryWorkflowLoad();+ }+ });++ useEffect(() => {+ if (pendingWorkflowId) {+ void loadPendingWorkflow(pendingWorkflowId);+ }+ }, [pendingWorkflowId]);++ return null;+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsxindex b898128264..c9b470614b 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx@@ -25,6 +25,7 @@ import type { WorkflowWidgetLabelProps, WorkflowWidgetViewProps } from './contraimport { AddNodeDialog } from './editor/AddNodeDialog';import { getWorkflowFlowInstance } from './editor/flowInstanceStore';import { WorkflowLibraryDialog } from './library/WorkflowLibraryDialog';+import { PendingLibraryWorkflowLoader } from './PendingLibraryWorkflowLoader';import { copyWorkflowJson, downloadWorkflowJson } from './workflowTransfer';import {useWorkflowHostCommands,@@ -401,6 +402,7 @@ export const WorkflowDialogHost = () => {onOpenChange={setAddNodeOpen}/><WorkflowLibraryDialog isOpen={isLibraryOpen} onOpenChange={setWorkflowLibraryOpen} />+ <PendingLibraryWorkflowLoader /><ConfirmDialogbody="Replace the project graph with an empty workflow? The current graph is saved to graph history first."confirmLabel="New workflow"diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.tsindex ee66096be7..ccc01e12bb 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts@@ -31,6 +31,8 @@ export interface WorkflowUiSnapshot {isNewWorkflowConfirmOpen: boolean;/** Bumped to ask the dialog host to open the JSON file picker. */importRequestCount: number;+ /** Library workflow a shell surface (command palette) asked to load; consumed by the widget chrome. */+ pendingLibraryWorkflowId: string | null;}export const workflowUiStore = createExternalStore<WorkflowUiSnapshot>({@@ -40,6 +42,7 @@ export const workflowUiStore = createExternalStore<WorkflowUiSnapshot>({isAddNodeOpen: false,isLibraryOpen: false,isNewWorkflowConfirmOpen: false,+ pendingLibraryWorkflowId: null,});export const setWorkflowLibraryOpen = (isOpen: boolean): void => {@@ -62,6 +65,14 @@ export const setNewWorkflowConfirmOpen = (isOpen: boolean): void => {workflowUiStore.patchSnapshot({ isNewWorkflowConfirmOpen: isOpen });};+export const requestLibraryWorkflowLoad = (workflowId: string): void => {+ workflowUiStore.patchSnapshot({ pendingLibraryWorkflowId: workflowId });+};++export const clearPendingLibraryWorkflowLoad = (): void => {+ workflowUiStore.patchSnapshot({ pendingLibraryWorkflowId: null });+};+export const requestWorkflowImport = (): void => {workflowUiStore.patchSnapshot({ importRequestCount: workflowUiStore.getSnapshot().importRequestCount + 1 });};diff --git a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsxindex f7ccced885..353c1aab27 100644--- a/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/palette/CommandPaletteDialog.tsx@@ -2,16 +2,25 @@ import type { ChangeEvent, KeyboardEvent, ReactNode } from 'react';import { Box, Dialog, HStack, Icon, Kbd, Portal, ScrollArea, Spacer, Text, chakra } from '@chakra-ui/react';import { useMountEffect } from '@platform/react/useMountEffect';+import { Button } from '@platform/ui';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 { SearchIcon } from 'lucide-react';-import { useCallback, useMemo, useState } from 'react';+import { CheckIcon, SearchIcon } from 'lucide-react';+import { useCallback, useEffect, useMemo, useState } from 'react';import { useVirtualizer } from 'react-hook-tanstack-virtual';-import type { PaletteEntry, PaletteRow } from './entries';+import type { PaletteEntry, PaletteRow, PaletteSearchProvider, PaletteStage, ProviderResultSection } from './entries';-import { searchPaletteRows } from './entries';+import {+ buildProviderSectionRows,+ buildScopeRows,+ buildStageEntries,+ PROVIDER_MIN_QUERY_LENGTH,+ searchPaletteRows,+} from './entries';import { getRecentEntryIds, recordRecentEntry } from './recents';/**@@ -20,18 +29,49 @@ import { getRecentEntryIds, recordRecentEntry } from './recents';* 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 };const INPUT_PLACEHOLDER_STYLE = { color: 'fg.subtle' };+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) {@@ -62,6 +102,18 @@ const renderTitle = (title: string, matchIndexes?: readonly number[]): ReactNodereturn 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,@@ -78,27 +130,22 @@ const EntryRow = ({onRun: () => void;}) => (<HStack+ {...rowButtonProps}id={id}- as="button"aria-selected={isActive}bg={isActive ? 'bg.emphasized' : undefined}role="option"- tabIndex={-1}- cursor="pointer"- gap="2.5"- h={`${ENTRY_ROW_HEIGHT_PX}px`}- px="3"- rounded="sm"- textAlign="start"- w="full"onClick={onRun}+ onMouseDown={preventFocusSteal}onMouseMove={onActive}><Text fontSize="sm" truncate>{renderTitle(entry.title, matchIndexes)}</Text>- {entry.subtitle ? (- <Text color="fg.subtle" flexShrink={0} fontSize="xs">+ {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}@@ -115,6 +162,39 @@ const EntryRow = ({</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,@@ -140,6 +220,8 @@ const VirtualPaletteRow = ({return null;}+ const isActive = virtualIndex === activeIndex;+return (<Boxref={measureElement}@@ -154,11 +236,19 @@ const VirtualPaletteRow = ({<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}+ />) : (<EntryRowid={getRowDomId(virtualIndex)}entry={row.entry}- isActive={virtualIndex === activeIndex}+ isActive={isActive}matchIndexes={row.matchIndexes}onActive={onActive}onRun={onRun}@@ -168,14 +258,27 @@ const VirtualPaletteRow = ({);};+const FooterHint = ({ children, keys }: { children: string; keys: string[] }) => (+ <HStack gap="1">+ {keys.map((key) => (+ <Kbd key={key} size="sm" textTransform="lowercase">+ {key}+ </Kbd>+ ))}+ <Text>{children}</Text>+ </HStack>+);+export const CommandPaletteDialog = ({entries,isOpen,onClose,+ providers = NO_PROVIDERS,}: {entries: PaletteEntry[];isOpen: boolean;onClose: () => void;+ providers?: PaletteSearchProvider[];}) => {const onDialogOpenChange = useCallback((event: { open: boolean }) => {@@ -187,26 +290,140 @@ export const CommandPaletteDialog = ({);return (- <Dialog.Root lazyMount open={isOpen} scrollBehavior="inside" unmountOnExit onOpenChange={onDialogOpenChange}>- {isOpen ? <CommandPaletteContent entries={entries} onClose={onClose} /> : null}+ <Dialog.Root+ closeOnEscape={false}+ lazyMount+ open={isOpen}+ scrollBehavior="inside"+ unmountOnExit+ onOpenChange={onDialogOpenChange}+ >+ {isOpen ? <CommandPaletteContent entries={entries} providers={providers} onClose={onClose} /> : null}</Dialog.Root>);};-const CommandPaletteContent = ({ entries, onClose }: { entries: PaletteEntry[]; onClose: () => void }) => {+const CommandPaletteContent = ({+ entries,+ onClose,+ providers,+}: {+ entries: PaletteEntry[];+ 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 rows = useMemo(() => searchPaletteRows(entries, query, recentIds), [entries, query, recentIds]);- const entryRowIndexes = useMemo(() => rows.flatMap((row, index) => (row.kind === 'entry' ? [index] : [])), [rows]);- // The highlight always lands on an entry row; -1 (or a stale index after a- // query change) resolves to the first hit so Enter runs the top result.- const effectiveActiveIndex = entryRowIndexes.includes(activeIndex) ? activeIndex : (entryRowIndexes[0] ?? -1);+ 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];const estimateRowSize = useCallback((index: number) => (rows[index]?.kind === 'label' ? LABEL_ROW_HEIGHT_PX : ENTRY_ROW_HEIGHT_PX),@@ -224,14 +441,32 @@ const CommandPaletteContent = ({ entries, onClose }: { entries: PaletteEntry[];overscan: 8,});+ // --- Execution ---------------------------------------------------------+ const enterScope = useCallback((providerId: string) => {+ setScopeProviderId(providerId);+ setActiveIndex(-1);+ }, []);+const runRow = useCallback((row: PaletteRow) => {- if (row.kind !== 'entry') {+ 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('');+ setActiveIndex(-1);+ return;+ }+if (row.entry.keepOpen) {void row.entry.run();return;@@ -242,21 +477,34 @@ const CommandPaletteContent = ({ entries, onClose }: { entries: PaletteEntry[];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 (entryRowIndexes.length === 0) {+ if (navigableRowIndexes.length === 0) {return;}- const position = entryRowIndexes.indexOf(effectiveActiveIndex);+ const position = navigableRowIndexes.indexOf(effectiveActiveIndex);const nextPosition =Math.abs(offset) === 1- ? (position + offset + entryRowIndexes.length) % entryRowIndexes.length- : Math.min(Math.max(position + offset, 0), entryRowIndexes.length - 1);- const nextIndex = entryRowIndexes[nextPosition];+ ? (position + offset + navigableRowIndexes.length) % navigableRowIndexes.length+ : Math.min(Math.max(position + offset, 0), navigableRowIndexes.length - 1);+ const nextIndex = navigableRowIndexes[nextPosition];if (nextIndex === undefined) {return;@@ -265,7 +513,30 @@ const CommandPaletteContent = ({ entries, onClose }: { entries: PaletteEntry[];setActiveIndex(nextIndex);virtualizer.scrollToIndex(nextIndex, { align: 'auto' });},- [effectiveActiveIndex, entryRowIndexes, virtualizer]+ [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 onSearchKeyDown = useCallback(@@ -282,31 +553,103 @@ const CommandPaletteContent = ({ entries, onClose }: { entries: PaletteEntry[];} 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();- const row = effectiveActiveIndex === -1 ? undefined : rows[effectiveActiveIndex];- if (row) {- runRow(row);+ if (!activeRow) {+ return;+ }++ if ((event.metaKey || event.ctrlKey) && activeRow.kind === 'entry' && activeRow.entry.secondary) {+ runSecondary(activeRow.entry);+ return;}++ runRow(activeRow);}},- [effectiveActiveIndex, moveActive, rows, runRow]+ [activeRow, enterScope, moveActive, popOverlay, query.length, runRow, runSecondary, scopeProviderId, stage]);- const onSearchChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {- setQuery(event.currentTarget.value);- setActiveIndex(-1);- }, []);+ const onSearchChange = useCallback(+ (event: ChangeEvent<HTMLInputElement>) => {+ setQuery(event.currentTarget.value);+ resetHighlight();+ },+ [resetHighlight]+ );++ // --- 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) {+ emptyState = (+ <EmptyState danger py="6" title={`Couldn't search ${scopeProvider.label.toLowerCase()}`}>+ <Button size="xs" variant="subtle" onClick={retryScopedSearch}>+ 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) {+ emptyState = <EmptyState py="6" title="Searching…" />;+ } else {+ emptyState = <EmptyState py="6" title={`No results for “${trimmedQuery}”`} />;+ }+ }++ const hasScopeRows = rows.some((row) => row.kind === 'scope');+ const secondaryHint = activeRow?.kind === 'entry' ? activeRow.entry.secondary?.label : undefined;return (<Portal><Dialog.Backdrop bg="blackAlpha.300" /><Dialog.Positioner alignItems="flex-start" pt="15vh">- <Dialog.Content maxW="none" overflow="hidden" p="0" w="min(560px, calc(100vw - 32px))">+ <Dialog.Content+ maxW="none"+ overflow="hidden"+ p="0"+ w="min(560px, calc(100vw - 32px))"+ onKeyDown={onContentKeyDown}+ ><HStack borderBottomWidth="1px" borderColor="border.emphasized" flexShrink={0} gap="2.5" h="12" px="3"><Icon as={SearchIcon} boxSize="4" color="fg.muted" flexShrink={0} />+ {chipLabel ? (+ <Text+ bg="bg.emphasized"+ borderRadius="sm"+ color="fg"+ flexShrink={0}+ fontSize="xs"+ fontWeight="600"+ px="1.5"+ py="0.5"+ >+ {chipLabel}+ </Text>+ ) : null}<chakra.input+ ref={setInputElement}autoFocusaria-activedescendant={effectiveActiveIndex === -1 ? undefined : getRowDomId(effectiveActiveIndex)}aria-controls={RESULT_LIST_ID}@@ -317,7 +660,7 @@ const CommandPaletteContent = ({ entries, onClose }: { entries: PaletteEntry[];flex="1"fontSize="sm"outline="none"- placeholder="Search commands, settings, and more…"+ placeholder={placeholder}role="combobox"value={query}w="full"@@ -327,7 +670,7 @@ const CommandPaletteContent = ({ entries, onClose }: { entries: PaletteEntry[];/></HStack>{rows.length === 0 ? (- <EmptyState py="6" title={`No results for “${query.trim()}”`} />+ 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">@@ -364,21 +707,12 @@ const CommandPaletteContent = ({ entries, onClose }: { entries: PaletteEntry[];hideBelow="sm"px="3">- <HStack gap="1">- <Kbd size="sm">↑</Kbd>- <Kbd size="sm">↓</Kbd>- <Text>Navigate</Text>- </HStack>- <HStack gap="1">- <Kbd size="sm">↵</Kbd>- <Text>Run</Text>- </HStack>- <HStack gap="1">- <Kbd size="sm" textTransform="lowercase">- esc- </Kbd>- <Text>Close</Text>- </HStack>+ <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}+ <Spacer />+ <FooterHint keys={ESC_HINT_KEYS}>{stage || scopeProviderId ? 'Back' : 'Close'}</FooterHint></HStack></Dialog.Content></Dialog.Positioner>diff --git a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsx b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsxindex a32d2732eb..83f734e339 100644--- a/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsx+++ b/invokeai/frontend/webv2/src/workbench/palette/WorkbenchCommandPalette.tsx@@ -1,12 +1,20 @@import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';import { patchWorkbenchPreferences, useWorkbenchPreferences } from '@workbench/settings/store';-import { useActiveProjectSelector, useWorkbenchExtensions } from '@workbench/WorkbenchContext';+import { openWidgetPlacement } from '@workbench/widgetPlacementCommands';+import { getWidgetsForRegion } from '@workbench/widgetRegistry';+import {+ useActiveProjectSelector,+ useWorkbenchCommands,+ useWorkbenchExtensions,+ useWorkbenchQueries,+} from '@workbench/WorkbenchContext';import { useCallback, useMemo, useSyncExternalStore } from 'react';-import type { PaletteEntry } from './entries';+import type { PaletteEntry, PaletteSearchProvider } from './entries';import { CommandPaletteDialog } from './CommandPaletteDialog';import { buildCatalogCommandEntries, buildSettingsEntries } from './entries';+import { createBoardsProvider, createPromptHistoryProvider, createWorkflowsProvider } from './paletteProviders';import { closeCommandPalette, commandPaletteStore } from './paletteStore';/**@@ -83,5 +91,44 @@ export const WorkbenchCommandPalette = () => {[executeCommand, extensions, paletteContributions, preferences, presentWidgetTypeIds]);- return <CommandPaletteDialog entries={entries} isOpen={isOpen} onClose={closeCommandPalette} />;+ const workbenchCommands = useWorkbenchCommands();+ const queries = useWorkbenchQueries();+ const providers = useMemo<PaletteSearchProvider[]>(() => {+ const { gallery, widgets } = workbenchCommands;+ const openWidget = (typeId: 'workflow' | 'gallery' | 'generate') =>+ openWidgetPlacement({+ getWidgetsForRegion,+ options:+ typeId === 'workflow'+ ? { preferredRegions: ['center'], requireCenterView: true }+ : { preferredRegions: typeId === 'gallery' ? ['center', 'right'] : ['left'] },+ typeId,+ widgets,+ });++ return [+ createWorkflowsProvider({ openWorkflowWidget: () => openWidget('workflow') }),+ createBoardsProvider({+ openGalleryWidget: () => openWidget('gallery'),+ selectBoard: (boardId) => gallery.selectBoard(boardId),+ }),+ 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);+ },+ }),+ ];+ }, [queries, workbenchCommands]);++ return <CommandPaletteDialog entries={entries} isOpen={isOpen} providers={providers} onClose={closeCommandPalette} />;};diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.test.tsindex 942ae45ede..f4b612088f 100644--- a/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts@@ -3,7 +3,14 @@ import { describe, expect, it, vi } from 'vitest';import type { PaletteEntry } from './entries';-import { buildCatalogCommandEntries, buildSettingsEntries, searchPaletteRows } from './entries';+import {+ buildCatalogCommandEntries,+ buildProviderSectionRows,+ buildScopeRows,+ buildSettingsEntries,+ buildStageEntries,+ searchPaletteRows,+} from './entries';/*** The palette's source aggregation and ranking contract: unimplemented and@@ -97,6 +104,75 @@ describe('buildSettingsEntries', () => {workflowSection?.run();expect(openSettingsSection).toHaveBeenCalledWith('workflow');});++ it('carries a value-picker stage on enum preferences that applies and marks the current value', () => {+ const patchPreferences = vi.fn();+ const entries = buildSettingsEntries(+ { ...DEFAULT_PREFERENCES, workflowEdgeStyle: 'curved' },+ { openSettingsSection: vi.fn(), patchPreferences }+ );+ const edgeStyle = entries.find((entry) => entry.id === 'setting.workflowEdgeStyle');++ expect(edgeStyle?.stage?.options.map((option) => [option.label, option.isCurrent])).toEqual([+ ['Curved', true],+ ['Square', false],+ ]);+ expect(edgeStyle?.secondary?.label).toBe('Open in Settings');++ edgeStyle?.stage?.options[1]?.apply();+ expect(patchPreferences).toHaveBeenCalledWith({ workflowEdgeStyle: 'square' });+ });+});++describe('buildStageEntries', () => {+ it('turns options into keep-open rows that apply then pop', () => {+ const apply = vi.fn();+ const onApplied = vi.fn();+ const entries = buildStageEntries(+ { options: [{ apply, id: 'a', isCurrent: true, label: 'Alpha' }], title: 'Theme' },+ onApplied+ );++ expect(entries[0]).toMatchObject({ group: 'Theme', keepOpen: true, subtitle: 'Current', title: 'Alpha' });++ entries[0]?.run();+ expect(apply).toHaveBeenCalled();+ expect(onApplied).toHaveBeenCalled();+ });+});++describe('provider row assembly', () => {+ const section = (id: string, count: number, isFetching = false) => ({+ entries: Array.from({ length: count }, (_, index) =>+ makeEntry({ group: id, id: `${id}:${index}`, title: `${id} ${index}` })+ ),+ isFetching,+ provider: { id, label: id },+ });++ it('caps sections in root mode and drops empty settled sections', () => {+ const rows = buildProviderSectionRows([section('workflows', 5), section('boards', 0)]);++ expect(rows.map((row) => row.id)).toEqual([+ 'label:provider:workflows',+ 'workflows:0',+ 'workflows:1',+ 'workflows:2',+ ]);+ });++ it('renders uncapped in scoped mode and labels in-flight sections', () => {+ const rows = buildProviderSectionRows([section('workflows', 5, true)], null);++ expect(rows).toHaveLength(6);+ expect(rows[0]).toMatchObject({ kind: 'label', label: 'workflows — Searching…' });+ });++ it('builds one trailing scope row per provider', () => {+ const rows = buildScopeRows([{ id: 'boards', label: 'Boards' }], 'sunset');++ expect(rows[0]).toMatchObject({ kind: 'scope', label: 'Search boards for “sunset”', providerId: 'boards' });+ });});describe('searchPaletteRows', () => {@@ -147,4 +223,11 @@ describe('searchPaletteRows', () => {it('returns no rows for a junk query', () => {expect(searchPaletteRows(entries, 'zzzzqqq', [])).toEqual([]);});++ it('excludes settings entries in commands-only mode (the ">" alias)', () => {+ const rows = searchPaletteRows(entries, 'o', [], { commandsOnly: true });++ expect(rows.map((row) => row.id)).not.toContain('setting.reduceMotion');+ expect(rows.map((row) => row.id)).toContain('app.invoke');+ });});diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.tsindex 5baf5ca167..0cbf271cf3 100644--- a/invokeai/frontend/webv2/src/workbench/palette/entries.ts+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.ts@@ -2,7 +2,8 @@ import type { CustomHotkeys, HotkeyDefinition } from '@workbench/hotkeys/types';import type { WorkbenchPreferences } from '@workbench/settings/contracts';import type { SettingsSectionId } from '@workbench/widgetContracts';-import { THEMES_BY_ID } from '@theme/themes';+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';@@ -15,6 +16,19 @@ import fuzzysort from 'fuzzysort';* the list reads spatially — commands above settings, always.*/+export interface PaletteStageOption {+ id: string;+ label: string;+ isCurrent: boolean;+ apply: () => unknown;+}++/** An inline value-picker pushed over the list (enum settings). */+export interface PaletteStage {+ title: string;+ options: PaletteStageOption[];+}+export interface PaletteEntry {id: string;title: string;@@ -30,12 +44,29 @@ export interface PaletteEntry {keepOpen?: boolean;/** Show in the empty-query launcher state (navigation entries). */showInEmptyState?: boolean;+ /** Enter pushes this value-picker stage instead of running the entry. */+ stage?: PaletteStage;+ /** mod+Enter alternative, advertised in the footer while highlighted. */+ secondary?: { label: string; run: () => unknown };run: () => unknown;}+/** An async entity source the palette can query (workflows, boards, …). */+export interface PaletteSearchProvider {+ id: string;+ label: string;+ search: (query: string) => Promise<PaletteEntry[]> | PaletteEntry[];+}+export type PaletteRow =| { kind: 'label'; id: string; label: string }- | { kind: 'entry'; id: string; entry: PaletteEntry; matchIndexes?: readonly number[] };+ | { kind: 'entry'; id: string; entry: PaletteEntry; matchIndexes?: readonly number[] }+ | { kind: 'scope'; id: string; providerId: string; label: string };++/** Max rows an entity section shows in root mode; depth lives behind the scope. */+export const PROVIDER_ROOT_RESULT_CAP = 3;+/** Entity providers only fire at this query length. */+export const PROVIDER_MIN_QUERY_LENGTH = 2;const PALETTE_GROUP_ORDER = ['Recent',@@ -214,41 +245,88 @@ export const buildSettingsEntries = (preferences: WorkbenchPreferences, deps: Setitle,}));- // Multi-value preferences deep-link to their settings section; the palette- // links to complex pickers rather than replicating them.+ // Multi-value preferences push an inline value-picker stage; mod+Enter (or+ // the section deep-link rows) still reaches the full settings dialog.+ const enumEntry = ({+ id,+ keywords,+ options,+ sectionId,+ subtitle,+ title,+ }: {+ id: string;+ keywords: string;+ options: PaletteStageOption[];+ sectionId: SettingsSectionId;+ subtitle: string;+ title: string;+ }): PaletteEntry => ({+ group: 'Settings',+ id,+ keywords,+ run: () => deps.openSettingsSection(sectionId),+ secondary: { label: 'Open in Settings', run: () => deps.openSettingsSection(sectionId) },+ stage: { options, title },+ subtitle,+ title,+ });+const enums: PaletteEntry[] = [- {- group: 'Settings',+ enumEntry({id: 'setting.themeId',keywords: 'appearance color dark light',- run: () => deps.openSettingsSection('appearance'),+ options: THEMES.map((theme) => ({+ apply: () => deps.patchPreferences({ themeId: theme.id }),+ id: theme.id,+ isCurrent: theme.id === preferences.themeId,+ label: theme.label,+ })),+ sectionId: 'appearance',subtitle: THEMES_BY_ID[preferences.themeId]?.label ?? preferences.themeId,title: 'Theme',- },- {- group: 'Settings',+ }),+ enumEntry({id: 'setting.language',keywords: 'locale translation',- run: () => deps.openSettingsSection('appearance'),- subtitle: preferences.language,+ options: WORKBENCH_LANGUAGE_OPTIONS.map((language) => ({+ apply: () => deps.patchPreferences({ language: language.value }),+ id: language.value,+ isCurrent: language.value === preferences.language,+ label: language.label,+ })),+ sectionId: 'appearance',+ subtitle:+ WORKBENCH_LANGUAGE_OPTIONS.find((language) => language.value === preferences.language)?.label ??+ preferences.language,title: 'Language',- },- {- group: 'Settings',+ }),+ enumEntry({id: 'setting.workflowEdgeStyle',keywords: 'workflow editor connections',- run: () => deps.openSettingsSection('workflow'),+ options: (['curved', 'square'] as const).map((style) => ({+ apply: () => deps.patchPreferences({ workflowEdgeStyle: style }),+ id: style,+ isCurrent: style === preferences.workflowEdgeStyle,+ label: style === 'square' ? 'Square' : 'Curved',+ })),+ sectionId: 'workflow',subtitle: preferences.workflowEdgeStyle === 'square' ? 'Square' : 'Curved',title: 'Workflow Edge Style',- },- {- group: 'Settings',+ }),+ enumEntry({id: 'setting.queueJobsScope',keywords: 'queue filter',- run: () => deps.openSettingsSection('queue'),+ options: (['active-project', 'all'] as const).map((scope) => ({+ apply: () => deps.patchPreferences({ queueJobsScope: scope }),+ id: scope,+ isCurrent: scope === preferences.queueJobsScope,+ label: scope === 'all' ? 'All Projects' : 'Active Project',+ })),+ sectionId: 'queue',subtitle: preferences.queueJobsScope === 'all' ? 'All Projects' : 'Active Project',title: 'Queue Jobs Scope',- },+ }),];const sections = SETTINGS_SECTIONS.map<PaletteEntry>(({ id, title }) => ({@@ -334,15 +412,29 @@ const buildEmptyStateRows = (entries: readonly PaletteEntry[], recentIds: readonexport const searchPaletteRows = (entries: readonly PaletteEntry[],query: string,- recentIds: readonly string[]+ recentIds: readonly string[],+ { commandsOnly = false, showAllOnEmpty = false }: { commandsOnly?: boolean; showAllOnEmpty?: boolean } = {}): PaletteRow[] => {+ const searchable = commandsOnly ? entries.filter((entry) => entry.group !== 'Settings') : entries;const trimmed = query.trim();if (trimmed.length === 0) {- return buildEmptyStateRows(entries, recentIds);+ // Stage mode lists every option before the user types; the root palette+ // shows the curated launcher instead.+ if (showAllOnEmpty) {+ const all = new Map<string, RankedEntry[]>();++ for (const entry of searchable) {+ all.set(entry.group, [...(all.get(entry.group) ?? []), { entry, score: 0 }]);+ }++ return toGroupedRows(all);+ }++ return buildEmptyStateRows(searchable, recentIds);}- const results = fuzzysort.go(trimmed, entries, {+ const results = fuzzysort.go(trimmed, searchable, {keys: [(entry) => entry.title, (entry) => entry.keywords ?? '', (entry) => entry.subtitle ?? ''],scoreFn: (result) => Math.max(result[0]?.score ?? 0, (result[1]?.score ?? 0) * 0.9, (result[2]?.score ?? 0) * 0.5),threshold: MATCH_THRESHOLD,@@ -376,3 +468,71 @@ export const searchPaletteRows = (return toGroupedRows(groups);};++// ---------------------------------------------------------------------------+// Stage / provider row assembly+// ---------------------------------------------------------------------------++/** Turn a value-picker stage into filterable entry rows; picking applies and pops. */+export const buildStageEntries = (stage: PaletteStage, onApplied: () => void): PaletteEntry[] =>+ stage.options.map((option) => ({+ group: stage.title,+ id: `stage:${option.id}`,+ keepOpen: true,+ run: () => {+ void option.apply();+ onApplied();+ },+ subtitle: option.isCurrent ? 'Current' : undefined,+ title: option.label,+ }));++export interface ProviderResultSection {+ provider: Pick<PaletteSearchProvider, 'id' | 'label'>;+ entries: PaletteEntry[];+ isFetching: boolean;+}++/**+ * Entity sections render below local sections as each provider resolves.+ * Empty non-fetching sections drop silently in root mode; `cap` bounds root+ * mode to a teaser (depth lives behind the scope), null means uncapped.+ */+export const buildProviderSectionRows = (+ sections: readonly ProviderResultSection[],+ cap: number | null = PROVIDER_ROOT_RESULT_CAP+): PaletteRow[] => {+ const rows: PaletteRow[] = [];++ for (const section of sections) {+ const visible = cap === null ? section.entries : section.entries.slice(0, cap);++ if (visible.length === 0 && !section.isFetching) {+ continue;+ }++ rows.push({+ id: `label:provider:${section.provider.id}`,+ 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' });+ }+ }++ return rows;+};++/** Trailing escape hatches into scoped mode, one per provider. */+export const buildScopeRows = (+ providers: ReadonlyArray<Pick<PaletteSearchProvider, 'id' | 'label'>>,+ query: string+): PaletteRow[] =>+ providers.map((provider) => ({+ id: `scope:${provider.id}`,+ kind: 'scope',+ label: `Search ${provider.label.toLowerCase()} for “${query}”`,+ providerId: provider.id,+ }));diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.tsnew file mode 100644index 0000000000..7baaf56282--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteProviders.ts@@ -0,0 +1,120 @@+import type { GalleryBoard } from '@features/gallery/contracts';+import type { PromptHistoryItem } from '@workbench/projectContracts';++import { galleryBoardsOptions } from '@features/gallery/queries';+import { focusPositivePrompt } from '@features/generation/react';+import { listLibraryWorkflows } from '@features/workflow/queries';+import { requestLibraryWorkflowLoad } from '@features/workflow/react';+import { queryClient } from '@platform/query/client';++import type { PaletteEntry, PaletteSearchProvider } from './entries';++/**+ * First-party entity providers behind the palette's scoped search. Each is a+ * plain factory taking the workbench callbacks it needs — the host component+ * owns the hooks. Extension `search` contributions adapt into the same+ * PaletteSearchProvider shape, so all sections aggregate identically.+ */++const PROVIDER_PAGE_SIZE = 8;++const matchesTerms = (haystack: string, query: string): boolean => {+ const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean);+ const lower = haystack.toLowerCase();++ return terms.every((term) => lower.includes(term));+};++export const createWorkflowsProvider = ({+ openWorkflowWidget,+}: {+ openWorkflowWidget: () => void;+}): PaletteSearchProvider => ({+ id: 'workflows',+ label: 'Workflows',+ search: async (query) => {+ const [user, defaults] = await Promise.all([+ listLibraryWorkflows({ category: 'user', page: 0, perPage: PROVIDER_PAGE_SIZE, query }),+ listLibraryWorkflows({ category: 'default', page: 0, perPage: PROVIDER_PAGE_SIZE, query }),+ ]);++ return [...user.items, ...defaults.items].map<PaletteEntry>((item) => ({+ group: 'Workflows',+ id: `workflow:${item.workflow_id}`,+ keywords: item.tags ?? undefined,+ run: () => {+ openWorkflowWidget();+ requestLibraryWorkflowLoad(item.workflow_id);+ },+ subtitle: item.category === 'default' ? 'Default workflow' : 'Workflow',+ title: item.name,+ }));+ },+});++export const createBoardsProvider = ({+ openGalleryWidget,+ selectBoard,+}: {+ openGalleryWidget: () => void;+ selectBoard: (boardId: string) => void;+}): PaletteSearchProvider => ({+ id: 'boards',+ label: 'Boards',+ search: async (query) => {+ const boards = await queryClient.fetchQuery(galleryBoardsOptions({ includeArchived: false }));++ return boards+ .filter((board: GalleryBoard) => matchesTerms(board.name, query))+ .map<PaletteEntry>((board) => ({+ group: 'Boards',+ id: `board:${board.id}`,+ run: () => {+ openGalleryWidget();+ selectBoard(board.id);+ },+ subtitle: `Board · ${board.imageCount} image${board.imageCount === 1 ? '' : 's'}`,+ title: board.name,+ }));+ },+});++export const createPromptHistoryProvider = ({+ getPromptHistory,+ openGenerateWidget,+ recallPrompt,+}: {+ getPromptHistory: () => readonly PromptHistoryItem[];+ openGenerateWidget: () => void;+ recallPrompt: (item: PromptHistoryItem) => void;+}): PaletteSearchProvider => ({+ id: 'prompt-history',+ label: 'Prompt history',+ search: (query) => {+ const seen = new Set<string>();+ const entries: PaletteEntry[] = [];++ for (const [index, item] of getPromptHistory().entries()) {+ const dedupeKey = `${item.positivePrompt}\n${item.negativePrompt ?? ''}`;++ if (seen.has(dedupeKey) || !matchesTerms(`${item.positivePrompt} ${item.negativePrompt ?? ''}`, query)) {+ continue;+ }++ seen.add(dedupeKey);+ entries.push({+ group: 'Prompt history',+ id: `prompt:${index}`,+ run: () => {+ openGenerateWidget();+ recallPrompt(item);+ window.requestAnimationFrame(() => focusPositivePrompt());+ },+ subtitle: item.negativePrompt ? `− ${item.negativePrompt}` : undefined,+ title: item.positivePrompt,+ });+ }++ return entries;+ },+});