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
test(webv2): cover workflow field entry in the Canvas node and Linear form
Josh Corbetta90ecbf0467f
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.tsindex b5198fd247..3590f7937c 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts@@ -106,6 +106,54 @@ describe('workflow field validation', () => {expect(isWorkflowFieldValueValid(template, 5.5)).toBe(false);});+ it('treats inclusive bounds, exclusive bounds, and steps exactly at their boundaries', () => {+ const inclusive = input({ maximum: 10, minimum: -2, type: single('FloatField') });++ expect(isWorkflowFieldValueValid(inclusive, -2)).toBe(true);+ expect(isWorkflowFieldValueValid(inclusive, -2.001)).toBe(false);+ expect(isWorkflowFieldValueValid(inclusive, 10)).toBe(true);+ expect(isWorkflowFieldValueValid(inclusive, 10.001)).toBe(false);++ const exclusive = input({ exclusiveMaximum: 1, exclusiveMinimum: -1, type: single('FloatField') });++ expect(isWorkflowFieldValueValid(exclusive, -1)).toBe(false);+ expect(isWorkflowFieldValueValid(exclusive, -0.999)).toBe(true);+ expect(isWorkflowFieldValueValid(exclusive, 1)).toBe(false);+ expect(isWorkflowFieldValueValid(exclusive, 0.999)).toBe(true);++ // An off-step value stays a value: it is reported, never snapped to the nearest step.+ const stepped = input({ exclusiveMinimum: -1, maximum: 1, multipleOf: 0.25, type: single('FloatField') });++ expect(isWorkflowFieldValueValid(stepped, 0.75)).toBe(true);+ expect(isWorkflowFieldValueValid(stepped, 0.7)).toBe(false);+ expect(isWorkflowFieldValueValid(stepped, -0.75)).toBe(true);+ expect(isWorkflowFieldValueValid(stepped, -1)).toBe(false);+ expect(isWorkflowFieldValueValid(stepped, -0.8)).toBe(false);+ expect(isWorkflowFieldValueValid(input({ multipleOf: 2, type: single('IntegerField') }), -4)).toBe(true);+ expect(isWorkflowFieldValueValid(input({ multipleOf: 2, type: single('IntegerField') }), -3)).toBe(false);+ });++ it('tells a cleared required number apart from a present but invalid one', () => {+ const required = input({ minimum: 0, type: single('IntegerField') });+ const optional = input({ required: false, type: single('FloatField') });++ expect(getWorkflowFieldInvalidReason({ isConnected: false, template: required, value: undefined })).toBe(+ 'Required value.'+ );+ expect(getWorkflowFieldInvalidReason({ isConnected: false, template: required, value: 2.5 })).toBe(+ 'Invalid value.'+ );+ expect(getWorkflowFieldInvalidReason({ isConnected: false, template: required, value: -1 })).toBe('Invalid value.');+ expect(getWorkflowFieldInvalidReason({ isConnected: false, template: optional, value: undefined })).toBe(null);+ expect(+ getWorkflowFieldInvalidReason({+ isConnected: false,+ template: input({ input: 'connection', type: single('IntegerField') }),+ value: 2.5,+ })+ ).toBe('Required connection.');+ });+it('allows empty optional direct values but flags populated invalid optional values', () => {const template = input({ maximum: 10, minimum: 1, required: false, type: single('IntegerField') });diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.tsindex 11f30396e1..142fae6f3e 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts@@ -309,7 +309,11 @@ export const getWorkflowFieldInvalidReason = ({return null;}- return isDirectInputField(template) ? 'Required value.' : 'Required connection.';+ if (!isDirectInputField(template)) {+ return 'Required connection.';+ }++ return isEmptyOptionalValue(value) ? 'Required value.' : 'Invalid value.';};// Raw hex (not Chakra tokens) because xyflow handles are styled inline.diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsxindex 1a799aee60..a8a45347f0 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx@@ -1,15 +1,16 @@import type { InvocationTemplate, ProjectGraphState, WorkflowInvocationNode } from '@features/workflow/contracts';import type { WorkflowNodeExecutionState } from '@features/workflow/ui/contracts';import type { WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';+import type { ProjectGraphAction } from '@features/workflow/utility';/* eslint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-array-as-prop -- each render mounts a fresh flow on purpose */import { ChakraProvider } from '@chakra-ui/react';import { WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';import { setNodePreviewCollapsed } from '@features/workflow/ui/workflowUiStore';-import { createProjectGraph } from '@features/workflow/utility';+import { createProjectGraph, projectGraphReducer } from '@features/workflow/utility';import { system } from '@theme/system';-import { ReactFlow } from '@xyflow/react';-import { act } from 'react';+import { applyNodeChanges, ReactFlow, type NodeChange } from '@xyflow/react';+import { act, startTransition, useCallback, useEffect, useState, useSyncExternalStore } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { page, userEvent } from 'vitest/browser';@@ -421,3 +422,270 @@ describe('InvocationFlowNode edge stacking', () => {expect(overOther.some((hit) => hit.closest('.react-flow__edge') !== null)).toBe(true);});});++describe('InvocationFlowNode field entry', () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ host = document.createElement('div');+ host.style.cssText = 'width: 480px; height: 520px;';+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ const entryInput = (name: string, title: string, typeName: string) => ({+ ...template.inputs.a!,+ input: 'any' as const,+ name,+ required: true,+ title,+ type: { batch: false, cardinality: 'SINGLE' as const, name: typeName },+ });+ const entryTemplate: InvocationTemplate = {+ ...template,+ inputs: {+ prompt: entryInput('prompt', 'Prompt', 'StringField'),+ steps: entryInput('steps', 'Steps', 'IntegerField'),+ weight: entryInput('weight', 'Weight', 'FloatField'),+ },+ outputs: {},+ title: 'Entry',+ type: 'entry',+ };+ const entryTemplates = { entry: entryTemplate };+ const entryNode: WorkflowInvocationNode = {+ ...documentNode,+ data: {+ ...documentNode.data,+ inputs: {+ prompt: { label: '', name: 'prompt', value: 'hello world' },+ steps: { label: '', name: 'steps', value: 20 },+ weight: { label: '', name: 'weight', value: 0.5 },+ },+ type: 'entry',+ },+ id: 'entry-node',+ };++ /** An undoable graph store standing in for the project aggregate. */+ const createGraphStore = (initial: ProjectGraphState) => {+ const listeners = new Set<() => void>();+ const history: ProjectGraphState[] = [];+ let graph = initial;+ const publish = (next: ProjectGraphState) => {+ graph = next;+ listeners.forEach((listener) => listener());+ };++ return {+ editGraph: (action: ProjectGraphAction) => {+ history.push(graph);+ publish(projectGraphReducer(graph, action));+ },+ getSnapshot: () => graph,+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ undo: () => {+ const previous = history.pop();+ if (previous) {+ publish(previous);+ }+ },+ };+ };+ type GraphStore = ReturnType<typeof createGraphStore>;++ const fieldValue = (store: GraphStore, name: string) => {+ const node = store.getSnapshot().nodes.find((candidate) => candidate.id === entryNode.id);+ return node?.type === 'invocation' ? node.data.inputs[name]?.value : undefined;+ };++ /**+ * Mirrors WorkflowEditorView: the flow model is rebuilt from the graph in a transition after an effect, so a+ * committed value echoes back to the node a beat after the keystroke that produced it. xyflow's node changes+ * (measured sizes) are applied as the editor does; a rebuilt node without them is hidden until remeasured and+ * drops the next keystroke.+ */+ const DeferredFlow = ({ store }: { store: GraphStore }) => {+ const graph = useSyncExternalStore(store.subscribe, store.getSnapshot);+ const [flowNodes, setFlowNodes] = useState(() => toFlowNodes(graph, [], entryTemplates));+ const onNodesChange = useCallback(+ (changes: NodeChange<(typeof flowNodes)[number]>[]) =>+ setFlowNodes((current) => applyNodeChanges(changes, current)),+ []+ );++ useEffect(() => {+ startTransition(() => {+ setFlowNodes((current) => toFlowNodes(graph, current, entryTemplates));+ });+ }, [graph]);++ return <ReactFlow edges={[]} nodes={flowNodes} nodeTypes={nodeTypes} onNodesChange={onNodesChange} />;+ };++ const renderEntryNode = async () => {+ const store = createGraphStore({ ...createProjectGraph('entry-test'), nodes: [entryNode] });+ const adapter = {+ ...createAdapter({ get: () => null, subscribe: () => () => {} }),+ commands: {+ bindLibraryWorkflow: vi.fn(),+ editGraph: store.editGraph,+ redo: vi.fn(),+ replace: vi.fn(),+ undo: store.undo,+ },+ getProjectGraph: store.getSnapshot,+ project: {+ getSnapshot: () => ({ ...projectSnapshot, projectGraph: store.getSnapshot() }),+ subscribe: store.subscribe,+ },+ } as unknown as WorkflowUiAdapter;++ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={adapter}>+ <DeferredFlow store={store} />+ </WorkflowUiProvider>+ </ChakraProvider>+ )+ );++ const field = (label: string) =>+ host.querySelector<HTMLInputElement>(`.react-flow__node input[aria-label="${label}"]`)!;++ return { field, store };+ };+ const focusAtEnd = (input: HTMLInputElement) =>+ act(async () => {+ await userEvent.click(input);+ await userEvent.keyboard('{End}');+ });+ const keys = (sequence: string) =>+ act(async () => {+ await userEvent.keyboard(sequence);+ });+ /** Lets the deferred flow-model rebuild land so the assertion sees the echoed value, not just the draft. */+ const settle = () =>+ act(async () => {+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 0);+ });+ });+ const rowError = (input: HTMLInputElement) =>+ input.closest('[data-scope="field"][data-part="root"]')?.querySelector('[data-part="error-text"]')?.textContent ??+ null;++ it('keeps focus and caret in a text field while the deferred flow model catches up', async () => {+ const { field, store } = await renderEntryNode();+ const prompt = field('Prompt');++ await focusAtEnd(prompt);+ await keys('{Home}{ArrowRight}{ArrowRight}XYZ');+ expect(prompt.value).toBe('heXYZllo world');+ expect([prompt.selectionStart, prompt.selectionEnd]).toEqual([5, 5]);++ await settle();+ expect(document.activeElement).toBe(prompt);+ expect(field('Prompt')).toBe(prompt);+ expect(prompt.value).toBe('heXYZllo world');+ expect([prompt.selectionStart, prompt.selectionEnd]).toEqual([5, 5]);+ expect(fieldValue(store, 'prompt')).toBe('heXYZllo world');++ await keys('{Shift>}{End}{/Shift}there');+ expect(prompt.value).toBe('heXYZthere');+ expect([prompt.selectionStart, prompt.selectionEnd]).toEqual([10, 10]);+ await keys('{Control>}a{/Control}{Backspace}');+ await settle();+ expect(prompt.value).toBe('');+ expect(fieldValue(store, 'prompt')).toBe('');+ expect(document.activeElement).toBe(prompt);+ expect(rowError(prompt)).toBeNull();++ // Undo from elsewhere (a toolbar button has focus) restores the text without pulling focus into a field.+ const weight = field('Weight');+ await act(async () => {+ await userEvent.click(host);+ });+ await act(() => store.undo());+ await settle();+ expect(prompt.value).toBe('heXYZthere');+ expect(document.activeElement).not.toBe(prompt);+ expect(document.activeElement).not.toBe(weight);+ });++ it('edits a float field in place and reports drafts, clears, and a leading minus through the graph', async () => {+ const { field, store } = await renderEntryNode();+ const weight = field('Weight');++ await focusAtEnd(weight);+ await keys('{Home}2');+ expect(weight.value).toBe('20.5');+ await settle();+ await keys('3');+ expect(weight.value).toBe('230.5');+ expect(fieldValue(store, 'weight')).toBe(230.5);+ expect(document.activeElement).toBe(weight);++ await keys('{Control>}a{/Control}0.60');+ await settle();+ expect(weight.value).toBe('0.60');+ expect(fieldValue(store, 'weight')).toBe(0.6);++ await keys('{Control>}a{/Control}2');+ await settle();+ expect(weight.value).toBe('2');+ expect(fieldValue(store, 'weight')).toBe(2);++ await keys('{Backspace}');+ await settle();+ expect(weight.value).toBe('');+ expect(fieldValue(store, 'weight')).toBeUndefined();+ expect(document.activeElement).toBe(weight);+ expect(rowError(weight)).toBe('Required value.');++ await keys('7{Home}-');+ await settle();+ expect(weight.value).toBe('-7');+ expect(fieldValue(store, 'weight')).toBe(-7);+ expect(rowError(weight)).toBeNull();++ await keys('{Home}{Delete}');+ await settle();+ expect(weight.value).toBe('7');+ expect(fieldValue(store, 'weight')).toBe(7);++ await act(() => weight.blur());+ await settle();+ expect(weight.value).toBe('7');+ });++ it('keeps a fractional integer visible and flagged until it is corrected', async () => {+ const { field, store } = await renderEntryNode();+ const steps = field('Steps');++ await focusAtEnd(steps);+ await keys('.5');+ await settle();+ expect(steps.value).toBe('20.5');+ expect(fieldValue(store, 'steps')).toBe(20.5);+ expect(steps.getAttribute('aria-invalid')).toBe('true');+ expect(rowError(steps)).toBe('Invalid value.');++ await keys('{Backspace}{Backspace}');+ await settle();+ expect(steps.value).toBe('20');+ expect(fieldValue(store, 'steps')).toBe(20);+ expect(steps.getAttribute('aria-invalid')).toBeNull();+ expect(rowError(steps)).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsxindex 4263863354..cfc906f6ba 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx@@ -1,5 +1,5 @@import type * as DndKitCoreModule from '@dnd-kit/core';-import type { ProjectGraphState } from '@features/workflow/contracts';+import type { InvocationTemplate, ProjectGraphState, WorkflowInvocationNode } from '@features/workflow/contracts';import type { WorkflowUiAdapter } from '@features/workflow/react';import type { ProjectGraphAction } from '@features/workflow/utility';@@ -15,6 +15,7 @@ import { userEvent } from 'vitest/browser';import { formEdgeDroppableId } from './formBuilderDnd';import { FormBuilderTab } from './FormBuilderTab';+import { LinearFormView } from './LinearFormView';import { PanelModeToggle } from './WorkflowLinearPanel';(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -27,6 +28,61 @@ vi.mock('@dnd-kit/core', async (importOriginal) => {return { ...actual, useDroppable: vi.fn(actual.useDroppable) };});+const entryInput = (+ name: string,+ title: string,+ typeName: string,+ required = true+): InvocationTemplate['inputs'][string] => ({+ default: undefined,+ description: '',+ exclusiveMaximum: null,+ exclusiveMinimum: null,+ fieldKind: 'input',+ input: 'any',+ maximum: null,+ minimum: null,+ multipleOf: null,+ name,+ options: null,+ required,+ title,+ type: { batch: false, cardinality: 'SINGLE', name: typeName },+ uiChoiceLabels: null,+ uiComponent: null,+ uiHidden: false,+ uiModelBase: null,+ uiModelFormat: null,+ uiModelType: null,+ uiOrder: null,+});+const entryTemplate: InvocationTemplate = {+ category: 'test',+ classification: 'stable',+ description: '',+ inputs: {+ prompt: entryInput('prompt', 'Prompt', 'StringField'),+ scale: entryInput('scale', 'Scale', 'FloatField', false),+ steps: entryInput('steps', 'Steps', 'IntegerField'),+ weight: entryInput('weight', 'Weight', 'FloatField'),+ },+ nodePack: 'invokeai',+ outputType: 'test',+ outputs: {},+ tags: [],+ title: 'Entry',+ type: 'entry',+ useCache: true,+ version: '1.0.0',+};++// File-wide: every describe sees only the `entry` template as loaded; the builder fixtures expose no node fields.+vi.mock('@features/workflow/react', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useInvocationTemplatesSelector: (selector: (snapshot: unknown) => unknown) =>+ selector({ error: null, status: 'loaded', templates: { entry: entryTemplate } }),+}));+describe('Workflow Linear panel mode toggle', () => {let host: HTMLDivElement;let root: Root;@@ -365,3 +421,174 @@ describe('Form builder drag and drop (dnd-kit)', () => {await interact(() => pointer('pointerup', handle.ownerDocument, midX, midY + 3));});});++describe('Linear form field entry', () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ host = document.createElement('div');+ host.style.width = '320px';+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ const entryNode: WorkflowInvocationNode = {+ data: {+ inputs: {+ prompt: { label: '', name: 'prompt', value: 'hello world' },+ scale: { label: '', name: 'scale', value: 1.5 },+ steps: { label: '', name: 'steps', value: 20 },+ weight: { label: '', name: 'weight', value: 0.5 },+ },+ isIntermediate: true,+ isOpen: true,+ label: '',+ nodePack: 'invokeai',+ notes: '',+ type: 'entry',+ useCache: true,+ version: '1.0.0',+ },+ id: 'entry-node',+ position: { x: 0, y: 0 },+ type: 'invocation',+ };++ /** The entry node with every field exposed on the form. */+ const buildGraph = (): ProjectGraphState => {+ let doc = projectGraphReducer(createProjectGraph('linear-entry-test'), { node: entryNode, type: 'addNode' });++ for (const fieldName of Object.keys(entryTemplate.inputs)) {+ doc = projectGraphReducer(doc, { fieldIdentifier: { fieldName, nodeId: entryNode.id }, type: 'exposeField' });+ }++ return doc;+ };++ const renderForm = async () => {+ let latest = buildGraph();+ const Harness = () => {+ const [projectGraph, setProjectGraph] = useState(latest);+ const editGraph = useCallback((action: ProjectGraphAction) => {+ setProjectGraph((current) => {+ latest = projectGraphReducer(current, action);+ return latest;+ });+ }, []);+ const adapter = useMemo(+ () =>+ ({+ commands: { bindLibraryWorkflow: vi.fn(), editGraph, redo: vi.fn(), replace: vi.fn(), undo: vi.fn() },+ widgets: { open: vi.fn(), patchValues: vi.fn() },+ }) as unknown as WorkflowUiAdapter,+ [editGraph]+ );++ return (+ <WorkflowUiProvider adapter={adapter}>+ <LinearFormView projectGraph={projectGraph} />+ </WorkflowUiProvider>+ );+ };++ await act(() => {+ root.render(+ <ChakraProvider value={system}>+ <Harness />+ </ChakraProvider>+ );+ });++ const field = (label: string) => host.querySelector<HTMLInputElement>(`input[aria-label="${label}"]`)!;+ const value = (name: string) => {+ const node = latest.nodes.find((candidate) => candidate.id === entryNode.id);+ return node?.type === 'invocation' ? node.data.inputs[name]?.value : undefined;+ };+ const error = (input: HTMLInputElement) =>+ input.closest('[data-scope="field"][data-part="root"]')?.querySelector('[data-part="error-text"]')?.textContent ??+ null;++ return { error, field, value };+ };+ const focusAtEnd = (input: HTMLInputElement) =>+ act(async () => {+ await userEvent.click(input);+ await userEvent.keyboard('{End}');+ });+ const keys = (sequence: string) =>+ act(async () => {+ await userEvent.keyboard(sequence);+ });++ it('keeps the caret while editing an exposed text field through the project graph', async () => {+ const { error, field, value } = await renderForm();+ const prompt = field('Prompt');++ await focusAtEnd(prompt);+ await keys('{Home}{ArrowRight}{ArrowRight}XYZ');+ expect(prompt.value).toBe('heXYZllo world');+ expect([prompt.selectionStart, prompt.selectionEnd]).toEqual([5, 5]);+ expect(value('prompt')).toBe('heXYZllo world');+ expect(field('Prompt')).toBe(prompt);++ await keys('{Control>}a{/Control}{Backspace}');+ expect(prompt.value).toBe('');+ expect(value('prompt')).toBe('');+ expect(document.activeElement).toBe(prompt);+ expect(error(prompt)).toBeNull();+ });++ it('commits numeric drafts as typed and reports required, invalid, and optional-empty states', async () => {+ const { error, field, value } = await renderForm();+ const weight = field('Weight');++ await focusAtEnd(weight);+ await keys('0');+ expect(weight.value).toBe('0.50');+ expect(value('weight')).toBe(0.5);+ await act(() => weight.blur());+ expect(weight.value).toBe('0.5');++ await focusAtEnd(weight);+ await keys('{Control>}a{/Control}{Backspace}');+ expect(weight.value).toBe('');+ expect(value('weight')).toBeUndefined();+ expect(document.activeElement).toBe(weight);+ expect(error(weight)).toBe('Required value.');++ await keys('-');+ await keys('2');+ expect(weight.value).toBe('-2');+ expect(value('weight')).toBe(-2);+ expect(error(weight)).toBeNull();++ const steps = field('Steps');++ await focusAtEnd(steps);+ await keys('.5');+ expect(steps.value).toBe('20.5');+ expect(value('steps')).toBe(20.5);+ expect(steps.getAttribute('aria-invalid')).toBe('true');+ expect(error(steps)).toBe('Invalid value.');+ await keys('{Backspace}{Backspace}');+ expect(value('steps')).toBe(20);+ expect(error(steps)).toBeNull();++ const scale = field('Scale');++ await focusAtEnd(scale);+ await keys('{Control>}a{/Control}{Delete}');+ expect(scale.value).toBe('');+ expect(value('scale')).toBeUndefined();+ expect(error(scale)).toBeNull();+ await act(() => scale.blur());+ expect(scale.value).toBe('');+ expect(scale.getAttribute('aria-invalid')).toBeNull();+ });+});