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.

fix(webv2): repair saved workflow integration

JPPhoto29c56171ebbe
diff --git a/invokeai/frontend/web/src/features/nodes/types/invocation.test.ts b/invokeai/frontend/web/src/features/nodes/types/invocation.test.ts
index 3b92f63108..1acc0c3885 100644
--- a/invokeai/frontend/web/src/features/nodes/types/invocation.test.ts
+++ b/invokeai/frontend/web/src/features/nodes/types/invocation.test.ts
@@ -96,4 +96,38 @@ describe('zInvocationNodeData: extra-input scoping', () => {
expect(parsed.inputs.z_image_seed_variance_enabled?.value).toBe(false);
expect(parsed.inputs.z_image_seed_variance_strength?.value).toBe(0.1);
});
+
+ it('normalizes webv2 dynamic input templates', () => {
+ const parsed = zInvocationNodeData.parse({
+ ...buildNodeData('call_saved_workflow', {}),
+ dynamicInputTemplates: {
+ board: {
+ batch: false,
+ cardinality: 'SINGLE',
+ description: 'Child board',
+ fieldKind: 'internal',
+ input: 'any',
+ name: 'board',
+ required: false,
+ title: 'Board',
+ type: { batch: false, cardinality: 'SINGLE', name: 'BoardField' },
+ uiChoiceLabels: null,
+ uiComponent: null,
+ uiHidden: false,
+ uiModelBase: null,
+ uiModelFormat: null,
+ uiModelType: null,
+ uiOrder: null,
+ },
+ },
+ });
+
+ expect(parsed.dynamicInputTemplates.board).toMatchObject({
+ fieldKind: 'input',
+ name: 'board',
+ title: 'Board',
+ type: { name: 'BoardField' },
+ ui_hidden: false,
+ });
+ });
});
diff --git a/invokeai/frontend/web/src/features/nodes/types/invocation.ts b/invokeai/frontend/web/src/features/nodes/types/invocation.ts
index 4013e2518c..f41a8055dd 100644
--- a/invokeai/frontend/web/src/features/nodes/types/invocation.ts
+++ b/invokeai/frontend/web/src/features/nodes/types/invocation.ts
@@ -7,6 +7,60 @@ import type { FieldInputInstance } from './field';
import { zFieldInputInstance, zFieldInputInstanceWithExtras, zFieldInputTemplate, zFieldOutputTemplate } from './field';
import { zSemVer } from './semver';
+const zWebv2DynamicInputTemplate = z
+ .object({
+ default: z.unknown().optional(),
+ description: z.string(),
+ exclusiveMaximum: z.number().nullable().optional(),
+ exclusiveMinimum: z.number().nullable().optional(),
+ fieldKind: z.enum(['input', 'internal']),
+ input: z.enum(['connection', 'direct', 'any']),
+ maximum: z.number().nullable().optional(),
+ minimum: z.number().nullable().optional(),
+ multipleOf: z.number().nullable().optional(),
+ name: z.string(),
+ options: z.array(z.string()).nullable().optional(),
+ required: z.boolean(),
+ title: z.string(),
+ type: z.object({
+ batch: z.boolean(),
+ cardinality: z.enum(['SINGLE', 'COLLECTION', 'SINGLE_OR_COLLECTION']),
+ name: z.string(),
+ originalType: z.unknown().optional(),
+ }),
+ uiChoiceLabels: z.record(z.string(), z.string()).nullable().optional(),
+ uiComponent: z.enum(['slider', 'textarea', 'video-frame-index']).nullable().optional(),
+ uiHidden: z.boolean(),
+ uiModelBase: z.array(z.string()).nullable().optional(),
+ uiModelFormat: z.array(z.string()).nullable().optional(),
+ uiModelType: z.array(z.string()).nullable().optional(),
+ uiOrder: z.number().int().nullable().optional(),
+ })
+ .transform((template) => ({
+ ...template,
+ fieldKind: 'input' as const,
+ labels: template.uiChoiceLabels ?? undefined,
+ exclusiveMaximum: template.exclusiveMaximum ?? undefined,
+ exclusiveMinimum: template.exclusiveMinimum ?? undefined,
+ maximum: template.maximum ?? undefined,
+ minimum: template.minimum ?? undefined,
+ multipleOf: template.multipleOf ?? undefined,
+ options: template.options ?? undefined,
+ originalType: template.type.originalType,
+ type: template.type,
+ ui_choice_labels: template.uiChoiceLabels ?? undefined,
+ ui_component: template.uiComponent ?? undefined,
+ ui_hidden: template.uiHidden,
+ ui_model_base: template.uiModelBase ?? undefined,
+ ui_model_format: template.uiModelFormat ?? undefined,
+ ui_model_type: template.uiModelType ?? undefined,
+ ui_order: template.uiOrder ?? undefined,
+ ui_type: undefined,
+ }))
+ .pipe(zFieldInputTemplate);
+
+const zCompatibleFieldInputTemplate = z.union([zFieldInputTemplate, zWebv2DynamicInputTemplate]);
+
// #region InvocationTemplate
const _zInvocationTemplate = z.object({
type: z.string(),
@@ -37,7 +91,7 @@ export const zInvocationNodeData = z
// Parsed per-input in the transform below so that the input-instance schema can be chosen based
// on the node type (extras are only accepted for nodes that declare `extra='allow'`).
inputs: z.record(z.string(), z.unknown()),
- dynamicInputTemplates: z.record(z.string(), zFieldInputTemplate).default({}),
+ dynamicInputTemplates: z.record(z.string(), zCompatibleFieldInputTemplate).default({}),
isOpen: z.boolean(),
isIntermediate: z.boolean(),
useCache: z.boolean(),
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 5b6866af68..09be108354 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1439,8 +1439,9 @@
"savedWorkflowShared": "Shared",
"savedWorkflowSearch": "Search saved workflows…",
"savedWorkflowClear": "Clear saved workflow",
+ "savedWorkflowLoading": "Loading saved workflow…",
+ "savedWorkflowNoExposedFields": "This workflow has no exposed fields.",
"savedWorkflowUpdating": "Updating saved workflows…",
- "savedWorkflowSelectExposedFields": "Select a saved workflow to show its exposed fields.",
"noMatchingWorkflows": "No matching saved workflows",
"iterationOutputs": "Iteration outputs",
"finalOutputs": "Final outputs",
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts
index 0dc246fa73..6768c24a3f 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts
@@ -9,6 +9,7 @@ import {
isSeedInputField,
planWorkflowSubmission,
} from './buildGraph';
+import { CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX } from './callSavedWorkflow';
import {
buildConnectorNode,
buildInvocationNode,
@@ -324,7 +325,7 @@ describe('compileProjectGraph', () => {
]);
});
- it('preserves auto/none board sentinels and keeps explicit boards', () => {
+ it('omits auto/none board sentinels from ordinary nodes and keeps explicit boards', () => {
const { doc, sinkId } = buildDocument();
const withAutoBoard = projectGraphReducer(doc, {
fieldName: 'board',
@@ -333,7 +334,7 @@ describe('compileProjectGraph', () => {
value: 'auto',
});
- expect(compileProjectGraph(withAutoBoard, templates).backendGraph?.nodes[sinkId]).toMatchObject({ board: 'auto' });
+ expect(compileProjectGraph(withAutoBoard, templates).backendGraph?.nodes[sinkId]).not.toHaveProperty('board');
const withNoneBoard = projectGraphReducer(doc, {
fieldName: 'board',
@@ -342,7 +343,7 @@ describe('compileProjectGraph', () => {
value: 'none',
});
- expect(compileProjectGraph(withNoneBoard, templates).backendGraph?.nodes[sinkId]).toMatchObject({ board: 'none' });
+ expect(compileProjectGraph(withNoneBoard, templates).backendGraph?.nodes[sinkId]).not.toHaveProperty('board');
const withExplicitBoard = projectGraphReducer(doc, {
fieldName: 'board',
@@ -356,6 +357,27 @@ describe('compileProjectGraph', () => {
});
});
+ it('preserves auto/none board sentinels only in Call Saved Workflow inputs', () => {
+ const callTemplate = template('call_saved_workflow', {
+ workflow_id: input('workflow_id', { type: { batch: false, cardinality: 'SINGLE', name: 'StringField' } }),
+ });
+ const callNode = buildInvocationNode(callTemplate, { x: 0, y: 0 });
+ const dynamicBoardName = `${CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX}${callNode.id}::board`;
+ callNode.data.dynamicInputTemplates = {
+ [dynamicBoardName]: input(dynamicBoardName, {
+ type: { batch: false, cardinality: 'SINGLE', name: 'BoardField' },
+ }),
+ };
+ callNode.data.inputs[dynamicBoardName] = { label: 'Board', name: dynamicBoardName, value: 'auto' };
+ const document = { ...createProjectGraph('call-saved-workflow-board'), nodes: [callNode] };
+ const graph = compileProjectGraph(document, { call_saved_workflow: callTemplate }).backendGraph;
+
+ expect(graph.nodes[callNode.id]).not.toHaveProperty(dynamicBoardName);
+ expect(graph.nodes[callNode.id]).toMatchObject({
+ workflow_inputs: { [dynamicBoardName]: 'auto' },
+ });
+ });
+
it('resolves connector chains into executable backend edges', () => {
const sourceNode = buildInvocationNode(templates.source, { x: 0, y: 0 });
const sinkNode = buildInvocationNode(templates.sink, { x: 10, y: 0 });
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts
index 785dda864e..8ce1d40b18 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts
@@ -61,12 +61,8 @@ const getNodeInputTemplates = (
template: InvocationTemplates[string]
): FieldInputTemplate[] => Object.values({ ...template.inputs, ...node.data.dynamicInputTemplates });
-/**
- * Translates a board field value to the backend shape: `auto` and `none`
- * sentinels are passed through for backend board handling.
- */
const toBoardGraphValue = (value: unknown): unknown => {
- if (isEmptyValue(value)) {
+ if (isEmptyValue(value) || value === 'auto' || value === 'none') {
return undefined;
}
@@ -196,9 +192,13 @@ export const getProjectGraphReadiness = (
return { canInvoke: reasons.length === 0, reasons };
};
-const toGraphInputValue = (inputTemplate: FieldInputTemplate, value: unknown): unknown => {
+const toGraphInputValue = (
+ inputTemplate: FieldInputTemplate,
+ value: unknown,
+ options: { preserveBoardSentinel?: boolean } = {}
+): unknown => {
if (inputTemplate.type.name === 'BoardField') {
- return toBoardGraphValue(value);
+ return options.preserveBoardSentinel ? value : toBoardGraphValue(value);
}
return value;
@@ -238,13 +238,14 @@ export const compileProjectGraph = (
continue;
}
- const value = toGraphInputValue(inputTemplate, instance.value);
+ const isSavedWorkflowInput =
+ node.data.type === 'call_saved_workflow' && instance.name.startsWith(CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX);
+ const value = toGraphInputValue(inputTemplate, instance.value, {
+ preserveBoardSentinel: isSavedWorkflowInput,
+ });
if (value !== undefined) {
- if (
- node.data.type === 'call_saved_workflow' &&
- instance.name.startsWith(CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX)
- ) {
+ if (isSavedWorkflowInput) {
workflowInputs[instance.name] = value;
} else {
graphNode[instance.name] = value;
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.test.ts
index 06b24afca8..214fed30cf 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.test.ts
@@ -192,6 +192,41 @@ describe('Call Saved Workflow dynamic fields', () => {
});
});
+ it('preserves valid dynamic values and presentation from parents without templates', () => {
+ const callNode = buildInvocationNode(callSavedWorkflowTemplate, { x: 0, y: 0 });
+ callNode.id = 'call-1';
+ callNode.data.inputs[dynamicFieldName('a')] = {
+ description: 'Persisted description',
+ label: 'Persisted label',
+ name: dynamicFieldName('a'),
+ value: 99,
+ };
+ callNode.data.inputs[dynamicFieldName('b')] = {
+ label: '',
+ name: dynamicFieldName('b'),
+ value: 'not an integer',
+ };
+
+ const fields = getSavedWorkflowDynamicFields(buildChildWorkflow(), templates);
+ const document = syncCallSavedWorkflowFields(
+ { ...createProjectGraph('legacy-parent'), nodes: [callNode] },
+ callNode.id,
+ fields,
+ []
+ );
+ const node = document.nodes.find((candidate): candidate is WorkflowInvocationNode => candidate.id === callNode.id);
+
+ expect(node?.data.inputs[dynamicFieldName('a')]).toMatchObject({
+ description: 'Persisted description',
+ label: 'Persisted label',
+ value: 99,
+ });
+ expect(node?.data.inputs[dynamicFieldName('b')]).toMatchObject({
+ label: 'B',
+ value: 2,
+ });
+ });
+
it('deduplicates duplicate child form fields before syncing', () => {
const child = buildChildWorkflow();
const root = child.form.elements[child.form.rootElementId];
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.ts b/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.ts
index af0ed3f402..81392ed3a6 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.ts
@@ -8,7 +8,7 @@ import type {
} from './types';
import { getResolvedWorkflowEdges } from './connectors';
-import { isDirectInputField } from './fields';
+import { isDirectInputField, isWorkflowFieldValueValid } from './fields';
import { isInvocationNode } from './types';
import { validateConnectionTypes } from './validation';
@@ -232,13 +232,21 @@ export const syncCallSavedWorkflowFields = (
for (const field of uniqueFields) {
const previous = node.data.inputs[field.fieldName];
const previousTemplate = previousTemplates[field.fieldName];
- const keepValue = previous && previousTemplate && sameFieldType(previousTemplate, field.fieldTemplate);
+ const keepValue =
+ previous &&
+ (previousTemplate
+ ? sameFieldType(previousTemplate, field.fieldTemplate)
+ : isWorkflowFieldValueValid(field.fieldTemplate, previous.value));
const label =
- keepValue && previous && previousTemplate && previous.label !== previousTemplate.title
+ keepValue && previous && (!previousTemplate ? previous.label !== '' : previous.label !== previousTemplate.title)
? previous.label
: field.label;
const description =
- keepValue && previous && previousTemplate && (previous.description ?? '') !== previousTemplate.description
+ keepValue &&
+ previous &&
+ (!previousTemplate
+ ? (previous.description ?? '') !== ''
+ : (previous.description ?? '') !== previousTemplate.description)
? previous.description
: field.description;
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts
index 5e51a1f860..480cc81113 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts
@@ -423,6 +423,11 @@ describe('getProjectGraphUndoEntry', () => {
expect(getProjectGraphUndoEntry({ fieldName: 'a', nodeId: 'n', type: 'setFieldValue', value: true })).toEqual({
label: 'Edit workflow field value',
});
+ expect(
+ getProjectGraphUndoEntry({ fieldName: 'workflow_id', nodeId: 'n', type: 'setFieldValue', value: 'workflow-a' })
+ ).toEqual({
+ label: 'Edit workflow field value',
+ });
expect(getProjectGraphUndoEntry({ nodeId: 'n', type: 'setNodeUseCache', useCache: false })).toEqual({
label: 'Change workflow node caching',
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.ts
index 9e92a99778..5d12ccbd79 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/document.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.ts
@@ -382,9 +382,11 @@ const getUndoMergeKey = (action: ProjectGraphAction): string | undefined => {
return `${action.type}:${action.nodeId}:${action.fieldName}`;
case 'setFieldValue':
// Typed text and dragged numbers stream; a pick (model, board, switch) is one step of its own.
- return typeof action.value === 'string' || typeof action.value === 'number'
- ? `${action.type}:${action.nodeId}:${action.fieldName}`
- : undefined;
+ return action.fieldName === 'workflow_id'
+ ? undefined
+ : typeof action.value === 'string' || typeof action.value === 'number'
+ ? `${action.type}:${action.nodeId}:${action.fieldName}`
+ : undefined;
case 'setNodeLabel':
case 'setNodeNotes':
return `${action.type}:${action.nodeId}`;
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts
index 543e962fc3..ea0e4b2139 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import type { InvocationTemplate } from './types';
+import type { FieldInputTemplate, InvocationTemplate } from './types';
import {
buildCurrentImageNode,
@@ -116,6 +116,37 @@ describe('workflow JSON round-trip', () => {
});
});
+ it('round-trips internal BoardField dynamic templates for legacy readers', () => {
+ const node = buildInvocationNode(template, { x: 0, y: 0 });
+ const boardTemplate: FieldInputTemplate = {
+ ...template.inputs.prompt!,
+ default: undefined,
+ fieldKind: 'internal',
+ name: 'board',
+ title: 'Board',
+ type: { batch: false, cardinality: 'SINGLE', name: 'BoardField' },
+ };
+ node.data.dynamicInputTemplates = { board: boardTemplate };
+ const document = projectGraphReducer(createProjectGraph('legacy-dynamic-board'), {
+ node,
+ type: 'addNode',
+ });
+
+ const serialized = serializeWorkflowJson(document) as {
+ nodes: Array<{ data: { dynamicInputTemplates: Record<string, Record<string, unknown>> } }>;
+ };
+ const persisted = serialized.nodes[0]?.data.dynamicInputTemplates.board;
+
+ expect(persisted).toMatchObject({
+ fieldKind: 'internal',
+ type: { name: 'BoardField' },
+ uiHidden: false,
+ });
+ expect(parseWorkflowJson(serialized).document.nodes[0]).toMatchObject({
+ data: { dynamicInputTemplates: { board: boardTemplate } },
+ });
+ });
+
it('round-trips notes, current_image, and connector UI nodes', () => {
let doc = createProjectGraph('ui-nodes');
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts
index fbcbe30974..12a5c433a8 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts
@@ -135,8 +135,11 @@ describe('workflow library cache invalidation listeners', () => {
cache.invalidateWorkflowLibraryCache();
expect(listener).toHaveBeenCalledTimes(1);
+ cache.invalidateWorkflowLibraryCache('workflow-1');
+ expect(listener).toHaveBeenLastCalledWith('workflow-1');
+
unsubscribe();
cache.invalidateWorkflowLibraryCache();
- expect(listener).toHaveBeenCalledTimes(1);
+ expect(listener).toHaveBeenCalledTimes(2);
});
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.ts
index bb7b9254da..8035592d81 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.ts
@@ -63,20 +63,22 @@ export const getLibraryWorkflowCached = async (
return result;
};
-const invalidationListeners = new Set<() => void>();
+type WorkflowLibraryCacheInvalidationListener = (workflowId?: string) => void;
+
+const invalidationListeners = new Set<WorkflowLibraryCacheInvalidationListener>();
/** Registers a listener fired at the end of every `invalidateWorkflowLibraryCache()` call. */
-export const onWorkflowLibraryCacheInvalidated = (listener: () => void): (() => void) => {
+export const onWorkflowLibraryCacheInvalidated = (listener: WorkflowLibraryCacheInvalidationListener): (() => void) => {
invalidationListeners.add(listener);
return () => invalidationListeners.delete(listener);
};
-export const invalidateWorkflowLibraryCache = (): void => {
+export const invalidateWorkflowLibraryCache = (workflowId?: string): void => {
pageCache.clear();
workflowCache.clear();
for (const listener of invalidationListeners) {
- listener();
+ listener(workflowId);
}
};
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.test.ts
index 15c8d216f6..0718a18f08 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.test.ts
@@ -13,9 +13,10 @@ const workflows = [
{
category: 'user' as const,
call_saved_workflow_compatibility: { is_callable: true, message: null, reason: 'ok' },
- description: '',
+ description: 'A landscape starter',
is_public: false,
name: 'Alpha Workflow',
+ tags: 'landscape,starter',
workflow_id: 'workflow-a',
},
{
@@ -35,7 +36,12 @@ const workflows = [
describe('savedWorkflowFieldUtils', () => {
it('builds named picker options and disables incompatible workflows', () => {
expect(buildSavedWorkflowOptions(workflows)).toEqual([
- { disabled: false, label: 'Alpha Workflow', value: 'workflow-a' },
+ {
+ disabled: false,
+ label: 'Alpha Workflow',
+ searchText: 'A landscape starter landscape,starter',
+ value: 'workflow-a',
+ },
{ disabled: true, label: 'Beta Workflow', value: 'workflow-b' },
]);
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.ts b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.ts
index f74316522d..7a1082e8fd 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.ts
@@ -10,11 +10,18 @@ export type SavedWorkflowSelectionState =
| { status: 'missing'; workflowId: string };
export const buildSavedWorkflowOptions = (workflows: WorkflowLibraryListItem[]): ComboboxOption[] =>
- workflows.map((workflow) => ({
- disabled: workflow.call_saved_workflow_compatibility?.is_callable === false,
- label: workflow.name,
- value: workflow.workflow_id,
- }));
+ workflows.map((workflow) => {
+ const searchText = [workflow.description, workflow.tags]
+ .filter((value): value is string => Boolean(value))
+ .join(' ');
+
+ return {
+ disabled: workflow.call_saved_workflow_compatibility?.is_callable === false,
+ label: workflow.name,
+ ...(searchText ? { searchText } : {}),
+ value: workflow.workflow_id,
+ };
+ });
const baseSavedWorkflowPickerQuery = {
page: 0,
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.test.ts
index ba8f0ab8da..8ec17c7621 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.test.ts
@@ -1,3 +1,4 @@
+import { QueryClient } from '@tanstack/react-query';
import { describe, expect, it } from 'vitest';
import {
@@ -14,7 +15,7 @@ describe('saved workflow detail query policy', () => {
expect(isSavedWorkflowDetailQueryKey(['workflow', 'call-saved', 'detail'])).toBe(false);
});
- it('fetches missing or invalidated detail queries but never retries an error from cache notifications', () => {
+ it('fetches missing or invalidated detail queries and only retries explicitly invalidated errors', () => {
expect(shouldFetchSavedWorkflowDetail(undefined)).toBe(true);
expect(
shouldFetchSavedWorkflowDetail({ state: { fetchStatus: 'idle', isInvalidated: true, status: 'success' } })
@@ -28,6 +29,12 @@ describe('saved workflow detail query policy', () => {
expect(
shouldFetchSavedWorkflowDetail({ state: { fetchStatus: 'idle', isInvalidated: true, status: 'error' } })
).toBe(false);
+ expect(
+ shouldFetchSavedWorkflowDetail(
+ { state: { fetchStatus: 'idle', isInvalidated: true, status: 'error' } },
+ { retryErrors: true }
+ )
+ ).toBe(true);
});
it('classifies detail query state for reconciliation', () => {
@@ -43,9 +50,57 @@ describe('saved workflow detail query policy', () => {
state: { data: { workflow_id: 'workflow-1' }, fetchStatus: 'idle', isInvalidated: false, status: 'success' },
})
).toBe('ready');
+ expect(
+ getSavedWorkflowDetailQueryStatus({
+ state: { data: { workflow_id: 'workflow-1' }, fetchStatus: 'fetching', isInvalidated: true, status: 'success' },
+ })
+ ).toBe('ready');
+ expect(
+ getSavedWorkflowDetailQueryStatus({
+ state: { data: { workflow_id: 'workflow-1' }, fetchStatus: 'idle', isInvalidated: true, status: 'error' },
+ })
+ ).toBe('ready');
});
it('does not retry a failed detail lookup', () => {
expect(savedWorkflowDetailQueryOptions('workflow-1').retry).toBe(false);
});
+
+ it('recovers an invalidated failed lookup with one authorized retry', async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const detailOptions = savedWorkflowDetailQueryOptions('workflow-1');
+ let attempts = 0;
+ const options = {
+ ...detailOptions,
+ queryFn: () => {
+ attempts += 1;
+
+ if (attempts === 1) {
+ throw new Error('temporary failure');
+ }
+
+ return { workflow_id: 'workflow-1' } as never;
+ },
+ };
+
+ try {
+ await expect(queryClient.fetchQuery(options)).rejects.toThrow('temporary failure');
+ const failedQuery = queryClient.getQueryCache().find({ queryKey: detailOptions.queryKey });
+
+ expect(shouldFetchSavedWorkflowDetail(failedQuery)).toBe(false);
+
+ await queryClient.invalidateQueries({ exact: true, queryKey: detailOptions.queryKey, refetchType: 'none' });
+ const invalidatedQuery = queryClient.getQueryCache().find({ queryKey: detailOptions.queryKey });
+
+ expect(shouldFetchSavedWorkflowDetail(invalidatedQuery, { retryErrors: true })).toBe(true);
+ await queryClient.ensureQueryData({ ...options, revalidateIfStale: true });
+
+ expect(attempts).toBe(2);
+ expect(
+ getSavedWorkflowDetailQueryStatus(queryClient.getQueryCache().find({ queryKey: detailOptions.queryKey }))
+ ).toBe('ready');
+ } finally {
+ queryClient.clear();
+ }
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.ts b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.ts
index c79071d8d5..399e534631 100644
--- a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.ts
@@ -29,9 +29,18 @@ type SavedWorkflowDetailQueryLike = {
};
};
-export const shouldFetchSavedWorkflowDetail = (query: SavedWorkflowDetailQueryLike | undefined): boolean =>
+export interface SavedWorkflowDetailFetchOptions {
+ retryErrors?: boolean;
+}
+
+export const shouldFetchSavedWorkflowDetail = (
+ query: SavedWorkflowDetailQueryLike | undefined,
+ options: SavedWorkflowDetailFetchOptions = {}
+): boolean =>
query === undefined ||
- (query.state.status === 'success' && query.state.isInvalidated && query.state.fetchStatus === 'idle');
+ (query.state.isInvalidated &&
+ query.state.fetchStatus === 'idle' &&
+ (query.state.status === 'success' || (options.retryErrors === true && query.state.status === 'error')));
export const getSavedWorkflowDetailQueryStatus = (
query: SavedWorkflowDetailQueryLike | undefined
@@ -40,6 +49,10 @@ export const getSavedWorkflowDetailQueryStatus = (
return 'missing';
}
+ if (query.state.data !== undefined && query.state.data !== null) {
+ return 'ready';
+ }
+
if (query.state.status === 'error') {
return 'error';
}
@@ -48,7 +61,7 @@ export const getSavedWorkflowDetailQueryStatus = (
return 'loading';
}
- return query.state.data ? 'ready' : 'error';
+ return query.state.data !== undefined && query.state.data !== null ? 'ready' : 'error';
};
export const savedWorkflowDetailQueryOptions = (workflowId: string) => ({
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx
index 6245e06c9f..614fc7ddc9 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx
@@ -300,7 +300,7 @@ export const WorkflowDialogHost = () => {
await updateLibraryWorkflow(workflowId, serialized, owner.signal);
assertAccountScopeCurrent(owner);
// The library dialog serves cached payloads and pages; a save changes both.
- invalidateWorkflowLibraryCache();
+ invalidateWorkflowLibraryCache(workflowId);
},
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.test.ts
index 5bf23d1440..d7767de8fe 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.test.ts
@@ -1,6 +1,11 @@
+import type { ParsedWorkflow } from '@features/workflow/core/workflowJson';
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { createDeferredCallSavedWorkflowReconciler } from './CallSavedWorkflowSyncRuntime';
+import {
+ createDeferredCallSavedWorkflowReconciler,
+ createSavedWorkflowDocumentParser,
+} from './CallSavedWorkflowSyncRuntime';
describe('createDeferredCallSavedWorkflowReconciler', () => {
beforeEach(() => {
@@ -36,3 +41,29 @@ describe('createDeferredCallSavedWorkflowReconciler', () => {
expect(reconcile).not.toHaveBeenCalled();
});
});
+
+describe('createSavedWorkflowDocumentParser', () => {
+ it('parses each immutable child workflow payload once', () => {
+ const parse = vi.fn((workflow: Record<string, unknown>) => ({ document: workflow }) as unknown as ParsedWorkflow);
+ const parser = createSavedWorkflowDocumentParser(parse);
+ const first = { name: 'first' };
+ const replacement = { name: 'replacement' };
+
+ expect(parser(first)).toBe(first);
+ expect(parser(first)).toBe(first);
+ expect(parser(replacement)).toBe(replacement);
+ expect(parse).toHaveBeenCalledTimes(2);
+ });
+
+ it('caches malformed payloads without reparsing on every graph update', () => {
+ const parse = vi.fn(() => {
+ throw new Error('invalid workflow');
+ });
+ const parser = createSavedWorkflowDocumentParser(parse);
+ const malformed = { name: 'malformed' };
+
+ expect(parser(malformed)).toBeUndefined();
+ expect(parser(malformed)).toBeUndefined();
+ expect(parse).toHaveBeenCalledOnce();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsx
index 9e1cd65b5f..4e283fe236 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsx
@@ -1,9 +1,12 @@
+import type { ProjectGraphState } from '@features/workflow/core/types';
+import type { ParsedWorkflow } from '@features/workflow/core/workflowJson';
import type { WorkflowRecordDTO } from '@features/workflow/data/api';
import { onWorkflowLibraryCacheInvalidated } from '@features/workflow/data/libraryCache';
import {
getSavedWorkflowDetailQueryStatus,
isSavedWorkflowDetailQueryKey,
+ savedWorkflowDetailQueryKey,
savedWorkflowDetailQueryOptions,
shouldFetchSavedWorkflowDetail,
} from '@features/workflow/data/savedWorkflowQueries';
@@ -18,6 +21,28 @@ import {
} from '@features/workflow/utility';
import { useMountEffect } from '@platform/react/useMountEffect';
import { useQueryClient } from '@tanstack/react-query';
+import { useMemo } from 'react';
+
+export const createSavedWorkflowDocumentParser = (
+ parse: (workflow: Record<string, unknown>) => ParsedWorkflow = parseWorkflowJson
+): ((workflow: Record<string, unknown>) => ProjectGraphState | undefined) => {
+ const cache = new WeakMap<object, ProjectGraphState | null>();
+
+ return (workflow) => {
+ if (cache.has(workflow)) {
+ return cache.get(workflow) ?? undefined;
+ }
+
+ try {
+ const document = parse(workflow).document;
+ cache.set(workflow, document);
+ return document;
+ } catch {
+ cache.set(workflow, null);
+ return undefined;
+ }
+ };
+};
export const createDeferredCallSavedWorkflowReconciler = (reconcile: () => void) => {
let timer: ReturnType<typeof setTimeout> | null = null;
@@ -107,6 +132,8 @@ const needsDynamicFieldSync = (
export const CallSavedWorkflowSyncRuntime = () => {
const queryClient = useQueryClient();
const { commands, project: projectPort } = useWorkflowUi();
+ const retryableDetailWorkflowIds = new Set<string>();
+ const parseChildWorkflow = useMemo(() => createSavedWorkflowDocumentParser(), []);
const reconcile = () => {
const templatesSnapshot = getInvocationTemplatesSnapshot();
@@ -157,11 +184,25 @@ export const CallSavedWorkflowSyncRuntime = () => {
const detailOptions = savedWorkflowDetailQueryOptions(workflowId);
const query = queryClient.getQueryCache().find({ queryKey: detailOptions.queryKey });
- if (shouldFetchSavedWorkflowDetail(query)) {
- setStatus(node.id, workflowId, 'loading');
- void queryClient.ensureQueryData({ ...detailOptions, revalidateIfStale: true }).catch(() => {
- setStatus(node.id, workflowId, 'error');
- });
+ if (shouldFetchSavedWorkflowDetail(query, { retryErrors: retryableDetailWorkflowIds.has(workflowId) })) {
+ const hasExistingDetail = query?.state.data !== undefined && query.state.data !== null;
+
+ if (!hasExistingDetail) {
+ setStatus(node.id, workflowId, 'loading');
+ }
+
+ void queryClient
+ .ensureQueryData({ ...detailOptions, revalidateIfStale: true })
+ .then(() => {
+ retryableDetailWorkflowIds.delete(workflowId);
+ })
+ .catch(() => {
+ retryableDetailWorkflowIds.delete(workflowId);
+ const failedQuery = queryClient.getQueryCache().find({ queryKey: detailOptions.queryKey });
+ const hasUsableDetail = failedQuery?.state.data !== undefined && failedQuery.state.data !== null;
+
+ setStatus(node.id, workflowId, hasUsableDetail ? 'ready' : 'error');
+ });
continue;
}
@@ -185,13 +226,7 @@ export const CallSavedWorkflowSyncRuntime = () => {
continue;
}
- let childDocument;
-
- try {
- childDocument = parseWorkflowJson(selectedWorkflow.workflow).document;
- } catch {
- childDocument = undefined;
- }
+ const childDocument = parseChildWorkflow(selectedWorkflow.workflow);
if (!childDocument) {
setStatus(node.id, workflowId, 'error');
@@ -233,8 +268,27 @@ export const CallSavedWorkflowSyncRuntime = () => {
reconciler.schedule();
}
});
- const unsubscribeLibrary = onWorkflowLibraryCacheInvalidated(() => {
- void queryClient.invalidateQueries({ queryKey: ['workflow', 'call-saved', 'detail'] });
+ const unsubscribeLibrary = onWorkflowLibraryCacheInvalidated((workflowId) => {
+ if (workflowId) {
+ retryableDetailWorkflowIds.add(workflowId);
+ void queryClient.invalidateQueries({
+ exact: true,
+ queryKey: savedWorkflowDetailQueryKey(workflowId),
+ refetchType: 'none',
+ });
+ } else {
+ for (const query of queryClient.getQueryCache().findAll({ queryKey: ['workflow', 'call-saved', 'detail'] })) {
+ if (isSavedWorkflowDetailQueryKey(query.queryKey)) {
+ retryableDetailWorkflowIds.add(query.queryKey[3]);
+ }
+ }
+
+ void queryClient.invalidateQueries({
+ queryKey: ['workflow', 'call-saved', 'detail'],
+ refetchType: 'none',
+ });
+ }
+
reconciler.schedule();
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.test.ts
index 50463dafa8..8ef45a8b4d 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.test.ts
@@ -2,7 +2,10 @@ import type { WorkflowInvocationNode } from '@features/workflow/contracts';
import { describe, expect, it } from 'vitest';
-import { shouldShowCallSavedWorkflowLoadingHint } from './InvocationFlowNode';
+import {
+ shouldShowCallSavedWorkflowLoadingHint,
+ shouldShowCallSavedWorkflowNoExposedFieldsHint,
+} from './InvocationFlowNode';
const node = (type: string, status?: WorkflowInvocationNode['data']['callSavedWorkflowStatus']) =>
({ data: { type, callSavedWorkflowStatus: status } }) as WorkflowInvocationNode;
@@ -16,3 +19,26 @@ describe('shouldShowCallSavedWorkflowLoadingHint', () => {
expect(shouldShowCallSavedWorkflowLoadingHint(node('other', 'loading'))).toBe(false);
});
});
+
+describe('shouldShowCallSavedWorkflowNoExposedFieldsHint', () => {
+ it('shows the empty-state hint only for a ready selected child with no dynamic fields', () => {
+ expect(
+ shouldShowCallSavedWorkflowNoExposedFieldsHint({
+ data: {
+ ...node('call_saved_workflow', 'ready').data,
+ inputs: { workflow_id: { label: '', name: 'workflow_id', value: 'workflow-1' } },
+ },
+ } as unknown as WorkflowInvocationNode)
+ ).toBe(true);
+ expect(shouldShowCallSavedWorkflowNoExposedFieldsHint(node('call_saved_workflow', 'loading'))).toBe(false);
+ expect(
+ shouldShowCallSavedWorkflowNoExposedFieldsHint({
+ data: {
+ ...node('call_saved_workflow', 'ready').data,
+ dynamicInputTemplates: { field: {} },
+ inputs: { workflow_id: { label: '', name: 'workflow_id', value: 'workflow-1' } },
+ },
+ } as unknown as WorkflowInvocationNode)
+ ).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
index d9e478f773..e90e034f18 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
@@ -34,6 +34,7 @@ import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCo
import { useWorkflowNodeExecutionState } from '@features/workflow/ui/WorkflowUiContext';
import { setNodePreviewCollapsed, workflowUiStore } from '@features/workflow/ui/workflowUiStore';
import {
+ CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX,
cloneWorkflowFieldDefault,
formatOutputFieldValue,
getFieldTypeLabel,
@@ -69,6 +70,21 @@ const useIsZoomedOut = (): boolean => useStore((state) => state.transform[2] < C
export const shouldShowCallSavedWorkflowLoadingHint = (node: WorkflowInvocationNode): boolean =>
node.data.type === 'call_saved_workflow' && node.data.callSavedWorkflowStatus === 'loading';
+/** A callable child can be valid without exposing any fields; explain the empty body instead of showing a blank node. */
+export const shouldShowCallSavedWorkflowNoExposedFieldsHint = (node: WorkflowInvocationNode): boolean => {
+ if (node.data.type !== 'call_saved_workflow' || node.data.callSavedWorkflowStatus !== 'ready') {
+ return false;
+ }
+
+ const workflowId = node.data.inputs.workflow_id?.value;
+ const hasSelectedWorkflow = typeof workflowId === 'string' && workflowId.trim() !== '';
+ const hasDynamicFields =
+ Object.keys(node.data.dynamicInputTemplates ?? {}).length > 0 ||
+ Object.keys(node.data.inputs).some((name) => name.startsWith(CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX));
+
+ return hasSelectedWorkflow && !hasDynamicFields;
+};
+
/** Static placeholder bar standing in for text/controls at far zoom. No animation — there may be hundreds. */
const SkeletonBar = ({ h = '2', w }: { h?: string; w?: string }) => <Box bg="bg.emphasized" h={h} rounded="sm" w={w} />;
@@ -867,7 +883,11 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode
))}
{shouldShowCallSavedWorkflowLoadingHint(node) ? (
<Text color="fg.subtle" fontSize="2xs" px={WORKFLOW_NODE_DENSITY.rowPaddingX} py="1">
- {t('nodes.savedWorkflowUpdating')}
+ {t('nodes.savedWorkflowLoading')}
+ </Text>
+ ) : shouldShowCallSavedWorkflowNoExposedFieldsHint(node) ? (
+ <Text color="fg.subtle" fontSize="2xs" px={WORKFLOW_NODE_DENSITY.rowPaddingX} py="1">
+ {t('nodes.savedWorkflowNoExposedFields')}
</Text>
) : null}
</Box>
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 ebb44f04a0..6f72926836 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
@@ -1589,7 +1589,7 @@ const SavedWorkflowInput = ({ onChange, template, value }: WorkflowFieldInputPro
flex="1"
noResultsText={t('nodes.noMatchingWorkflows')}
options={options}
- searchPlaceholder={isLoading ? t('common.loading') : t('nodes.savedWorkflowSearch')}
+ searchPlaceholder={isLoading ? t('nodes.savedWorkflowLoading') : t('nodes.savedWorkflowSearch')}
value={selectedOption?.value ?? null}
onInputValueChange={setSearch}
onListScrollToBottom={fetchNextPage}
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts
index 7dbdd35a10..1536f0967e 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts
@@ -76,7 +76,7 @@ export const useSaveWorkflowToLibrary = (): {
markLibraryGraphSynced(syncedSerialized);
setWorkflowLibrarySyncStatus('saved');
- invalidateWorkflowLibraryCache();
+ invalidateWorkflowLibraryCache(workflowId);
return workflowId;
} catch (error) {
@@ -103,7 +103,7 @@ export const useSaveWorkflowToLibrary = (): {
const workflowId = await createLibraryWorkflow(serialized, owner.signal);
assertAccountScopeCurrent(owner);
- invalidateWorkflowLibraryCache();
+ invalidateWorkflowLibraryCache(workflowId);
return workflowId;
} catch (error) {
diff --git a/invokeai/frontend/webv2/src/platform/ui/Combobox.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Combobox.browser.test.tsx
index c0e42f1942..2064e5ee91 100644
--- a/invokeai/frontend/webv2/src/platform/ui/Combobox.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/Combobox.browser.test.tsx
@@ -12,7 +12,7 @@ import { Combobox, type ComboboxOption } from './Combobox';
const options: ComboboxOption[] = [
{ label: 'Euler Ancestral', value: 'euler_a' },
{ label: 'DPM++ 2M', value: 'dpmpp_2m' },
- { label: 'UniPC', value: 'unipc' },
+ { label: 'UniPC', searchText: 'popular sampler', value: 'unipc' },
];
const i18n = createInstance();
@@ -48,10 +48,12 @@ const interact = (action: () => void): Promise<void> =>
const Harness = ({
disabled = false,
filterOptions = false,
+ onInputValueChange,
onChange,
}: {
disabled?: boolean;
filterOptions?: boolean;
+ onInputValueChange?: (value: string) => void;
onChange: (value: string) => void;
}) => {
const [value, setValue] = useState('euler_a');
@@ -66,7 +68,14 @@ const Harness = ({
disabled={disabled}
options={visibleOptions}
value={value}
- onInputValueChange={filterOptions ? setSearch : undefined}
+ onInputValueChange={
+ filterOptions
+ ? (nextSearch) => {
+ setSearch(nextSearch);
+ onInputValueChange?.(nextSearch);
+ }
+ : undefined
+ }
onValueChange={(nextValue) => {
setValue(nextValue);
onChange(nextValue);
@@ -80,18 +89,24 @@ const renderCombobox = async (disabled = false, filterOptions = false) => {
document.body.append(host);
root = createRoot(host);
const onChange = vi.fn();
+ const onInputValueChange = vi.fn();
await interact(() => {
root?.render(
<I18nextProvider i18n={i18n}>
<ChakraProvider value={system}>
- <Harness disabled={disabled} filterOptions={filterOptions} onChange={onChange} />
+ <Harness
+ disabled={disabled}
+ filterOptions={filterOptions}
+ onChange={onChange}
+ onInputValueChange={onInputValueChange}
+ />
</ChakraProvider>
</I18nextProvider>
);
});
- return { input: host.querySelector<HTMLInputElement>('input[role="combobox"]')!, onChange };
+ return { input: host.querySelector<HTMLInputElement>('input[role="combobox"]')!, onChange, onInputValueChange };
};
const setInputValue = async (input: HTMLInputElement, value: string) => {
@@ -125,6 +140,16 @@ describe('Combobox', () => {
expect(document.body.textContent).toContain('No schedulers found');
});
+ it('keeps an option that matches secondary server-search text', async () => {
+ const { input } = await renderCombobox();
+
+ await interact(() => input.click());
+ await setInputValue(input, 'popular');
+
+ expect(document.querySelectorAll('[role="option"]')).toHaveLength(1);
+ expect(document.querySelector('[role="option"]')?.textContent).toContain('UniPC');
+ });
+
it('supports controlled mouse and keyboard selection with selected-state indication', async () => {
const { input, onChange } = await renderCombobox();
@@ -148,7 +173,7 @@ describe('Combobox', () => {
});
it('clears the controlled search query when reopened', async () => {
- const { input } = await renderCombobox(false, true);
+ const { input, onInputValueChange } = await renderCombobox(false, true);
await interact(() => input.click());
await setInputValue(input, 'DPM');
@@ -157,6 +182,8 @@ describe('Combobox', () => {
await interact(() => {
input.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Escape' }));
});
+ expect(onInputValueChange).toHaveBeenLastCalledWith('');
+ expect(onInputValueChange).toHaveBeenCalledTimes(2);
expect(input.getAttribute('aria-expanded')).toBe('false');
await interact(() => input.click());
diff --git a/invokeai/frontend/webv2/src/platform/ui/Combobox.tsx b/invokeai/frontend/webv2/src/platform/ui/Combobox.tsx
index f517ff08b5..bc6eefddc7 100644
--- a/invokeai/frontend/webv2/src/platform/ui/Combobox.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/Combobox.tsx
@@ -7,7 +7,7 @@ import type {
import { Combobox as ChakraCombobox, createListCollection, Portal } from '@chakra-ui/react';
import { CheckIcon, ChevronDownIcon } from 'lucide-react';
-import { useCallback, useMemo, useState, type UIEvent } from 'react';
+import { useCallback, useMemo, useRef, useState, type UIEvent } from 'react';
import { useTranslation } from 'react-i18next';
const COMBOBOX_POSITIONING = { placement: 'bottom-start', sameWidth: true } as const;
@@ -20,6 +20,8 @@ const LIST_SCROLL_CSS = {
export interface ComboboxOption extends CollectionItem {
disabled?: boolean;
label: string;
+ /** Additional fields already searched by the server, such as tags and descriptions. */
+ searchText?: string;
value: string;
}
@@ -61,6 +63,7 @@ export const Combobox = ({
const { t } = useTranslation();
const [isOpen, setIsOpen] = useState(false);
const [query, setQuery] = useState('');
+ const lastNotifiedInputValue = useRef('');
const selectedLabel = options.find((option) => option.value === value)?.label ?? '';
const normalizedQuery = query.trim().toLocaleLowerCase();
const selectedValues = useMemo(() => (value ? [value] : []), [value]);
@@ -71,7 +74,8 @@ export const Combobox = ({
: options.filter(
(option) =>
option.label.toLocaleLowerCase().includes(normalizedQuery) ||
- option.value.toLocaleLowerCase().includes(normalizedQuery)
+ option.value.toLocaleLowerCase().includes(normalizedQuery) ||
+ option.searchText?.toLocaleLowerCase().includes(normalizedQuery)
),
[normalizedQuery, options]
);
@@ -85,25 +89,36 @@ export const Combobox = ({
}),
[filteredOptions]
);
+ const notifyInputValueChange = useCallback(
+ (nextValue: string) => {
+ if (nextValue === lastNotifiedInputValue.current) {
+ return;
+ }
+
+ lastNotifiedInputValue.current = nextValue;
+ onInputValueChange?.(nextValue);
+ },
+ [onInputValueChange]
+ );
const handleOpenChange = useCallback(
(details: { open: boolean }) => {
setIsOpen(details.open);
setQuery('');
if (!details.open) {
- onInputValueChange?.('');
+ notifyInputValueChange('');
}
},
- [onInputValueChange]
+ [notifyInputValueChange]
);
const handleInputValueChange = useCallback(
(details: { inputValue: string; reason?: string }) => {
if (details.reason === 'input-change' || details.reason === 'clear-trigger') {
setQuery(details.inputValue);
- onInputValueChange?.(details.inputValue);
+ notifyInputValueChange(details.inputValue);
}
},
- [onInputValueChange]
+ [notifyInputValueChange]
);
const handleListScroll = useCallback(
(event: UIEvent<HTMLDivElement>) => {