Skip to content

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

feat(webv2): pick style presets and system prompts in workflow nodes

Josh Corbettd2a729850f25
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index bd11587322..0d4571d169 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1509,6 +1509,16 @@
"addItem": "Add item",
"removeItem": "Remove {{field}} item {{index}}",
"collectionItemLabel": "{{field}} item {{index}}",
+ "stylePresetSearch": "Search style presets…",
+ "stylePresetMissing": "Style preset unavailable",
+ "stylePresetClear": "Clear style preset",
+ "noMatchingStylePresets": "No matching style presets",
+ "systemPromptSearch": "Search system prompts…",
+ "systemPromptMissing": "System prompt unavailable",
+ "systemPromptClear": "Clear system prompt",
+ "noMatchingSystemPrompts": "No matching system prompts",
+ "recordListLoading": "Loading…",
+ "recordListFailed": "The list could not be loaded.",
"collectionItemCount_one": "{{count}} item",
"collectionItemCount_other": "{{count}} items",
"forLoopBodyBoundaryStatus": {
diff --git a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
index b54b121db0..50804d1ab6 100644
--- a/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
+++ b/invokeai/frontend/webv2/src/architecture/dependencyPolicy.test.ts
@@ -237,9 +237,15 @@ describe('feature public-interface registry', () => {
expect(checkDependency('app/GenerateWidgetSyncRuntime.tsx', '@features/generation/runtime')).toEqual([]);
expect(checkDependency('workbench/widgets/canvas/invoke.ts', '@features/generation/canvasGraph')).toEqual([]);
expect(checkDependency('workbench/WorkbenchContext.tsx', '@features/intermediates/holdLease')).toEqual([]);
+ expect(
+ checkDependency('features/workflow/ui/fields/RecordPickerInput.tsx', '@features/generation/systemPrompts')
+ ).toEqual([]);
expect(
checkDependency('workbench/invocationSubmit.ts', '@features/generation/data/dynamicPromptsQueries')
).toMatchObject([{ rule: 'feature-private-interface' }]);
+ expect(
+ checkDependency('features/workflow/ui/fields/RecordPickerInput.tsx', '@features/generation/data/systemPrompts')
+ ).toMatchObject([{ rule: 'feature-public-interface' }]);
});
it('treats unregistered features as fully private', () => {
diff --git a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
index 27422dba8b..65e1035679 100644
--- a/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
+++ b/invokeai/frontend/webv2/src/architecture/featureInterfaces.ts
@@ -28,6 +28,7 @@ export const FEATURE_PUBLIC_INTERFACES: Readonly<Record<string, readonly string[
'react',
'runtime',
'settings',
+ 'systemPrompts',
'widget',
],
identity: [],
diff --git a/invokeai/frontend/webv2/src/features/generation/queries.ts b/invokeai/frontend/webv2/src/features/generation/queries.ts
index 4ff0fa0849..e74aa34e28 100644
--- a/invokeai/frontend/webv2/src/features/generation/queries.ts
+++ b/invokeai/frontend/webv2/src/features/generation/queries.ts
@@ -1,2 +1,2 @@
-/** Generation's server-state query surface for App-owned runtimes. */
+/** Generation's server-state query surface for App-owned runtimes and other features' pickers. */
export { promptTemplatesQueryOptions } from './data/promptTemplates';
diff --git a/invokeai/frontend/webv2/src/features/generation/systemPrompts.ts b/invokeai/frontend/webv2/src/features/generation/systemPrompts.ts
new file mode 100644
index 0000000000..004b6378a2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/systemPrompts.ts
@@ -0,0 +1,5 @@
+/**
+ * System prompt read model for other features' pickers. Kept apart from `queries` so consumers that load lazily
+ * do not pull the list into the editor's boot graph.
+ */
+export { systemPromptsQueryOptions, type SystemPromptRecord } from './data/systemPrompts';
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
index 781a075688..8d5c58076f 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts
@@ -4,6 +4,7 @@ import type { FieldInputTemplate, FieldType } from './types';
import {
getEffectiveWorkflowFieldDescription,
+ getFieldRecordId,
getWorkflowFieldInvalidReason,
isDirectInputField,
isLoraFieldCollectionEntry,
@@ -279,6 +280,30 @@ describe('workflow field validation', () => {
);
});
+ it('validates style preset and system prompt references by their record id', () => {
+ const preset = input({ type: single('StylePresetField') });
+ const prompt = input({ type: single('SystemPromptField') });
+
+ expect(isDirectInputField(preset)).toBe(true);
+ expect(isDirectInputField(prompt)).toBe(true);
+ expect(isWorkflowFieldValueValid(preset, { style_preset_id: 'preset-1' })).toBe(true);
+ expect(isWorkflowFieldValueValid(preset, { style_preset_id: '' })).toBe(false);
+ expect(isWorkflowFieldValueValid(preset, { system_prompt_id: 'prompt-1' })).toBe(false);
+ expect(isWorkflowFieldValueValid(prompt, { system_prompt_id: 'prompt-1' })).toBe(true);
+ expect(isWorkflowFieldValueValid(prompt, 'prompt-1')).toBe(false);
+ expect(getWorkflowFieldInvalidReason({ isConnected: false, template: preset, value: undefined })).toBe(
+ 'Required value.'
+ );
+ expect(getWorkflowFieldInvalidReason({ isConnected: false, template: preset, value: {} })).toBe('Invalid value.');
+ // Core cannot see the preset list, so a stale id stays valid here and the backend rejects it on invoke.
+ expect(
+ getWorkflowFieldInvalidReason({ isConnected: false, template: preset, value: { style_preset_id: 'gone' } })
+ ).toBeNull();
+ expect(getFieldRecordId({ style_preset_id: 'preset-1' }, 'style_preset_id')).toBe('preset-1');
+ expect(getFieldRecordId({ style_preset_id: ' ' }, 'style_preset_id')).toBeNull();
+ expect(getFieldRecordId(undefined, 'style_preset_id')).toBeNull();
+ });
+
it('treats empty board values as the Auto sentinel', () => {
expect(isWorkflowFieldValueValid(input({ type: single('BoardField') }), undefined)).toBe(true);
expect(isWorkflowFieldValueValid(input({ type: single('BoardField') }), { board_id: 'board-id' })).toBe(true);
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
index 0a4c3b3492..a7aef4f32e 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts
@@ -26,6 +26,8 @@ const STATEFUL_FIELD_TYPE_NAMES = new Set([
'SchedulerField',
'SavedWorkflowField',
'StringField',
+ 'StylePresetField',
+ 'SystemPromptField',
'VideoField',
]);
@@ -135,6 +137,10 @@ const isNonEmptyString = (value: unknown): value is string => typeof value === '
const hasNonEmptyStringProp = (value: unknown, prop: string): boolean =>
typeof value === 'object' && value !== null && isNonEmptyString((value as Record<string, unknown>)[prop]);
+/** The id inside a record-reference value such as `{ style_preset_id }`, or null when absent. */
+export const getFieldRecordId = (value: unknown, prop: string): string | null =>
+ hasNonEmptyStringProp(value, prop) ? ((value as Record<string, string>)[prop] as string) : null;
+
/** A LoRA model identifier paired with its weight — one entry of a LoRA collection field. */
export interface LoraFieldCollectionEntry {
lora: { base: string; hash: string; key: string; name: string; type: string };
@@ -320,6 +326,10 @@ export const isWorkflowFieldValueValid = (template: FieldInputTemplate, value: u
return Array.isArray(value) ? value.every(isLoraFieldCollectionEntry) : isLoraFieldCollectionEntry(value);
case 'SchedulerField':
return isNonEmptyString(value);
+ case 'StylePresetField':
+ return hasNonEmptyStringProp(value, 'style_preset_id');
+ case 'SystemPromptField':
+ return hasNonEmptyStringProp(value, 'system_prompt_id');
case 'BoardField':
return (
value === undefined ||
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts
index 294425da56..53ecac8c10 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts
@@ -105,6 +105,13 @@ const openApiFixture = {
title: 'Scheduler',
type: 'string',
},
+ style_preset: {
+ anyOf: [{ $ref: '#/components/schemas/StylePresetField' }, { type: 'null' }],
+ field_kind: 'input',
+ input: 'any',
+ orig_required: true,
+ title: 'Style Preset',
+ },
type: { const: 'denoise', default: 'denoise', title: 'type' },
use_cache: { default: true, field_kind: 'internal', type: 'boolean' },
},
@@ -241,6 +248,13 @@ describe('parseOpenApiToTemplates', () => {
});
expect(denoise?.inputs.scheduler?.type.name).toBe('EnumField');
expect(denoise?.inputs.scheduler?.options).toEqual(['euler', 'ddim']);
+ // Record references (`{ style_preset_id }`) arrive as bare refs with no schema default; unset until picked.
+ expect(denoise?.inputs.style_preset).toMatchObject({
+ default: undefined,
+ input: 'any',
+ required: true,
+ type: { batch: false, cardinality: 'SINGLE', name: 'StylePresetField' },
+ });
});
it('reads list bounds and item constraints from the array schema of a collection input', () => {
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/RecordPickerInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/RecordPickerInput.tsx
new file mode 100644
index 0000000000..c1ebe0ac04
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/RecordPickerInput.tsx
@@ -0,0 +1,148 @@
+import { HStack, Stack, Text } from '@chakra-ui/react';
+import { promptTemplatesQueryOptions } from '@features/generation/queries';
+import { systemPromptsQueryOptions } from '@features/generation/systemPrompts';
+import { getFieldRecordId } from '@features/workflow/utility';
+import { Combobox, IconButton, Tooltip } from '@platform/ui';
+import { useQuery } from '@tanstack/react-query';
+import { RotateCcwIcon, XIcon } from 'lucide-react';
+import { useCallback, useId, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { WorkflowFieldInputProps } from './WorkflowFieldInput';
+
+interface RecordPickerLabels {
+ clear: string;
+ missing: string;
+ noMatches: string;
+ search: string;
+}
+
+interface RecordListQuery {
+ isError: boolean;
+ isFetching: boolean;
+ records: readonly { id: string; name: string }[] | undefined;
+ refetch: () => void;
+}
+
+/**
+ * Picks one server record by id for `{ [idProp]: id }` values. A stored id the list no longer holds stays put and
+ * is shown as missing: readiness cannot see the list, so the backend reports the stale reference on invoke.
+ */
+const RecordPickerInput = ({
+ idProp,
+ invalid,
+ labels,
+ onChange,
+ query,
+ template,
+ value,
+}: WorkflowFieldInputProps & { idProp: string; labels: RecordPickerLabels; query: RecordListQuery }) => {
+ const { t } = useTranslation();
+ const { isError, isFetching, records, refetch } = query;
+ const messageId = useId();
+ const inputRef = useRef<HTMLInputElement>(null);
+ const selectedId = getFieldRecordId(value, idProp);
+ const isMissing = selectedId !== null && records !== undefined && !records.some((record) => record.id === selectedId);
+ const message = isMissing ? labels.missing : isError ? t('nodes.recordListFailed') : null;
+ const options = useMemo(() => {
+ const base = (records ?? []).map((record) => ({ label: record.name, value: record.id }));
+
+ return isMissing && selectedId !== null ? [{ label: labels.missing, value: selectedId }, ...base] : base;
+ }, [isMissing, labels.missing, records, selectedId]);
+ const inputProps = useMemo(
+ () => ({ ref: inputRef, 'aria-describedby': message !== null ? messageId : undefined }),
+ [message, messageId]
+ );
+ const onPick = useCallback((id: string) => onChange({ [idProp]: id }), [idProp, onChange]);
+ // The clear button leaves with the value; hand keyboard focus to the input before it goes.
+ const onClear = useCallback(() => {
+ inputRef.current?.focus();
+ onChange(undefined);
+ }, [onChange]);
+ const onRetry = useCallback(() => refetch(), [refetch]);
+
+ return (
+ <Stack gap="1" minW="0" w="full">
+ <HStack gap="1" minW="0" w="full">
+ <Combobox
+ aria-label={template.title}
+ className="nodrag nowheel"
+ flex="1"
+ inputProps={inputProps}
+ invalid={invalid || isMissing}
+ noResultsText={labels.noMatches}
+ options={options}
+ searchPlaceholder={isFetching && records === undefined ? t('nodes.recordListLoading') : labels.search}
+ value={selectedId}
+ onValueChange={onPick}
+ />
+ {isError ? (
+ <Tooltip content={t('common.retry')}>
+ <IconButton
+ aria-label={t('common.retry')}
+ className="nodrag"
+ disabled={isFetching}
+ size="xs"
+ variant="ghost"
+ onClick={onRetry}
+ >
+ <RotateCcwIcon />
+ </IconButton>
+ </Tooltip>
+ ) : null}
+ {selectedId !== null ? (
+ <Tooltip content={labels.clear}>
+ <IconButton aria-label={labels.clear} className="nodrag" size="xs" variant="ghost" onClick={onClear}>
+ <XIcon />
+ </IconButton>
+ </Tooltip>
+ ) : null}
+ </HStack>
+ {message !== null ? (
+ <Text color="fg.error" fontSize="2xs" id={messageId}>
+ {message}
+ </Text>
+ ) : null}
+ </Stack>
+ );
+};
+
+export const StylePresetInput = (props: WorkflowFieldInputProps) => {
+ const { t } = useTranslation();
+ const { data, isError, isFetching, refetch } = useQuery(promptTemplatesQueryOptions());
+ const labels = useMemo<RecordPickerLabels>(
+ () => ({
+ clear: t('nodes.stylePresetClear'),
+ missing: t('nodes.stylePresetMissing'),
+ noMatches: t('nodes.noMatchingStylePresets'),
+ search: t('nodes.stylePresetSearch'),
+ }),
+ [t]
+ );
+ const query = useMemo<RecordListQuery>(
+ () => ({ isError, isFetching, records: data, refetch: () => void refetch() }),
+ [data, isError, isFetching, refetch]
+ );
+
+ return <RecordPickerInput {...props} idProp="style_preset_id" labels={labels} query={query} />;
+};
+
+export const SystemPromptInput = (props: WorkflowFieldInputProps) => {
+ const { t } = useTranslation();
+ const { data, isError, isFetching, refetch } = useQuery(systemPromptsQueryOptions());
+ const labels = useMemo<RecordPickerLabels>(
+ () => ({
+ clear: t('nodes.systemPromptClear'),
+ missing: t('nodes.systemPromptMissing'),
+ noMatches: t('nodes.noMatchingSystemPrompts'),
+ search: t('nodes.systemPromptSearch'),
+ }),
+ [t]
+ );
+ const query = useMemo<RecordListQuery>(
+ () => ({ isError, isFetching, records: data, refetch: () => void refetch() }),
+ [data, isError, isFetching, refetch]
+ );
+
+ return <RecordPickerInput {...props} idProp="system_prompt_id" labels={labels} query={query} />;
+};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
index fff158fa8a..e53eaa9240 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx
@@ -231,7 +231,8 @@ afterEach(async () => {
host.remove();
});
-const queryClient = new QueryClient();
+// No retry backoff: failure states must be observable inside a test timeout.
+const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const renderField = async (
template: FieldInputTemplate,
@@ -1840,3 +1841,99 @@ describe('WorkflowFieldInput scalar collections', () => {
expect(document.activeElement).toBe(button('nodes.addItem'));
});
});
+
+describe('WorkflowFieldInput record pickers', () => {
+ const STYLE_PRESET = fullTemplate('StringField', {
+ title: 'Style Preset',
+ type: { batch: false, cardinality: 'SINGLE', name: 'StylePresetField' },
+ });
+ const SYSTEM_PROMPT = fullTemplate('StringField', {
+ title: 'System Prompt',
+ type: { batch: false, cardinality: 'SINGLE', name: 'SystemPromptField' },
+ });
+ const presetDto = (id: string, name: string) => ({
+ id,
+ image: null,
+ is_public: false,
+ name,
+ preset_data: { negative_prompt: '', positive_prompt: '{prompt}, cinematic' },
+ type: 'user',
+ user_id: 'user-1',
+ });
+ const promptDto = (id: string, name: string) => ({
+ content: 'Be helpful.',
+ id,
+ is_public: true,
+ max_tokens: null,
+ name,
+ user_id: 'user-1',
+ });
+ const combobox = () => host.querySelector<HTMLInputElement>('input[role="combobox"]');
+ const option = (label: string) =>
+ Array.from(document.querySelectorAll<HTMLElement>('[data-scope="combobox"][data-part="item"]')).find((item) =>
+ item.textContent?.includes(label)
+ );
+
+ it('picks a style preset by name and clears it back to an absent value', async () => {
+ workflowApiMock.apiFetchJson.mockResolvedValue([
+ presetDto('preset-1', 'Cinematic'),
+ presetDto('preset-2', 'Anime'),
+ ]);
+ const onChange = vi.fn();
+
+ await renderField(STYLE_PRESET, undefined, onChange);
+ await vi.waitFor(() => expect(combobox()?.placeholder).toBe('nodes.stylePresetSearch'));
+ expect(host.querySelector('button[aria-label="nodes.stylePresetClear"]')).toBeNull();
+
+ await act(() => userEvent.click(combobox()!));
+ await vi.waitFor(() => expect(option('Anime')).toBeDefined());
+ await act(() => userEvent.click(option('Anime')!));
+ expect(onChange).toHaveBeenLastCalledWith({ style_preset_id: 'preset-2' });
+
+ await renderField(STYLE_PRESET, { style_preset_id: 'preset-2' }, onChange);
+ await vi.waitFor(() => expect(combobox()?.value).toBe('Anime'));
+ expect(combobox()?.getAttribute('aria-invalid')).toBeNull();
+ await act(() =>
+ userEvent.click(host.querySelector<HTMLButtonElement>('button[aria-label="nodes.stylePresetClear"]')!)
+ );
+ expect(onChange).toHaveBeenLastCalledWith(undefined);
+ // The clear button leaves with the value; focus lands on the input rather than falling to the page.
+ expect(document.activeElement).toBe(combobox());
+ });
+
+ it('keeps a system prompt id the list no longer holds and flags it as missing', async () => {
+ workflowApiMock.apiFetchJson.mockResolvedValue([promptDto('prompt-1', 'Helpful')]);
+ const onChange = vi.fn();
+
+ await renderField(SYSTEM_PROMPT, { system_prompt_id: 'prompt-gone' }, onChange);
+ await vi.waitFor(() => expect(combobox()?.value).toBe('nodes.systemPromptMissing'));
+ expect(combobox()?.getAttribute('aria-invalid')).toBe('true');
+ // The reason is linked to the input so assistive tech reads it with the invalid state.
+ const describedBy = combobox()?.getAttribute('aria-describedby');
+ expect(describedBy).toBeTruthy();
+ expect(document.getElementById(describedBy!)?.textContent).toBe('nodes.systemPromptMissing');
+ expect(onChange).not.toHaveBeenCalled();
+
+ // The live record is still offered next to the missing one.
+ await act(() => userEvent.click(combobox()!));
+ await vi.waitFor(() => expect(option('Helpful')).toBeDefined());
+ await act(() => userEvent.click(option('Helpful')!));
+ expect(onChange).toHaveBeenLastCalledWith({ system_prompt_id: 'prompt-1' });
+ });
+
+ it('offers a retry when the list fails to load', async () => {
+ workflowApiMock.apiFetchJson.mockRejectedValue(new Error('offline'));
+
+ await renderField(SYSTEM_PROMPT, undefined, vi.fn());
+ await vi.waitFor(() =>
+ expect(host.querySelector<HTMLButtonElement>('button[aria-label="common.retry"]')).not.toBeNull()
+ );
+ expect(host.textContent).toContain('nodes.recordListFailed');
+
+ workflowApiMock.apiFetchJson.mockResolvedValue([promptDto('prompt-1', 'Helpful')]);
+ await act(() => userEvent.click(host.querySelector<HTMLButtonElement>('button[aria-label="common.retry"]')!));
+ await vi.waitFor(() => expect(host.querySelector('button[aria-label="common.retry"]')).toBeNull());
+ await act(() => userEvent.click(combobox()!));
+ await vi.waitFor(() => expect(option('Helpful')).toBeDefined());
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
index 6063774d4b..2a16006c04 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
@@ -116,6 +116,19 @@ const MODEL_SELECT_FALLBACK = (
Loading models…
</Button>
);
+const RECORD_PICKER_FALLBACK = (
+ <Button disabled size="xs" w="full">
+ Loading…
+ </Button>
+);
+
+// Record pickers load with their node so the system-prompt query stays out of the editor's boot graph.
+const StylePresetInput = lazy(() =>
+ import('./RecordPickerInput').then((module) => ({ default: module.StylePresetInput }))
+);
+const SystemPromptInput = lazy(() =>
+ import('./RecordPickerInput').then((module) => ({ default: module.SystemPromptInput }))
+);
export const getWorkflowSelectedGalleryImage = getSelectedGalleryImageFromValues;
@@ -1883,6 +1896,18 @@ export const WorkflowFieldInput = (props: WorkflowFieldInputProps) => {
return <ModelIdentifierInput {...props} />;
case 'SchedulerField':
return <SchedulerInput {...props} />;
+ case 'StylePresetField':
+ return (
+ <Suspense fallback={RECORD_PICKER_FALLBACK}>
+ <StylePresetInput {...props} />
+ </Suspense>
+ );
+ case 'SystemPromptField':
+ return (
+ <Suspense fallback={RECORD_PICKER_FALLBACK}>
+ <SystemPromptInput {...props} />
+ </Suspense>
+ );
case 'BoardField':
return <BoardInput {...props} />;
case 'ImageField':