Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(webv2): harden saved workflow synchronization
JPPhoto9015b17bb225
diff --git a/invokeai/frontend/web/src/features/nodes/types/invocation.test.ts b/invokeai/frontend/web/src/features/nodes/types/invocation.test.tsindex 1acc0c3885..fdea1579aa 100644--- a/invokeai/frontend/web/src/features/nodes/types/invocation.test.ts+++ b/invokeai/frontend/web/src/features/nodes/types/invocation.test.ts@@ -130,4 +130,28 @@ describe('zInvocationNodeData: extra-input scoping', () => {ui_hidden: false,});});++ it('accepts legacy-compatible enum dynamic templates from webv2', () => {+ const parsed = zInvocationNodeData.parse({+ ...buildNodeData('call_saved_workflow', {}),+ dynamicInputTemplates: {+ literal: {+ batch: false,+ cardinality: 'SINGLE',+ default: '2',+ description: 'Literal value',+ fieldKind: 'input',+ input: 'any',+ name: 'literal',+ options: ['2'],+ required: false,+ title: 'Literal',+ type: { batch: false, cardinality: 'SINGLE', name: 'EnumField' },+ uiHidden: false,+ },+ },+ });++ expect(parsed.dynamicInputTemplates.literal).toMatchObject({ default: '2', options: ['2'] });+ });});diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex ed24d364a8..1d4b53c7e4 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1439,7 +1439,8 @@"savedWorkflowShared": "Shared","savedWorkflowSearch": "Search saved workflows…","savedWorkflowClear": "Clear saved workflow",- "savedWorkflowLoading": "Loading saved workflow…",+ "savedWorkflowListLoading": "Loading saved workflows…",+ "savedWorkflowDetailLoading": "Loading saved workflow…","savedWorkflowNoExposedFields": "This workflow has no exposed fields.","savedWorkflowUpdating": "Updating saved workflows…","noMatchingWorkflows": "No matching saved workflows",diff --git a/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.test.tsindex 214fed30cf..c303ba9685 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.test.ts@@ -192,7 +192,7 @@ describe('Call Saved Workflow dynamic fields', () => {});});- it('preserves valid dynamic values and presentation from parents without templates', () => {+ it('preserves valid values while refreshing generated presentation from parents without templates', () => {const callNode = buildInvocationNode(callSavedWorkflowTemplate, { x: 0, y: 0 });callNode.id = 'call-1';callNode.data.inputs[dynamicFieldName('a')] = {@@ -218,7 +218,7 @@ describe('Call Saved Workflow dynamic fields', () => {expect(node?.data.inputs[dynamicFieldName('a')]).toMatchObject({description: 'Persisted description',- label: 'Persisted label',+ label: 'Left Addend',value: 99,});expect(node?.data.inputs[dynamicFieldName('b')]).toMatchObject({@@ -227,6 +227,28 @@ describe('Call Saved Workflow dynamic fields', () => {});});+ it('preserves an explicit label override from a parent without templates', () => {+ const callNode = buildInvocationNode(callSavedWorkflowTemplate, { x: 0, y: 0 });+ callNode.id = 'call-1';+ callNode.data.inputs[dynamicFieldName('a')] = {+ label: 'Custom label',+ labelOverride: true,+ name: dynamicFieldName('a'),+ value: 99,+ };++ 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({ label: 'Custom label', labelOverride: true });+ });+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.tsindex 81392ed3a6..fc79f2def3 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/callSavedWorkflow.ts@@ -238,7 +238,9 @@ export const syncCallSavedWorkflowFields = (? sameFieldType(previousTemplate, field.fieldTemplate): isWorkflowFieldValueValid(field.fieldTemplate, previous.value));const label =- keepValue && previous && (!previousTemplate ? previous.label !== '' : previous.label !== previousTemplate.title)+ keepValue &&+ previous &&+ (!previousTemplate ? previous.labelOverride === true : previous.label !== previousTemplate.title)? previous.label: field.label;const description =diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.tsindex 5d12ccbd79..611a7464a6 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/document.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.ts@@ -637,6 +637,7 @@ const applyProjectGraphAction = (document: ProjectGraphState, action: ProjectGrareturn setFieldInstance(document, action.nodeId, action.fieldName, (instance) => ({...instance,label: action.label,+ labelOverride: action.label !== '',}));}case 'setFieldDescription': {diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.tsindex c43d9a3416..07bb21d890 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts@@ -245,6 +245,22 @@ describe('getRandomWorkflowFieldValue', () => {expect(getRandomWorkflowFieldValue(steppedExclusive, () => 0.999)).toBe(0.5);});+ it('keeps legacy numeric templates finite when optional constraints are absent', () => {+ const legacy = input({+ exclusiveMaximum: undefined,+ exclusiveMinimum: undefined,+ maximum: undefined,+ minimum: undefined,+ multipleOf: undefined,+ type: single('IntegerField'),+ });+ const value = getRandomWorkflowFieldValue(legacy, () => 0.5);++ expect(Number.isFinite(value)).toBe(true);+ expect(Number.isInteger(value)).toBe(true);+ expect(isWorkflowFieldValueValid(legacy, value)).toBe(true);+ });+it('shuffles only direct numeric fields', () => {expect(isShuffleableField(input({ type: single('IntegerField') }))).toBe(true);expect(isShuffleableField(input({ type: single('FloatField') }))).toBe(true);diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.tsindex d094d384b0..621530cae8 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts@@ -63,11 +63,18 @@ const countDecimals = (value: number): number => {return fraction.length;};+const finiteNumberOrNull = (value: number | null | undefined): number | null =>+ typeof value === 'number' && Number.isFinite(value) ? value : null;+/** A random value inside the template's bounds, snapped to its step; unbounded ends default to 0…SEED_MAX. */export const getRandomWorkflowFieldValue = (template: FieldInputTemplate, random = Math.random): number => {const isInteger = template.type.name === 'IntegerField';- const step = template.multipleOf ?? (isInteger ? 1 : 0);- const { exclusiveMaximum, exclusiveMinimum, maximum, minimum } = template;+ const multipleOf = finiteNumberOrNull(template.multipleOf);+ const step = multipleOf !== null && multipleOf > 0 ? multipleOf : isInteger ? 1 : 0;+ const exclusiveMaximum = finiteNumberOrNull(template.exclusiveMaximum);+ const exclusiveMinimum = finiteNumberOrNull(template.exclusiveMinimum);+ const maximum = finiteNumberOrNull(template.maximum);+ const minimum = finiteNumberOrNull(template.minimum);if (step <= 0) {const min = minimum ?? exclusiveMinimum ?? 0;@@ -171,24 +178,31 @@ const isNumberFieldValueValid = (template: FieldInputTemplate, value: unknown):return false;}- if (template.minimum !== null && value < template.minimum) {+ const minimum = finiteNumberOrNull(template.minimum);+ const maximum = finiteNumberOrNull(template.maximum);+ const exclusiveMinimum = finiteNumberOrNull(template.exclusiveMinimum);+ const exclusiveMaximum = finiteNumberOrNull(template.exclusiveMaximum);++ if (minimum !== null && value < minimum) {return false;}- if (template.maximum !== null && value > template.maximum) {+ if (maximum !== null && value > maximum) {return false;}- if (template.exclusiveMinimum !== null && value <= template.exclusiveMinimum) {+ if (exclusiveMinimum !== null && value <= exclusiveMinimum) {return false;}- if (template.exclusiveMaximum !== null && value >= template.exclusiveMaximum) {+ if (exclusiveMaximum !== null && value >= exclusiveMaximum) {return false;}- if (template.multipleOf !== null) {- const quotient = value / template.multipleOf;+ const multipleOf = finiteNumberOrNull(template.multipleOf);++ if (multipleOf !== null && multipleOf > 0) {+ const quotient = value / multipleOf;if (Math.abs(quotient - Math.round(quotient)) > Number.EPSILON * 100) {return false;diff --git a/invokeai/frontend/webv2/src/features/workflow/core/types.ts b/invokeai/frontend/webv2/src/features/workflow/core/types.tsindex 000b0c201c..ee7ca68a52 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/types.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/types.ts@@ -87,6 +87,8 @@ export interface XYPosition {export interface WorkflowFieldInstance {name: string;label: string;+ /** True when the label was explicitly changed by the user rather than generated from a template. */+ labelOverride?: boolean;/** User override of the template's field description (shown in the Linear UI). */description?: string;/**diff --git a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.tsindex 407d258519..651af2e766 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/workflowJson.ts@@ -29,6 +29,7 @@ const zXYPosition = z.object({ x: z.number().catch(0), y: z.number().catch(0) })const zFieldInstance = z.object({description: z.string().optional().catch(undefined),label: z.string().catch(''),+ labelOverride: z.boolean().optional().catch(undefined),name: z.string(),seedMode: z.enum(SEED_MODES).optional().catch(undefined),value: z.unknown().optional(),diff --git a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.test.tsindex 8ec17c7621..91da8fe5a5 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.test.ts@@ -1,14 +1,19 @@import { QueryClient } from '@tanstack/react-query';-import { describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import {getSavedWorkflowDetailQueryStatus,isSavedWorkflowDetailQueryKey,savedWorkflowDetailQueryOptions,+ savedWorkflowPickerQueryOptions,shouldFetchSavedWorkflowDetail,} from './savedWorkflowQueries';describe('saved workflow detail query policy', () => {+ afterEach(() => {+ vi.useRealTimers();+ });+it('recognizes only detail query keys with a workflow id', () => {expect(isSavedWorkflowDetailQueryKey(['workflow', 'call-saved', 'detail', 'workflow-1'])).toBe(true);expect(isSavedWorkflowDetailQueryKey(['workflow', 'call-saved', 'picker', 'workflow-1'])).toBe(false);@@ -35,6 +40,14 @@ describe('saved workflow detail query policy', () => {{ retryErrors: true })).toBe(true);+ expect(+ shouldFetchSavedWorkflowDetail(+ { state: { fetchStatus: 'idle', isInvalidated: false, status: 'error' } },+ {+ retryErrors: true,+ }+ )+ ).toBe(true);});it('classifies detail query state for reconciliation', () => {@@ -59,11 +72,13 @@ describe('saved workflow detail query policy', () => {getSavedWorkflowDetailQueryStatus({state: { data: { workflow_id: 'workflow-1' }, fetchStatus: 'idle', isInvalidated: true, status: 'error' },})- ).toBe('ready');+ ).toBe('error');});it('does not retry a failed detail lookup', () => {expect(savedWorkflowDetailQueryOptions('workflow-1').retry).toBe(false);+ expect(savedWorkflowDetailQueryOptions('workflow-1').gcTime).toBe(Infinity);+ expect(savedWorkflowPickerQueryOptions({ isPublic: true, page: 0 }).staleTime).toBe(30_000);});it('recovers an invalidated failed lookup with one authorized retry', async () => {@@ -103,4 +118,22 @@ describe('saved workflow detail query policy', () => {queryClient.clear();}});++ it('retains an observerless selected detail beyond the default cache lifetime', async () => {+ vi.useFakeTimers();+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const detailOptions = savedWorkflowDetailQueryOptions('workflow-1');++ try {+ await queryClient.fetchQuery({+ ...detailOptions,+ queryFn: () => Promise.resolve({ workflow_id: 'workflow-1' }) as never,+ });+ vi.advanceTimersByTime(5 * 60_000 + 1);++ expect(queryClient.getQueryCache().find({ queryKey: detailOptions.queryKey })).toBeDefined();+ } finally {+ queryClient.clear();+ }+ });});diff --git a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.ts b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.tsindex 399e534631..f5c9fa9321 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowQueries.ts@@ -38,9 +38,9 @@ export const shouldFetchSavedWorkflowDetail = (options: SavedWorkflowDetailFetchOptions = {}): boolean =>query === undefined ||- (query.state.isInvalidated &&- query.state.fetchStatus === 'idle' &&- (query.state.status === 'success' || (options.retryErrors === true && query.state.status === 'error')));+ (query.state.fetchStatus === 'idle' &&+ ((query.state.isInvalidated && query.state.status === 'success') ||+ (options.retryErrors === true && query.state.status === 'error')));export const getSavedWorkflowDetailQueryStatus = (query: SavedWorkflowDetailQueryLike | undefined@@ -49,14 +49,14 @@ export const getSavedWorkflowDetailQueryStatus = (return 'missing';}- if (query.state.data !== undefined && query.state.data !== null) {- return 'ready';- }-if (query.state.status === 'error') {return 'error';}+ if (query.state.data !== undefined && query.state.data !== null) {+ return 'ready';+ }+if (query.state.status !== 'success' || query.state.fetchStatus !== 'idle') {return 'loading';}@@ -68,6 +68,7 @@ export const savedWorkflowDetailQueryOptions = (workflowId: string) => ({queryKey: savedWorkflowDetailQueryKey(workflowId),queryFn: ({ signal }: { signal: AbortSignal }): Promise<WorkflowRecordDTO> =>getLibraryWorkflowRecord(workflowId, signal),+ gcTime: Infinity,retry: false,staleTime: 30_000,});@@ -76,6 +77,7 @@ export const savedWorkflowPickerQueryOptions = (params: ListWorkflowsParams) =>queryKey: ['workflow', 'call-saved', 'picker', params] as const,queryFn: ({ pageParam, signal }: { pageParam: number; signal: AbortSignal }): Promise<WorkflowLibraryPage> =>listLibraryWorkflows({ ...params, page: pageParam, signal }),+ staleTime: 30_000,initialPageParam: 0,getNextPageParam: (lastPage: WorkflowLibraryPage): number | undefined =>lastPage.page + 1 < lastPage.pages ? lastPage.page + 1 : undefined,diff --git a/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.test.tsindex 567524b9e8..a441256643 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/templates.test.ts@@ -270,6 +270,47 @@ describe('parseOpenApiToTemplates', () => {expect(parsed.for?.outputs.output_collection?.outputScope).toBe('final');expect(parsed.for?.outputs.output?.uiHidden).toBe(true);});++ it('extracts options from nullable Literal schemas and normalizes numeric options', () => {+ const parsed = parseOpenApiToTemplates({+ components: {+ schemas: {+ LiteralInvocation: {+ class: 'invocation',+ output: { $ref: '#/components/schemas/IntegerOutput' },+ properties: {+ type: { default: 'literal_invocation' },+ text: {+ anyOf: [{ enum: ['fast', 'slow'], type: 'string' }, { type: 'null' }],+ default: 'slow',+ field_kind: 'input',+ orig_required: false,+ title: 'Text',+ },+ number: {+ anyOf: [{ const: 2, type: 'integer' }, { type: 'null' }],+ field_kind: 'input',+ orig_required: false,+ title: 'Number',+ },+ },+ title: 'Literal',+ type: 'object',+ },+ IntegerOutput: {+ class: 'output',+ properties: { type: { const: 'integer_output' }, value: { field_kind: 'output', type: 'integer' } },+ type: 'object',+ },+ },+ },+ });++ expect(parsed.literal_invocation?.inputs.text?.options).toEqual(['fast', 'slow']);+ expect(parsed.literal_invocation?.inputs.text?.default).toBe('slow');+ expect(parsed.literal_invocation?.inputs.number?.options).toEqual(['2']);+ expect(parsed.literal_invocation?.inputs.number?.default).toBe('2');+ });});describe('parseFieldType', () => {diff --git a/invokeai/frontend/webv2/src/features/workflow/data/templates.ts b/invokeai/frontend/webv2/src/features/workflow/data/templates.tsindex 7aed36d9bd..60d6e23791 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/templates.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/templates.ts@@ -175,6 +175,28 @@ const getNumberOrNull = (value: unknown): number | null => (typeof value === 'nuconst getStringArrayOrNull = (value: unknown): string[] | null =>Array.isArray(value) && value.every((item) => typeof item === 'string') ? value : null;+const getEnumValues = (property: JsonObject): unknown[] | null => {+ if (Array.isArray(property.enum)) {+ return property.enum;+ }++ if (property.const !== undefined) {+ return [property.const];+ }++ if (Array.isArray(property.anyOf)) {+ const variants = property.anyOf.filter(+ (variant): variant is JsonObject => isJsonObject(variant) && variant.type !== 'null'+ );++ if (variants.length === 1) {+ return getEnumValues(variants[0]);+ }+ }++ return null;+};+const getDefaultValueForType = (type: FieldType, options: string[] | null): unknown => {if (type.cardinality === 'COLLECTION') {return undefined;@@ -201,12 +223,12 @@ const buildInputTemplate = (type: FieldType,fieldKind: FieldInputTemplate['fieldKind']): FieldInputTemplate => {- const enumValues = Array.isArray(property.enum)- ? property.enum- : property.const !== undefined- ? [property.const]- : null;- const options = enumValues ? enumValues.filter((value): value is string => typeof value === 'string') : null;+ const enumValues = getEnumValues(property);+ const options = enumValues+ ? enumValues+ .filter((value) => typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')+ .map(String)+ : null;const input = property.input === 'connection' || property.input === 'direct' ? property.input : 'any';const uiChoiceLabels = isJsonObject(property.ui_choice_labels)? Object.fromEntries(@@ -217,7 +239,10 @@ const buildInputTemplate = (: null;return {- default: property.default ?? getDefaultValueForType(type, options),+ default:+ type.name === 'EnumField' && property.default !== undefined && property.default !== null+ ? String(property.default)+ : (property.default ?? getDefaultValueForType(type, options)),description: typeof property.description === 'string' ? property.description : '',exclusiveMaximum: getNumberOrNull(property.exclusiveMaximum),exclusiveMinimum: getNumberOrNull(property.exclusiveMinimum),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.tsindex d7767de8fe..60b9df4444 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@@ -66,4 +66,14 @@ describe('createSavedWorkflowDocumentParser', () => {expect(parser(malformed)).toBeUndefined();expect(parse).toHaveBeenCalledOnce();});++ it('rejects non-object payloads before consulting the object cache', () => {+ const parse = vi.fn();+ const parser = createSavedWorkflowDocumentParser(parse);++ expect(parser(42)).toBeUndefined();+ expect(parser(null)).toBeUndefined();+ expect(parser([])).toBeUndefined();+ expect(parse).not.toHaveBeenCalled();+ });});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsxindex 4e283fe236..54b8f902bc 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsx@@ -21,20 +21,24 @@ import {} from '@features/workflow/utility';import { useMountEffect } from '@platform/react/useMountEffect';import { useQueryClient } from '@tanstack/react-query';-import { useMemo } from 'react';+import { useMemo, useRef } from 'react';export const createSavedWorkflowDocumentParser = (parse: (workflow: Record<string, unknown>) => ParsedWorkflow = parseWorkflowJson-): ((workflow: Record<string, unknown>) => ProjectGraphState | undefined) => {+): ((workflow: unknown) => ProjectGraphState | undefined) => {const cache = new WeakMap<object, ProjectGraphState | null>();return (workflow) => {+ if (typeof workflow !== 'object' || workflow === null || Array.isArray(workflow)) {+ return undefined;+ }+if (cache.has(workflow)) {return cache.get(workflow) ?? undefined;}try {- const document = parse(workflow).document;+ const document = parse(workflow as Record<string, unknown>).document;cache.set(workflow, document);return document;} catch {@@ -132,7 +136,8 @@ const needsDynamicFieldSync = (export const CallSavedWorkflowSyncRuntime = () => {const queryClient = useQueryClient();const { commands, project: projectPort } = useWorkflowUi();- const retryableDetailWorkflowIds = new Set<string>();+ const retryableDetailWorkflowIds = useRef(new Set<string>());+ const previousDetailWorkflowIds = useRef(new Map<string, string>());const parseChildWorkflow = useMemo(() => createSavedWorkflowDocumentParser(), []);const reconcile = () => {const templatesSnapshot = getInvocationTemplatesSnapshot();@@ -163,6 +168,13 @@ 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);++ if (workflowId && workflowId !== previousWorkflowId) {+ retryableDetailWorkflowIds.current.add(workflowId);+ }++ previousDetailWorkflowIds.current.set(node.id, workflowId);if (!workflowId) {const hasDynamicFields =@@ -184,7 +196,11 @@ export const CallSavedWorkflowSyncRuntime = () => {const detailOptions = savedWorkflowDetailQueryOptions(workflowId);const query = queryClient.getQueryCache().find({ queryKey: detailOptions.queryKey });- if (shouldFetchSavedWorkflowDetail(query, { retryErrors: retryableDetailWorkflowIds.has(workflowId) })) {+ if (+ shouldFetchSavedWorkflowDetail(query, {+ retryErrors: retryableDetailWorkflowIds.current.has(workflowId),+ })+ ) {const hasExistingDetail = query?.state.data !== undefined && query.state.data !== null;if (!hasExistingDetail) {@@ -192,16 +208,18 @@ export const CallSavedWorkflowSyncRuntime = () => {}void queryClient- .ensureQueryData({ ...detailOptions, revalidateIfStale: true })+ .fetchQuery(detailOptions).then(() => {- retryableDetailWorkflowIds.delete(workflowId);+ retryableDetailWorkflowIds.current.delete(workflowId);}).catch(() => {- retryableDetailWorkflowIds.delete(workflowId);+ retryableDetailWorkflowIds.current.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');+ setStatus(+ node.id,+ workflowId,+ getSavedWorkflowDetailQueryStatus(failedQuery) === 'error' ? 'error' : 'loading'+ );});continue;}@@ -270,7 +288,7 @@ export const CallSavedWorkflowSyncRuntime = () => {});const unsubscribeLibrary = onWorkflowLibraryCacheInvalidated((workflowId) => {if (workflowId) {- retryableDetailWorkflowIds.add(workflowId);+ retryableDetailWorkflowIds.current.add(workflowId);void queryClient.invalidateQueries({exact: true,queryKey: savedWorkflowDetailQueryKey(workflowId),@@ -279,7 +297,7 @@ export const CallSavedWorkflowSyncRuntime = () => {} else {for (const query of queryClient.getQueryCache().findAll({ queryKey: ['workflow', 'call-saved', 'detail'] })) {if (isSavedWorkflowDetailQueryKey(query.queryKey)) {- retryableDetailWorkflowIds.add(query.queryKey[3]);+ retryableDetailWorkflowIds.current.add(query.queryKey[3]);}}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsxindex e90e034f18..8f4053948d 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx@@ -883,7 +883,7 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode))}{shouldShowCallSavedWorkflowLoadingHint(node) ? (<Text color="fg.subtle" fontSize="2xs" px={WORKFLOW_NODE_DENSITY.rowPaddingX} py="1">- {t('nodes.savedWorkflowLoading')}+ {t('nodes.savedWorkflowDetailLoading')}</Text>) : shouldShowCallSavedWorkflowNoExposedFieldsHint(node) ? (<Text color="fg.subtle" fontSize="2xs" px={WORKFLOW_NODE_DENSITY.rowPaddingX} py="1">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.tsxindex d4aaee25e0..174b35436d 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@@ -332,6 +332,18 @@ describe('WorkflowFieldInput textarea', () => {});describe('WorkflowFieldInput saved workflows', () => {+ it('uses plural loading copy while the workflow list is loading', async () => {+ workflowApiMock.apiFetchJson.mockImplementation(() => new Promise(() => {}));++ await renderField(SAVED_WORKFLOW_TEMPLATE, '', vi.fn());++ await vi.waitFor(() =>+ expect(host.querySelector<HTMLInputElement>('input[role="combobox"]')?.placeholder).toBe(+ 'nodes.savedWorkflowListLoading'+ )+ );+ });+it('displays dynamic workflow names and marks incompatible workflows disabled', async () => {const onChange = vi.fn();workflowApiMock.apiFetchJson.mockImplementation((path: string) => {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsxindex 6f72926836..5e068f6e45 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx@@ -149,6 +149,15 @@ const toFiniteNumber = (raw: string): number | null => {return Number.isFinite(parsed) ? parsed : null;};+const finiteNumberOrUndefined = (value: number | null | undefined): number | undefined =>+ typeof value === 'number' && Number.isFinite(value) ? value : undefined;++const positiveFiniteNumberOrUndefined = (value: number | null | undefined): number | undefined => {+ const normalized = finiteNumberOrUndefined(value);++ return normalized !== undefined && normalized > 0 ? normalized : undefined;+};+const StringInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {const text = typeof value === 'string' ? value : '';const onTextareaChange = useCallback(@@ -199,8 +208,9 @@ const selectInputText = (event: MouseEvent<HTMLInputElement>) => event.currentTaconst NumericInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {const isInteger = template.type.name === 'IntegerField';const numericValue = typeof value === 'number' && Number.isFinite(value) ? value : '';- const min = template.minimum ?? template.exclusiveMinimum ?? undefined;- const max = template.maximum ?? template.exclusiveMaximum ?? undefined;+ const min = finiteNumberOrUndefined(template.minimum) ?? finiteNumberOrUndefined(template.exclusiveMinimum);+ const max = finiteNumberOrUndefined(template.maximum) ?? finiteNumberOrUndefined(template.exclusiveMaximum);+ const multipleOf = positiveFiniteNumberOrUndefined(template.multipleOf);const onInputChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {const parsed = toFiniteNumber(event.currentTarget.value);@@ -220,7 +230,7 @@ const NumericInput = ({ id, invalid, onChange, template, value }: WorkflowFieldImax={max !== undefined ? String(max) : undefined}min={min !== undefined ? String(min) : undefined}size="xs"- step={template.multipleOf !== null ? String(template.multipleOf) : isInteger ? '1' : 'any'}+ step={multipleOf !== undefined ? String(multipleOf) : isInteger ? '1' : 'any'}type="number"value={numericValue}w="full"@@ -1589,7 +1599,7 @@ const SavedWorkflowInput = ({ onChange, template, value }: WorkflowFieldInputProflex="1"noResultsText={t('nodes.noMatchingWorkflows')}options={options}- searchPlaceholder={isLoading ? t('nodes.savedWorkflowLoading') : t('nodes.savedWorkflowSearch')}+ searchPlaceholder={isLoading ? t('nodes.savedWorkflowListLoading') : t('nodes.savedWorkflowSearch')}value={selectedOption?.value ?? null}onInputValueChange={setSearch}onListScrollToBottom={fetchNextPage}diff --git a/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsxindex 6977bb6764..3cd6d715ff 100644--- a/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsx@@ -37,22 +37,20 @@ let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;/**- * Returns the pointer to a stable, visible area in the upper-left of the- * viewport — where the harness below states it starts.+ * Returns the pointer to the viewport origin — where the harness below states+ * it starts.** That only holds for the first test. Once one has hovered the trigger the* cursor stays on it, so the next render mounts a fresh trigger underneath the* pointer and the card opens before the test asks for it. That surfaced as a* strict-mode violation, with `CLIP skip` matching both the trigger and the* already-open card's own heading and paragraph. The trigger is inset by- * 120px, so this area is reliably clear of it. Keep the target away from the- * viewport edge: Playwright can classify a 2px box at (0, 0) as outside the- * viewport after another browser test changes the viewport.+ * 120px, so the origin is reliably clear of it.*/const parkPointer = async (): Promise<void> => {const parking = document.createElement('div');- parking.style.cssText = 'position:fixed;left:8px;top:8px;width:64px;height:64px;z-index:2147483647';+ parking.style.cssText = 'position:fixed;left:0;top:0;width:2px;height:2px;z-index:2147483647';document.body.append(parking);await act(async () => {@@ -88,9 +86,9 @@ const render = async (adapter: FeatureHintsAdapter) => {<I18nextProvider i18n={i18n}><FeatureHintsProvider adapter={adapter}>{/*- Inset and shrink-wrapped on purpose: the mouse starts in the- upper-left parking area, so a full-width trigger at (0,0) would- already contain the pointer and `pointerenter` would never fire.+ Inset and shrink-wrapped on purpose: the mouse starts at the+ viewport origin, so a full-width trigger at (0,0) would already+ contain the pointer and `pointerenter` would never fire.*/}<FeatureHint hint="clipSkip"><Text display="inline-block" m="120px">diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.test.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.test.tsnew file mode 100644index 0000000000..13dcfdd830--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest';++import { projectHasWidgetType } from './WidgetHosts';++const project = (instanceIds: string[], floatingIds: string[] = []) => ({+ floatingWidgets: Object.fromEntries(floatingIds.map((id) => [id, {}])),+ widgetInstances: Object.fromEntries(+ [...instanceIds, ...floatingIds].map((id) => [id, { id, typeId: id.startsWith('workflow') ? 'workflow' : 'queue' }])+ ),+ widgetRegions: {+ center: { instanceIds },+ left: { instanceIds: [] },+ right: { instanceIds: [] },+ bottom: { instanceIds: [] },+ },+});++describe('projectHasWidgetType', () => {+ it('finds widget types mounted in regions', () => {+ expect(projectHasWidgetType(project(['workflow-1']), 'workflow')).toBe(true);+ expect(projectHasWidgetType(project(['queue-1']), 'workflow')).toBe(false);+ });++ it('finds widget types mounted in floating windows', () => {+ expect(projectHasWidgetType(project([], ['workflow-1']), 'workflow')).toBe(true);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsxindex 9216a879ea..45f33538e5 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetHosts.tsx@@ -1,8 +1,24 @@import { getWidgetHosts } from '@workbench/widgetRegistry';+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { Suspense, use } from 'react';import { WidgetFailureBoundary } from './WidgetFailureBoundary';+type WidgetHostProject = {+ floatingWidgets?: Record<string, unknown>;+ widgetInstances: Record<string, { typeId?: string }>;+ widgetRegions: Record<string, { instanceIds: string[] }>;+};++export const projectHasWidgetType = (project: WidgetHostProject, widgetTypeId: string): boolean => {+ const regionInstanceIds = Object.values(project.widgetRegions).flatMap((region) => region.instanceIds);+ const floatingInstanceIds = Object.keys(project.floatingWidgets ?? {});++ return [...regionInstanceIds, ...floatingInstanceIds].some(+ (instanceId) => project.widgetInstances[instanceId]?.typeId === widgetTypeId+ );+};+const WidgetHost = ({ widget }: { widget: ReturnType<typeof getWidgetHosts>[number] }) => {const Host = use(widget.host!.load());@@ -37,10 +53,15 @@ const WidgetHostBoundary = ({ widget }: { widget: ReturnType<typeof getWidgetHos);};-export const WidgetHosts = () => (- <>- {getWidgetHosts().map((widget) => (- <WidgetHostBoundary key={widget.manifest.id} widget={widget} />- ))}- </>-);+export const WidgetHosts = () => {+ const hasWorkflowWidget = useActiveProjectSelector((project) => projectHasWidgetType(project, 'workflow'));+ const widgets = getWidgetHosts().filter((widget) => widget.manifest.id !== 'workflow' || hasWorkflowWidget);++ return (+ <>+ {widgets.map((widget) => (+ <WidgetHostBoundary key={widget.manifest.id} widget={widget} />+ ))}+ </>+ );+};