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): preserve called-workflow previews and metadata

JPPhotob58ee4df8184
diff --git a/invokeai/app/services/session_queue/session_queue_base.py b/invokeai/app/services/session_queue/session_queue_base.py
index 02b14f1c7a..b3b91a5d4a 100644
--- a/invokeai/app/services/session_queue/session_queue_base.py
+++ b/invokeai/app/services/session_queue/session_queue_base.py
@@ -255,6 +255,11 @@ class SessionQueueBase(ABC):
"""Gets a session queue item by ID for a given queue"""
pass
+ @abstractmethod
+ def get_queue_item_workflow_json(self, item_id: int) -> str | None:
+ """Gets only the workflow metadata JSON for a queue item, if present."""
+ pass
+
@abstractmethod
def set_queue_item_session(self, item_id: int, session: GraphExecutionState) -> SessionQueueItem:
"""Sets the session for a session queue item. Use this to update the session state."""
diff --git a/invokeai/app/services/session_queue/session_queue_sqlite.py b/invokeai/app/services/session_queue/session_queue_sqlite.py
index be167517fd..026ac2b9af 100644
--- a/invokeai/app/services/session_queue/session_queue_sqlite.py
+++ b/invokeai/app/services/session_queue/session_queue_sqlite.py
@@ -1417,6 +1417,19 @@ class SqliteSessionQueue(SessionQueueBase):
raise SessionQueueItemNotFoundError(f"No queue item with id {item_id}")
return SessionQueueItem.queue_item_from_dict(dict(result))
+ def get_queue_item_workflow_json(self, item_id: int) -> str | None:
+ with self._db.transaction() as cursor:
+ cursor.execute(
+ """--sql
+ SELECT workflow
+ FROM session_queue
+ WHERE item_id = ?
+ """,
+ (item_id,),
+ )
+ result = cast(Union[sqlite3.Row, None], cursor.fetchone())
+ return cast(str | None, result["workflow"]) if result is not None else None
+
def save_queue_item_session(self, item_id: int, session: GraphExecutionState) -> None:
with self._db.transaction() as cursor:
# Use exclude_none so we don't end up with a bunch of nulls in the graph - this can cause validation errors
@@ -1496,7 +1509,7 @@ class SqliteSessionQueue(SessionQueueBase):
parent_queue_item.batch_id,
field_values_json,
parent_queue_item.priority,
- parent_queue_item.workflow.model_dump_json() if parent_queue_item.workflow else None,
+ None,
parent_queue_item.origin,
parent_queue_item.destination,
None,
diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.py
index 7f05af7f08..5ac4f4de94 100644
--- a/invokeai/app/services/shared/invocation_context.py
+++ b/invokeai/app/services/shared/invocation_context.py
@@ -73,6 +73,14 @@ class InvocationContextInterface:
self._services = services
self._data = data
+ def _get_workflow_json(self) -> str | None:
+ queue_item = self._data.queue_item
+ if queue_item.workflow is not None:
+ return queue_item.workflow.model_dump_json()
+ if queue_item.root_item_id is not None:
+ return self._services.session_queue.get_queue_item_workflow_json(queue_item.root_item_id)
+ return None
+
class BoardsInterface(InvocationContextInterface):
def create(self, board_name: str) -> BoardDTO:
@@ -249,9 +257,7 @@ class ImagesInterface(InvocationContextInterface):
):
raise PermissionError("Queue user is not authorized to save images to this board")
- workflow_ = None
- if self._data.queue_item.workflow:
- workflow_ = self._data.queue_item.workflow.model_dump_json()
+ workflow_ = self._get_workflow_json()
graph_ = None
if self._data.queue_item.session.graph:
@@ -414,9 +420,7 @@ class VideosInterface(InvocationContextInterface):
):
raise PermissionError("Queue user is not authorized to save videos to this board")
- workflow_ = None
- if self._data.queue_item.workflow:
- workflow_ = self._data.queue_item.workflow.model_dump_json()
+ workflow_ = self._get_workflow_json()
graph_ = None
if self._data.queue_item.session.graph:
diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/Flow.tsx b/invokeai/frontend/web/src/features/nodes/components/flow/Flow.tsx
index 7f0e9d544a..3c4676fbb2 100644
--- a/invokeai/frontend/web/src/features/nodes/components/flow/Flow.tsx
+++ b/invokeai/frontend/web/src/features/nodes/components/flow/Flow.tsx
@@ -63,8 +63,7 @@ import { useTranslation } from 'react-i18next';
import { PiPlugsConnectedBold, PiTrashBold } from 'react-icons/pi';
import CustomConnectionLine from './connectionLines/CustomConnectionLine';
-import InvocationCollapsedEdge from './edges/InvocationCollapsedEdge';
-import InvocationDefaultEdge from './edges/InvocationDefaultEdge';
+import { edgeTypes } from './edgeTypes';
import ConnectorNode from './nodes/Connector/ConnectorNode';
import CurrentImageNode from './nodes/CurrentImage/CurrentImageNode';
import InvocationNodeWrapper from './nodes/Invocation/InvocationNodeWrapper';
@@ -73,11 +72,6 @@ import type { WorkflowContextMenuState } from './workflowContextMenu';
import { getWorkflowContextMenuState } from './workflowContextMenu';
import { isWorkflowHotkeyEnabled, shouldIgnoreWorkflowCopyHotkey } from './workflowHotkeys';
-const edgeTypes = {
- collapsed: InvocationCollapsedEdge,
- default: InvocationDefaultEdge,
-} as const;
-
const nodeTypes = {
invocation: InvocationNodeWrapper,
connector: ConnectorNode,
diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/edgeTypes.ts b/invokeai/frontend/web/src/features/nodes/components/flow/edgeTypes.ts
new file mode 100644
index 0000000000..a3fab8e5c6
--- /dev/null
+++ b/invokeai/frontend/web/src/features/nodes/components/flow/edgeTypes.ts
@@ -0,0 +1,8 @@
+import InvocationCollapsedEdge from './edges/InvocationCollapsedEdge';
+import InvocationDefaultEdge from './edges/InvocationDefaultEdge';
+
+export const edgeTypes = {
+ collapsed: InvocationCollapsedEdge,
+ default: InvocationDefaultEdge,
+ loop_linkage: InvocationDefaultEdge,
+} as const;
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 29d0453d39..2aa9f5e8c4 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,3 +1,4 @@
+import { edgeTypes } from 'features/nodes/components/flow/edgeTypes';
import { describe, expect, it } from 'vitest';
import { connectionToEdge } from './reactFlowUtil';
@@ -36,4 +37,8 @@ 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/webv2/src/features/queue/runtime/coordinator.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
index 456eec498a..1cebb31306 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
@@ -1011,6 +1011,36 @@ describe('queueCoordinator', () => {
await expect(harness.coordinator.waitForResults('local-1', '2026-06-10T00:00:00Z')).resolves.toHaveLength(1);
});
+ it('replays a child preview received before the enqueue response', 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_progress', {
+ ...createStatusEvent({ item_id: 2 }),
+ image: { dataURL: 'data:image/png;base64:child', height: 32, width: 64 },
+ invocation_source_id: 'child-node',
+ message: 'Child sampling',
+ percentage: 0.5,
+ revision: 1,
+ root_item_id: 1,
+ session_id: 'child-session',
+ workflow_call_parent_source_id: 'call-node',
+ });
+
+ expect(harness.progressImage.set).not.toHaveBeenCalled();
+
+ acceptance.resolve({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 });
+ await submission;
+
+ expect(harness.progressImage.set).toHaveBeenCalledWith(
+ { dataUrl: 'data:image/png;base64:child', height: 32, width: 64 },
+ { itemIndex: 1, queueItemId: 'local-1' }
+ );
+ });
+
it('routes child invocation events to the parent call node', async () => {
harness.api.enqueueWorkflow.mockResolvedValue({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 });
harness.coordinator.connect();
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
index 245a3b1032..4bac1285f1 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
@@ -40,6 +40,7 @@ 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 PROGRESS_EVENT_BUFFER_ITEM_LIMIT = 64;
const BACKEND_READ_CONCURRENCY = 16;
const FRAME_GATE_LIMIT = 1024;
@@ -241,13 +242,15 @@ export const createQueueCoordinator = (
* is still resolving.
*/
const pendingNodeEvents = new Map<number, NodeEvent[]>();
+ /** Latest preview for items whose enqueue response has not registered them yet. */
+ const pendingProgressEvents = new Map<number, InvocationProgressEvent>();
/** 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. */
+ /** 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>();
/**
@@ -465,6 +468,23 @@ export const createQueueCoordinator = (
}
};
+ const bufferProgressEvent = (event: InvocationProgressEvent): void => {
+ const backendItemId = getTrackedBackendItemId(event);
+
+ pendingProgressEvents.delete(backendItemId);
+ pendingProgressEvents.set(backendItemId, event);
+
+ while (pendingProgressEvents.size > PROGRESS_EVENT_BUFFER_ITEM_LIMIT) {
+ const oldestId = pendingProgressEvents.keys().next().value;
+
+ if (oldestId === undefined) {
+ break;
+ }
+
+ pendingProgressEvents.delete(oldestId);
+ }
+ };
+
const replayNodeEvents = (backendItemId: number): void => {
const events = pendingNodeEvents.get(backendItemId);
@@ -487,7 +507,7 @@ export const createQueueCoordinator = (
}
};
- /** Runs an enqueue call while buffering node events that may land before its response registers the items. */
+ /** Runs an enqueue call while buffering events that may land before its response registers the items. */
const withSubmissionInFlight = async <T>(submit: () => Promise<T>): Promise<T> => {
inFlightSubmissions += 1;
@@ -498,6 +518,7 @@ export const createQueueCoordinator = (
if (inFlightSubmissions === 0) {
pendingNodeEvents.clear();
+ pendingProgressEvents.clear();
}
}
};
@@ -591,6 +612,7 @@ export const createQueueCoordinator = (
if (bufferedOutcome) {
replayNodeEvents(backendItemId);
recentTerminalOutcomes.delete(backendItemId);
+ pendingProgressEvents.delete(backendItemId);
settleNodes(backendItemId, bufferedOutcome.status);
return Promise.resolve(bufferedOutcome);
@@ -599,6 +621,7 @@ export const createQueueCoordinator = (
return new Promise<TerminalOutcome>((settle) => {
waits.set(backendItemId, { localQueueItemId, settle });
replayNodeEvents(backendItemId);
+ replayProgressEvent(backendItemId);
});
};
@@ -796,6 +819,9 @@ export const createQueueCoordinator = (
const wait = waits.get(backendItemId);
if (!wait) {
+ if (inFlightSubmissions > 0) {
+ bufferProgressEvent(event);
+ }
return;
}
@@ -826,6 +852,16 @@ export const createQueueCoordinator = (
}
};
+ const replayProgressEvent = (backendItemId: number): void => {
+ const event = pendingProgressEvents.get(backendItemId);
+
+ pendingProgressEvents.delete(backendItemId);
+
+ if (event) {
+ handleProgress(event);
+ }
+ };
+
/**
* React to the shared socket's connection lifecycle. The Platform hub owns
* transport mechanics only; this Queue coordinator clears its transient
@@ -847,6 +883,7 @@ export const createQueueCoordinator = (
nodeExecutionItemId = null;
nodeExecutionItemSequence = 0;
pendingNodeEvents.clear();
+ // Keep previews received before enqueue adoption; the HTTP response may still be in flight.
nodeIdsByBackendItem.clear();
modelLoads.reset();
@@ -952,6 +989,7 @@ export const createQueueCoordinator = (
runs.clear();
runProgress.clear();
recentTerminalOutcomes.clear();
+ pendingProgressEvents.clear();
latestStatusSequences.clear();
latestFrameGates.clear();
};
diff --git a/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py b/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
index 7dd31ffb86..49036da1e0 100644
--- a/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
+++ b/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py
@@ -278,12 +278,14 @@ def test_enqueue_workflow_call_child_inherits_workflow_for_image_metadata(
assert child_queue_item.root_item_id == parent_item_id
assert child_queue_item.workflow_call_depth == 1
assert child_queue_item.session_id == child_session.id
- assert child_queue_item.workflow == _workflow_without_id()
+ assert child_queue_item.workflow is None
services = MagicMock()
services.configuration.multiuser = False
services.configuration.pil_compress_level = 6
services.images.create.return_value = MagicMock()
+ workflow_json = _workflow_without_id().model_dump_json()
+ services.session_queue.get_queue_item_workflow_json.return_value = workflow_json
images = ImagesInterface(
services,
InvocationContextData(
@@ -294,7 +296,8 @@ def test_enqueue_workflow_call_child_inherits_workflow_for_image_metadata(
MagicMock(),
)
images.save(Image.new("RGB", (4, 4)))
- workflow_json = services.images.create.call_args.kwargs["workflow"]
+ assert services.session_queue.get_queue_item_workflow_json.call_args.args == (parent_item_id,)
+ assert services.images.create.call_args.kwargs["workflow"] == workflow_json
storage = DiskImageFileStorage(tmp_path)
storage._DiskImageFileStorage__invoker = services # type: ignore
@@ -371,8 +374,9 @@ def test_enqueue_workflow_call_child_preserves_workflow_through_nested_calls(
assert grandchild_event.parent_item_id == child_queue_item.item_id
assert grandchild_event.workflow_call_parent_source_id == "root-call"
- assert child_queue_item.workflow == workflow
- assert grandchild_queue_item.workflow == workflow
+ assert child_queue_item.workflow is None
+ assert grandchild_queue_item.workflow is None
+ assert session_queue.get_queue_item_workflow_json(root_item_id) == workflow.model_dump_json()
def test_enqueue_workflow_call_child_persists_batch_field_values(session_queue: SqliteSessionQueue) -> None: