Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(workflows): finish PR 298 follow-ups

JPPhotoef088f3d1681
diff --git a/invokeai/frontend/web/src/features/nodes/hooks/useNodeCopyPaste.ts b/invokeai/frontend/web/src/features/nodes/hooks/useNodeCopyPaste.ts
index 5c86a0b8f0..75c845c22b 100644
--- a/invokeai/frontend/web/src/features/nodes/hooks/useNodeCopyPaste.ts
+++ b/invokeai/frontend/web/src/features/nodes/hooks/useNodeCopyPaste.ts
@@ -134,11 +134,11 @@ const _pasteSelection = (withEdgesToCopiedNodes?: boolean) => {
);
return;
}
- } else if (e.type === 'default') {
+ } else if (e.type === 'default' || e.type === 'loop_linkage') {
const { type, source, sourceHandle, target, targetHandle } = e;
- // Our "default" type edges always have handles, but the reactflow types don't seem to inherit this typing, so we
- // need a type guard here. But these _should_ always be present.
+ // Our handle-bearing edges do not inherit this typing from React Flow, so
+ // we need a type guard here. These edges should always have handles.
if (!sourceHandle || !targetHandle) {
log.warn(
{ edge: { type, source, sourceHandle, target, targetHandle } },
@@ -165,7 +165,7 @@ const _pasteSelection = (withEdgesToCopiedNodes?: boolean) => {
return;
}
} else {
- // All our edges should be either "collapsed" or "default" type, so if we get here, something is wrong
+ // All our edges should be "collapsed", "default", or "loop_linkage".
const { type } = e;
log.warn({ edge: { type } }, `Invalid edge type, cannot paste`);
return;
diff --git a/invokeai/frontend/web/src/features/nodes/store/util/reactFlowUtil.test.ts b/invokeai/frontend/web/src/features/nodes/store/util/reactFlowUtil.test.ts
index 2aa9f5e8c4..0797618d17 100644
--- a/invokeai/frontend/web/src/features/nodes/store/util/reactFlowUtil.test.ts
+++ b/invokeai/frontend/web/src/features/nodes/store/util/reactFlowUtil.test.ts
@@ -1,4 +1,3 @@
-import { edgeTypes } from 'features/nodes/components/flow/edgeTypes';
import { describe, expect, it } from 'vitest';
import { connectionToEdge } from './reactFlowUtil';
@@ -38,7 +37,4 @@ describe('connectionToEdge', () => {
).toMatchObject({ type: 'loop_linkage' });
});
- it('registers loop_linkage with the React Flow renderer', () => {
- expect(edgeTypes.loop_linkage).toBe(edgeTypes.default);
- });
});
diff --git a/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.test.ts b/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.test.ts
index 0edd9a70c5..46157a8a30 100644
--- a/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.test.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.test.ts
@@ -1,6 +1,6 @@
import type { InvocationTemplate } from 'features/nodes/types/invocation';
import { buildInvocationNode } from 'features/nodes/util/node/buildInvocationNode';
-import { updateNode } from 'features/nodes/util/node/nodeUpdate';
+import { getConnectedInputNames, updateNode } from 'features/nodes/util/node/nodeUpdate';
import { describe, expect, it } from 'vitest';
const imageCollectionOutput = {
@@ -231,6 +231,13 @@ const currentMiniMaxH3DenoiseTemplate = {
} satisfies InvocationTemplate;
describe('updateNode', () => {
+ it('treats loop linkage edges as connected inputs during migration', () => {
+ expect(
+ getConnectedInputNames('for-return', [
+ { target: 'for-return', targetHandle: 'loop_linkage', type: 'loop_linkage' },
+ ])
+ ).toEqual(new Set(['loop_linkage']));
+ });
it('adds the seeded default when updating a stored text_llm node', () => {
const node = buildInvocationNode({ x: 0, y: 0 }, oldTextLLMTemplate);
node.data.inputs.prompt!.value = 'a cat';
diff --git a/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.ts b/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.ts
index ca1b397a91..3519b4f64c 100644
--- a/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/node/nodeUpdate.ts
@@ -18,7 +18,9 @@ type UpdateNodeOptions = {
export const getConnectedInputNames = (nodeId: string, edges: ConnectedInputEdge[]): Set<string> =>
new Set(
edges.flatMap((edge) =>
- edge.type === 'default' && edge.target === nodeId && edge.targetHandle ? [edge.targetHandle] : []
+ (edge.type === 'default' || edge.type === 'loop_linkage') && edge.target === nodeId && edge.targetHandle
+ ? [edge.targetHandle]
+ : []
)
);
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.md
index 2a71877ec4..77917dc39c 100644
--- a/invokeai/frontend/webv2/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/ARCHITECTURE.md
@@ -47,6 +47,8 @@ Workbench persistence follows the same lifetime rule. `createWorkbenchPersistenc
Contracts live with the module that owns their invariants. The retired `workbench/types.ts` path is an architecture violation; Workbench aggregate, widget, Canvas, persistence, settings, and feature contracts each have an owner-local canonical path. Persisted schemas and backend DTOs remain private versioned/wire values and cross seams only through explicit serializers, hydrators, or mappers.
+`platform/core/outputImages.ts` is the explicit shared adapter for backend invocation-output image names. It is platform-owned because Queue and Nodes both need the projection and cannot import each other's private implementations. The adapter recognizes only the backend's direct image, image-collection, and workflow-return output contracts; it must not become a recursive walker for arbitrary metadata or input fields.
+
Feature callers import a feature's public entry modules; imports of another feature's `core/`, `data/`, `ui/`, or runtime implementation are rejected outside a ticketed migration exception. Wildcard exports may aggregate files inside one owner, but may not cross an ownership seam. The contract caller matrix and development-invalidation budgets are generated by `pnpm architecture:check` and `pnpm test:performance:build` respectively.
The byte budgets in `performance/architecture-baseline.json` and `performance/browser-baseline.json` record measurements only. Each byte ceiling is the lower of `max(1%, 4 KB)` over the **higher of the base reference and committed measurement**, and `max(10%, 32 KB)` over the committed measurement (`deriveLimit` in `scripts/performance-budgets.mjs`). Deliberately re-recording a higher baseline therefore accepts reviewed growth, such as a dependency upgrade, in the same PR. Growth beyond that allowance still fails. Previously recorded higher measurements remain accepted until a downward re-record protects the savings; the committed hard ceiling continues to bound cumulative growth in the base branch. Re-record with `pnpm test:performance:build:update-baseline` and `pnpm test:performance:browser:update-baseline`, and include the measured cost or savings in review.
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 cab8999b48..446aaea8f9 100644
--- a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.test.ts
+++ b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.test.ts
@@ -15,6 +15,16 @@ beforeEach(() => {
});
describe('node execution lifecycle', () => {
+ it('clears a previous thumbnail when the current result has no image', () => {
+ nodeExecutionStore.completed({ invocation_source_id: 'node-1', result: { image: { image_name: 'old.png' } } });
+ nodeExecutionStore.completed({ invocation_source_id: 'node-1', result: { type: 'integer_output', value: 1 } });
+
+ expect(nodeExecutionStore.get('node-1')).toMatchObject({
+ latestOutput: { type: 'integer_output', value: 1 },
+ outputImageUrl: null,
+ status: 'completed',
+ });
+ });
it('preserves the latest image across progress and failure transitions', () => {
nodeExecutionStore.completed({
invocation_source_id: 'node-1',
diff --git a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts
index 53e0e3047f..440d987053 100644
--- a/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts
+++ b/invokeai/frontend/webv2/src/features/nodes/data/nodeExecutionStore.ts
@@ -49,13 +49,12 @@ export const nodeExecutionStore = {
},
completed(event: NodeInvocationCompleteEvent): void {
const imageName = getOutputImageNames(event.result)[0];
- const previous = stateByNodeId.get(event.invocation_source_id);
stateByNodeId.set(event.invocation_source_id, {
error: null,
outputImageUrl: imageName
? browserNodesDataPort.buildUrl(`/api/v1/images/i/${encodeURIComponent(imageName)}/thumbnail`)
- : (previous?.outputImageUrl ?? null),
+ : null,
latestOutput: event.result,
progress: null,
progressMessage: null,
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
index f41cd5c89a..11c90d0105 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
@@ -42,7 +42,7 @@ const NODE_EVENT_BUFFER_ITEM_LIMIT = 64;
const NODE_EVENT_BUFFER_EVENTS_PER_ITEM = 512;
const PROGRESS_EVENT_BUFFER_ITEM_LIMIT = 64;
const BACKEND_READ_CONCURRENCY = 16;
-const FRAME_GATE_LIMIT = 1024;
+const FRAME_GATES_PER_WAIT_LIMIT = 64;
/**
* Queue's view of model-load activity derived from socket events. The
@@ -183,6 +183,7 @@ interface RunProgressState {
}
interface WaitState {
+ frameGates: Map<number, { revision: number | null; sessionId: string }>;
localQueueItemId: string;
settle: (outcome: TerminalOutcome) => void;
}
@@ -230,6 +231,13 @@ export const createQueueCoordinator = (
const runs = new Map<string, RunState>();
const runProgress = new Map<string, RunProgressState>();
const waits = new Map<number, WaitState>();
+ const clearFrameGate = (itemId: number): void => {
+ for (const wait of waits.values()) {
+ if (wait.frameGates.delete(itemId)) {
+ return;
+ }
+ }
+ };
/**
* Terminal events that arrived for items nobody tracks yet. Closes the race
* where a very fast generation finishes between `enqueue_batch` resolving
@@ -253,35 +261,6 @@ export const createQueueCoordinator = (
/** Enqueue requests awaiting a response; early node events and previews are 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
- * frame. Socket delivery is ordered, so this only bites when a second source
- * — the reconnect snapshot the backend is to grow — races the live stream.
- */
- const latestFrameGates = new Map<number, { revision: number | null; sessionId: string }>();
-
- const rememberFrameGate = (itemId: number, gate: { revision: number | null; sessionId: string }): void => {
- latestFrameGates.delete(itemId);
- latestFrameGates.set(itemId, gate);
-
- while (latestFrameGates.size > FRAME_GATE_LIMIT) {
- let oldestId: number | undefined;
-
- for (const candidate of latestFrameGates.keys()) {
- if (!waits.has(candidate)) {
- oldestId = candidate;
- break;
- }
- }
-
- if (oldestId === undefined) {
- return;
- }
-
- latestFrameGates.delete(oldestId);
- }
- };
-
const getTrackedBackendItemId = (event: { item_id: number; root_item_id?: number | null }): number =>
event.root_item_id ?? event.item_id;
@@ -441,12 +420,14 @@ export const createQueueCoordinator = (
// A called workflow's child lifecycle is represented by the visible
// Call Saved Workflow node. Only the root invocation may settle that
// node or replace its latest output.
+ waits.get(backendItemId)?.frameGates.delete(nodeEvent.event.item_id);
if (backendItemId !== nodeEvent.event.item_id) {
return;
}
nodeExecution.completed(routeNodeEvent(nodeEvent.event, backendItemId, invocationSourceId));
return;
case 'failed':
+ waits.get(backendItemId)?.frameGates.delete(nodeEvent.event.item_id);
if (backendItemId !== nodeEvent.event.item_id) {
return;
}
@@ -540,8 +521,8 @@ export const createQueueCoordinator = (
return;
}
+ wait.frameGates.clear();
waits.delete(backendItemId);
- latestFrameGates.delete(backendItemId);
settleNodes(backendItemId, outcome.status);
const progressTarget = getProgressImageTarget(wait.localQueueItemId, backendItemId);
const releaseProgressSlot = (): void => {
@@ -628,7 +609,7 @@ export const createQueueCoordinator = (
}
return new Promise<TerminalOutcome>((settle) => {
- waits.set(backendItemId, { localQueueItemId, settle });
+ waits.set(backendItemId, { frameGates: new Map(), localQueueItemId, settle });
replayNodeEvents(backendItemId);
replayProgressEvent(backendItemId);
});
@@ -760,16 +741,13 @@ export const createQueueCoordinator = (
if (wait) {
activeProgressTarget.clear(getProgressImageTarget(wait.localQueueItemId, event.item_id));
}
- latestFrameGates.delete(event.item_id);
+ wait?.frameGates.clear();
}
return;
}
- // Child status events are not tracked waits, but their preview gate is
- // still per-child. Release it when the child ends so repeated calls do not
- // retain one entry forever. The size cap below covers missed terminal events.
- latestFrameGates.delete(event.item_id);
+ clearFrameGate(event.item_id);
if (!isTrackedEvent(event)) {
bufferTerminalOutcome(event.item_id, toTerminalOutcome(event.status, event.error_message, event.error_type));
@@ -801,8 +779,13 @@ export const createQueueCoordinator = (
* starts over.
*/
const isStaleFrame = (event: InvocationProgressEvent): boolean => {
+ const wait = waits.get(getTrackedBackendItemId(event));
+ if (!wait) {
+ return false;
+ }
+
const revision = event.revision ?? null;
- const gate = latestFrameGates.get(event.item_id);
+ const gate = wait.frameGates.get(event.item_id);
if (
gate &&
@@ -814,7 +797,15 @@ export const createQueueCoordinator = (
return true;
}
- rememberFrameGate(event.item_id, { revision, sessionId: event.session_id });
+ wait.frameGates.delete(event.item_id);
+ wait.frameGates.set(event.item_id, { revision, sessionId: event.session_id });
+ while (wait.frameGates.size > FRAME_GATES_PER_WAIT_LIMIT) {
+ const oldestItemId = wait.frameGates.keys().next().value;
+ if (oldestItemId === undefined) {
+ break;
+ }
+ wait.frameGates.delete(oldestItemId);
+ }
return false;
};
@@ -1000,7 +991,6 @@ export const createQueueCoordinator = (
recentTerminalOutcomes.clear();
pendingProgressEvents.clear();
latestStatusSequences.clear();
- latestFrameGates.clear();
};
const reconcile = async (items: ReconcileInput[]): Promise<Map<string, ReconcileOutcome>> => {
@@ -1224,7 +1214,7 @@ export const createQueueCoordinator = (
const wait = waits.get(backendItemId);
if (wait?.localQueueItemId === localQueueItemId) {
waits.delete(backendItemId);
- latestFrameGates.delete(backendItemId);
+ wait.frameGates.clear();
settleNodes(backendItemId, 'canceled');
wait.settle({ status: 'canceled' });
}
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsx
index 4c0b69b705..bc60fc6980 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsx
@@ -89,11 +89,18 @@ const settle = async (ms: number) => {
/** Waits until the request count stops changing, so an early window cannot read as a pass. */
const settleUntilRequestsStop = async (getCount: () => number, sample = 25, maxSamples = 80) => {
let previous = -1;
+ let unchangedSamples = 0;
for (let index = 0; index < maxSamples; index += 1) {
const current = getCount();
if (current === previous) {
+ unchangedSamples += 1;
+ } else {
+ unchangedSamples = 0;
+ }
+
+ if (unchangedSamples >= 3) {
return;
}
diff --git a/invokeai/frontend/webv2/src/platform/core/outputImages.test.ts b/invokeai/frontend/webv2/src/platform/core/outputImages.test.ts
index 3e4727ee20..e8fc9fd1c9 100644
--- a/invokeai/frontend/webv2/src/platform/core/outputImages.test.ts
+++ b/invokeai/frontend/webv2/src/platform/core/outputImages.test.ts
@@ -7,14 +7,29 @@ describe('getOutputImageNames', () => {
expect(
getOutputImageNames({
collection: [{ image_name: 'a.png' }, { image_name: 'b.png' }],
- image: { image_name: 'a.png' },
+ }),
+ ).toEqual(['a.png', 'b.png']);
+
+ expect(
+ getOutputImageNames({
+ type: 'workflow_return_output',
values: {
- collection: { collection: [{ image_name: 'c.png' }] },
- image: { image: { image_name: 'd.png' } },
+ collection: {
+ collection: [{ image_name: 'c.png' }],
+ type: 'image_collection_output',
+ },
+ image: { image: { image_name: 'd.png' }, type: 'image_output' },
values: { image_name: 'e.png' },
},
+ }),
+ ).toEqual(['c.png', 'd.png', 'e.png']);
+
+ expect(
+ getOutputImageNames({
+ type: 'workflow_return_output',
+ values: { Images: { collection: [{ image_name: 'legacy.png' }] } },
})
- ).toEqual(['a.png', 'b.png', 'c.png', 'd.png', 'e.png']);
+ ).toEqual(['legacy.png']);
});
it('does not inspect metadata, controls, or nested input objects', () => {
@@ -23,7 +38,7 @@ describe('getOutputImageNames', () => {
input: { image: { image_name: 'input.png' } },
metadata: { image: { image_name: 'metadata.png' } },
output_meta: { image: { image_name: 'meta-output.png' } },
- values: { result: { image: { image_name: 'result.png' } } },
+ values: { result: { image_name: 'result.png' } },
})
).toEqual(['result.png']);
});
diff --git a/invokeai/frontend/webv2/src/platform/core/outputImages.ts b/invokeai/frontend/webv2/src/platform/core/outputImages.ts
index d31979c163..dbbca8518c 100644
--- a/invokeai/frontend/webv2/src/platform/core/outputImages.ts
+++ b/invokeai/frontend/webv2/src/platform/core/outputImages.ts
@@ -8,40 +8,76 @@
export const getOutputImageNames = (output: unknown): string[] => {
const imageNames = new Set<string>();
- const visitOutputValue = (value: unknown): void => {
+ const visitImageField = (value: unknown): void => {
if (!value || typeof value !== 'object') {
return;
}
- if (Array.isArray(value)) {
- value.forEach(visitOutputValue);
- return;
- }
-
const record = value as Record<string, unknown>;
const imageName = record.image_name;
if (typeof imageName === 'string') {
imageNames.add(imageName);
+ }
+ };
+
+ const visitImageCollection = (value: unknown): void => {
+ if (!Array.isArray(value)) {
return;
}
- if ('image' in record) {
- visitOutputValue(record.image);
+ value.forEach(visitImageField);
+ };
+
+ const visitWorkflowReturnValue = (value: unknown): void => {
+ if (!value || typeof value !== 'object') {
+ return;
}
- if ('collection' in record) {
- visitOutputValue(record.collection);
+ if (Array.isArray(value)) {
+ visitImageCollection(value);
+ return;
}
- // `values` is the workflow-return wrapper. Its keys are user-selected and
- // therefore must never be interpreted as field names.
- if ('values' in record && record.values && typeof record.values === 'object') {
- Object.values(record.values as Record<string, unknown>).forEach(visitOutputValue);
+ const record = value as Record<string, unknown>;
+ visitImageField(record);
+
+ if (record.type === 'image_output') {
+ visitImageField(record.image);
+ } else if (record.type === 'image_collection_output') {
+ visitImageCollection(record.collection);
+ } else if (
+ 'image' in record &&
+ Object.keys(record).every((key) => key === 'image' || key === 'width' || key === 'height')
+ ) {
+ // Older workflow-return values omitted the output type for a single-image wrapper.
+ visitImageField(record.image);
+ } else if ('collection' in record && Object.keys(record).every((key) => key === 'collection')) {
+ // Older workflow-return values omitted the output type for a collection wrapper.
+ visitImageCollection(record.collection);
}
};
- if (output && typeof output === 'object' && !Array.isArray(output)) {
- visitOutputValue(output);
+ if (!output || typeof output !== 'object' || Array.isArray(output)) {
+ return [];
+ }
+
+ const record = output as Record<string, unknown>;
+ if (record.type === 'workflow_return_output' || 'values' in record) {
+ if (record.values && typeof record.values === 'object' && !Array.isArray(record.values)) {
+ Object.values(record.values as Record<string, unknown>).forEach(visitWorkflowReturnValue);
+ }
+ } else if (record.type === 'image_output') {
+ visitImageField(record.image);
+ } else if (record.type === 'image_collection_output') {
+ visitImageCollection(record.collection);
+ } else if ('image' in record) {
+ // Older queue results omitted the output type for single-image outputs.
+ visitImageField(record.image);
+ } else if ('collection' in record) {
+ // Older queue results omitted the output type for image collections.
+ visitImageCollection(record.collection);
+ } else {
+ visitWorkflowReturnValue(record);
}
return [...imageNames];