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): complete PR 298 follow-ups

JPPhoto4999138c1767
diff --git a/invokeai/app/services/shared/invocation_context.py b/invokeai/app/services/shared/invocation_context.py
index 5ac4f4de94..713e0b6648 100644
--- a/invokeai/app/services/shared/invocation_context.py
+++ b/invokeai/app/services/shared/invocation_context.py
@@ -66,6 +66,9 @@ class InvocationContextData:
"""The invocation that is being executed."""
source_invocation_id: str
"""The ID of the invocation from which the currently executing invocation was prepared."""
+ workflow_json: str | None = None
+ """Cached workflow JSON used by repeated image/video saves in this invocation context."""
+ workflow_json_loaded: bool = False
class InvocationContextInterface:
@@ -74,12 +77,16 @@ class InvocationContextInterface:
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
+ if not self._data.workflow_json_loaded:
+ queue_item = self._data.queue_item
+ if queue_item.workflow is not None:
+ self._data.workflow_json = queue_item.workflow.model_dump_json()
+ elif queue_item.root_item_id is not None:
+ self._data.workflow_json = self._services.session_queue.get_queue_item_workflow_json(
+ queue_item.root_item_id
+ )
+ self._data.workflow_json_loaded = True
+ return self._data.workflow_json
class BoardsInterface(InvocationContextInterface):
diff --git a/invokeai/frontend/webv2/src/features/queue/data/mappers.ts b/invokeai/frontend/webv2/src/features/queue/data/mappers.ts
index 17e9413ed4..66358b6952 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/mappers.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/mappers.ts
@@ -6,6 +6,8 @@ import type {
QueueStatusReadModel,
} from '@features/queue/core/types';
+import { getOutputImageNames } from '@platform/core/outputImages';
+
import type {
QueueAndProcessorStatusDTO,
QueueItemIdsResultDTO,
@@ -20,33 +22,7 @@ const mapNodeFieldValue = (dto: QueueNodeFieldValueDTO): QueueNodeFieldValue =>
});
const getResultImageNames = (dto: QueueServerItemDTO): string[] => {
- const imageNames: string[] = [];
-
- for (const result of Object.values(dto.session?.results ?? {})) {
- if (!result || typeof result !== 'object') {
- continue;
- }
-
- const image = (result as { image?: { image_name?: unknown } }).image;
-
- if (typeof image?.image_name === 'string') {
- imageNames.push(image.image_name);
- }
-
- const collection = (result as { collection?: unknown }).collection;
-
- if (Array.isArray(collection)) {
- for (const entry of collection) {
- const imageName = entry && typeof entry === 'object' ? (entry as { image_name?: unknown }).image_name : null;
-
- if (typeof imageName === 'string') {
- imageNames.push(imageName);
- }
- }
- }
- }
-
- return imageNames;
+ return Object.values(dto.session?.results ?? {}).flatMap(getOutputImageNames);
};
export const mapQueueItemDTO = (dto: QueueServerItemDTO): QueueItemReadModel => ({
diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
index 8eb0e85b8c..4401363c78 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
@@ -145,7 +145,6 @@ export const enqueueUtility = async (request: {
};
const getResultImageNames = (queueItem: QueueServerItemDTO, options?: QueueResultImageOptions): string[] => {
- const imageNames = new Set<string>();
const results = queueItem.session?.results ?? {};
const preparedSourceMapping = queueItem.session?.prepared_source_mapping ?? {};
const resultValues = options?.resultNodeIds
@@ -154,11 +153,7 @@ const getResultImageNames = (queueItem: QueueServerItemDTO, options?: QueueResul
.map(([, result]) => result)
: Object.values(results);
- for (const result of resultValues) {
- getOutputImageNames(result).forEach((imageName) => imageNames.add(imageName));
- }
-
- return [...imageNames];
+ return [...new Set(resultValues.flatMap(getOutputImageNames))];
};
const getResultImage = async (
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 1cebb31306..620c20f52e 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts
@@ -1061,6 +1061,25 @@ describe('queueCoordinator', () => {
);
});
+ it('does not let child terminal events settle the visible call node', async () => {
+ harness.api.enqueueWorkflow.mockResolvedValue({ batchId: 'batch-1', enqueued: 1, itemIds: [1], requested: 1 });
+ harness.coordinator.connect();
+ await harness.coordinator.submitWorkflow('local-1', workflowRequest);
+
+ const child = {
+ ...createStatusEvent({ item_id: 2 }),
+ invocation_source_id: 'child-node',
+ root_item_id: 1,
+ workflow_call_parent_source_id: 'call-node',
+ };
+ harness.socket.fire('invocation_complete', { ...child, result: { type: 'integer_output', value: 1 } });
+ harness.socket.fire('invocation_error', { ...child, error_message: 'child failed', error_type: 'ValueError' });
+
+ expect(harness.nodeExecution.completed).not.toHaveBeenCalled();
+ expect(harness.nodeExecution.failed).not.toHaveBeenCalled();
+ expect(harness.nodeExecution.settleRunning).not.toHaveBeenCalled();
+ });
+
it('routes child preview frames to the parent call node and root progress slot', 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 4bac1285f1..f41cd5c89a 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts
@@ -438,9 +438,18 @@ export const createQueueCoordinator = (
return;
}
case 'completed':
+ // 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.
+ if (backendItemId !== nodeEvent.event.item_id) {
+ return;
+ }
nodeExecution.completed(routeNodeEvent(nodeEvent.event, backendItemId, invocationSourceId));
return;
case 'failed':
+ if (backendItemId !== nodeEvent.event.item_id) {
+ return;
+ }
nodeExecution.failed(routeNodeEvent(nodeEvent.event, backendItemId, invocationSourceId));
return;
}
diff --git a/invokeai/frontend/webv2/src/platform/core/outputImages.test.ts b/invokeai/frontend/webv2/src/platform/core/outputImages.test.ts
new file mode 100644
index 0000000000..3e4727ee20
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/core/outputImages.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+
+import { getOutputImageNames } from './outputImages';
+
+describe('getOutputImageNames', () => {
+ it('reads direct images, collections, and workflow-return values independent of names', () => {
+ expect(
+ getOutputImageNames({
+ collection: [{ image_name: 'a.png' }, { image_name: 'b.png' }],
+ image: { image_name: 'a.png' },
+ values: {
+ collection: { collection: [{ image_name: 'c.png' }] },
+ image: { image: { image_name: 'd.png' } },
+ values: { image_name: 'e.png' },
+ },
+ })
+ ).toEqual(['a.png', 'b.png', 'c.png', 'd.png', 'e.png']);
+ });
+
+ it('does not inspect metadata, controls, or nested input objects', () => {
+ expect(
+ 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' } } },
+ })
+ ).toEqual(['result.png']);
+ });
+
+ it('accepts return keys named image, collection, and values', () => {
+ expect(
+ getOutputImageNames({
+ values: {
+ collection: [{ image_name: 'collection.png' }],
+ image: { image_name: 'image.png' },
+ values: { image_name: 'values.png' },
+ },
+ })
+ ).toEqual(['collection.png', 'image.png', 'values.png']);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/core/outputImages.ts b/invokeai/frontend/webv2/src/platform/core/outputImages.ts
index d213e05af4..d31979c163 100644
--- a/invokeai/frontend/webv2/src/platform/core/outputImages.ts
+++ b/invokeai/frontend/webv2/src/platform/core/outputImages.ts
@@ -1,56 +1,47 @@
/**
- * Collect image names from an invocation output, including named values returned by
- * `workflow_return`. A collection is intentionally flattened: callers that render one
- * thumbnail use the first name, while queue result routing uses every name.
+ * Shared adapter from backend invocation-output contracts to image names.
+ *
+ * This deliberately understands only the output shapes owned by the backend
+ * contract. It is not a general object walker: metadata and invocation inputs
+ * may contain images, but they are not outputs.
*/
export const getOutputImageNames = (output: unknown): string[] => {
const imageNames = new Set<string>();
- const visitImageValue = (value: unknown): void => {
- if (Array.isArray(value)) {
- value.forEach(visitImageValue);
+ const visitOutputValue = (value: unknown): void => {
+ if (!value || typeof value !== 'object') {
return;
}
- if (!value || typeof value !== 'object') {
+ if (Array.isArray(value)) {
+ value.forEach(visitOutputValue);
return;
}
- const imageName = (value as { image_name?: unknown }).image_name;
+ const record = value as Record<string, unknown>;
+ const imageName = record.image_name;
if (typeof imageName === 'string') {
imageNames.add(imageName);
return;
}
- if ('image' in value) {
- visitImageValue(value.image);
+ if ('image' in record) {
+ visitOutputValue(record.image);
}
- if ('collection' in value) {
- visitImageValue(value.collection);
+ if ('collection' in record) {
+ visitOutputValue(record.collection);
}
- // `values` is the only output field whose nested values are all returned
- // values. Do not walk arbitrary output fields such as `value` or metadata.
- if ('values' in value) {
- visitImageValue(value.values);
- }
-
- // A workflow return value is a mapping from names to output values. Its
- // entries need one more explicit descent, without opening unrelated fields.
- if (!('image' in value) && !('collection' in value) && !('values' in value)) {
- Object.entries(value)
- .filter(([key]) => key !== 'output_meta')
- .forEach(([, nestedValue]) => visitImageValue(nestedValue));
+ // `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);
}
};
if (output && typeof output === 'object' && !Array.isArray(output)) {
- const result = output as Record<string, unknown>;
-
- visitImageValue(result.image);
- visitImageValue(result.collection);
- visitImageValue(result.values);
+ visitOutputValue(output);
}
return [...imageNames];
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 49036da1e0..528e139d3c 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
@@ -1,6 +1,7 @@
"""Tests for workflow-call relationship metadata on session_queue items."""
import uuid
+from pathlib import Path
from unittest.mock import MagicMock
import pytest
@@ -13,6 +14,7 @@ from invokeai.app.services.events.events_common import (
QueueItemStatusChangedEvent,
)
from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage
+from invokeai.app.services.names.names_default import SimpleNameService
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.session_queue.session_queue_common import (
NodeFieldValue,
@@ -22,6 +24,7 @@ from invokeai.app.services.session_queue.session_queue_common import (
from invokeai.app.services.session_queue.session_queue_sqlite import SqliteSessionQueue
from invokeai.app.services.shared.graph import Graph, GraphExecutionState
from invokeai.app.services.shared.invocation_context import ImagesInterface, InvocationContextData
+from invokeai.app.services.urls.urls_default import LocalUrlService
from invokeai.app.services.workflow_records.workflow_records_common import WorkflowMeta, WorkflowWithoutID
from tests.test_nodes import TestEventService
@@ -219,7 +222,7 @@ def test_status_transition_reuses_loaded_queue_item(
def test_enqueue_workflow_call_child_inherits_workflow_for_image_metadata(
- session_queue: SqliteSessionQueue, tmp_path
+ session_queue: SqliteSessionQueue, mock_invoker: Invoker, tmp_path: Path
) -> None:
parent_graph = Graph()
parent_graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))
@@ -280,31 +283,29 @@ def test_enqueue_workflow_call_child_inherits_workflow_for_image_metadata(
assert child_queue_item.session_id == child_session.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
+ image_files = DiskImageFileStorage(tmp_path / "images")
+ mock_invoker.services.session_queue = session_queue
+ mock_invoker.services.image_files = image_files
+ mock_invoker.services.names = SimpleNameService()
+ mock_invoker.services.urls = LocalUrlService()
+ image_files.start(mock_invoker)
+ mock_invoker.services.images.start(mock_invoker)
+
images = ImagesInterface(
- services,
+ mock_invoker.services,
InvocationContextData(
queue_item=child_queue_item,
- invocation=MagicMock(is_intermediate=False),
+ invocation=MagicMock(is_intermediate=False, id="image-node"),
source_invocation_id="image-node",
),
MagicMock(),
)
- images.save(Image.new("RGB", (4, 4)))
- 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
+ dto = images.save(Image.new("RGB", (4, 4)))
- storage = DiskImageFileStorage(tmp_path)
- storage._DiskImageFileStorage__invoker = services # type: ignore
- storage.save(image=Image.new("RGB", (4, 4)), image_name="child.png", workflow=workflow_json)
-
- with Image.open(storage.get_path("child.png")) as saved:
+ workflow_json = _workflow_without_id().model_dump_json()
+ with Image.open(image_files.get_path(dto.image_name)) as saved:
assert saved.info["invokeai_workflow"] == workflow_json
+ assert mock_invoker.services.images.get_workflow(dto.image_name) == workflow_json
def test_enqueue_workflow_call_child_rejects_full_pending_queue(session_queue: SqliteSessionQueue) -> None:
diff --git a/tests/app/test_invocation_event_socketio.py b/tests/app/test_invocation_event_socketio.py
index 93b156cc62..e6d4919d5e 100644
--- a/tests/app/test_invocation_event_socketio.py
+++ b/tests/app/test_invocation_event_socketio.py
@@ -8,6 +8,7 @@ admin room - but in a single emit so that an admin who owns the queue item (whic
the "system" user in single-user mode) receives exactly one copy.
"""
+from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
@@ -24,6 +25,8 @@ from invokeai.app.services.events.events_common import (
ModelInstallStartedEvent,
)
from invokeai.app.services.model_install.model_install_common import URLModelSource
+from invokeai.app.services.session_processor.session_processor_common import ProgressImage
+from tests.test_nodes import TextToImageTestInvocation
@pytest.fixture
@@ -42,6 +45,39 @@ _COMMON_FIELDS = {
}
+def test_invocation_event_builders_preserve_nested_workflow_ancestry() -> None:
+ invocation = TextToImageTestInvocation(id="child-node")
+ queue_item = SimpleNamespace(
+ batch_id="batch-child",
+ destination=None,
+ device=None,
+ item_id=9,
+ origin="workflow",
+ parent_item_id=7,
+ queue_id="default",
+ root_item_id=3,
+ session=SimpleNamespace(
+ prepared_source_mapping={"child-node": "child-source"},
+ workflow_call_stack=[SimpleNamespace(source_call_node_id="call-node")],
+ ),
+ session_id="child-session",
+ user_id="owner-1",
+ )
+
+ events = [
+ InvocationStartedEvent.build(queue_item, invocation),
+ InvocationProgressEvent.build(
+ queue_item, invocation, "working", image=ProgressImage(dataURL="data", width=1, height=1)
+ ),
+ InvocationCompleteEvent.build(queue_item, invocation, {"type": "integer_output", "value": 1}),
+ InvocationErrorEvent.build(queue_item, invocation, "ValueError", "failed", "traceback"),
+ ]
+ for event in events:
+ assert event.parent_item_id == 7
+ assert event.root_item_id == 3
+ assert event.workflow_call_parent_source_id == "call-node"
+
+
@pytest.mark.anyio
async def test_progress_event_is_emitted_only_to_owner() -> None:
socketio = SocketIO(FastAPI())