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: stabilize saved workflow syncing

JPPhoto62d54291a10f
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 1b0c975695..02a04c99c6 100644
--- a/invokeai/frontend/web/src/features/nodes/types/invocation.test.ts
+++ b/invokeai/frontend/web/src/features/nodes/types/invocation.test.ts
@@ -190,6 +190,27 @@ describe('zInvocationNodeData: extra-input scoping', () => {
},
});
- expect(parsed.dynamicInputTemplates.fidelity).toMatchObject({ options: ['low', 'high'] });
+ expect(parsed.dynamicInputTemplates.fidelity).toMatchObject({ default: 'low', options: ['low', 'high'] });
+ });
+
+ it('accepts an optional enum dynamic template with no options at the legacy boundary', () => {
+ const parsed = zInvocationNodeData.parse({
+ ...buildNodeData('call_saved_workflow', {}),
+ dynamicInputTemplates: {
+ empty: {
+ description: 'Empty enum',
+ fieldKind: 'input',
+ input: 'any',
+ name: 'empty',
+ options: [],
+ required: false,
+ title: 'Empty enum',
+ type: { batch: false, cardinality: 'SINGLE', name: 'EnumField' },
+ uiHidden: false,
+ },
+ },
+ });
+
+ expect(parsed.dynamicInputTemplates.empty).toMatchObject({ default: '', options: [] });
});
});
diff --git a/invokeai/frontend/web/src/features/nodes/types/invocation.ts b/invokeai/frontend/web/src/features/nodes/types/invocation.ts
index 07b15b0825..0019c13bb9 100644
--- a/invokeai/frontend/web/src/features/nodes/types/invocation.ts
+++ b/invokeai/frontend/web/src/features/nodes/types/invocation.ts
@@ -44,6 +44,10 @@ const zWebv2DynamicInputTemplate = z.preprocess((value) => {
const template = result.data;
const options = template.options?.map(String);
+ const defaultValue =
+ template.type.name === 'EnumField' && (template.default === undefined || template.default === null)
+ ? (options?.[0] ?? '')
+ : template.default;
return {
...template,
fieldKind: 'input' as const,
@@ -55,9 +59,9 @@ const zWebv2DynamicInputTemplate = z.preprocess((value) => {
multipleOf: template.multipleOf ?? undefined,
options: options ?? undefined,
default:
- template.type.name === 'EnumField' && template.default !== undefined && template.default !== null
- ? String(template.default)
- : template.default,
+ template.type.name === 'EnumField' && defaultValue !== undefined && defaultValue !== null
+ ? String(defaultValue)
+ : defaultValue,
originalType: template.type.originalType,
type: template.type,
ui_choice_labels: template.uiChoiceLabels ?? undefined,
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 9dda1b7de4..cc11437f89 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -3992,6 +3992,7 @@
"loading": "Loading workflows…",
"loadingMore": "Loading more…",
"multipleWorkflowReturnNodes": "The workflow must contain exactly one workflow return node before it can be saved.",
+ "multipleWorkflowReturnNodesForTransfer": "The workflow must contain exactly one workflow return node before it can be exported or copied.",
"moreActions": "More actions",
"nodeCount_one": "{{count}} node",
"nodeCount_other": "{{count}} nodes",
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 1daa5bfa60..5fbd02c052 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.test.ts
@@ -210,6 +210,52 @@ describe('Call Saved Workflow dynamic fields', () => {
expect(changedNode?.type === 'invocation' && changedNode.data.inputs[dynamicFieldName('a')]?.value).toBe(3);
});
+ it('preserves presentation overrides when an incompatible value is reset', () => {
+ const callNode = buildInvocationNode(callSavedWorkflowTemplate, { x: 0, y: 0 });
+ callNode.id = 'call-1';
+ const fields = getSavedWorkflowDynamicFields(buildChildWorkflow(), templates);
+ let document = syncCallSavedWorkflowFields(
+ { ...createProjectGraph('parent'), nodes: [callNode] },
+ callNode.id,
+ fields,
+ []
+ );
+ document = projectGraphReducer(document, {
+ fieldName: dynamicFieldName('a'),
+ nodeId: callNode.id,
+ type: 'setFieldValue',
+ value: 99,
+ });
+ document = projectGraphReducer(document, {
+ fieldName: dynamicFieldName('a'),
+ label: 'Custom label',
+ nodeId: callNode.id,
+ type: 'setFieldLabel',
+ });
+ document = projectGraphReducer(document, {
+ description: 'Custom description',
+ fieldName: dynamicFieldName('a'),
+ nodeId: callNode.id,
+ type: 'setFieldDescription',
+ });
+
+ const narrowedFields = fields.map((field) =>
+ field.fieldName === dynamicFieldName('a')
+ ? { ...field, fieldTemplate: { ...field.fieldTemplate, maximum: 10 }, initialValue: 5 }
+ : field
+ );
+ const resynced = syncCallSavedWorkflowFields(document, callNode.id, narrowedFields, []);
+ const node = resynced.nodes.find((candidate): candidate is WorkflowInvocationNode => candidate.id === callNode.id);
+
+ expect(node?.data.inputs[dynamicFieldName('a')]).toMatchObject({
+ description: 'Custom description',
+ descriptionOverride: true,
+ label: 'Custom label',
+ labelOverride: true,
+ value: 5,
+ });
+ });
+
it('honors explicit presentation overrides even when they match the old generated value', () => {
const callNode = buildInvocationNode(callSavedWorkflowTemplate, { x: 0, y: 0 });
callNode.id = 'call-1';
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.ts b/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.ts
index d979e49b64..034f353f28 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.ts
@@ -237,12 +237,10 @@ export const syncCallSavedWorkflowFields = (
(!previousTemplate || sameFieldType(previousTemplate, field.fieldTemplate)) &&
isWorkflowFieldValueValid(field.fieldTemplate, previous.value);
const labelOverridden =
- keepValue &&
previous &&
(previous.labelOverride === true ||
(previousTemplate !== undefined && previous.label !== previousTemplate.title));
const descriptionOverridden =
- keepValue &&
previous &&
(previous.descriptionOverride === true ||
(previousTemplate !== undefined
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.test.ts
index 2f9377d808..0da352b908 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.test.ts
@@ -15,6 +15,7 @@ import { buildConnectorNode, buildInvocationNode, createProjectGraph } from './d
import {
buildLayerWorkflowGraph,
getDefaultLayerWorkflowSelection,
+ getLayerWorkflowInjectedInput,
getLayerWorkflowInputs,
getLayerWorkflowOutputs,
getRunnableLayerWorkflowInputs,
@@ -322,6 +323,22 @@ describe('layer workflow dialog selection', () => {
});
describe('buildLayerWorkflowGraph', () => {
+ it('preserves an explicit description override when injecting the layer image', () => {
+ expect(
+ getLayerWorkflowInjectedInput(
+ { description: '', descriptionOverride: true, label: 'Layer image', name: 'image', value: undefined },
+ 'image',
+ 'layer.png'
+ )
+ ).toEqual({
+ description: '',
+ descriptionOverride: true,
+ label: 'Layer image',
+ name: 'image',
+ value: { image_name: 'layer.png' },
+ });
+ });
+
it('injects a direct-capable input before readiness without mutating the document', () => {
const processorTemplate = template(
'processor',
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts
index ed6d5b914e..137ee81091 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/layerWorkflow.ts
@@ -5,6 +5,7 @@ import type {
InvocationTemplates,
InvocationTemplatesSnapshot,
ProjectGraphState,
+ WorkflowFieldInstance,
WorkflowInvocationNode,
} from './types';
@@ -185,6 +186,18 @@ const getAvailableBinding = (
selected: WorkflowImageBinding
): WorkflowImageBinding | undefined => bindings.find((candidate) => isSameBinding(candidate, selected));
+export const getLayerWorkflowInjectedInput = (
+ instance: WorkflowFieldInstance | undefined,
+ fieldName: string,
+ imageName: string
+): WorkflowFieldInstance => ({
+ label: instance?.label ?? '',
+ name: fieldName,
+ ...(instance?.description === undefined ? {} : { description: instance.description }),
+ ...(instance?.descriptionOverride === undefined ? {} : { descriptionOverride: instance.descriptionOverride }),
+ value: { image_name: imageName },
+});
+
const allocateNodeId = (graph: WorkflowBackendGraph, base: string): string => {
if (!graph.nodes[base]) {
return base;
@@ -255,12 +268,7 @@ export const buildLayerWorkflowGraph = (options: BuildLayerWorkflowGraphOptions)
if (!isConnectionOnly) {
const instance = inputNode.data.inputs[input.fieldName];
- inputNode.data.inputs[input.fieldName] = {
- label: instance?.label ?? '',
- name: input.fieldName,
- ...(instance?.description === undefined ? {} : { description: instance.description }),
- value: { image_name: imageName },
- };
+ inputNode.data.inputs[input.fieldName] = getLayerWorkflowInjectedInput(instance, input.fieldName, imageName);
}
const readiness = getProjectGraphReadiness(cloned, templatesSnapshot, { externallySatisfiedInputs });
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 0b5407bc5e..c277134adc 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.test.ts
@@ -119,17 +119,29 @@ describe('workflow JSON round-trip', () => {
});
});
- it('omits runtime templates from the embedded submission workflow', () => {
+ it('keeps Call Saved Workflow templates for image recall but strips other runtime templates', () => {
const node = buildInvocationNode(template, { x: 0, y: 0 });
node.data.dynamicInputTemplates = { runtime: template.inputs.prompt! };
+ const callNode = buildInvocationNode(template, { x: 1, y: 1 });
+ callNode.data = {
+ ...callNode.data,
+ dynamicInputTemplates: { runtime: template.inputs.prompt! },
+ type: 'call_saved_workflow',
+ };
let doc = createProjectGraph('submission-runtime-fields');
doc = projectGraphReducer(doc, { node, type: 'addNode' });
+ doc = projectGraphReducer(doc, { node: callNode, type: 'addNode' });
const serialized = serializeWorkflowJsonForSubmission(doc) as {
nodes: Array<{ data: Record<string, unknown> }>;
};
- expect(serialized.nodes[0]?.data).not.toHaveProperty('dynamicInputTemplates');
+ expect(
+ serialized.nodes.find((candidate) => candidate.data.type !== 'call_saved_workflow')?.data
+ ).not.toHaveProperty('dynamicInputTemplates');
+ expect(serialized.nodes.find((candidate) => candidate.data.type === 'call_saved_workflow')?.data).toHaveProperty(
+ 'dynamicInputTemplates'
+ );
});
it('omits current-image nodes and their edges from embedded workflows', () => {
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts
index d54480e5ff..610473d442 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts
@@ -504,7 +504,9 @@ export const serializeWorkflowJsonForSubmission = (document: ProjectGraphState):
}
const { dynamicInputTemplates: _dynamicInputTemplates, ...data } = node.data;
- return { ...node, data };
+ return node.data.type === 'call_saved_workflow' && isRecord(_dynamicInputTemplates)
+ ? { ...node, data: { ...data, dynamicInputTemplates: _dynamicInputTemplates } }
+ : { ...node, data };
}),
};
};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx
index 34b6aa2d0f..3b6df101a7 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx
@@ -1,3 +1,5 @@
+import type { ProjectGraphState } from '@features/workflow/core/types';
+
import { ChakraProvider } from '@chakra-ui/react';
import { createProjectGraph } from '@features/workflow/utility';
import { accountLifecycle } from '@platform/state/accountLifecycle';
@@ -62,6 +64,15 @@ const createMutablePort = <Snapshot,>(initialSnapshot: Snapshot) => {
};
};
+const createGraphWithDuplicateWorkflowReturns = (): ProjectGraphState => ({
+ ...createProjectGraph('workflow-1'),
+ libraryWorkflowId: 'library-workflow-1',
+ nodes: [
+ { data: { type: 'workflow_return' }, id: 'return-1', position: { x: 0, y: 0 }, type: 'invocation' },
+ { data: { type: 'workflow_return' }, id: 'return-2', position: { x: 100, y: 0 }, type: 'invocation' },
+ ] as unknown as ProjectGraphState['nodes'],
+});
+
/**
* Regression coverage for the StrictMode autosaver-disposal bug: the
* autosaver used to be created once via a `useState` initializer and
@@ -176,6 +187,65 @@ describe('WorkflowDialogHost library autosave under StrictMode', () => {
stopListening();
});
+ it('rejects an autosave when the graph has duplicate workflow returns', async () => {
+ const boundGraph = createGraphWithDuplicateWorkflowReturns();
+ const project = createMutablePort({
+ galleryValues: {},
+ id: 'project-1',
+ isWorkflowRunning: false,
+ projectGraph: boundGraph,
+ workflowValues: {},
+ });
+ const notifications = { error: vi.fn(), info: vi.fn(), success: vi.fn() };
+
+ // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime
+ const adapter = {
+ commands: {
+ bindLibraryWorkflow: vi.fn(),
+ editGraph: vi.fn(),
+ redo: vi.fn(),
+ replace: vi.fn(),
+ undo: vi.fn(),
+ },
+ getProjectGraph: () => project.port.getSnapshot().projectGraph,
+ notifications,
+ project: project.port,
+ widgets: { open: vi.fn(), patchValues: vi.fn() },
+ } as unknown as WorkflowUiAdapter;
+
+ root = createRoot(host);
+
+ await act(() => {
+ root.render(
+ <StrictMode>
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient}>
+ <WorkflowUiProvider adapter={adapter}>
+ <WorkflowDialogHost />
+ </WorkflowUiProvider>
+ </QueryClientProvider>
+ </ChakraProvider>
+ </StrictMode>
+ );
+ });
+
+ await act(() => {
+ project.setSnapshot({
+ ...project.port.getSnapshot(),
+ projectGraph: { ...boundGraph, name: 'Invalid duplicate-return edit' },
+ });
+ });
+ await act(
+ () =>
+ new Promise<void>((resolve) => {
+ setTimeout(resolve, 2100);
+ })
+ );
+
+ expect(updateLibraryWorkflowMock).not.toHaveBeenCalled();
+ expect(notifications.error).toHaveBeenCalledTimes(1);
+ });
+
/**
* The host used to learn about graph edits through a selector
* (`useWorkflowProjectSelector`) feeding a change-detecting effect, which
@@ -359,4 +429,66 @@ describe('WorkflowDialogHost library autosave under StrictMode', () => {
accountLifecycle.invalidate();
}
});
+
+ it('does not flush a pending old-account edit after the account switches', async () => {
+ const boundGraph = { ...createProjectGraph('workflow-1'), libraryWorkflowId: 'library-workflow-1' };
+ const project = createMutablePort({
+ galleryValues: {},
+ id: 'project-1',
+ isWorkflowRunning: false,
+ projectGraph: boundGraph,
+ workflowValues: {},
+ });
+ const notifications = { error: vi.fn(), info: vi.fn(), success: vi.fn() };
+
+ accountLifecycle.activate('workflow-dialog-host-old-account', ':user:workflow-dialog-host-old-account');
+
+ // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime
+ const adapter = {
+ commands: {
+ bindLibraryWorkflow: vi.fn(),
+ editGraph: vi.fn(),
+ redo: vi.fn(),
+ replace: vi.fn(),
+ undo: vi.fn(),
+ },
+ getProjectGraph: () => project.port.getSnapshot().projectGraph,
+ notifications,
+ project: project.port,
+ widgets: { open: vi.fn(), patchValues: vi.fn() },
+ } as unknown as WorkflowUiAdapter;
+
+ root = createRoot(host);
+
+ try {
+ await act(() => {
+ root.render(
+ <StrictMode>
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient}>
+ <WorkflowUiProvider adapter={adapter}>
+ <WorkflowDialogHost />
+ </WorkflowUiProvider>
+ </QueryClientProvider>
+ </ChakraProvider>
+ </StrictMode>
+ );
+ });
+
+ await act(() => {
+ project.setSnapshot({
+ ...project.port.getSnapshot(),
+ projectGraph: { ...boundGraph, name: 'Old account edit' },
+ });
+ });
+
+ accountLifecycle.activate('workflow-dialog-host-new-account', ':user:workflow-dialog-host-new-account');
+ await act(() => root.render(null));
+ await Promise.resolve();
+
+ expect(updateLibraryWorkflowMock).not.toHaveBeenCalled();
+ } finally {
+ accountLifecycle.invalidate();
+ }
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowMenuItems.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowMenuItems.browser.test.tsx
new file mode 100644
index 0000000000..52d74eab79
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowMenuItems.browser.test.tsx
@@ -0,0 +1,129 @@
+import type { ProjectGraphState, WorkflowNode } from '@features/workflow/core/types';
+import type { WorkflowRuntimeApi } from '@features/workflow/ui/contracts';
+import type { WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';
+
+import { ChakraProvider, Menu } from '@chakra-ui/react';
+import { createProjectGraph } from '@features/workflow/utility';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { WorkflowUiProvider } from './WorkflowUiContext';
+import { WorkflowMenuItems } from './WorkflowWidgetChrome';
+
+const { copyWorkflowJsonMock, downloadWorkflowJsonMock } = vi.hoisted(() => ({
+ copyWorkflowJsonMock: vi.fn(),
+ downloadWorkflowJsonMock: vi.fn(),
+}));
+
+vi.mock('./workflowTransfer', () => ({
+ copyWorkflowJson: copyWorkflowJsonMock,
+ downloadWorkflowJson: downloadWorkflowJsonMock,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) =>
+ ({
+ 'projects.exportFailed': 'Export failed',
+ 'widgets.labels.workflow': 'Workflow',
+ 'widgets.workflow.copyJson': 'Copy workflow JSON',
+ 'widgets.workflow.copyJsonFailed': 'Failed to copy workflow JSON',
+ 'widgets.workflow.detailsWithEllipsis': 'Workflow details…',
+ 'widgets.workflow.exportJson': 'Export workflow JSON',
+ 'widgets.workflow.importJsonWithEllipsis': 'Import workflow JSON…',
+ 'widgets.workflow.newWorkflowWithEllipsis': 'New workflow…',
+ 'workflowLibrary.multipleWorkflowReturnNodesForTransfer':
+ 'The workflow must contain exactly one workflow return node before it can be exported or copied.',
+ })[key] ?? key,
+ }),
+}));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const duplicateReturnGraph = (): ProjectGraphState => ({
+ ...createProjectGraph('workflow-1'),
+ nodes: [
+ { data: { type: 'workflow_return' }, id: 'return-1', position: { x: 0, y: 0 }, type: 'invocation' },
+ { data: { type: 'workflow_return' }, id: 'return-2', position: { x: 100, y: 0 }, type: 'invocation' },
+ ] as unknown as WorkflowNode[],
+});
+
+const TEST_RUNTIME: WorkflowRuntimeApi = {
+ commands: { register: () => () => undefined },
+ hotkeys: { register: () => () => undefined },
+ instanceId: 'workflow-menu-test',
+ region: 'center',
+ typeId: 'workflow',
+};
+
+describe('WorkflowMenuItems duplicate workflow-return feedback', () => {
+ let host: HTMLDivElement;
+ let root: Root;
+ let notifications: WorkflowUiAdapter['notifications'];
+
+ beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ copyWorkflowJsonMock.mockReset();
+ downloadWorkflowJsonMock.mockReset();
+ notifications = { error: vi.fn(), info: vi.fn(), success: vi.fn() };
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ });
+
+ const renderMenu = async () => {
+ const graph = duplicateReturnGraph();
+ // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally minimal test adapter
+ const adapter = {
+ getProjectGraph: () => graph,
+ notifications,
+ widgets: { open: vi.fn(), patchValues: vi.fn() },
+ } as unknown as WorkflowUiAdapter;
+
+ await act(() => {
+ root.render(
+ <ChakraProvider value={system}>
+ <WorkflowUiProvider adapter={adapter}>
+ <Menu.Root open>
+ <Menu.Positioner>
+ <Menu.Content>
+ <WorkflowMenuItems region="center" runtime={TEST_RUNTIME} />
+ </Menu.Content>
+ </Menu.Positioner>
+ </Menu.Root>
+ </WorkflowUiProvider>
+ </ChakraProvider>
+ );
+ });
+ };
+
+ it('blocks export and copy with action-specific translated feedback', async () => {
+ await renderMenu();
+
+ const menuItems = () => Array.from(host.querySelectorAll<HTMLElement>('[role="menuitem"]'));
+ const exportItem = () => menuItems().find((item) => item.textContent === 'Export workflow JSON');
+ const copyItem = () => menuItems().find((item) => item.textContent === 'Copy workflow JSON');
+
+ await act(() => exportItem()?.click());
+ await act(() => copyItem()?.click());
+
+ expect(downloadWorkflowJsonMock).not.toHaveBeenCalled();
+ expect(copyWorkflowJsonMock).not.toHaveBeenCalled();
+ expect(notifications.error).toHaveBeenNthCalledWith(
+ 1,
+ 'Export failed',
+ 'The workflow must contain exactly one workflow return node before it can be exported or copied.'
+ );
+ expect(notifications.error).toHaveBeenNthCalledWith(
+ 2,
+ 'Failed to copy workflow JSON',
+ 'The workflow must contain exactly one workflow return node before it can be exported or copied.'
+ );
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx
index 51dc100cb7..a472f8a5a4 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx
@@ -128,9 +128,25 @@ export const WorkflowMenuItems = (_props: WorkflowWidgetViewProps) => {
widgets.open({ region: 'left', widgetId: 'workflow' });
widgets.patchValues('workflow', { editTab: 'details', panelMode: 'edit' });
}, [widgets]);
- const exportWorkflow = useCallback(() => downloadWorkflowJson(getProjectGraph()), [getProjectGraph]);
+ const exportWorkflow = useCallback(() => {
+ const projectGraph = getProjectGraph();
+
+ if (hasMultipleWorkflowReturnNodes(projectGraph)) {
+ notify.error(t('projects.exportFailed'), t('workflowLibrary.multipleWorkflowReturnNodesForTransfer'));
+ return;
+ }
+
+ downloadWorkflowJson(projectGraph);
+ }, [getProjectGraph, notify, t]);
const copyWorkflow = useCallback(() => {
- copyWorkflowJson(getProjectGraph())
+ const projectGraph = getProjectGraph();
+
+ if (hasMultipleWorkflowReturnNodes(projectGraph)) {
+ notify.error(t('widgets.workflow.copyJsonFailed'), t('workflowLibrary.multipleWorkflowReturnNodesForTransfer'));
+ return;
+ }
+
+ copyWorkflowJson(projectGraph)
.then(() => notify.success(t('widgets.workflow.copyJsonSuccess')))
.catch(() => notify.error(t('widgets.workflow.copyJsonFailed')));
}, [getProjectGraph, notify, t]);
@@ -248,6 +264,9 @@ export const WorkflowDialogHost = () => {
const { editGraph, replace } = useProjectGraphCommands();
const { project: projectStore } = useWorkflowUi();
const notify = useWorkflowNotifications();
+ const { t } = useTranslation();
+ const notifyRef = useRef(notify);
+ const translationRef = useRef(t);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const addNodeConnection = workflowUiStore.useSelector((snapshot) => snapshot.addNodeConnection);
const addNodePosition = workflowUiStore.useSelector((snapshot) => snapshot.addNodePosition);
@@ -257,6 +276,11 @@ export const WorkflowDialogHost = () => {
const isNewWorkflowConfirmOpen = workflowUiStore.useSelector((snapshot) => snapshot.isNewWorkflowConfirmOpen);
const lastImportRequestRef = useRef(importRequestCount);
+ useEffect(() => {
+ notifyRef.current = notify;
+ translationRef.current = t;
+ }, [notify, t]);
+
// Library autosave: bound graphs save themselves back after edits settle.
//
// The autosaver is created AND disposed inside one mount effect, held in a
@@ -297,12 +321,16 @@ export const WorkflowDialogHost = () => {
save: async (workflowId, serialized) => {
// Same scope discipline as the manual save paths: never let a
// debounced write land in the next account's library.
- const owner = captureAccountScope();
+ assertAccountScopeCurrent(hostScope);
if (hasMultipleWorkflowReturnNodes(projectStore.getSnapshot().projectGraph)) {
+ notifyRef.current.error(
+ translationRef.current('workflowLibrary.saveFailed'),
+ translationRef.current('workflowLibrary.multipleWorkflowReturnNodes')
+ );
throw new Error('Workflow contains multiple workflow_return nodes.');
}
- await updateLibraryWorkflow(workflowId, serialized, owner.signal);
- assertAccountScopeCurrent(owner);
+ await updateLibraryWorkflow(workflowId, serialized, hostScope.signal);
+ assertAccountScopeCurrent(hostScope);
// The library dialog serves cached payloads and pages; a save changes both.
invalidateWorkflowLibraryCache(workflowId);
},
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsx
index d50561656d..fb5b245866 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsx
@@ -2,6 +2,7 @@ import type { ProjectGraphState, WorkflowNode } from '@features/workflow/core/ty
import type { WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';
import type { ProjectGraphAction } from '@features/workflow/utility';
+import { invalidateWorkflowLibraryCache } from '@features/workflow/data/libraryCache';
import { createProjectGraph, projectGraphReducer } from '@features/workflow/utility';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act } from 'react';
@@ -32,11 +33,34 @@ import { CallSavedWorkflowSyncRuntime } from './CallSavedWorkflowSyncRuntime';
const MISSING_WORKFLOW_ID = 'missing-workflow';
/** A call node as `parseWorkflowJson` produces it for a reloaded parent: an id, and status `loading`. */
-const buildCallNode = (id: string, workflowId: string = MISSING_WORKFLOW_ID): WorkflowNode =>
+const buildCallNode = (
+ id: string,
+ workflowId: string = MISSING_WORKFLOW_ID,
+ withCapturedFields = false
+): WorkflowNode =>
({
data: {
callSavedWorkflowStatus: 'loading',
- inputs: { workflow_id: { label: '', name: 'workflow_id', value: workflowId } },
+ inputs: {
+ ...(withCapturedFields ? { captured: { label: 'Captured', name: 'captured', value: 'persisted' } } : {}),
+ workflow_id: { label: '', name: 'workflow_id', value: workflowId },
+ },
+ ...(withCapturedFields
+ ? {
+ dynamicInputTemplates: {
+ captured: {
+ description: 'Captured field',
+ fieldKind: 'input',
+ input: 'any',
+ name: 'captured',
+ required: false,
+ title: 'Captured',
+ type: { batch: false, cardinality: 'SINGLE', name: 'StringField' },
+ uiHidden: false,
+ },
+ },
+ }
+ : {}),
isIntermediate: false,
isOpen: true,
label: '',
@@ -147,16 +171,28 @@ describe('CallSavedWorkflowSyncRuntime with an unreachable child workflow', () =
);
});
- return () => graph;
+ return {
+ readGraph: () => graph,
+ updateGraph: (nextGraph: ProjectGraphState) => {
+ graph = nextGraph;
+ current = snapshot();
+ for (const listener of listeners) {
+ listener();
+ }
+ },
+ };
};
/** Every node reports the failure, and no further requests go out once they do. */
- const expectSettled = async (readGraph: () => ProjectGraphState, expected: string[]) => {
+ const expectSettled = async (readGraph: () => ProjectGraphState, expected: string[], expectedCalls?: number) => {
await settle(250);
expect(readStatuses(readGraph())).toEqual(expected);
const settledCalls = getLibraryWorkflowRecordMock.mock.calls.length;
+ if (expectedCalls !== undefined) {
+ expect(settledCalls).toBe(expectedCalls);
+ }
await settle(250);
@@ -164,7 +200,7 @@ describe('CallSavedWorkflowSyncRuntime with an unreachable child workflow', () =
};
it('settles a single node', async () => {
- const readGraph = await mountWith([buildCallNode('call-1')]);
+ const { readGraph } = await mountWith([buildCallNode('call-1')]);
await expectSettled(readGraph, ['error']);
});
@@ -172,14 +208,57 @@ describe('CallSavedWorkflowSyncRuntime with an unreachable child workflow', () =
// The contrast that pins the cause: the same two nodes, but distinct ids, so
// the shared retry flag is never contended.
it('settles two nodes naming different unreachable workflows', async () => {
- const readGraph = await mountWith([buildCallNode('call-1', 'missing-a'), buildCallNode('call-2', 'missing-b')]);
+ const { readGraph } = await mountWith([buildCallNode('call-1', 'missing-a'), buildCallNode('call-2', 'missing-b')]);
await expectSettled(readGraph, ['error', 'error']);
});
it('settles two nodes naming the same unreachable workflow', async () => {
- const readGraph = await mountWith([buildCallNode('call-1'), buildCallNode('call-2')]);
+ const { readGraph } = await mountWith([buildCallNode('call-1'), buildCallNode('call-2')]);
- await expectSettled(readGraph, ['error', 'error']);
+ await expectSettled(readGraph, ['error', 'error'], 1);
+ });
+
+ it('keeps recalled dynamic fields visible when the child workflow is unavailable', async () => {
+ const { readGraph } = await mountWith([buildCallNode('call-1', MISSING_WORKFLOW_ID, true)]);
+
+ await expectSettled(readGraph, ['error']);
+
+ const node = readGraph().nodes[0];
+ expect(node.type === 'invocation' && node.data.dynamicInputTemplates).toHaveProperty('captured');
+ expect(node.type === 'invocation' && node.data.inputs.captured?.value).toBe('persisted');
+ });
+
+ it('keeps a switched workflow retryable when the previous request settles late', async () => {
+ let rejectWorkflowA: ((error: Error) => void) | undefined;
+ getLibraryWorkflowRecordMock.mockImplementation((workflowId: string) => {
+ if (workflowId === 'workflow-a') {
+ return new Promise((_resolve, reject) => {
+ rejectWorkflowA = reject;
+ });
+ }
+
+ return Promise.reject(new Error('not found'));
+ });
+
+ const { readGraph, updateGraph } = await mountWith([buildCallNode('call-1', 'workflow-a')]);
+ await settle(25);
+
+ updateGraph(
+ projectGraphReducer(readGraph(), {
+ fieldName: 'workflow_id',
+ nodeId: 'call-1',
+ type: 'setFieldValue',
+ value: 'workflow-b',
+ })
+ );
+ await settle(25);
+ expect(readStatuses(readGraph())).toEqual(['error']);
+
+ invalidateWorkflowLibraryCache('workflow-b');
+ rejectWorkflowA?.(new Error('workflow A settled late'));
+ await settle(25);
+
+ expect(getLibraryWorkflowRecordMock).toHaveBeenCalledTimes(3);
});
});
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 8cb3244082..441a2a2702 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsx
@@ -137,8 +137,9 @@ const needsDynamicFieldSync = (
export const CallSavedWorkflowSyncRuntime = () => {
const queryClient = useQueryClient();
const { commands, project: projectPort } = useWorkflowUi();
- const retryableDetailWorkflowIds = useRef(new Set<string>());
+ const retryableDetailWorkflowIds = useRef(new Map<string, string>());
const previousDetailWorkflowIds = useRef(new Map<string, string>());
+ const previousDetailStatuses = useRef(new Map<string, 'loading' | 'ready' | 'error'>());
const parseChildWorkflow = useMemo(() => createSavedWorkflowDocumentParser(), []);
const reconcile = () => {
const templatesSnapshot = getInvocationTemplatesSnapshot();
@@ -148,6 +149,20 @@ export const CallSavedWorkflowSyncRuntime = () => {
}
const document = projectPort.getSnapshot().projectGraph;
+ const currentNodeIds = new Set(document.nodes.map((node) => node.id));
+
+ for (const nodeId of retryableDetailWorkflowIds.current.keys()) {
+ if (!currentNodeIds.has(nodeId)) {
+ retryableDetailWorkflowIds.current.delete(nodeId);
+ }
+ }
+
+ for (const nodeId of previousDetailStatuses.current.keys()) {
+ if (!currentNodeIds.has(nodeId)) {
+ previousDetailStatuses.current.delete(nodeId);
+ }
+ }
+
const setStatus = (nodeId: string, workflowId: string, status: 'loading' | 'ready' | 'error') => {
const currentDocument = projectPort.getSnapshot().projectGraph;
const currentNode = currentDocument.nodes.find((candidate) => candidate.id === nodeId);
@@ -170,10 +185,12 @@ export const CallSavedWorkflowSyncRuntime = () => {
const workflowId =
typeof node.data.inputs.workflow_id?.value === 'string' ? node.data.inputs.workflow_id.value : '';
const previousWorkflowId = previousDetailWorkflowIds.current.get(node.id);
+ const previousStatus = previousDetailStatuses.current.get(node.id);
+ const currentStatus = node.data.callSavedWorkflowStatus ?? (workflowId ? 'loading' : 'ready');
+ const detailOptions = workflowId ? savedWorkflowDetailQueryOptions(workflowId) : undefined;
+ const query = detailOptions ? queryClient.getQueryCache().find({ queryKey: detailOptions.queryKey }) : undefined;
- if (workflowId && workflowId !== previousWorkflowId) {
- retryableDetailWorkflowIds.current.add(workflowId);
- }
+ previousDetailStatuses.current.set(node.id, currentStatus);
previousDetailWorkflowIds.current.set(node.id, workflowId);
@@ -194,18 +211,24 @@ export const CallSavedWorkflowSyncRuntime = () => {
continue;
}
- const detailOptions = savedWorkflowDetailQueryOptions(workflowId);
- const query = queryClient.getQueryCache().find({ queryKey: detailOptions.queryKey });
+ if (!detailOptions) {
+ continue;
+ }
- if (node.data.callSavedWorkflowStatus === 'loading' && query?.state.status === 'error') {
- retryableDetailWorkflowIds.current.add(workflowId);
+ if (
+ node.data.callSavedWorkflowStatus === 'loading' &&
+ previousWorkflowId === workflowId &&
+ previousStatus === 'error' &&
+ query?.state.status === 'error'
+ ) {
+ retryableDetailWorkflowIds.current.set(node.id, workflowId);
}
- const retryWasAuthorized = retryableDetailWorkflowIds.current.has(workflowId);
+ const retryWasAuthorized = retryableDetailWorkflowIds.current.get(node.id) === workflowId;
if (
shouldFetchSavedWorkflowDetail(query, {
- retryErrors: retryableDetailWorkflowIds.current.has(workflowId),
+ retryErrors: retryWasAuthorized,
})
) {
const hasExistingDetail = query?.state.data !== undefined && query.state.data !== null;
@@ -217,12 +240,24 @@ export const CallSavedWorkflowSyncRuntime = () => {
void queryClient
.fetchQuery(detailOptions)
.then(() => {
- retryableDetailWorkflowIds.current.delete(workflowId);
+ if (retryableDetailWorkflowIds.current.get(node.id) === workflowId) {
+ retryableDetailWorkflowIds.current.delete(node.id);
+ }
})
.catch(() => {
- retryableDetailWorkflowIds.current.delete(workflowId);
+ if (retryableDetailWorkflowIds.current.get(node.id) === workflowId) {
+ retryableDetailWorkflowIds.current.delete(node.id);
+ }
const failedQuery = queryClient.getQueryCache().find({ queryKey: detailOptions.queryKey });
+ const currentNode = projectPort
+ .getSnapshot()
+ .projectGraph.nodes.find((candidate) => candidate.id === node.id);
+ const isCurrentWorkflow =
+ currentNode?.type === 'invocation' &&
+ currentNode.data.type === 'call_saved_workflow' &&
+ currentNode.data.inputs.workflow_id?.value === workflowId;
if (
+ isCurrentWorkflow &&
shouldRetrySavedWorkflowDetailAfterFailure(
retryWasAuthorized,
failedQuery?.state.data !== undefined && failedQuery.state.data !== null
@@ -231,7 +266,7 @@ export const CallSavedWorkflowSyncRuntime = () => {
// Keep the node blocked while stale data is being retried. This
// permits transient revalidation failures to recover without
// allowing a deleted child workflow to enqueue stale inputs.
- retryableDetailWorkflowIds.current.add(workflowId);
+ retryableDetailWorkflowIds.current.set(node.id, workflowId);
}
setStatus(node.id, workflowId, 'error');
});
@@ -302,7 +337,15 @@ export const CallSavedWorkflowSyncRuntime = () => {
});
const unsubscribeLibrary = onWorkflowLibraryCacheInvalidated((workflowId) => {
if (workflowId) {
- retryableDetailWorkflowIds.current.add(workflowId);
+ for (const node of projectPort.getSnapshot().projectGraph.nodes) {
+ if (
+ node.type === 'invocation' &&
+ node.data.type === 'call_saved_workflow' &&
+ node.data.inputs.workflow_id?.value === workflowId
+ ) {
+ retryableDetailWorkflowIds.current.set(node.id, workflowId);
+ }
+ }
void queryClient.invalidateQueries({
exact: true,
queryKey: savedWorkflowDetailQueryKey(workflowId),
@@ -311,7 +354,15 @@ export const CallSavedWorkflowSyncRuntime = () => {
} else {
for (const query of queryClient.getQueryCache().findAll({ queryKey: ['workflow', 'call-saved', 'detail'] })) {
if (isSavedWorkflowDetailQueryKey(query.queryKey)) {
- retryableDetailWorkflowIds.current.add(query.queryKey[3]);
+ for (const node of projectPort.getSnapshot().projectGraph.nodes) {
+ if (
+ node.type === 'invocation' &&
+ node.data.type === 'call_saved_workflow' &&
+ node.data.inputs.workflow_id?.value === query.queryKey[3]
+ ) {
+ retryableDetailWorkflowIds.current.set(node.id, query.queryKey[3]);
+ }
+ }
}
}
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.test.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.test.ts
index 2f0dbd59c8..618a7972f9 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.test.ts
@@ -42,4 +42,13 @@ describe('projectHasWidgetType', () => {
})
).toBe(false);
});
+
+ it('keeps the workflow host for a library-bound graph after its last call node is removed', () => {
+ expect(
+ projectNeedsWorkflowHost({
+ ...project([]),
+ projectGraph: { libraryWorkflowId: 'library-workflow-1', nodes: [] },
+ })
+ ).toBe(true);
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx
index c0a1eeeae1..c94f9b3084 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx
@@ -6,7 +6,7 @@ import { WidgetFailureBoundary } from './WidgetFailureBoundary';
type WidgetHostProject = {
floatingWidgets?: Record<string, unknown>;
- projectGraph?: { nodes: unknown[] };
+ projectGraph?: { libraryWorkflowId?: unknown; nodes: unknown[] };
widgetInstances: Record<string, { typeId?: string }>;
widgetRegions: Record<string, { instanceIds: string[] }>;
};
@@ -24,6 +24,7 @@ export const projectHasWidgetType = (project: WidgetHostProject, widgetTypeId: s
export const projectNeedsWorkflowHost = (project: WidgetHostProject): boolean =>
projectHasWidgetType(project, 'workflow') ||
+ (typeof project.projectGraph?.libraryWorkflowId === 'string' && project.projectGraph.libraryWorkflowId.length > 0) ||
(project.projectGraph?.nodes.some((node) => {
if (typeof node !== 'object' || node === null) {
return false;