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.

feat(webv2): show node execution outcomes and settle fast runs

Josh Corbettcca8e9dff5c2
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 20a39f1118..4c59d3d7d3 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1439,6 +1439,8 @@
"forLoopLinkageInvalid": "Loop linkage must connect a For to its ForReturn",
"forLoopLinkageDuplicate": "A For and ForReturn can each belong to only one loop",
"forReturnOwnership": "Each ForReturn must belong to exactly one For",
+ "executionCompleted": "Completed",
+ "executionFailed": "Failed",
"forLoopBodyBoundary": "For loop body",
"forLoopBodyBoundaryStatus": {
"missing_linkage": "missing loop linkage",
diff --git a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.test.ts b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.test.ts
index c2b33d3d3f..5e3d47e26f 100644
--- a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.test.ts
+++ b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.test.ts
@@ -26,19 +26,35 @@ describe('node execution lifecycle', () => {
expect(nodeExecutionStore.get('node-1')).toEqual({
error: 'Out of memory',
outputImageUrl: 'https://api.test/api/v1/images/i/result%20image.png/thumbnail',
+ latestOutput: { image: { image_name: 'result image.png' } },
progress: null,
progressMessage: null,
status: 'failed',
});
});
- it('settles every running node without disturbing terminal state', () => {
+ it('keeps only the most recent result of a run', () => {
+ nodeExecutionStore.started({ invocation_source_id: 'node-1' });
+ nodeExecutionStore.completed({ invocation_source_id: 'node-1', result: { type: 'integer_output', value: 1 } });
+ nodeExecutionStore.started({ invocation_source_id: 'node-1' });
+ nodeExecutionStore.completed({ invocation_source_id: 'node-1', result: { type: 'integer_output', value: 2 } });
+
+ expect(nodeExecutionStore.get('node-1')?.latestOutput).toEqual({ type: 'integer_output', value: 2 });
+ });
+
+ it('settles the named running nodes to the run outcome without disturbing terminal or other nodes', () => {
nodeExecutionStore.started({ invocation_source_id: 'running' });
+ nodeExecutionStore.started({ invocation_source_id: 'other-run' });
nodeExecutionStore.failed({ error_message: 'failed', invocation_source_id: 'terminal' });
- nodeExecutionStore.settleRunning();
+ nodeExecutionStore.settleRunning(['running', 'terminal'], 'completed');
expect(nodeExecutionStore.get('running')?.status).toBe('completed');
expect(nodeExecutionStore.get('terminal')?.status).toBe('failed');
+ expect(nodeExecutionStore.get('other-run')?.status).toBe('running');
+
+ nodeExecutionStore.settleRunning(['other-run'], 'canceled');
+
+ expect(nodeExecutionStore.get('other-run')).toBeNull();
});
});
diff --git a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts
index 513279a79f..c41f036f2e 100644
--- a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts
+++ b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts
@@ -19,6 +19,9 @@ import { browserNodesDataPort } from './transport';
export type NodeExecutionStatus = 'running' | 'completed' | 'failed';
+/** How the queue item that was running these nodes ended. */
+export type NodeExecutionOutcome = 'completed' | 'failed' | 'canceled';
+
export interface NodeExecutionState {
status: NodeExecutionStatus;
/** 0..1, or null while indeterminate. Only meaningful while running. */
@@ -26,6 +29,8 @@ export interface NodeExecutionState {
progressMessage: string | null;
/** Thumbnail of the node's most recent image output, when it produced one. */
outputImageUrl: string | null;
+ /** The node's most recent invocation result in the current run (a loop body runs many times). */
+ latestOutput: unknown;
error: string | null;
}
@@ -57,6 +62,7 @@ export const nodeExecutionStore = {
outputImageUrl: imageName
? browserNodesDataPort.buildUrl(`/api/v1/images/i/${encodeURIComponent(imageName)}/thumbnail`)
: (previous?.outputImageUrl ?? null),
+ latestOutput: event.result,
progress: null,
progressMessage: null,
status: 'completed',
@@ -68,6 +74,7 @@ export const nodeExecutionStore = {
stateByNodeId.set(event.invocation_source_id, {
error: event.error_message,
outputImageUrl: previous?.outputImageUrl ?? null,
+ latestOutput: previous?.latestOutput ?? null,
progress: null,
progressMessage: null,
status: 'failed',
@@ -79,16 +86,28 @@ export const nodeExecutionStore = {
stateByNodeId.set(nodeId, {
error: null,
outputImageUrl: previous?.outputImageUrl ?? null,
+ latestOutput: previous?.latestOutput ?? null,
progress: percentage,
progressMessage: message,
status: 'running',
});
},
- /** A queue item reached a terminal state: nothing can still be running. */
- settleRunning(): void {
- for (const [nodeId, state] of stateByNodeId.entries()) {
- if (state.status === 'running') {
+ /**
+ * The queue item running these nodes reached a terminal state: a node still marked running
+ * finished with it, or never will (its failure/cancel event was lost or never sent).
+ */
+ settleRunning(nodeIds: Iterable<string>, outcome: NodeExecutionOutcome): void {
+ for (const nodeId of nodeIds) {
+ const state = stateByNodeId.get(nodeId);
+
+ if (state?.status !== 'running') {
+ continue;
+ }
+
+ if (outcome === 'completed') {
stateByNodeId.set(nodeId, { ...state, progress: null, progressMessage: null, status: 'completed' });
+ } else {
+ stateByNodeId.delete(nodeId);
}
}
},
@@ -98,6 +117,7 @@ export const nodeExecutionStore = {
stateByNodeId.set(event.invocation_source_id, {
error: null,
outputImageUrl: previous?.outputImageUrl ?? null,
+ latestOutput: previous?.latestOutput ?? null,
progress: null,
progressMessage: null,
status: 'running',
@@ -111,7 +131,7 @@ export interface NodeExecutionSink {
failed(event: NodeInvocationErrorEvent): void;
get(nodeId: string): NodeExecutionState | null;
progress(nodeId: string, percentage: number | null, message: string): void;
- settleRunning(): void;
+ settleRunning(nodeIds: Iterable<string>, outcome: NodeExecutionOutcome): void;
started(event: NodeInvocationStartedEvent): void;
subscribe(nodeId: string, listener: () => void): () => void;
}
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
index aff938a1a0..e14911e021 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
@@ -2,6 +2,7 @@ import type {
QueueBackendItem,
QueueEnqueueResult,
QueueEnqueueGenerateRequest,
+ QueueEnqueueWorkflowRequest,
QueueItemProgress,
QueueProgressPreviewPayload,
QueueResultImage,
@@ -175,6 +176,14 @@ const generateRequest: QueueEnqueueGenerateRequest = {
sourceQueueItemId: 'local-1',
};
+const workflowRequest: QueueEnqueueWorkflowRequest = {
+ batchCount: 1,
+ destination: 'gallery',
+ graph: { edges: [], id: 'graph-1', nodes: {} },
+ projectId: 'project-1',
+ sourceQueueItemId: 'local-1',
+};
+
interface Harness {
activeProgressTarget: {
clear: ReturnType<typeof vi.fn>;
@@ -939,6 +948,135 @@ describe('queueCoordinator', () => {
expect(harness.modelLoads.reset).toHaveBeenCalled();
});
+ it('replays node events that landed before the enqueue response and settles the nodes', async () => {
+ const acceptance = deferred<QueueEnqueueResult>();
+
+ harness.api.enqueueWorkflow.mockReturnValue(acceptance.promise);
+ harness.coordinator.connect();
+ const submission = harness.coordinator.submitWorkflow('local-1', workflowRequest);
+
+ harness.socket.fire('invocation_started', { ...createStatusEvent({ item_id: 1 }), invocation_source_id: 'node-1' });
+ harness.socket.fire('invocation_complete', {
+ ...createStatusEvent({ item_id: 1 }),
+ invocation_source_id: 'node-1',
+ result: { type: 'integer_output', value: 7 },
+ });
+ harness.socket.fire('invocation_started', { ...createStatusEvent({ item_id: 1 }), invocation_source_id: 'node-2' });
+ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 1, status: 'completed' }));
+
+ expect(harness.nodeExecution.started).not.toHaveBeenCalled();
+
+ acceptance.resolve({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 });
+ await submission;
+
+ expect(harness.nodeExecution.started.mock.calls.map(([event]) => event.invocation_source_id)).toEqual([
+ 'node-1',
+ 'node-2',
+ ]);
+ expect(harness.nodeExecution.completed).toHaveBeenCalledTimes(1);
+ expect(harness.nodeExecution.settleRunning).toHaveBeenCalledWith(new Set(['node-1', 'node-2']), 'completed');
+ await expect(harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z')).resolves.toHaveLength(1);
+ });
+
+ it('does not buffer node events while no enqueue request is in flight', async () => {
+ harness.api.enqueueWorkflow.mockResolvedValueOnce({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 });
+ harness.coordinator.connect();
+ harness.socket.fire('invocation_started', { ...createStatusEvent({ item_id: 1 }), invocation_source_id: 'node-1' });
+
+ await harness.coordinator.submitWorkflow('local-1', workflowRequest);
+
+ expect(harness.nodeExecution.started).not.toHaveBeenCalled();
+ });
+
+ it('follows whichever item runs live, even a lower id after a higher one', async () => {
+ harness.api.enqueueWorkflow
+ .mockResolvedValueOnce({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 })
+ .mockResolvedValueOnce({ batchId: 'batch-2', enqueued: 1, itemIds: [2], requested: 1 });
+ harness.coordinator.connect();
+ await harness.coordinator.submitWorkflow('local-1', workflowRequest);
+ await harness.coordinator.submitWorkflow('local-2', { ...workflowRequest, sourceQueueItemId: 'local-2' });
+
+ // Model affinity ran item 2 first.
+ harness.socket.fire('invocation_started', { ...createStatusEvent({ item_id: 2 }), invocation_source_id: 'node-1' });
+ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 2, status: 'completed' }));
+ harness.nodeExecution.clearAll.mockClear();
+ harness.socket.fire('invocation_started', { ...createStatusEvent({ item_id: 1 }), invocation_source_id: 'node-1' });
+ harness.socket.fire('invocation_complete', {
+ ...createStatusEvent({ item_id: 1 }),
+ invocation_source_id: 'node-1',
+ result: { type: 'integer_output', value: 1 },
+ });
+ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 1, status: 'completed' }));
+
+ expect(harness.nodeExecution.clearAll).toHaveBeenCalledTimes(1);
+ expect(harness.nodeExecution.completed).toHaveBeenCalledTimes(1);
+ expect(harness.nodeExecution.settleRunning).toHaveBeenLastCalledWith(new Set(['node-1']), 'completed');
+ });
+
+ it('skips replayed events and a late settle from an item another item has since taken over', async () => {
+ const acceptance = deferred<QueueEnqueueResult>();
+
+ harness.api.enqueueWorkflow
+ .mockReturnValueOnce(acceptance.promise)
+ .mockResolvedValueOnce({ batchId: 'batch-2', enqueued: 1, itemIds: [2], requested: 1 });
+ harness.coordinator.connect();
+ const submission = harness.coordinator.submitWorkflow('local-1', workflowRequest);
+
+ // Item 1 ran while its enqueue response was still in flight; those events are buffered.
+ harness.socket.fire('invocation_started', { ...createStatusEvent({ item_id: 1 }), invocation_source_id: 'node-1' });
+ harness.socket.fire('invocation_complete', {
+ ...createStatusEvent({ item_id: 1 }),
+ invocation_source_id: 'node-1',
+ result: { type: 'integer_output', value: 1 },
+ });
+ await harness.coordinator.submitWorkflow('local-2', { ...workflowRequest, sourceQueueItemId: 'local-2' });
+ harness.socket.fire('invocation_started', { ...createStatusEvent({ item_id: 2 }), invocation_source_id: 'node-1' });
+ harness.nodeExecution.clearAll.mockClear();
+
+ acceptance.resolve({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 });
+ await submission;
+ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 1, status: 'completed' }));
+
+ expect(harness.nodeExecution.clearAll).not.toHaveBeenCalled();
+ expect(harness.nodeExecution.completed).not.toHaveBeenCalled();
+ expect(harness.nodeExecution.settleRunning).not.toHaveBeenCalled();
+
+ harness.socket.fire('queue_item_status_changed', createStatusEvent({ item_id: 2, status: 'completed' }));
+ expect(harness.nodeExecution.settleRunning).toHaveBeenLastCalledWith(new Set(['node-1']), 'completed');
+ });
+
+ it('resets node state when a new item starts and settles running nodes to the item outcome', async () => {
+ harness.api.enqueueWorkflow
+ .mockResolvedValueOnce({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 })
+ .mockResolvedValueOnce({ batchId: 'batch-2', enqueued: 1, itemIds: [2], requested: 1 });
+ harness.coordinator.connect();
+ await harness.coordinator.submitWorkflow('local-1', workflowRequest);
+ await harness.coordinator.submitWorkflow('local-2', { ...workflowRequest, sourceQueueItemId: 'local-2' });
+ harness.nodeExecution.clearAll.mockClear();
+
+ harness.socket.fire('invocation_started', { ...createStatusEvent({ item_id: 1 }), invocation_source_id: 'node-1' });
+ expect(harness.nodeExecution.clearAll).toHaveBeenCalledTimes(1);
+ harness.socket.fire('invocation_progress', {
+ ...createStatusEvent({ item_id: 1 }),
+ invocation_source_id: 'node-1',
+ message: 'sampling',
+ percentage: 0.5,
+ });
+ expect(harness.nodeExecution.clearAll).toHaveBeenCalledTimes(1);
+ harness.socket.fire(
+ 'queue_item_status_changed',
+ createStatusEvent({ error_message: 'boom', item_id: 1, status: 'failed' })
+ );
+
+ expect(harness.nodeExecution.settleRunning).toHaveBeenLastCalledWith(new Set(['node-1']), 'failed');
+
+ harness.socket.fire('invocation_started', { ...createStatusEvent({ item_id: 2 }), invocation_source_id: 'node-1' });
+ expect(harness.nodeExecution.clearAll).toHaveBeenCalledTimes(2);
+
+ harness.coordinator.detachRun('local-2');
+ expect(harness.nodeExecution.settleRunning).toHaveBeenLastCalledWith(new Set(['node-1']), 'canceled');
+ });
+
it('ignores untracked queue events before mutating local execution state', () => {
vi.useFakeTimers();
harness = createHarness({ galleryRefreshCoalesceMs: 400 });
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
index 44360203f9..e3ca731b20 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
@@ -38,6 +38,8 @@ import { ApiError } from '@platform/transport/http';
const GALLERY_REFRESH_COALESCE_MS = 400;
const SAFETY_SWEEP_INTERVAL_MS = 30_000;
const TERMINAL_EVENT_BUFFER_LIMIT = 256;
+const NODE_EVENT_BUFFER_ITEM_LIMIT = 64;
+const NODE_EVENT_BUFFER_EVENTS_PER_ITEM = 512;
const BACKEND_READ_CONCURRENCY = 16;
/**
@@ -56,10 +58,19 @@ export interface QueueNodeExecutionPort {
completed(event: InvocationCompleteEvent): void;
failed(event: InvocationErrorEvent): void;
progress(nodeId: string, percentage: number | null, message: string): void;
- settleRunning(): void;
+ settleRunning(nodeIds: Iterable<string>, outcome: 'completed' | 'failed' | 'canceled'): void;
started(event: InvocationStartedEvent): void;
}
+type NodeEvent = (
+ | { kind: 'started'; event: InvocationStartedEvent }
+ | { kind: 'completed'; event: InvocationCompleteEvent }
+ | { kind: 'failed'; event: InvocationErrorEvent }
+) & {
+ /** Receipt order; a replayed event keeps the order it arrived in. */
+ sequence: number;
+};
+
export type QueueCoordinatorBackendPort = Pick<
QueueBackendPort,
| 'cancelQueueItems'
@@ -223,6 +234,20 @@ export const createQueueCoordinator = (
* and the run being registered.
*/
const recentTerminalOutcomes = new Map<number, TerminalOutcome>();
+ /**
+ * Node lifecycle events for items nobody tracks yet, replayed once the item
+ * is registered: a fast run's nodes start and finish while `enqueue_batch`
+ * is still resolving.
+ */
+ const pendingNodeEvents = new Map<number, NodeEvent[]>();
+ /** Nodes each backend item has driven; settled with the item's terminal outcome. */
+ const nodeIdsByBackendItem = new Map<number, Set<string>>();
+ /** The backend item whose node events the execution store currently reflects, and the receipt sequence it took over at. */
+ let nodeExecutionItemId: number | null = null;
+ let nodeExecutionItemSequence = 0;
+ let nodeEventSequence = 0;
+ /** Enqueue requests awaiting a response; node events are only buffered while one is in flight. */
+ let inFlightSubmissions = 0;
const latestStatusSequences = new Map<number, number>();
/**
* Per backend item, the session and revision of the last accepted preview
@@ -312,6 +337,121 @@ export const createQueueCoordinator = (
return { itemIndex: itemIndex === -1 ? 1 : itemIndex + 1, queueItemId: localQueueItemId };
};
+ const settleNodes = (backendItemId: number, outcome: TerminalOutcome['status']): void => {
+ const nodeIds = nodeIdsByBackendItem.get(backendItemId);
+
+ nodeIdsByBackendItem.delete(backendItemId);
+
+ // A late settle for an item the store no longer reflects must not touch the current run's nodes.
+ if (nodeIds && isActive() && nodeExecutionItemId === backendItemId) {
+ nodeExecution.settleRunning(nodeIds, outcome);
+ }
+ };
+
+ /**
+ * The store follows whichever item most recently produced a live event; the backend may run items
+ * in any order, so only a replayed event from before the current item's takeover is a straggler.
+ */
+ const isStaleNodeEvent = (nodeEvent: NodeEvent): boolean =>
+ nodeExecutionItemId !== null &&
+ nodeEvent.event.item_id !== nodeExecutionItemId &&
+ nodeEvent.sequence < nodeExecutionItemSequence;
+
+ const trackNodeForItem = (backendItemId: number, nodeId: string, sequence: number): void => {
+ if (nodeExecutionItemId !== backendItemId) {
+ nodeExecutionItemId = backendItemId;
+ nodeExecutionItemSequence = sequence;
+ nodeExecution.clearAll();
+ }
+
+ const nodeIds = nodeIdsByBackendItem.get(backendItemId);
+
+ if (nodeIds) {
+ nodeIds.add(nodeId);
+ } else {
+ nodeIdsByBackendItem.set(backendItemId, new Set([nodeId]));
+ }
+ };
+
+ const applyNodeEvent = (nodeEvent: NodeEvent): void => {
+ if (isStaleNodeEvent(nodeEvent)) {
+ return;
+ }
+
+ trackNodeForItem(nodeEvent.event.item_id, nodeEvent.event.invocation_source_id, nodeEvent.sequence);
+
+ switch (nodeEvent.kind) {
+ case 'started':
+ nodeExecution.started(nodeEvent.event);
+ return;
+ case 'completed':
+ nodeExecution.completed(nodeEvent.event);
+ return;
+ case 'failed':
+ nodeExecution.failed(nodeEvent.event);
+ return;
+ }
+ };
+
+ const bufferNodeEvent = (nodeEvent: NodeEvent): void => {
+ const itemId = nodeEvent.event.item_id;
+ const events = pendingNodeEvents.get(itemId) ?? [];
+
+ if (events.length >= NODE_EVENT_BUFFER_EVENTS_PER_ITEM) {
+ return;
+ }
+
+ pendingNodeEvents.delete(itemId);
+ pendingNodeEvents.set(itemId, [...events, nodeEvent]);
+
+ while (pendingNodeEvents.size > NODE_EVENT_BUFFER_ITEM_LIMIT) {
+ const oldestId = pendingNodeEvents.keys().next().value;
+
+ if (oldestId === undefined) {
+ break;
+ }
+
+ pendingNodeEvents.delete(oldestId);
+ }
+ };
+
+ const replayNodeEvents = (backendItemId: number): void => {
+ const events = pendingNodeEvents.get(backendItemId);
+
+ pendingNodeEvents.delete(backendItemId);
+
+ for (const nodeEvent of events ?? []) {
+ applyNodeEvent(nodeEvent);
+ }
+ };
+
+ const handleNodeEvent = (nodeEvent: NodeEvent): void => {
+ if (!isActive()) {
+ return;
+ }
+
+ if (isTrackedEvent(nodeEvent.event)) {
+ applyNodeEvent(nodeEvent);
+ } else if (inFlightSubmissions > 0) {
+ bufferNodeEvent(nodeEvent);
+ }
+ };
+
+ /** Runs an enqueue call while buffering node events that may land before its response registers the items. */
+ const withSubmissionInFlight = async <T>(submit: () => Promise<T>): Promise<T> => {
+ inFlightSubmissions += 1;
+
+ try {
+ return await submit();
+ } finally {
+ inFlightSubmissions -= 1;
+
+ if (inFlightSubmissions === 0) {
+ pendingNodeEvents.clear();
+ }
+ }
+ };
+
const settleWait = (backendItemId: number, outcome: TerminalOutcome): void => {
const wait = waits.get(backendItemId);
@@ -322,6 +462,7 @@ export const createQueueCoordinator = (
waits.delete(backendItemId);
latestFrameGates.delete(backendItemId);
+ settleNodes(backendItemId, outcome.status);
const progressTarget = getProgressImageTarget(wait.localQueueItemId, backendItemId);
const releaseProgressSlot = (): void => {
if (isActive()) {
@@ -385,10 +526,12 @@ export const createQueueCoordinator = (
const isTrackedEvent = (event: { item_id: number }): boolean => waits.has(event.item_id);
const trackBackendItem = (localQueueItemId: string, backendItemId: number): Promise<TerminalOutcome> => {
+ replayNodeEvents(backendItemId);
const bufferedOutcome = recentTerminalOutcomes.get(backendItemId);
if (bufferedOutcome) {
recentTerminalOutcomes.delete(backendItemId);
+ settleNodes(backendItemId, bufferedOutcome.status);
return Promise.resolve(bufferedOutcome);
}
@@ -528,7 +671,6 @@ export const createQueueCoordinator = (
return;
}
- nodeExecution.settleRunning();
settleWait(event.item_id, toTerminalOutcome(event.status, event.error_message, event.error_type));
if (event.status === 'completed') {
@@ -587,6 +729,7 @@ export const createQueueCoordinator = (
return;
}
+ trackNodeForItem(event.item_id, event.invocation_source_id, ++nodeEventSequence);
nodeExecution.progress(event.invocation_source_id, event.percentage, event.message);
const target = getProgressImageTarget(wait.localQueueItemId, event.item_id);
@@ -626,6 +769,10 @@ export const createQueueCoordinator = (
progress.clearAll?.();
nodeExecution.clearAll();
+ nodeExecutionItemId = null;
+ nodeExecutionItemSequence = 0;
+ pendingNodeEvents.clear();
+ nodeIdsByBackendItem.clear();
modelLoads.reset();
if (status === 'connected') {
@@ -646,27 +793,15 @@ export const createQueueCoordinator = (
backend.on('queue_item_status_changed', handleStatusChanged),
backend.on('queue_items_canceled', handleItemsCanceled),
backend.on('invocation_progress', handleProgress),
- backend.on('invocation_started', (event: InvocationStartedEvent) => {
- if (!isActive() || !isTrackedEvent(event)) {
- return;
- }
-
- nodeExecution.started(event);
- }),
- backend.on('invocation_complete', (event: InvocationCompleteEvent) => {
- if (!isActive() || !isTrackedEvent(event)) {
- return;
- }
-
- nodeExecution.completed(event);
- }),
- backend.on('invocation_error', (event: InvocationErrorEvent) => {
- if (!isActive() || !isTrackedEvent(event)) {
- return;
- }
-
- nodeExecution.failed(event);
- }),
+ backend.on('invocation_started', (event: InvocationStartedEvent) =>
+ handleNodeEvent({ event, kind: 'started', sequence: ++nodeEventSequence })
+ ),
+ backend.on('invocation_complete', (event: InvocationCompleteEvent) =>
+ handleNodeEvent({ event, kind: 'completed', sequence: ++nodeEventSequence })
+ ),
+ backend.on('invocation_error', (event: InvocationErrorEvent) =>
+ handleNodeEvent({ event, kind: 'failed', sequence: ++nodeEventSequence })
+ ),
backend.on('model_load_started', (payload: never) => {
if (isActive()) {
modelLoads.started(payload);
@@ -874,7 +1009,9 @@ export const createQueueCoordinator = (
throw new QueueItemCancelledError(localQueueItemId);
}
- return adoptEnqueueResult(localQueueItemId, await backend.enqueueGenerate(request), 'generation');
+ return await withSubmissionInFlight(async () =>
+ adoptEnqueueResult(localQueueItemId, await backend.enqueueGenerate(request), 'generation')
+ );
};
const submitWorkflow = async (
@@ -885,7 +1022,9 @@ export const createQueueCoordinator = (
throw new QueueItemCancelledError(localQueueItemId);
}
- return adoptEnqueueResult(localQueueItemId, await backend.enqueueWorkflow(request), 'workflow');
+ return await withSubmissionInFlight(async () =>
+ adoptEnqueueResult(localQueueItemId, await backend.enqueueWorkflow(request), 'workflow')
+ );
};
const waitForResults = async (
@@ -964,6 +1103,7 @@ export const createQueueCoordinator = (
if (wait?.localQueueItemId === localQueueItemId) {
waits.delete(backendItemId);
latestFrameGates.delete(backendItemId);
+ settleNodes(backendItemId, 'canceled');
wait.settle({ status: 'canceled' });
}
}
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/outputFields.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/outputFields.test.ts
index 18f27db9c8..5943bae86c 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/outputFields.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/outputFields.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { getOutputFieldNamesByScope, getOutputFieldRows } from './outputFields';
+import { formatOutputFieldValue, getOutputFieldNamesByScope, getOutputFieldRows } from './outputFields';
describe('output field scopes', () => {
it('groups visible outputs and keeps hidden scheduler outputs out of the node body', () => {
@@ -51,3 +51,25 @@ describe('output field scopes', () => {
]);
});
});
+
+describe('output value formatting', () => {
+ it('formats primitives, named objects, collections, and truncates long strings', () => {
+ expect(formatOutputFieldValue({ type: 'integer_output', value: 7 }, 'value')).toEqual({ full: '7', short: '7' });
+ expect(formatOutputFieldValue({ value: 0.123456 }, 'value')?.short).toBe('0.1235');
+ expect(formatOutputFieldValue({ image: { image_name: 'a.png', width: 1 } }, 'image')?.short).toBe('a.png');
+ expect(formatOutputFieldValue({ latents: { latents_name: 'lat-1' } }, 'latents')?.short).toBe('lat-1');
+ expect(formatOutputFieldValue({ collection: [1, 2, 3] }, 'collection')?.short).toBe('3 items');
+ expect(formatOutputFieldValue({ color: { a: 255, b: 3, g: 2, r: 1 } }, 'color')?.short).toBe('rgba(1, 2, 3, 255)');
+ expect(formatOutputFieldValue({ value: null }, 'value')?.short).toBe('—');
+
+ const long = formatOutputFieldValue({ value: 'x'.repeat(60) }, 'value');
+
+ expect(long?.short).toHaveLength(40);
+ expect(long?.full).toHaveLength(60);
+ });
+
+ it('returns null when the result has no such field', () => {
+ expect(formatOutputFieldValue({ type: 'integer_output' }, 'value')).toBeNull();
+ expect(formatOutputFieldValue('not-an-object', 'value')).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/outputFields.ts b/invokeai/frontend/webv2/src/features/workflow/core/outputFields.ts
index e955b53bd5..49572b39e3 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/outputFields.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/outputFields.ts
@@ -40,3 +40,57 @@ export const getOutputFieldRows = (fieldNames: OutputFieldNamesByScope): OutputF
return rows;
};
+
+const OUTPUT_VALUE_MAX_LENGTH = 40;
+const NAMED_OBJECT_KEYS = ['image_name', 'video_name', 'latents_name', 'tensor_name', 'name', 'key', 'board_id'];
+
+/** Compact label for one output field's runtime value; `null` when the result carries no such field. */
+export const formatOutputFieldValue = (result: unknown, fieldName: string): { full: string; short: string } | null => {
+ if (typeof result !== 'object' || result === null || !(fieldName in result)) {
+ return null;
+ }
+
+ const value = (result as Record<string, unknown>)[fieldName];
+ const full = formatOutputValue(value);
+
+ return {
+ full,
+ short: full.length > OUTPUT_VALUE_MAX_LENGTH ? `${full.slice(0, OUTPUT_VALUE_MAX_LENGTH - 1)}…` : full,
+ };
+};
+
+const formatOutputValue = (value: unknown): string => {
+ if (value === null || value === undefined) {
+ return '—';
+ }
+
+ if (typeof value === 'number') {
+ return Number.isInteger(value) ? String(value) : String(Number(value.toFixed(4)));
+ }
+
+ if (typeof value === 'string' || typeof value === 'boolean') {
+ return String(value);
+ }
+
+ if (Array.isArray(value)) {
+ return `${value.length} item${value.length === 1 ? '' : 's'}`;
+ }
+
+ if (typeof value === 'object') {
+ const record = value as Record<string, unknown>;
+
+ for (const key of NAMED_OBJECT_KEYS) {
+ if (typeof record[key] === 'string') {
+ return record[key];
+ }
+ }
+
+ if (['r', 'g', 'b', 'a'].every((channel) => typeof record[channel] === 'number')) {
+ return `rgba(${record.r}, ${record.g}, ${record.b}, ${record.a})`;
+ }
+
+ return `{${Object.keys(record).length} fields}`;
+ }
+
+ return String(value);
+};
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts
index dc395f6840..be07dd0d92 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts
@@ -62,6 +62,8 @@ export interface WorkflowNodeExecutionState {
progress: number | null;
progressMessage: string | null;
outputImageUrl: string | null;
+ /** The most recent invocation result of the current run. */
+ latestOutput: unknown;
error: string | null;
}
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
index 6414281a5a..b029ce6c47 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx
@@ -13,11 +13,14 @@ import {
getWorkflowNodeShellProps,
WORKFLOW_NODE_DENSITY,
WorkflowNodeInfoIcon,
+ WorkflowNodeOutcomeIcon,
+ type WorkflowNodeOutcome,
} from '@features/workflow/ui/nodeChrome';
import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';
import { useWorkflowNodeExecutionState } from '@features/workflow/ui/WorkflowUiContext';
import {
cloneWorkflowFieldDefault,
+ formatOutputFieldValue,
getFieldTypeLabel,
getOutputFieldNamesByScope,
getOutputFieldRows,
@@ -63,28 +66,51 @@ const hasMissingRequiredInputs = (
}) !== null
);
+const getExecutionOutcome = (execution: NodeExecutionState | null): WorkflowNodeOutcome | null =>
+ execution?.status === 'completed' || execution?.status === 'failed' ? execution.status : null;
+
const NodeShell = ({
hasMissingRequiredInput,
children,
isMissing,
isRunning,
+ outcome,
selected,
}: {
hasMissingRequiredInput?: boolean;
children: React.ReactNode;
isMissing?: boolean;
isRunning?: boolean;
+ outcome?: WorkflowNodeOutcome | null;
selected: boolean;
}) => {
const isInvalid = isMissing || hasMissingRequiredInput;
return (
- <Box w={NODE_WIDTH} {...getWorkflowNodeShellProps({ invalid: isInvalid, running: isRunning, selected })}>
+ <Box w={NODE_WIDTH} {...getWorkflowNodeShellProps({ invalid: isInvalid, outcome, running: isRunning, selected })}>
{children}
</Box>
);
};
+/** The header's completed/failed mark, named for screen readers and tooltipped with the failure. */
+const NodeOutcomeIcon = ({ execution }: { execution: NodeExecutionState | null }) => {
+ const { t } = useTranslation();
+ const outcome = getExecutionOutcome(execution);
+
+ if (!outcome) {
+ return null;
+ }
+
+ return (
+ <WorkflowNodeOutcomeIcon
+ error={execution?.error}
+ label={outcome === 'completed' ? t('nodes.executionCompleted') : t('nodes.executionFailed')}
+ outcome={outcome}
+ />
+ );
+};
+
/** Thin progress strip under the header while the node's invocation executes. */
const NodeProgressStrip = ({ execution }: { execution: NodeExecutionState | null }) => {
if (execution?.status !== 'running') {
@@ -460,8 +486,17 @@ const InputFieldRow = ({
);
};
-const OutputFieldRow = ({ isSkeleton, template }: { isSkeleton: boolean; template: FieldOutputTemplate }) => {
+const OutputFieldRow = ({
+ isSkeleton,
+ latestResult,
+ template,
+}: {
+ isSkeleton: boolean;
+ latestResult: unknown;
+ template: FieldOutputTemplate;
+}) => {
const handleTooltip = getHandleTypeTooltip(template.type);
+ const value = latestResult === undefined ? null : formatOutputFieldValue(latestResult, template.name);
return (
<Box px={WORKFLOW_NODE_DENSITY.rowPaddingX} py={WORKFLOW_NODE_DENSITY.rowPaddingY}>
@@ -479,19 +514,36 @@ const OutputFieldRow = ({ isSkeleton, template }: { isSkeleton: boolean; templat
<SkeletonBar w="40%" />
</Flex>
) : (
- <Box textAlign="end">
- <Tooltip content={<OutputFieldTooltip template={template} />} positioning={{ placement: 'top-end' }}>
- <MiddleTruncate
- as="span"
- color="fg.muted"
- fontSize="2xs"
- justifyContent="flex-end"
- lineHeight="shorter"
- maxW="full"
- text={template.title}
- />
- </Tooltip>
- </Box>
+ <HStack gap="1.5" justify="flex-end" minW="0" w="full">
+ {value ? (
+ <Tooltip content={value.full} positioning={{ placement: 'top-end' }}>
+ <Text
+ color="fg.subtle"
+ fontSize="2xs"
+ lineHeight="shorter"
+ minW="0"
+ overflow="hidden"
+ textOverflow="ellipsis"
+ whiteSpace="nowrap"
+ >
+ {value.short}
+ </Text>
+ </Tooltip>
+ ) : null}
+ <Box flexShrink={0} maxW={value ? '60%' : 'full'} textAlign="end">
+ <Tooltip content={<OutputFieldTooltip template={template} />} positioning={{ placement: 'top-end' }}>
+ <MiddleTruncate
+ as="span"
+ color="fg.muted"
+ fontSize="2xs"
+ justifyContent="flex-end"
+ lineHeight="shorter"
+ maxW="full"
+ text={template.title}
+ />
+ </Tooltip>
+ </Box>
+ </HStack>
)}
</Flex>
</Box>
@@ -587,14 +639,22 @@ const CompactNodeBody = ({ inputCount, outputCount }: { inputCount: number; outp
const CompactInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeType>) => {
const node = data.documentNode;
const templateView = data.template;
+ const execution = useWorkflowNodeExecutionState(node.id);
const inputTemplates = templateView?.inputTemplates ?? [];
const outputTemplates = templateView?.outputTemplates ?? [];
const title = node.data.label || templateView?.template.title || node.data.type;
return (
- <NodeShell isMissing={!templateView} selected={selected ?? false}>
+ <NodeShell
+ isMissing={!templateView}
+ isRunning={execution?.status === 'running'}
+ outcome={getExecutionOutcome(execution)}
+ selected={selected ?? false}
+ >
<Flex {...getWorkflowNodeHeaderProps()}>
<MiddleTruncate fontSize="sm" fontWeight="700" minW="0" text={title} />
+ <Box flex="1" />
+ <NodeOutcomeIcon execution={execution} />
</Flex>
{templateView ? (
<CompactNodeBody inputCount={inputTemplates.length} outputCount={outputTemplates.length} />
@@ -649,9 +709,15 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode
const isCompact = data.isCompact && !selected;
const withFooter = !isZoomedOut && templateView.isExecutable && templateView.hasImageOutput;
const withOutputPreview = Boolean(execution?.outputImageUrl);
+ const latestResult = execution?.latestOutput;
return (
- <NodeShell hasMissingRequiredInput={isMissingRequiredInput} isRunning={isRunning} selected={selected ?? false}>
+ <NodeShell
+ hasMissingRequiredInput={isMissingRequiredInput}
+ isRunning={isRunning}
+ outcome={getExecutionOutcome(execution)}
+ selected={selected ?? false}
+ >
{/* The collapse chevron carries its own hit padding, so the header pulls its start padding in. */}
<Flex {...getWorkflowNodeHeaderProps({ roundedBottom: !isOpen })} gap="1" ps="1">
<IconButton
@@ -669,6 +735,7 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode
<>
<NodeTitle node={node} title={node.data.label || template.title} />
<Box flex="1" />
+ <NodeOutcomeIcon execution={execution} />
<NodeInfoIcon node={node} template={template} />
</>
)}
@@ -688,6 +755,7 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode
<OutputFieldRow
key={row.fieldName}
isSkeleton={isZoomedOut}
+ latestResult={latestResult}
template={outputTemplatesByName.get(row.fieldName) as FieldOutputTemplate}
/>
)
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsx
index 78b570d281..9e205514d4 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsx
@@ -5,7 +5,7 @@ import type { CSSProperties, ReactNode } from 'react';
import { Box, Icon } from '@chakra-ui/react';
import { getFieldTypeColor, isModelFieldType } from '@features/workflow/utility';
import { Tooltip } from '@platform/ui';
-import { InfoIcon } from 'lucide-react';
+import { CircleAlertIcon, CircleCheckIcon, InfoIcon } from 'lucide-react';
/**
* The single source of the workflow-node visual language. Every surface that
@@ -32,28 +32,43 @@ export const WORKFLOW_NODE_DENSITY = {
rowPaddingY: '0.5',
} as const;
-export const getWorkflowNodeChromeProps = ({
- invalid = false,
- running = false,
- selected,
-}: {
+/** How the node's last invocation ended, once it is no longer running. */
+export type WorkflowNodeOutcome = 'completed' | 'failed';
+
+export interface WorkflowNodeChromeState {
invalid?: boolean;
+ outcome?: WorkflowNodeOutcome | null;
running?: boolean;
selected: boolean;
-}): BoxProps => ({
- borderColor: invalid ? 'red.solid' : running ? 'brand.solid' : 'border.emphasized',
+}
+
+const getNodeBorderColor = ({ invalid, outcome, running }: WorkflowNodeChromeState): string => {
+ if (invalid) {
+ return 'red.solid';
+ }
+ if (running) {
+ return 'brand.solid';
+ }
+ if (outcome === 'completed') {
+ return 'fg.success';
+ }
+ if (outcome === 'failed') {
+ return 'border.error';
+ }
+
+ return 'border.emphasized';
+};
+
+export const getWorkflowNodeChromeProps = (state: WorkflowNodeChromeState): BoxProps => ({
+ borderColor: getNodeBorderColor(state),
borderWidth: '1px',
- shadow: selected ? NODE_SELECTED_RING : running ? NODE_RUNNING_RING : 'sm',
+ shadow: state.selected ? NODE_SELECTED_RING : state.running ? NODE_RUNNING_RING : 'sm',
transition: 'border-color var(--wb-motion-duration-fast) ease, box-shadow var(--wb-motion-duration-fast) ease',
- _hover: selected ? undefined : { shadow: NODE_HOVER_RING },
+ _hover: state.selected ? undefined : { shadow: NODE_HOVER_RING },
});
/** The node surface itself: chrome plus background, radius, and base type size. */
-export const getWorkflowNodeShellProps = (state: {
- invalid?: boolean;
- running?: boolean;
- selected: boolean;
-}): BoxProps => ({
+export const getWorkflowNodeShellProps = (state: WorkflowNodeChromeState): BoxProps => ({
bg: 'bg',
fontSize: 'xs',
rounded: 'lg',
@@ -155,3 +170,33 @@ export const WorkflowNodeInfoIcon = ({ content, label }: { content: ReactNode; l
<Icon aria-label={label} as={InfoIcon} boxSize="3.5" color="fg.subtle" />
</Tooltip>
);
+
+/** Header mark for a node whose invocation finished; the failure tooltip carries the backend message. */
+export const WorkflowNodeOutcomeIcon = ({
+ error,
+ label,
+ outcome,
+}: {
+ error?: string | null;
+ label: string;
+ outcome: WorkflowNodeOutcome;
+}) => {
+ const icon = (
+ <Icon
+ aria-label={label}
+ as={outcome === 'completed' ? CircleCheckIcon : CircleAlertIcon}
+ boxSize="3.5"
+ color={outcome === 'completed' ? 'fg.success' : 'fg.error'}
+ flexShrink={0}
+ role="img"
+ />
+ );
+
+ return outcome === 'failed' ? (
+ <Tooltip content={error || label} positioning={INFO_TOOLTIP_POSITIONING} showArrow>
+ {icon}
+ </Tooltip>
+ ) : (
+ icon
+ );
+};