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
feat(workflow): show a node's latest run in the inspector's Outputs tab
Josh Corbettc0a9c883268b
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 3289e56b30..d81271de0c 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2970,7 +2970,15 @@"panelContent": "Workflow panel content","panelMode": "Workflow panel mode","resizeNodeInspector": "Resize node inspector",- "runOutputsNotRecorded": "Run outputs are not recorded per node yet; results currently route to the Gallery or Canvas. This tab will show the node's outputs from its most recent run once run records land.",+ "latestOutput": "Latest output",+ "noRunRecorded": "This node has not run in this session.",+ "outputImage": "Output image",+ "runStatus": {+ "completed": "Completed",+ "failed": "Failed",+ "running": "Running…"+ },+ "status": "Status","newWorkflowWithEllipsis": "New workflow…","saveToLibrary": "Save to library","selectNodeToInspect": "Select a node in the Workflow editor to inspect it.",diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.browser.test.tsxnew file mode 100644index 0000000000..bb20b9bbbf--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.browser.test.tsx@@ -0,0 +1,196 @@+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 { ChakraProvider } from '@chakra-ui/react';+import { workflowSelectionStore } from '@features/workflow/ui/editor/selectionStore';+import { WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';+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 { NodeInspector } from './NodeInspector';++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const template: InvocationTemplate = {+ category: 'test',+ classification: 'stable',+ description: '',+ inputs: {},+ nodePack: 'invokeai',+ outputType: 'test',+ outputs: {+ height: {+ description: '',+ name: 'height',+ title: 'Height',+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },+ },+ width: {+ description: '',+ name: 'width',+ title: 'Width',+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },+ },+ },+ tags: [],+ title: 'Resize',+ type: 'resize',+ useCache: true,+ version: '1.0.0',+};++vi.mock('@features/workflow/react', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useInvocationTemplatesSelector: (selector: (snapshot: unknown) => unknown) =>+ selector({ error: null, status: 'loaded', templates: { resize: template } }),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) =>+ ({+ 'widgets.workflow.inspectorTabs.outputs': 'Outputs',+ 'widgets.workflow.latestOutput': 'Latest output',+ 'widgets.workflow.noRunRecorded': 'This node has not run in this session.',+ 'widgets.workflow.runStatus.completed': 'Completed',+ 'widgets.workflow.runStatus.failed': 'Failed',+ 'widgets.workflow.status': 'Status',+ })[key] ?? key,+ }),+}));++const node: WorkflowInvocationNode = {+ data: {+ inputs: {},+ isIntermediate: true,+ isOpen: true,+ label: '',+ nodePack: 'invokeai',+ notes: '',+ type: 'resize',+ useCache: true,+ version: '1.0.0',+ },+ id: 'node-1',+ position: { x: 0, y: 0 },+ type: 'invocation',+};+const projectGraph: ProjectGraphState = { ...createProjectGraph('inspector-test'), nodes: [node] };+const projectSnapshot = {+ galleryValues: {},+ id: 'project-1',+ isWorkflowRunning: false,+ projectGraph,+ workflowValues: { inspectorTab: 'outputs' },+};++/** A node-execution port the test can advance between renders. */+const createExecutionPort = () => {+ const listeners = new Set<() => void>();+ let state: WorkflowNodeExecutionState | null = null;++ return {+ port: {+ get: (nodeId: string) => (nodeId === node.id ? state : null),+ subscribe: (_nodeId: string, listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ set(next: WorkflowNodeExecutionState | null) {+ state = next;+ listeners.forEach((listener) => listener());+ },+ };+};++const createAdapter = (nodeExecution: WorkflowUiAdapter['nodeExecution']): WorkflowUiAdapter =>+ ({+ capabilities: { getSnapshot: () => ({ canUseCache: true }), subscribe: () => () => {} },+ commands: { bindLibraryWorkflow: vi.fn(), editGraph: vi.fn(), redo: vi.fn(), replace: vi.fn(), undo: vi.fn() },+ getProjectGraph: () => projectGraph,+ nodeExecution,+ notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },+ openAddModels: vi.fn(),+ performance: {+ mark: vi.fn(),+ measure: vi.fn(),+ time: <T,>(_name: string, _source: unknown, callback: () => T) => callback(),+ },+ preferences: { getSnapshot: () => ({}), subscribe: () => () => {} },+ project: { getSnapshot: () => projectSnapshot, subscribe: () => () => {} },+ registerModalHotkeyLayer: vi.fn(() => vi.fn()),+ widgets: { open: vi.fn(), patchValues: vi.fn() },+ }) as unknown as WorkflowUiAdapter;++describe('NodeInspector outputs tab', () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ workflowSelectionStore.patchSnapshot({ hoveredNodeId: null, selectedNodeIds: [node.id], selectionRequest: null });+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ it('shows the latest run: status, each declared output value, the saved image, and the raw result', async () => {+ const execution = createExecutionPort();++ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={createAdapter(execution.port)}>+ <NodeInspector projectGraph={projectGraph} />+ </WorkflowUiProvider>+ </ChakraProvider>+ )+ );++ expect(host.textContent).toContain('This node has not run in this session.');+ expect(host.textContent).toContain('IntegerField');++ await act(() =>+ execution.set({+ error: null,+ latestOutput: { height: 768, type: 'image_output', width: 1024 },+ outputImageUrl: 'data:image/png;base64,',+ progress: null,+ progressMessage: null,+ status: 'completed',+ })+ );++ expect(host.textContent).not.toContain('This node has not run in this session.');+ expect(host.textContent).toContain('Completed');+ expect(host.textContent).toContain('1024');+ expect(host.textContent).toContain('768');+ expect(host.querySelector('img')?.getAttribute('src')).toBe('data:image/png;base64,');+ expect(host.querySelector('[aria-label="Latest output"]')?.textContent).toContain('"type": "image_output"');++ // The store carries the previous run's result through a failure; the tab must not pass it off as this run's.+ await act(() =>+ execution.set({+ error: 'Out of memory',+ latestOutput: { height: 768, type: 'image_output', width: 1024 },+ outputImageUrl: 'data:image/png;base64,',+ progress: null,+ progressMessage: null,+ status: 'failed',+ })+ );++ expect(host.textContent).toContain('Failed — Out of memory');+ expect(host.textContent).not.toContain('1024');+ expect(host.querySelector('img')).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsxindex d233b301b2..d2478d3731 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.tsx@@ -6,11 +6,16 @@ import type {} from '@features/workflow/contracts';import type { ChangeEvent } from 'react';-import { Flex, HStack, Stack, Text, Textarea } from '@chakra-ui/react';+import { Flex, HStack, Image, Stack, Text, Textarea } from '@chakra-ui/react';import { useInvocationTemplatesSelector } from '@features/workflow/react';import { workflowSelectionStore } from '@features/workflow/ui/editor/selectionStore';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';-import { useWorkflowHostCommands, useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';+import {+ useWorkflowHostCommands,+ useWorkflowNodeExecutionState,+ useWorkflowProjectSelector,+} from '@features/workflow/ui/WorkflowUiContext';+import { formatOutputFieldValue } from '@features/workflow/utility';import { JsonPreview, Scrollable, Tabs } from '@platform/ui';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -77,23 +82,73 @@ const DetailsTab = ({ node, template }: { node: WorkflowInvocationNode; template);};-const OutputsTab = ({ template }: { template: InvocationTemplate | undefined }) => {+/**+ * What the node produced the last time it ran in this session: each declared+ * output's value from the latest result, the image it saved (if any), and the+ * raw result for anything the summary does not show.+ */+const OutputsTab = ({ nodeId, template }: { nodeId: string; template: InvocationTemplate | undefined }) => {const { t } = useTranslation();+ const execution = useWorkflowNodeExecutionState(nodeId);+ const outputs = template ? Object.values(template.outputs) : [];++ if (!execution) {+ return (+ <Stack gap="2">+ <Text color="fg.subtle" fontSize="2xs">+ {t('widgets.workflow.noRunRecorded')}+ </Text>+ {outputs.length > 0 ? (+ <Stack gap="1">+ <Text color="fg.subtle" fontSize="2xs">+ {t('widgets.workflow.declaredOutputs')}+ </Text>+ {outputs.map((output) => (+ <DetailRow key={output.name} label={output.title} value={output.type.name} />+ ))}+ </Stack>+ ) : null}+ </Stack>+ );+ }++ // The store keeps the previous run's result while a node runs or fails;+ // showing it under a "Running…" or "Failed" line would pass it off as this run's.+ const hasResult =+ execution.status === 'completed' && execution.latestOutput !== null && execution.latestOutput !== undefined;return (<Stack gap="2">- <Text color="fg.subtle" fontSize="2xs">- {t('widgets.workflow.runOutputsNotRecorded')}- </Text>- {template ? (- <Stack gap="1">- <Text color="fg.subtle" fontSize="2xs">- {t('widgets.workflow.declaredOutputs')}- </Text>- {Object.values(template.outputs).map((output) => (- <DetailRow key={output.name} label={output.title} value={output.type.name} />+ <DetailRow+ label={t('widgets.workflow.status')}+ value={+ execution.status === 'failed' && execution.error+ ? `${t('widgets.workflow.runStatus.failed')} — ${execution.error}`+ : t(`widgets.workflow.runStatus.${execution.status}`)+ }+ />+ {execution.status === 'completed' && execution.outputImageUrl ? (+ <Image+ alt={t('widgets.workflow.outputImage')}+ bg="bg.muted"+ h="10rem"+ objectFit="contain"+ rounded="sm"+ src={execution.outputImageUrl}+ w="full"+ />+ ) : null}+ {hasResult ? (+ <>+ {outputs.map((output) => (+ <DetailRow+ key={output.name}+ label={output.title}+ value={formatOutputFieldValue(execution.latestOutput, output.name)?.full ?? '—'}+ />))}- </Stack>+ <JsonBlock label={t('widgets.workflow.latestOutput')} value={execution.latestOutput} />+ </>) : null}</Stack>);@@ -124,7 +179,7 @@ const InspectorBody = ({ node, tab }: { node: WorkflowNode; tab: InspectorTab })case 'details':return <DetailsTab node={node} template={template} />;case 'outputs':- return <OutputsTab template={template} />;+ return <OutputsTab nodeId={node.id} template={template} />;case 'data':return <JsonBlock label={t('widgets.workflow.nodeData')} value={node.data} />;case 'template':