Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
Feature: Add the ability to call a saved workflow from another (#9093)
Jonathan4ea04f6944a3
diff --git a/docs/src/content/docs/contributing/call-saved-workflow.md b/docs/src/content/docs/contributing/call-saved-workflow.mdnew file mode 100644index 0000000000..d96f8c8564--- /dev/null+++ b/docs/src/content/docs/contributing/call-saved-workflow.md@@ -0,0 +1,813 @@+---+title: Call Saved Workflow Architecture+---++## Goal++`CallSavedWorkflowInvocation` should become an engine-native workflow call boundary, not a frontend-only dynamic node+and not a compile-time graph inliner.++The long-term feature goal is:++- A parent workflow can call a saved workflow selected by ID.+- The call node redraws in the editor based on the selected workflow's exposed form fields.+- Parent values and inbound connections bind to those exposed fields as call arguments.+- Execution suspends at the call node, runs the selected workflow as a dependent workflow execution, captures explicit+ return values, and then resumes the parent workflow.+- The architecture must work for Invoke frontend graphs and for externally submitted graphs that use the same node type.++This document records the current state, the target architecture, and the execution contract needed to continue+development later.++## Implementation Priority++Favor the architecturally correct design over the fastest implementation path.++The work may still proceed incrementally, but each increment should satisfy all of the following:++- testable in isolation+- compatible with the long-term architecture described here+- non-breaking to existing code and existing workflow execution behavior++Speed is not the primary goal for this phase. The primary goal is to move toward the durable design without introducing+throwaway execution semantics that would need to be unwound later.++## Current State++Implemented already in the branch:++- A real invocation exists: `call_saved_workflow`.+- A real return node exists: `workflow_return`.+- Named returns exist through `workflow_return_value`, `workflow_return`, and caller-side `workflow_return_get`.+- `workflow_return` accepts one key/value return member directly or a collected list of return members, then emits a+ named `values: dict[str, Any]` map.+- Only one `workflow_return` node is allowed per workflow, enforced in both frontend validation and Python validation.+- The frontend provides a saved-workflow picker using a reusable `SavedWorkflowField` UI type.+- The node redraws dynamically based on the selected saved workflow's exposed form fields.+- Dynamic field values persist with the parent workflow.+- Compatible inbound edges are preserved when switching between workflows with matching exposed field identities and+ compatible types.+- Incompatible or no-longer-exposed inbound edges are removed in the editor.+- Backend validation exists for `workflow_id` existence and access rights.++Implemented runtime scaffolding:++- `GraphExecutionState` now persists workflow-call runtime state:+ - `workflow_call_stack`+ - `workflow_call_history`+ - `workflow_call_parent`+ - `waiting_workflow_call`+ - `waiting_workflow_call_execution`+ - `waiting_workflow_call_child_session`+ - `max_workflow_call_depth`+- Nested and recursive calls are represented by the stack, with a runtime depth cap of 4.+- Parent/child workflow-call identity is now explicit in runtime state:+ - the parent tracks an active `WorkflowCallExecution` record while waiting+ - completed and failed calls are preserved in `workflow_call_history`+ - child sessions carry a `workflow_call_parent` reference back to the parent call relationship+- `GraphExecutionState.next()` returns no runnable node while the parent session is waiting on a child workflow call.+- `GraphExecutionState.is_complete()` stays false while waiting.+- `DefaultSessionRunner.run_node()` now treats `call_saved_workflow` as a call boundary instead of a normal executable+ node.+- On boundary entry, the runner:+ - validates the selected workflow+ - builds a workflow call frame+ - converts the saved workflow JSON into a backend `Graph`+ - validates and applies parent call arguments to the child graph+ - creates a child `GraphExecutionState`+ - attaches that child session to the waiting parent session+- Workflow-call runtime responsibilities are now split:+ - `WorkflowCallCoordinator` handles call-specific setup:+ - build the child graph+ - apply parent call arguments+ - create the child `GraphExecutionState`+ - suspend the parent and enqueue the child queue item+ - `WorkflowCallQueueLifecycle` handles queue-visible parent/child lifecycle:+ - run child queue items+ - resume waiting parents after child success+ - complete the parent call node with the child `workflow_return` values+ - fail suspended parents after child failure and cascade that failure upward through parent call chains+- Child `SessionQueueItem` rows now carry explicit relationship metadata:+ - `workflow_call_id`+ - `parent_item_id`+ - `parent_session_id`+ - `root_item_id`+ - `workflow_call_depth`+ - this metadata is now used directly by queue-visible child execution and parent resume/failure handling+- The `session_queue` table now has matching durable columns for that relationship metadata:+ - `workflow_call_id`+ - `parent_item_id`+ - `parent_session_id`+ - `root_item_id`+ - `workflow_call_depth`+ - child workflow executions are now inserted as their own pending queue rows using those columns+- Parent queue items now enter a real `waiting` status while suspended on a child workflow execution.+- `_on_after_run_session()` no longer completes queue items whose sessions are incomplete but waiting.+- Dynamic call arguments now execute end-to-end in the current runner path:+ - literal dynamic values are serialized into a hidden `workflow_inputs` payload on the parent node at graph-build time+ - stale hidden `workflow_inputs` values from recalled graphs are ignored unless a matching current dynamic field+ exists+ - existing dynamic input values are preserved across refresh only while the exposed field type remains compatible; if+ the selected child workflow changes the exposed field type at the same node/field path, the caller input resets to+ the child workflow's current initial value+ - connected dynamic values are accepted as special call-boundary edges and are resolved from parent results at runtime+ - both are validated against the child workflow's exposed form interface before being applied to the child graph+- Queue lifecycle semantics now exist for workflow-call chains:+ - parent queue items are suspended in `waiting` while a child queue row runs+ - child success resumes the suspended parent and completes the parent call node with the child `workflow_return`+ values+ - child failure fails the suspended parent and cascades upward through any waiting parent chain+ - canceling a parent cancels its descendant child chain+ - canceling a child cancels the waiting parent chain upward+ - canceling remaining siblings after a batched child failure also cancels descendants of those sibling rows+ - deleting any queue row in a workflow-call chain deletes the full chain to avoid leaving orphaned parent or child+ rows behind+ - `cancel_all_except_current` and `delete_all_except_current` preserve the active queue item plus its workflow-call+ ancestors and descendants; this also covers the handoff window where a parent is `waiting` and its child is still+ `pending`; unrelated waiting chains are still canceled or deleted+ - retry is root-oriented rather than child-oriented; child queue rows should not be directly retried from the UI+ - the current UI policy is:+ - child queue rows keep `Cancel`+ - child queue rows hide `Retry`+ - child queue-row creation is now fail-clean:+ - if call-boundary setup fails after some child rows have already been inserted, those child rows are deleted before+ the parent invocation is failed+ - child queue-row fan-out is bounded by remaining queue capacity, not just the global queue-size setting:+ - a workflow call that would exceed the remaining pending capacity now fails instead of silently truncating or+ over-enqueuing child rows+ - child insertion rechecks pending capacity in the same database transaction as the insert++Implemented conversion helper:++- `workflow_graph_builder.py` converts saved workflow JSON into an executable backend `Graph`.+- It currently supports the invocation-node subset needed for this feature.+- It flattens connector nodes and omits explicit destination field values when a connection exists, matching frontend+ graph-build semantics.+- It now serves as the first explicit callable-workflow compatibility gate:+ - the selected workflow must contain exactly one `workflow_return` node+ - connected batch child inputs produced by ordinary non-generator upstream nodes still fail early with a clear+ unsupported-feature error+ - malformed batch input wiring, including multiple connected inputs to one batch field, is reported as+ `unsupported_batch_input` compatibility rather than a generic unsupported-node failure+ - child workflows that mix supported batch nodes with unrelated generator nodes are currently rejected with a clear+ unsupported-feature error+ - unsupported callees are rejected before any child queue row is created+- Compatibility metadata is now exposed through workflow library API responses:+ - workflow list items and workflow detail responses include `call_saved_workflow_compatibility`+ - workflow list items use structural generator-backed batch checks so list/picker rendering does not enumerate every+ image in board-backed generators; workflow detail and runtime execution still resolve real generator values+ - the saved-workflow picker uses that metadata to disable unsupported workflows before execution+ - the picker still allows an already-selected unsupported workflow to render, with an explicit unsupported state and+ a localized frontend message selected from the structured backend reason+ - workflow library list items now surface an explicit unsupported badge and localized reason without blocking normal+ workflow viewing or editing++What is still not implemented:++- connected batch child inputs whose batch values are produced by ordinary non-generator upstream nodes are still not+ supported and must fail with a clear domain error+- child workflows that mix supported batch nodes with unrelated generator nodes are still not supported and must fail+ with a clear domain error+- broader child-workflow compatibility coverage still needs to be expanded from real unsupported shapes rather than+ trying to interpret every frontend-only workflow representation through the current graph-builder path+- the current workflow-call queue lifecycle is still implemented through dedicated workflow-call runtime classes rather+ than a fully generalized parent/child scheduler model++Conclusion:++- the editor contract is largely in place+- the parent-side runtime call boundary is in place+- child execution, argument forwarding, explicit child return capture, suspended parent status, queue-visible child+ rows, and upward failure cascade now work+- the remaining major runtime work is to harden and generalize the parent/child scheduler model rather than prove the+ basic call boundary++## Architectural Direction++Use the architecture that is more likely to be kept long-term:++- `call_saved_workflow` is a call boundary.+- The parent graph does not inline the full child workflow into itself at queue time.+- Runtime execution pauses at the call node and creates a dependent child workflow execution.+- The child workflow receives arguments from the parent.+- The child workflow returns explicit outputs to the parent.+- The parent resumes once the child returns successfully.++This is preferred over full graph expansion because it:++- avoids execution-graph blowup+- preserves workflow boundaries+- matches the conceptual model of workflow reuse+- supports explicit return values+- keeps externally submitted graphs viable as long as they use the same node type and contract++## Non-Goals For The Next Phase++These should not be the first implementation target:++- full inline graph expansion of called workflows+- unlimited nested workflow call support+- automatic exposure of arbitrary internal child workflow state+- implicit output inference from arbitrary child nodes++## Execution Contract++### 1. Callable Interface++The callable interface of a saved workflow is defined by its saved workflow JSON.++Primary source:++- `workflow.form`++Fallback source for older workflows:++- `workflow.exposedFields`++Only fields exposed by the child workflow form are callable inputs. Internal child inputs that exist in the workflow+graph but are not exposed by the form are not part of the public call interface.++### 2. Input Arguments++`CallSavedWorkflowInvocation` exposes dynamic inputs in the editor based on the selected workflow's callable interface.++The saved-workflow picker sends typed search text to the workflow-list endpoint. This keeps large workflow libraries+discoverable even when the desired workflow has not already been loaded into the combobox pages.++Each dynamic input must have:++- a stable external handle name+- a type+- a default value if defined by the child workflow+- a user-facing label and description when available++Current fast-path identity is based on child `nodeId + fieldName`. That is acceptable short-term in the editor, but a+longer-term stable interface ID would be better if child workflows are frequently duplicated or refactored.++### 3. Input Binding At Runtime++At runtime, when the parent reaches `call_saved_workflow`:++- the engine resolves `workflow_id`+- the engine loads the selected child workflow record+- the engine reconstructs the callable interface from the saved workflow JSON+- the engine collects argument values from the parent node's dynamic inputs+- the engine starts a dependent child workflow execution using those arguments++Argument values may come from:++- parent literal field values+- resolved inbound connections into the call node's dynamic inputs++For batch-aware child workflows, the parent call boundary should still pass normal exposed form inputs. Batching should+emerge from the child workflow's own internal batch nodes or generators, not from a separate caller-side batch protocol.++### 4. Child Workflow Execution++The child workflow runs as its own dependent execution context, not as an inlined copy of the parent graph.++Desired semantics:++- parent execution pauses at the call node+- child execution runs with inherited context where appropriate+- child workflow finishes or fails+- parent resumes only if child execution succeeds++This implies the queue/session/runtime layer needs an explicit parent-child execution relationship.++Current limitation:++- the temporary `workflow_graph_builder.py` path still reconstructs only the ordinary invocation subset of child+ workflows+- direct batch-special child workflows now bypass that path and use queue batch expansion instead+- generator-backed batch child workflows now bypass that path too when the batch is fed directly by a supported+ generator node+- connected batch child inputs produced by ordinary non-generator upstream nodes are still not supported and should fail+ early with a clear unsupported-feature error+- the current queue-visible child execution path still relies on `WorkflowCallCoordinator` to resume or fail parents+ directly rather than a more general queue scheduler abstraction+- the current implementation is still an intermediate architecture step, but it is now materially closer to the intended+ durable parent/child model than the earlier inline-runner path++### 4a. Queue Lifecycle Contract++The current queue-visible implementation uses the following lifecycle contract:++- root or parent queue items may enter `waiting` while suspended on a child workflow call+- child workflow executions are represented as real queue rows with explicit parent/child relationship metadata+- child completion resumes the suspended parent and returns control to normal queue execution+- child failure fails the suspended parent call node and cascades upward through any ancestor chain+- cancel operations are chain-aware:+ - canceling a waiting parent cancels descendants+ - canceling a child cancels waiting ancestors+ - canceling batched siblings after one child fails includes nested descendants of those siblings+ - bulk "all except current" actions preserve the active queue item and its parent/child chain, not just the single+ `in_progress` row; a pending child with a waiting parent is treated as the active chain during processor handoff+- retry operations are root-aware:+ - retrying a root queue item creates a new root execution+ - retrying a child queue item should be normalized to the root by backend code+ - retry and full-chain delete authorization is checked against the root queue item owner+ - child queue rows should not expose direct retry affordances in the UI+ - retry websocket delivery is owner-scoped; when an admin retries roots owned by multiple users, each non-admin user+ must receive only the retry item ids for their own roots, while admins can still observe the full retried set+- workflow live-update sockets join workflow event rooms in both authenticated multiuser mode and unauthenticated+ single-user mode; the frontend relies on those events to invalidate workflow library data and clear deleted saved+ workflow selections; in single-user mode, workflow CRUD events emit only to the admin room to avoid duplicate delivery+ to sockets that are also joined to `user:system`+- a public-to-private transition emits a schema-defined `workflow_access_revoked` event to shared-workflow subscribers;+ non-owner, non-admin clients clear references to that workflow while owners and admins retain access+- the saved-workflow node picker queries owned/default workflows and public shared workflows separately, merges them by+ workflow id, and fetches additional pages as the combobox menu reaches the end+- queue status events must preserve user isolation:+ - `QueueItemStatusChangedEvent.queue_status` may keep global aggregate counts+ - embedded current-item identifiers (`item_id`, `session_id`, `batch_id`) must only be present when the current+ in-progress item belongs to the event owner, or when the status is being built for an admin/global context+ - workflow-call child enqueue events use the same owner-aware redaction as ordinary status transitions, even though+ they do not pass through `_set_queue_item_status`++This is now part of the intended user-facing contract, even though the orchestration still lives in+`WorkflowCallCoordinator`.++### 4b. Batch Child Workflows++The current implementation now supports direct batch-special child workflows for:++- `image_batch`+- `string_batch`+- `integer_batch`+- `float_batch`++It also supports generator-backed batch child workflows when those batch nodes are fed directly by:++- `integer_generator`+- `float_generator`+- `string_generator`+- `image_generator` using `image_generator_images_from_board`++Current semantics:++- batch-special nodes are removed from the executable child graph before ordinary graph validation+- supported generator nodes that feed those batch-special nodes are removed from the executable child graph as well+- their outgoing edges are converted into queue batch substitutions+- ungrouped batch nodes expand as a cartesian product+- grouped batch nodes zip by `batch_group_id`+- the workflow call creates one child queue row per expanded batch session+- supported generator value shapes are resolved into concrete batch items before queue batch expansion+- declared generator counts are rejected before resolution when they exceed remaining child capacity+- cartesian expansion size is computed arithmetically before session generation rather than by materializing the product+- batch outputs may feed a named `workflow_return_value.value` directly; each expanded child returns one value for that+ key+- parent resume waits for all child rows tied to that workflow call+- parent return aggregation produces `values: dict[str, list[Any]]`, where each key maps to one value per child row+- all child rows in one batch call must return the same key set; mismatched keys fail the parent call clearly+- if any child row fails, remaining sibling child rows are canceled and the parent call fails+- generator-backed image batches must respect board access:+ - the caller may expand images from a board they own+ - admins may expand any board+ - shared/public boards may be expanded by other users+ - inaccessible private boards must fail before image expansion rather than leaking board contents across users++Current generator coverage:++- integer generators:+ - arithmetic sequence+ - linear distribution+ - parse string+ - seeded uniform random distribution+- float generators:+ - arithmetic sequence+ - linear distribution+ - parse string+ - seeded uniform random distribution+- string generators:+ - parse string+ - dynamic prompts combinatorial+ - dynamic prompts random+- image generators:+ - images from board++Still unsupported:++- connected batch inputs whose batch values are produced by non-generator upstream nodes++Plain-English summary:++1. The parent workflow reaches `call_saved_workflow`.+1. The parent pauses and enters `waiting`.+1. The child workflow is inspected before execution.+1. If the child contains supported batch inputs, that one call expands into multiple child executions instead of one.+1. Each expanded child execution becomes its own queue row.+1. Each child queue row keeps the substituted batch `field_values`, matching ordinary batch queue rows.+1. Those child queue rows run independently.+1. The parent does not resume until all child queue rows for that call have finished.+1. Each child execution produces its own named `workflow_return.values` map.+1. The parent aggregates those maps into `values: dict[str, list[Any]]`.+1. The `call_saved_workflow` node completes with that named values map, and the parent workflow continues.++Expansion rules:++- ungrouped batch inputs expand as a cartesian product+- batch inputs that share the same `batch_group_id` zip together by position++Example:++- ungrouped inputs `[1, 2]` and `[10, 20]` produce 4 child executions:+ - `(1, 10)`+ - `(1, 20)`+ - `(2, 10)`+ - `(2, 20)`+- grouped inputs `[1, 2, 3]` and `[10, 20, 30]` with the same `batch_group_id` produce 3 child executions:+ - `(1, 10)`+ - `(2, 20)`+ - `(3, 30)`++### 4c. Tricky Areas++The following parts of the runtime contract are easy to misread and should stay explicit in both code and tests.++Waiting and resume:++- a parent queue row in `waiting` is suspended, not completed+- a parent resumes only after every child queue row tied to that workflow call has reached a terminal state++Return aggregation:++- each child queue row returns its own named `workflow_return.values`+- for batched calls, the parent call node output is `values: dict[str, list[Any]]`+- all child rows in one batched call must return the same key set so each returned list is row-aligned+- if one key should contain multiple images for a non-batch child, the child must collect those images into a single+ list value before returning that key++Sibling failure behavior:++- if one child queue row in a batched workflow call fails, remaining sibling child rows for that same workflow call are+ canceled+- if parent return aggregation rejects a completed child row, remaining sibling child rows for that same workflow call+ are canceled+- after sibling cancelation, the parent call fails+- if that parent is itself a child of another workflow call, failure continues upward through the ancestor chain++Cancel behavior:++- canceling a waiting parent cancels descendant child rows+- canceling a child row cancels waiting ancestors+- cancelation should stay cancelation; it should not be rewritten into ordinary failure semantics+- startup recovery cancels any interrupted `in_progress` or `waiting` workflow-call chain, including pending+ descendants, so a restart cannot leave a suspended parent waiting on a child row that will never report back++Retry behavior:++- retry is root-oriented+- child queue rows should not be directly retried from the UI+- backend retry of a child id should normalize to the root workflow call chain rather than create an isolated child-only+ rerun++### 5. Return Values++Return values should be explicit.++Implemented model:++- `workflow_return` is the explicit return node for callable workflows+- the child workflow declares named return values through explicit `workflow_return_value` key/value return members+- each return member has a stable string key and a connected value+- when the workflow is run independently, the return node has no caller-visible effect+- when the workflow is run via `call_saved_workflow`, the named return map becomes the return value of the call+- `call_saved_workflow` exposes that named return map to the parent workflow++Only one workflow return node may exist per workflow. That rule is enforced in both the frontend editor and in Python+validation/runtime code.++Do not infer child outputs from arbitrary terminal nodes. That is too ambiguous and too brittle.++Named return contract:++- the called workflow builds return members with a dedicated key/value node+- `workflow_return` accepts one return member directly, or a collected list of return members when the workflow returns+ multiple named values+- non-batch execution rejects duplicate return keys+- if a non-batch workflow needs to return multiple images under one key, the child workflow should collect those images+ into one list value and return that list under the key+- the caller extracts a named return value with a companion caller-side extraction node+- missing keys should fail clearly unless the extraction node explicitly supports and receives a default value++Batch return aggregation:++- when a called workflow expands into multiple child queue rows, each child row produces its own named return map+- the parent aggregates those child maps as `dict[str, list[Any]]`+- each key maps to child values in child enqueue order, preserving positional correspondence with batch inputs even when+ child executions complete out of order+- duplicate keys within a single child return map are still invalid; repeated keys across batch children are the normal+ aggregation path++### 6. Error Propagation++If child execution fails:++- the call node fails+- the parent workflow fails unless a later design adds explicit error-handling semantics++For the first implementation, failure propagation should be simple and strict.++### 7. Access Control++Runtime must enforce the same access rules used elsewhere for saved workflows.++The caller may execute a child workflow only if it is allowed to access that saved workflow at runtime.++This matters even if the parent workflow was authored in a context where the child was once visible.++### 8. Recursion And Nesting++Nested and recursive `call_saved_workflow` execution should be allowed, but bounded.++Initial implementation should enforce:++- nested workflow calls are allowed+- recursive workflow calls are allowed+- maximum workflow call depth is capped at 4 call frames+- the depth cap is enforced at runtime, based on the active call stack, not by static validation alone++This allows legitimate recursive or conditionally terminating workflow structures while still preventing unbounded call+growth.++## Where The Runtime Work Belongs++The goal is to support externally submitted graphs, not only frontend-authored graphs. Therefore the authoritative+execution logic must live in Python.++Recommended high-level design:++- a backend `GraphExpander` or broader graph-preparation service may still exist as an abstraction point+- but for this feature, the preferred long-term runtime model is not full graph expansion+- instead, the runtime needs a call-execution mechanism in the Python execution stack++Relevant existing path:++- frontend builds and submits a graph and workflow payload+- backend receives the batch via session queue APIs+- session queue stores session state+- runtime executes through `GraphExecutionState`++Current insertion points already used:++- `DefaultSessionRunner.run_node()` detects `call_saved_workflow` and enters boundary state+- `GraphExecutionState` stores the waiting/call-stack state and attached child session+- `WorkflowCallCoordinator` currently establishes the call boundary and enqueues child workflow executions as real queue+ rows+- `WorkflowCallQueueLifecycle` currently resumes or fails parents when those child rows complete+- child queue items already carry stable parent/child identifiers in both runtime objects and durable queue columns++Next runtime work still needed:++- keep `WorkflowCallQueueLifecycle` as the bounded workflow-call lifecycle component for this PR+ - the current workflow-call feature is the only caller of parent/child queue semantics+ - replacing it with a generalized queue dependency scheduler now would add regression risk without unlocking a+ concrete user workflow+ - revisit only if another feature needs dependent queue items, richer retry/cancel policies, or resumable waits+- if support expands beyond the currently supported direct and generator-backed batch shapes, route those new child+ workflow execution shapes through machinery that can honor ordinary Invoke batch semantics++## Runtime Components++### CallSavedWorkflowRuntime++Call-specific runtime behavior currently lives in `WorkflowCallCoordinator` and `WorkflowCallQueueLifecycle`.+Responsibilities:++- load and validate the selected child workflow record+- validate runtime access rights+- extract callable inputs from the child workflow definition+- build child execution arguments from the parent node state+- launch dependent child queue rows+- collect declared returns+- map returned values back to the parent node outputs++### Workflow Return Node++The dedicated child-workflow return nodes are implemented. Responsibilities:++- define the return interface of the called workflow+- build named key/value return members with `workflow_return_value`+- accept either one named return member or a collected list of return members with `workflow_return`+- provide that named values map back to the parent call site when invoked through `call_saved_workflow`+- remain inert from a caller perspective when the workflow is run independently+- guarantee that only one such node exists per workflow+- behave as a normal node in the editor, with singularity enforced by both frontend and Python validation/runtime code++This should remain the canonical reusable return mechanism for any future subworkflow call behavior.++### Execution Relationship Tracking++Session/runtime state records:++- parent execution waiting on child execution+- child execution belonging to a parent node call site+- result propagation back to the parent+- strict failure propagation rules++### Workflow Return Value Flow++The workflow return value should not be persisted back into the saved workflow record and should not be derived from+frontend state.++The intended runtime flow is:++1. The child workflow computes named return members like ordinary node outputs.+1. The child workflow connects one return member directly to `workflow_return.values`, or collects multiple return+ members and connects that list to `workflow_return.values`.+1. When the child reaches `workflow_return`, runtime captures the resolved named return map as the child workflow+ result.+1. The child workflow result is stored in child execution state.+1. That result is handed back to the suspended parent call frame.+1. The parent `call_saved_workflow` node is completed with that returned named value map.+1. The parent graph resumes.++## Named Return Implementation Status++Named returns are implemented for backend invocation behavior, caller-side extraction, runtime propagation, and batch+aggregation. Remaining work is limited to incremental frontend UX cleanup and any future expansion of supported batch+shapes.++### Stage 1: Backend Return Contract++Status: implemented in backend invocation tests.++Goal:++- establish the named return data model and invocation primitives++Contract:++- `WorkflowReturnValueField` stores one `key: str` and one `value: Any`+- `workflow_return_value` creates a single `WorkflowReturnValueField` from a key and connected value+- `workflow_return` accepts either one `WorkflowReturnValueField` member or a list of `WorkflowReturnValueField` members+- `WorkflowReturnOutput` exposes `values: dict[str, Any]`+- duplicate keys in one non-batch `workflow_return` execution are invalid and must fail clearly++Tests first:++- `workflow_return_value` emits the requested key/value pair+- `workflow_return` emits a named value map from one or more return members+- duplicate keys in one `workflow_return` execution are rejected+- empty returns are valid only if that remains an intentional callable-workflow contract++### Stage 2: Caller-Side Extraction Primitive++Status: implemented in backend invocation tests.++Goal:++- let the calling workflow extract a named return value without relying on collection position++Contract:++- `workflow_return_get` accepts the named return map and a key+- `workflow_return_get` outputs the selected value as `Any`+- missing keys fail clearly unless a later version intentionally adds default-value support++Tests first:++- extracting an existing key returns the stored value+- extracting a missing key fails with a useful message+- extracted `Any` values can feed typed downstream nodes through the existing connection compatibility rules++### Stage 3: Runtime Propagation++Status: implemented in backend runtime tests.++Goal:++- carry named return maps through queue-visible child execution and parent resume++Contract:++- non-batch child execution returns `values: dict[str, Any]`+- `call_saved_workflow` exposes that map on its output+- failed child execution behavior is unchanged+- cancel/retry lifecycle behavior is unchanged++Tests first:++- a called workflow returning `{image: image_value}` completes the parent `call_saved_workflow` output with that key+- a caller-side extraction node can consume that output after parent resume+- missing or invalid `workflow_return` nodes still fail with the existing clear errors++### Stage 4: Batch Return Aggregation++Status: implemented in backend runtime tests.++Goal:++- define named returns for child workflows that expand into multiple queue rows++Contract:++- each child queue row produces one named return map+- the parent aggregates child maps as `dict[str, list[Any]]`+- each key maps to values returned by completed child rows for that key+- all child rows in one batch call must return the same key set+- repeated keys across child rows are expected+- duplicate keys within one child row remain invalid+- if a non-batch workflow wants multiple images under one key, it must collect those images into a single list value+ before returning that key++Tests first:++- a batched child returning `{image: image_value}` from each child row produces `{image: [image_1, image_2, ...]}`+- sibling failure still cancels remaining siblings and fails the parent+- duplicate keys inside one child row are rejected rather than silently aggregated++### Stage 5: Frontend Schema, UI, And Docs++Status: mostly implemented. Schema/type generation includes the backend nodes and fields; editor connection coverage and+localized UI strings are in place for the current node wiring. Future UX cleanup should be driven by concrete user+testing rather than added as speculative work.++Goal:++- make named returns usable and visible in the editor++Contract:++- generated schema/types include the new return field, return-value node, and extraction node+- visible UI strings are localized through `en.json`+- `call_saved_workflow` exposes the named return map output+- users can wire that output to `workflow_return_get`++Tests first:++- frontend connection/type tests cover return-value collection wiring+- frontend connection/type tests cover wiring one `workflow_return_value.value` directly to `workflow_return.values`+- frontend connection/type tests cover `call_saved_workflow.values -> workflow_return_get.values`+- docs describe how a called workflow creates named returns and how a caller extracts them++## Frontend Responsibilities In The Long-Term Design++The frontend remains responsible for editor-time behavior:++- choosing the saved workflow+- redrawing dynamic inputs based on the child workflow callable interface+- persisting those dynamic fields and their values+- preserving compatible inbound edges when workflow selection changes+- clearing incompatible edges and invalid selections in a predictable way+- using backend compatibility metadata so unsupported saved workflows are not presented as callable choices+ - compatibility analysis now tolerates required exposed caller inputs by synthesizing placeholder values for those+ inputs during backend compatibility evaluation, so workflows that are valid once the caller supplies exposed values+ are not disabled prematurely++Potential future optimization:++- add a backend endpoint that returns a normalized callable workflow interface+- this would let the frontend avoid re-parsing full saved workflow payloads to redraw the node+- it would also give the frontend a backend-authoritative interface hash for drift detection++## Tests Needed Going Forward++Already covered:++- workflow-call stack and waiting state on `GraphExecutionState`+- depth-limit enforcement+- waiting blocks scheduling+- parent sessions are not completed while waiting+- runner boundary entry for `call_saved_workflow`+- validation failures and depth-limit failures still follow normal node-error behavior+- child workflow JSON conversion to backend `Graph`+- child graph build failure does not leave the parent in a partial waiting state+- child `GraphExecutionState` is attached to the waiting parent session+- coordinator-owned child execution completes the parent queue item instead of leaving it stuck in `in_progress`+- literal and connected dynamic call arguments are applied to the child graph at runtime+- non-exposed dynamic call arguments are rejected at runtime+- child `workflow_return` output is captured and becomes the parent `call_saved_workflow` output+- named `workflow_return` values can be constructed, propagated to the parent, extracted by key, and batch-aggregated as+ `dict[str, list[Any]]`+- child workflows without a `workflow_return` node fail cleanly when called+- child execution events now include stable workflow-call relationship metadata on the child `SessionQueueItem`+- parent-child resume and failure propagation through queue-visible child rows+- nested runtime execution with bounded stack depth+- direct and generator-backed batch-special child workflows through queue child-row expansion+- compatibility metadata for required exposed inputs, missing/multiple returns, supported named batch-return shapes, and+ unsupported batch input wiring++Still needed in later increments:++- focused coverage for any newly supported batch or generator shape when its contract changes+- possible migration from dedicated workflow-call queue lifecycle handling to a more general scheduler or+ queue-lifecycle model only if another feature needs reusable dependent queue items++## Recommended Immediate Next Step++The next incremental step should be:++- stop adding feature slices unless they close a concrete correctness gap or unlock a realistic user workflow+- stabilize the current branch with review, targeted test runs, and cleanup of stale design-doc language+- treat migration from `WorkflowCallQueueLifecycle` to a generalized parent/child queue lifecycle as a larger+ architecture slice, not as small follow-on busywork++The current branch is at the point where:++- parent call-boundary state exists+- child execution state can be created from the selected saved workflow+- child execution, argument forwarding, explicit return propagation, suspended parent status, queue-visible child rows,+ and upward failure cascade work through the current coordinator + queue path+- but long-term generalized parent/child scheduling semantics are still missingdiff --git a/invokeai/app/api/routers/session_queue.py b/invokeai/app/api/routers/session_queue.pyindex 2e829eca99..89d2f9a739 100644--- a/invokeai/app/api/routers/session_queue.py+++ b/invokeai/app/api/routers/session_queue.py@@ -39,6 +39,12 @@ class SessionQueueAndProcessorStatus(BaseModel):processor: SessionProcessorStatus+def _get_workflow_call_root_queue_item(queue_item: SessionQueueItem) -> SessionQueueItem:+ if queue_item.root_item_id is None:+ return queue_item+ return ApiDependencies.invoker.services.session_queue.get_queue_item(queue_item.root_item_id)++def sanitize_queue_item_for_user(queue_item: SessionQueueItem, current_user_id: str, is_admin: bool) -> SessionQueueItem:@@ -73,6 +79,11 @@ def sanitize_queue_item_for_user(sanitized_item.priority = 0sanitized_item.field_values = Nonesanitized_item.retried_from_item_id = None+ sanitized_item.workflow_call_id = None+ sanitized_item.parent_item_id = None+ sanitized_item.parent_session_id = None+ sanitized_item.root_item_id = None+ sanitized_item.workflow_call_depth = Nonesanitized_item.workflow = Nonesanitized_item.error_type = Nonesanitized_item.error_message = None@@ -321,20 +332,32 @@ async def retry_items_by_id() -> RetryItemsResult:"""Retries the given queue items. Users can only retry their own items unless they are an admin."""try:- # Check authorization: user must own all items or be an admin- if not current_user.is_admin:- for item_id in item_ids:- try:- queue_item = ApiDependencies.invoker.services.session_queue.get_queue_item(item_id)- if queue_item.user_id != current_user.user_id:- raise HTTPException(- status_code=403, detail=f"You do not have permission to retry queue item {item_id}"- )- except SessionQueueItemNotFoundError:- # Skip items that don't exist - they will be handled by retry_items_by_id- continue+ # Check queue membership for all items and ownership for non-admins.+ valid_item_ids: list[int] = []+ for item_id in item_ids:+ try:+ queue_item = ApiDependencies.invoker.services.session_queue.get_queue_item(item_id)+ if queue_item.queue_id != queue_id:+ raise HTTPException(+ status_code=404, detail=f"Queue item with id {item_id} not found in queue {queue_id}"+ )+ root_queue_item = _get_workflow_call_root_queue_item(queue_item)+ if root_queue_item.queue_id != queue_id:+ raise HTTPException(+ status_code=404, detail=f"Queue item with id {item_id} not found in queue {queue_id}"+ )+ if not current_user.is_admin and root_queue_item.user_id != current_user.user_id:+ raise HTTPException(+ status_code=403, detail=f"You do not have permission to retry queue item {item_id}"+ )+ valid_item_ids.append(item_id)+ except SessionQueueItemNotFoundError:+ # Skip items that don't exist - they will be handled by retry_items_by_id+ continue- return ApiDependencies.invoker.services.session_queue.retry_items_by_id(queue_id=queue_id, item_ids=item_ids)+ return ApiDependencies.invoker.services.session_queue.retry_items_by_id(+ queue_id=queue_id, item_ids=valid_item_ids+ )except HTTPException:raiseexcept Exception as e:@@ -518,9 +541,15 @@ async def delete_queue_item(try:# Get the queue item to check ownershipqueue_item = ApiDependencies.invoker.services.session_queue.get_queue_item(item_id)+ if queue_item.queue_id != queue_id:+ raise HTTPException(status_code=404, detail=f"Queue item with id {item_id} not found in queue {queue_id}")- # Check authorization: user must own the item or be an admin- if queue_item.user_id != current_user.user_id and not current_user.is_admin:+ root_queue_item = _get_workflow_call_root_queue_item(queue_item)+ if root_queue_item.queue_id != queue_id:+ raise HTTPException(status_code=404, detail=f"Queue item with id {item_id} not found in queue {queue_id}")++ # The queue service deletes the entire chain, so authorization must use the root owner.+ if root_queue_item.user_id != current_user.user_id and not current_user.is_admin:raise HTTPException(status_code=403, detail="You do not have permission to delete this queue item")ApiDependencies.invoker.services.session_queue.delete_queue_item(item_id)@@ -548,6 +577,8 @@ async def cancel_queue_item(try:# Get the queue item to check ownershipqueue_item = ApiDependencies.invoker.services.session_queue.get_queue_item(item_id)+ if queue_item.queue_id != queue_id:+ raise HTTPException(status_code=404, detail=f"Queue item with id {item_id} not found in queue {queue_id}")# Check authorization: user must own the item or be an adminif queue_item.user_id != current_user.user_id and not current_user.is_admin:diff --git a/invokeai/app/api/routers/workflows.py b/invokeai/app/api/routers/workflows.pyindex eb89325195..7daf93fb5c 100644--- a/invokeai/app/api/routers/workflows.py+++ b/invokeai/app/api/routers/workflows.py@@ -10,6 +10,7 @@ from invokeai.app.api.auth_dependencies import CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.services.shared.pagination import PaginatedResultsfrom invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection+from invokeai.app.services.shared.workflow_call_compatibility import get_workflow_call_compatibilityfrom invokeai.app.services.workflow_records.workflow_records_common import (Workflow,WorkflowCategory,@@ -51,7 +52,18 @@ async def get_workflow(raise HTTPException(status_code=403, detail="Not authorized to access this workflow")thumbnail_url = ApiDependencies.invoker.services.workflow_thumbnails.get_url(workflow_id)- return WorkflowRecordWithThumbnailDTO(thumbnail_url=thumbnail_url, **workflow.model_dump())+ compatibility = get_workflow_call_compatibility(+ workflow=workflow.workflow.model_dump(),+ workflow_id=workflow.workflow_id,+ services=ApiDependencies.invoker.services,+ user_id=current_user.user_id,+ maximum_children=ApiDependencies.invoker.services.configuration.max_queue_size,+ )+ return WorkflowRecordWithThumbnailDTO(+ thumbnail_url=thumbnail_url,+ call_saved_workflow_compatibility=compatibility,+ **workflow.model_dump(),+ )@workflows_router.patch(@@ -66,17 +78,24 @@ async def update_workflow(workflow: Workflow = Body(description="The updated workflow", embed=True),) -> WorkflowRecordDTO:"""Updates a workflow"""+ try:+ existing = ApiDependencies.invoker.services.workflow_records.get(workflow.id)+ except WorkflowNotFoundError:+ raise HTTPException(status_code=404, detail="Workflow not found")+config = ApiDependencies.invoker.services.configurationif config.multiuser:- try:- existing = ApiDependencies.invoker.services.workflow_records.get(workflow.id)- except WorkflowNotFoundError:- raise HTTPException(status_code=404, detail="Workflow not found")if not current_user.is_admin and existing.user_id != current_user.user_id:raise HTTPException(status_code=403, detail="Not authorized to update this workflow")- # Pass user_id for defense-in-depth SQL scoping; admins pass None to allow any.user_id = None if current_user.is_admin else current_user.user_id- return ApiDependencies.invoker.services.workflow_records.update(workflow=workflow, user_id=user_id)+ updated = ApiDependencies.invoker.services.workflow_records.update(workflow=workflow, user_id=user_id)+ ApiDependencies.invoker.services.events.emit_workflow_updated(+ workflow_id=updated.workflow_id,+ user_id=updated.user_id,+ old_is_public=existing.is_public,+ new_is_public=updated.is_public,+ )+ return updated@workflows_router.delete(@@ -88,12 +107,13 @@ async def delete_workflow(workflow_id: str = Path(description="The workflow to delete"),) -> None:"""Deletes a workflow"""+ try:+ existing = ApiDependencies.invoker.services.workflow_records.get(workflow_id)+ except WorkflowNotFoundError:+ raise HTTPException(status_code=404, detail="Workflow not found")+config = ApiDependencies.invoker.services.configurationif config.multiuser:- try:- existing = ApiDependencies.invoker.services.workflow_records.get(workflow_id)- except WorkflowNotFoundError:- raise HTTPException(status_code=404, detail="Workflow not found")if not current_user.is_admin and existing.user_id != current_user.user_id:raise HTTPException(status_code=403, detail="Not authorized to delete this workflow")try:@@ -103,6 +123,11 @@ async def delete_workflow(passuser_id = None if current_user.is_admin else current_user.user_idApiDependencies.invoker.services.workflow_records.delete(workflow_id, user_id=user_id)+ ApiDependencies.invoker.services.events.emit_workflow_deleted(+ workflow_id=existing.workflow_id,+ user_id=existing.user_id,+ is_public=existing.is_public,+ )@workflows_router.post(@@ -121,9 +146,15 @@ async def create_workflow(# workflows remain visible. In multiuser mode, workflows are private to the creator by default.config = ApiDependencies.invoker.services.configurationis_public = not config.multiuser- return ApiDependencies.invoker.services.workflow_records.create(+ created = ApiDependencies.invoker.services.workflow_records.create(workflow=workflow, user_id=current_user.user_id, is_public=is_public)+ ApiDependencies.invoker.services.events.emit_workflow_created(+ workflow_id=created.workflow_id,+ user_id=created.user_id,+ is_public=created.is_public,+ )+ return created@workflows_router.get(@@ -171,16 +202,31 @@ async def list_workflows(user_id=user_id_filter,is_public=is_public,)+ skipped_missing_workflows = 0for workflow in workflows.items:+ try:+ full_workflow = ApiDependencies.invoker.services.workflow_records.get(workflow.workflow_id)+ except WorkflowNotFoundError:+ skipped_missing_workflows += 1+ continue+ compatibility = get_workflow_call_compatibility(+ workflow=full_workflow.workflow.model_dump(),+ workflow_id=full_workflow.workflow_id,+ services=ApiDependencies.invoker.services,+ user_id=current_user.user_id,+ maximum_children=ApiDependencies.invoker.services.configuration.max_queue_size,+ resolve_generator_items=False,+ )workflows_with_thumbnails.append(WorkflowRecordListItemWithThumbnailDTO(thumbnail_url=ApiDependencies.invoker.services.workflow_thumbnails.get_url(workflow.workflow_id),+ call_saved_workflow_compatibility=compatibility,**workflow.model_dump(),))return PaginatedResults[WorkflowRecordListItemWithThumbnailDTO](items=workflows_with_thumbnails,- total=workflows.total,+ total=max(len(workflows_with_thumbnails), workflows.total - skipped_missing_workflows),page=workflows.page,pages=workflows.pages,per_page=workflows.per_page,@@ -312,9 +358,16 @@ async def update_workflow_is_public(raise HTTPException(status_code=403, detail="Not authorized to update this workflow")user_id = None if current_user.is_admin else current_user.user_id- return ApiDependencies.invoker.services.workflow_records.update_is_public(+ updated = ApiDependencies.invoker.services.workflow_records.update_is_public(workflow_id=workflow_id, is_public=is_public, user_id=user_id)+ ApiDependencies.invoker.services.events.emit_workflow_updated(+ workflow_id=updated.workflow_id,+ user_id=updated.user_id,+ old_is_public=existing.is_public,+ new_is_public=updated.is_public,+ )+ return updated@workflows_router.get("/tags", operation_id="get_all_tags")diff --git a/invokeai/app/api/sockets.py b/invokeai/app/api/sockets.pyindex 8e48b40233..70ca97740c 100644--- a/invokeai/app/api/sockets.py+++ b/invokeai/app/api/sockets.py@@ -35,8 +35,14 @@ from invokeai.app.services.events.events_common import (ModelLoadStartedEvent,QueueClearedEvent,QueueEventBase,+ QueueItemsRetriedEvent,QueueItemStatusChangedEvent,RecallParametersUpdatedEvent,+ WorkflowAccessRevokedEvent,+ WorkflowCreatedEvent,+ WorkflowDeletedEvent,+ WorkflowEventBase,+ WorkflowUpdatedEvent,register_events,)from invokeai.backend.util.logging import InvokeAILogger@@ -65,6 +71,7 @@ QUEUE_EVENTS = {InvocationErrorEvent,QueueItemStatusChangedEvent,BatchEnqueuedEvent,+ QueueItemsRetriedEvent,QueueClearedEvent,RecallParametersUpdatedEvent,}@@ -86,6 +93,7 @@ MODEL_EVENTS = {}BULK_DOWNLOAD_EVENTS = {BulkDownloadStartedEvent, BulkDownloadCompleteEvent, BulkDownloadErrorEvent}+WORKFLOW_EVENTS = {WorkflowCreatedEvent, WorkflowUpdatedEvent, WorkflowDeletedEvent}class SocketIO:@@ -115,6 +123,7 @@ class SocketIO:register_events(QUEUE_EVENTS, self._handle_queue_event)register_events(MODEL_EVENTS, self._handle_model_event)register_events(BULK_DOWNLOAD_EVENTS, self._handle_bulk_image_download_event)+ register_events(WORKFLOW_EVENTS, self._handle_workflow_event)async def _handle_connect(self, sid: str, environ: dict, auth: dict | None) -> bool:"""Handle socket connection and authenticate the user.@@ -167,6 +176,10 @@ class SocketIO:logger.info(f"Socket {sid} connected with user_id: {token_data.user_id}, is_admin: {token_data.is_admin}")+ await self._sio.enter_room(sid, f"user:{token_data.user_id}")+ await self._sio.enter_room(sid, "workflows:shared")+ if token_data.is_admin:+ await self._sio.enter_room(sid, "admin")return True# No valid token provided. In multiuser mode this is not allowed — reject@@ -183,6 +196,9 @@ class SocketIO:"is_admin": True,}logger.debug(f"Socket {sid} connected as system admin (single-user mode)")+ await self._sio.enter_room(sid, "user:system")+ await self._sio.enter_room(sid, "workflows:shared")+ await self._sio.enter_room(sid, "admin")return True@staticmethod@@ -409,6 +425,26 @@ class SocketIO:f"Emitted batch_enqueued: full to {user_room}+admin, sanitized to queue {event_data.queue_id}")+ # QueueItemsRetriedEvent carries queue item ids that should only be visible+ # to the affected owners + admins.+ elif isinstance(event_data, QueueItemsRetriedEvent):+ for user_id in event_data.user_ids:+ user_room = f"user:{user_id}"+ owner_event_data = event_data.model_copy(+ update={+ "retried_item_ids": event_data.retried_item_ids_by_user.get(user_id, []),+ "user_ids": [user_id],+ "retried_item_ids_by_user": {user_id: event_data.retried_item_ids_by_user.get(user_id, [])},+ }+ )+ await self._sio.emit(+ event=event_name, data=owner_event_data.model_dump(mode="json"), room=user_room+ )+ await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room="admin")+ logger.debug(+ f"Emitted private queue_items_retried event to user rooms {event_data.user_ids} and admin room"+ )+else:# For remaining queue events (e.g. QueueClearedEvent) that do not# carry user identity, emit to all subscribers in the queue room.@@ -440,3 +476,37 @@ class SocketIO:await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room=event_data.bulk_download_id)++ async def _handle_workflow_event(self, event: FastAPIEvent[WorkflowEventBase]) -> None:+ event_name, event_data = event+ payload = event_data.model_dump(mode="json")++ if not self._is_multiuser_enabled():+ await self._sio.emit(event=event_name, data=payload, room="admin")+ return++ await self._sio.emit(event=event_name, data=payload, room=f"user:{event_data.user_id}")+ await self._sio.emit(event=event_name, data=payload, room="admin")++ if event_name == "workflow_created":+ if getattr(event_data, "is_public", False):+ await self._sio.emit(event=event_name, data=payload, room="workflows:shared")+ return++ if event_name == "workflow_deleted":+ if getattr(event_data, "is_public", False):+ await self._sio.emit(event=event_name, data=payload, room="workflows:shared")+ return++ if event_name == "workflow_updated":+ if getattr(event_data, "new_is_public", False):+ await self._sio.emit(event=event_name, data=payload, room="workflows:shared")+ elif getattr(event_data, "old_is_public", False):+ access_revoked = WorkflowAccessRevokedEvent.build(+ workflow_id=event_data.workflow_id, user_id=event_data.user_id+ )+ await self._sio.emit(+ event=access_revoked.__event_name__,+ data=access_revoked.model_dump(mode="json"),+ room="workflows:shared",+ )diff --git a/invokeai/app/invocations/call_saved_workflow.py b/invokeai/app/invocations/call_saved_workflow.pynew file mode 100644index 0000000000..36f03021b1--- /dev/null+++ b/invokeai/app/invocations/call_saved_workflow.py@@ -0,0 +1,75 @@+from typing import Any++from invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocation+from invokeai.app.invocations.fields import InputField, UIType+from invokeai.app.invocations.workflow_return import WorkflowReturnOutput+from invokeai.app.services.shared.invocation_context import InvocationContext+from invokeai.app.services.workflow_records.workflow_records_common import WorkflowCategory, WorkflowNotFoundError++CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX = "saved_workflow_input::"+++def is_call_saved_workflow_dynamic_input(field_name: str) -> bool:+ return field_name.startswith(CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX)+++def parse_call_saved_workflow_dynamic_input(field_name: str) -> tuple[str, str]:+ if not is_call_saved_workflow_dynamic_input(field_name):+ raise ValueError(f"'{field_name}' is not a call_saved_workflow dynamic input field")++ raw_identifier = field_name.removeprefix(CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX)+ node_id, separator, input_field_name = raw_identifier.rpartition("::")+ if not separator or not node_id or not input_field_name:+ raise ValueError(f"Invalid call_saved_workflow dynamic input field '{field_name}'")++ return node_id, input_field_name+++@invocation(+ "call_saved_workflow",+ title="Call Saved Workflow",+ tags=["workflow", "saved", "library"],+ category="workflow",+ version="1.0.0",+ use_cache=False,+ classification=Classification.Beta,+)+class CallSavedWorkflowInvocation(BaseInvocation):+ """Displays and later executes against a selected saved workflow."""++ workflow_id: str = InputField(+ default="",+ description="The selected saved workflow ID, managed by the workflow editor UI.",+ ui_type=UIType.SavedWorkflow,+ )+ workflow_inputs: dict[str, Any] = InputField(+ default={},+ description="Literal values for the selected workflow's exposed inputs, managed by the workflow editor UI.",+ ui_hidden=True,+ )++ def validate_selected_workflow(self, context: InvocationContext):+ if not self.workflow_id:+ raise ValueError("A saved workflow must be selected before executing call_saved_workflow.")++ try:+ workflow_record = context._services.workflow_records.get(self.workflow_id)+ except WorkflowNotFoundError as e:+ raise ValueError(f"The selected saved workflow '{self.workflow_id}' could not be found.") from e++ config = context._services.configuration+ if config.multiuser:+ queue_user_id = context._data.queue_item.user_id+ user = context._services.users.get(queue_user_id)+ is_admin = bool(user and user.is_admin)+ is_owner = workflow_record.user_id == queue_user_id+ is_default = workflow_record.workflow.meta.category is WorkflowCategory.Default+ if not (is_default or is_owner or workflow_record.is_public or is_admin):+ raise ValueError(f"The selected saved workflow '{self.workflow_id}' is not accessible to this user.")++ return workflow_record++ def invoke(self, context: InvocationContext) -> WorkflowReturnOutput:+ self.validate_selected_workflow(context)++ return WorkflowReturnOutput(values={})diff --git a/invokeai/app/invocations/fields.py b/invokeai/app/invocations/fields.pyindex e53aeb417b..4418c86371 100644--- a/invokeai/app/invocations/fields.py+++ b/invokeai/app/invocations/fields.py@@ -49,6 +49,7 @@ class UIType(str, Enum, metaclass=MetaEnum):# region Misc Field TypesScheduler = "SchedulerField"Any = "AnyField"+ SavedWorkflow = "SavedWorkflowField"# endregion# region Internal Field Typesdiff --git a/invokeai/app/invocations/workflow_return.py b/invokeai/app/invocations/workflow_return.pynew file mode 100644index 0000000000..9f517a2648--- /dev/null+++ b/invokeai/app/invocations/workflow_return.py@@ -0,0 +1,139 @@+from typing import Any++from pydantic import BaseModel, Field++from invokeai.app.invocations.baseinvocation import (+ BaseInvocation,+ BaseInvocationOutput,+ Classification,+ invocation,+ invocation_output,+)+from invokeai.app.invocations.fields import Input, InputField, OutputField, UIType+from invokeai.app.services.shared.invocation_context import InvocationContext+++@invocation_output("workflow_return_output")+class WorkflowReturnOutput(BaseInvocationOutput):+ """The explicit named values returned from a callable workflow."""++ values: dict[str, Any] = OutputField(+ default={},+ description="The workflow return values, keyed by return name.",+ title="Values",+ ui_type=UIType.Any,+ )+++class WorkflowReturnValueField(BaseModel):+ """One named workflow return value."""++ key: str = Field(description="The workflow return key.")+ value: Any = Field(default=None, description="The workflow return value.")+++@invocation_output("workflow_return_value_output")+class WorkflowReturnValueOutput(BaseInvocationOutput):+ """A named workflow return value."""++ value: WorkflowReturnValueField = OutputField(+ description="The named workflow return value.",+ title="Return Value",+ ui_type=UIType._CollectionItem,+ )+++@invocation(+ "workflow_return_value",+ title="Workflow Return Value",+ tags=["workflow", "return", "output"],+ category="workflow",+ version="1.0.0",+ classification=Classification.Beta,+ use_cache=False,+)+class WorkflowReturnValueInvocation(BaseInvocation):+ """Creates one named value for a callable workflow return."""++ key: str = InputField(default="", description="The return key.", title="Key")+ value: Any = InputField(+ default=None,+ description="The value returned under this key.",+ title="Value",+ ui_type=UIType.Any,+ )++ def invoke(self, context: InvocationContext) -> WorkflowReturnValueOutput:+ key = self.key.strip()+ if not key:+ raise ValueError("Workflow return key must not be empty.")+ return WorkflowReturnValueOutput(value=WorkflowReturnValueField(key=key, value=self.value))+++@invocation(+ "workflow_return",+ title="Workflow Return",+ tags=["workflow", "return", "output"],+ category="workflow",+ version="1.0.0",+ classification=Classification.Beta,+ use_cache=False,+)+class WorkflowReturnInvocation(BaseInvocation):+ """Defines the explicit named result returned by a callable workflow."""++ values: WorkflowReturnValueField | list[WorkflowReturnValueField] = InputField(+ default=[],+ description="The named values returned to a calling workflow.",+ title="Values",+ input=Input.Connection,+ )++ def invoke(self, context: InvocationContext) -> WorkflowReturnOutput:+ named_values: dict[str, Any] = {}+ return_values = self.values if isinstance(self.values, list) else [self.values]+ for value in return_values:+ key = value.key.strip()+ if not key:+ raise ValueError("Workflow return key must not be empty.")+ if key in named_values:+ raise ValueError(f"Duplicate workflow return key '{key}'.")+ named_values[key] = value.value+ return WorkflowReturnOutput(values=named_values)+++@invocation_output("workflow_return_get_output")+class WorkflowReturnGetOutput(BaseInvocationOutput):+ """A value extracted from named workflow return values."""++ value: Any = OutputField(description="The extracted workflow return value.", title="Value", ui_type=UIType.Any)+++@invocation(+ "workflow_return_get",+ title="Get Workflow Return Value",+ tags=["workflow", "return", "input"],+ category="workflow",+ version="1.0.0",+ classification=Classification.Beta,+ use_cache=False,+)+class WorkflowReturnGetInvocation(BaseInvocation):+ """Extracts one named value from a callable workflow return."""++ values: dict[str, Any] = InputField(+ default={},+ description="The named workflow return values.",+ title="Values",+ ui_type=UIType.Any,+ input=Input.Connection,+ )+ key: str = InputField(default="", description="The return key to extract.", title="Key")++ def invoke(self, context: InvocationContext) -> WorkflowReturnGetOutput:+ key = self.key.strip()+ if not key:+ raise ValueError("Workflow return key must not be empty.")+ if key not in self.values:+ raise ValueError(f"Workflow return key '{key}' was not found.")+ return WorkflowReturnGetOutput(value=self.values[key])diff --git a/invokeai/app/services/events/events_base.py b/invokeai/app/services/events/events_base.pyindex 935b422a73..0e1f71c2bc 100644--- a/invokeai/app/services/events/events_base.py+++ b/invokeai/app/services/events/events_base.py@@ -32,6 +32,9 @@ from invokeai.app.services.events.events_common import (QueueItemsRetriedEvent,QueueItemStatusChangedEvent,RecallParametersUpdatedEvent,+ WorkflowCreatedEvent,+ WorkflowDeletedEvent,+ WorkflowUpdatedEvent,)if TYPE_CHECKING:@@ -104,9 +107,11 @@ class EventServiceBase:"""Emitted when a batch is enqueued"""self.dispatch(BatchEnqueuedEvent.build(enqueue_result, user_id))- def emit_queue_items_retried(self, retry_result: "RetryItemsResult") -> None:+ def emit_queue_items_retried(+ self, retry_result: "RetryItemsResult", user_ids: list[str], retried_item_ids_by_user: dict[str, list[int]]+ ) -> None:"""Emitted when a list of queue items are retried"""- self.dispatch(QueueItemsRetriedEvent.build(retry_result))+ self.dispatch(QueueItemsRetriedEvent.build(retry_result, user_ids, retried_item_ids_by_user))def emit_queue_cleared(self, queue_id: str) -> None:"""Emitted when a queue is cleared"""@@ -118,6 +123,29 @@ class EventServiceBase:# endregion+ # region Workflow library++ def emit_workflow_created(self, workflow_id: str, user_id: str, is_public: bool) -> None:+ """Emitted when a workflow is created."""+ self.dispatch(WorkflowCreatedEvent.build(workflow_id=workflow_id, user_id=user_id, is_public=is_public))++ def emit_workflow_updated(self, workflow_id: str, user_id: str, old_is_public: bool, new_is_public: bool) -> None:+ """Emitted when a workflow is updated."""+ self.dispatch(+ WorkflowUpdatedEvent.build(+ workflow_id=workflow_id,+ user_id=user_id,+ old_is_public=old_is_public,+ new_is_public=new_is_public,+ )+ )++ def emit_workflow_deleted(self, workflow_id: str, user_id: str, is_public: bool) -> None:+ """Emitted when a workflow is deleted."""+ self.dispatch(WorkflowDeletedEvent.build(workflow_id=workflow_id, user_id=user_id, is_public=is_public))++ # endregion+# region Downloaddef emit_download_started(self, job: "DownloadJob") -> None:diff --git a/invokeai/app/services/events/events_common.py b/invokeai/app/services/events/events_common.pyindex 0c530f9a2f..005b0e5435 100644--- a/invokeai/app/services/events/events_common.py+++ b/invokeai/app/services/events/events_common.py@@ -308,12 +308,20 @@ class QueueItemsRetriedEvent(QueueEventBase):__event_name__ = "queue_items_retried"retried_item_ids: list[int] = Field(description="The IDs of the queue items that were retried")+ user_ids: list[str] = Field(description="The IDs of the users who own the retried root queue items")+ retried_item_ids_by_user: dict[str, list[int]] = Field(+ description="The retried root queue item IDs keyed by owner user ID."+ )@classmethod- def build(cls, retry_result: RetryItemsResult) -> "QueueItemsRetriedEvent":+ def build(+ cls, retry_result: RetryItemsResult, user_ids: list[str], retried_item_ids_by_user: dict[str, list[int]]+ ) -> "QueueItemsRetriedEvent":return cls(queue_id=retry_result.queue_id,retried_item_ids=retry_result.retried_item_ids,+ user_ids=user_ids,+ retried_item_ids_by_user=retried_item_ids_by_user,)@@ -328,6 +336,69 @@ class QueueClearedEvent(QueueEventBase):return cls(queue_id=queue_id)+class WorkflowEventBase(EventBase):+ """Base class for workflow library CRUD events."""++ workflow_id: str = Field(description="The ID of the workflow")+ user_id: str = Field(description="The owner of the workflow")+++@payload_schema.register+class WorkflowCreatedEvent(WorkflowEventBase):+ """Event model for workflow_created"""++ __event_name__ = "workflow_created"++ is_public: bool = Field(description="Whether the workflow is shared with all users")++ @classmethod+ def build(cls, workflow_id: str, user_id: str, is_public: bool) -> "WorkflowCreatedEvent":+ return cls(workflow_id=workflow_id, user_id=user_id, is_public=is_public)+++@payload_schema.register+class WorkflowUpdatedEvent(WorkflowEventBase):+ """Event model for workflow_updated"""++ __event_name__ = "workflow_updated"++ old_is_public: bool = Field(description="Whether the workflow was shared before the update")+ new_is_public: bool = Field(description="Whether the workflow is shared after the update")++ @classmethod+ def build(cls, workflow_id: str, user_id: str, old_is_public: bool, new_is_public: bool) -> "WorkflowUpdatedEvent":+ return cls(+ workflow_id=workflow_id,+ user_id=user_id,+ old_is_public=old_is_public,+ new_is_public=new_is_public,+ )+++@payload_schema.register+class WorkflowDeletedEvent(WorkflowEventBase):+ """Event model for workflow_deleted"""++ __event_name__ = "workflow_deleted"++ is_public: bool = Field(description="Whether the workflow was shared when it was deleted")++ @classmethod+ def build(cls, workflow_id: str, user_id: str, is_public: bool) -> "WorkflowDeletedEvent":+ return cls(workflow_id=workflow_id, user_id=user_id, is_public=is_public)+++@payload_schema.register+class WorkflowAccessRevokedEvent(WorkflowEventBase):+ """Event model for workflow_access_revoked."""++ __event_name__ = "workflow_access_revoked"++ @classmethod+ def build(cls, workflow_id: str, user_id: str) -> "WorkflowAccessRevokedEvent":+ return cls(workflow_id=workflow_id, user_id=user_id)++class DownloadEventBase(EventBase):"""Base class for events associated with a download"""diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.pyindex b10aa6bbb6..e6d3dfe15d 100644--- a/invokeai/app/services/session_processor/session_processor_default.py+++ b/invokeai/app/services/session_processor/session_processor_default.py@@ -6,6 +6,7 @@ from threading import Event as ThreadEventfrom typing import Optionalfrom invokeai.app.invocations.baseinvocation import BaseInvocation, BaseInvocationOutput+from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocationfrom invokeai.app.services.events.events_common import (BatchEnqueuedEvent,FastAPIEvent,@@ -27,6 +28,10 @@ from invokeai.app.services.session_processor.session_processor_base import (SessionRunnerBase,)from invokeai.app.services.session_processor.session_processor_common import CanceledException, SessionProcessorStatus+from invokeai.app.services.session_processor.workflow_call_runtime import (+ WorkflowCallCoordinator,+ WorkflowCallQueueLifecycle,+)from invokeai.app.services.session_queue.session_queue_common import SessionQueueItem, SessionQueueItemNotFoundErrorfrom invokeai.app.services.shared.graph import NodeInputErrorfrom invokeai.app.services.shared.invocation_context import InvocationContextData, build_invocation_context@@ -58,6 +63,8 @@ class DefaultSessionRunner(SessionRunnerBase):self._on_after_run_node_callbacks = on_after_run_node_callbacks or []self._on_node_error_callbacks = on_node_error_callbacks or []self._on_after_run_session_callbacks = on_after_run_session_callbacks or []+ self.workflow_call_coordinator = WorkflowCallCoordinator(self)+ self.workflow_call_queue_lifecycle = WorkflowCallQueueLifecycle(self)def start(self, services: InvocationServices, cancel_event: ThreadEvent, profiler: Optional[Profiler] = None):self._services = services@@ -69,11 +76,7 @@ class DefaultSessionRunner(SessionRunnerBase):denoising to check if the session has been canceled."""return self._cancel_event.is_set()- def run(self, queue_item: SessionQueueItem):- # Exceptions raised outside `run_node` are handled by the processor. There is no need to catch them here.-- self._on_before_run_session(queue_item=queue_item)-+ def _run_session_loop(self, queue_item: SessionQueueItem) -> None:# Loop over invocations until the session is complete or canceledwhile True:try:@@ -107,6 +110,11 @@ class DefaultSessionRunner(SessionRunnerBase):):break+ def run(self, queue_item: SessionQueueItem):+ # Exceptions raised outside `run_node` are handled by the processor. There is no need to catch them here.++ self._on_before_run_session(queue_item=queue_item)+ self._run_session_loop(queue_item)self._on_after_run_session(queue_item=queue_item)def run_node(self, invocation: BaseInvocation, queue_item: SessionQueueItem):@@ -126,6 +134,11 @@ class DefaultSessionRunner(SessionRunnerBase):is_canceled=self._is_canceled,)+ if isinstance(invocation, CallSavedWorkflowInvocation):+ workflow_record = invocation.validate_selected_workflow(context)+ self.workflow_call_coordinator.begin_workflow_call_boundary(invocation, queue_item, workflow_record)+ return+# Invoke the nodeoutput = invocation.invoke_internal(context=context, services=self._services)# Save output and history@@ -201,7 +214,7 @@ class DefaultSessionRunner(SessionRunnerBase):# The queue item may have been canceled or failed while the session was running. We should only complete it# if it is not already canceled or failed.- if queue_item.status not in ["canceled", "failed"]:+ if queue_item.status not in ["canceled", "failed"] and queue_item.session.is_complete():queue_item = self._services.session_queue.complete_queue_item(queue_item.item_id)# We'll get a GESStatsNotFoundError if we try to log stats for an untracked graph, but in the processor@@ -316,6 +329,7 @@ class DefaultSessionProcessor(SessionProcessorBase):super().__init__()self.session_runner = session_runner if session_runner else DefaultSessionRunner()+ self.workflow_call_queue_lifecycle = self.session_runner.workflow_call_queue_lifecycleself._on_non_fatal_processor_error_callbacks = on_non_fatal_processor_error_callbacks or []self._thread_limit = thread_limitself._polling_interval = polling_interval@@ -467,7 +481,7 @@ class DefaultSessionProcessor(SessionProcessorBase):cancel_event.clear()# Run the graph- self.session_runner.run(queue_item=self._queue_item)+ self.workflow_call_queue_lifecycle.run_queue_item(self._queue_item)except Exception as e:error_type = e.__class__.__name__diff --git a/invokeai/app/services/session_processor/workflow_call_batch.py b/invokeai/app/services/session_processor/workflow_call_batch.pynew file mode 100644index 0000000000..01deee5d7a--- /dev/null+++ b/invokeai/app/services/session_processor/workflow_call_batch.py@@ -0,0 +1,725 @@+from __future__ import annotations++import copy+import json+import random+from collections.abc import Mapping, Sequence+from dataclasses import dataclass+from typing import Any++from dynamicprompts.generators import CombinatorialPromptGenerator, RandomPromptGenerator++from invokeai.app.invocations.fields import ImageField+from invokeai.app.services.board_records.board_records_common import BoardRecordOrderBy, BoardVisibility+from invokeai.app.services.image_records.image_records_common import ASSETS_CATEGORIES, IMAGE_CATEGORIES+from invokeai.app.services.session_queue.session_queue_common import (+ Batch,+ BatchDatum,+ NodeFieldValue,+ TooManySessionsError,+ calc_session_count,+ create_session_nfv_tuples,+)+from invokeai.app.services.shared.graph import GraphExecutionState, WorkflowCallFrame+from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection+from invokeai.app.services.shared.workflow_graph_builder import (+ UnsupportedWorkflowNodeError,+ apply_workflow_inputs_to_workflow,+ build_graph_from_workflow,+)++BATCH_FIELD_NAMES = {+ "image_batch": "images",+ "string_batch": "strings",+ "integer_batch": "integers",+ "float_batch": "floats",+}+SUPPORTED_BATCH_TYPES = set(BATCH_FIELD_NAMES)+SUPPORTED_BATCH_GROUP_IDS = {+ "None",+ "Group 1",+ "Group 2",+ "Group 3",+ "Group 4",+ "Group 5",+}+CONNECTOR_INPUT_HANDLE = "in"+++@dataclass(frozen=True)+class WorkflowCallChildSessionResult:+ session: GraphExecutionState+ field_values: list[NodeFieldValue] | None = None+++def _is_mapping(value: Any) -> bool:+ return isinstance(value, Mapping)+++def _is_invocation_node(node: Any) -> bool:+ return _is_mapping(node) and node.get("type") == "invocation" and _is_mapping(node.get("data"))+++def _is_connector_node(node: Any) -> bool:+ return _is_mapping(node) and node.get("type") == "connector"+++def workflow_contains_supported_batch_nodes(workflow: Mapping[str, Any]) -> bool:+ workflow_nodes = workflow.get("nodes", [])+ if not isinstance(workflow_nodes, Sequence):+ return False+ return any(+ _is_invocation_node(node) and node["data"].get("type") in SUPPORTED_BATCH_TYPES for node in workflow_nodes+ )+++def _get_workflow_nodes(workflow: Mapping[str, Any]) -> dict[str, Mapping[str, Any]]:+ workflow_nodes = workflow.get("nodes", [])+ if not isinstance(workflow_nodes, Sequence):+ return {}+ return {node["id"]: node for node in workflow_nodes if _is_mapping(node) and isinstance(node.get("id"), str)}+++def _get_default_edges(workflow: Mapping[str, Any]) -> list[Mapping[str, Any]]:+ workflow_edges = workflow.get("edges", [])+ if not isinstance(workflow_edges, Sequence):+ return []+ return [edge for edge in workflow_edges if _is_mapping(edge) and edge.get("type") == "default"]+++def _get_connector_input_edge(+ connector_id: str, workflow_edges: Sequence[Mapping[str, Any]]+) -> Mapping[str, Any] | None:+ return next(+ (+ edge+ for edge in workflow_edges+ if edge.get("target") == connector_id and edge.get("targetHandle") == CONNECTOR_INPUT_HANDLE+ ),+ None,+ )+++def _resolve_connector_source(+ connector_id: str, workflow_nodes: Mapping[str, Mapping[str, Any]], workflow_edges: Sequence[Mapping[str, Any]]+) -> tuple[str, str] | None:+ visited: set[str] = set()++ def resolve(node_id: str) -> tuple[str, str] | None:+ if node_id in visited:+ return None+ visited.add(node_id)++ incoming_edge = _get_connector_input_edge(node_id, workflow_edges)+ if incoming_edge is None:+ return None++ source_id = incoming_edge.get("source")+ source_handle = incoming_edge.get("sourceHandle")+ if not isinstance(source_id, str) or not isinstance(source_handle, str):+ return None++ source_node = workflow_nodes.get(source_id)+ if source_node is None:+ return None++ if _is_invocation_node(source_node):+ return (source_id, source_handle)++ if _is_connector_node(source_node):+ return resolve(source_id)++ return None++ return resolve(connector_id)+++def _build_child_graph_workflow(workflow: Mapping[str, Any], used_generator_node_ids: set[str]) -> dict[str, Any]:+ workflow_nodes = workflow.get("nodes", [])+ workflow_edges = workflow.get("edges", [])+ if not isinstance(workflow_nodes, list) or not isinstance(workflow_edges, list):+ raise UnsupportedWorkflowNodeError("call_saved_workflow child workflow is malformed")++ filtered_nodes = [+ node+ for node in workflow_nodes+ if not (+ _is_invocation_node(node)+ and (+ node["data"].get("type") in SUPPORTED_BATCH_TYPES+ or (isinstance(node.get("id"), str) and node["id"] in used_generator_node_ids)+ )+ )+ ]+ filtered_node_ids = {node["id"] for node in filtered_nodes if _is_mapping(node) and isinstance(node.get("id"), str)}+ filtered_edges = [+ edge+ for edge in workflow_edges+ if _is_mapping(edge)+ and edge.get("type") == "default"+ and edge.get("source") in filtered_node_ids+ and edge.get("target") in filtered_node_ids+ ]+ return {**workflow, "nodes": filtered_nodes, "edges": filtered_edges}+++def _reject_unrelated_generator_nodes(workflow: Mapping[str, Any], used_generator_node_ids: set[str]) -> None:+ workflow_nodes = workflow.get("nodes", [])+ if not isinstance(workflow_nodes, list):+ raise UnsupportedWorkflowNodeError("call_saved_workflow child workflow is malformed")++ unrelated_generator_nodes: list[tuple[str, str]] = []+ for node in workflow_nodes:+ if not _is_invocation_node(node):+ continue++ node_data = node["data"]+ node_id = node_data.get("id")+ node_type = node_data.get("type")+ if not isinstance(node_id, str) or not isinstance(node_type, str):+ continue+ if node_type.endswith("_generator") and node_id not in used_generator_node_ids:+ unrelated_generator_nodes.append((node_type, node_id))++ if unrelated_generator_nodes:+ unsupported_nodes = ", ".join(+ f"'{node_type}' (node '{node_id}')" for node_type, node_id in unrelated_generator_nodes+ )+ raise UnsupportedWorkflowNodeError(+ "call_saved_workflow does not yet support child workflows that mix supported batch nodes with "+ f"unrelated generator nodes: {unsupported_nodes}"+ )+++def _get_batch_group_id(node_data: Mapping[str, Any]) -> str:+ inputs = node_data.get("inputs")+ if not _is_mapping(inputs):+ return "None"+ batch_group_input = inputs.get("batch_group_id")+ if not _is_mapping(batch_group_input):+ return "None"+ batch_group_id = batch_group_input.get("value")+ if not isinstance(batch_group_id, str):+ return "None"+ if batch_group_id not in SUPPORTED_BATCH_GROUP_IDS:+ raise UnsupportedWorkflowNodeError(f"Unsupported batch group id '{batch_group_id}' in called workflow")+ return batch_group_id+++def _get_batch_items(node_data: Mapping[str, Any], field_name: str) -> list[Any]:+ inputs = node_data.get("inputs")+ if not _is_mapping(inputs):+ raise UnsupportedWorkflowNodeError("call_saved_workflow batch child workflow node inputs are malformed")+ batch_input = inputs.get(field_name)+ if not _is_mapping(batch_input):+ raise UnsupportedWorkflowNodeError(+ f"call_saved_workflow batch child workflow node is missing required '{field_name}' input"+ )+ batch_items = batch_input.get("value")+ if not isinstance(batch_items, list):+ raise UnsupportedWorkflowNodeError(+ f"call_saved_workflow batch child workflow node '{node_data.get('id')}' must provide a direct list for '{field_name}'"+ )+ return batch_items+++def _parse_split_values(input_value: str, split_on: str) -> list[str]:+ if split_on == "":+ return [input_value]+ try:+ return input_value.split(json.loads(f'"{split_on}"'))+ except Exception:+ return input_value.split(split_on)+++def _resolve_float_generator(value: Mapping[str, Any]) -> list[float]:+ generator_type = value.get("type")+ if generator_type == "float_generator_arithmetic_sequence":+ start = float(value.get("start", 0))+ step = float(value.get("step", 1))+ count = int(value.get("count", 10))+ if step == 0:+ return [start]+ return [start + i * step for i in range(count)]+ if generator_type == "float_generator_linear_distribution":+ start = float(value.get("start", 0))+ end = float(value.get("end", 1))+ count = int(value.get("count", 10))+ if count == 1:+ return [start]+ return [start + (end - start) * (i / (count - 1)) for i in range(count)]+ if generator_type == "float_generator_random_distribution_uniform":+ minimum = float(value.get("min", 0))+ maximum = float(value.get("max", 1))+ count = int(value.get("count", 10))+ if "values" in value and isinstance(value["values"], list):+ return [float(v) for v in value["values"]]+ rng = random.Random(value.get("seed"))+ return [rng.random() * (maximum - minimum) + minimum for _ in range(count)]+ if generator_type == "float_generator_parse_string":+ if "values" in value and isinstance(value["values"], list):+ return [float(v) for v in value["values"]]+ split_values = _parse_split_values(str(value.get("input", "")), str(value.get("splitOn", ",")))+ return [float(v.strip()) for v in split_values if v.strip()]+ raise UnsupportedWorkflowNodeError(f"Unsupported float generator type '{generator_type}'")+++def _resolve_integer_generator(value: Mapping[str, Any]) -> list[int]:+ generator_type = value.get("type")+ if generator_type == "integer_generator_arithmetic_sequence":+ start = int(value.get("start", 0))+ step = int(value.get("step", 1))+ count = int(value.get("count", 10))+ if step == 0:+ return [start]+ return [start + i * step for i in range(count)]+ if generator_type == "integer_generator_linear_distribution":+ start = int(value.get("start", 0))+ end = int(value.get("end", 10))+ count = int(value.get("count", 10))+ if count == 1:+ return [start]+ return [start + round((end - start) * (i / (count - 1))) for i in range(count)]+ if generator_type == "integer_generator_random_distribution_uniform":+ minimum = int(value.get("min", 0))+ maximum = int(value.get("max", 10))+ count = int(value.get("count", 10))+ rng = random.Random(value.get("seed"))+ return [int(rng.random() * (maximum - minimum + 1)) + minimum for _ in range(count)]+ if generator_type == "integer_generator_parse_string":+ split_values = _parse_split_values(str(value.get("input", "")), str(value.get("splitOn", ",")))+ return [int(v.strip()) for v in split_values if v.strip()]+ raise UnsupportedWorkflowNodeError(f"Unsupported integer generator type '{generator_type}'")+++def _resolve_string_generator(value: Mapping[str, Any]) -> list[str]:+ generator_type = value.get("type")+ if generator_type == "string_generator_parse_string":+ return [v for v in _parse_split_values(str(value.get("input", "")), str(value.get("splitOn", ","))) if v]+ if generator_type == "string_generator_dynamic_prompts_combinatorial":+ generator = CombinatorialPromptGenerator()+ return list(generator.generate(str(value.get("input", "")), max_prompts=int(value.get("maxPrompts", 10))))+ if generator_type == "string_generator_dynamic_prompts_random":+ seed = value.get("seed")+ if seed is None:+ seed = random.randint(0, 2**31 - 1)+ generator = RandomPromptGenerator(seed=int(seed))+ return list(generator.generate(str(value.get("input", "")), num_images=int(value.get("count", 10))))+ raise UnsupportedWorkflowNodeError(f"Unsupported string generator type '{generator_type}'")+++def _assert_user_can_access_board(board_id: str, services: Any, user_id: str | None) -> None:+ if not user_id:+ return++ board_records = getattr(services, "board_records", None)+ if board_records is None or not hasattr(board_records, "get"):+ return++ users = getattr(services, "users", None)+ user = users.get(user_id) if users is not None and hasattr(users, "get") else None+ is_admin = bool(user and getattr(user, "is_admin", False))+ if is_admin:+ return++ try:+ board_record = board_records.get(board_id)+ except Exception as e:+ raise UnsupportedWorkflowNodeError(+ f"call_saved_workflow could not access board '{board_id}' for image generator expansion"+ ) from e++ if getattr(board_record, "user_id", None) == user_id:+ return++ board_visibility = getattr(board_record, "board_visibility", BoardVisibility.Private)+ if isinstance(board_visibility, str):+ try:+ board_visibility = BoardVisibility(board_visibility)+ except ValueError:+ board_visibility = BoardVisibility.Private+ if board_visibility in {BoardVisibility.Shared, BoardVisibility.Public}:+ return++ if hasattr(board_records, "get_all"):+ try:+ accessible_boards = board_records.get_all(+ user_id=user_id,+ is_admin=False,+ order_by=BoardRecordOrderBy.Name,+ direction=SQLiteDirection.Ascending,+ include_archived=True,+ )+ except Exception:+ accessible_boards = []+ if any(getattr(board, "board_id", None) == board_id for board in accessible_boards):+ return++ raise UnsupportedWorkflowNodeError(+ f"call_saved_workflow caller does not have access to board '{board_id}' for image generator expansion"+ )+++def _resolve_image_generator(value: Mapping[str, Any], services: Any, user_id: str | None) -> list[ImageField]:+ generator_type = value.get("type")+ if generator_type != "image_generator_images_from_board":+ raise UnsupportedWorkflowNodeError(f"Unsupported image generator type '{generator_type}'")+ board_id = value.get("board_id")+ if not isinstance(board_id, str) or not board_id:+ return []+ _assert_user_can_access_board(board_id, services, user_id)+ category = value.get("category", "images")+ categories = IMAGE_CATEGORIES if category == "images" else ASSETS_CATEGORIES+ image_names = services.board_images.get_all_board_image_names_for_board(+ board_id=board_id,+ categories=categories,+ is_intermediate=False,+ )+ return [ImageField(image_name=image_name) for image_name in image_names]+++def _get_declared_generator_item_count(value: Mapping[str, Any]) -> int | None:+ explicit_values = value.get("values")+ if isinstance(explicit_values, list):+ return len(explicit_values)+ if value.get("type") == "string_generator_dynamic_prompts_combinatorial":+ return int(value.get("maxPrompts", 10))+ if value.get("type") in {+ "float_generator_arithmetic_sequence",+ "float_generator_linear_distribution",+ "float_generator_random_distribution_uniform",+ "integer_generator_arithmetic_sequence",+ "integer_generator_linear_distribution",+ "integer_generator_random_distribution_uniform",+ "string_generator_dynamic_prompts_random",+ }:+ return int(value.get("count", 10))+ return None+++def _resolve_generator_items(+ generator_node: Mapping[str, Any], services: Any, user_id: str | None, maximum_items: int+) -> list[Any]:+ generator_node_data = generator_node["data"]+ node_type = generator_node_data.get("type")+ inputs = generator_node_data.get("inputs")+ if not isinstance(node_type, str) or not _is_mapping(inputs):+ raise UnsupportedWorkflowNodeError("call_saved_workflow generator node is malformed")+ generator_input = inputs.get("generator")+ if not _is_mapping(generator_input):+ raise UnsupportedWorkflowNodeError(+ f"call_saved_workflow generator node '{generator_node_data.get('id')}' is missing generator input"+ )+ generator_value = generator_input.get("value")+ if not _is_mapping(generator_value):+ raise UnsupportedWorkflowNodeError(+ f"call_saved_workflow generator node '{generator_node_data.get('id')}' has invalid generator value"+ )+ declared_item_count = _get_declared_generator_item_count(generator_value)+ if declared_item_count is not None and declared_item_count > maximum_items:+ raise TooManySessionsError("call_saved_workflow exceeds remaining queue capacity for child workflow executions")+ if node_type == "integer_generator":+ return _resolve_integer_generator(generator_value)+ if node_type == "float_generator":+ return _resolve_float_generator(generator_value)+ if node_type == "string_generator":+ return _resolve_string_generator(generator_value)+ if node_type == "image_generator":+ return _resolve_image_generator(generator_value, services, user_id)+ raise UnsupportedWorkflowNodeError(f"Unsupported generator node type '{node_type}'")+++def _get_generator_placeholder_items(generator_node: Mapping[str, Any]) -> list[Any]:+ generator_node_data = generator_node["data"]+ node_type = generator_node_data.get("type")+ if node_type == "integer_generator":+ return [0]+ if node_type == "float_generator":+ return [0.0]+ if node_type == "string_generator":+ return [""]+ if node_type == "image_generator":+ return [ImageField(image_name="compatibility-placeholder")]+ raise UnsupportedWorkflowNodeError(f"Unsupported generator node type '{node_type}'")+++def _get_outgoing_default_edges(+ node_id: str, source_handle: str, workflow_edges: Sequence[Mapping[str, Any]]+) -> list[Mapping[str, Any]]:+ return [+ edge+ for edge in workflow_edges+ if edge.get("source") == node_id and edge.get("sourceHandle") == source_handle and edge.get("type") == "default"+ ]+++def _resolve_connector_destinations(+ connector_id: str, workflow_nodes: Mapping[str, Mapping[str, Any]], workflow_edges: Sequence[Mapping[str, Any]]+) -> list[tuple[str, str]]:+ visited: set[str] = set()+ destinations: list[tuple[str, str]] = []+ stack = [connector_id]+ while stack:+ current_id = stack.pop()+ if current_id in visited:+ continue+ visited.add(current_id)+ outgoing_edges = _get_outgoing_default_edges(current_id, "out", workflow_edges)+ for edge in outgoing_edges:+ target_id = edge.get("target")+ target_handle = edge.get("targetHandle")+ if not isinstance(target_id, str) or not isinstance(target_handle, str):+ continue+ target_node = workflow_nodes.get(target_id)+ if target_node is None:+ continue+ if _is_invocation_node(target_node):+ destinations.append((target_id, target_handle))+ elif _is_connector_node(target_node):+ stack.append(target_id)+ return destinations+++def _resolve_batch_destinations(+ node_id: str,+ source_handle: str,+ workflow_nodes: Mapping[str, Mapping[str, Any]],+ workflow_edges: Sequence[Mapping[str, Any]],+) -> list[tuple[str, str]]:+ destinations: list[tuple[str, str]] = []+ for edge in _get_outgoing_default_edges(node_id, source_handle, workflow_edges):+ target_id = edge.get("target")+ target_handle = edge.get("targetHandle")+ if not isinstance(target_id, str) or not isinstance(target_handle, str):+ continue+ target_node = workflow_nodes.get(target_id)+ if target_node is None:+ continue+ if _is_invocation_node(target_node):+ destinations.append((target_id, target_handle))+ elif _is_connector_node(target_node):+ destinations.extend(_resolve_connector_destinations(target_id, workflow_nodes, workflow_edges))+ return destinations+++def _normalize_batch_item_for_destination(destination_field: str, batch_items: list[Any]) -> list[Any]:+ if destination_field == "collection":+ return [[item] for item in batch_items]+ return batch_items+++def _resolve_batch_items_from_inputs(+ node_id: str,+ field_name: str,+ workflow_edges: Sequence[Mapping[str, Any]],+ workflow_nodes: Mapping[str, Mapping[str, Any]],+) -> list[Any] | None:+ incoming_edges = [+ edge+ for edge in workflow_edges+ if edge.get("target") == node_id and edge.get("targetHandle") == field_name and edge.get("type") == "default"+ ]+ if not incoming_edges:+ return None+ incoming_source_ids = [edge.get("source") for edge in incoming_edges if isinstance(edge.get("source"), str)]+ if len(incoming_source_ids) != 1:+ raise UnsupportedWorkflowNodeError(+ f"call_saved_workflow does not yet support multiple connected batch inputs on node '{node_id}'"+ )+ source_id = incoming_source_ids[0]+ source_node = workflow_nodes.get(source_id)+ if _is_invocation_node(source_node) and source_node["data"].get("type", "").endswith("_generator"):+ return source_id+ if _is_connector_node(source_node):+ resolved_source = _resolve_connector_source(source_id, workflow_nodes, workflow_edges)+ if resolved_source is not None:+ resolved_source_id, _resolved_source_handle = resolved_source+ resolved_source_node = workflow_nodes.get(resolved_source_id)+ if _is_invocation_node(resolved_source_node) and resolved_source_node["data"].get("type", "").endswith(+ "_generator"+ ):+ return resolved_source_id+ raise UnsupportedWorkflowNodeError(+ f"call_saved_workflow does not yet support connected batch child workflow inputs on node '{node_id}'"+ )+++def build_batch_child_workflow_session_results(+ *,+ parent_session: GraphExecutionState,+ workflow: Mapping[str, Any],+ workflow_inputs: Mapping[str, Any],+ call_frame: WorkflowCallFrame,+ maximum_children: int,+ services: Any = None,+ user_id: str | None = None,+ resolve_generator_items: bool = True,+) -> list[GraphExecutionState]:+ mutable_workflow = copy.deepcopy(workflow)+ apply_workflow_inputs_to_workflow(mutable_workflow, workflow_inputs)++ workflow_nodes = _get_workflow_nodes(mutable_workflow)+ workflow_edges = _get_default_edges(mutable_workflow)++ batch_data_by_group: dict[str, list[BatchDatum]] = {}+ used_generator_node_ids: set[str] = set()+ for node in workflow_nodes.values():+ if not _is_invocation_node(node):+ continue+ node_data = node["data"]+ node_id = node_data.get("id")+ node_type = node_data.get("type")+ if not isinstance(node_id, str) or not isinstance(node_type, str):+ continue+ if node_type.endswith("_generator"):+ continue+ if node_type not in SUPPORTED_BATCH_TYPES:+ continue++ field_name = BATCH_FIELD_NAMES[node_type]+ generator_source_id = _resolve_batch_items_from_inputs(node_id, field_name, workflow_edges, workflow_nodes)+ if generator_source_id is not None:+ generator_node = workflow_nodes.get(generator_source_id)+ if generator_node is None:+ raise UnsupportedWorkflowNodeError(+ f"call_saved_workflow generator-backed batch child workflow is missing generator node '{generator_source_id}'"+ )+ generator_node_type = generator_node["data"].get("type") if _is_invocation_node(generator_node) else None+ if generator_node_type == "image_generator" and services is None and resolve_generator_items:+ raise UnsupportedWorkflowNodeError(+ "call_saved_workflow image-generator-backed batch child workflows require runtime services"+ )+ batch_items = (+ _resolve_generator_items(generator_node, services, user_id, maximum_children)+ if resolve_generator_items+ else _get_generator_placeholder_items(generator_node)+ )+ used_generator_node_ids.add(generator_source_id)+ if not batch_items:+ raise UnsupportedWorkflowNodeError(+ f"call_saved_workflow generator-backed batch child workflow node '{generator_source_id}' produced no batch items"+ )+ else:+ batch_items = _get_batch_items(node_data, field_name)+ if not batch_items:+ raise UnsupportedWorkflowNodeError(+ f"call_saved_workflow batch child workflow node '{node_id}' must provide at least one batch item"+ )+ batch_group_id = _get_batch_group_id(node_data)+ destinations = _resolve_batch_destinations(node_id, field_name, workflow_nodes, workflow_edges)+ if not destinations:+ raise UnsupportedWorkflowNodeError(+ f"call_saved_workflow batch child workflow node '{node_id}' is not connected to any invocation input"+ )+ group_batch_data = batch_data_by_group.setdefault(batch_group_id, [])+ for destination_node_id, destination_field in destinations:+ group_batch_data.append(+ BatchDatum(+ node_path=destination_node_id,+ field_name=destination_field,+ items=_normalize_batch_item_for_destination(destination_field, batch_items),+ )+ )++ if not batch_data_by_group:+ raise UnsupportedWorkflowNodeError("call_saved_workflow batch child workflow contains no supported batch nodes")++ _reject_unrelated_generator_nodes(mutable_workflow, used_generator_node_ids)+ sanitized_workflow = _build_child_graph_workflow(mutable_workflow, used_generator_node_ids)+ child_graph = build_graph_from_workflow(sanitized_workflow)+ batch_data = [[datum] for datum in batch_data_by_group.pop("None", [])]+ batch_data.extend(batch_data_by_group.values())+ batch = Batch(graph=child_graph, data=batch_data)+ if calc_session_count(batch) > maximum_children:+ raise TooManySessionsError("call_saved_workflow exceeds remaining queue capacity for child workflow executions")++ child_session_results: list[WorkflowCallChildSessionResult] = []+ for session_id, session_json, field_values_json in create_session_nfv_tuples(batch, maximum_children):+ generated_session = GraphExecutionState.model_validate_json(session_json)+ child_session = parent_session.create_child_workflow_execution_state(generated_session.graph, call_frame)+ child_session.id = session_id+ field_values = [NodeFieldValue.model_validate(field_value) for field_value in json.loads(field_values_json)]+ child_session_results.append(WorkflowCallChildSessionResult(session=child_session, field_values=field_values))+ return child_session_results+++def build_batch_child_workflow_sessions(+ *,+ parent_session: GraphExecutionState,+ workflow: Mapping[str, Any],+ workflow_inputs: Mapping[str, Any],+ call_frame: WorkflowCallFrame,+ maximum_children: int,+ services: Any = None,+ user_id: str | None = None,+ resolve_generator_items: bool = True,+) -> list[GraphExecutionState]:+ return [+ child_result.session+ for child_result in build_batch_child_workflow_session_results(+ parent_session=parent_session,+ workflow=workflow,+ workflow_inputs=workflow_inputs,+ call_frame=call_frame,+ maximum_children=maximum_children,+ services=services,+ user_id=user_id,+ resolve_generator_items=resolve_generator_items,+ )+ ]+++def build_child_workflow_session_results(+ *,+ parent_session: GraphExecutionState,+ workflow: Mapping[str, Any],+ workflow_inputs: Mapping[str, Any],+ call_frame: WorkflowCallFrame,+ maximum_children: int,+ services: Any = None,+ user_id: str | None = None,+ resolve_generator_items: bool = True,+) -> list[WorkflowCallChildSessionResult]:+ if workflow_contains_supported_batch_nodes(workflow):+ return build_batch_child_workflow_session_results(+ parent_session=parent_session,+ workflow=workflow,+ workflow_inputs=workflow_inputs,+ call_frame=call_frame,+ maximum_children=maximum_children,+ services=services,+ user_id=user_id,+ resolve_generator_items=resolve_generator_items,+ )++ mutable_workflow = copy.deepcopy(workflow)+ apply_workflow_inputs_to_workflow(mutable_workflow, workflow_inputs)+ child_graph = build_graph_from_workflow(mutable_workflow)+ child_session = parent_session.create_child_workflow_execution_state(child_graph, call_frame)+ return [WorkflowCallChildSessionResult(session=child_session)]+++def build_child_workflow_sessions(+ *,+ parent_session: GraphExecutionState,+ workflow: Mapping[str, Any],+ workflow_inputs: Mapping[str, Any],+ call_frame: WorkflowCallFrame,+ maximum_children: int,+ services: Any = None,+ user_id: str | None = None,+ resolve_generator_items: bool = True,+) -> list[GraphExecutionState]:+ return [+ child_result.session+ for child_result in build_child_workflow_session_results(+ parent_session=parent_session,+ workflow=workflow,+ workflow_inputs=workflow_inputs,+ call_frame=call_frame,+ maximum_children=maximum_children,+ services=services,+ user_id=user_id,+ resolve_generator_items=resolve_generator_items,+ )+ ]diff --git a/invokeai/app/services/session_processor/workflow_call_runtime.py b/invokeai/app/services/session_processor/workflow_call_runtime.pynew file mode 100644index 0000000000..dba1665048--- /dev/null+++ b/invokeai/app/services/session_processor/workflow_call_runtime.py@@ -0,0 +1,267 @@+from __future__ import annotations++from typing import TYPE_CHECKING, Any++from invokeai.app.invocations.call_saved_workflow import (+ CallSavedWorkflowInvocation,+ is_call_saved_workflow_dynamic_input,+)+from invokeai.app.invocations.workflow_return import WorkflowReturnOutput+from invokeai.app.services.session_processor.workflow_call_batch import build_child_workflow_session_results+from invokeai.app.services.session_queue.session_queue_common import NodeFieldValue, SessionQueueItem+from invokeai.app.services.shared.graph import GraphExecutionState++if TYPE_CHECKING:+ from invokeai.app.services.session_processor.session_processor_default import DefaultSessionRunner+++class WorkflowCallCoordinator:+ """Coordinates call-specific workflow setup."""++ def __init__(self, session_runner: DefaultSessionRunner) -> None:+ self._session_runner = session_runner++ def _collect_call_saved_workflow_inputs(+ self, invocation: CallSavedWorkflowInvocation, queue_item: SessionQueueItem+ ) -> dict[str, Any]:+ workflow_inputs = dict(invocation.workflow_inputs)+ for edge in queue_item.session.execution_graph._get_input_edges(invocation.id):+ if not is_call_saved_workflow_dynamic_input(edge.destination.field):+ continue+ if edge.source.node_id not in queue_item.session.results:+ continue+ workflow_inputs[edge.destination.field] = getattr(+ queue_item.session.results[edge.source.node_id], edge.source.field+ )+ return workflow_inputs++ @staticmethod+ def build_child_queue_item(+ queue_item: SessionQueueItem,+ child_session: GraphExecutionState,+ field_values: list[NodeFieldValue] | None = None,+ ) -> SessionQueueItem:+ workflow_call_execution = queue_item.session.waiting_workflow_call_execution+ if workflow_call_execution is None:+ raise ValueError("Parent queue item is missing active workflow call execution metadata.")+ root_item_id = getattr(queue_item, "root_item_id", None) or queue_item.item_id+ child_updates = {+ "session": child_session,+ "session_id": child_session.id,+ "workflow_call_id": workflow_call_execution.id,+ "parent_item_id": queue_item.item_id,+ "parent_session_id": queue_item.session_id,+ "root_item_id": root_item_id,+ "workflow_call_depth": workflow_call_execution.depth,+ "field_values": field_values,+ }+ if hasattr(queue_item, "model_copy"):+ return queue_item.model_copy(update=child_updates)++ child_queue_item = type(queue_item).__new__(type(queue_item))+ child_queue_item.__dict__ = {**queue_item.__dict__, **child_updates}+ return child_queue_item++ def begin_workflow_call_boundary(+ self,+ invocation: CallSavedWorkflowInvocation,+ queue_item: SessionQueueItem,+ workflow_record,+ ) -> SessionQueueItem:+ queue_status = self._session_runner._services.session_queue.get_queue_status(queue_item.queue_id)+ remaining_queue_capacity = self._session_runner._services.configuration.max_queue_size - queue_status.pending+ if remaining_queue_capacity <= 0:+ raise ValueError("call_saved_workflow exceeds remaining queue capacity for child workflow executions")++ call_frame = queue_item.session.build_workflow_call_frame(invocation.id, invocation.workflow_id)+ workflow_inputs = self._collect_call_saved_workflow_inputs(invocation, queue_item)+ child_session_results = build_child_workflow_session_results(+ parent_session=queue_item.session,+ workflow=workflow_record.workflow.model_dump(),+ workflow_inputs=workflow_inputs,+ call_frame=call_frame,+ maximum_children=remaining_queue_capacity,+ services=self._session_runner._services,+ user_id=getattr(queue_item, "user_id", None),+ )+ child_sessions = [child_result.session for child_result in child_session_results]+ if len(child_sessions) > remaining_queue_capacity:+ raise ValueError("call_saved_workflow exceeds remaining queue capacity for child workflow executions")+ queue_item.session.begin_waiting_on_workflow_call(call_frame)+ queue_item.session.attach_waiting_workflow_call_child_sessions(child_sessions)+ child_queue_item = None+ enqueued_child_item_ids: list[int] = []+ try:+ self._session_runner._services.session_queue.set_queue_item_session(queue_item.item_id, queue_item.session)+ for child_result in child_session_results:+ child_queue_item = self._session_runner._services.session_queue.enqueue_workflow_call_child(+ parent_queue_item=queue_item,+ child_session=child_result.session,+ field_values=child_result.field_values,+ )+ enqueued_child_item_ids.append(child_queue_item.item_id)+ queue_item.session.set_waiting_workflow_call_child_item_ids(enqueued_child_item_ids)+ self._session_runner._services.session_queue.set_queue_item_session(queue_item.item_id, queue_item.session)+ self._session_runner._services.session_queue.suspend_queue_item(queue_item.item_id)+ except Exception as e:+ if enqueued_child_item_ids:+ self._session_runner._services.session_queue.delete_queue_items_by_id(enqueued_child_item_ids)+ queue_item.session.end_waiting_on_workflow_call(status="failed", error_message=str(e))+ raise+ queue_item.status = "waiting"+ if child_queue_item is None:+ raise ValueError("Workflow call did not produce any child executions.")+ return child_queue_item+++class WorkflowCallQueueLifecycle:+ """Coordinates queue-visible child workflow execution and parent lifecycle transitions."""++ def __init__(self, session_runner: DefaultSessionRunner) -> None:+ self._session_runner = session_runner++ @staticmethod+ def get_waiting_workflow_call_invocation(queue_item: SessionQueueItem) -> CallSavedWorkflowInvocation:+ waiting_frame = queue_item.session.waiting_workflow_call+ if waiting_frame is None:+ raise ValueError("Execution state is not waiting on a workflow call.")+ invocation = queue_item.session.execution_graph.nodes.get(waiting_frame.prepared_call_node_id)+ if not isinstance(invocation, CallSavedWorkflowInvocation):+ raise ValueError("Waiting workflow call frame does not point to a call_saved_workflow invocation.")+ return invocation++ @staticmethod+ def get_child_workflow_return_output(child_session: GraphExecutionState) -> WorkflowReturnOutput:+ workflow_return_node_ids = [+ node_id for node_id, node in child_session.graph.nodes.items() if node.get_type() == "workflow_return"+ ]+ if not workflow_return_node_ids:+ raise ValueError("The selected saved workflow must contain exactly one workflow_return node.")+ if len(workflow_return_node_ids) > 1:+ raise ValueError("The selected saved workflow must not contain more than one workflow_return node.")++ workflow_return_node_id = workflow_return_node_ids[0]+ prepared_return_node_ids = child_session.source_prepared_mapping.get(workflow_return_node_id, set())+ if len(prepared_return_node_ids) != 1:+ raise ValueError(+ "The selected saved workflow produced an unsupported number of workflow_return executions."+ )++ prepared_return_node_id = next(iter(prepared_return_node_ids))+ output = child_session.results.get(prepared_return_node_id)+ if not isinstance(output, WorkflowReturnOutput):+ raise ValueError("The selected saved workflow did not produce a valid workflow_return output.")++ return output++ def resume_waiting_workflow_call(self, queue_item: SessionQueueItem) -> None:+ invocation = self.get_waiting_workflow_call_invocation(queue_item)+ child_session = queue_item.session.waiting_workflow_call_child_session+ if child_session is None:+ raise ValueError("Execution state is waiting on a workflow call but has no attached child session.")+ output = self.get_child_workflow_return_output(child_session)+ queue_item.session.end_waiting_on_workflow_call(status="completed")+ queue_item.session.complete(invocation.id, output)+ self._session_runner._on_after_run_node(invocation, queue_item, output)++ def fail_waiting_workflow_call(self, queue_item: SessionQueueItem, error_message: str) -> None:+ invocation = self.get_waiting_workflow_call_invocation(queue_item)+ queue_item.session.end_waiting_on_workflow_call(status="failed", error_message=error_message)+ self._session_runner._on_node_error(+ invocation=invocation,+ queue_item=queue_item,+ error_type="ValueError",+ error_message=error_message,+ error_traceback=error_message,+ )++ def _get_parent_queue_item(self, child_queue_item: SessionQueueItem) -> SessionQueueItem:+ parent_item_id = child_queue_item.parent_item_id+ if parent_item_id is None:+ raise ValueError("Child workflow queue item is missing parent_item_id metadata.")+ return self._session_runner._services.session_queue.get_queue_item(parent_item_id)++ def _resume_parent_from_completed_child(self, child_queue_item: SessionQueueItem) -> None:+ parent_queue_item = self._get_parent_queue_item(child_queue_item)+ if parent_queue_item.status in ("completed", "failed", "canceled"):+ return+ try:+ output = self.get_child_workflow_return_output(child_queue_item.session)+ should_resume_parent, aggregated_values = (+ parent_queue_item.session.record_waiting_workflow_call_child_completion(+ child_queue_item.item_id, output.values+ )+ )+ except Exception as e:+ workflow_call_execution = parent_queue_item.session.waiting_workflow_call_execution+ if workflow_call_execution is not None:+ self._session_runner._services.session_queue.cancel_workflow_call_children(+ workflow_call_execution.id,+ exclude_item_ids={child_queue_item.item_id},+ )+ self.fail_waiting_workflow_call(parent_queue_item, str(e))+ parent_queue_item = self._session_runner._services.session_queue.get_queue_item(parent_queue_item.item_id)+ if getattr(parent_queue_item, "parent_item_id", None) is not None:+ self._fail_parent_from_failed_child(parent_queue_item)+ return+ if not should_resume_parent:+ self._session_runner._services.session_queue.set_queue_item_session(+ parent_queue_item.item_id, parent_queue_item.session+ )+ return+ parent_queue_item.session.waiting_workflow_call_child_session = child_queue_item.session+ waiting_invocation = self.get_waiting_workflow_call_invocation(parent_queue_item)+ parent_queue_item.session.end_waiting_on_workflow_call(status="completed")+ parent_output = WorkflowReturnOutput(values=aggregated_values)+ parent_queue_item.session.complete(waiting_invocation.id, parent_output)+ self._session_runner._on_after_run_node(waiting_invocation, parent_queue_item, parent_output)+ parent_queue_item = self._session_runner._services.session_queue.set_queue_item_session(+ parent_queue_item.item_id, parent_queue_item.session+ )+ if parent_queue_item.session.is_complete():+ parent_queue_item = self._session_runner._services.session_queue.complete_queue_item(+ parent_queue_item.item_id+ )+ if getattr(parent_queue_item, "parent_item_id", None) is not None:+ self._resume_parent_from_completed_child(parent_queue_item)+ return+ self._session_runner._services.session_queue.resume_queue_item(parent_queue_item.item_id)++ def _fail_parent_from_failed_child(self, child_queue_item: SessionQueueItem) -> None:+ parent_queue_item = self._get_parent_queue_item(child_queue_item)+ if parent_queue_item.status in ("completed", "failed", "canceled"):+ return+ waiting_frame = parent_queue_item.session.waiting_workflow_call+ if waiting_frame is None:+ raise ValueError("Parent queue item is missing workflow call waiting state.")+ workflow_call_execution = parent_queue_item.session.waiting_workflow_call_execution+ if workflow_call_execution is not None:+ self._session_runner._services.session_queue.cancel_workflow_call_children(+ workflow_call_execution.id,+ exclude_item_ids={child_queue_item.item_id},+ )+ child_error_message = getattr(child_queue_item, "error_message", None) or (+ f"The selected saved workflow '{waiting_frame.workflow_id}' failed during child execution."+ )+ self.fail_waiting_workflow_call(parent_queue_item, child_error_message)+ parent_queue_item = self._session_runner._services.session_queue.get_queue_item(parent_queue_item.item_id)+ if getattr(parent_queue_item, "parent_item_id", None) is not None:+ self._fail_parent_from_failed_child(parent_queue_item)++ def _cancel_parent_from_canceled_child(self, child_queue_item: SessionQueueItem) -> None:+ parent_queue_item = self._get_parent_queue_item(child_queue_item)+ if parent_queue_item.status == "canceled":+ return+ self._session_runner._services.session_queue.cancel_queue_item(parent_queue_item.item_id)++ def run_queue_item(self, queue_item: SessionQueueItem) -> None:+ self._session_runner.run(queue_item)+ updated_queue_item = self._session_runner._services.session_queue.get_queue_item(queue_item.item_id)+ if getattr(updated_queue_item, "parent_item_id", None) is None:+ return+ if updated_queue_item.status == "completed":+ self._resume_parent_from_completed_child(updated_queue_item)+ elif updated_queue_item.status == "failed":+ self._fail_parent_from_failed_child(updated_queue_item)+ elif updated_queue_item.status == "canceled":+ self._cancel_parent_from_canceled_child(updated_queue_item)diff --git a/invokeai/app/services/session_queue/session_queue_base.py b/invokeai/app/services/session_queue/session_queue_base.pyindex bb7971cf90..a07abf10ee 100644--- a/invokeai/app/services/session_queue/session_queue_base.py+++ b/invokeai/app/services/session_queue/session_queue_base.py@@ -16,6 +16,7 @@ from invokeai.app.services.session_queue.session_queue_common import (IsEmptyResult,IsFullResult,ItemIdsResult,+ NodeFieldValue,PruneResult,RetryItemsResult,SessionQueueCountsByDestination,@@ -110,6 +111,16 @@ class SessionQueueBase(ABC):"""Completes a session queue item"""pass+ @abstractmethod+ def suspend_queue_item(self, item_id: int) -> SessionQueueItem:+ """Suspends a session queue item while waiting on a child workflow execution."""+ pass++ @abstractmethod+ def resume_queue_item(self, item_id: int) -> SessionQueueItem:+ """Resumes a suspended session queue item by returning it to pending state."""+ pass+@abstractmethoddef cancel_queue_item(self, item_id: int) -> SessionQueueItem:"""Cancels a session queue item"""@@ -120,6 +131,11 @@ class SessionQueueBase(ABC):"""Deletes a session queue item"""pass+ @abstractmethod+ def delete_queue_items_by_id(self, item_ids: list[int]) -> None:+ """Deletes session queue items by ID."""+ pass+@abstractmethoddef fail_queue_item(self, item_id: int, error_type: str, error_message: str, error_traceback: str@@ -205,6 +221,23 @@ class SessionQueueBase(ABC):"""Sets the session for a session queue item. Use this to update the session state."""pass+ @abstractmethod+ def enqueue_workflow_call_child(+ self,+ parent_queue_item: SessionQueueItem,+ child_session: GraphExecutionState,+ field_values: list[NodeFieldValue] | None = None,+ ) -> SessionQueueItem:+ """Enqueues a child workflow execution linked to a suspended parent queue item."""+ pass++ @abstractmethod+ def cancel_workflow_call_children(+ self, workflow_call_id: str, exclude_item_ids: set[int] | None = None+ ) -> list[int]:+ """Cancels child workflow queue items for a workflow call without canceling the waiting parent chain."""+ pass+@abstractmethoddef retry_items_by_id(self, queue_id: str, item_ids: list[int]) -> RetryItemsResult:"""Retries the given queue items"""diff --git a/invokeai/app/services/session_queue/session_queue_common.py b/invokeai/app/services/session_queue/session_queue_common.pyindex 54bf9158af..8d068b3fa6 100644--- a/invokeai/app/services/session_queue/session_queue_common.py+++ b/invokeai/app/services/session_queue/session_queue_common.py@@ -51,7 +51,8 @@ class SessionQueueItemNotFoundError(ValueError):# region Batch-BatchDataType = Union[StrictStr, float, int, ImageField]+BatchScalarDataType = Union[StrictStr, float, int, ImageField]+BatchDataType = Union[BatchScalarDataType, list[BatchScalarDataType]]class NodeFieldValue(BaseModel):@@ -172,7 +173,7 @@ class Batch(BaseModel):DEFAULT_QUEUE_ID = "default"SYSTEM_USER_ID = "system" # Default user_id for system-generated queue items-QUEUE_ITEM_STATUS = Literal["pending", "in_progress", "completed", "failed", "canceled"]+QUEUE_ITEM_STATUS = Literal["pending", "in_progress", "waiting", "completed", "failed", "canceled"]class ItemIdsResult(BaseModel):@@ -262,6 +263,21 @@ class SessionQueueItem(BaseModel):retried_from_item_id: Optional[int] = Field(default=None, description="The item_id of the queue item that this item was retried from")+ workflow_call_id: Optional[str] = Field(+ default=None, description="The active workflow-call relationship id when this queue item is a child execution."+ )+ parent_item_id: Optional[int] = Field(+ default=None, description="The parent queue item id when this queue item is a child workflow execution."+ )+ parent_session_id: Optional[str] = Field(+ default=None, description="The parent session id when this queue item is a child workflow execution."+ )+ root_item_id: Optional[int] = Field(+ default=None, description="The root queue item id for this workflow call chain, if any."+ )+ workflow_call_depth: Optional[int] = Field(+ default=None, description="The 1-based workflow-call depth for this queue item when it is a child execution."+ )session: GraphExecutionState = Field(description="The fully-populated session to be executed")workflow: Optional[WorkflowWithoutID] = Field(default=None, description="The workflow associated with this queue item"@@ -305,6 +321,7 @@ class SessionQueueStatus(BaseModel):session_id: Optional[str] = Field(description="The current queue item's session id")pending: int = Field(..., description="Number of queue items with status 'pending'")in_progress: int = Field(..., description="Number of queue items with status 'in_progress'")+ waiting: int = Field(..., description="Number of queue items with status 'waiting'")completed: int = Field(..., description="Number of queue items with status 'complete'")failed: int = Field(..., description="Number of queue items with status 'error'")canceled: int = Field(..., description="Number of queue items with status 'canceled'")@@ -324,6 +341,7 @@ class SessionQueueCountsByDestination(BaseModel):destination: str = Field(..., description="The destination of queue items included in this status")pending: int = Field(..., description="Number of queue items with status 'pending' for the destination")in_progress: int = Field(..., description="Number of queue items with status 'in_progress' for the destination")+ waiting: int = Field(..., description="Number of queue items with status 'waiting' for the destination")completed: int = Field(..., description="Number of queue items with status 'complete' for the destination")failed: int = Field(..., description="Number of queue items with status 'error' for the destination")canceled: int = Field(..., description="Number of queue items with status 'canceled' for the destination")@@ -337,6 +355,7 @@ class BatchStatus(BaseModel):destination: str | None = Field(..., description="The destination of the batch")pending: int = Field(..., description="Number of queue items with status 'pending'")in_progress: int = Field(..., description="Number of queue items with status 'in_progress'")+ waiting: int = Field(..., description="Number of queue items with status 'waiting'")completed: int = Field(..., description="Number of queue items with status 'complete'")failed: int = Field(..., description="Number of queue items with status 'error'")canceled: int = Field(..., description="Number of queue items with status 'canceled'")@@ -564,15 +583,11 @@ def calc_session_count(batch: Batch) -> int:# TODO: Should this be a class method on Batch?if not batch.data:return batch.runs- data = []+ session_count = batch.runsfor batch_datum_list in batch.data:- to_zip = []- for batch_datum in batch_datum_list:- batch_data_items = range(len(batch_datum.items))- to_zip.append(batch_data_items)- data.append(list(zip(*to_zip, strict=True)))- data_product = list(product(*data))- return len(data_product) * batch.runs+ group_length = len(batch_datum_list[0].items) if batch_datum_list else 0+ session_count *= group_length+ return session_countValueToInsertTuple: TypeAlias = tuple[diff --git a/invokeai/app/services/session_queue/session_queue_sqlite.py b/invokeai/app/services/session_queue/session_queue_sqlite.pyindex ca9c1ca607..5307932289 100644--- a/invokeai/app/services/session_queue/session_queue_sqlite.py+++ b/invokeai/app/services/session_queue/session_queue_sqlite.py@@ -1,7 +1,7 @@import asyncioimport jsonimport sqlite3-from typing import Optional, Union, cast+from typing import Any, Optional, Union, castfrom pydantic_core import to_jsonable_python@@ -23,12 +23,14 @@ from invokeai.app.services.session_queue.session_queue_common import (IsEmptyResult,IsFullResult,ItemIdsResult,+ NodeFieldValue,PruneResult,RetryItemsResult,SessionQueueCountsByDestination,SessionQueueItem,SessionQueueItemNotFoundError,SessionQueueStatus,+ TooManySessionsError,ValueToInsertTuple,calc_session_count,prepare_values_to_insert,@@ -126,17 +128,40 @@ class SqliteSessionQueue(SessionQueueBase):def _set_in_progress_to_canceled(self) -> None:"""- Sets all in_progress queue items to canceled. Run on app startup, not associated with any queue.- This is necessary because the invoker may have been killed while processing a queue item.+ Sets all in_progress or waiting queue items to canceled. Run on app startup, not associated with any queue.+ This is necessary because the invoker may have been killed while processing a queue item or while a parent+ queue item was suspended waiting on a child workflow execution."""with self._db.transaction() as cursor:cursor.execute("""--sql+ SELECT item_id+ FROM session_queue+ WHERE status = 'in_progress'+ OR status = 'waiting';+ """+ )+ interrupted_item_ids = [row[0] for row in cast(list[sqlite3.Row], cursor.fetchall())]+ item_ids_to_cancel: set[int] = set()+ for item_id in interrupted_item_ids:+ item_ids_to_cancel.update(self._get_workflow_call_chain_item_ids(item_id))+ if not item_ids_to_cancel:+ return+ with self._db.transaction() as cursor:+ placeholders = ",".join("?" for _ in item_ids_to_cancel)+ cursor.execute(+ f"""--sqlUPDATE session_queueSET status = 'canceled',status_sequence = COALESCE(status_sequence, 0) + 1- WHERE status = 'in_progress';- """+ WHERE item_id IN ({placeholders})+ AND (+ status = 'pending'+ OR status = 'in_progress'+ OR status = 'waiting'+ );+ """,+ tuple(item_ids_to_cancel),)def _prune_terminal_to_limit(self, queue_id: str, keep: int) -> int:@@ -379,6 +404,72 @@ class SqliteSessionQueue(SessionQueueBase):self.__invoker.services.events.emit_queue_item_status_changed(queue_item, batch_status, queue_status)return queue_item+ def _get_workflow_call_child_ids(self, item_id: int) -> list[int]:+ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ SELECT item_id+ FROM session_queue+ WHERE parent_item_id = ?+ ORDER BY item_id ASC+ """,+ (item_id,),+ )+ rows = cast(list[sqlite3.Row], cursor.fetchall())+ return [row[0] for row in rows]++ def _get_workflow_call_descendant_ids(self, item_id: int) -> list[int]:+ descendant_ids: list[int] = []+ queue: list[int] = [item_id]+ while queue:+ current_item_id = queue.pop(0)+ child_ids = self._get_workflow_call_child_ids(current_item_id)+ descendant_ids.extend(child_ids)+ queue.extend(child_ids)+ return descendant_ids++ def _get_workflow_call_ancestor_ids(self, item_id: int) -> list[int]:+ ancestor_ids: list[int] = []+ current_queue_item = self.get_queue_item(item_id)+ while current_queue_item.parent_item_id is not None:+ parent_item_id = current_queue_item.parent_item_id+ ancestor_ids.append(parent_item_id)+ current_queue_item = self.get_queue_item(parent_item_id)+ return ancestor_ids++ def _get_workflow_call_chain_item_ids(self, item_id: int) -> list[int]:+ ancestor_ids = self._get_workflow_call_ancestor_ids(item_id)+ root_item_id = ancestor_ids[-1] if ancestor_ids else item_id+ descendant_ids = self._get_workflow_call_descendant_ids(root_item_id)+ chain_item_ids = ancestor_ids + [item_id] + descendant_ids+ deduped_chain_item_ids = list(dict.fromkeys(chain_item_ids))+ return deduped_chain_item_ids++ def _get_current_workflow_call_chain_item_ids(self, queue_id: str) -> set[int]:+ current_queue_item = self.get_current(queue_id)+ if current_queue_item is not None:+ return set(self._get_workflow_call_chain_item_ids(current_queue_item.item_id))++ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ SELECT child.item_id+ FROM session_queue child+ JOIN session_queue parent ON parent.item_id = child.parent_item_id+ WHERE+ child.queue_id = ?+ AND child.status = 'pending'+ AND parent.status = 'waiting'+ ORDER BY child.priority DESC, child.created_at ASC, child.item_id ASC+ LIMIT 1+ """,+ (queue_id,),+ )+ row = cursor.fetchone()+ if row is None:+ return set()+ return set(self._get_workflow_call_chain_item_ids(cast(int, row[0])))+def is_empty(self, queue_id: str) -> IsEmptyResult:with self._db.transaction() as cursor:cursor.execute(@@ -436,6 +527,20 @@ class SqliteSessionQueue(SessionQueueBase):self.__invoker.services.events.emit_queue_cleared(queue_id)return ClearResult(deleted=count)+ def delete_queue_items_by_id(self, item_ids: list[int]) -> None:+ if not item_ids:+ return+ placeholders = ", ".join(["?" for _ in item_ids])+ with self._db.transaction() as cursor:+ cursor.execute(+ f"""--sql+ DELETE+ FROM session_queue+ WHERE item_id IN ({placeholders})+ """,+ tuple(item_ids),+ )+def prune(self, queue_id: str, user_id: Optional[str] = None) -> PruneResult:with self._db.transaction() as cursor:# Build WHERE clause with optional user_id filter@@ -450,7 +555,7 @@ class SqliteSessionQueue(SessionQueueBase):){user_filter}"""- params = [queue_id]+ params: list[Any] = [queue_id]if user_id is not None:params.append(user_id)@@ -474,29 +579,33 @@ class SqliteSessionQueue(SessionQueueBase):return PruneResult(deleted=count)def cancel_queue_item(self, item_id: int) -> SessionQueueItem:- queue_item = self._set_queue_item_status(item_id=item_id, status="canceled")- return queue_item+ chain_item_ids = self._get_workflow_call_chain_item_ids(item_id)+ for chain_item_id in chain_item_ids:+ self._set_queue_item_status(item_id=chain_item_id, status="canceled")+ return self.get_queue_item(item_id)def delete_queue_item(self, item_id: int) -> None:"""Deletes a session queue item"""- try:+ chain_item_ids = self._get_workflow_call_chain_item_ids(item_id)+ if any(+ self.get_queue_item(chain_item_id).status not in {"completed", "failed", "canceled"}+ for chain_item_id in chain_item_ids+ ):self.cancel_queue_item(item_id)- except SessionQueueItemNotFoundError:- pass- with self._db.transaction() as cursor:- cursor.execute(- """--sql- DELETE- FROM session_queue- WHERE item_id = ?- """,- (item_id,),- )+ self.delete_queue_items_by_id(chain_item_ids)def complete_queue_item(self, item_id: int) -> SessionQueueItem:queue_item = self._set_queue_item_status(item_id=item_id, status="completed")return queue_item+ def suspend_queue_item(self, item_id: int) -> SessionQueueItem:+ queue_item = self._set_queue_item_status(item_id=item_id, status="waiting")+ return queue_item++ def resume_queue_item(self, item_id: int) -> SessionQueueItem:+ queue_item = self._set_queue_item_status(item_id=item_id, status="pending")+ return queue_item+def fail_queue_item(self,item_id: int,@@ -654,18 +763,25 @@ class SqliteSessionQueue(SessionQueueBase):return DeleteByDestinationResult(deleted=count)def delete_all_except_current(self, queue_id: str, user_id: Optional[str] = None) -> DeleteAllExceptCurrentResult:+ current_chain_item_ids = self._get_current_workflow_call_chain_item_ids(queue_id)with self._db.transaction() as cursor:# Build WHERE clause with optional user_id filteruser_filter = "AND user_id = ?" if user_id is not None else ""+ current_chain_filter = ""+ if current_chain_item_ids:+ placeholders = ", ".join(["?" for _ in current_chain_item_ids])+ current_chain_filter = f"AND item_id NOT IN ({placeholders})"where = f"""--sqlWHEREqueue_id == ?- AND status == 'pending'+ AND status IN ('pending', 'waiting'){user_filter}+ {current_chain_filter}"""- params = [queue_id]+ params: list[Any] = [queue_id]if user_id is not None:params.append(user_id)+ params.extend(current_chain_item_ids)cursor.execute(f"""--sql@@ -723,18 +839,25 @@ class SqliteSessionQueue(SessionQueueBase):return CancelByQueueIDResult(canceled=count)def cancel_all_except_current(self, queue_id: str, user_id: Optional[str] = None) -> CancelAllExceptCurrentResult:+ current_chain_item_ids = self._get_current_workflow_call_chain_item_ids(queue_id)with self._db.transaction() as cursor:# Build WHERE clause with optional user_id filteruser_filter = "AND user_id = ?" if user_id is not None else ""+ current_chain_filter = ""+ if current_chain_item_ids:+ placeholders = ", ".join(["?" for _ in current_chain_item_ids])+ current_chain_filter = f"AND item_id NOT IN ({placeholders})"where = f"""--sqlWHEREqueue_id == ?- AND status == 'pending'+ AND status IN ('pending', 'waiting'){user_filter}+ {current_chain_filter}"""params = [queue_id]if user_id is not None:params.append(user_id)+ params.extend(current_chain_item_ids)cursor.execute(f"""--sql@@ -791,6 +914,116 @@ class SqliteSessionQueue(SessionQueueBase):)return self.get_queue_item(item_id)+ def enqueue_workflow_call_child(+ self,+ parent_queue_item: SessionQueueItem,+ child_session: GraphExecutionState,+ field_values: list[NodeFieldValue] | None = None,+ ) -> SessionQueueItem:+ workflow_call_execution = parent_queue_item.session.waiting_workflow_call_execution+ if workflow_call_execution is None:+ raise ValueError("Parent queue item is missing active workflow call execution metadata.")++ session_json = child_session.model_dump_json(warnings=False, exclude_none=True)+ field_values_json = json.dumps(field_values, default=to_jsonable_python) if field_values is not None else None+ root_item_id = parent_queue_item.root_item_id or parent_queue_item.item_id++ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ SELECT COUNT(*)+ FROM session_queue+ WHERE queue_id = ? AND status = 'pending'+ """,+ (parent_queue_item.queue_id,),+ )+ pending_count = cast(int, cursor.fetchone()[0])+ if pending_count >= self.__invoker.services.configuration.max_queue_size:+ raise TooManySessionsError(+ "call_saved_workflow exceeds remaining queue capacity for child workflow executions"+ )++ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id,+ session,+ session_id,+ batch_id,+ field_values,+ priority,+ workflow,+ origin,+ destination,+ retried_from_item_id,+ user_id,+ workflow_call_id,+ parent_item_id,+ parent_session_id,+ root_item_id,+ workflow_call_depth,+ status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')+ """,+ (+ parent_queue_item.queue_id,+ session_json,+ child_session.id,+ parent_queue_item.batch_id,+ field_values_json,+ parent_queue_item.priority,+ None,+ parent_queue_item.origin,+ parent_queue_item.destination,+ None,+ parent_queue_item.user_id,+ workflow_call_execution.id,+ parent_queue_item.item_id,+ parent_queue_item.session_id,+ root_item_id,+ workflow_call_execution.depth,+ ),+ )+ item_id = cursor.lastrowid++ queue_item = self.get_queue_item(item_id)+ batch_status = self.get_batch_status(queue_id=queue_item.queue_id, batch_id=queue_item.batch_id)+ queue_status = self.get_queue_status(queue_id=queue_item.queue_id, acting_user_id=queue_item.user_id)+ self.__invoker.services.events.emit_queue_item_status_changed(queue_item, batch_status, queue_status)+ return queue_item++ def cancel_workflow_call_children(+ self, workflow_call_id: str, exclude_item_ids: set[int] | None = None+ ) -> list[int]:+ exclude_item_ids = exclude_item_ids or set()+ with self._db.transaction() as cursor:+ cursor.execute(+ """--sql+ SELECT item_id+ FROM session_queue+ WHERE workflow_call_id = ?+ ORDER BY item_id ASC+ """,+ (workflow_call_id,),+ )+ item_ids = [row[0] for row in cast(list[sqlite3.Row], cursor.fetchall())]+ item_ids_with_descendants: list[int] = []+ for item_id in item_ids:+ item_ids_with_descendants.append(item_id)+ item_ids_with_descendants.extend(self._get_workflow_call_descendant_ids(item_id))+ item_ids = list(dict.fromkeys(item_ids_with_descendants))+ canceled_item_ids: list[int] = []+ for item_id in item_ids:+ if item_id in exclude_item_ids:+ continue+ queue_item = self.get_queue_item(item_id)+ if queue_item.status in {"completed", "failed", "canceled"}:+ continue+ self._set_queue_item_status(item_id=item_id, status="canceled")+ canceled_item_ids.append(item_id)+ return canceled_item_ids+def list_queue_items(self,queue_id: str,@@ -971,6 +1204,7 @@ class SqliteSessionQueue(SessionQueueBase):batch_id=current_item.batch_id if show_current_item else None,pending=counts.get("pending", 0),in_progress=counts.get("in_progress", 0),+ waiting=counts.get("waiting", 0),completed=counts.get("completed", 0),failed=counts.get("failed", 0),canceled=counts.get("canceled", 0),@@ -1005,6 +1239,7 @@ class SqliteSessionQueue(SessionQueueBase):queue_id=queue_id,pending=counts.get("pending", 0),in_progress=counts.get("in_progress", 0),+ waiting=counts.get("waiting", 0),completed=counts.get("completed", 0),failed=counts.get("failed", 0),canceled=counts.get("canceled", 0),@@ -1036,6 +1271,7 @@ class SqliteSessionQueue(SessionQueueBase):destination=destination,pending=counts.get("pending", 0),in_progress=counts.get("in_progress", 0),+ waiting=counts.get("waiting", 0),completed=counts.get("completed", 0),failed=counts.get("failed", 0),canceled=counts.get("canceled", 0),@@ -1046,47 +1282,77 @@ class SqliteSessionQueue(SessionQueueBase):"""Retries the given queue items"""with self._db.transaction() as cursor:values_to_insert: list[ValueToInsertTuple] = []- retried_item_ids: list[int] = []+ retried_root_item_ids: list[int] = []+ retried_user_ids: list[str] = []+ retried_item_ids_by_user: dict[str, list[int]] = {}+ seen_root_item_ids: set[int] = set()+ max_new_queue_items = self.__invoker.services.configuration.max_queue_size - self._get_current_queue_size(+ queue_id+ )++ if max_new_queue_items <= 0:+ return RetryItemsResult(queue_id=queue_id, retried_item_ids=[])for item_id in item_ids:- queue_item = self.get_queue_item(item_id)+ try:+ queue_item = self.get_queue_item(item_id)+ except SessionQueueItemNotFoundError:+ continue+ if queue_item.queue_id != queue_id:+ continueif queue_item.status not in ("failed", "canceled"):continue- retried_item_ids.append(item_id)+ root_item_id = queue_item.root_item_id or queue_item.item_id+ if root_item_id in seen_root_item_ids:+ continue+ seen_root_item_ids.add(root_item_id)++ root_queue_item = self.get_queue_item(root_item_id)+ if root_queue_item.status not in ("failed", "canceled"):+ continue++ retried_root_item_ids.append(root_item_id)+ retried_user_ids.append(root_queue_item.user_id)+ retried_item_ids_by_user.setdefault(root_queue_item.user_id, []).append(root_item_id)field_values_json = (- json.dumps(queue_item.field_values, default=to_jsonable_python) if queue_item.field_values else None+ json.dumps(root_queue_item.field_values, default=to_jsonable_python)+ if root_queue_item.field_values+ else None)workflow_json = (- json.dumps(queue_item.workflow, default=to_jsonable_python) if queue_item.workflow else None+ json.dumps(root_queue_item.workflow, default=to_jsonable_python)+ if root_queue_item.workflow+ else None)- cloned_session = GraphExecutionState(graph=queue_item.session.graph)+ cloned_session = GraphExecutionState(graph=root_queue_item.session.graph)cloned_session_json = cloned_session.model_dump_json(warnings=False, exclude_none=True)retried_from_item_id = (- queue_item.retried_from_item_id- if queue_item.retried_from_item_id is not None- else queue_item.item_id+ root_queue_item.retried_from_item_id+ if root_queue_item.retried_from_item_id is not None+ else root_queue_item.item_id)value_to_insert: ValueToInsertTuple = (- queue_item.queue_id,+ root_queue_item.queue_id,cloned_session_json,cloned_session.id,- queue_item.batch_id,+ root_queue_item.batch_id,field_values_json,- queue_item.priority,+ root_queue_item.priority,workflow_json,- queue_item.origin,- queue_item.destination,+ root_queue_item.origin,+ root_queue_item.destination,retried_from_item_id,- queue_item.user_id,+ root_queue_item.user_id,)values_to_insert.append(value_to_insert)- # TODO(psyche): Handle max queue size?+ if len(values_to_insert) >= max_new_queue_items:+ breakcursor.executemany("""--sql@@ -1098,7 +1364,11 @@ class SqliteSessionQueue(SessionQueueBase):retry_result = RetryItemsResult(queue_id=queue_id,- retried_item_ids=retried_item_ids,+ retried_item_ids=retried_root_item_ids,+ )+ self.__invoker.services.events.emit_queue_items_retried(+ retry_result,+ user_ids=list(dict.fromkeys(retried_user_ids)),+ retried_item_ids_by_user=retried_item_ids_by_user,)- self.__invoker.services.events.emit_queue_items_retried(retry_result)return retry_resultdiff --git a/invokeai/app/services/shared/README.md b/invokeai/app/services/shared/README.mdindex f92b1f1ea2..c6603f2c5d 100644--- a/invokeai/app/services/shared/README.md+++ b/invokeai/app/services/shared/README.md@@ -58,6 +58,19 @@ Runs a sequence of checks:1. **Type compatibility** `get_output_field_type` vs `get_input_field_type` and `are_connection_types_compatible`.+ Special case:++ - `call_saved_workflow` currently accepts dynamic destination handles of the form+ `saved_workflow_input::{childNodeId}::{childFieldName}` as part of its temporary call-boundary contract.+ - Those handles are allowed through graph validation even though they are not static Python model fields on the+ invocation class.+ - Runtime later validates them against the selected child workflow's exposed callable interface before applying+ values to the child graph.+ - The editor preserves dynamic caller values only while the exposed field type remains compatible; type drift at the+ same child node/field path resets to the selected workflow's current initial value.+ - Saved-workflow picker search is server-backed so large workflow libraries do not require scrolling every page+ before selecting a workflow by name.+1. **Iterator / collector structure** Enforce special rules:- Iterator's input must be `collection`; its outgoing edges use `item`.@@ -105,6 +118,14 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre- `prepared_source_mapping: dict[str, str]` - exec id -> source id.- `source_prepared_mapping: dict[str, set[str]]` - source id -> exec ids.- `indegree: dict[str, int]` - unmet inputs per exec node.+- Workflow-call runtime state:+ - `workflow_call_stack` - active parent call frames.+ - `workflow_call_history` - completed or failed workflow-call relationships observed by this execution state.+ - `workflow_call_parent` - parent workflow-call relationship metadata when this execution state is a child session.+ - `waiting_workflow_call` - the call frame currently suspending this execution state, if any.+ - `waiting_workflow_call_execution` - the active parent/child workflow-call relationship record for the waiting call.+ - `waiting_workflow_call_child_session` - attached child execution state for the waiting workflow call, if any.+ - `max_workflow_call_depth` - runtime guardrail for nested or recursive workflow calls.- Prepared exec metadata caches:- source node id- iteration path@@ -115,10 +136,42 @@ mutation helpers. Those helpers reject changes once the affected nodes have alre### 4.2 Core methods- `next()` Returns the next ready exec node. If none are ready, it asks the materializer to expand more source nodes and- then retries. Before returning a node, the runtime helper deep-copies inbound values into the node fields.+ then retries. If the execution state is paused on a workflow call boundary, it returns `None` without scheduling more+ work. Before returning a node, the runtime helper deep-copies inbound values into the node fields.- `complete(node_id, output)` Records the result, marks the exec node executed, marks the source node executed once allof its prepared exec copies are done, then decrements downstream indegrees and enqueues newly ready nodes.+Workflow-call note:++- `GraphExecutionState` can represent a paused parent execution plus an attached child execution state, but it does not+ itself orchestrate child execution.+- In the current implementation, `DefaultSessionRunner.run_node()` establishes the workflow call boundary and attaches+ the child execution state, while `WorkflowCallCoordinator` handles call-specific setup and+ `WorkflowCallQueueLifecycle` later resumes or fails the parent based on that child queue row's outcome.+- Child `SessionQueueItem` rows created by the coordinator now carry explicit relationship metadata such as+ `workflow_call_id`, `parent_item_id`, `parent_session_id`, `root_item_id`, and `workflow_call_depth`, even though the+ higher-level scheduler semantics are still evolving.+- The `session_queue` schema now has matching columns for those relationship fields, and parent queue items can enter a+ `waiting` status while suspended on a child workflow execution.+- Queue lifecycle semantics are now partially defined for workflow-call chains:+ - child success resumes the waiting parent+ - multiple child queue rows may complete under one waiting parent when the called workflow contains direct batch+ nodes; the parent resumes only after all expected child rows complete+ - child failure fails the waiting parent and can cascade upward through ancestors+ - failing child rows cancel their remaining workflow-call siblings before the parent is failed+ - cancelation is chain-aware across parents and children, including nested descendants of batched siblings+ - "all except current" queue actions preserve the active current item plus its workflow-call chain, while still+ canceling or deleting unrelated waiting chains+ - startup recovery cancels interrupted `in_progress` or `waiting` workflow-call chains, including pending descendants+ - deleting a workflow-call queue row currently deletes the whole parent/child chain rather than leaving orphaned rows+ behind+ - retry is root-oriented and should not be exposed directly on child queue rows in the UI+ - child queue-row creation is cleaned up on boundary-setup failure and child fan-out is bounded by remaining queue+ capacity+ - child workflows that mix supported batch nodes with unrelated generator nodes are rejected for now+- This is still an intermediate architecture step and should eventually be replaced by a more general parent/child+ execution mechanism rather than workflow-call-specific queue lifecycle handling.+### 4.3 Runtime helper classes`GraphExecutionState` now delegates most runtime behavior to internal helpers:@@ -218,7 +271,7 @@ This behavior is implemented in the runtime scheduler, not in the invocation bod- Execute node externally -> `output`.- `state.complete(node.id, output)` -> updates indegrees, `If` state, and ready queues.-1. Finish when `next()` returns `None`.+1. Finish when `next()` returns `None` and the execution state is not paused waiting on a workflow call boundary.In normal execution, all runtime expansion occurs in `execution_graph` with traceability back to source nodes.@@ -239,6 +292,35 @@ In normal execution, all runtime expansion occurs in `execution_graph` with traccomplexity.- **Dynamic behaviors** (future): can be added in `GraphExecutionState` by creating exec nodes and edges at `complete()`time, as long as the DAG invariant holds.+- **Workflow call boundaries**: `GraphExecutionState` can suspend a parent execution state on a workflow call, attach a+ child execution state, and later resume the parent without mutating the source graph.++Current limitation:++- Child workflow executions are now represented as first-class queue items. Parent resume/failure is intentionally+ handled by a dedicated workflow-call queue lifecycle component for this PR because no other feature currently needs a+ generalized dependent-queue scheduler.+- Called workflows currently require exactly one valid `workflow_return` node to be callable at all.+- A single `workflow_return_value.value` may connect directly to `workflow_return.values`; multiple named return members+ should be collected and then connected to `workflow_return.values`.+- Direct batch-special child workflows are now supported by expanding them into multiple child queue rows.+- Batch outputs may feed a named `workflow_return_value.value` directly. Parent resume aggregates named return maps as+ `values: dict[str, list[Any]]`, and all rows in one batch call must return the same key set.+- Generator-backed batch child workflows are now supported when the batch node is fed directly by a supported integer,+ float, string, or image generator.+- Connected batch child inputs produced by ordinary non-generator upstream nodes are still rejected before any child+ queue row is created.+- Workflow library API responses now include compatibility metadata so the frontend can disable unsupported callees+ before execution rather than failing only at runtime.+- Workflow library list compatibility uses structural generator-backed batch validation so list and picker rendering do+ not enumerate every image in board-backed generators; workflow detail and runtime execution still resolve real+ generator values.+- Batch-specific compatibility failures, including multiple connected inputs to one batch field, are reported as+ `unsupported_batch_input` rather than generic unsupported-node failures.+- The workflow library list also surfaces that metadata as an informational unsupported state; workflows remain+ viewable/editable even when they are not currently callable by `call_saved_workflow`.+- Single-user workflow CRUD socket events emit only to the admin room because every single-user socket already joins+ that room, avoiding duplicate delivery through both `user:system` and `admin`.## 8) Error Model (selected)diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex aa47c3b4bb..bebdde4a7c 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -29,6 +29,10 @@ from invokeai.app.invocations.baseinvocation import (invocation,invocation_output,)+from invokeai.app.invocations.call_saved_workflow import (+ CallSavedWorkflowInvocation,+ is_call_saved_workflow_dynamic_input,+)from invokeai.app.invocations.fields import Input, InputField, OutputField, UITypefrom invokeai.app.invocations.logic import IfInvocationfrom invokeai.app.services.shared.invocation_context import InvocationContext@@ -66,6 +70,56 @@ class Edge(BaseModel):PreparedExecState = Literal["pending", "ready", "executed", "skipped"]+WorkflowCallStatus = Literal["waiting_for_child", "running_child", "completed", "failed"]+++class WorkflowCallFrame(BaseModel):+ """Represents one workflow-call frame in a nested call chain."""++ prepared_call_node_id: str = Field(description="The prepared exec node id for the call site.")+ source_call_node_id: str = Field(description="The source graph node id for the call site.")+ workflow_id: str = Field(description="The saved workflow being called.")+ depth: int = Field(description="The 1-based depth of this call frame.", ge=1)+++class WorkflowCallExecution(BaseModel):+ """Tracks one parent/child workflow-call relationship and its lifecycle."""++ id: str = Field(description="The workflow-call execution id.", default_factory=uuid_string)+ parent_session_id: str = Field(description="The parent graph execution state id.")+ child_session_id: Optional[str] = Field(default=None, description="The child graph execution state id, if any.")+ prepared_call_node_id: str = Field(description="The prepared exec node id for the parent call site.")+ source_call_node_id: str = Field(description="The source graph node id for the parent call site.")+ workflow_id: str = Field(description="The saved workflow being called.")+ depth: int = Field(description="The 1-based depth of this call frame.", ge=1)+ status: WorkflowCallStatus = Field(description="The current workflow-call lifecycle state.")+ error_message: Optional[str] = Field(default=None, description="Failure reason, if the call failed.")+ child_session_ids: list[str] = Field(default_factory=list, description="All child graph execution state ids.")+ child_item_ids: list[int] = Field(default_factory=list, description="Child queue item ids in enqueue order.")+ expected_child_count: int = Field(default=1, ge=1, description="The number of child executions for this call.")+ completed_child_item_ids: list[int] = Field(+ default_factory=list,+ description="The child queue item ids whose workflow_return outputs have been aggregated.",+ )+ aggregated_values: dict[str, list[Any]] = Field(+ default_factory=dict,+ description="The aggregated workflow_return values accumulated from child executions.",+ )+ child_outputs: dict[int, dict[str, Any]] = Field(+ default_factory=dict,+ description="Workflow return values keyed by child queue item id.",+ )+++class WorkflowCallParentRef(BaseModel):+ """Reference from a child execution state back to its parent workflow-call relationship."""++ workflow_call_id: str = Field(description="The workflow-call execution id.")+ parent_session_id: str = Field(description="The parent graph execution state id.")+ prepared_call_node_id: str = Field(description="The prepared exec node id for the parent call site.")+ source_call_node_id: str = Field(description="The source graph node id for the parent call site.")+ workflow_id: str = Field(description="The saved workflow being called.")+ depth: int = Field(description="The 1-based depth of this call frame.", ge=1)@dataclass@@ -772,6 +826,10 @@ class _ExecutionRuntime:for edge in input_edges:if allowed_fields is not None and edge.destination.field not in allowed_fields:continue+ if isinstance(node, CallSavedWorkflowInvocation) and is_call_saved_workflow_dynamic_input(+ edge.destination.field+ ):+ continuesetattr(node, edge.destination.field, self._get_copied_result_value(edge))def _prepare_collect_inputs(self, node: "CollectInvocation", input_edges: list[Edge]) -> None:@@ -1201,6 +1259,10 @@ class Graph(BaseModel):)if edge.destination.field not in type(destination_node).model_fields:+ if isinstance(destination_node, CallSavedWorkflowInvocation) and is_call_saved_workflow_dynamic_input(+ edge.destination.field+ ):+ continueraise NodeFieldNotFoundError(f"Edge destination field {edge.destination.field} does not exist in node {edge.destination.node_id}")@@ -1212,10 +1274,15 @@ class Graph(BaseModel):def _validate_edge_type_compatibility(self) -> None:for edge in self.edges:+ destination_node = self.get_node(edge.destination.node_id)+ if isinstance(destination_node, CallSavedWorkflowInvocation) and is_call_saved_workflow_dynamic_input(+ edge.destination.field+ ):+ continueif not are_connections_compatible(self.get_node(edge.source.node_id),edge.source.field,- self.get_node(edge.destination.node_id),+ destination_node,edge.destination.field,):raise InvalidEdgeError(f"Edge source and target types do not match ({edge})")@@ -1305,6 +1372,10 @@ class Graph(BaseModel):def _validate_edge_field_compatibility(self, edge: Edge, source_node: BaseInvocation, destination_node: BaseInvocation) -> None:+ if isinstance(destination_node, CallSavedWorkflowInvocation) and is_call_saved_workflow_dynamic_input(+ edge.destination.field+ ):+ returnif not are_connections_compatible(source_node, edge.source.field, destination_node, edge.destination.field):raise InvalidEdgeError(f"Field types are incompatible ({edge})")@@ -1736,6 +1807,36 @@ class GraphExecutionState(BaseModel):# Errors raised when executing nodeserrors: dict[str, str] = Field(description="Errors raised when executing nodes", default_factory=dict)+ workflow_call_stack: list[WorkflowCallFrame] = Field(+ description="The nested workflow call stack inherited by this execution state.",+ default_factory=list,+ )+ workflow_call_history: list[WorkflowCallExecution] = Field(+ description="Completed or failed workflow-call relationships observed by this execution state.",+ default_factory=list,+ )+ workflow_call_parent: Optional[WorkflowCallParentRef] = Field(+ default=None,+ description="Parent workflow-call relationship metadata when this execution state is a child workflow session.",+ )+ waiting_workflow_call: Optional[WorkflowCallFrame] = Field(+ default=None,+ description="The child workflow call this execution state is currently waiting on, if any.",+ )+ waiting_workflow_call_execution: Optional[WorkflowCallExecution] = Field(+ default=None,+ description="The active workflow-call relationship metadata for the current waiting child workflow, if any.",+ )+ waiting_workflow_call_child_session: Optional["GraphExecutionState"] = Field(+ default=None,+ description="The child workflow execution state spawned by the current waiting workflow call, if any.",+ )+ max_workflow_call_depth: int = Field(+ default=4,+ ge=1,+ description="The maximum permitted workflow call depth for nested workflow execution.",+ )+# Map of prepared/executed nodes to their original nodesprepared_source_mapping: dict[str, str] = Field(description="The map of prepared nodes to original graph nodes",@@ -1918,6 +2019,8 @@ class GraphExecutionState(BaseModel):"executed_history","results","errors",+ "workflow_call_stack",+ "workflow_call_history","prepared_source_mapping","source_prepared_mapping",]@@ -1936,6 +2039,9 @@ class GraphExecutionState(BaseModel):# TODO: enable multiple nodes to execute simultaneously by tracking currently executing nodes# possibly with a timeout?+ if self.is_waiting_on_workflow_call():+ return None+# If there are no prepared nodes, prepare some nodesnext_node = self._get_next_node()if next_node is None:@@ -1961,6 +2067,8 @@ class GraphExecutionState(BaseModel):def is_complete(self) -> bool:"""Returns true if the graph is complete"""+ if self.is_waiting_on_workflow_call():+ return Falsenode_ids = set(self.graph.nx_graph_flat().nodes)return self.has_error() or all((k in self.executed for k in node_ids))@@ -1968,6 +2076,150 @@ class GraphExecutionState(BaseModel):"""Returns true if the graph has any errors"""return len(self.errors) > 0+ def get_workflow_call_depth(self) -> int:+ return len(self.workflow_call_stack)++ def is_waiting_on_workflow_call(self) -> bool:+ return self.waiting_workflow_call is not None++ def build_workflow_call_frame(self, exec_node_id: str, workflow_id: str) -> WorkflowCallFrame:+ if exec_node_id not in self.execution_graph.nodes:+ raise NodeNotFoundError(f"Node {exec_node_id} not found in execution graph")+ if exec_node_id not in self.prepared_source_mapping:+ raise ValueError(f"Node {exec_node_id} is not a prepared execution node")++ next_depth = self.get_workflow_call_depth() + 1+ if next_depth > self.max_workflow_call_depth:+ raise ValueError(+ f"Maximum workflow call depth exceeded ({self.max_workflow_call_depth}) for workflow '{workflow_id}'"+ )++ return WorkflowCallFrame(+ prepared_call_node_id=exec_node_id,+ source_call_node_id=self.prepared_source_mapping[exec_node_id],+ workflow_id=workflow_id,+ depth=next_depth,+ )++ def begin_waiting_on_workflow_call(self, frame: WorkflowCallFrame) -> None:+ if self.waiting_workflow_call is not None:+ raise ValueError("Execution state is already waiting on a workflow call")+ self.waiting_workflow_call = frame+ self.waiting_workflow_call_execution = WorkflowCallExecution(+ parent_session_id=self.id,+ prepared_call_node_id=frame.prepared_call_node_id,+ source_call_node_id=frame.source_call_node_id,+ workflow_id=frame.workflow_id,+ depth=frame.depth,+ status="waiting_for_child",+ )++ def attach_waiting_workflow_call_child_session(self, child_session: "GraphExecutionState") -> None:+ if self.waiting_workflow_call is None:+ raise ValueError("Execution state must be waiting on a workflow call before attaching a child session")+ if self.waiting_workflow_call_execution is None:+ raise ValueError("Execution state is waiting on a workflow call but has no workflow call execution")+ self.waiting_workflow_call_child_session = child_session+ self.waiting_workflow_call_execution.child_session_id = child_session.id+ self.waiting_workflow_call_execution.child_session_ids = [child_session.id]+ self.waiting_workflow_call_execution.expected_child_count = 1+ self.waiting_workflow_call_execution.status = "running_child"+ child_session.workflow_call_parent = WorkflowCallParentRef(+ workflow_call_id=self.waiting_workflow_call_execution.id,+ parent_session_id=self.waiting_workflow_call_execution.parent_session_id,+ prepared_call_node_id=self.waiting_workflow_call_execution.prepared_call_node_id,+ source_call_node_id=self.waiting_workflow_call_execution.source_call_node_id,+ workflow_id=self.waiting_workflow_call_execution.workflow_id,+ depth=self.waiting_workflow_call_execution.depth,+ )++ def attach_waiting_workflow_call_child_sessions(self, child_sessions: list["GraphExecutionState"]) -> None:+ if not child_sessions:+ raise ValueError("Workflow call must attach at least one child session")+ if self.waiting_workflow_call_execution is None:+ raise ValueError("Execution state is waiting on a workflow call but has no workflow call execution")+ self.waiting_workflow_call_child_session = child_sessions[0] if len(child_sessions) == 1 else None+ self.waiting_workflow_call_execution.child_session_id = child_sessions[0].id+ self.waiting_workflow_call_execution.child_session_ids = [child_session.id for child_session in child_sessions]+ self.waiting_workflow_call_execution.expected_child_count = len(child_sessions)+ self.waiting_workflow_call_execution.status = "running_child"+ for child_session in child_sessions:+ child_session.workflow_call_parent = WorkflowCallParentRef(+ workflow_call_id=self.waiting_workflow_call_execution.id,+ parent_session_id=self.waiting_workflow_call_execution.parent_session_id,+ prepared_call_node_id=self.waiting_workflow_call_execution.prepared_call_node_id,+ source_call_node_id=self.waiting_workflow_call_execution.source_call_node_id,+ workflow_id=self.waiting_workflow_call_execution.workflow_id,+ depth=self.waiting_workflow_call_execution.depth,+ )++ def set_waiting_workflow_call_child_item_ids(self, child_item_ids: list[int]) -> None:+ if self.waiting_workflow_call_execution is None:+ raise ValueError("Execution state is not waiting on a workflow call.")+ if len(child_item_ids) != self.waiting_workflow_call_execution.expected_child_count:+ raise ValueError("Workflow call child item count does not match expected child count.")+ if len(set(child_item_ids)) != len(child_item_ids):+ raise ValueError("Workflow call child item ids must be unique.")+ self.waiting_workflow_call_execution.child_item_ids = list(child_item_ids)++ def record_waiting_workflow_call_child_completion(+ self, child_item_id: int, output_values: dict[str, Any]+ ) -> tuple[bool, dict[str, Any]]:+ if self.waiting_workflow_call_execution is None:+ raise ValueError("Execution state is not waiting on a workflow call.")+ execution = self.waiting_workflow_call_execution+ if execution.child_item_ids and child_item_id not in execution.child_item_ids:+ raise ValueError(f"Child queue item {child_item_id} does not belong to the active workflow call.")+ if child_item_id not in execution.completed_child_item_ids:+ if (+ execution.expected_child_count > 1+ and execution.child_outputs+ and set(output_values.keys()) != set(next(iter(execution.child_outputs.values())).keys())+ ):+ raise ValueError("Batched child workflows returned different workflow return keys.")+ execution.completed_child_item_ids.append(child_item_id)+ execution.child_outputs[child_item_id] = dict(output_values)++ ordered_item_ids = execution.child_item_ids or execution.completed_child_item_ids+ execution.aggregated_values = {+ key: [+ execution.child_outputs[item_id][key]+ for item_id in ordered_item_ids+ if item_id in execution.child_outputs+ ]+ for key in output_values+ }+ is_complete = len(execution.completed_child_item_ids) >= execution.expected_child_count+ if execution.expected_child_count == 1:+ return (+ is_complete,+ {key: values[0] for key, values in execution.aggregated_values.items()},+ )+ return (+ is_complete,+ {key: list(values) for key, values in execution.aggregated_values.items()},+ )++ def end_waiting_on_workflow_call(+ self,+ status: Literal["completed", "failed"] = "completed",+ error_message: Optional[str] = None,+ ) -> None:+ if self.waiting_workflow_call_execution is not None:+ self.waiting_workflow_call_execution.status = status+ self.waiting_workflow_call_execution.error_message = error_message+ self.workflow_call_history.append(self.waiting_workflow_call_execution.model_copy(deep=True))+ self.waiting_workflow_call = None+ self.waiting_workflow_call_execution = None+ self.waiting_workflow_call_child_session = None++ def create_child_workflow_execution_state(self, graph: Graph, frame: WorkflowCallFrame) -> "GraphExecutionState":+ return GraphExecutionState(+ graph=graph,+ workflow_call_stack=[*self.workflow_call_stack, frame],+ max_workflow_call_depth=self.max_workflow_call_depth,+ )+def _create_execution_node(self, node_id: str, iteration_node_map: list[tuple[str, str]]) -> list[str]:return self._materializer().create_execution_node(node_id, iteration_node_map)diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_07_01_add_workflow_call_queue_metadata.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_07_01_add_workflow_call_queue_metadata.pynew file mode 100644index 0000000000..3dc61d470d--- /dev/null+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_2026_07_01_add_workflow_call_queue_metadata.py@@ -0,0 +1,53 @@+"""Add workflow-call relationship columns to session_queue."""++import sqlite3++from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration+++class AddWorkflowCallQueueMetadataCallback:+ """Add durable parent/child workflow-call relationship columns to session_queue."""++ def __call__(self, cursor: sqlite3.Cursor) -> None:+ cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='session_queue';")+ if cursor.fetchone() is None:+ return++ cursor.execute("PRAGMA table_info(session_queue);")+ columns = [row[1] for row in cursor.fetchall()]++ if "workflow_call_id" not in columns:+ cursor.execute("ALTER TABLE session_queue ADD COLUMN workflow_call_id TEXT;")+ cursor.execute(+ "CREATE INDEX IF NOT EXISTS idx_session_queue_workflow_call_id ON session_queue(workflow_call_id);"+ )++ if "parent_item_id" not in columns:+ cursor.execute("ALTER TABLE session_queue ADD COLUMN parent_item_id INTEGER;")+ cursor.execute(+ "CREATE INDEX IF NOT EXISTS idx_session_queue_parent_item_id ON session_queue(parent_item_id);"+ )++ if "parent_session_id" not in columns:+ cursor.execute("ALTER TABLE session_queue ADD COLUMN parent_session_id TEXT;")+ cursor.execute(+ "CREATE INDEX IF NOT EXISTS idx_session_queue_parent_session_id ON session_queue(parent_session_id);"+ )++ if "root_item_id" not in columns:+ cursor.execute("ALTER TABLE session_queue ADD COLUMN root_item_id INTEGER;")+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_session_queue_root_item_id ON session_queue(root_item_id);")++ if "workflow_call_depth" not in columns:+ cursor.execute("ALTER TABLE session_queue ADD COLUMN workflow_call_depth INTEGER;")+ cursor.execute(+ "CREATE INDEX IF NOT EXISTS idx_session_queue_workflow_call_depth ON session_queue(workflow_call_depth);"+ )+++def build_migration() -> Migration:+ return Migration(+ id="2026_07_01_add_workflow_call_queue_metadata",+ depends_on="migration_33",+ callback=AddWorkflowCallQueueMetadataCallback(),+ )diff --git a/invokeai/app/services/shared/workflow_call_compatibility.py b/invokeai/app/services/shared/workflow_call_compatibility.pynew file mode 100644index 0000000000..97b295971e--- /dev/null+++ b/invokeai/app/services/shared/workflow_call_compatibility.py@@ -0,0 +1,229 @@+from collections.abc import Mapping+from copy import deepcopy+from typing import Any, get_args, get_origin++from pydantic import BaseModel+from pydantic_core import PydanticUndefined++from invokeai.app.invocations.baseinvocation import InvocationRegistry+from invokeai.app.invocations.call_saved_workflow import parse_call_saved_workflow_dynamic_input+from invokeai.app.invocations.fields import ImageField+from invokeai.app.services.session_processor.workflow_call_batch import build_child_workflow_sessions+from invokeai.app.services.session_queue.session_queue_common import TooManySessionsError+from invokeai.app.services.shared.graph import Graph, GraphExecutionState, WorkflowCallFrame+from invokeai.app.services.shared.workflow_call_compatibility_common import (+ WorkflowCallCompatibility,+ WorkflowCallCompatibilityReason,+)+from invokeai.app.services.shared.workflow_graph_builder import (+ InvalidWorkflowInputError,+ UnsupportedWorkflowNodeError,+ get_exposed_workflow_input_names,+)+++def _count_workflow_return_nodes(workflow: dict[str, Any]) -> int:+ workflow_return_count = 0+ for node in workflow.get("nodes", []):+ if not isinstance(node, dict) or node.get("type") != "invocation":+ continue+ data = node.get("data")+ if isinstance(data, dict) and data.get("type") == "workflow_return":+ workflow_return_count += 1+ return workflow_return_count+++def _is_mapping(value: Any) -> bool:+ return isinstance(value, Mapping)+++def _build_placeholder_model(annotation: type[BaseModel]) -> Any:+ values: dict[str, Any] = {}+ for field_name, field_info in annotation.model_fields.items():+ if field_info.default is not PydanticUndefined:+ values[field_name] = deepcopy(field_info.default)+ continue+ if field_info.default_factory is not None:+ values[field_name] = field_info.default_factory()+ continue+ placeholder = _get_placeholder_for_annotation(field_info.annotation)+ if placeholder is None:+ return None+ values[field_name] = placeholder+ return annotation.model_construct(**values)+++def _get_placeholder_for_annotation(annotation: Any) -> Any:+ origin = get_origin(annotation)+ if origin is not None:+ if origin is list:+ return []+ if origin is dict:+ return {}+ if origin is tuple:+ return []+ if origin is set:+ return []+ args = [arg for arg in get_args(annotation) if arg is not type(None)]+ if args:+ return _get_placeholder_for_annotation(args[0])+ return None++ if annotation is Any:+ return {}+ if annotation is str:+ return ""+ if annotation is int:+ return 0+ if annotation is float:+ return 0.0+ if annotation is bool:+ return False+ if annotation is ImageField:+ return ImageField(image_name="compatibility-placeholder")+ if isinstance(annotation, type) and issubclass(annotation, BaseModel):+ return _build_placeholder_model(annotation)+ return None+++def _build_compatibility_workflow_inputs(workflow: dict[str, Any]) -> dict[str, Any]:+ workflow_inputs: dict[str, Any] = {}+ workflow_nodes = workflow.get("nodes", [])+ if not isinstance(workflow_nodes, list):+ return workflow_inputs++ nodes_by_id = {+ node.get("id"): node+ for node in workflow_nodes+ if _is_mapping(node) and isinstance(node.get("id"), str) and _is_mapping(node.get("data"))+ }++ for input_name in get_exposed_workflow_input_names(workflow):+ node_id, field_name = parse_call_saved_workflow_dynamic_input(input_name)+ node = nodes_by_id.get(node_id)+ if not _is_mapping(node):+ continue+ node_data = node.get("data")+ if not _is_mapping(node_data):+ continue+ node_type = node_data.get("type")+ if not isinstance(node_type, str):+ continue+ invocation_class = InvocationRegistry.get_invocation_for_type(node_type)+ if invocation_class is None:+ continue+ field_info = invocation_class.model_fields.get(field_name)+ if field_info is None:+ continue+ if field_info.default is not PydanticUndefined:+ workflow_inputs[input_name] = deepcopy(field_info.default)+ continue+ if field_info.default_factory is not None:+ workflow_inputs[input_name] = field_info.default_factory()+ continue+ placeholder = _get_placeholder_for_annotation(field_info.annotation)+ if placeholder is not None:+ workflow_inputs[input_name] = placeholder++ return workflow_inputs+++def _is_unsupported_batch_input_message(message: str) -> bool:+ return any(+ marker in message+ for marker in (+ "batch child workflow",+ "batch group",+ "batch input",+ "batch inputs",+ "batch node",+ "batch-special child workflow nodes",+ "connected batch",+ "generator-backed batch",+ )+ )+++def get_workflow_call_compatibility(+ *,+ workflow: dict[str, Any],+ workflow_id: str,+ services: Any,+ user_id: str | None,+ maximum_children: int,+ resolve_generator_items: bool = True,+) -> WorkflowCallCompatibility:+ workflow_return_count = _count_workflow_return_nodes(workflow)+ if workflow_return_count == 0:+ return WorkflowCallCompatibility(+ is_callable=False,+ reason=WorkflowCallCompatibilityReason.MissingWorkflowReturn,+ message="The workflow must contain exactly one workflow_return node.",+ )+ if workflow_return_count > 1:+ return WorkflowCallCompatibility(+ is_callable=False,+ reason=WorkflowCallCompatibilityReason.MultipleWorkflowReturn,+ message="The workflow must not contain more than one workflow_return node.",+ )++ try:+ workflow_inputs = _build_compatibility_workflow_inputs(workflow)+ build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs=workflow_inputs,+ call_frame=WorkflowCallFrame(+ prepared_call_node_id="compatibility-call",+ source_call_node_id="compatibility-call",+ workflow_id=workflow_id,+ depth=1,+ ),+ maximum_children=maximum_children,+ services=services,+ user_id=user_id,+ resolve_generator_items=resolve_generator_items,+ )+ except InvalidWorkflowInputError as e:+ return WorkflowCallCompatibility(+ is_callable=False,+ reason=WorkflowCallCompatibilityReason.InvalidInputs,+ message=str(e),+ )+ except UnsupportedWorkflowNodeError as e:+ message = str(e)+ reason = WorkflowCallCompatibilityReason.UnsupportedNode+ if _is_unsupported_batch_input_message(message):+ reason = WorkflowCallCompatibilityReason.UnsupportedBatchInput+ elif "exactly one workflow_return" in message and workflow_return_count == 0:+ reason = WorkflowCallCompatibilityReason.MissingWorkflowReturn+ elif "exactly one workflow_return" in message:+ reason = WorkflowCallCompatibilityReason.InvalidGraph+ return WorkflowCallCompatibility(+ is_callable=False,+ reason=reason,+ message=message,+ )+ except TooManySessionsError as e:+ return WorkflowCallCompatibility(+ is_callable=False,+ reason=WorkflowCallCompatibilityReason.ExceedsCapacity,+ message=str(e),+ )+ except ValueError as e:+ return WorkflowCallCompatibility(+ is_callable=False,+ reason=WorkflowCallCompatibilityReason.InvalidGraph,+ message=str(e),+ )+ except Exception as e:+ return WorkflowCallCompatibility(+ is_callable=False,+ reason=WorkflowCallCompatibilityReason.Unknown,+ message=str(e),+ )++ return WorkflowCallCompatibility(+ is_callable=True,+ reason=WorkflowCallCompatibilityReason.Ok,+ )diff --git a/invokeai/app/services/shared/workflow_call_compatibility_common.py b/invokeai/app/services/shared/workflow_call_compatibility_common.pynew file mode 100644index 0000000000..589579ebaa--- /dev/null+++ b/invokeai/app/services/shared/workflow_call_compatibility_common.py@@ -0,0 +1,21 @@+from enum import Enum++from pydantic import BaseModel, Field+++class WorkflowCallCompatibilityReason(str, Enum):+ Ok = "ok"+ MissingWorkflowReturn = "missing_workflow_return"+ MultipleWorkflowReturn = "multiple_workflow_return"+ UnsupportedNode = "unsupported_node"+ UnsupportedBatchInput = "unsupported_batch_input"+ InvalidGraph = "invalid_graph"+ InvalidInputs = "invalid_inputs"+ ExceedsCapacity = "exceeds_capacity"+ Unknown = "unknown"+++class WorkflowCallCompatibility(BaseModel):+ is_callable: bool = Field(description="Whether the workflow can currently be executed by call_saved_workflow.")+ reason: WorkflowCallCompatibilityReason = Field(description="Structured compatibility result.")+ message: str | None = Field(default=None, description="Human-readable compatibility detail when unavailable.")diff --git a/invokeai/app/services/shared/workflow_graph_builder.py b/invokeai/app/services/shared/workflow_graph_builder.pynew file mode 100644index 0000000000..a32d9d01f6--- /dev/null+++ b/invokeai/app/services/shared/workflow_graph_builder.py@@ -0,0 +1,368 @@+from collections.abc import Mapping, MutableMapping, Sequence+from typing import Any++from invokeai.app.invocations.baseinvocation import Classification, InvocationRegistry+from invokeai.app.invocations.call_saved_workflow import (+ CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX,+ parse_call_saved_workflow_dynamic_input,+)+from invokeai.app.services.shared.graph import Edge, EdgeConnection, Graph++CONNECTOR_INPUT_HANDLE = "in"+CONNECTOR_OUTPUT_HANDLE = "out"+++class UnsupportedWorkflowNodeError(ValueError):+ pass+++class InvalidWorkflowInputError(ValueError):+ pass+++def _is_mapping(value: Any) -> bool:+ return isinstance(value, Mapping)+++def _is_invocation_node(node: Any) -> bool:+ return _is_mapping(node) and node.get("type") == "invocation" and _is_mapping(node.get("data"))+++def _is_connector_node(node: Any) -> bool:+ return _is_mapping(node) and node.get("type") == "connector"+++def _build_dynamic_input_name(node_id: str, field_name: str) -> str:+ return f"{CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX}{node_id}::{field_name}"+++def _get_form_elements(workflow: Mapping[str, Any]) -> tuple[Mapping[str, Any], str | None]:+ form = workflow.get("form")+ if not _is_mapping(form):+ return {}, None++ elements = form.get("elements")+ root_element_id = form.get("rootElementId")+ if not _is_mapping(elements) or not isinstance(root_element_id, str):+ return {}, None++ return elements, root_element_id+++def _collect_exposed_inputs_from_form(workflow: Mapping[str, Any]) -> set[str]:+ elements, root_element_id = _get_form_elements(workflow)+ if not elements or root_element_id is None:+ return set()++ exposed_inputs: set[str] = set()+ stack = [root_element_id]+ visited: set[str] = set()++ while stack:+ element_id = stack.pop()+ if element_id in visited:+ continue+ visited.add(element_id)++ element = elements.get(element_id)+ if not _is_mapping(element):+ continue++ if element.get("type") == "node-field":+ data = element.get("data")+ if _is_mapping(data):+ field_identifier = data.get("fieldIdentifier")+ if _is_mapping(field_identifier):+ node_id = field_identifier.get("nodeId")+ field_name = field_identifier.get("fieldName")+ if isinstance(node_id, str) and isinstance(field_name, str):+ exposed_inputs.add(_build_dynamic_input_name(node_id, field_name))++ data = element.get("data")+ if _is_mapping(data):+ children = data.get("children")+ if isinstance(children, Sequence):+ for child_id in reversed(children):+ if isinstance(child_id, str):+ stack.append(child_id)++ return exposed_inputs+++def get_exposed_workflow_input_names(workflow: Mapping[str, Any]) -> set[str]:+ exposed_inputs = _collect_exposed_inputs_from_form(workflow)+ if exposed_inputs:+ return exposed_inputs++ workflow_exposed_fields = workflow.get("exposedFields", [])+ if not isinstance(workflow_exposed_fields, Sequence):+ return set()++ fallback_inputs: set[str] = set()+ for field in workflow_exposed_fields:+ if not _is_mapping(field):+ continue+ node_id = field.get("nodeId")+ field_name = field.get("fieldName")+ if isinstance(node_id, str) and isinstance(field_name, str):+ fallback_inputs.add(_build_dynamic_input_name(node_id, field_name))++ return fallback_inputs+++def apply_workflow_inputs_to_workflow(workflow: MutableMapping[str, Any], workflow_inputs: Mapping[str, Any]) -> None:+ if not workflow_inputs:+ return++ allowed_inputs = get_exposed_workflow_input_names(workflow)+ for input_name, value in workflow_inputs.items():+ if input_name not in allowed_inputs:+ raise InvalidWorkflowInputError(+ f"call_saved_workflow input '{input_name}' is not exposed by the selected workflow"+ )++ node_id, field_name = parse_call_saved_workflow_dynamic_input(input_name)+ workflow_nodes = workflow.get("nodes", [])+ if not isinstance(workflow_nodes, list):+ raise InvalidWorkflowInputError(+ f"call_saved_workflow input '{input_name}' targets missing child workflow node '{node_id}'"+ )+ matching_node = next(+ (+ node+ for node in workflow_nodes+ if _is_mapping(node)+ and _is_mapping(node.get("data"))+ and node.get("id") == node_id+ and node["data"].get("id") == node_id+ ),+ None,+ )+ if matching_node is None:+ raise InvalidWorkflowInputError(+ f"call_saved_workflow input '{input_name}' targets missing child workflow node '{node_id}'"+ )+ matching_node_data = matching_node["data"]+ node_type = matching_node_data.get("type")+ if not isinstance(node_type, str):+ raise InvalidWorkflowInputError(+ f"call_saved_workflow input '{input_name}' targets missing child workflow node '{node_id}'"+ )+ invocation_class = InvocationRegistry.get_invocation_for_type(node_type)+ if invocation_class is None or field_name not in invocation_class.model_fields:+ raise InvalidWorkflowInputError(+ f"call_saved_workflow input '{input_name}' targets missing child workflow field '{field_name}'"+ )+ inputs = matching_node_data.setdefault("inputs", {})+ if not _is_mapping(inputs):+ raise InvalidWorkflowInputError(+ f"call_saved_workflow input '{input_name}' targets invalid child workflow inputs on '{node_id}'"+ )+ inputs[field_name] = {"value": value}+++def apply_workflow_inputs_to_graph(+ graph: Graph, workflow: Mapping[str, Any], workflow_inputs: Mapping[str, Any]+) -> None:+ if not workflow_inputs:+ return++ mutable_workflow = dict(workflow)+ apply_workflow_inputs_to_workflow(mutable_workflow, workflow_inputs)+ for input_name, value in workflow_inputs.items():+ node_id, field_name = parse_call_saved_workflow_dynamic_input(input_name)+ node = graph.nodes.get(node_id)+ if node is None:+ continue+ setattr(node, field_name, value)+++def _raise_if_unsupported_invocation_type(node_type: str, node_id: str) -> None:+ invocation_class = InvocationRegistry.get_invocation_for_type(node_type)+ if invocation_class is None:+ return++ if (+ invocation_class.UIConfig.category == "batch"+ and invocation_class.UIConfig.classification == Classification.Special+ and not node_type.endswith("_generator")+ ):+ raise UnsupportedWorkflowNodeError(+ f"call_saved_workflow does not yet support batch-special child workflow nodes such as "+ f"'{node_type}' (node '{node_id}')"+ )+++def _validate_callable_workflow_nodes(workflow_nodes: Sequence[Any]) -> None:+ workflow_return_node_ids: list[str] = []++ for node in workflow_nodes:+ if not _is_invocation_node(node):+ continue++ data = node["data"]+ node_id = data.get("id")+ node_type = data.get("type")+ if not isinstance(node_id, str) or not isinstance(node_type, str):+ continue++ _raise_if_unsupported_invocation_type(node_type, node_id)++ if node_type == "workflow_return":+ workflow_return_node_ids.append(node_id)++ if len(workflow_return_node_ids) != 1:+ raise UnsupportedWorkflowNodeError(+ "call_saved_workflow requires the selected workflow to contain exactly one workflow_return node"+ )+++def _get_default_edges(workflow_edges: Sequence[Any]) -> list[Mapping[str, Any]]:+ return [edge for edge in workflow_edges if _is_mapping(edge) and edge.get("type") == "default"]+++def _get_connector_input_edge(+ connector_id: str, workflow_edges: Sequence[Mapping[str, Any]]+) -> Mapping[str, Any] | None:+ return next(+ (+ edge+ for edge in workflow_edges+ if edge.get("target") == connector_id and edge.get("targetHandle") == CONNECTOR_INPUT_HANDLE+ ),+ None,+ )+++def _resolve_connector_source(+ connector_id: str, workflow_nodes: dict[str, Mapping[str, Any]], workflow_edges: Sequence[Mapping[str, Any]]+) -> tuple[str, str] | None:+ visited: set[str] = set()++ def resolve(node_id: str) -> tuple[str, str] | None:+ if node_id in visited:+ return None+ visited.add(node_id)++ incoming_edge = _get_connector_input_edge(node_id, workflow_edges)+ if incoming_edge is None:+ return None++ source_id = incoming_edge.get("source")+ source_handle = incoming_edge.get("sourceHandle")+ if not isinstance(source_id, str) or not isinstance(source_handle, str):+ return None++ source_node = workflow_nodes.get(source_id)+ if source_node is None:+ return None++ if _is_invocation_node(source_node):+ return (source_id, source_handle)++ if _is_connector_node(source_node):+ return resolve(source_id)++ return None++ return resolve(connector_id)+++def build_graph_from_workflow(workflow: Mapping[str, Any]) -> Graph:+ workflow_nodes_raw = workflow.get("nodes", [])+ workflow_edges_raw = workflow.get("edges", [])+ _validate_callable_workflow_nodes(workflow_nodes_raw if isinstance(workflow_nodes_raw, Sequence) else [])++ workflow_nodes = {+ node["id"]: node for node in workflow_nodes_raw if _is_mapping(node) and isinstance(node.get("id"), str)+ }+ default_edges = _get_default_edges(workflow_edges_raw if isinstance(workflow_edges_raw, Sequence) else [])++ parsed_nodes: dict[str, dict[str, Any]] = {}+ for node in workflow_nodes.values():+ if not _is_invocation_node(node):+ continue++ data = node["data"]+ node_id = data.get("id")+ node_type = data.get("type")+ if not isinstance(node_id, str) or not isinstance(node_type, str):+ continue++ graph_node: dict[str, Any] = {+ "id": node_id,+ "type": node_type,+ "use_cache": data.get("useCache", False),+ "is_intermediate": data.get("isIntermediate", False),+ }++ inputs = data.get("inputs", {})+ if _is_mapping(inputs):+ for field_name, field_value in inputs.items():+ if not isinstance(field_name, str) or not _is_mapping(field_value):+ continue+ graph_node[field_name] = field_value.get("value")++ parsed_nodes[node_id] = graph_node++ parsed_edges: list[dict[str, dict[str, str]]] = []+ seen_edges: set[tuple[str, str, str, str]] = set()++ for edge in default_edges:+ source_id = edge.get("source")+ target_id = edge.get("target")+ source_handle = edge.get("sourceHandle")+ target_handle = edge.get("targetHandle")+ if not all(isinstance(v, str) for v in (source_id, target_id, source_handle, target_handle)):+ continue++ target_node = workflow_nodes.get(target_id)+ if not _is_invocation_node(target_node):+ continue++ source_node = workflow_nodes.get(source_id)+ resolved_source: tuple[str, str] | None = None+ if _is_invocation_node(source_node):+ resolved_source = (source_id, source_handle)+ elif _is_connector_node(source_node):+ resolved_source = _resolve_connector_source(source_id, workflow_nodes, default_edges)++ if resolved_source is None:+ continue++ resolved_source_id, resolved_source_handle = resolved_source+ edge_key = (resolved_source_id, resolved_source_handle, target_id, target_handle)+ if edge_key in seen_edges:+ continue+ seen_edges.add(edge_key)++ parsed_edges.append(+ {+ "source": {+ "node_id": resolved_source_id,+ "field": resolved_source_handle,+ },+ "destination": {+ "node_id": target_id,+ "field": target_handle,+ },+ }+ )++ for edge in parsed_edges:+ destination_node_id = edge["destination"]["node_id"]+ destination_field = edge["destination"]["field"]+ parsed_nodes[destination_node_id].pop(destination_field, None)++ return Graph.model_validate(+ {+ "nodes": parsed_nodes,+ "edges": [+ Edge(+ source=EdgeConnection(**edge["source"]),+ destination=EdgeConnection(**edge["destination"]),+ )+ for edge in parsed_edges+ ],+ }+ )diff --git a/invokeai/app/services/workflow_records/workflow_records_common.py b/invokeai/app/services/workflow_records/workflow_records_common.pyindex 9c505530c9..178dd5a8cf 100644--- a/invokeai/app/services/workflow_records/workflow_records_common.py+++ b/invokeai/app/services/workflow_records/workflow_records_common.py@@ -5,6 +5,7 @@ from typing import Any, Optional, Unionimport semverfrom pydantic import BaseModel, ConfigDict, Field, JsonValue, TypeAdapter, field_validator+from invokeai.app.services.shared.workflow_call_compatibility_common import WorkflowCallCompatibilityfrom invokeai.app.util.metaenum import MetaEnum__workflow_meta_version__ = semver.Version.parse("1.0.0")@@ -73,6 +74,23 @@ class WorkflowWithoutID(BaseModel):model_config = ConfigDict(extra="ignore")+ @field_validator("nodes")+ @classmethod+ def validate_workflow_return_node_uniqueness(cls, nodes: list[dict[str, JsonValue]]):+ workflow_return_count = 0++ for node in nodes:+ if not isinstance(node, dict) or node.get("type") != "invocation":+ continue+ data = node.get("data")+ if isinstance(data, dict) and data.get("type") == "workflow_return":+ workflow_return_count += 1++ if workflow_return_count > 1:+ raise ValueError("A workflow may not contain more than one workflow_return node.")++ return nodes+WorkflowWithoutIDValidator = TypeAdapter(WorkflowWithoutID)@@ -131,7 +149,13 @@ WorkflowRecordListItemDTOValidator = TypeAdapter(WorkflowRecordListItemDTO)class WorkflowRecordWithThumbnailDTO(WorkflowRecordDTO):thumbnail_url: str | None = Field(default=None, description="The URL of the workflow thumbnail.")+ call_saved_workflow_compatibility: WorkflowCallCompatibility | None = Field(+ default=None, description="Whether this workflow is currently callable by call_saved_workflow."+ )class WorkflowRecordListItemWithThumbnailDTO(WorkflowRecordListItemDTO):thumbnail_url: str | None = Field(default=None, description="The URL of the workflow thumbnail.")+ call_saved_workflow_compatibility: WorkflowCallCompatibility | None = Field(+ default=None, description="Whether this workflow is currently callable by call_saved_workflow."+ )diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 0c8d8dc51c..ef1f81a745 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -12113,6 +12113,25 @@},{"$ref": "#/components/schemas/ImageField"+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "integer"+ },+ {+ "$ref": "#/components/schemas/ImageField"+ }+ ]+ },+ "type": "array"}]},@@ -12228,6 +12247,11 @@"title": "In Progress","description": "Number of queue items with status 'in_progress'"},+ "waiting": {+ "type": "integer",+ "title": "Waiting",+ "description": "Number of queue items with status 'waiting'"+ },"completed": {"type": "integer","title": "Completed",@@ -12257,6 +12281,7 @@"destination","pending","in_progress",+ "waiting","completed","failed","canceled",@@ -14786,6 +14811,77 @@"title": "CalculateImageTilesOutput","type": "object"},+ "CallSavedWorkflowInvocation": {+ "category": "workflow",+ "class": "invocation",+ "classification": "beta",+ "description": "Displays and later executes against a selected saved workflow.",+ "node_pack": "invokeai",+ "properties": {+ "id": {+ "description": "The id of this instance of an invocation. Must be unique among all instances of invocations.",+ "field_kind": "node_attribute",+ "title": "Id",+ "type": "string"+ },+ "is_intermediate": {+ "default": false,+ "description": "Whether or not this is an intermediate invocation.",+ "field_kind": "node_attribute",+ "input": "direct",+ "orig_required": true,+ "title": "Is Intermediate",+ "type": "boolean",+ "ui_hidden": false,+ "ui_type": "IsIntermediate"+ },+ "use_cache": {+ "default": false,+ "description": "Whether or not to use the cache",+ "field_kind": "node_attribute",+ "title": "Use Cache",+ "type": "boolean"+ },+ "workflow_id": {+ "default": "",+ "description": "The selected saved workflow ID, managed by the workflow editor UI.",+ "field_kind": "input",+ "input": "any",+ "orig_default": "",+ "orig_required": false,+ "title": "Workflow Id",+ "type": "string",+ "ui_type": "SavedWorkflowField"+ },+ "workflow_inputs": {+ "additionalProperties": true,+ "default": {},+ "description": "Literal values for the selected workflow's exposed inputs, managed by the workflow editor UI.",+ "field_kind": "input",+ "input": "any",+ "orig_default": {},+ "orig_required": false,+ "title": "Workflow Inputs",+ "type": "object",+ "ui_hidden": true+ },+ "type": {+ "const": "call_saved_workflow",+ "default": "call_saved_workflow",+ "field_kind": "node_attribute",+ "title": "type",+ "type": "string"+ }+ },+ "required": ["type", "id"],+ "tags": ["workflow", "saved", "library"],+ "title": "Call Saved Workflow",+ "type": "object",+ "version": "1.0.0",+ "output": {+ "$ref": "#/components/schemas/WorkflowReturnOutput"+ }+ },"CancelAllExceptCurrentResult": {"properties": {"canceled": {@@ -28746,6 +28842,9 @@{"$ref": "#/components/schemas/CalculateImageTilesMinimumOverlapInvocation"},+ {+ "$ref": "#/components/schemas/CallSavedWorkflowInvocation"+ },{"$ref": "#/components/schemas/CannyEdgeDetectionInvocation"},@@ -29415,6 +29514,15 @@{"$ref": "#/components/schemas/VAELoaderInvocation"},+ {+ "$ref": "#/components/schemas/WorkflowReturnGetInvocation"+ },+ {+ "$ref": "#/components/schemas/WorkflowReturnInvocation"+ },+ {+ "$ref": "#/components/schemas/WorkflowReturnValueInvocation"+ },{"$ref": "#/components/schemas/ZImageControlInvocation"},@@ -29757,6 +29865,15 @@{"$ref": "#/components/schemas/VAEOutput"},+ {+ "$ref": "#/components/schemas/WorkflowReturnGetOutput"+ },+ {+ "$ref": "#/components/schemas/WorkflowReturnOutput"+ },+ {+ "$ref": "#/components/schemas/WorkflowReturnValueOutput"+ },{"$ref": "#/components/schemas/ZImageConditioningOutput"},@@ -29783,6 +29900,73 @@"title": "Errors","description": "Errors raised when executing nodes"},+ "workflow_call_stack": {+ "items": {+ "$ref": "#/components/schemas/WorkflowCallFrame"+ },+ "type": "array",+ "title": "Workflow Call Stack",+ "description": "The nested workflow call stack inherited by this execution state."+ },+ "workflow_call_history": {+ "items": {+ "$ref": "#/components/schemas/WorkflowCallExecution"+ },+ "type": "array",+ "title": "Workflow Call History",+ "description": "Completed or failed workflow-call relationships observed by this execution state."+ },+ "workflow_call_parent": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/WorkflowCallParentRef"+ },+ {+ "type": "null"+ }+ ],+ "description": "Parent workflow-call relationship metadata when this execution state is a child workflow session."+ },+ "waiting_workflow_call": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/WorkflowCallFrame"+ },+ {+ "type": "null"+ }+ ],+ "description": "The child workflow call this execution state is currently waiting on, if any."+ },+ "waiting_workflow_call_execution": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/WorkflowCallExecution"+ },+ {+ "type": "null"+ }+ ],+ "description": "The active workflow-call relationship metadata for the current waiting child workflow, if any."+ },+ "waiting_workflow_call_child_session": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/GraphExecutionState"+ },+ {+ "type": "null"+ }+ ],+ "description": "The child workflow execution state spawned by the current waiting workflow call, if any."+ },+ "max_workflow_call_depth": {+ "type": "integer",+ "minimum": 1.0,+ "title": "Max Workflow Call Depth",+ "description": "The maximum permitted workflow call depth for nested workflow execution.",+ "default": 4+ },"prepared_source_mapping": {"additionalProperties": {"type": "string"@@ -29828,6 +30012,8 @@"executed_history","results","errors",+ "workflow_call_stack",+ "workflow_call_history","prepared_source_mapping","source_prepared_mapping"],@@ -36352,6 +36538,9 @@{"$ref": "#/components/schemas/CalculateImageTilesMinimumOverlapInvocation"},+ {+ "$ref": "#/components/schemas/CallSavedWorkflowInvocation"+ },{"$ref": "#/components/schemas/CannyEdgeDetectionInvocation"},@@ -37021,6 +37210,15 @@{"$ref": "#/components/schemas/VAELoaderInvocation"},+ {+ "$ref": "#/components/schemas/WorkflowReturnGetInvocation"+ },+ {+ "$ref": "#/components/schemas/WorkflowReturnInvocation"+ },+ {+ "$ref": "#/components/schemas/WorkflowReturnValueInvocation"+ },{"$ref": "#/components/schemas/ZImageControlInvocation"},@@ -37320,6 +37518,15 @@{"$ref": "#/components/schemas/VAEOutput"},+ {+ "$ref": "#/components/schemas/WorkflowReturnGetOutput"+ },+ {+ "$ref": "#/components/schemas/WorkflowReturnOutput"+ },+ {+ "$ref": "#/components/schemas/WorkflowReturnValueOutput"+ },{"$ref": "#/components/schemas/ZImageConditioningOutput"},@@ -37481,6 +37688,9 @@{"$ref": "#/components/schemas/CalculateImageTilesMinimumOverlapInvocation"},+ {+ "$ref": "#/components/schemas/CallSavedWorkflowInvocation"+ },{"$ref": "#/components/schemas/CannyEdgeDetectionInvocation"},@@ -38150,6 +38360,15 @@{"$ref": "#/components/schemas/VAELoaderInvocation"},+ {+ "$ref": "#/components/schemas/WorkflowReturnGetInvocation"+ },+ {+ "$ref": "#/components/schemas/WorkflowReturnInvocation"+ },+ {+ "$ref": "#/components/schemas/WorkflowReturnValueInvocation"+ },{"$ref": "#/components/schemas/ZImageControlInvocation"},@@ -38282,6 +38501,9 @@"calculate_image_tiles_min_overlap": {"$ref": "#/components/schemas/CalculateImageTilesOutput"},+ "call_saved_workflow": {+ "$ref": "#/components/schemas/WorkflowReturnOutput"+ },"canny_edge_detection": {"$ref": "#/components/schemas/ImageOutput"},@@ -38960,6 +39182,15 @@"vae_loader": {"$ref": "#/components/schemas/VAEOutput"},+ "workflow_return": {+ "$ref": "#/components/schemas/WorkflowReturnOutput"+ },+ "workflow_return_get": {+ "$ref": "#/components/schemas/WorkflowReturnGetOutput"+ },+ "workflow_return_value": {+ "$ref": "#/components/schemas/WorkflowReturnValueOutput"+ },"z_image_control": {"$ref": "#/components/schemas/ZImageControlOutput"},@@ -39011,6 +39242,7 @@"calculate_image_tiles","calculate_image_tiles_even_split","calculate_image_tiles_min_overlap",+ "call_saved_workflow","canny_edge_detection","canvas_output","canvas_paste_back",@@ -39237,6 +39469,9 @@"unsharp_mask","unsharp_mask_oklab","vae_loader",+ "workflow_return",+ "workflow_return_get",+ "workflow_return_value","z_image_control","z_image_denoise","z_image_denoise_meta",@@ -39378,6 +39613,9 @@{"$ref": "#/components/schemas/CalculateImageTilesMinimumOverlapInvocation"},+ {+ "$ref": "#/components/schemas/CallSavedWorkflowInvocation"+ },{"$ref": "#/components/schemas/CannyEdgeDetectionInvocation"},@@ -40047,6 +40285,15 @@{"$ref": "#/components/schemas/VAELoaderInvocation"},+ {+ "$ref": "#/components/schemas/WorkflowReturnGetInvocation"+ },+ {+ "$ref": "#/components/schemas/WorkflowReturnInvocation"+ },+ {+ "$ref": "#/components/schemas/WorkflowReturnValueInvocation"+ },{"$ref": "#/components/schemas/ZImageControlInvocation"},@@ -40265,6 +40512,9 @@{"$ref": "#/components/schemas/CalculateImageTilesMinimumOverlapInvocation"},+ {+ "$ref": "#/components/schemas/CallSavedWorkflowInvocation"+ },{"$ref": "#/components/schemas/CannyEdgeDetectionInvocation"},@@ -40934,6 +41184,15 @@{"$ref": "#/components/schemas/VAELoaderInvocation"},+ {+ "$ref": "#/components/schemas/WorkflowReturnGetInvocation"+ },+ {+ "$ref": "#/components/schemas/WorkflowReturnInvocation"+ },+ {+ "$ref": "#/components/schemas/WorkflowReturnValueInvocation"+ },{"$ref": "#/components/schemas/ZImageControlInvocation"},@@ -57533,6 +57792,25 @@},{"$ref": "#/components/schemas/ImageField"+ },+ {+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "number"+ },+ {+ "type": "integer"+ },+ {+ "$ref": "#/components/schemas/ImageField"+ }+ ]+ },+ "type": "array"}],"title": "Value",@@ -59363,7 +59641,7 @@},"status": {"description": "The new status of the queue item",- "enum": ["pending", "in_progress", "completed", "failed", "canceled"],+ "enum": ["pending", "in_progress", "waiting", "completed", "failed", "canceled"],"title": "Status","type": "string"},@@ -59513,9 +59791,28 @@},"title": "Retried Item Ids","type": "array"+ },+ "user_ids": {+ "description": "The IDs of the users who own the retried root queue items",+ "items": {+ "type": "string"+ },+ "title": "User Ids",+ "type": "array"+ },+ "retried_item_ids_by_user": {+ "additionalProperties": {+ "items": {+ "type": "integer"+ },+ "type": "array"+ },+ "description": "The retried root queue item IDs keyed by owner user ID.",+ "title": "Retried Item Ids By User",+ "type": "object"}},- "required": ["timestamp", "queue_id", "retried_item_ids"],+ "required": ["timestamp", "queue_id", "retried_item_ids", "user_ids", "retried_item_ids_by_user"],"title": "QueueItemsRetriedEvent","type": "object"},@@ -65326,6 +65623,11 @@"title": "In Progress","description": "Number of queue items with status 'in_progress' for the destination"},+ "waiting": {+ "type": "integer",+ "title": "Waiting",+ "description": "Number of queue items with status 'waiting' for the destination"+ },"completed": {"type": "integer","title": "Completed",@@ -65348,7 +65650,17 @@}},"type": "object",- "required": ["queue_id", "destination", "pending", "in_progress", "completed", "failed", "canceled", "total"],+ "required": [+ "queue_id",+ "destination",+ "pending",+ "in_progress",+ "waiting",+ "completed",+ "failed",+ "canceled",+ "total"+ ],"title": "SessionQueueCountsByDestination"},"SessionQueueItem": {@@ -65360,7 +65672,7 @@},"status": {"type": "string",- "enum": ["pending", "in_progress", "completed", "failed", "canceled"],+ "enum": ["pending", "in_progress", "waiting", "completed", "failed", "canceled"],"title": "Status","description": "The status of this queue item","default": "pending"@@ -65573,6 +65885,66 @@"title": "Retried From Item Id","description": "The item_id of the queue item that this item was retried from"},+ "workflow_call_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Workflow Call Id",+ "description": "The active workflow-call relationship id when this queue item is a child execution."+ },+ "parent_item_id": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Parent Item Id",+ "description": "The parent queue item id when this queue item is a child workflow execution."+ },+ "parent_session_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Parent Session Id",+ "description": "The parent session id when this queue item is a child workflow execution."+ },+ "root_item_id": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Root Item Id",+ "description": "The root queue item id for this workflow call chain, if any."+ },+ "workflow_call_depth": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "title": "Workflow Call Depth",+ "description": "The 1-based workflow-call depth for this queue item when it is a child execution."+ },"session": {"$ref": "#/components/schemas/GraphExecutionState","description": "The fully-populated session to be executed"@@ -65658,6 +66030,11 @@"title": "In Progress","description": "Number of queue items with status 'in_progress'"},+ "waiting": {+ "type": "integer",+ "title": "Waiting",+ "description": "Number of queue items with status 'waiting'"+ },"completed": {"type": "integer","title": "Completed",@@ -65711,6 +66088,7 @@"session_id","pending","in_progress",+ "waiting","completed","failed","canceled",@@ -70079,6 +70457,7 @@"enum": ["SchedulerField","AnyField",+ "SavedWorkflowField","CollectionField","CollectionItemField","IsIntermediate",@@ -72311,6 +72690,29 @@],"title": "Workflow"},+ "WorkflowAccessRevokedEvent": {+ "description": "Event model for workflow_access_revoked.",+ "properties": {+ "timestamp": {+ "description": "The timestamp of the event",+ "title": "Timestamp",+ "type": "integer"+ },+ "workflow_id": {+ "description": "The ID of the workflow",+ "title": "Workflow Id",+ "type": "string"+ },+ "user_id": {+ "description": "The owner of the workflow",+ "title": "User Id",+ "type": "string"+ }+ },+ "required": ["timestamp", "workflow_id", "user_id"],+ "title": "WorkflowAccessRevokedEvent",+ "type": "object"+ },"WorkflowAndGraphResponse": {"properties": {"workflow": {@@ -72342,11 +72744,310 @@"required": ["workflow", "graph"],"title": "WorkflowAndGraphResponse"},+ "WorkflowCallCompatibility": {+ "properties": {+ "is_callable": {+ "type": "boolean",+ "title": "Is Callable",+ "description": "Whether the workflow can currently be executed by call_saved_workflow."+ },+ "reason": {+ "$ref": "#/components/schemas/WorkflowCallCompatibilityReason",+ "description": "Structured compatibility result."+ },+ "message": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Message",+ "description": "Human-readable compatibility detail when unavailable."+ }+ },+ "type": "object",+ "required": ["is_callable", "reason"],+ "title": "WorkflowCallCompatibility"+ },+ "WorkflowCallCompatibilityReason": {+ "type": "string",+ "enum": [+ "ok",+ "missing_workflow_return",+ "multiple_workflow_return",+ "unsupported_node",+ "unsupported_batch_input",+ "invalid_graph",+ "invalid_inputs",+ "exceeds_capacity",+ "unknown"+ ],+ "title": "WorkflowCallCompatibilityReason"+ },+ "WorkflowCallExecution": {+ "properties": {+ "id": {+ "type": "string",+ "title": "Id",+ "description": "The workflow-call execution id."+ },+ "parent_session_id": {+ "type": "string",+ "title": "Parent Session Id",+ "description": "The parent graph execution state id."+ },+ "child_session_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Child Session Id",+ "description": "The child graph execution state id, if any."+ },+ "prepared_call_node_id": {+ "type": "string",+ "title": "Prepared Call Node Id",+ "description": "The prepared exec node id for the parent call site."+ },+ "source_call_node_id": {+ "type": "string",+ "title": "Source Call Node Id",+ "description": "The source graph node id for the parent call site."+ },+ "workflow_id": {+ "type": "string",+ "title": "Workflow Id",+ "description": "The saved workflow being called."+ },+ "depth": {+ "type": "integer",+ "minimum": 1.0,+ "title": "Depth",+ "description": "The 1-based depth of this call frame."+ },+ "status": {+ "type": "string",+ "enum": ["waiting_for_child", "running_child", "completed", "failed"],+ "title": "Status",+ "description": "The current workflow-call lifecycle state."+ },+ "error_message": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Error Message",+ "description": "Failure reason, if the call failed."+ },+ "child_session_ids": {+ "items": {+ "type": "string"+ },+ "type": "array",+ "title": "Child Session Ids",+ "description": "All child graph execution state ids."+ },+ "child_item_ids": {+ "items": {+ "type": "integer"+ },+ "type": "array",+ "title": "Child Item Ids",+ "description": "Child queue item ids in enqueue order."+ },+ "expected_child_count": {+ "type": "integer",+ "minimum": 1.0,+ "title": "Expected Child Count",+ "description": "The number of child executions for this call.",+ "default": 1+ },+ "completed_child_item_ids": {+ "items": {+ "type": "integer"+ },+ "type": "array",+ "title": "Completed Child Item Ids",+ "description": "The child queue item ids whose workflow_return outputs have been aggregated."+ },+ "aggregated_values": {+ "additionalProperties": {+ "items": {},+ "type": "array"+ },+ "type": "object",+ "title": "Aggregated Values",+ "description": "The aggregated workflow_return values accumulated from child executions."+ },+ "child_outputs": {+ "additionalProperties": {+ "additionalProperties": true,+ "type": "object"+ },+ "type": "object",+ "title": "Child Outputs",+ "description": "Workflow return values keyed by child queue item id."+ }+ },+ "type": "object",+ "required": [+ "parent_session_id",+ "prepared_call_node_id",+ "source_call_node_id",+ "workflow_id",+ "depth",+ "status"+ ],+ "title": "WorkflowCallExecution",+ "description": "Tracks one parent/child workflow-call relationship and its lifecycle."+ },+ "WorkflowCallFrame": {+ "properties": {+ "prepared_call_node_id": {+ "type": "string",+ "title": "Prepared Call Node Id",+ "description": "The prepared exec node id for the call site."+ },+ "source_call_node_id": {+ "type": "string",+ "title": "Source Call Node Id",+ "description": "The source graph node id for the call site."+ },+ "workflow_id": {+ "type": "string",+ "title": "Workflow Id",+ "description": "The saved workflow being called."+ },+ "depth": {+ "type": "integer",+ "minimum": 1.0,+ "title": "Depth",+ "description": "The 1-based depth of this call frame."+ }+ },+ "type": "object",+ "required": ["prepared_call_node_id", "source_call_node_id", "workflow_id", "depth"],+ "title": "WorkflowCallFrame",+ "description": "Represents one workflow-call frame in a nested call chain."+ },+ "WorkflowCallParentRef": {+ "properties": {+ "workflow_call_id": {+ "type": "string",+ "title": "Workflow Call Id",+ "description": "The workflow-call execution id."+ },+ "parent_session_id": {+ "type": "string",+ "title": "Parent Session Id",+ "description": "The parent graph execution state id."+ },+ "prepared_call_node_id": {+ "type": "string",+ "title": "Prepared Call Node Id",+ "description": "The prepared exec node id for the parent call site."+ },+ "source_call_node_id": {+ "type": "string",+ "title": "Source Call Node Id",+ "description": "The source graph node id for the parent call site."+ },+ "workflow_id": {+ "type": "string",+ "title": "Workflow Id",+ "description": "The saved workflow being called."+ },+ "depth": {+ "type": "integer",+ "minimum": 1.0,+ "title": "Depth",+ "description": "The 1-based depth of this call frame."+ }+ },+ "type": "object",+ "required": [+ "workflow_call_id",+ "parent_session_id",+ "prepared_call_node_id",+ "source_call_node_id",+ "workflow_id",+ "depth"+ ],+ "title": "WorkflowCallParentRef",+ "description": "Reference from a child execution state back to its parent workflow-call relationship."+ },"WorkflowCategory": {"type": "string","enum": ["user", "default"],"title": "WorkflowCategory"},+ "WorkflowCreatedEvent": {+ "description": "Event model for workflow_created",+ "properties": {+ "timestamp": {+ "description": "The timestamp of the event",+ "title": "Timestamp",+ "type": "integer"+ },+ "workflow_id": {+ "description": "The ID of the workflow",+ "title": "Workflow Id",+ "type": "string"+ },+ "user_id": {+ "description": "The owner of the workflow",+ "title": "User Id",+ "type": "string"+ },+ "is_public": {+ "description": "Whether the workflow is shared with all users",+ "title": "Is Public",+ "type": "boolean"+ }+ },+ "required": ["timestamp", "workflow_id", "user_id", "is_public"],+ "title": "WorkflowCreatedEvent",+ "type": "object"+ },+ "WorkflowDeletedEvent": {+ "description": "Event model for workflow_deleted",+ "properties": {+ "timestamp": {+ "description": "The timestamp of the event",+ "title": "Timestamp",+ "type": "integer"+ },+ "workflow_id": {+ "description": "The ID of the workflow",+ "title": "Workflow Id",+ "type": "string"+ },+ "user_id": {+ "description": "The owner of the workflow",+ "title": "User Id",+ "type": "string"+ },+ "is_public": {+ "description": "Whether the workflow was shared when it was deleted",+ "title": "Is Public",+ "type": "boolean"+ }+ },+ "required": ["timestamp", "workflow_id", "user_id", "is_public"],+ "title": "WorkflowDeletedEvent",+ "type": "object"+ },"WorkflowMeta": {"properties": {"version": {@@ -72525,6 +73226,17 @@],"title": "Thumbnail Url","description": "The URL of the workflow thumbnail."+ },+ "call_saved_workflow_compatibility": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/WorkflowCallCompatibility"+ },+ {+ "type": "null"+ }+ ],+ "description": "Whether this workflow is currently callable by call_saved_workflow."}},"type": "object",@@ -72626,12 +73338,359 @@],"title": "Thumbnail Url","description": "The URL of the workflow thumbnail."+ },+ "call_saved_workflow_compatibility": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/WorkflowCallCompatibility"+ },+ {+ "type": "null"+ }+ ],+ "description": "Whether this workflow is currently callable by call_saved_workflow."}},"type": "object","required": ["workflow_id", "name", "created_at", "updated_at", "user_id", "is_public", "workflow"],"title": "WorkflowRecordWithThumbnailDTO"},+ "WorkflowReturnGetInvocation": {+ "category": "workflow",+ "class": "invocation",+ "classification": "beta",+ "description": "Extracts one named value from a callable workflow return.",+ "node_pack": "invokeai",+ "properties": {+ "id": {+ "description": "The id of this instance of an invocation. Must be unique among all instances of invocations.",+ "field_kind": "node_attribute",+ "title": "Id",+ "type": "string"+ },+ "is_intermediate": {+ "default": false,+ "description": "Whether or not this is an intermediate invocation.",+ "field_kind": "node_attribute",+ "input": "direct",+ "orig_required": true,+ "title": "Is Intermediate",+ "type": "boolean",+ "ui_hidden": false,+ "ui_type": "IsIntermediate"+ },+ "use_cache": {+ "default": false,+ "description": "Whether or not to use the cache",+ "field_kind": "node_attribute",+ "title": "Use Cache",+ "type": "boolean"+ },+ "values": {+ "additionalProperties": true,+ "default": {},+ "description": "The named workflow return values.",+ "field_kind": "input",+ "input": "connection",+ "orig_default": {},+ "orig_required": false,+ "title": "Values",+ "type": "object",+ "ui_type": "AnyField"+ },+ "key": {+ "default": "",+ "description": "The return key to extract.",+ "field_kind": "input",+ "input": "any",+ "orig_default": "",+ "orig_required": false,+ "title": "Key",+ "type": "string"+ },+ "type": {+ "const": "workflow_return_get",+ "default": "workflow_return_get",+ "field_kind": "node_attribute",+ "title": "type",+ "type": "string"+ }+ },+ "required": ["type", "id"],+ "tags": ["workflow", "return", "input"],+ "title": "Get Workflow Return Value",+ "type": "object",+ "version": "1.0.0",+ "output": {+ "$ref": "#/components/schemas/WorkflowReturnGetOutput"+ }+ },+ "WorkflowReturnGetOutput": {+ "class": "output",+ "description": "A value extracted from named workflow return values.",+ "properties": {+ "value": {+ "description": "The extracted workflow return value.",+ "field_kind": "output",+ "title": "Value",+ "ui_hidden": false,+ "ui_type": "AnyField"+ },+ "type": {+ "const": "workflow_return_get_output",+ "default": "workflow_return_get_output",+ "field_kind": "node_attribute",+ "title": "type",+ "type": "string"+ }+ },+ "required": ["output_meta", "value", "type", "type"],+ "title": "WorkflowReturnGetOutput",+ "type": "object"+ },+ "WorkflowReturnInvocation": {+ "category": "workflow",+ "class": "invocation",+ "classification": "beta",+ "description": "Defines the explicit named result returned by a callable workflow.",+ "node_pack": "invokeai",+ "properties": {+ "id": {+ "description": "The id of this instance of an invocation. Must be unique among all instances of invocations.",+ "field_kind": "node_attribute",+ "title": "Id",+ "type": "string"+ },+ "is_intermediate": {+ "default": false,+ "description": "Whether or not this is an intermediate invocation.",+ "field_kind": "node_attribute",+ "input": "direct",+ "orig_required": true,+ "title": "Is Intermediate",+ "type": "boolean",+ "ui_hidden": false,+ "ui_type": "IsIntermediate"+ },+ "use_cache": {+ "default": false,+ "description": "Whether or not to use the cache",+ "field_kind": "node_attribute",+ "title": "Use Cache",+ "type": "boolean"+ },+ "values": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/WorkflowReturnValueField"+ },+ {+ "items": {+ "$ref": "#/components/schemas/WorkflowReturnValueField"+ },+ "type": "array"+ }+ ],+ "default": [],+ "description": "The named values returned to a calling workflow.",+ "field_kind": "input",+ "input": "connection",+ "orig_default": [],+ "orig_required": false,+ "title": "Values"+ },+ "type": {+ "const": "workflow_return",+ "default": "workflow_return",+ "field_kind": "node_attribute",+ "title": "type",+ "type": "string"+ }+ },+ "required": ["type", "id"],+ "tags": ["workflow", "return", "output"],+ "title": "Workflow Return",+ "type": "object",+ "version": "1.0.0",+ "output": {+ "$ref": "#/components/schemas/WorkflowReturnOutput"+ }+ },+ "WorkflowReturnOutput": {+ "class": "output",+ "description": "The explicit named values returned from a callable workflow.",+ "properties": {+ "values": {+ "additionalProperties": true,+ "default": {},+ "description": "The workflow return values, keyed by return name.",+ "field_kind": "output",+ "title": "Values",+ "type": "object",+ "ui_hidden": false,+ "ui_type": "AnyField"+ },+ "type": {+ "const": "workflow_return_output",+ "default": "workflow_return_output",+ "field_kind": "node_attribute",+ "title": "type",+ "type": "string"+ }+ },+ "required": ["output_meta", "values", "type", "type"],+ "title": "WorkflowReturnOutput",+ "type": "object"+ },+ "WorkflowReturnValueField": {+ "description": "One named workflow return value.",+ "properties": {+ "key": {+ "description": "The workflow return key.",+ "title": "Key",+ "type": "string"+ },+ "value": {+ "default": null,+ "description": "The workflow return value.",+ "title": "Value"+ }+ },+ "required": ["key"],+ "title": "WorkflowReturnValueField",+ "type": "object"+ },+ "WorkflowReturnValueInvocation": {+ "category": "workflow",+ "class": "invocation",+ "classification": "beta",+ "description": "Creates one named value for a callable workflow return.",+ "node_pack": "invokeai",+ "properties": {+ "id": {+ "description": "The id of this instance of an invocation. Must be unique among all instances of invocations.",+ "field_kind": "node_attribute",+ "title": "Id",+ "type": "string"+ },+ "is_intermediate": {+ "default": false,+ "description": "Whether or not this is an intermediate invocation.",+ "field_kind": "node_attribute",+ "input": "direct",+ "orig_required": true,+ "title": "Is Intermediate",+ "type": "boolean",+ "ui_hidden": false,+ "ui_type": "IsIntermediate"+ },+ "use_cache": {+ "default": false,+ "description": "Whether or not to use the cache",+ "field_kind": "node_attribute",+ "title": "Use Cache",+ "type": "boolean"+ },+ "key": {+ "default": "",+ "description": "The return key.",+ "field_kind": "input",+ "input": "any",+ "orig_default": "",+ "orig_required": false,+ "title": "Key",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {},+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "The value returned under this key.",+ "field_kind": "input",+ "input": "any",+ "orig_default": null,+ "orig_required": false,+ "title": "Value",+ "ui_type": "AnyField"+ },+ "type": {+ "const": "workflow_return_value",+ "default": "workflow_return_value",+ "field_kind": "node_attribute",+ "title": "type",+ "type": "string"+ }+ },+ "required": ["type", "id"],+ "tags": ["workflow", "return", "output"],+ "title": "Workflow Return Value",+ "type": "object",+ "version": "1.0.0",+ "output": {+ "$ref": "#/components/schemas/WorkflowReturnValueOutput"+ }+ },+ "WorkflowReturnValueOutput": {+ "class": "output",+ "description": "A named workflow return value.",+ "properties": {+ "value": {+ "$ref": "#/components/schemas/WorkflowReturnValueField",+ "description": "The named workflow return value.",+ "field_kind": "output",+ "title": "Return Value",+ "ui_hidden": false,+ "ui_type": "CollectionItemField"+ },+ "type": {+ "const": "workflow_return_value_output",+ "default": "workflow_return_value_output",+ "field_kind": "node_attribute",+ "title": "type",+ "type": "string"+ }+ },+ "required": ["output_meta", "value", "type", "type"],+ "title": "WorkflowReturnValueOutput",+ "type": "object"+ },+ "WorkflowUpdatedEvent": {+ "description": "Event model for workflow_updated",+ "properties": {+ "timestamp": {+ "description": "The timestamp of the event",+ "title": "Timestamp",+ "type": "integer"+ },+ "workflow_id": {+ "description": "The ID of the workflow",+ "title": "Workflow Id",+ "type": "string"+ },+ "user_id": {+ "description": "The owner of the workflow",+ "title": "User Id",+ "type": "string"+ },+ "old_is_public": {+ "description": "Whether the workflow was shared before the update",+ "title": "Old Is Public",+ "type": "boolean"+ },+ "new_is_public": {+ "description": "Whether the workflow is shared after the update",+ "title": "New Is Public",+ "type": "boolean"+ }+ },+ "required": ["timestamp", "workflow_id", "user_id", "old_is_public", "new_is_public"],+ "title": "WorkflowUpdatedEvent",+ "type": "object"+ },"WorkflowWithoutID": {"properties": {"name": {diff --git a/invokeai/frontend/web/public/locales/en.json b/invokeai/frontend/web/public/locales/en.jsonindex fdb9391f97..7f4f88f8bb 100644--- a/invokeai/frontend/web/public/locales/en.json+++ b/invokeai/frontend/web/public/locales/en.json@@ -448,6 +448,7 @@"credits": "Credits","pending": "Pending","in_progress": "In Progress",+ "waiting": "Waiting On Child Workflow","paused": "Paused","completed": "Completed","failed": "Failed",@@ -1491,6 +1492,12 @@"loadWorkflow": "Load Workflow","noWorkflows": "No Workflows","noMatchingWorkflows": "No Matching Workflows",+ "savedWorkflowChoose": "Choose a workflow",+ "savedWorkflowDefaultBadge": "Default",+ "savedWorkflowMissing": "Missing or inaccessible workflow",+ "savedWorkflowUnsupported": "Unsupported",+ "savedWorkflowSelectExposedFields": "Select a workflow with exposed form fields",+ "savedWorkflowUpdating": "Updating...","noWorkflow": "No Workflow","noWorkflowToSave": "No workflow to save","unableToUpdateNode": "Node update failed: node {{node}} of type {{type}} (may require deleting and recreating)",@@ -2482,6 +2489,17 @@"noRecentWorkflows": "No Recent Workflows","private": "Private","shared": "Shared",+ "savedWorkflowUnsupportedDescription": "This workflow cannot currently be used by Call Saved Workflow.",+ "savedWorkflowCompatibility": {+ "missingWorkflowReturn": "The workflow must contain a Workflow Return node.",+ "multipleWorkflowReturn": "The workflow may contain only one Workflow Return node.",+ "unsupportedNode": "The workflow contains a node that Call Saved Workflow does not support.",+ "unsupportedBatchInput": "The workflow contains batch input wiring that Call Saved Workflow does not support.",+ "invalidGraph": "The workflow graph is invalid and cannot be called.",+ "invalidInputs": "The workflow has invalid exposed inputs and cannot be called.",+ "exceedsCapacity": "The workflow would create more child executions than the queue currently allows.",+ "unknown": "The workflow cannot currently be used by Call Saved Workflow."+ },"published": "Published","browseWorkflows": "Browse Workflows","deselectAll": "Deselect All",diff --git a/invokeai/frontend/web/src/features/controlLayers/components/StagingArea/state.ts b/invokeai/frontend/web/src/features/controlLayers/components/StagingArea/state.tsindex 6c16a8fdf2..4ee71acdff 100644--- a/invokeai/frontend/web/src/features/controlLayers/components/StagingArea/state.ts+++ b/invokeai/frontend/web/src/features/controlLayers/components/StagingArea/state.ts@@ -70,7 +70,9 @@ const getQueueItemStatusRank = (status: S['SessionQueueItem']['status']): numberswitch (status) {case 'pending':return 0;+ // Waiting items are suspended on child workflow execution, but they are still nonterminal.case 'in_progress':+ case 'waiting':return 1;case 'completed':case 'failed':diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/CallSavedWorkflowNode.tsx b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/CallSavedWorkflowNode.tsxnew file mode 100644index 0000000000..8db547a40d--- /dev/null+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/CallSavedWorkflowNode.tsx@@ -0,0 +1,198 @@+import type { SystemStyleObject } from '@invoke-ai/ui-library';+import { Badge, Flex, Grid, GridItem } from '@invoke-ai/ui-library';+import { useStore } from '@nanostores/react';+import { useAppDispatch, useAppSelector } from 'app/store/storeHooks';+import { InputFieldEditModeNodes } from 'features/nodes/components/flow/nodes/Invocation/fields/InputFieldEditModeNodes';+import { InputFieldGate } from 'features/nodes/components/flow/nodes/Invocation/fields/InputFieldGate';+import { OutputFieldGate } from 'features/nodes/components/flow/nodes/Invocation/fields/OutputFieldGate';+import { OutputFieldNodesEditorView } from 'features/nodes/components/flow/nodes/Invocation/fields/OutputFieldNodesEditorView';+import InvocationNodeFooter from 'features/nodes/components/flow/nodes/Invocation/InvocationNodeFooter';+import InvocationNodeHeader from 'features/nodes/components/flow/nodes/Invocation/InvocationNodeHeader';+import { useInputFieldInstance } from 'features/nodes/hooks/useInputFieldInstance';+import { useOutputFieldNames } from 'features/nodes/hooks/useOutputFieldNames';+import { useWithFooter } from 'features/nodes/hooks/useWithFooter';+import { $templates, callSavedWorkflowDynamicFieldsChanged } from 'features/nodes/store/nodesSlice';+import { selectNodesSlice } from 'features/nodes/store/selectors';+import type { SavedWorkflowFieldInputInstance } from 'features/nodes/types/field';+import { memo, useEffect, useMemo, useRef } from 'react';+import { useTranslation } from 'react-i18next';+import { useGetWorkflowQuery } from 'services/api/endpoints/workflows';++import {+ getSavedWorkflowDynamicEdgeIdsToRemove,+ getSavedWorkflowDynamicFields,+ shouldSyncSavedWorkflowDynamicFields,+} from './callSavedWorkflowFormUtils';++const bodySx: SystemStyleObject = {+ flexDirection: 'column',+ w: 'full',+ h: 'full',+ py: 2,+ gap: 1,+ borderBottomRadius: 'base',+ '&[data-with-footer="true"]': {+ borderBottomRadius: 0,+ },+ '&[data-with-footer="false"]': {+ pb: 4,+ },+};++const dynamicFieldSx: SystemStyleObject = {+ w: 'full',+};++type Props = {+ nodeId: string;+ isOpen: boolean;+};++const CallSavedWorkflowNode = ({ nodeId, isOpen }: Props) => {+ const withFooter = useWithFooter();+ const { t } = useTranslation();+ const workflowIdField = useInputFieldInstance<SavedWorkflowFieldInputInstance>('workflow_id');+ const templates = useStore($templates);+ const dispatch = useAppDispatch();+ const nodesState = useAppSelector(selectNodesSlice);++ const { data: workflow } = useGetWorkflowQuery(workflowIdField.value, {+ skip: !workflowIdField.value,+ });++ const shouldSyncDynamicFields = shouldSyncSavedWorkflowDynamicFields({ workflowId: workflowIdField.value, workflow });+ const dynamicFields = useMemo(() => getSavedWorkflowDynamicFields(workflow, templates), [templates, workflow]);+ const edgeIdsToRemove = useMemo(+ () =>+ getSavedWorkflowDynamicEdgeIdsToRemove({+ nodeId,+ fields: dynamicFields,+ nodes: nodesState.nodes,+ edges: nodesState.edges,+ templates,+ }),+ [dynamicFields, nodeId, nodesState.edges, nodesState.nodes, templates]+ );+ const syncKey = useMemo(+ () => JSON.stringify({ fields: dynamicFields, edgeIdsToRemove }),+ [dynamicFields, edgeIdsToRemove]+ );+ const lastSyncKeyRef = useRef<string | null>(null);++ useEffect(() => {+ if (!shouldSyncDynamicFields) {+ return;+ }+ if (lastSyncKeyRef.current === syncKey) {+ return;+ }+ lastSyncKeyRef.current = syncKey;+ dispatch(callSavedWorkflowDynamicFieldsChanged({ nodeId, fields: dynamicFields, edgeIdsToRemove }));+ }, [dispatch, dynamicFields, edgeIdsToRemove, nodeId, shouldSyncDynamicFields, syncKey]);++ return (+ <>+ <InvocationNodeHeader nodeId={nodeId} isOpen={isOpen} />+ {isOpen && (+ <>+ <Flex layerStyle="nodeBody" sx={bodySx} data-with-footer={withFooter}>+ <Flex flexDir="column" px={2} w="full" h="full">+ <Grid gridTemplateColumns="1fr auto" gridAutoRows="1fr">+ <GridItem gridColumnStart={1} gridRowStart={1}>+ <InputFieldGate nodeId={nodeId} fieldName="workflow_id">+ <InputFieldEditModeNodes nodeId={nodeId} fieldName="workflow_id" />+ </InputFieldGate>+ </GridItem>+ <OutputFields nodeId={nodeId} />+ </Grid>+ <DynamicFieldsSection+ nodeId={nodeId}+ fields={dynamicFields}+ emptyMessage={t('nodes.savedWorkflowSelectExposedFields')}+ />+ </Flex>+ </Flex>+ {withFooter && <InvocationNodeFooter nodeId={nodeId} />}+ </>+ )}+ </>+ );+};++export default memo(CallSavedWorkflowNode);++const DynamicFieldsSection = memo(+ ({+ nodeId,+ fields,+ emptyMessage,+ }: {+ nodeId: string;+ fields: ReturnType<typeof getSavedWorkflowDynamicFields>;+ emptyMessage: string;+ }) => {+ if (fields.length === 0) {+ return (+ <Badge variant="subtle" alignSelf="flex-start">+ {emptyMessage}+ </Badge>+ );+ }++ return (+ <>+ {fields.map((field) => (+ <DynamicFieldRow+ key={field.fieldName}+ nodeId={nodeId}+ fieldName={field.fieldName}+ settings={field.settings}+ />+ ))}+ </>+ );+ }+);+DynamicFieldsSection.displayName = 'DynamicFieldsSection';++const DynamicFieldRow = memo(+ ({+ nodeId,+ fieldName,+ settings,+ }: {+ nodeId: string;+ fieldName: string;+ settings: ReturnType<typeof getSavedWorkflowDynamicFields>[number]['settings'];+ }) => {+ return (+ <Flex sx={dynamicFieldSx}>+ <InputFieldGate nodeId={nodeId} fieldName={fieldName}>+ <InputFieldEditModeNodes nodeId={nodeId} fieldName={fieldName} settings={settings} />+ </InputFieldGate>+ </Flex>+ );+ }+);+DynamicFieldRow.displayName = 'DynamicFieldRow';++const OutputFields = memo(({ nodeId }: { nodeId: string }) => {+ const fieldNames = useOutputFieldNames();++ if (fieldNames.length === 0) {+ return null;+ }++ return (+ <>+ {fieldNames.map((fieldName, i) => (+ <GridItem gridColumnStart={2} gridRowStart={i + 1} key={`${nodeId}.${fieldName}.output-field`}>+ <OutputFieldGate nodeId={nodeId} fieldName={fieldName}>+ <OutputFieldNodesEditorView nodeId={nodeId} fieldName={fieldName} />+ </OutputFieldGate>+ </GridItem>+ ))}+ </>+ );+});+OutputFields.displayName = 'OutputFields';diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/InvocationNodeWrapper.tsx b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/InvocationNodeWrapper.tsxindex 7a4ea9ca65..1961e4dc75 100644--- a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/InvocationNodeWrapper.tsx+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/InvocationNodeWrapper.tsx@@ -3,6 +3,7 @@ import { createSelector } from '@reduxjs/toolkit';import type { Node, NodeProps } from '@xyflow/react';import { useAppSelector } from 'app/store/storeHooks';import NodeWrapper from 'features/nodes/components/flow/nodes/common/NodeWrapper';+import CallSavedWorkflowNode from 'features/nodes/components/flow/nodes/Invocation/CallSavedWorkflowNode';import InvocationNode from 'features/nodes/components/flow/nodes/Invocation/InvocationNode';import { $templates } from 'features/nodes/store/nodesSlice';import { selectNodes } from 'features/nodes/store/selectors';@@ -40,7 +41,11 @@ const InvocationNodeWrapper = (props: NodeProps<Node<InvocationNodeData>>) => {return (<InvocationNodeContextProvider nodeId={nodeId}><NodeWrapper nodeId={nodeId} selected={selected}>- <InvocationNode nodeId={nodeId} isOpen={isOpen} />+ {type === 'call_saved_workflow' ? (+ <CallSavedWorkflowNode nodeId={nodeId} isOpen={isOpen} />+ ) : (+ <InvocationNode nodeId={nodeId} isOpen={isOpen} />+ )}</NodeWrapper></InvocationNodeContextProvider>);diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/callSavedWorkflowFormUtils.test.ts b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/callSavedWorkflowFormUtils.test.tsnew file mode 100644index 0000000000..68290298bb--- /dev/null+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/callSavedWorkflowFormUtils.test.ts@@ -0,0 +1,292 @@+import { buildEdge, buildNode, call_saved_workflow, templates } from 'features/nodes/store/util/testUtils';+import type { BooleanFieldInputTemplate } from 'features/nodes/types/field';+import {+ type BuilderForm,+ buildHeading,+ buildNodeFieldElement,+ getDefaultForm,+ isContainerElement,+} from 'features/nodes/types/workflow';+import type { paths } from 'services/api/schema';+import { describe, expect, it } from 'vitest';++import {+ getRenderableWorkflowForm,+ getSavedWorkflowDynamicEdgeIdsToRemove,+ getSavedWorkflowDynamicFields,+ getSavedWorkflowFormFieldData,+ shouldSyncSavedWorkflowDynamicFields,+} from './callSavedWorkflowFormUtils';++type WorkflowResponse =+ paths['/api/v1/workflows/i/{workflow_id}']['get']['responses']['200']['content']['application/json'];++const addTemplate = templates.add;+if (!addTemplate) {+ throw new Error('Expected add template');+}+const addInputA = addTemplate.inputs.a;+const addInputB = addTemplate.inputs.b;+if (!addInputA || !addInputB) {+ throw new Error('Expected add template inputs');+}++const getRootChildren = (form: BuilderForm): string[] => {+ const root = form.elements[form.rootElementId];++ if (!root || !isContainerElement(root)) {+ throw new Error('Expected root container');+ }++ return root.data.children;+};++const buildWorkflowResponse = (overrides?: {+ exposedFields?: Array<{ nodeId: string; fieldName: string }>;+ form?: BuilderForm | null;+ inputs?: Record<string, { name: string; label?: string; value?: unknown }>;+}): WorkflowResponse =>+ ({+ workflow_id: 'workflow-1',+ name: 'Workflow 1',+ created_at: '2026-04-08T00:00:00Z',+ updated_at: '2026-04-08T00:00:00Z',+ opened_at: null,+ user_id: 'user-1',+ is_public: false,+ thumbnail_url: null,+ workflow: {+ id: 'workflow-1',+ name: 'Workflow 1',+ author: 'InvokeAI',+ description: 'A workflow',+ version: '1.0.0',+ contact: '',+ tags: '',+ notes: '',+ exposedFields: overrides?.exposedFields ?? [],+ meta: {+ category: 'user',+ version: '3.0.0',+ },+ nodes: [+ {+ id: 'node-1',+ type: 'invocation',+ data: {+ id: 'node-1',+ type: 'add',+ inputs: overrides?.inputs ?? {+ a: { name: 'a', label: 'Left Addend', value: 1 },+ b: { name: 'b', label: '', value: 2 },+ },+ },+ },+ ],+ edges: [],+ form: overrides?.form ?? getDefaultForm(),+ },+ }) as WorkflowResponse;++describe('callSavedWorkflowFormUtils', () => {+ it('does not sync dynamic fields while a selected saved workflow is still loading', () => {+ expect(+ shouldSyncSavedWorkflowDynamicFields({+ workflowId: 'workflow-1',+ workflow: undefined,+ })+ ).toBe(false);+ });++ it('syncs dynamic fields when no workflow is selected or when the selected workflow is loaded', () => {+ expect(+ shouldSyncSavedWorkflowDynamicFields({+ workflowId: '',+ workflow: undefined,+ })+ ).toBe(true);+ expect(+ shouldSyncSavedWorkflowDynamicFields({+ workflowId: 'workflow-1',+ workflow: buildWorkflowResponse(),+ })+ ).toBe(true);+ });++ it('returns the stored form when it is non-empty and valid', () => {+ const form = getDefaultForm();+ const heading = buildHeading('Workflow Inputs');+ form.elements[heading.id] = { ...heading, parentId: form.rootElementId };+ getRootChildren(form).push(heading.id);++ const workflow = buildWorkflowResponse({ form });++ expect(getRenderableWorkflowForm(workflow, templates)).toBe(form);+ });++ it('builds a fallback form from exposed fields when the stored form is empty', () => {+ const workflow = buildWorkflowResponse({+ exposedFields: [{ nodeId: 'node-1', fieldName: 'a' }],+ });++ const form = getRenderableWorkflowForm(workflow, templates);++ expect(form).not.toBeNull();+ expect(form ? getRootChildren(form) : []).toHaveLength(1);+ const childId = form ? getRootChildren(form)[0] : undefined;+ expect(childId).toBeDefined();+ expect(childId ? form?.elements[childId]?.type : undefined).toBe('node-field');+ });++ it('skips exposed fields that do not resolve to a known node field', () => {+ const workflow = buildWorkflowResponse({+ exposedFields: [{ nodeId: 'missing-node', fieldName: 'a' }],+ });++ const form = getRenderableWorkflowForm(workflow, templates);++ expect(form).not.toBeNull();+ expect(form ? getRootChildren(form) : []).toHaveLength(0);+ });++ it('uses the stored field label when available', () => {+ const element = buildNodeFieldElement('node-1', 'a', addInputA.type);+ const workflow = buildWorkflowResponse();++ expect(getSavedWorkflowFormFieldData(workflow, templates, element)).toEqual(+ expect.objectContaining({+ label: 'Left Addend',+ description: 'The first number',+ typeName: 'IntegerField',+ isMissing: false,+ })+ );+ });++ it('falls back to the template title when the stored field label is empty', () => {+ const element = buildNodeFieldElement('node-1', 'b', addInputB.type);+ const workflow = buildWorkflowResponse();++ expect(getSavedWorkflowFormFieldData(workflow, templates, element)).toEqual(+ expect.objectContaining({+ label: 'B',+ description: 'The second number',+ typeName: 'IntegerField',+ isMissing: false,+ })+ );+ });++ it('marks missing node field references as missing', () => {+ const element = buildNodeFieldElement('missing-node', 'a', addInputA.type);+ const workflow = buildWorkflowResponse();++ expect(getSavedWorkflowFormFieldData(workflow, templates, element)).toEqual(+ expect.objectContaining({+ label: 'a',+ description: '',+ typeName: null,+ isMissing: true,+ })+ );+ });++ it('builds ordered dynamic fields from the workflow form', () => {+ const workflow = buildWorkflowResponse({+ exposedFields: [+ { nodeId: 'node-1', fieldName: 'a' },+ { nodeId: 'node-1', fieldName: 'b' },+ ],+ });++ const dynamicFields = getSavedWorkflowDynamicFields(workflow, templates);++ expect(dynamicFields).toHaveLength(2);+ expect(dynamicFields[0]?.fieldName).toBe('saved_workflow_input::node-1::a');+ expect(dynamicFields[1]?.fieldName).toBe('saved_workflow_input::node-1::b');+ expect(dynamicFields[0]?.fieldTemplate.title).toBe('Left Addend');+ expect(dynamicFields[1]?.fieldTemplate.title).toBe('B');+ expect(dynamicFields[0]?.fieldTemplate.name).toBe(dynamicFields[0]?.fieldName);+ expect(dynamicFields[1]?.fieldTemplate.ui_order).toBe(1);+ expect(dynamicFields[0]?.initialValue).toBe(1);+ expect(dynamicFields[1]?.initialValue).toBe(2);+ });++ it('preserves inbound edges when the same exposed dynamic field remains compatible', () => {+ const sourceNode = buildNode(addTemplate);+ const targetNode = buildNode(call_saved_workflow);+ const fields = getSavedWorkflowDynamicFields(+ buildWorkflowResponse({+ exposedFields: [{ nodeId: 'node-1', fieldName: 'a' }],+ }),+ templates+ );++ const edgeIdsToRemove = getSavedWorkflowDynamicEdgeIdsToRemove({+ nodeId: targetNode.id,+ fields,+ nodes: [sourceNode, targetNode],+ edges: [buildEdge(sourceNode.id, 'value', targetNode.id, 'saved_workflow_input::node-1::a')],+ templates,+ });++ expect(edgeIdsToRemove).toEqual([]);+ });++ it('removes inbound edges when a previously connected field is no longer exposed', () => {+ const sourceNode = buildNode(addTemplate);+ const targetNode = buildNode(call_saved_workflow);+ const edge = buildEdge(sourceNode.id, 'value', targetNode.id, 'saved_workflow_input::node-1::a');++ const edgeIdsToRemove = getSavedWorkflowDynamicEdgeIdsToRemove({+ nodeId: targetNode.id,+ fields: [],+ nodes: [sourceNode, targetNode],+ edges: [edge],+ templates,+ });++ expect(edgeIdsToRemove).toEqual([edge.id]);+ });++ it('removes inbound edges when an exposed field changes to an incompatible type', () => {+ const sourceNode = buildNode(addTemplate);+ const targetNode = buildNode(call_saved_workflow);+ const edge = buildEdge(sourceNode.id, 'value', targetNode.id, 'saved_workflow_input::node-1::a');++ const booleanTemplate: BooleanFieldInputTemplate = {+ name: 'saved_workflow_input::node-1::a',+ title: 'Enabled',+ required: false,+ description: 'Whether the workflow is enabled',+ fieldKind: 'input',+ input: 'any',+ ui_hidden: false,+ default: false,+ type: {+ name: 'BooleanField',+ cardinality: 'SINGLE',+ batch: false,+ },+ };++ const edgeIdsToRemove = getSavedWorkflowDynamicEdgeIdsToRemove({+ nodeId: targetNode.id,+ fields: [+ {+ fieldName: 'saved_workflow_input::node-1::a',+ fieldTemplate: booleanTemplate,+ label: 'Enabled',+ description: 'Whether the workflow is enabled',+ initialValue: false,+ settings: undefined,+ },+ ],+ nodes: [sourceNode, targetNode],+ edges: [edge],+ templates,+ });++ expect(edgeIdsToRemove).toEqual([edge.id]);+ });+});diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/callSavedWorkflowFormUtils.ts b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/callSavedWorkflowFormUtils.tsnew file mode 100644index 0000000000..fbc600f85c--- /dev/null+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/callSavedWorkflowFormUtils.ts@@ -0,0 +1,307 @@+import { addElement, getIsFormEmpty } from 'features/nodes/components/sidePanel/builder/form-manipulation';+import { CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX } from 'features/nodes/store/nodesSlice';+import type { Templates } from 'features/nodes/store/types';+import { validateConnectionTypes } from 'features/nodes/store/util/validateConnectionTypes';+import type { FieldInputTemplate, StatefulFieldValue } from 'features/nodes/types/field';+import { isStatefulFieldType } from 'features/nodes/types/field';+import type { AnyEdge, AnyNode } from 'features/nodes/types/invocation';+import { isInvocationNode } from 'features/nodes/types/invocation';+import {+ type BuilderForm,+ buildNodeFieldElement,+ type FormElement,+ getDefaultForm,+ isContainerElement,+ type NodeFieldElement,+ validateFormStructure,+} from 'features/nodes/types/workflow';+import type { paths } from 'services/api/schema';++type WorkflowResponse =+ paths['/api/v1/workflows/i/{workflow_id}']['get']['responses']['200']['content']['application/json'];++type WorkflowNodeLike = {+ data?: {+ id?: string;+ type?: string;+ inputs?: Record<string, { label?: string; description?: string; value?: StatefulFieldValue }>;+ };+};++type ExposedFieldLike = {+ nodeId?: string;+ fieldName?: string;+};++type SavedWorkflowFormFieldData = {+ label: string;+ description: string;+ typeName: string | null;+ isMissing: boolean;+};++type SavedWorkflowDynamicField = {+ fieldName: string;+ fieldTemplate: FieldInputTemplate;+ label: string;+ description: string;+ initialValue: StatefulFieldValue;+ settings: NodeFieldElement['data']['settings'];+};++const getStoredForm = (workflow: WorkflowResponse | undefined): BuilderForm | null => {+ const form = workflow?.workflow.form;++ if (!form || typeof form !== 'object' || !('elements' in form) || !('rootElementId' in form)) {+ return null;+ }++ return form as unknown as BuilderForm;+};++const getWorkflowNodes = (workflow: WorkflowResponse | undefined): WorkflowNodeLike[] => {+ return (workflow?.workflow.nodes ?? []) as WorkflowNodeLike[];+};++const buildFormFromExposedFields = (+ workflow: WorkflowResponse | undefined,+ templates: Templates+): BuilderForm | null => {+ const exposedFields = (workflow?.workflow.exposedFields ?? []) as ExposedFieldLike[];++ if (exposedFields.length === 0) {+ return null;+ }++ const nodes = getWorkflowNodes(workflow);+ const form = getDefaultForm();++ for (const { nodeId, fieldName } of [...exposedFields].reverse()) {+ if (!nodeId || !fieldName) {+ continue;+ }++ const node = nodes.find((candidate) => candidate.data?.id === nodeId);+ const nodeType = node?.data?.type;+ if (!nodeType) {+ continue;+ }++ const fieldTemplate = templates[nodeType]?.inputs[fieldName];+ if (!fieldTemplate) {+ continue;+ }++ const element = buildNodeFieldElement(nodeId, fieldName, fieldTemplate.type);+ element.data.showDescription = false;+ addElement({+ form,+ element,+ parentId: form.rootElementId,+ index: 0,+ });+ }++ return form;+};++export const getRenderableWorkflowForm = (+ workflow: WorkflowResponse | undefined,+ templates: Templates+): BuilderForm | null => {+ const storedForm = getStoredForm(workflow);++ if (storedForm && validateFormStructure(storedForm) && !getIsFormEmpty(storedForm)) {+ return storedForm;+ }++ const fallbackForm = buildFormFromExposedFields(workflow, templates);+ if (fallbackForm && !getIsFormEmpty(fallbackForm)) {+ return fallbackForm;+ }++ if (storedForm && validateFormStructure(storedForm)) {+ return storedForm;+ }++ return null;+};++export const getSavedWorkflowFormFieldData = (+ workflow: WorkflowResponse | undefined,+ templates: Templates,+ element: NodeFieldElement+): SavedWorkflowFormFieldData => {+ const { nodeId, fieldName } = element.data.fieldIdentifier;+ const node = getWorkflowNodes(workflow).find((candidate) => candidate.data?.id === nodeId);+ const nodeType = node?.data?.type;+ const field = node?.data?.inputs?.[fieldName];+ const fieldTemplate = nodeType ? templates[nodeType]?.inputs[fieldName] : undefined;++ return {+ label: field?.label || fieldTemplate?.title || fieldName,+ description: fieldTemplate?.description || '',+ typeName: fieldTemplate?.type.name ?? null,+ isMissing: !node || !field || !fieldTemplate,+ };+};++const getElementsInOrder = (form: BuilderForm): FormElement[] => {+ const orderedElements: FormElement[] = [];++ const visit = (elementId: string) => {+ const element = form.elements[elementId];+ if (!element) {+ return;+ }++ orderedElements.push(element);+ if (isContainerElement(element)) {+ for (const childId of element.data.children) {+ visit(childId);+ }+ }+ };++ visit(form.rootElementId);+ return orderedElements;+};++const buildDynamicFieldName = (nodeId: string, fieldName: string): string => {+ return `${CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX}${nodeId}::${fieldName}`;+};++const cloneDynamicFieldTemplate = ({+ fieldName,+ fieldTemplate,+ label,+ description,+ uiOrder,+}: {+ fieldName: string;+ fieldTemplate: FieldInputTemplate;+ label: string;+ description: string;+ uiOrder: number;+}): FieldInputTemplate => {+ return {+ ...fieldTemplate,+ name: fieldName,+ title: label,+ description,+ ui_order: uiOrder,+ input: 'any',+ ui_hidden: false,+ } as FieldInputTemplate;+};++export const getSavedWorkflowDynamicFields = (+ workflow: WorkflowResponse | undefined,+ templates: Templates+): SavedWorkflowDynamicField[] => {+ const form = getRenderableWorkflowForm(workflow, templates);+ if (!form) {+ return [];+ }++ const nodes = getWorkflowNodes(workflow);+ const dynamicFields: SavedWorkflowDynamicField[] = [];++ for (const element of getElementsInOrder(form)) {+ if (!('data' in element) || !('fieldIdentifier' in (element.data ?? {}))) {+ continue;+ }+ if (!('type' in element) || element.type !== 'node-field') {+ continue;+ }++ const { nodeId, fieldName } = element.data.fieldIdentifier;+ const node = nodes.find((candidate) => candidate.data?.id === nodeId);+ const nodeType = node?.data?.type;+ const field = node?.data?.inputs?.[fieldName];+ const fieldTemplate = nodeType ? templates[nodeType]?.inputs[fieldName] : undefined;++ if (!field || !fieldTemplate || !isStatefulFieldType(fieldTemplate.type)) {+ continue;+ }++ const dynamicFieldName = buildDynamicFieldName(nodeId, fieldName);+ const label = field.label || fieldTemplate.title || fieldName;+ const description = field.description || fieldTemplate.description || '';++ dynamicFields.push({+ fieldName: dynamicFieldName,+ fieldTemplate: cloneDynamicFieldTemplate({+ fieldName: dynamicFieldName,+ fieldTemplate,+ label,+ description,+ uiOrder: dynamicFields.length,+ }),+ label,+ description,+ initialValue: field.value,+ settings: element.data.settings,+ });+ }++ return dynamicFields;+};++export const shouldSyncSavedWorkflowDynamicFields = ({+ workflowId,+ workflow,+}: {+ workflowId: string | null | undefined;+ workflow: WorkflowResponse | undefined;+}): boolean => {+ return !workflowId || Boolean(workflow);+};++export const getSavedWorkflowDynamicEdgeIdsToRemove = ({+ nodeId,+ fields,+ nodes,+ edges,+ templates,+}: {+ nodeId: string;+ fields: SavedWorkflowDynamicField[];+ nodes: AnyNode[];+ edges: AnyEdge[];+ templates: Templates;+}): string[] => {+ const nextFieldTemplates = new Map(fields.map((field) => [field.fieldName, field.fieldTemplate]));++ return edges.flatMap((edge) => {+ if (edge.type !== 'default' || edge.target !== nodeId || !edge.targetHandle) {+ return [];+ }++ if (!edge.targetHandle.startsWith(CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX)) {+ return [];+ }++ const targetFieldTemplate = nextFieldTemplates.get(edge.targetHandle);+ if (!targetFieldTemplate || targetFieldTemplate.input === 'direct' || !edge.sourceHandle) {+ return [edge.id];+ }++ const sourceNode = nodes.find((node) => node.id === edge.source);+ if (!sourceNode || !isInvocationNode(sourceNode)) {+ return [edge.id];+ }++ const sourceTemplate = templates[sourceNode.data.type];+ const sourceFieldTemplate = sourceTemplate?.outputs[edge.sourceHandle];+ if (!sourceFieldTemplate) {+ return [edge.id];+ }++ if (!validateConnectionTypes(sourceFieldTemplate.type, targetFieldTemplate.type)) {+ return [edge.id];+ }++ return [];+ });+};diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/context.tsx b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/context.tsxindex 8618511d77..af0a9fe4e9 100644--- a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/context.tsx+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/context.tsx@@ -4,7 +4,12 @@ import { createSelector } from '@reduxjs/toolkit';import type { RootState } from 'app/store/store';import { $templates } from 'features/nodes/store/nodesSlice';import { selectEdges, selectNodeFieldElements, selectNodes } from 'features/nodes/store/selectors';-import type { InvocationNode, InvocationTemplate } from 'features/nodes/types/invocation';+import {+ getInvocationNodeInputTemplate,+ getInvocationNodeTemplateWithDynamicInputs,+ type InvocationNode,+ type InvocationTemplate,+} from 'features/nodes/types/invocation';import { getNeedsUpdate } from 'features/nodes/util/node/nodeUpdate';import type { PropsWithChildren } from 'react';import { createContext, memo, useContext, useMemo } from 'react';@@ -81,8 +86,12 @@ export const InvocationNodeContextProvider = memo(({ nodeId, children }: PropsWi}));const selectNodeTemplateSafe = getSelectorFromCache(cache, 'selectNodeTemplateSafe', () =>- createSelector(selectNodeTypeSafe, (type) => {- return type ? (templates[type] ?? null) : null;+ createSelector(selectNodeDataSafe, (data) => {+ if (!data) {+ return null;+ }+ const template = templates[data.type];+ return template ? getInvocationNodeTemplateWithDynamicInputs(data, template) : null;}));const selectNodeInputsSafe = getSelectorFromCache(cache, 'selectNodeInputsSafe', () =>@@ -129,12 +138,12 @@ export const InvocationNodeContextProvider = memo(({ nodeId, children }: PropsWi}));const selectNodeTemplateOrThrow = getSelectorFromCache(cache, 'selectNodeTemplateOrThrow', () =>- createSelector(selectNodeTypeOrThrow, (type) => {- const template = templates[type];+ createSelector(selectNodeDataOrThrow, (data) => {+ const template = templates[data.type];if (template === undefined) {- throw new Error(`Cannot find template for node with id ${nodeId} with type ${type}`);+ throw new Error(`Cannot find template for node with id ${nodeId} with type ${data.type}`);}- return template;+ return getInvocationNodeTemplateWithDynamicInputs(data, template);}));const selectNodeInputsOrThrow = getSelectorFromCache(cache, 'selectNodeInputsOrThrow', () =>@@ -154,8 +163,8 @@ export const InvocationNodeContextProvider = memo(({ nodeId, children }: PropsWi);const buildSelectInputFieldTemplateOrThrow = (fieldName: string) =>getSelectorFromCache(cache, `buildSelectInputFieldTemplateOrThrow-${fieldName}`, () =>- createSelector(selectNodeTemplateOrThrow, (template) => {- const fieldTemplate = template.inputs[fieldName];+ createSelector(selectNodeDataOrThrow, selectNodeTemplateOrThrow, (data, template) => {+ const fieldTemplate = getInvocationNodeInputTemplate(data, template, fieldName);if (fieldTemplate === undefined) {throw new Error(`Cannot find input field template with name ${fieldName} in node ${nodeId}`);}diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldEditModeNodes.tsx b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldEditModeNodes.tsxindex 1597f4ede1..60ce93fa61 100644--- a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldEditModeNodes.tsx+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldEditModeNodes.tsx@@ -9,6 +9,7 @@ import { useInputFieldIsInvalid } from 'features/nodes/hooks/useInputFieldIsInvaimport { useInputFieldTemplateOrThrow } from 'features/nodes/hooks/useInputFieldTemplateOrThrow';import { NO_DRAG_CLASS } from 'features/nodes/types/constants';import type { FieldInputTemplate } from 'features/nodes/types/field';+import type { NodeFieldElement } from 'features/nodes/types/workflow';import { memo, useRef } from 'react';import { InputFieldAddRemoveFormRoot } from './InputFieldAddRemoveFormRoot';@@ -19,9 +20,10 @@ import { InputFieldWrapper } from './InputFieldWrapper';interface Props {nodeId: string;fieldName: string;+ settings?: NodeFieldElement['data']['settings'];}-export const InputFieldEditModeNodes = memo(({ nodeId, fieldName }: Props) => {+export const InputFieldEditModeNodes = memo(({ nodeId, fieldName, settings }: Props) => {const fieldTemplate = useInputFieldTemplateOrThrow(fieldName);const isInvalid = useInputFieldIsInvalid(fieldName);const isConnected = useInputFieldIsConnected(fieldName);@@ -45,6 +47,7 @@ export const InputFieldEditModeNodes = memo(({ nodeId, fieldName }: Props) => {isInvalid={isInvalid}isConnected={isConnected}fieldTemplate={fieldTemplate}+ settings={settings}/>);});@@ -57,6 +60,7 @@ type CommonProps = {isInvalid: boolean;isConnected: boolean;fieldTemplate: FieldInputTemplate;+ settings?: NodeFieldElement['data']['settings'];};const ConnectedOrConnectionField = memo(({ nodeId, fieldName, isInvalid }: CommonProps) => {@@ -96,7 +100,7 @@ const directFieldSx: SystemStyleObject = {},};-const DirectField = memo(({ nodeId, fieldName, isInvalid, isConnected, fieldTemplate }: CommonProps) => {+const DirectField = memo(({ nodeId, fieldName, isInvalid, isConnected, fieldTemplate, settings }: CommonProps) => {const draggableRef = useRef<HTMLDivElement>(null);const dragHandleRef = useRef<HTMLDivElement>(null);@@ -116,7 +120,7 @@ const DirectField = memo(({ nodeId, fieldName, isInvalid, isConnected, fieldTemp<InputFieldAddRemoveFormRoot nodeId={nodeId} fieldName={fieldName} /></Flex></Flex>- <InputFieldRenderer nodeId={nodeId} fieldName={fieldName} />+ <InputFieldRenderer nodeId={nodeId} fieldName={fieldName} settings={settings} /></Flex>{fieldTemplate.input !== 'direct' && <InputFieldHandle nodeId={nodeId} fieldName={fieldName} />}</InputFieldWrapper>diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldRenderer.tsx b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldRenderer.tsxindex 60a3f8e472..4fa020212e 100644--- a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldRenderer.tsx+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/InputFieldRenderer.tsx@@ -8,6 +8,7 @@ import { ImageGeneratorFieldInputComponent } from 'features/nodes/components/floimport { IntegerFieldCollectionInputComponent } from 'features/nodes/components/flow/nodes/Invocation/fields/inputs/IntegerFieldCollectionInputComponent';import { IntegerGeneratorFieldInputComponent } from 'features/nodes/components/flow/nodes/Invocation/fields/inputs/IntegerGeneratorFieldComponent';import ModelIdentifierFieldInputComponent from 'features/nodes/components/flow/nodes/Invocation/fields/inputs/ModelIdentifierFieldInputComponent';+import SavedWorkflowFieldInputComponent from 'features/nodes/components/flow/nodes/Invocation/fields/inputs/SavedWorkflowFieldInputComponent';import { StringFieldCollectionInputComponent } from 'features/nodes/components/flow/nodes/Invocation/fields/inputs/StringFieldCollectionInputComponent';import { StringGeneratorFieldInputComponent } from 'features/nodes/components/flow/nodes/Invocation/fields/inputs/StringGeneratorFieldComponent';import { IntegerFieldInput } from 'features/nodes/components/flow/nodes/Invocation/fields/IntegerField/IntegerFieldInput';@@ -47,6 +48,8 @@ import {isIntegerGeneratorFieldInputTemplate,isModelIdentifierFieldInputInstance,isModelIdentifierFieldInputTemplate,+ isSavedWorkflowFieldInputInstance,+ isSavedWorkflowFieldInputTemplate,isSchedulerFieldInputInstance,isSchedulerFieldInputTemplate,isStringFieldCollectionInputInstance,@@ -223,6 +226,13 @@ export const InputFieldRenderer = memo(({ nodeId, fieldName, settings }: Props)return <ModelIdentifierFieldInputComponent nodeId={nodeId} field={field} fieldTemplate={template} />;}+ if (isSavedWorkflowFieldInputTemplate(template)) {+ if (!isSavedWorkflowFieldInputInstance(field)) {+ return null;+ }+ return <SavedWorkflowFieldInputComponent nodeId={nodeId} field={field} fieldTemplate={template} />;+ }+if (isColorFieldInputTemplate(template)) {if (!isColorFieldInputInstance(field)) {return null;diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/SavedWorkflowFieldInputComponent.tsx b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/SavedWorkflowFieldInputComponent.tsxnew file mode 100644index 0000000000..998297cc30--- /dev/null+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/SavedWorkflowFieldInputComponent.tsx@@ -0,0 +1,175 @@+import type { ComboboxOnChange, ComboboxOption } from '@invoke-ai/ui-library';+import { Badge, Combobox, Flex, Text } from '@invoke-ai/ui-library';+import { EMPTY_ARRAY } from 'app/store/constants';+import { useAppDispatch } from 'app/store/storeHooks';+import { fieldStringValueChanged } from 'features/nodes/store/nodesSlice';+import { NO_DRAG_CLASS, NO_WHEEL_CLASS } from 'features/nodes/types/constants';+import type { SavedWorkflowFieldInputInstance, SavedWorkflowFieldInputTemplate } from 'features/nodes/types/field';+import { memo, useCallback, useDeferredValue, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useGetWorkflowQuery, useListWorkflowsInfiniteInfiniteQuery } from 'services/api/endpoints/workflows';++import {+ buildSavedWorkflowOptions,+ getSavedWorkflowDisplayState,+ getSavedWorkflowListItemFromRecord,+ getSavedWorkflowPickerOwnedQueryArg,+ getSavedWorkflowPickerSharedQueryArg,+ getSavedWorkflowSelectionOption,+ getSavedWorkflowSelectionState,+ mergeSavedWorkflowPickerItems,+ MISSING_WORKFLOW_OPTION_VALUE,+ shouldFetchNextSavedWorkflowPickerPage,+} from './savedWorkflowFieldUtils';+import type { FieldComponentProps } from './types';++const queryOptions = {+ selectFromResult: ({ data, ...rest }) => ({+ items: data?.pages.flatMap(({ items }) => items) ?? EMPTY_ARRAY,+ ...rest,+ }),+} satisfies Parameters<typeof useListWorkflowsInfiniteInfiniteQuery>[1];++const SavedWorkflowFieldInputComponent = (+ props: FieldComponentProps<SavedWorkflowFieldInputInstance, SavedWorkflowFieldInputTemplate>+) => {+ const { nodeId, field } = props;+ const dispatch = useAppDispatch();+ const { t } = useTranslation();+ const [workflowSearchQuery, setWorkflowSearchQuery] = useState('');+ const deferredWorkflowSearchQuery = useDeferredValue(workflowSearchQuery);+ const ownedQueryArg = useMemo(+ () =>+ getSavedWorkflowPickerOwnedQueryArg(deferredWorkflowSearchQuery) satisfies Parameters<+ typeof useListWorkflowsInfiniteInfiniteQuery+ >[0],+ [deferredWorkflowSearchQuery]+ );+ const sharedQueryArg = useMemo(+ () =>+ getSavedWorkflowPickerSharedQueryArg(deferredWorkflowSearchQuery) satisfies Parameters<+ typeof useListWorkflowsInfiniteInfiniteQuery+ >[0],+ [deferredWorkflowSearchQuery]+ );+ const {+ items: ownedItems,+ isLoading: isOwnedLoading,+ isFetching: isOwnedFetching,+ hasNextPage: hasNextOwnedPage,+ fetchNextPage: fetchNextOwnedPage,+ } = useListWorkflowsInfiniteInfiniteQuery(ownedQueryArg, queryOptions);+ const {+ items: sharedItems,+ isLoading: isSharedLoading,+ isFetching: isSharedFetching,+ hasNextPage: hasNextSharedPage,+ fetchNextPage: fetchNextSharedPage,+ } = useListWorkflowsInfiniteInfiniteQuery(sharedQueryArg, queryOptions);+ const items = useMemo(() => mergeSavedWorkflowPickerItems(ownedItems, sharedItems), [ownedItems, sharedItems]);+ const isSelectedWorkflowInList = useMemo(+ () => items.some((workflow) => workflow.workflow_id === field.value),+ [field.value, items]+ );+ const { data: selectedWorkflowRecord } = useGetWorkflowQuery(field.value, {+ skip: !field.value || isSelectedWorkflowInList,+ });+ const selectedWorkflow = useMemo(+ () => (selectedWorkflowRecord ? getSavedWorkflowListItemFromRecord(selectedWorkflowRecord) : undefined),+ [selectedWorkflowRecord]+ );++ const options = useMemo<ComboboxOption[]>(() => buildSavedWorkflowOptions(items), [items]);+ const selectionState = useMemo(+ () => getSavedWorkflowSelectionState(items, field.value, selectedWorkflow),+ [field.value, items, selectedWorkflow]+ );+ const value = useMemo<ComboboxOption | null>(() => {+ const option = getSavedWorkflowSelectionOption(selectionState);+ if (option?.value === MISSING_WORKFLOW_OPTION_VALUE) {+ return {+ ...option,+ label: t('nodes.savedWorkflowMissing'),+ };+ }+ return option;+ }, [selectionState, t]);+ const statusLabel = useMemo(() => {+ const displayState = getSavedWorkflowDisplayState(selectionState);+ return displayState.statusLabelKey ? t(displayState.statusLabelKey) : null;+ }, [selectionState, t]);+ const displayState = useMemo(() => getSavedWorkflowDisplayState(selectionState), [selectionState]);++ const onChange = useCallback<ComboboxOnChange>(+ (v) => {+ dispatch(+ fieldStringValueChanged({+ nodeId,+ fieldName: field.name,+ value: v?.value ?? '',+ })+ );+ },+ [dispatch, field.name, nodeId]+ );+ const onMenuScrollToBottom = useCallback(() => {+ if (shouldFetchNextSavedWorkflowPickerPage({ hasNextPage: hasNextOwnedPage, isFetching: isOwnedFetching })) {+ fetchNextOwnedPage();+ }+ if (shouldFetchNextSavedWorkflowPickerPage({ hasNextPage: hasNextSharedPage, isFetching: isSharedFetching })) {+ fetchNextSharedPage();+ }+ }, [fetchNextOwnedPage, fetchNextSharedPage, hasNextOwnedPage, hasNextSharedPage, isOwnedFetching, isSharedFetching]);+ const onInputChange = useCallback((inputValue: string) => {+ setWorkflowSearchQuery(inputValue);+ return inputValue;+ }, []);++ const noOptionsMessage = useCallback(() => t('nodes.noMatchingWorkflows'), [t]);+ const isLoading = isOwnedLoading || isSharedLoading;+ const isFetching = isOwnedFetching || isSharedFetching;++ return (+ <Flex flexDir="column" gap={1}>+ <Combobox+ className={`${NO_WHEEL_CLASS} ${NO_DRAG_CLASS}`}+ value={value}+ options={options}+ onChange={onChange}+ onInputChange={onInputChange}+ onMenuScrollToBottom={onMenuScrollToBottom}+ placeholder={isLoading ? t('common.loading') : t('controlLayers.workflowIntegration.selectPlaceholder')}+ noOptionsMessage={noOptionsMessage}+ isClearable+ />+ {selectionState.status === 'selected' ? (+ <Flex alignItems="center" gap={1} flexWrap="wrap">+ <Text fontSize="xs" variant="subtext" noOfLines={1}>+ {selectionState.workflow.name}+ </Text>+ {displayState.badges.includes('unsupported') && (+ <Badge variant="subtle">{t('nodes.savedWorkflowUnsupported')}</Badge>+ )}+ {displayState.badges.includes('default') && (+ <Badge variant="subtle">{t('nodes.savedWorkflowDefaultBadge')}</Badge>+ )}+ {displayState.badges.includes('shared') && <Badge variant="subtle">{t('workflows.shared')}</Badge>}+ </Flex>+ ) : (+ <Badge variant="subtle">{statusLabel ?? t('nodes.savedWorkflowChoose')}</Badge>+ )}+ {selectionState.status === 'selected' && displayState.compatibilityMessageKey && (+ <Text variant="subtext" fontSize="xs">+ {t(displayState.compatibilityMessageKey)}+ </Text>+ )}+ {isFetching && (+ <Text variant="subtext" fontSize="xs">+ {t('nodes.savedWorkflowUpdating')}+ </Text>+ )}+ </Flex>+ );+};++export default memo(SavedWorkflowFieldInputComponent);diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/savedWorkflowFieldUtils.test.ts b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/savedWorkflowFieldUtils.test.tsnew file mode 100644index 0000000000..2ee640f4d9--- /dev/null+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/savedWorkflowFieldUtils.test.ts@@ -0,0 +1,203 @@+import type { WorkflowRecordListItemWithThumbnailDTO } from 'services/api/types';+import { describe, expect, it } from 'vitest';++import {+ buildSavedWorkflowOptions,+ getSavedWorkflowDisplayState,+ getSavedWorkflowListItemFromRecord,+ getSavedWorkflowPickerOwnedQueryArg,+ getSavedWorkflowPickerSharedQueryArg,+ getSavedWorkflowSelectionOption,+ getSavedWorkflowSelectionState,+ mergeSavedWorkflowPickerItems,+ MISSING_WORKFLOW_OPTION_VALUE,+ shouldFetchNextSavedWorkflowPickerPage,+} from './savedWorkflowFieldUtils';++const workflows: WorkflowRecordListItemWithThumbnailDTO[] = [+ {+ workflow_id: 'workflow-a',+ name: 'Alpha Workflow',+ created_at: '',+ updated_at: '',+ opened_at: null,+ description: '',+ tags: '',+ is_public: false,+ thumbnail_url: null,+ category: 'user',+ user_id: 'user-a',+ call_saved_workflow_compatibility: {+ is_callable: true,+ reason: 'ok',+ message: null,+ },+ },+ {+ workflow_id: 'workflow-b',+ name: 'Beta Workflow',+ created_at: '',+ updated_at: '',+ opened_at: null,+ description: '',+ tags: '',+ is_public: true,+ thumbnail_url: null,+ category: 'default',+ user_id: 'system',+ call_saved_workflow_compatibility: {+ is_callable: false,+ reason: 'missing_workflow_return',+ message: 'The workflow must contain exactly one workflow_return node.',+ },+ },+];++describe('savedWorkflowFieldUtils', () => {+ it('builds combobox options from visible workflows', () => {+ expect(buildSavedWorkflowOptions(workflows)).toEqual([+ { label: 'Alpha Workflow', value: 'workflow-a', isDisabled: false },+ { label: 'Beta Workflow', value: 'workflow-b', isDisabled: true },+ ]);+ });++ it('returns an unselected state for the default empty value', () => {+ const selectionState = getSavedWorkflowSelectionState(workflows, '');+ expect(selectionState).toEqual({ status: 'unselected' });+ expect(getSavedWorkflowSelectionOption(selectionState)).toBeNull();+ });++ it('returns a selected state for a valid workflow id', () => {+ const selectionState = getSavedWorkflowSelectionState(workflows, 'workflow-b');+ expect(selectionState).toEqual({ status: 'selected', workflow: workflows[1] });+ expect(getSavedWorkflowSelectionOption(selectionState)).toEqual({+ label: 'Beta Workflow',+ value: 'workflow-b',+ });+ });++ it('returns a missing state for a stale or inaccessible workflow id', () => {+ const selectionState = getSavedWorkflowSelectionState(workflows, 'missing-workflow');+ expect(selectionState).toEqual({ status: 'missing', workflowId: 'missing-workflow' });+ expect(getSavedWorkflowSelectionOption(selectionState)).toEqual({+ label: MISSING_WORKFLOW_OPTION_VALUE,+ value: MISSING_WORKFLOW_OPTION_VALUE,+ });+ });++ it('builds display state for an already-selected unsupported workflow', () => {+ const selectionState = getSavedWorkflowSelectionState(workflows, 'workflow-b');++ expect(getSavedWorkflowDisplayState(selectionState)).toEqual({+ selection: 'selected',+ statusLabelKey: null,+ badges: ['unsupported', 'default'],+ compatibilityMessageKey: 'workflows.savedWorkflowCompatibility.missingWorkflowReturn',+ });+ });++ it('builds display state for missing and unselected workflows', () => {+ expect(getSavedWorkflowDisplayState({ status: 'unselected' })).toEqual({+ selection: 'unselected',+ statusLabelKey: 'nodes.savedWorkflowChoose',+ badges: [],+ compatibilityMessageKey: null,+ });++ expect(getSavedWorkflowDisplayState({ status: 'missing', workflowId: 'missing-workflow' })).toEqual({+ selection: 'missing',+ statusLabelKey: 'nodes.savedWorkflowMissing',+ badges: [],+ compatibilityMessageKey: null,+ });+ });++ it('uses a fetched selected workflow when it is not present in the first list page', () => {+ const selectedWorkflow = getSavedWorkflowListItemFromRecord({+ workflow_id: 'workflow-z',+ name: 'Zeta Workflow',+ created_at: '',+ updated_at: '',+ opened_at: null,+ user_id: 'user-z',+ is_public: true,+ thumbnail_url: null,+ call_saved_workflow_compatibility: {+ is_callable: true,+ reason: 'ok',+ message: null,+ },+ workflow: {+ id: 'workflow-z',+ name: 'Zeta Workflow',+ author: '',+ description: 'A workflow outside the first page',+ version: '',+ contact: '',+ tags: 'paged',+ notes: '',+ exposedFields: [],+ meta: {+ category: 'user',+ version: '1.0.0',+ },+ nodes: [],+ edges: [],+ form: null,+ },+ });++ const selectionState = getSavedWorkflowSelectionState(workflows, 'workflow-z', selectedWorkflow);++ expect(selectionState).toEqual({ status: 'selected', workflow: selectedWorkflow });+ expect(getSavedWorkflowDisplayState(selectionState)).toEqual({+ selection: 'selected',+ statusLabelKey: null,+ badges: ['shared'],+ compatibilityMessageKey: null,+ });+ });++ it('queries owned/default workflows and shared public workflows separately', () => {+ expect(getSavedWorkflowPickerOwnedQueryArg('landscape')).toMatchObject({+ page: 0,+ per_page: 50,+ query: 'landscape',+ categories: ['user', 'default'],+ is_public: undefined,+ });+ expect(getSavedWorkflowPickerSharedQueryArg('landscape')).toMatchObject({+ page: 0,+ per_page: 50,+ query: 'landscape',+ categories: ['user'],+ is_public: true,+ });+ });++ it('merges paged owned and shared workflow picker results without duplicates', () => {+ const ownedWorkflow = workflows[0];+ const defaultWorkflow = workflows[1];+ if (!ownedWorkflow || !defaultWorkflow) {+ throw new Error('Expected workflow fixtures');+ }+ const sharedWorkflow = {+ ...ownedWorkflow,+ workflow_id: 'workflow-shared',+ name: 'Shared Workflow',+ is_public: true,+ };++ expect(mergeSavedWorkflowPickerItems([ownedWorkflow], [defaultWorkflow, sharedWorkflow], [ownedWorkflow])).toEqual([+ ownedWorkflow,+ defaultWorkflow,+ sharedWorkflow,+ ]);+ });++ it('fetches more workflow picker pages only when a query has another idle page', () => {+ expect(shouldFetchNextSavedWorkflowPickerPage({ hasNextPage: true, isFetching: false })).toBe(true);+ expect(shouldFetchNextSavedWorkflowPickerPage({ hasNextPage: false, isFetching: false })).toBe(false);+ expect(shouldFetchNextSavedWorkflowPickerPage({ hasNextPage: true, isFetching: true })).toBe(false);+ });+});diff --git a/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/savedWorkflowFieldUtils.ts b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/savedWorkflowFieldUtils.tsnew file mode 100644index 0000000000..8214ee0060--- /dev/null+++ b/invokeai/frontend/web/src/features/nodes/components/flow/nodes/Invocation/fields/inputs/savedWorkflowFieldUtils.ts@@ -0,0 +1,178 @@+import type { ComboboxOption } from '@invoke-ai/ui-library';+import {+ getWorkflowCallCompatibilityState,+ type WorkflowCallCompatibilityMessageKey,+} from 'features/workflowLibrary/util/workflowCallCompatibility';+import type { S, WorkflowRecordListItemWithThumbnailDTO } from 'services/api/types';++export const MISSING_WORKFLOW_OPTION_VALUE = '__missing_workflow__';+const SAVED_WORKFLOW_PICKER_PAGE_SIZE = 50;+type SavedWorkflowBadge = 'unsupported' | 'default' | 'shared';++type SavedWorkflowSelectionState =+ | { status: 'unselected' }+ | { status: 'selected'; workflow: WorkflowRecordListItemWithThumbnailDTO }+ | { status: 'missing'; workflowId: string };++export const buildSavedWorkflowOptions = (workflows: WorkflowRecordListItemWithThumbnailDTO[]): ComboboxOption[] => {+ return workflows.map((workflow) => ({+ label: workflow.name,+ value: workflow.workflow_id,+ isDisabled: workflow.call_saved_workflow_compatibility?.is_callable === false,+ }));+};++const baseSavedWorkflowPickerQueryArg = {+ page: 0,+ per_page: SAVED_WORKFLOW_PICKER_PAGE_SIZE,+ order_by: 'name',+ direction: 'ASC',+ tags: [] as string[],+ has_been_opened: undefined,+} as const;++export const getSavedWorkflowPickerOwnedQueryArg = (query = '') => ({+ ...baseSavedWorkflowPickerQueryArg,+ query,+ categories: ['user', 'default'] as ('user' | 'default')[],+ is_public: undefined,+});++export const getSavedWorkflowPickerSharedQueryArg = (query = '') => ({+ ...baseSavedWorkflowPickerQueryArg,+ query,+ categories: ['user'] as ('user' | 'default')[],+ is_public: true,+});++export const mergeSavedWorkflowPickerItems = (+ ...workflowLists: WorkflowRecordListItemWithThumbnailDTO[][]+): WorkflowRecordListItemWithThumbnailDTO[] => {+ const workflowsById = new Map<string, WorkflowRecordListItemWithThumbnailDTO>();+ for (const workflows of workflowLists) {+ for (const workflow of workflows) {+ if (!workflowsById.has(workflow.workflow_id)) {+ workflowsById.set(workflow.workflow_id, workflow);+ }+ }+ }+ return Array.from(workflowsById.values());+};++export const shouldFetchNextSavedWorkflowPickerPage = ({+ hasNextPage,+ isFetching,+}: {+ hasNextPage: boolean;+ isFetching: boolean;+}) => hasNextPage && !isFetching;++export const getSavedWorkflowSelectionState = (+ workflows: WorkflowRecordListItemWithThumbnailDTO[],+ workflowId: string,+ selectedWorkflow?: WorkflowRecordListItemWithThumbnailDTO+): SavedWorkflowSelectionState => {+ if (!workflowId) {+ return { status: 'unselected' };+ }++ const workflow = workflows.find((workflow) => workflow.workflow_id === workflowId);+ if (workflow) {+ return { status: 'selected', workflow };+ }++ if (selectedWorkflow?.workflow_id === workflowId) {+ return { status: 'selected', workflow: selectedWorkflow };+ }++ return { status: 'missing', workflowId };+};++export const getSavedWorkflowListItemFromRecord = (+ workflow: S['WorkflowRecordWithThumbnailDTO']+): WorkflowRecordListItemWithThumbnailDTO => ({+ workflow_id: workflow.workflow_id,+ name: workflow.name,+ created_at: workflow.created_at,+ updated_at: workflow.updated_at,+ opened_at: workflow.opened_at,+ user_id: workflow.user_id,+ is_public: workflow.is_public,+ description: workflow.workflow.description,+ category: workflow.workflow.meta.category,+ tags: workflow.workflow.tags,+ thumbnail_url: workflow.thumbnail_url,+ call_saved_workflow_compatibility: workflow.call_saved_workflow_compatibility,+});++export const getSavedWorkflowSelectionOption = (selectionState: SavedWorkflowSelectionState): ComboboxOption | null => {+ if (selectionState.status === 'unselected') {+ return null;+ }++ if (selectionState.status === 'selected') {+ return {+ label: selectionState.workflow.name,+ value: selectionState.workflow.workflow_id,+ };+ }++ return {+ label: MISSING_WORKFLOW_OPTION_VALUE,+ value: MISSING_WORKFLOW_OPTION_VALUE,+ };+};++type SavedWorkflowDisplayState =+ | {+ selection: 'unselected' | 'missing';+ statusLabelKey: 'nodes.savedWorkflowChoose' | 'nodes.savedWorkflowMissing';+ badges: SavedWorkflowBadge[];+ compatibilityMessageKey: null;+ }+ | {+ selection: 'selected';+ statusLabelKey: null;+ badges: SavedWorkflowBadge[];+ compatibilityMessageKey: WorkflowCallCompatibilityMessageKey | null;+ };++export const getSavedWorkflowDisplayState = (+ selectionState: SavedWorkflowSelectionState+): SavedWorkflowDisplayState => {+ if (selectionState.status === 'unselected') {+ return {+ selection: 'unselected',+ statusLabelKey: 'nodes.savedWorkflowChoose',+ badges: [],+ compatibilityMessageKey: null,+ };+ }++ if (selectionState.status === 'missing') {+ return {+ selection: 'missing',+ statusLabelKey: 'nodes.savedWorkflowMissing',+ badges: [],+ compatibilityMessageKey: null,+ };+ }++ const compatibilityState = getWorkflowCallCompatibilityState(selectionState.workflow);+ const badges: SavedWorkflowBadge[] = [];+ if (compatibilityState.isUnsupported) {+ badges.push('unsupported');+ }+ if (selectionState.workflow.category === 'default') {+ badges.push('default');+ } else if (selectionState.workflow.is_public) {+ badges.push('shared');+ }++ return {+ selection: 'selected',+ statusLabelKey: null,+ badges,+ compatibilityMessageKey: compatibilityState.messageKey,+ };+};diff --git a/invokeai/frontend/web/src/features/nodes/components/sidePanel/workflow/WorkflowLibrary/WorkflowListItem.tsx b/invokeai/frontend/web/src/features/nodes/components/sidePanel/workflow/WorkflowLibrary/WorkflowListItem.tsxindex 3291d75f59..468a69db25 100644--- a/invokeai/frontend/web/src/features/nodes/components/sidePanel/workflow/WorkflowLibrary/WorkflowListItem.tsx+++ b/invokeai/frontend/web/src/features/nodes/components/sidePanel/workflow/WorkflowLibrary/WorkflowListItem.tsx@@ -5,6 +5,7 @@ import { selectCurrentUser } from 'features/auth/store/authSlice';import { selectWorkflowId } from 'features/nodes/store/selectors';import { workflowModeChanged } from 'features/nodes/store/workflowLibrarySlice';import { useLoadWorkflowWithDialog } from 'features/workflowLibrary/components/LoadWorkflowConfirmationAlertDialog';+import { getWorkflowLibraryListItemState } from 'features/workflowLibrary/util/workflowLibraryListItemState';import InvokeLogo from 'public/assets/images/invoke-symbol-wht-lrg.svg';import { type ChangeEvent, memo, type MouseEvent, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -65,6 +66,7 @@ export const WorkflowListItem = memo(({ workflow }: { workflow: WorkflowRecordLi.map((tag) => tag.trim()).filter((tag) => tag.length > 0);}, [workflow.tags]);+ const listItemState = useMemo(() => getWorkflowLibraryListItemState(workflow), [workflow]);const handleClickLoad = useCallback(() => {loadWorkflowWithDialog({@@ -119,7 +121,7 @@ export const WorkflowListItem = memo(({ workflow }: { workflow: WorkflowRecordLi{t('workflows.opened')}</Badge>)}- {setupStatus?.multiuser_enabled && workflow.is_public && workflow.category !== 'default' && (+ {setupStatus?.multiuser_enabled && listItemState.showSharedBadge && (<Badgecolor="invokeGreen.400"borderColor="invokeGreen.700"@@ -131,7 +133,27 @@ export const WorkflowListItem = memo(({ workflow }: { workflow: WorkflowRecordLi{t('workflows.shared')}</Badge>)}- {workflow.category === 'default' && (+ {listItemState.showUnsupportedBadge && (+ <Tooltip+ label={+ listItemState.unsupportedMessageKey+ ? t(listItemState.unsupportedMessageKey)+ : t('workflows.savedWorkflowUnsupportedDescription')+ }+ >+ <Badge+ color="warning.300"+ borderColor="warning.600"+ borderWidth={1}+ bg="transparent"+ flexShrink={0}+ variant="subtle"+ >+ {t('nodes.savedWorkflowUnsupported')}+ </Badge>+ </Tooltip>+ )}+ {listItemState.showDefaultIcon && (<Imagesrc={InvokeLogo}alt="invoke-logo"@@ -148,6 +170,13 @@ export const WorkflowListItem = memo(({ workflow }: { workflow: WorkflowRecordLi<Text variant="subtext" fontSize="xs" noOfLines={3}>{workflow.description}</Text>+ {listItemState.showUnsupportedBadge && (+ <Text variant="subtext" fontSize="xs" noOfLines={2} color="warning.300">+ {listItemState.unsupportedMessageKey+ ? t(listItemState.unsupportedMessageKey)+ : t('workflows.savedWorkflowUnsupportedDescription')}+ </Text>+ )}{tags.length > 0 && (<Text fontSize="xs" noOfLines={1}><Text as="span" color="base.400">diff --git a/invokeai/frontend/web/src/features/nodes/store/nodesSlice.test.ts b/invokeai/frontend/web/src/features/nodes/store/nodesSlice.test.tsindex f331692b43..6c1d8ea970 100644--- a/invokeai/frontend/web/src/features/nodes/store/nodesSlice.test.ts+++ b/invokeai/frontend/web/src/features/nodes/store/nodesSlice.test.ts@@ -1,10 +1,48 @@import { deepClone } from 'common/util/deepClone';+import type { IntegerFieldInputTemplate, StringFieldInputTemplate } from 'features/nodes/types/field';import { buildConnectorNode } from 'features/nodes/util/node/buildConnectorNode';import { describe, expect, it } from 'vitest';-import { connectorInserted, nodesChanged, nodesSliceConfig } from './nodesSlice';+import {+ callSavedWorkflowDynamicFieldsChanged,+ connectorInserted,+ fieldIntegerValueChanged,+ nodesChanged,+ nodesSliceConfig,+} from './nodesSlice';import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE } from './util/connectorTopology';-import { add, buildEdge, buildNode, sub } from './util/testUtils';+import { add, buildEdge, buildNode, sub, templates } from './util/testUtils';++const callSavedWorkflowTemplate = templates.call_saved_workflow;+const addTemplate = templates.add;++if (!callSavedWorkflowTemplate || !addTemplate || !addTemplate.inputs.a) {+ throw new Error('Expected saved workflow and add templates');+}+const addIntegerInputTemplate = addTemplate.inputs.a as IntegerFieldInputTemplate;++const buildDynamicIntegerTemplate = (fieldName: string): IntegerFieldInputTemplate => ({+ ...addIntegerInputTemplate,+ name: fieldName,+ title: 'Left Addend',+ input: 'any' as const,+});++const buildDynamicStringTemplate = (fieldName: string): StringFieldInputTemplate => ({+ name: fieldName,+ title: 'Prompt',+ required: false,+ description: 'Prompt text',+ fieldKind: 'input',+ input: 'any',+ ui_hidden: false,+ default: 'new default',+ type: {+ name: 'StringField',+ cardinality: 'SINGLE',+ batch: false,+ },+});const buildFixedConnectorNode = (id: string) => {const connectorNode = buildConnectorNode({ x: 0, y: 0 });@@ -18,6 +56,226 @@ const buildFixedConnectorNode = (id: string) => {};};+describe('callSavedWorkflowDynamicFieldsChanged', () => {+ it('seeds new dynamic fields with the source workflow values', () => {+ const state = nodesSliceConfig.getInitialState();+ const node = buildNode(callSavedWorkflowTemplate);+ state.nodes.push(node);++ const nextState = nodesSliceConfig.slice.reducer(+ state,+ callSavedWorkflowDynamicFieldsChanged({+ nodeId: node.id,+ fields: [+ {+ fieldName: 'saved_workflow_input::node-1::a',+ fieldTemplate: buildDynamicIntegerTemplate('saved_workflow_input::node-1::a'),+ label: 'Left Addend',+ description: 'The first number',+ initialValue: 23,+ },+ ],+ edgeIdsToRemove: [],+ })+ );++ const dynamicField = nextState.nodes[0];+ if (!dynamicField || dynamicField.type !== 'invocation') {+ throw new Error('Expected invocation node');+ }++ expect(dynamicField.data.inputs['saved_workflow_input::node-1::a']?.value).toBe(23);+ expect(dynamicField.data.inputs['saved_workflow_input::node-1::a']?.label).toBe('Left Addend');+ expect(dynamicField.data.dynamicInputTemplates['saved_workflow_input::node-1::a']?.title).toBe('Left Addend');+ });++ it('preserves existing dynamic field values on resync', () => {+ const state = nodesSliceConfig.getInitialState();+ const node = buildNode(callSavedWorkflowTemplate);+ state.nodes.push(node);++ const fieldName = 'saved_workflow_input::node-1::a';++ let nextState = nodesSliceConfig.slice.reducer(+ state,+ callSavedWorkflowDynamicFieldsChanged({+ nodeId: node.id,+ fields: [+ {+ fieldName,+ fieldTemplate: buildDynamicIntegerTemplate(fieldName),+ label: 'Left Addend',+ description: 'The first number',+ initialValue: 23,+ },+ ],+ edgeIdsToRemove: [],+ })+ );++ nextState = nodesSliceConfig.slice.reducer(+ nextState,+ fieldIntegerValueChanged({+ nodeId: node.id,+ fieldName,+ value: 99,+ })+ );++ nextState = nodesSliceConfig.slice.reducer(+ nextState,+ callSavedWorkflowDynamicFieldsChanged({+ nodeId: node.id,+ fields: [+ {+ fieldName,+ fieldTemplate: buildDynamicIntegerTemplate(fieldName),+ label: 'Left Addend',+ description: 'The first number',+ initialValue: 23,+ },+ ],+ edgeIdsToRemove: [],+ })+ );++ const resyncedNode = nextState.nodes[0];+ if (!resyncedNode || resyncedNode.type !== 'invocation') {+ throw new Error('Expected invocation node');+ }++ expect(resyncedNode.data.inputs[fieldName]?.value).toBe(99);+ expect(resyncedNode.data.dynamicInputTemplates[fieldName]?.name).toBe(fieldName);+ });++ it('resets an existing dynamic field value when the exposed field type changes', () => {+ const state = nodesSliceConfig.getInitialState();+ const node = buildNode(callSavedWorkflowTemplate);+ state.nodes.push(node);++ const fieldName = 'saved_workflow_input::node-1::a';++ let nextState = nodesSliceConfig.slice.reducer(+ state,+ callSavedWorkflowDynamicFieldsChanged({+ nodeId: node.id,+ fields: [+ {+ fieldName,+ fieldTemplate: buildDynamicIntegerTemplate(fieldName),+ label: 'Left Addend',+ description: 'The first number',+ initialValue: 23,+ },+ ],+ edgeIdsToRemove: [],+ })+ );++ nextState = nodesSliceConfig.slice.reducer(+ nextState,+ fieldIntegerValueChanged({+ nodeId: node.id,+ fieldName,+ value: 99,+ })+ );++ nextState = nodesSliceConfig.slice.reducer(+ nextState,+ callSavedWorkflowDynamicFieldsChanged({+ nodeId: node.id,+ fields: [+ {+ fieldName,+ fieldTemplate: buildDynamicStringTemplate(fieldName),+ label: 'Prompt',+ description: 'Prompt text',+ initialValue: 'new default',+ },+ ],+ edgeIdsToRemove: [],+ })+ );++ const resyncedNode = nextState.nodes[0];+ if (!resyncedNode || resyncedNode.type !== 'invocation') {+ throw new Error('Expected invocation node');+ }++ expect(resyncedNode.data.inputs[fieldName]?.value).toBe('new default');+ expect(resyncedNode.data.dynamicInputTemplates[fieldName]?.type.name).toBe('StringField');+ });++ it('removes stale dynamic field templates when the selected workflow fields change', () => {+ const state = nodesSliceConfig.getInitialState();+ const node = buildNode(callSavedWorkflowTemplate);+ state.nodes.push(node);++ const fieldName = 'saved_workflow_input::node-1::a';++ let nextState = nodesSliceConfig.slice.reducer(+ state,+ callSavedWorkflowDynamicFieldsChanged({+ nodeId: node.id,+ fields: [+ {+ fieldName,+ fieldTemplate: buildDynamicIntegerTemplate(fieldName),+ label: 'Left Addend',+ description: 'The first number',+ initialValue: 23,+ },+ ],+ edgeIdsToRemove: [],+ })+ );++ nextState = nodesSliceConfig.slice.reducer(+ nextState,+ callSavedWorkflowDynamicFieldsChanged({+ nodeId: node.id,+ fields: [],+ edgeIdsToRemove: [],+ })+ );++ const resyncedNode = nextState.nodes[0];+ if (!resyncedNode || resyncedNode.type !== 'invocation') {+ throw new Error('Expected invocation node');+ }++ expect(resyncedNode.data.inputs[fieldName]).toBeUndefined();+ expect(resyncedNode.data.dynamicInputTemplates[fieldName]).toBeUndefined();+ });++ it('removes specified inbound edges during dynamic field resync', () => {+ const state = nodesSliceConfig.getInitialState();+ const sourceNode = buildNode(addTemplate);+ const targetNode = buildNode(callSavedWorkflowTemplate);+ state.nodes.push(sourceNode, targetNode);+ state.edges.push({+ id: 'edge-1',+ type: 'default',+ source: sourceNode.id,+ sourceHandle: 'value',+ target: targetNode.id,+ targetHandle: 'saved_workflow_input::node-1::a',+ });++ const nextState = nodesSliceConfig.slice.reducer(+ state,+ callSavedWorkflowDynamicFieldsChanged({+ nodeId: targetNode.id,+ fields: [],+ edgeIdsToRemove: ['edge-1'],+ })+ );++ expect(nextState.edges).toHaveLength(0);+ });+});+describe('nodesSlice connector actions', () => {it('removes an unconnected connector', () => {const connector = buildFixedConnectorNode('connector-1');diff --git a/invokeai/frontend/web/src/features/nodes/store/nodesSlice.ts b/invokeai/frontend/web/src/features/nodes/store/nodesSlice.tsindex 6713ee8fb4..9c6a9eea9f 100644--- a/invokeai/frontend/web/src/features/nodes/store/nodesSlice.ts+++ b/invokeai/frontend/web/src/features/nodes/store/nodesSlice.ts@@ -92,6 +92,7 @@ import {isNodeFieldElement,isTextElement,} from 'features/nodes/types/workflow';+import { buildFieldInputInstance } from 'features/nodes/util/schema/buildFieldInputInstance';import { atom, computed } from 'nanostores';import type { MouseEvent } from 'react';import type { UndoableOptions } from 'redux-undo';@@ -100,6 +101,8 @@ import type { z } from 'zod';import type { PendingConnection, Templates } from './types';+const CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX = 'saved_workflow_input::';+export const getInitialWorkflow = (): Omit<NodesState, 'mode' | 'formFieldInitialValues' | '_version'> => {return {name: '',@@ -550,6 +553,69 @@ const slice = createSlice({}field.description = val || '';},+ callSavedWorkflowDynamicFieldsChanged: (+ state,+ action: PayloadAction<{+ nodeId: string;+ fields: Array<{+ fieldName: string;+ fieldTemplate: Parameters<typeof buildFieldInputInstance>[1];+ label: string;+ description: string;+ initialValue: StatefulFieldValue;+ }>;+ edgeIdsToRemove: string[];+ }>+ ) => {+ const { nodeId, fields, edgeIdsToRemove } = action.payload;+ const node = state.nodes.find((n) => n.id === nodeId);+ if (!isInvocationNode(node) || node.data.type !== 'call_saved_workflow') {+ return;+ }++ const nextFieldNames = new Set(fields.map((field) => field.fieldName));++ for (const fieldName of Object.keys(node.data.inputs)) {+ if (fieldName.startsWith(CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX) && !nextFieldNames.has(fieldName)) {+ delete node.data.inputs[fieldName];+ delete node.data.dynamicInputTemplates[fieldName];+ }+ }++ for (const { fieldName, fieldTemplate, label, description, initialValue } of fields) {+ const existingTemplate = node.data.dynamicInputTemplates[fieldName];+ node.data.dynamicInputTemplates[fieldName] = fieldTemplate;+ const existing = node.data.inputs[fieldName];+ if (existing) {+ if (+ existingTemplate?.type.name !== fieldTemplate.type.name ||+ existingTemplate?.type.cardinality !== fieldTemplate.type.cardinality ||+ existingTemplate?.type.batch !== fieldTemplate.type.batch+ ) {+ const instance = buildFieldInputInstance(fieldName, fieldTemplate);+ instance.label = label;+ instance.description = description;+ instance.value = initialValue;+ node.data.inputs[fieldName] = instance;+ continue;+ }+ existing.label = label;+ existing.description = description;+ continue;+ }++ const instance = buildFieldInputInstance(fieldName, fieldTemplate);+ instance.label = label;+ instance.description = description;+ instance.value = initialValue;+ node.data.inputs[fieldName] = instance;+ }++ if (edgeIdsToRemove.length > 0) {+ const edgeIdsToRemoveSet = new Set(edgeIdsToRemove);+ state.edges = state.edges.filter((edge) => !edgeIdsToRemoveSet.has(edge.id));+ }+ },notesNodeValueChanged: (state, action: PayloadAction<{ nodeId: string; value: string }>) => {const { nodeId, value } = action.payload;const nodeIndex = state.nodes.findIndex((n) => n.id === nodeId);@@ -680,6 +746,7 @@ export const {fieldStringGeneratorValueChanged,fieldImageGeneratorValueChanged,fieldDescriptionChanged,+ callSavedWorkflowDynamicFieldsChanged,nodeEditorReset,nodeIsIntermediateChanged,nodeIsOpenChanged,@@ -925,3 +992,5 @@ export const getFormFieldInitialValues = (form: BuilderForm, nodes: NodesState['return formFieldInitialValues;};++export { CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX };diff --git a/invokeai/frontend/web/src/features/nodes/store/util/fieldValidators.test.ts b/invokeai/frontend/web/src/features/nodes/store/util/fieldValidators.test.tsnew file mode 100644index 0000000000..dacc143446--- /dev/null+++ b/invokeai/frontend/web/src/features/nodes/store/util/fieldValidators.test.ts@@ -0,0 +1,53 @@+import { callSavedWorkflowDynamicFieldsChanged, nodesSliceConfig } from 'features/nodes/store/nodesSlice';+import { buildNode, templates } from 'features/nodes/store/util/testUtils';+import type { IntegerFieldInputTemplate } from 'features/nodes/types/field';+import { describe, expect, it } from 'vitest';++import { getInvocationNodeErrors } from './fieldValidators';++const callSavedWorkflowTemplate = templates.call_saved_workflow;+const addTemplate = templates.add;++if (!callSavedWorkflowTemplate || !addTemplate || !addTemplate.inputs.a) {+ throw new Error('Expected saved workflow and add templates');+}++const addIntegerInputTemplate = addTemplate.inputs.a as IntegerFieldInputTemplate;++const buildDynamicIntegerTemplate = (fieldName: string): IntegerFieldInputTemplate => ({+ ...addIntegerInputTemplate,+ name: fieldName,+ title: 'Left Addend',+ input: 'any',+});++describe('getInvocationNodeErrors', () => {+ it('does not report missing field templates for dynamic saved workflow inputs', () => {+ const state = nodesSliceConfig.getInitialState();+ const node = buildNode(callSavedWorkflowTemplate);+ state.nodes.push(node);++ const nextState = nodesSliceConfig.slice.reducer(+ state,+ callSavedWorkflowDynamicFieldsChanged({+ nodeId: node.id,+ fields: [+ {+ fieldName: 'saved_workflow_input::node-1::a',+ fieldTemplate: buildDynamicIntegerTemplate('saved_workflow_input::node-1::a'),+ label: 'Left Addend',+ description: 'The first number',+ initialValue: 23,+ },+ ],+ edgeIdsToRemove: [],+ })+ );++ const errors = getInvocationNodeErrors(node.id, templates, nextState);++ expect(+ errors.find((error) => error.type === 'node-error' && error.issue === 'parameters.invoke.missingFieldTemplate')+ ).toBeUndefined();+ });+});diff --git a/invokeai/frontend/web/src/features/nodes/store/util/fieldValidators.ts b/invokeai/frontend/web/src/features/nodes/store/util/fieldValidators.tsindex 85738b357c..b3ac3424fd 100644--- a/invokeai/frontend/web/src/features/nodes/store/util/fieldValidators.ts+++ b/invokeai/frontend/web/src/features/nodes/store/util/fieldValidators.ts@@ -36,7 +36,12 @@ import {isStringFieldCollectionInputInstance,isStringFieldCollectionInputTemplate,} from 'features/nodes/types/field';-import { type InvocationNode, type InvocationTemplate, isInvocationNode } from 'features/nodes/types/invocation';+import {+ getInvocationNodeInputTemplate,+ type InvocationNode,+ type InvocationTemplate,+ isInvocationNode,+} from 'features/nodes/types/invocation';import { t } from 'i18next';import { map } from 'nanostores';import { useEffect } from 'react';@@ -272,7 +277,7 @@ export const getInvocationNodeErrors = (}for (const [fieldName, field] of Object.entries(node.data.inputs)) {- const fieldTemplate = nodeTemplate.inputs[fieldName];+ const fieldTemplate = getInvocationNodeInputTemplate(node.data, nodeTemplate, fieldName);if (!fieldTemplate) {errors.push({ type: 'node-error', nodeId, issue: t('parameters.invoke.missingFieldTemplate') });@@ -307,7 +312,7 @@ const syncNodeErrors = (nodesState: NodesState, templates: Templates) => {}for (const [fieldName, field] of Object.entries(node.data.inputs)) {- const fieldTemplate = nodeTemplate.inputs[fieldName];+ const fieldTemplate = getInvocationNodeInputTemplate(node.data, nodeTemplate, fieldName);if (!fieldTemplate) {errors.push({ type: 'node-error', nodeId: node.id, issue: t('parameters.invoke.missingFieldTemplate') });diff --git a/invokeai/frontend/web/src/features/nodes/store/util/getFirstValidConnection.ts b/invokeai/frontend/web/src/features/nodes/store/util/getFirstValidConnection.tsindex 2a466aae44..17b068ad0c 100644--- a/invokeai/frontend/web/src/features/nodes/store/util/getFirstValidConnection.ts+++ b/invokeai/frontend/web/src/features/nodes/store/util/getFirstValidConnection.ts@@ -9,7 +9,7 @@ import {import { validateConnection } from 'features/nodes/store/util/validateConnection';import type { FieldInputTemplate, FieldOutputTemplate } from 'features/nodes/types/field';import type { AnyEdge, AnyNode } from 'features/nodes/types/invocation';-import { isConnectorNode } from 'features/nodes/types/invocation';+import { getInvocationNodeInputTemplate, isConnectorNode, isInvocationNode } from 'features/nodes/types/invocation';/***@@ -118,6 +118,10 @@ export const getTargetCandidateFields = (return validateConnection(c, nodes, edges, templates, edgePendingUpdate, true) === null ? [candidate] : [];}+ if (!isInvocationNode(targetNode)) {+ return [];+ }+const targetTemplate = templates[targetNode.data.type];if (!targetTemplate) {return [];@@ -136,10 +140,14 @@ export const getTargetCandidateFields = (}}- const targetCandidateFields = map(targetTemplate.inputs).filter((field) => {+ const targetCandidateFields = Object.entries(targetNode.data.inputs).flatMap(([fieldName, input]) => {+ const field = getInvocationNodeInputTemplate(targetNode.data, targetTemplate, fieldName);+ if (!field || field.name !== input.name) {+ return [];+ }const c = { source, sourceHandle, target, targetHandle: field.name };const connectionErrorTKey = validateConnection(c, nodes, edges, templates, edgePendingUpdate, true);- return connectionErrorTKey === null;+ return connectionErrorTKey === null ? [field] : [];});return targetCandidateFields;@@ -162,8 +170,11 @@ export const getSourceCandidateFields = (if (isConnectorNode(sourceNode)) {const sourceFieldType = resolveConnectorSourceFieldType(sourceNode.id, nodes, edges, templates);- const targetTemplate = !isConnectorNode(targetNode) ? templates[targetNode.data.type] : null;- const targetFieldType = targetTemplate?.inputs[targetHandle]?.type;+ const targetTemplate = isInvocationNode(targetNode) ? templates[targetNode.data.type] : null;+ const targetFieldType =+ isInvocationNode(targetNode) && targetTemplate+ ? getInvocationNodeInputTemplate(targetNode.data, targetTemplate, targetHandle)?.type+ : undefined;const candidateType = sourceFieldType ?? targetFieldType;if (!candidateType) {return [];@@ -188,13 +199,16 @@ export const getSourceCandidateFields = (}if (!isConnectorNode(targetNode)) {+ if (!isInvocationNode(targetNode)) {+ return [];+ }+const targetTemplate = templates[targetNode.data.type];if (!targetTemplate) {return [];}- const targetField = targetTemplate.inputs[targetHandle];-+ const targetField = getInvocationNodeInputTemplate(targetNode.data, targetTemplate, targetHandle);if (!targetField) {return [];}diff --git a/invokeai/frontend/web/src/features/nodes/store/util/testUtils.ts b/invokeai/frontend/web/src/features/nodes/store/util/testUtils.tsindex 8706e199bb..67c477408f 100644--- a/invokeai/frontend/web/src/features/nodes/store/util/testUtils.ts+++ b/invokeai/frontend/web/src/features/nodes/store/util/testUtils.ts@@ -73,6 +73,102 @@ export const add: InvocationTemplate = {category: 'math',};+export const call_saved_workflow: InvocationTemplate = {+ title: 'Call Saved Workflow',+ type: 'call_saved_workflow',+ version: '1.0.0',+ tags: ['workflow', 'saved', 'library'],+ description: 'Displays and later executes against a selected saved workflow.',+ category: 'workflow',+ outputType: 'integer_output',+ inputs: {+ workflow_id: {+ name: 'workflow_id',+ title: 'Workflow Id',+ required: false,+ description: 'The selected saved workflow ID, managed by the workflow editor UI.',+ fieldKind: 'input',+ input: 'any',+ ui_hidden: false,+ ui_type: 'SavedWorkflowField',+ type: {+ name: 'SavedWorkflowField',+ cardinality: 'SINGLE',+ batch: false,+ originalType: {+ name: 'StringField',+ cardinality: 'SINGLE',+ batch: false,+ },+ },+ default: '',+ },+ },+ outputs: {+ value: {+ fieldKind: 'output',+ name: 'value',+ title: 'Value',+ description: 'The output integer',+ type: {+ name: 'IntegerField',+ cardinality: 'SINGLE',+ batch: false,+ },+ ui_hidden: false,+ },+ },+ useCache: false,+ nodePack: 'invokeai',+ classification: 'beta',+};++export const workflow_return: InvocationTemplate = {+ title: 'Workflow Return',+ type: 'workflow_return',+ version: '1.0.0',+ tags: ['workflow', 'return', 'output'],+ description: 'Defines the explicit collection result returned by a callable workflow.',+ category: 'workflow',+ outputType: 'workflow_return_output',+ inputs: {+ collection: {+ name: 'collection',+ title: 'Collection',+ required: false,+ description: 'The collection returned to a calling workflow.',+ fieldKind: 'input',+ input: 'connection',+ ui_hidden: false,+ ui_type: 'CollectionField',+ type: {+ name: 'CollectionField',+ cardinality: 'COLLECTION',+ batch: false,+ },+ default: undefined,+ },+ },+ outputs: {+ collection: {+ fieldKind: 'output',+ name: 'collection',+ title: 'Collection',+ description: 'The workflow return collection',+ type: {+ name: 'CollectionField',+ cardinality: 'COLLECTION',+ batch: false,+ },+ ui_hidden: false,+ ui_type: 'CollectionField',+ },+ },+ useCache: false,+ nodePack: 'invokeai',+ classification: 'beta',+};+export const sub: InvocationTemplate = {title: 'Subtract Integers',type: 'sub',@@ -537,6 +633,8 @@ const iterate: InvocationTemplate = {export const templates: Templates = {add,+ call_saved_workflow,+ workflow_return,sub,collect,iterate,@@ -554,6 +652,146 @@ export const schema = {},components: {schemas: {+ CallSavedWorkflowInvocation: {+ properties: {+ id: {+ type: 'string',+ title: 'Id',+ description: 'The id of this instance of an invocation. Must be unique among all instances of invocations.',+ field_kind: 'node_attribute',+ },+ is_intermediate: {+ type: 'boolean',+ title: 'Is Intermediate',+ description: 'Whether or not this is an intermediate invocation.',+ default: false,+ field_kind: 'node_attribute',+ ui_type: 'IsIntermediate',+ },+ use_cache: {+ type: 'boolean',+ title: 'Use Cache',+ description: 'Whether or not to use the cache',+ default: false,+ field_kind: 'node_attribute',+ },+ workflow_id: {+ type: 'string',+ title: 'Workflow Id',+ description: 'The selected saved workflow ID, managed by the workflow editor UI.',+ default: '',+ field_kind: 'input',+ input: 'any',+ orig_default: '',+ orig_required: false,+ ui_hidden: false,+ ui_type: 'SavedWorkflowField',+ },+ type: {+ type: 'string',+ enum: ['call_saved_workflow'],+ const: 'call_saved_workflow',+ title: 'type',+ default: 'call_saved_workflow',+ field_kind: 'node_attribute',+ },+ },+ type: 'object',+ required: ['type', 'id'],+ title: 'Call Saved Workflow',+ description: 'Displays and later executes against a selected saved workflow.',+ category: 'workflow',+ classification: 'beta',+ node_pack: 'invokeai',+ tags: ['workflow', 'saved', 'library'],+ version: '1.0.0',+ output: {+ $ref: '#/components/schemas/IntegerOutput',+ },+ class: 'invocation',+ },+ WorkflowReturnInvocation: {+ properties: {+ id: {+ type: 'string',+ title: 'Id',+ description: 'The id of this instance of an invocation. Must be unique among all instances of invocations.',+ field_kind: 'node_attribute',+ },+ is_intermediate: {+ type: 'boolean',+ title: 'Is Intermediate',+ description: 'Whether or not this is an intermediate invocation.',+ default: false,+ field_kind: 'node_attribute',+ ui_type: 'IsIntermediate',+ },+ use_cache: {+ type: 'boolean',+ title: 'Use Cache',+ description: 'Whether or not to use the cache',+ default: false,+ field_kind: 'node_attribute',+ },+ collection: {+ type: 'array',+ items: {},+ title: 'Collection',+ description: 'The collection returned to a calling workflow.',+ field_kind: 'input',+ input: 'connection',+ orig_required: false,+ ui_hidden: false,+ ui_type: 'CollectionField',+ },+ type: {+ type: 'string',+ enum: ['workflow_return'],+ const: 'workflow_return',+ title: 'type',+ default: 'workflow_return',+ field_kind: 'node_attribute',+ },+ },+ type: 'object',+ required: ['type', 'id'],+ title: 'Workflow Return',+ description: 'Defines the explicit collection result returned by a callable workflow.',+ category: 'workflow',+ classification: 'beta',+ node_pack: 'invokeai',+ tags: ['workflow', 'return', 'output'],+ version: '1.0.0',+ output: {+ $ref: '#/components/schemas/WorkflowReturnOutput',+ },+ class: 'invocation',+ },+ WorkflowReturnOutput: {+ properties: {+ type: {+ type: 'string',+ enum: ['workflow_return_output'],+ const: 'workflow_return_output',+ title: 'type',+ default: 'workflow_return_output',+ field_kind: 'node_attribute',+ },+ collection: {+ type: 'array',+ items: {},+ title: 'Collection',+ description: 'The workflow return collection',+ field_kind: 'output',+ ui_hidden: false,+ ui_type: 'CollectionField',+ },+ },+ type: 'object',+ required: ['type', 'collection'],+ title: 'Workflow Return Output',+ class: 'output',+ },AddInvocation: {properties: {id: {diff --git a/invokeai/frontend/web/src/features/nodes/store/util/validateConnection.test.ts b/invokeai/frontend/web/src/features/nodes/store/util/validateConnection.test.tsindex 730dced1d3..1eef079443 100644--- a/invokeai/frontend/web/src/features/nodes/store/util/validateConnection.test.ts+++ b/invokeai/frontend/web/src/features/nodes/store/util/validateConnection.test.ts@@ -1,5 +1,7 @@import { deepClone } from 'common/util/deepClone';import { set } from 'es-toolkit/compat';+import { callSavedWorkflowDynamicFieldsChanged, nodesSliceConfig } from 'features/nodes/store/nodesSlice';+import type { IntegerFieldInputTemplate } from 'features/nodes/types/field';import type { InvocationTemplate } from 'features/nodes/types/invocation';import { describe, expect, it } from 'vitest';@@ -8,7 +10,17 @@ import {CONNECTOR_OUTPUT_HANDLE,getConnectorDeletionSpliceConnections,} from './connectorTopology';-import { add, buildEdge, buildNode, collect, img_resize, main_model_loader, sub, templates } from './testUtils';+import {+ add,+ buildEdge,+ buildNode,+ call_saved_workflow,+ collect,+ img_resize,+ main_model_loader,+ sub,+ templates,+} from './testUtils';import { validateConnection } from './validateConnection';const ifTemplate: InvocationTemplate = {@@ -147,6 +159,66 @@ const integerCollectionOutputTemplate: InvocationTemplate = {classification: 'stable',};+const workflowReturnValueTemplate: InvocationTemplate = {+ title: 'Workflow Return Value',+ type: 'workflow_return_value',+ version: '1.0.0',+ tags: ['workflow', 'return', 'output'],+ category: 'workflow',+ description: 'Creates one named value for a callable workflow return.',+ outputType: 'workflow_return_value_output',+ inputs: {},+ outputs: {+ value: {+ fieldKind: 'output',+ name: 'value',+ title: 'Return Value',+ description: 'The named workflow return value.',+ type: {+ name: 'CollectionItemField',+ cardinality: 'SINGLE',+ batch: false,+ },+ ui_hidden: false,+ ui_type: 'CollectionItemField',+ },+ },+ useCache: false,+ nodePack: 'invokeai',+ classification: 'beta',+};++const workflowReturnTemplate: InvocationTemplate = {+ title: 'Workflow Return',+ type: 'workflow_return',+ version: '1.0.0',+ tags: ['workflow', 'return', 'output'],+ category: 'workflow',+ description: 'Defines the explicit named result returned by a callable workflow.',+ outputType: 'workflow_return_output',+ inputs: {+ values: {+ name: 'values',+ title: 'Values',+ required: false,+ description: 'The named values returned to a calling workflow.',+ fieldKind: 'input',+ input: 'connection',+ ui_hidden: false,+ type: {+ name: 'WorkflowReturnValueField',+ cardinality: 'SINGLE_OR_COLLECTION',+ batch: false,+ },+ default: undefined,+ },+ },+ outputs: {},+ useCache: false,+ nodePack: 'invokeai',+ classification: 'beta',+};+const buildConnectorNode = (id: string) => ({id,type: 'connector' as const,@@ -217,6 +289,64 @@ describe(validateConnection.name, () => {});});+ it('accepts connections to dynamic saved workflow input fields', () => {+ const addIntegerInputTemplate = add.inputs.a as IntegerFieldInputTemplate;+ const state = nodesSliceConfig.getInitialState();+ const sourceNode = buildNode(add);+ const targetNode = buildNode(call_saved_workflow);+ state.nodes.push(sourceNode, targetNode);++ const nextState = nodesSliceConfig.slice.reducer(+ state,+ callSavedWorkflowDynamicFieldsChanged({+ nodeId: targetNode.id,+ fields: [+ {+ fieldName: 'saved_workflow_input::node-1::a',+ fieldTemplate: {+ ...addIntegerInputTemplate,+ name: 'saved_workflow_input::node-1::a',+ title: 'Left Addend',+ input: 'any',+ },+ label: 'Left Addend',+ description: 'The first number',+ initialValue: 23,+ },+ ],+ edgeIdsToRemove: [],+ })+ );++ const c = {+ source: sourceNode.id,+ sourceHandle: 'value',+ target: targetNode.id,+ targetHandle: 'saved_workflow_input::node-1::a',+ };+ const r = validateConnection(c, nextState.nodes, [], templates, null);+ expect(r).toEqual(null);+ });++ it('accepts a single workflow return value connected directly to workflow_return values', () => {+ const sourceNode = buildNode(workflowReturnValueTemplate);+ const targetNode = buildNode(workflowReturnTemplate);+ const c = { source: sourceNode.id, sourceHandle: 'value', target: targetNode.id, targetHandle: 'values' };++ const r = validateConnection(+ c,+ [sourceNode, targetNode],+ [],+ {+ workflow_return_value: workflowReturnValueTemplate,+ workflow_return: workflowReturnTemplate,+ },+ null+ );++ expect(r).toEqual(null);+ });+describe('duplicate connections', () => {const n1 = buildNode(add);const n2 = buildNode(sub);diff --git a/invokeai/frontend/web/src/features/nodes/store/util/validateConnection.ts b/invokeai/frontend/web/src/features/nodes/store/util/validateConnection.tsindex bb98d472d3..710e49de7c 100644--- a/invokeai/frontend/web/src/features/nodes/store/util/validateConnection.ts+++ b/invokeai/frontend/web/src/features/nodes/store/util/validateConnection.ts@@ -11,7 +11,7 @@ import { getHasCycles } from 'features/nodes/store/util/getHasCycles';import { validateConnectionTypes } from 'features/nodes/store/util/validateConnectionTypes';import type { FieldType } from 'features/nodes/types/field';import type { AnyEdge, AnyNode, InvocationNode } from 'features/nodes/types/invocation';-import { isConnectorNode, isInvocationNode } from 'features/nodes/types/invocation';+import { getInvocationNodeInputTemplate, isConnectorNode, isInvocationNode } from 'features/nodes/types/invocation';import type { SetNonNullable } from 'type-fest';type Connection = SetNonNullable<NullableConnection>;@@ -291,7 +291,7 @@ export const validateConnection: ValidateConnectionFunc = (return 'nodes.missingInvocationTemplate';}- const targetFieldTemplate = targetTemplate.inputs[c.targetHandle];+ const targetFieldTemplate = getInvocationNodeInputTemplate(targetNode.data, targetTemplate, c.targetHandle);if (!targetFieldTemplate) {return 'nodes.missingFieldTemplate';}diff --git a/invokeai/frontend/web/src/features/nodes/types/field.ts b/invokeai/frontend/web/src/features/nodes/types/field.tsindex ffd87ae398..df2f909dc7 100644--- a/invokeai/frontend/web/src/features/nodes/types/field.ts+++ b/invokeai/frontend/web/src/features/nodes/types/field.ts@@ -188,6 +188,10 @@ const zSchedulerFieldType = zFieldTypeBase.extend({name: z.literal('SchedulerField'),originalType: zStatelessFieldType.optional(),});+const zSavedWorkflowFieldType = zFieldTypeBase.extend({+ name: z.literal('SavedWorkflowField'),+ originalType: zStatelessFieldType.optional(),+});const zFloatGeneratorFieldType = zFieldTypeBase.extend({name: z.literal('FloatGeneratorField'),originalType: zStatelessFieldType.optional(),@@ -216,6 +220,7 @@ const zStatefulFieldType = z.union([zModelIdentifierFieldType,zColorFieldType,zSchedulerFieldType,+ zSavedWorkflowFieldType,zFloatGeneratorFieldType,zIntegerGeneratorFieldType,zStringGeneratorFieldType,@@ -697,6 +702,28 @@ export const isSchedulerFieldInputInstance = buildInstanceTypeGuard(zSchedulerFiexport const isSchedulerFieldInputTemplate = buildTemplateTypeGuard<SchedulerFieldInputTemplate>('SchedulerField');// #endregion+// #region SavedWorkflowField+const zSavedWorkflowFieldValue = z.string();+const zSavedWorkflowFieldInputInstance = zFieldInputInstanceBase.extend({+ value: zSavedWorkflowFieldValue,+});+const zSavedWorkflowFieldInputTemplate = zFieldInputTemplateBase.extend({+ type: zSavedWorkflowFieldType,+ originalType: zFieldType.optional(),+ default: zSavedWorkflowFieldValue,+ maxLength: z.number().int().gte(0).optional(),+ minLength: z.number().int().gte(0).optional(),+});+const zSavedWorkflowFieldOutputTemplate = zFieldOutputTemplateBase.extend({+ type: zSavedWorkflowFieldType,+});+export type SavedWorkflowFieldInputInstance = z.infer<typeof zSavedWorkflowFieldInputInstance>;+export type SavedWorkflowFieldInputTemplate = z.infer<typeof zSavedWorkflowFieldInputTemplate>;+export const isSavedWorkflowFieldInputInstance = buildInstanceTypeGuard(zSavedWorkflowFieldInputInstance);+export const isSavedWorkflowFieldInputTemplate =+ buildTemplateTypeGuard<SavedWorkflowFieldInputTemplate>('SavedWorkflowField');+// #endregion+// #region FloatGeneratorFieldexport const FloatGeneratorArithmeticSequenceType = 'float_generator_arithmetic_sequence';const zFloatGeneratorArithmeticSequence = z.object({@@ -1290,6 +1317,7 @@ export const zStatefulFieldValue = z.union([zModelIdentifierFieldValue,zColorFieldValue,zSchedulerFieldValue,+ zSavedWorkflowFieldValue,zFloatGeneratorFieldValue,zIntegerGeneratorFieldValue,zStringGeneratorFieldValue,@@ -1318,6 +1346,7 @@ const zStatefulFieldInputInstance = z.union([zModelIdentifierFieldInputInstance,zColorFieldInputInstance,zSchedulerFieldInputInstance,+ zSavedWorkflowFieldInputInstance,zFloatGeneratorFieldInputInstance,zIntegerGeneratorFieldInputInstance,zStringGeneratorFieldInputInstance,@@ -1345,7 +1374,7 @@ const zStatefulFieldInputTemplate = z.union([zModelIdentifierFieldInputTemplate,zColorFieldInputTemplate,zSchedulerFieldInputTemplate,- zStatelessFieldInputTemplate,+ zSavedWorkflowFieldInputTemplate,zFloatGeneratorFieldInputTemplate,zIntegerGeneratorFieldInputTemplate,zStringGeneratorFieldInputTemplate,@@ -1373,6 +1402,7 @@ const zStatefulFieldOutputTemplate = z.union([zModelIdentifierFieldOutputTemplate,zColorFieldOutputTemplate,zSchedulerFieldOutputTemplate,+ zSavedWorkflowFieldOutputTemplate,zFloatGeneratorFieldOutputTemplate,zIntegerGeneratorFieldOutputTemplate,zStringGeneratorFieldOutputTemplate,diff --git a/invokeai/frontend/web/src/features/nodes/types/invocation.ts b/invokeai/frontend/web/src/features/nodes/types/invocation.tsindex 5d8d85dd87..5ceb30f779 100644--- a/invokeai/frontend/web/src/features/nodes/types/invocation.ts+++ b/invokeai/frontend/web/src/features/nodes/types/invocation.ts@@ -32,6 +32,7 @@ export const zInvocationNodeData = z.object({notes: z.string(),type: z.string().trim().min(1),inputs: z.record(z.string(), zFieldInputInstance),+ dynamicInputTemplates: z.record(z.string(), zFieldInputTemplate).default({}),isOpen: z.boolean(),isIntermediate: z.boolean(),useCache: z.boolean(),@@ -162,3 +163,28 @@ const isGeneratorNode = (node: InvocationNode) => isGeneratorNodeType(node.data.export const isExecutableNode = (node: InvocationNode) => {return !isBatchNode(node) && !isGeneratorNode(node);};++export const getInvocationNodeInputTemplate = (+ nodeData: Pick<InvocationNodeData, 'inputs'> & Partial<Pick<InvocationNodeData, 'dynamicInputTemplates'>>,+ template: InvocationTemplate,+ fieldName: string+) => {+ return nodeData.dynamicInputTemplates?.[fieldName] ?? template.inputs[fieldName];+};++export const getInvocationNodeTemplateWithDynamicInputs = (+ nodeData: Pick<InvocationNodeData, 'inputs'> & Partial<Pick<InvocationNodeData, 'dynamicInputTemplates'>>,+ template: InvocationTemplate+): InvocationTemplate => {+ if (!nodeData.dynamicInputTemplates || Object.keys(nodeData.dynamicInputTemplates).length === 0) {+ return template;+ }++ return {+ ...template,+ inputs: {+ ...template.inputs,+ ...nodeData.dynamicInputTemplates,+ },+ };+};diff --git a/invokeai/frontend/web/src/features/nodes/types/workflow.ts b/invokeai/frontend/web/src/features/nodes/types/workflow.tsindex 34f98eb289..bfb7b92b18 100644--- a/invokeai/frontend/web/src/features/nodes/types/workflow.ts+++ b/invokeai/frontend/web/src/features/nodes/types/workflow.ts@@ -369,24 +369,38 @@ const zValidatedBuilderForm = zBuilderForm//# endregion// #region Workflow-export const zWorkflowV3 = z.object({- id: z.string().min(1).optional(),- name: z.string(),- author: z.string(),- description: z.string(),- version: z.string(),- contact: z.string(),- tags: z.string(),- notes: z.string(),- nodes: z.array(zWorkflowNode),- edges: z.array(zWorkflowEdge),- exposedFields: z.array(zFieldIdentifier),- meta: z.object({- category: zWorkflowCategory.default('user'),- version: z.literal('4.0.0'),- }),- // Use the validated form schema!- form: zValidatedBuilderForm,-});+export const zWorkflowV3 = z+ .object({+ id: z.string().min(1).optional(),+ name: z.string(),+ author: z.string(),+ description: z.string(),+ version: z.string(),+ contact: z.string(),+ tags: z.string(),+ notes: z.string(),+ nodes: z.array(zWorkflowNode),+ edges: z.array(zWorkflowEdge),+ exposedFields: z.array(zFieldIdentifier),+ meta: z.object({+ category: zWorkflowCategory.default('user'),+ version: z.literal('4.0.0'),+ }),+ // Use the validated form schema!+ form: zValidatedBuilderForm,+ })+ .superRefine((workflow, ctx) => {+ const workflowReturnCount = workflow.nodes.filter(+ (node) => node.type === 'invocation' && node.data.type === 'workflow_return'+ ).length;++ if (workflowReturnCount > 1) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'A workflow may not contain more than one workflow_return node.',+ path: ['nodes'],+ });+ }+ });export type WorkflowV3 = z.infer<typeof zWorkflowV3>;// #endregiondiff --git a/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.test.ts b/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.test.tsindex b44c6b38cd..046487e40e 100644--- a/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.test.ts+++ b/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.test.ts@@ -1,10 +1,28 @@import { deepClone } from 'common/util/deepClone';+import { callSavedWorkflowDynamicFieldsChanged, nodesSliceConfig } from 'features/nodes/store/nodesSlice';import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE } from 'features/nodes/store/util/connectorTopology';import { add, buildEdge, buildNode, img_resize, sub, templates } from 'features/nodes/store/util/testUtils';+import type { IntegerFieldInputTemplate } from 'features/nodes/types/field';import { describe, expect, it } from 'vitest';import { buildNodesGraph } from './buildNodesGraph';+const callSavedWorkflowTemplate = templates.call_saved_workflow;+const addTemplate = templates.add;++if (!callSavedWorkflowTemplate || !addTemplate || !addTemplate.inputs.a) {+ throw new Error('Expected saved workflow and add templates');+}++const addIntegerInputTemplate = addTemplate.inputs.a as IntegerFieldInputTemplate;++const buildDynamicIntegerTemplate = (fieldName: string): IntegerFieldInputTemplate => ({+ ...addIntegerInputTemplate,+ name: fieldName,+ title: 'Left Addend',+ input: 'any',+});+const buildConnectorNode = (id: string) => ({id,type: 'connector' as const,@@ -54,6 +72,139 @@ const buildState = (nodes: unknown[], edges: unknown[]) =>}) as unknown as Parameters<typeof buildNodesGraph>[0];describe('buildNodesGraph', () => {+ it('serializes dynamic saved workflow inputs into workflow_inputs', () => {+ const state = nodesSliceConfig.getInitialState();+ const node = buildNode(callSavedWorkflowTemplate);+ state.nodes.push(node);++ const nextState = nodesSliceConfig.slice.reducer(+ state,+ callSavedWorkflowDynamicFieldsChanged({+ nodeId: node.id,+ fields: [+ {+ fieldName: 'saved_workflow_input::node-1::a',+ fieldTemplate: buildDynamicIntegerTemplate('saved_workflow_input::node-1::a'),+ label: 'Left Addend',+ description: 'The first number',+ initialValue: 23,+ },+ ],+ edgeIdsToRemove: [],+ })+ );++ const rootState = {+ nodes: {+ past: [],+ future: [],+ present: nextState,+ },+ gallery: {+ autoAddBoardId: 'none',+ },+ } as never;++ const graph = buildNodesGraph(rootState, templates);++ expect(graph.nodes[node.id]).toMatchObject({+ workflow_id: '',+ workflow_inputs: {+ ['saved_workflow_input::node-1::a']: 23,+ },+ });+ });++ it('omits connected dynamic saved workflow literal values from workflow_inputs while preserving the edge', () => {+ const state = nodesSliceConfig.getInitialState();+ const sourceNode = buildNode(add);+ const callNode = buildNode(callSavedWorkflowTemplate);+ state.nodes.push(sourceNode, callNode);++ const nextState = deepClone(+ nodesSliceConfig.slice.reducer(+ state,+ callSavedWorkflowDynamicFieldsChanged({+ nodeId: callNode.id,+ fields: [+ {+ fieldName: 'saved_workflow_input::node-1::a',+ fieldTemplate: buildDynamicIntegerTemplate('saved_workflow_input::node-1::a'),+ label: 'Left Addend',+ description: 'The first number',+ initialValue: 23,+ },+ ],+ edgeIdsToRemove: [],+ })+ )+ );++ nextState.edges.push(buildEdge(sourceNode.id, 'value', callNode.id, 'saved_workflow_input::node-1::a'));++ const rootState = {+ nodes: {+ past: [],+ future: [],+ present: nextState,+ },+ gallery: {+ autoAddBoardId: 'none',+ },+ } as never;++ const graph = buildNodesGraph(rootState, templates);++ expect(graph.nodes[callNode.id]).toMatchObject({+ workflow_id: '',+ workflow_inputs: {},+ });+ expect(graph.edges).toContainEqual({+ source: { node_id: sourceNode.id, field: 'value' },+ destination: { node_id: callNode.id, field: 'saved_workflow_input::node-1::a' },+ });+ });++ it('does not serialize stale hidden saved workflow input values without matching dynamic fields', () => {+ const state = nodesSliceConfig.getInitialState();+ const node = buildNode(callSavedWorkflowTemplate);+ node.data.inputs.workflow_inputs = {+ name: 'workflow_inputs',+ type: 'workflow_inputs',+ value: {+ ['saved_workflow_input::old-node::a']: 23,+ },+ } as never;+ state.nodes.push(node);+ const templatesWithWorkflowInputs = {+ ...templates,+ call_saved_workflow: {+ ...callSavedWorkflowTemplate,+ inputs: {+ ...callSavedWorkflowTemplate.inputs,+ workflow_inputs: buildDynamicIntegerTemplate('workflow_inputs'),+ },+ },+ };++ const rootState = {+ nodes: {+ past: [],+ future: [],+ present: state,+ },+ gallery: {+ autoAddBoardId: 'none',+ },+ } as never;++ const graph = buildNodesGraph(rootState, templatesWithWorkflowInputs);+ const graphNode = graph.nodes[node.id] as { workflow_id: string; workflow_inputs: Record<string, unknown> };++ expect(graphNode.workflow_id).toBe('');+ expect(graphNode.workflow_inputs).toEqual({});+ });+it('flattens a single connector to one direct execution edge', () => {const source = buildNode(add);const target = buildNode(sub);diff --git a/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.ts b/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.tsindex 50052c806c..eb2ce06d15 100644--- a/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.ts+++ b/invokeai/frontend/web/src/features/nodes/util/graph/buildNodesGraph.ts@@ -8,11 +8,17 @@ import { resolveConnectorSource } from 'features/nodes/store/util/connectorTopolimport type { BoardField } from 'features/nodes/types/common';import type { BoardFieldInputInstance } from 'features/nodes/types/field';import { isBoardFieldInputInstance, isBoardFieldInputTemplate } from 'features/nodes/types/field';-import { isConnectorNode, isExecutableNode, isInvocationNode } from 'features/nodes/types/invocation';+import {+ getInvocationNodeInputTemplate,+ isConnectorNode,+ isExecutableNode,+ isInvocationNode,+} from 'features/nodes/types/invocation';import type { AnyInvocation, Graph } from 'services/api/types';import { v4 as uuidv4 } from 'uuid';const log = logger('workflows');+const CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX = 'saved_workflow_input::';const getBoardField = (field: BoardFieldInputInstance, state: RootState): BoardField | undefined => {// Translate the UI value to the graph value. See note in BoardFieldInputComponent for more info.@@ -59,7 +65,20 @@ export const buildNodesGraph = (state: RootState, templates: Templates): Requireconst transformedInputs = reduce(inputs,(inputsAccumulator, input, name) => {- const fieldTemplate = nodeTemplate.inputs[name];+ if (type === 'call_saved_workflow' && name === 'workflow_inputs') {+ return inputsAccumulator;+ }++ if (type === 'call_saved_workflow' && name.startsWith(CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX)) {+ const workflowInputs = {+ ...((inputsAccumulator['workflow_inputs'] as Record<string, unknown> | undefined) ?? {}),+ };+ workflowInputs[name] = input.value;+ inputsAccumulator['workflow_inputs'] = workflowInputs;+ return inputsAccumulator;+ }++ const fieldTemplate = getInvocationNodeInputTemplate(data, nodeTemplate, name);if (!fieldTemplate) {log.warn({ id, name }, 'Field template not found!');return inputsAccumulator;@@ -75,6 +94,10 @@ export const buildNodesGraph = (state: RootState, templates: Templates): Require{} as Record<Exclude<string, 'id' | 'type'>, unknown>);+ if (type === 'call_saved_workflow' && transformedInputs['workflow_inputs'] === undefined) {+ transformedInputs['workflow_inputs'] = {};+ }+// add reserved use_cachetransformedInputs['use_cache'] = node.data.useCache;@@ -181,7 +204,20 @@ export const buildNodesGraph = (state: RootState, templates: Templates): Require*/parsedEdges.forEach((edge) => {const destination_node = parsedNodes[edge.destination.node_id];+ if (!destination_node) {+ return;+ }const field = edge.destination.field;+ const destinationNodeRecord = destination_node as Record<string, unknown>;+ if (+ destination_node.type === 'call_saved_workflow' &&+ field.startsWith(CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX) &&+ typeof destinationNodeRecord['workflow_inputs'] === 'object' &&+ destinationNodeRecord['workflow_inputs'] !== null+ ) {+ delete (destinationNodeRecord['workflow_inputs'] as Record<string, unknown>)[field];+ return;+ }parsedNodes[edge.destination.node_id] = omit(destination_node, field) as AnyInvocation;});diff --git a/invokeai/frontend/web/src/features/nodes/util/node/buildInvocationNode.ts b/invokeai/frontend/web/src/features/nodes/util/node/buildInvocationNode.tsindex 859e978b0f..2af152e6bb 100644--- a/invokeai/frontend/web/src/features/nodes/util/node/buildInvocationNode.ts+++ b/invokeai/frontend/web/src/features/nodes/util/node/buildInvocationNode.ts@@ -40,6 +40,7 @@ export const buildInvocationNode = (position: XYPosition, template: InvocationTeuseCache: template.useCache,nodePack: template.nodePack,inputs,+ dynamicInputTemplates: {},},};diff --git a/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputInstance.ts b/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputInstance.tsindex ef7b92efdd..6bb3155f47 100644--- a/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputInstance.ts+++ b/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputInstance.ts@@ -11,6 +11,7 @@ const FIELD_VALUE_FALLBACK_MAP: Record<StatefulFieldType['name'], FieldValue> =IntegerField: 0,ModelIdentifierField: undefined,SchedulerField: 'dpmpp_3m_k',+ SavedWorkflowField: '',StringField: '',StylePresetField: undefined,FloatGeneratorField: undefined,diff --git a/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputTemplate.ts b/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputTemplate.tsindex adaa3f413c..ca31b988ff 100644--- a/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputTemplate.ts+++ b/invokeai/frontend/web/src/features/nodes/util/schema/buildFieldInputTemplate.ts@@ -17,6 +17,7 @@ import type {IntegerFieldInputTemplate,IntegerGeneratorFieldInputTemplate,ModelIdentifierFieldInputTemplate,+ SavedWorkflowFieldInputTemplate,SchedulerFieldInputTemplate,StatefulFieldType,StatelessFieldInputTemplate,@@ -408,6 +409,28 @@ const buildSchedulerFieldInputTemplate: FieldInputTemplateBuilder<SchedulerFieldreturn template;};+const buildSavedWorkflowFieldInputTemplate: FieldInputTemplateBuilder<SavedWorkflowFieldInputTemplate> = ({+ schemaObject,+ baseField,+ fieldType,+}) => {+ const template: SavedWorkflowFieldInputTemplate = {+ ...baseField,+ type: fieldType,+ default: schemaObject.default ?? '',+ };++ if (schemaObject.minLength !== undefined) {+ template.minLength = schemaObject.minLength;+ }++ if (schemaObject.maxLength !== undefined) {+ template.maxLength = schemaObject.maxLength;+ }++ return template;+};+const buildFloatGeneratorFieldInputTemplate: FieldInputTemplateBuilder<FloatGeneratorFieldInputTemplate> = ({// schemaObject,baseField,@@ -474,6 +497,7 @@ const TEMPLATE_BUILDER_MAP: Record<StatefulFieldType['name'], FieldInputTemplateIntegerField: buildIntegerFieldInputTemplate,ModelIdentifierField: buildModelIdentifierFieldInputTemplate,SchedulerField: buildSchedulerFieldInputTemplate,+ SavedWorkflowField: buildSavedWorkflowFieldInputTemplate,StringField: buildStringFieldInputTemplate,StylePresetField: buildStylePresetFieldInputTemplate,FloatGeneratorField: buildFloatGeneratorFieldInputTemplate,diff --git a/invokeai/frontend/web/src/features/nodes/util/schema/parseSchema.test.ts b/invokeai/frontend/web/src/features/nodes/util/schema/parseSchema.test.tsindex 45dd0f79a3..1317f973dd 100644--- a/invokeai/frontend/web/src/features/nodes/util/schema/parseSchema.test.ts+++ b/invokeai/frontend/web/src/features/nodes/util/schema/parseSchema.test.ts@@ -1,5 +1,5 @@import { omit, pick } from 'es-toolkit/compat';-import { schema, templates } from 'features/nodes/store/util/testUtils';+import { call_saved_workflow, schema, templates, workflow_return } from 'features/nodes/store/util/testUtils';import { parseSchema } from 'features/nodes/util/schema/parseSchema';import { describe, expect, it } from 'vitest';@@ -18,4 +18,32 @@ describe('parseSchema', () => {const parsed = parseSchema(schema, ['add']);expect(stripUndefinedDeep(parsed)).toEqual(stripUndefinedDeep(pick(templates, 'add')));});+ it('should parse the call_saved_workflow node template', () => {+ const parsed = parseSchema(schema);+ expect(stripUndefinedDeep(parsed.call_saved_workflow)).toEqual(stripUndefinedDeep(call_saved_workflow));+ const template = parsed.call_saved_workflow;+ if (!template) {+ throw new Error('Expected call_saved_workflow template');+ }+ const workflowIdInput = template.inputs.workflow_id;+ if (!workflowIdInput) {+ throw new Error('Expected workflow_id input');+ }+ expect(workflowIdInput.type.name).toBe('SavedWorkflowField');+ expect(workflowIdInput.ui_type).toBe('SavedWorkflowField');+ });+ it('should parse the workflow_return node template', () => {+ const parsed = parseSchema(schema);+ expect(stripUndefinedDeep(parsed.workflow_return)).toEqual(stripUndefinedDeep(workflow_return));+ const template = parsed.workflow_return;+ if (!template) {+ throw new Error('Expected workflow_return template');+ }+ const collectionInput = template.inputs.collection;+ if (!collectionInput) {+ throw new Error('Expected collection input');+ }+ expect(collectionInput.type.name).toBe('CollectionField');+ expect(collectionInput.ui_type).toBe('CollectionField');+ });});diff --git a/invokeai/frontend/web/src/features/nodes/util/workflow/buildWorkflow.test.ts b/invokeai/frontend/web/src/features/nodes/util/workflow/buildWorkflow.test.tsnew file mode 100644index 0000000000..c7bdd80ace--- /dev/null+++ b/invokeai/frontend/web/src/features/nodes/util/workflow/buildWorkflow.test.ts@@ -0,0 +1,43 @@+import { getInitialWorkflow } from 'features/nodes/store/nodesSlice';+import { buildNode, call_saved_workflow } from 'features/nodes/store/util/testUtils';+import { describe, expect, it } from 'vitest';++describe('buildWorkflowFast', () => {+ it('persists the selected workflow id for call_saved_workflow nodes', async () => {+ Object.assign(globalThis, {+ window: {+ location: {+ origin: 'http://localhost',+ },+ },+ });++ const { buildWorkflowFast } = await import('features/nodes/util/workflow/buildWorkflow');+ const node = buildNode(call_saved_workflow);+ const workflowIdInput = node.data.inputs.workflow_id;+ if (!workflowIdInput) {+ throw new Error('Expected workflow_id input');+ }+ workflowIdInput.value = 'workflow-123';++ const workflow = buildWorkflowFast({+ _version: 1,+ formFieldInitialValues: {},+ ...getInitialWorkflow(),+ nodes: [node],+ edges: [],+ });++ expect(workflow.nodes).toHaveLength(1);+ expect(workflow.nodes[0]?.type).toBe('invocation');+ if (workflow.nodes[0]?.type !== 'invocation') {+ throw new Error('Expected invocation node');+ }+ expect(workflow.nodes[0].data.type).toBe('call_saved_workflow');+ const serializedWorkflowIdInput = workflow.nodes[0].data.inputs.workflow_id;+ if (!serializedWorkflowIdInput) {+ throw new Error('Expected serialized workflow_id input');+ }+ expect(serializedWorkflowIdInput.value).toBe('workflow-123');+ });+});diff --git a/invokeai/frontend/web/src/features/nodes/util/workflow/graphToWorkflow.ts b/invokeai/frontend/web/src/features/nodes/util/workflow/graphToWorkflow.tsindex 0dc24db323..d853d3574e 100644--- a/invokeai/frontend/web/src/features/nodes/util/workflow/graphToWorkflow.ts+++ b/invokeai/frontend/web/src/features/nodes/util/workflow/graphToWorkflow.ts@@ -85,6 +85,7 @@ export const graphToWorkflow = (graph: NonNullableGraph, autoLayout = true): Worversion: template.version,label: '',notes: '',+ dynamicInputTemplates: {},isOpen: true,isIntermediate: node.is_intermediate ?? false,useCache: node.use_cache ?? true,diff --git a/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.test.ts b/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.test.tsindex b7ead12fa2..f7ee86da1f 100644--- a/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.test.ts+++ b/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.test.ts@@ -1,12 +1,23 @@import { get } from 'es-toolkit/compat';import { addElement } from 'features/nodes/components/sidePanel/builder/form-manipulation';import { CONNECTOR_INPUT_HANDLE, CONNECTOR_OUTPUT_HANDLE } from 'features/nodes/store/util/connectorTopology';-import { img_resize, main_model_loader } from 'features/nodes/store/util/testUtils';+import { img_resize, main_model_loader, workflow_return } from 'features/nodes/store/util/testUtils';import type { InvocationTemplate } from 'features/nodes/types/invocation';import type { WorkflowV3 } from 'features/nodes/types/workflow';import { buildNodeFieldElement, getDefaultForm, isNodeFieldElement } from 'features/nodes/types/workflow';+import { buildInvocationNode } from 'features/nodes/util/node/buildInvocationNode';import { validateWorkflow } from 'features/nodes/util/workflow/validateWorkflow';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';++vi.mock('app/logging/logger', () => ({+ logger: () => ({+ trace: vi.fn(),+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ }),+}));const imageCollectionTemplate = {title: 'Image Collection Primitive',@@ -89,6 +100,7 @@ describe('validateWorkflow', () => {version: '1.0.2',label: '',notes: '',+ dynamicInputTemplates: {},isOpen: true,isIntermediate: true,useCache: true,@@ -119,6 +131,7 @@ describe('validateWorkflow', () => {version: '1.2.2',label: '',notes: '',+ dynamicInputTemplates: {},isOpen: true,isIntermediate: true,useCache: true,@@ -169,6 +182,7 @@ describe('validateWorkflow', () => {isIntermediate: true,useCache: true,nodePack: 'invokeai',+ dynamicInputTemplates: {},inputs: {collection: {name: 'collection',@@ -215,6 +229,46 @@ describe('validateWorkflow', () => {expect(validationResult.warnings.length).toBe(1);expect(get(validationResult, 'workflow.nodes[0].data.inputs.model.value')).toBeUndefined();});+ it('should reject workflows with duplicate workflow_return nodes at build time', async () => {+ Object.assign(globalThis, {+ window: {+ location: {+ origin: 'http://localhost',+ },+ },+ });++ const { buildWorkflowWithValidation } = await import('features/nodes/util/workflow/buildWorkflow');+ const returnNode1 = buildInvocationNode({ x: 0, y: 0 }, workflow_return);+ const returnNode2 = buildInvocationNode({ x: 100, y: 0 }, workflow_return);++ const built = buildWorkflowWithValidation({+ _version: 1,+ formFieldInitialValues: {},+ ...getWorkflow(),+ nodes: [returnNode1, returnNode2],+ edges: [],+ });++ expect(built).toBeNull();+ });+ it('should warn when loading a workflow with duplicate workflow_return nodes', async () => {+ const returnNode1 = buildInvocationNode({ x: 0, y: 0 }, workflow_return);+ const returnNode2 = buildInvocationNode({ x: 100, y: 0 }, workflow_return);++ await expect(+ validateWorkflow({+ workflow: {+ ...getWorkflow(),+ nodes: [returnNode1, returnNode2],+ },+ templates: { img_resize, main_model_loader, workflow_return },+ checkImageAccess: resolveTrue,+ checkBoardAccess: resolveTrue,+ checkModelAccess: resolveTrue,+ })+ ).rejects.toThrow(/workflow_return/i);+ });it('should delete malformed connector edges with invalid handles', async () => {const workflow = getWorkflow();diff --git a/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.ts b/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.tsindex 741591dcdf..2e2ab16bba 100644--- a/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.ts+++ b/invokeai/frontend/web/src/features/nodes/util/workflow/validateWorkflow.ts@@ -9,6 +9,7 @@ import {isModelFieldType,isModelIdentifierFieldInputInstance,} from 'features/nodes/types/field';+import { getInvocationNodeInputTemplate } from 'features/nodes/types/invocation';import type { WorkflowV3 } from 'features/nodes/types/workflow';import {buildNodeFieldElement,@@ -121,7 +122,13 @@ export const validateWorkflow = async (args: ValidateWorkflowArgs): Promise<Vali);}- if (targetNode && targetTemplate && edge.type === 'default' && !(edge.targetHandle in targetTemplate.inputs)) {+ if (+ targetNode &&+ isWorkflowInvocationNode(targetNode) &&+ targetTemplate &&+ edge.type === 'default' &&+ !getInvocationNodeInputTemplate(targetNode.data, targetTemplate, edge.targetHandle)+ ) {// The edge's target/input node field does not existissues.push(t('nodes.targetNodeFieldDoesNotExist', {@@ -193,7 +200,7 @@ export const validateWorkflow = async (args: ValidateWorkflowArgs): Promise<Vali}for (const input of Object.values(node.data.inputs)) {- const fieldTemplate = template.inputs[input.name];+ const fieldTemplate = getInvocationNodeInputTemplate(node.data, template, input.name);if (!fieldTemplate) {const message = t('nodes.missingFieldTemplate');@@ -275,14 +282,14 @@ export const validateWorkflow = async (args: ValidateWorkflowArgs): Promise<Valifor (const { nodeId, fieldName } of reverseExposedFields) {const node = nodes.find(({ id }) => id === nodeId);- if (!node) {+ if (!node || !isWorkflowInvocationNode(node)) {continue;}const nodeTemplate = templates[node.data.type];if (!nodeTemplate) {continue;}- const fieldTemplate = nodeTemplate.inputs[fieldName];+ const fieldTemplate = getInvocationNodeInputTemplate(node.data, nodeTemplate, fieldName);if (!fieldTemplate) {continue;}diff --git a/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemComponent.tsx b/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemComponent.tsxindex e1c5f4ec97..8add8c0014 100644--- a/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemComponent.tsx+++ b/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemComponent.tsx@@ -15,6 +15,7 @@ import { PiArrowCounterClockwiseBold, PiXBold } from 'react-icons/pi';import type { S } from 'services/api/types';import { COLUMN_WIDTHS, SYSTEM_USER_ID } from './constants';+import { getQueueItemActionVisibility } from './getQueueItemActionVisibility';import QueueItemDetail from './QueueItemDetail';const selectedStyles = { bg: 'base.700' };@@ -97,6 +98,7 @@ const QueueItemComponent = ({ index, item }: InnerItemProps) => {const isCanceled = useMemo(() => ['canceled', 'completed', 'failed'].includes(item.status), [item.status]);const isFailed = useMemo(() => ['canceled', 'failed'].includes(item.status), [item.status]);+ const { canShowCancelQueueItem, canShowRetryQueueItem } = useMemo(() => getQueueItemActionVisibility(item), [item]);const originText = useOriginText(item.origin);const destinationText = useDestinationText(item.destination);@@ -183,7 +185,7 @@ const QueueItemComponent = ({ index, item }: InnerItemProps) => {<Flex alignItems="center" w={COLUMN_WIDTHS.actions} pe={3}><ButtonGroup size="xs" variant="ghost">- {!isFailed && (+ {canShowCancelQueueItem && !isFailed && (<IconButtononClick={onClickCancelQueueItem}isDisabled={isCanceled || !canManageItem}@@ -192,7 +194,7 @@ const QueueItemComponent = ({ index, item }: InnerItemProps) => {icon={<PiXBold />}/>)}- {isFailed && (+ {canShowRetryQueueItem && isFailed && (<IconButtononClick={onClickRetryQueueItem}isDisabled={!canManageItem}diff --git a/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemDetail.tsx b/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemDetail.tsxindex ccba0f56b1..02c25761c5 100644--- a/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemDetail.tsx+++ b/invokeai/frontend/web/src/features/queue/components/QueueList/QueueItemDetail.tsx@@ -15,6 +15,8 @@ import { PiArrowCounterClockwiseBold, PiXBold } from 'react-icons/pi';import { useGetQueueItemQuery } from 'services/api/endpoints/queue';import type { S } from 'services/api/types';+import { getQueueItemActionVisibility } from './getQueueItemActionVisibility';+type Props = {queueItem: S['SessionQueueItem'];};@@ -51,6 +53,10 @@ const QueueItemComponent = ({ queueItem: queueItemDTO }: Props) => {);const isFailed = useMemo(() => !!queueItem && ['canceled', 'failed'].includes(queueItem.status), [queueItem]);+ const { canShowCancelQueueItem, canShowRetryQueueItem } = useMemo(+ () => getQueueItemActionVisibility(queueItemDTO),+ [queueItemDTO]+ );const onCancelBatch = useCallback(() => {cancelBatch.trigger(batch_id);@@ -82,7 +88,7 @@ const QueueItemComponent = ({ queueItem: queueItemDTO }: Props) => {<QueueItemData label={t('queue.batch')} data={batch_id} /><QueueItemData label={t('queue.session')} data={session_id} /><ButtonGroup size="xs" orientation="vertical">- {!isFailed && (+ {canShowCancelQueueItem && !isFailed && (<ButtononClick={onCancelQueueItem}isLoading={cancelQueueItem.isLoading}@@ -94,7 +100,7 @@ const QueueItemComponent = ({ queueItem: queueItemDTO }: Props) => {{t('queue.cancelItem')}</Button>)}- {isFailed && (+ {canShowRetryQueueItem && isFailed && (<ButtononClick={onRetryQueueItem}isLoading={retryQueueItem.isLoading}diff --git a/invokeai/frontend/web/src/features/queue/components/QueueList/getQueueItemActionVisibility.test.ts b/invokeai/frontend/web/src/features/queue/components/QueueList/getQueueItemActionVisibility.test.tsnew file mode 100644index 0000000000..7559af2c0c--- /dev/null+++ b/invokeai/frontend/web/src/features/queue/components/QueueList/getQueueItemActionVisibility.test.ts@@ -0,0 +1,64 @@+import type { S } from 'services/api/types';+import { describe, expect, it } from 'vitest';++import { getQueueItemActionVisibility } from './getQueueItemActionVisibility';++const buildQueueItem = (overrides: Partial<S['SessionQueueItem']> = {}): S['SessionQueueItem'] =>+ ({+ item_id: 1,+ status: 'pending',+ priority: 0,+ batch_id: 'batch-1',+ origin: null,+ destination: null,+ session_id: 'session-1',+ error_type: null,+ error_message: null,+ error_traceback: null,+ created_at: '2026-04-21T00:00:00Z',+ updated_at: '2026-04-21T00:00:00Z',+ started_at: null,+ completed_at: null,+ queue_id: 'default',+ user_id: 'user-1',+ user_display_name: null,+ user_email: null,+ field_values: null,+ retried_from_item_id: null,+ workflow_call_id: null,+ parent_item_id: null,+ parent_session_id: null,+ root_item_id: null,+ workflow_call_depth: null,+ session: {+ id: 'ges-1',+ graph: { id: 'graph-1', nodes: {}, edges: [] },+ execution_graph: { id: 'graph-2', nodes: {}, edges: [] },+ executed: [],+ executed_history: [],+ results: {},+ errors: {},+ workflow_call_stack: [],+ workflow_call_history: [],+ prepared_source_mapping: {},+ source_prepared_mapping: {},+ },+ workflow: null,+ ...overrides,+ }) as S['SessionQueueItem'];++describe('getQueueItemActionVisibility', () => {+ it('shows cancel and retry for root queue items', () => {+ const queueItem = buildQueueItem();++ expect(getQueueItemActionVisibility(queueItem).canShowCancelQueueItem).toBe(true);+ expect(getQueueItemActionVisibility(queueItem).canShowRetryQueueItem).toBe(true);+ });++ it('shows cancel and hides retry for child queue items', () => {+ const queueItem = buildQueueItem({ parent_item_id: 42, workflow_call_id: 'workflow-call-1' });++ expect(getQueueItemActionVisibility(queueItem).canShowCancelQueueItem).toBe(true);+ expect(getQueueItemActionVisibility(queueItem).canShowRetryQueueItem).toBe(false);+ });+});diff --git a/invokeai/frontend/web/src/features/queue/components/QueueList/getQueueItemActionVisibility.ts b/invokeai/frontend/web/src/features/queue/components/QueueList/getQueueItemActionVisibility.tsnew file mode 100644index 0000000000..b9576a2b6f--- /dev/null+++ b/invokeai/frontend/web/src/features/queue/components/QueueList/getQueueItemActionVisibility.ts@@ -0,0 +1,9 @@+import type { S } from 'services/api/types';++const isChildQueueItem = (item: S['SessionQueueItem']): boolean =>+ item.parent_item_id !== null && item.parent_item_id !== undefined;++export const getQueueItemActionVisibility = (item: S['SessionQueueItem']) => ({+ canShowCancelQueueItem: true,+ canShowRetryQueueItem: !isChildQueueItem(item),+});diff --git a/invokeai/frontend/web/src/features/queue/components/common/QueueStatusBadge.test.ts b/invokeai/frontend/web/src/features/queue/components/common/QueueStatusBadge.test.tsnew file mode 100644index 0000000000..7eb2e0fe08--- /dev/null+++ b/invokeai/frontend/web/src/features/queue/components/common/QueueStatusBadge.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';++import { getQueueStatusBadgeState } from './QueueStatusBadge';++describe('QueueStatusBadge', () => {+ it('maps waiting status to the waiting translation key and color', () => {+ expect(getQueueStatusBadgeState('waiting')).toEqual({+ colorScheme: 'purple',+ translationKey: 'queue.waiting',+ });+ });++ it('keeps existing retry-terminal statuses distinct', () => {+ expect(getQueueStatusBadgeState('failed')).toEqual({+ colorScheme: 'red',+ translationKey: 'queue.failed',+ });+ expect(getQueueStatusBadgeState('canceled')).toEqual({+ colorScheme: 'orange',+ translationKey: 'queue.canceled',+ });+ });+});diff --git a/invokeai/frontend/web/src/features/queue/components/common/QueueStatusBadge.tsx b/invokeai/frontend/web/src/features/queue/components/common/QueueStatusBadge.tsxindex 09924c6cfd..780844ee42 100644--- a/invokeai/frontend/web/src/features/queue/components/common/QueueStatusBadge.tsx+++ b/invokeai/frontend/web/src/features/queue/components/common/QueueStatusBadge.tsx@@ -3,16 +3,20 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';import type { SessionQueueItemStatus } from 'services/api/endpoints/queue';-const STATUSES = {+const QUEUE_STATUS_BADGE_STATES = {pending: { colorScheme: 'cyan', translationKey: 'queue.pending' },in_progress: { colorScheme: 'yellow', translationKey: 'queue.in_progress' },+ waiting: { colorScheme: 'purple', translationKey: 'queue.waiting' },completed: { colorScheme: 'green', translationKey: 'queue.completed' },failed: { colorScheme: 'red', translationKey: 'queue.failed' },canceled: { colorScheme: 'orange', translationKey: 'queue.canceled' },};+export const getQueueStatusBadgeState = (status: SessionQueueItemStatus) => QUEUE_STATUS_BADGE_STATES[status];+const StatusBadge = ({ status }: { status: SessionQueueItemStatus }) => {const { t } = useTranslation();- return <Badge colorScheme={STATUSES[status].colorScheme}>{t(STATUSES[status].translationKey)}</Badge>;+ const badgeState = getQueueStatusBadgeState(status);+ return <Badge colorScheme={badgeState.colorScheme}>{t(badgeState.translationKey)}</Badge>;};export default memo(StatusBadge);diff --git a/invokeai/frontend/web/src/features/workflowLibrary/util/workflowCallCompatibility.test.ts b/invokeai/frontend/web/src/features/workflowLibrary/util/workflowCallCompatibility.test.tsnew file mode 100644index 0000000000..9e3294af11--- /dev/null+++ b/invokeai/frontend/web/src/features/workflowLibrary/util/workflowCallCompatibility.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it } from 'vitest';++import { getWorkflowCallCompatibilityState } from './workflowCallCompatibility';++describe('workflowCallCompatibility', () => {+ it('treats missing compatibility metadata as supported', () => {+ expect(+ getWorkflowCallCompatibilityState({+ call_saved_workflow_compatibility: null,+ })+ ).toEqual({+ isUnsupported: false,+ messageKey: null,+ });+ });++ it('treats callable workflows as supported', () => {+ expect(+ getWorkflowCallCompatibilityState({+ call_saved_workflow_compatibility: {+ is_callable: true,+ reason: 'ok',+ message: null,+ },+ })+ ).toEqual({+ isUnsupported: false,+ messageKey: null,+ });+ });++ it('maps structured compatibility reasons to localized message keys', () => {+ expect(+ getWorkflowCallCompatibilityState({+ call_saved_workflow_compatibility: {+ is_callable: false,+ reason: 'missing_workflow_return',+ message: 'The workflow must contain exactly one workflow_return node.',+ },+ })+ ).toEqual({+ isUnsupported: true,+ messageKey: 'workflows.savedWorkflowCompatibility.missingWorkflowReturn',+ });+ });++ it('uses a localized fallback for unknown compatibility reasons', () => {+ expect(+ getWorkflowCallCompatibilityState({+ call_saved_workflow_compatibility: {+ is_callable: false,+ reason: 'unknown',+ message: 'Backend-only diagnostic text',+ },+ })+ ).toEqual({+ isUnsupported: true,+ messageKey: 'workflows.savedWorkflowCompatibility.unknown',+ });+ });++ it('maps queue capacity failures to a localized message key', () => {+ expect(+ getWorkflowCallCompatibilityState({+ call_saved_workflow_compatibility: {+ is_callable: false,+ reason: 'exceeds_capacity',+ message: 'call_saved_workflow exceeds remaining queue capacity for child workflow executions',+ },+ })+ ).toEqual({+ isUnsupported: true,+ messageKey: 'workflows.savedWorkflowCompatibility.exceedsCapacity',+ });+ });+});diff --git a/invokeai/frontend/web/src/features/workflowLibrary/util/workflowCallCompatibility.ts b/invokeai/frontend/web/src/features/workflowLibrary/util/workflowCallCompatibility.tsnew file mode 100644index 0000000000..69bed5edc8--- /dev/null+++ b/invokeai/frontend/web/src/features/workflowLibrary/util/workflowCallCompatibility.ts@@ -0,0 +1,43 @@+import type { S, WorkflowRecordListItemWithThumbnailDTO } from 'services/api/types';++const compatibilityMessageKeys = {+ ok: 'workflows.savedWorkflowCompatibility.unknown',+ missing_workflow_return: 'workflows.savedWorkflowCompatibility.missingWorkflowReturn',+ multiple_workflow_return: 'workflows.savedWorkflowCompatibility.multipleWorkflowReturn',+ unsupported_node: 'workflows.savedWorkflowCompatibility.unsupportedNode',+ unsupported_batch_input: 'workflows.savedWorkflowCompatibility.unsupportedBatchInput',+ invalid_graph: 'workflows.savedWorkflowCompatibility.invalidGraph',+ invalid_inputs: 'workflows.savedWorkflowCompatibility.invalidInputs',+ exceeds_capacity: 'workflows.savedWorkflowCompatibility.exceedsCapacity',+ unknown: 'workflows.savedWorkflowCompatibility.unknown',+} as const satisfies Record<S['WorkflowCallCompatibilityReason'], string>;++export type WorkflowCallCompatibilityMessageKey =+ (typeof compatibilityMessageKeys)[keyof typeof compatibilityMessageKeys];++type WorkflowCallCompatibilityState =+ | {+ isUnsupported: false;+ messageKey: null;+ }+ | {+ isUnsupported: true;+ messageKey: WorkflowCallCompatibilityMessageKey;+ };++export const getWorkflowCallCompatibilityState = (+ workflow: Pick<WorkflowRecordListItemWithThumbnailDTO, 'call_saved_workflow_compatibility'>+): WorkflowCallCompatibilityState => {+ const compatibility = workflow.call_saved_workflow_compatibility;+ if (!compatibility || compatibility.is_callable) {+ return {+ isUnsupported: false,+ messageKey: null,+ };+ }++ return {+ isUnsupported: true,+ messageKey: compatibilityMessageKeys[compatibility.reason],+ };+};diff --git a/invokeai/frontend/web/src/features/workflowLibrary/util/workflowLibraryListItemState.test.ts b/invokeai/frontend/web/src/features/workflowLibrary/util/workflowLibraryListItemState.test.tsnew file mode 100644index 0000000000..9f7e680b04--- /dev/null+++ b/invokeai/frontend/web/src/features/workflowLibrary/util/workflowLibraryListItemState.test.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from 'vitest';++import { getWorkflowLibraryListItemState } from './workflowLibraryListItemState';++describe('workflowLibraryListItemState', () => {+ it('marks unsupported workflows with their localized reason key', () => {+ expect(+ getWorkflowLibraryListItemState({+ category: 'user',+ is_public: false,+ call_saved_workflow_compatibility: {+ is_callable: false,+ reason: 'missing_workflow_return',+ message: 'The workflow must contain exactly one workflow_return node.',+ },+ })+ ).toEqual({+ showUnsupportedBadge: true,+ unsupportedMessageKey: 'workflows.savedWorkflowCompatibility.missingWorkflowReturn',+ showSharedBadge: false,+ showDefaultIcon: false,+ });+ });++ it('marks shared non-default workflows and leaves callable workflows supported', () => {+ expect(+ getWorkflowLibraryListItemState({+ category: 'user',+ is_public: true,+ call_saved_workflow_compatibility: {+ is_callable: true,+ reason: 'ok',+ message: null,+ },+ })+ ).toEqual({+ showUnsupportedBadge: false,+ unsupportedMessageKey: null,+ showSharedBadge: true,+ showDefaultIcon: false,+ });+ });++ it('marks default workflows with the default icon instead of the shared badge', () => {+ expect(+ getWorkflowLibraryListItemState({+ category: 'default',+ is_public: true,+ call_saved_workflow_compatibility: {+ is_callable: true,+ reason: 'ok',+ message: null,+ },+ })+ ).toEqual({+ showUnsupportedBadge: false,+ unsupportedMessageKey: null,+ showSharedBadge: false,+ showDefaultIcon: true,+ });+ });+});diff --git a/invokeai/frontend/web/src/features/workflowLibrary/util/workflowLibraryListItemState.ts b/invokeai/frontend/web/src/features/workflowLibrary/util/workflowLibraryListItemState.tsnew file mode 100644index 0000000000..13fcf42946--- /dev/null+++ b/invokeai/frontend/web/src/features/workflowLibrary/util/workflowLibraryListItemState.ts@@ -0,0 +1,25 @@+import {+ getWorkflowCallCompatibilityState,+ type WorkflowCallCompatibilityMessageKey,+} from 'features/workflowLibrary/util/workflowCallCompatibility';+import type { WorkflowRecordListItemWithThumbnailDTO } from 'services/api/types';++type WorkflowLibraryListItemState = {+ showUnsupportedBadge: boolean;+ unsupportedMessageKey: WorkflowCallCompatibilityMessageKey | null;+ showSharedBadge: boolean;+ showDefaultIcon: boolean;+};++export const getWorkflowLibraryListItemState = (+ workflow: Pick<WorkflowRecordListItemWithThumbnailDTO, 'category' | 'is_public' | 'call_saved_workflow_compatibility'>+): WorkflowLibraryListItemState => {+ const compatibilityState = getWorkflowCallCompatibilityState(workflow);++ return {+ showUnsupportedBadge: compatibilityState.isUnsupported,+ unsupportedMessageKey: compatibilityState.messageKey,+ showSharedBadge: workflow.is_public && workflow.category !== 'default',+ showDefaultIcon: workflow.category === 'default',+ };+};diff --git a/invokeai/frontend/web/src/services/api/endpoints/queue.ts b/invokeai/frontend/web/src/services/api/endpoints/queue.tsindex e2788406c1..70f4e6a65c 100644--- a/invokeai/frontend/web/src/services/api/endpoints/queue.ts+++ b/invokeai/frontend/web/src/services/api/endpoints/queue.ts@@ -6,6 +6,7 @@ import type {GetQueueItemIdsArgs,GetQueueItemIdsResult,} from 'services/api/types';+import { getQueueStatusWithObservedEvents } from 'services/events/queueStatusEvents';import stableHash from 'stable-hash';import type { Param0 } from 'tsafe';@@ -152,6 +153,9 @@ export const queueApi = api.injectEndpoints({url: buildQueueUrl('status'),method: 'GET',}),+ transformResponse: (+ response: paths['/api/v1/queue/{queue_id}/status']['get']['responses']['200']['content']['application/json']+ ) => getQueueStatusWithObservedEvents(response),providesTags: ['SessionQueueStatus', 'FetchOnReconnect'],}),getBatchStatus: build.query<diff --git a/invokeai/frontend/web/src/services/api/run-graph.ts b/invokeai/frontend/web/src/services/api/run-graph.tsindex 8b154673a7..b4a7e236d1 100644--- a/invokeai/frontend/web/src/services/api/run-graph.ts+++ b/invokeai/frontend/web/src/services/api/run-graph.ts@@ -319,8 +319,8 @@ const _runGraph = async (return;}- // Ignore events where the status is pending or in progress - no need to do anything for these- if (event.status === 'pending' || event.status === 'in_progress') {+ // Ignore events where the status is still nonterminal - no need to do anything for these+ if (event.status === 'pending' || event.status === 'in_progress' || event.status === 'waiting') {return;}@@ -329,8 +329,8 @@ const _runGraph = async (const queueItem = await dependencies.executor.getQueueItem(event.item_id);const { status, session, error_type, error_message, error_traceback } = queueItem;- // We are confident that the queue item is not pending or in progress, at this time.- if (status === 'pending' || status === 'in_progress') {+ // We are confident that the queue item is not in a nonterminal status, at this time.+ if (status === 'pending' || status === 'in_progress' || status === 'waiting') {throw new UnexpectedStatusError(event.item_id, session, status);}diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 375b4957e6..61db935fa9 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -3819,7 +3819,7 @@ export type components = {* Items* @description The list of items to substitute into the node/field.*/- items?: (string | number | components["schemas"]["ImageField"])[];+ items?: (string | number | components["schemas"]["ImageField"] | (string | number | components["schemas"]["ImageField"])[])[];};/*** BatchEnqueuedEvent@@ -3901,6 +3901,11 @@ export type components = {* @description Number of queue items with status 'in_progress'*/in_progress: number;+ /**+ * Waiting+ * @description Number of queue items with status 'waiting'+ */+ waiting: number;/*** Completed* @description Number of queue items with status 'complete'@@ -5431,6 +5436,49 @@ export type components = {*/type: "calculate_image_tiles_output";};+ /**+ * Call Saved Workflow+ * @description Displays and later executes against a selected saved workflow.+ */+ CallSavedWorkflowInvocation: {+ /**+ * Id+ * @description The id of this instance of an invocation. Must be unique among all instances of invocations.+ */+ id: string;+ /**+ * Is Intermediate+ * @description Whether or not this is an intermediate invocation.+ * @default false+ */+ is_intermediate?: boolean;+ /**+ * Use Cache+ * @description Whether or not to use the cache+ * @default false+ */+ use_cache?: boolean;+ /**+ * Workflow Id+ * @description The selected saved workflow ID, managed by the workflow editor UI.+ * @default+ */+ workflow_id?: string;+ /**+ * Workflow Inputs+ * @description Literal values for the selected workflow's exposed inputs, managed by the workflow editor UI.+ * @default {}+ */+ workflow_inputs?: {+ [key: string]: unknown;+ };+ /**+ * type+ * @default call_saved_workflow+ * @constant+ */+ type: "call_saved_workflow";+ };/*** CancelAllExceptCurrentResult* @description Result of canceling all except current@@ -12336,7 +12384,7 @@ export type components = {* @description The nodes in this graph*/nodes?: {- [key: string]: components["schemas"]["AddInvocation"] | components["schemas"]["AlibabaCloudImageGenerationInvocation"] | components["schemas"]["AlphaMaskToTensorInvocation"] | components["schemas"]["AnimaDenoiseInvocation"] | components["schemas"]["AnimaImageToLatentsInvocation"] | components["schemas"]["AnimaLatentsToImageInvocation"] | components["schemas"]["AnimaLoRACollectionLoader"] | components["schemas"]["AnimaLoRALoaderInvocation"] | components["schemas"]["AnimaModelLoaderInvocation"] | components["schemas"]["AnimaTextEncoderInvocation"] | components["schemas"]["ApplyMaskTensorToImageInvocation"] | components["schemas"]["ApplyMaskToImageInvocation"] | components["schemas"]["BlankImageInvocation"] | components["schemas"]["BlendLatentsInvocation"] | components["schemas"]["BooleanCollectionInvocation"] | components["schemas"]["BooleanInvocation"] | components["schemas"]["BoundingBoxInvocation"] | components["schemas"]["CLIPSkipInvocation"] | components["schemas"]["CV2InfillInvocation"] | components["schemas"]["CalculateImageTilesEvenSplitInvocation"] | components["schemas"]["CalculateImageTilesInvocation"] | components["schemas"]["CalculateImageTilesMinimumOverlapInvocation"] | components["schemas"]["CannyEdgeDetectionInvocation"] | components["schemas"]["CanvasOutputInvocation"] | components["schemas"]["CanvasPasteBackInvocation"] | components["schemas"]["CanvasV2MaskAndCropInvocation"] | components["schemas"]["CenterPadCropInvocation"] | components["schemas"]["CogView4DenoiseInvocation"] | components["schemas"]["CogView4ImageToLatentsInvocation"] | components["schemas"]["CogView4LatentsToImageInvocation"] | components["schemas"]["CogView4ModelLoaderInvocation"] | components["schemas"]["CogView4TextEncoderInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["ColorCorrectInvocation"] | components["schemas"]["ColorInvocation"] | components["schemas"]["ColorMapInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["ConditioningCollectionInvocation"] | components["schemas"]["ConditioningInvocation"] | components["schemas"]["ContentShuffleInvocation"] | components["schemas"]["ControlNetInvocation"] | components["schemas"]["CoreMetadataInvocation"] | components["schemas"]["CreateDenoiseMaskInvocation"] | components["schemas"]["CreateGradientMaskInvocation"] | components["schemas"]["CropImageToBoundingBoxInvocation"] | components["schemas"]["CropLatentsCoreInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["DWOpenposeDetectionInvocation"] | components["schemas"]["DecodeInvisibleWatermarkInvocation"] | components["schemas"]["DenoiseLatentsInvocation"] | components["schemas"]["DenoiseLatentsMetaInvocation"] | components["schemas"]["DepthAnythingDepthEstimationInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["ExpandMaskWithFadeInvocation"] | components["schemas"]["FLUXLoRACollectionLoader"] | components["schemas"]["FaceIdentifierInvocation"] | components["schemas"]["FaceMaskInvocation"] | components["schemas"]["FaceOffInvocation"] | components["schemas"]["FloatBatchInvocation"] | components["schemas"]["FloatCollectionInvocation"] | components["schemas"]["FloatGenerator"] | components["schemas"]["FloatInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["FloatMathInvocation"] | components["schemas"]["FloatToIntegerInvocation"] | components["schemas"]["Flux2DenoiseInvocation"] | components["schemas"]["Flux2KleinLoRACollectionLoader"] | components["schemas"]["Flux2KleinLoRALoaderInvocation"] | components["schemas"]["Flux2KleinModelLoaderInvocation"] | components["schemas"]["Flux2KleinTextEncoderInvocation"] | components["schemas"]["Flux2VaeDecodeInvocation"] | components["schemas"]["Flux2VaeEncodeInvocation"] | components["schemas"]["FluxControlLoRALoaderInvocation"] | components["schemas"]["FluxControlNetInvocation"] | components["schemas"]["FluxDenoiseInvocation"] | components["schemas"]["FluxDenoiseLatentsMetaInvocation"] | components["schemas"]["FluxFillInvocation"] | components["schemas"]["FluxIPAdapterInvocation"] | components["schemas"]["FluxKontextConcatenateImagesInvocation"] | components["schemas"]["FluxKontextInvocation"] | components["schemas"]["FluxLoRALoaderInvocation"] | components["schemas"]["FluxModelLoaderInvocation"] | components["schemas"]["FluxReduxInvocation"] | components["schemas"]["FluxTextEncoderInvocation"] | components["schemas"]["FluxVaeDecodeInvocation"] | components["schemas"]["FluxVaeEncodeInvocation"] | components["schemas"]["FreeUInvocation"] | components["schemas"]["GeminiImageGenerationInvocation"] | components["schemas"]["GetMaskBoundingBoxInvocation"] | components["schemas"]["GroundingDinoInvocation"] | components["schemas"]["HEDEdgeDetectionInvocation"] | components["schemas"]["HeuristicResizeInvocation"] | components["schemas"]["IPAdapterInvocation"] | components["schemas"]["IdealSizeInvocation"] | components["schemas"]["IfInvocation"] | components["schemas"]["ImageBatchInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageChannelMultiplyInvocation"] | components["schemas"]["ImageChannelOffsetInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImageGenerator"] | components["schemas"]["ImageHueAdjustmentInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageMaskToTensorInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageNoiseInvocation"] | components["schemas"]["ImagePanelLayoutInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["IntegerBatchInvocation"] | components["schemas"]["IntegerCollectionInvocation"] | components["schemas"]["IntegerGenerator"] | components["schemas"]["IntegerInvocation"] | components["schemas"]["IntegerMathInvocation"] | components["schemas"]["InvertTensorMaskInvocation"] | components["schemas"]["InvokeAdjustImageHuePlusInvocation"] | components["schemas"]["InvokeEquivalentAchromaticLightnessInvocation"] | components["schemas"]["InvokeImageBlendInvocation"] | components["schemas"]["InvokeImageCompositorInvocation"] | components["schemas"]["InvokeImageDilateOrErodeInvocation"] | components["schemas"]["InvokeImageEnhanceInvocation"] | components["schemas"]["InvokeImageValueThresholdsInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["LaMaInfillInvocation"] | components["schemas"]["LatentsCollectionInvocation"] | components["schemas"]["LatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["LineartAnimeEdgeDetectionInvocation"] | components["schemas"]["LineartEdgeDetectionInvocation"] | components["schemas"]["LlavaOnevisionVllmInvocation"] | components["schemas"]["LoRACollectionLoader"] | components["schemas"]["LoRALoaderInvocation"] | components["schemas"]["LoRASelectorInvocation"] | components["schemas"]["MLSDDetectionInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["MaskCombineInvocation"] | components["schemas"]["MaskEdgeInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["MaskFromIDInvocation"] | components["schemas"]["MaskTensorToImageInvocation"] | components["schemas"]["MediaPipeFaceDetectionInvocation"] | components["schemas"]["MergeMetadataInvocation"] | components["schemas"]["MergeTilesToImageInvocation"] | components["schemas"]["MetadataFieldExtractorInvocation"] | components["schemas"]["MetadataFromImageInvocation"] | components["schemas"]["MetadataInvocation"] | components["schemas"]["MetadataItemInvocation"] | components["schemas"]["MetadataItemLinkedInvocation"] | components["schemas"]["MetadataToBoolCollectionInvocation"] | components["schemas"]["MetadataToBoolInvocation"] | components["schemas"]["MetadataToControlnetsInvocation"] | components["schemas"]["MetadataToFloatCollectionInvocation"] | components["schemas"]["MetadataToFloatInvocation"] | components["schemas"]["MetadataToIPAdaptersInvocation"] | components["schemas"]["MetadataToIntegerCollectionInvocation"] | components["schemas"]["MetadataToIntegerInvocation"] | components["schemas"]["MetadataToLorasCollectionInvocation"] | components["schemas"]["MetadataToLorasInvocation"] | components["schemas"]["MetadataToModelInvocation"] | components["schemas"]["MetadataToSDXLLorasInvocation"] | components["schemas"]["MetadataToSDXLModelInvocation"] | components["schemas"]["MetadataToSchedulerInvocation"] | components["schemas"]["MetadataToStringCollectionInvocation"] | components["schemas"]["MetadataToStringInvocation"] | components["schemas"]["MetadataToT2IAdaptersInvocation"] | components["schemas"]["MetadataToVAEInvocation"] | components["schemas"]["ModelIdentifierInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["NormalMapInvocation"] | components["schemas"]["OklabUnsharpMaskInvocation"] | components["schemas"]["OklchImageHueAdjustmentInvocation"] | components["schemas"]["OpenAIImageGenerationInvocation"] | components["schemas"]["PBRMapsInvocation"] | components["schemas"]["PairTileImageInvocation"] | components["schemas"]["PasteImageIntoBoundingBoxInvocation"] | components["schemas"]["PiDiNetEdgeDetectionInvocation"] | components["schemas"]["PromptTemplateInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["QwenImageDenoiseInvocation"] | components["schemas"]["QwenImageImageToLatentsInvocation"] | components["schemas"]["QwenImageLatentsToImageInvocation"] | components["schemas"]["QwenImageLoRACollectionLoader"] | components["schemas"]["QwenImageLoRALoaderInvocation"] | components["schemas"]["QwenImageModelLoaderInvocation"] | components["schemas"]["QwenImageTextEncoderInvocation"] | components["schemas"]["RandomFloatInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RectangleMaskInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["RoundInvocation"] | components["schemas"]["SD3DenoiseInvocation"] | components["schemas"]["SD3ImageToLatentsInvocation"] | components["schemas"]["SD3LatentsToImageInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLLoRACollectionLoader"] | components["schemas"]["SDXLLoRALoaderInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SaveImageInvocation"] | components["schemas"]["SaveImageToFileInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["SchedulerInvocation"] | components["schemas"]["Sd3ModelLoaderInvocation"] | components["schemas"]["Sd3TextEncoderInvocation"] | components["schemas"]["SeamlessModeInvocation"] | components["schemas"]["SeedreamImageGenerationInvocation"] | components["schemas"]["SegmentAnythingInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["SpandrelImageToImageAutoscaleInvocation"] | components["schemas"]["SpandrelImageToImageInvocation"] | components["schemas"]["StringBatchInvocation"] | components["schemas"]["StringCollectionInvocation"] | components["schemas"]["StringGenerator"] | components["schemas"]["StringInvocation"] | components["schemas"]["StringJoinInvocation"] | components["schemas"]["StringJoinThreeInvocation"] | components["schemas"]["StringReplaceInvocation"] | components["schemas"]["StringSplitInvocation"] | components["schemas"]["StringSplitNegInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["T2IAdapterInvocation"] | components["schemas"]["TextLLMInvocation"] | components["schemas"]["TileToPropertiesInvocation"] | components["schemas"]["TiledMultiDiffusionDenoiseLatents"] | components["schemas"]["UnsharpMaskInvocation"] | components["schemas"]["VAELoaderInvocation"] | components["schemas"]["ZImageControlInvocation"] | components["schemas"]["ZImageDenoiseInvocation"] | components["schemas"]["ZImageDenoiseMetaInvocation"] | components["schemas"]["ZImageImageToLatentsInvocation"] | components["schemas"]["ZImageLatentsToImageInvocation"] | components["schemas"]["ZImageLoRACollectionLoader"] | components["schemas"]["ZImageLoRALoaderInvocation"] | components["schemas"]["ZImageModelLoaderInvocation"] | components["schemas"]["ZImageSeedVarianceEnhancerInvocation"] | components["schemas"]["ZImageTextEncoderInvocation"];+ [key: string]: components["schemas"]["AddInvocation"] | components["schemas"]["AlibabaCloudImageGenerationInvocation"] | components["schemas"]["AlphaMaskToTensorInvocation"] | components["schemas"]["AnimaDenoiseInvocation"] | components["schemas"]["AnimaImageToLatentsInvocation"] | components["schemas"]["AnimaLatentsToImageInvocation"] | components["schemas"]["AnimaLoRACollectionLoader"] | components["schemas"]["AnimaLoRALoaderInvocation"] | components["schemas"]["AnimaModelLoaderInvocation"] | components["schemas"]["AnimaTextEncoderInvocation"] | components["schemas"]["ApplyMaskTensorToImageInvocation"] | components["schemas"]["ApplyMaskToImageInvocation"] | components["schemas"]["BlankImageInvocation"] | components["schemas"]["BlendLatentsInvocation"] | components["schemas"]["BooleanCollectionInvocation"] | components["schemas"]["BooleanInvocation"] | components["schemas"]["BoundingBoxInvocation"] | components["schemas"]["CLIPSkipInvocation"] | components["schemas"]["CV2InfillInvocation"] | components["schemas"]["CalculateImageTilesEvenSplitInvocation"] | components["schemas"]["CalculateImageTilesInvocation"] | components["schemas"]["CalculateImageTilesMinimumOverlapInvocation"] | components["schemas"]["CallSavedWorkflowInvocation"] | components["schemas"]["CannyEdgeDetectionInvocation"] | components["schemas"]["CanvasOutputInvocation"] | components["schemas"]["CanvasPasteBackInvocation"] | components["schemas"]["CanvasV2MaskAndCropInvocation"] | components["schemas"]["CenterPadCropInvocation"] | components["schemas"]["CogView4DenoiseInvocation"] | components["schemas"]["CogView4ImageToLatentsInvocation"] | components["schemas"]["CogView4LatentsToImageInvocation"] | components["schemas"]["CogView4ModelLoaderInvocation"] | components["schemas"]["CogView4TextEncoderInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["ColorCorrectInvocation"] | components["schemas"]["ColorInvocation"] | components["schemas"]["ColorMapInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["ConditioningCollectionInvocation"] | components["schemas"]["ConditioningInvocation"] | components["schemas"]["ContentShuffleInvocation"] | components["schemas"]["ControlNetInvocation"] | components["schemas"]["CoreMetadataInvocation"] | components["schemas"]["CreateDenoiseMaskInvocation"] | components["schemas"]["CreateGradientMaskInvocation"] | components["schemas"]["CropImageToBoundingBoxInvocation"] | components["schemas"]["CropLatentsCoreInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["DWOpenposeDetectionInvocation"] | components["schemas"]["DecodeInvisibleWatermarkInvocation"] | components["schemas"]["DenoiseLatentsInvocation"] | components["schemas"]["DenoiseLatentsMetaInvocation"] | components["schemas"]["DepthAnythingDepthEstimationInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["ExpandMaskWithFadeInvocation"] | components["schemas"]["FLUXLoRACollectionLoader"] | components["schemas"]["FaceIdentifierInvocation"] | components["schemas"]["FaceMaskInvocation"] | components["schemas"]["FaceOffInvocation"] | components["schemas"]["FloatBatchInvocation"] | components["schemas"]["FloatCollectionInvocation"] | components["schemas"]["FloatGenerator"] | components["schemas"]["FloatInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["FloatMathInvocation"] | components["schemas"]["FloatToIntegerInvocation"] | components["schemas"]["Flux2DenoiseInvocation"] | components["schemas"]["Flux2KleinLoRACollectionLoader"] | components["schemas"]["Flux2KleinLoRALoaderInvocation"] | components["schemas"]["Flux2KleinModelLoaderInvocation"] | components["schemas"]["Flux2KleinTextEncoderInvocation"] | components["schemas"]["Flux2VaeDecodeInvocation"] | components["schemas"]["Flux2VaeEncodeInvocation"] | components["schemas"]["FluxControlLoRALoaderInvocation"] | components["schemas"]["FluxControlNetInvocation"] | components["schemas"]["FluxDenoiseInvocation"] | components["schemas"]["FluxDenoiseLatentsMetaInvocation"] | components["schemas"]["FluxFillInvocation"] | components["schemas"]["FluxIPAdapterInvocation"] | components["schemas"]["FluxKontextConcatenateImagesInvocation"] | components["schemas"]["FluxKontextInvocation"] | components["schemas"]["FluxLoRALoaderInvocation"] | components["schemas"]["FluxModelLoaderInvocation"] | components["schemas"]["FluxReduxInvocation"] | components["schemas"]["FluxTextEncoderInvocation"] | components["schemas"]["FluxVaeDecodeInvocation"] | components["schemas"]["FluxVaeEncodeInvocation"] | components["schemas"]["FreeUInvocation"] | components["schemas"]["GeminiImageGenerationInvocation"] | components["schemas"]["GetMaskBoundingBoxInvocation"] | components["schemas"]["GroundingDinoInvocation"] | components["schemas"]["HEDEdgeDetectionInvocation"] | components["schemas"]["HeuristicResizeInvocation"] | components["schemas"]["IPAdapterInvocation"] | components["schemas"]["IdealSizeInvocation"] | components["schemas"]["IfInvocation"] | components["schemas"]["ImageBatchInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageChannelMultiplyInvocation"] | components["schemas"]["ImageChannelOffsetInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImageGenerator"] | components["schemas"]["ImageHueAdjustmentInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageMaskToTensorInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageNoiseInvocation"] | components["schemas"]["ImagePanelLayoutInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["IntegerBatchInvocation"] | components["schemas"]["IntegerCollectionInvocation"] | components["schemas"]["IntegerGenerator"] | components["schemas"]["IntegerInvocation"] | components["schemas"]["IntegerMathInvocation"] | components["schemas"]["InvertTensorMaskInvocation"] | components["schemas"]["InvokeAdjustImageHuePlusInvocation"] | components["schemas"]["InvokeEquivalentAchromaticLightnessInvocation"] | components["schemas"]["InvokeImageBlendInvocation"] | components["schemas"]["InvokeImageCompositorInvocation"] | components["schemas"]["InvokeImageDilateOrErodeInvocation"] | components["schemas"]["InvokeImageEnhanceInvocation"] | components["schemas"]["InvokeImageValueThresholdsInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["LaMaInfillInvocation"] | components["schemas"]["LatentsCollectionInvocation"] | components["schemas"]["LatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["LineartAnimeEdgeDetectionInvocation"] | components["schemas"]["LineartEdgeDetectionInvocation"] | components["schemas"]["LlavaOnevisionVllmInvocation"] | components["schemas"]["LoRACollectionLoader"] | components["schemas"]["LoRALoaderInvocation"] | components["schemas"]["LoRASelectorInvocation"] | components["schemas"]["MLSDDetectionInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["MaskCombineInvocation"] | components["schemas"]["MaskEdgeInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["MaskFromIDInvocation"] | components["schemas"]["MaskTensorToImageInvocation"] | components["schemas"]["MediaPipeFaceDetectionInvocation"] | components["schemas"]["MergeMetadataInvocation"] | components["schemas"]["MergeTilesToImageInvocation"] | components["schemas"]["MetadataFieldExtractorInvocation"] | components["schemas"]["MetadataFromImageInvocation"] | components["schemas"]["MetadataInvocation"] | components["schemas"]["MetadataItemInvocation"] | components["schemas"]["MetadataItemLinkedInvocation"] | components["schemas"]["MetadataToBoolCollectionInvocation"] | components["schemas"]["MetadataToBoolInvocation"] | components["schemas"]["MetadataToControlnetsInvocation"] | components["schemas"]["MetadataToFloatCollectionInvocation"] | components["schemas"]["MetadataToFloatInvocation"] | components["schemas"]["MetadataToIPAdaptersInvocation"] | components["schemas"]["MetadataToIntegerCollectionInvocation"] | components["schemas"]["MetadataToIntegerInvocation"] | components["schemas"]["MetadataToLorasCollectionInvocation"] | components["schemas"]["MetadataToLorasInvocation"] | components["schemas"]["MetadataToModelInvocation"] | components["schemas"]["MetadataToSDXLLorasInvocation"] | components["schemas"]["MetadataToSDXLModelInvocation"] | components["schemas"]["MetadataToSchedulerInvocation"] | components["schemas"]["MetadataToStringCollectionInvocation"] | components["schemas"]["MetadataToStringInvocation"] | components["schemas"]["MetadataToT2IAdaptersInvocation"] | components["schemas"]["MetadataToVAEInvocation"] | components["schemas"]["ModelIdentifierInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["NormalMapInvocation"] | components["schemas"]["OklabUnsharpMaskInvocation"] | components["schemas"]["OklchImageHueAdjustmentInvocation"] | components["schemas"]["OpenAIImageGenerationInvocation"] | components["schemas"]["PBRMapsInvocation"] | components["schemas"]["PairTileImageInvocation"] | components["schemas"]["PasteImageIntoBoundingBoxInvocation"] | components["schemas"]["PiDiNetEdgeDetectionInvocation"] | components["schemas"]["PromptTemplateInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["QwenImageDenoiseInvocation"] | components["schemas"]["QwenImageImageToLatentsInvocation"] | components["schemas"]["QwenImageLatentsToImageInvocation"] | components["schemas"]["QwenImageLoRACollectionLoader"] | components["schemas"]["QwenImageLoRALoaderInvocation"] | components["schemas"]["QwenImageModelLoaderInvocation"] | components["schemas"]["QwenImageTextEncoderInvocation"] | components["schemas"]["RandomFloatInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RectangleMaskInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["RoundInvocation"] | components["schemas"]["SD3DenoiseInvocation"] | components["schemas"]["SD3ImageToLatentsInvocation"] | components["schemas"]["SD3LatentsToImageInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLLoRACollectionLoader"] | components["schemas"]["SDXLLoRALoaderInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SaveImageInvocation"] | components["schemas"]["SaveImageToFileInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["SchedulerInvocation"] | components["schemas"]["Sd3ModelLoaderInvocation"] | components["schemas"]["Sd3TextEncoderInvocation"] | components["schemas"]["SeamlessModeInvocation"] | components["schemas"]["SeedreamImageGenerationInvocation"] | components["schemas"]["SegmentAnythingInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["SpandrelImageToImageAutoscaleInvocation"] | components["schemas"]["SpandrelImageToImageInvocation"] | components["schemas"]["StringBatchInvocation"] | components["schemas"]["StringCollectionInvocation"] | components["schemas"]["StringGenerator"] | components["schemas"]["StringInvocation"] | components["schemas"]["StringJoinInvocation"] | components["schemas"]["StringJoinThreeInvocation"] | components["schemas"]["StringReplaceInvocation"] | components["schemas"]["StringSplitInvocation"] | components["schemas"]["StringSplitNegInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["T2IAdapterInvocation"] | components["schemas"]["TextLLMInvocation"] | components["schemas"]["TileToPropertiesInvocation"] | components["schemas"]["TiledMultiDiffusionDenoiseLatents"] | components["schemas"]["UnsharpMaskInvocation"] | components["schemas"]["VAELoaderInvocation"] | components["schemas"]["WorkflowReturnGetInvocation"] | components["schemas"]["WorkflowReturnInvocation"] | components["schemas"]["WorkflowReturnValueInvocation"] | components["schemas"]["ZImageControlInvocation"] | components["schemas"]["ZImageDenoiseInvocation"] | components["schemas"]["ZImageDenoiseMetaInvocation"] | components["schemas"]["ZImageImageToLatentsInvocation"] | components["schemas"]["ZImageLatentsToImageInvocation"] | components["schemas"]["ZImageLoRACollectionLoader"] | components["schemas"]["ZImageLoRALoaderInvocation"] | components["schemas"]["ZImageModelLoaderInvocation"] | components["schemas"]["ZImageSeedVarianceEnhancerInvocation"] | components["schemas"]["ZImageTextEncoderInvocation"];};/*** Edges@@ -12373,7 +12421,7 @@ export type components = {* @description The results of node executions*/results: {- [key: string]: components["schemas"]["AnimaConditioningOutput"] | components["schemas"]["AnimaLoRALoaderOutput"] | components["schemas"]["AnimaModelLoaderOutput"] | components["schemas"]["BooleanCollectionOutput"] | components["schemas"]["BooleanOutput"] | components["schemas"]["BoundingBoxCollectionOutput"] | components["schemas"]["BoundingBoxOutput"] | components["schemas"]["CLIPOutput"] | components["schemas"]["CLIPSkipInvocationOutput"] | components["schemas"]["CalculateImageTilesOutput"] | components["schemas"]["CogView4ConditioningOutput"] | components["schemas"]["CogView4ModelLoaderOutput"] | components["schemas"]["CollectInvocationOutput"] | components["schemas"]["ColorCollectionOutput"] | components["schemas"]["ColorOutput"] | components["schemas"]["ConditioningCollectionOutput"] | components["schemas"]["ConditioningOutput"] | components["schemas"]["ControlOutput"] | components["schemas"]["DenoiseMaskOutput"] | components["schemas"]["FaceMaskOutput"] | components["schemas"]["FaceOffOutput"] | components["schemas"]["FloatCollectionOutput"] | components["schemas"]["FloatGeneratorOutput"] | components["schemas"]["FloatOutput"] | components["schemas"]["Flux2KleinLoRALoaderOutput"] | components["schemas"]["Flux2KleinModelLoaderOutput"] | components["schemas"]["FluxConditioningCollectionOutput"] | components["schemas"]["FluxConditioningOutput"] | components["schemas"]["FluxControlLoRALoaderOutput"] | components["schemas"]["FluxControlNetOutput"] | components["schemas"]["FluxFillOutput"] | components["schemas"]["FluxKontextOutput"] | components["schemas"]["FluxLoRALoaderOutput"] | components["schemas"]["FluxModelLoaderOutput"] | components["schemas"]["FluxReduxOutput"] | components["schemas"]["GradientMaskOutput"] | components["schemas"]["IPAdapterOutput"] | components["schemas"]["IdealSizeOutput"] | components["schemas"]["IfInvocationOutput"] | components["schemas"]["ImageCollectionOutput"] | components["schemas"]["ImageGeneratorOutput"] | components["schemas"]["ImageOutput"] | components["schemas"]["ImagePanelCoordinateOutput"] | components["schemas"]["IntegerCollectionOutput"] | components["schemas"]["IntegerGeneratorOutput"] | components["schemas"]["IntegerOutput"] | components["schemas"]["IterateInvocationOutput"] | components["schemas"]["LatentsCollectionOutput"] | components["schemas"]["LatentsMetaOutput"] | components["schemas"]["LatentsOutput"] | components["schemas"]["LoRALoaderOutput"] | components["schemas"]["LoRASelectorOutput"] | components["schemas"]["MDControlListOutput"] | components["schemas"]["MDIPAdapterListOutput"] | components["schemas"]["MDT2IAdapterListOutput"] | components["schemas"]["MaskOutput"] | components["schemas"]["MetadataItemOutput"] | components["schemas"]["MetadataOutput"] | components["schemas"]["MetadataToLorasCollectionOutput"] | components["schemas"]["MetadataToModelOutput"] | components["schemas"]["MetadataToSDXLModelOutput"] | components["schemas"]["ModelIdentifierOutput"] | components["schemas"]["ModelLoaderOutput"] | components["schemas"]["NoiseOutput"] | components["schemas"]["PBRMapsOutput"] | components["schemas"]["PairTileImageOutput"] | components["schemas"]["PromptTemplateOutput"] | components["schemas"]["QwenImageConditioningOutput"] | components["schemas"]["QwenImageLoRALoaderOutput"] | components["schemas"]["QwenImageModelLoaderOutput"] | components["schemas"]["SD3ConditioningOutput"] | components["schemas"]["SDXLLoRALoaderOutput"] | components["schemas"]["SDXLModelLoaderOutput"] | components["schemas"]["SDXLRefinerModelLoaderOutput"] | components["schemas"]["SchedulerOutput"] | components["schemas"]["Sd3ModelLoaderOutput"] | components["schemas"]["SeamlessModeOutput"] | components["schemas"]["String2Output"] | components["schemas"]["StringCollectionOutput"] | components["schemas"]["StringGeneratorOutput"] | components["schemas"]["StringOutput"] | components["schemas"]["StringPosNegOutput"] | components["schemas"]["T2IAdapterOutput"] | components["schemas"]["TileToPropertiesOutput"] | components["schemas"]["UNetOutput"] | components["schemas"]["VAEOutput"] | components["schemas"]["ZImageConditioningOutput"] | components["schemas"]["ZImageControlOutput"] | components["schemas"]["ZImageLoRALoaderOutput"] | components["schemas"]["ZImageModelLoaderOutput"];+ [key: string]: components["schemas"]["AnimaConditioningOutput"] | components["schemas"]["AnimaLoRALoaderOutput"] | components["schemas"]["AnimaModelLoaderOutput"] | components["schemas"]["BooleanCollectionOutput"] | components["schemas"]["BooleanOutput"] | components["schemas"]["BoundingBoxCollectionOutput"] | components["schemas"]["BoundingBoxOutput"] | components["schemas"]["CLIPOutput"] | components["schemas"]["CLIPSkipInvocationOutput"] | components["schemas"]["CalculateImageTilesOutput"] | components["schemas"]["CogView4ConditioningOutput"] | components["schemas"]["CogView4ModelLoaderOutput"] | components["schemas"]["CollectInvocationOutput"] | components["schemas"]["ColorCollectionOutput"] | components["schemas"]["ColorOutput"] | components["schemas"]["ConditioningCollectionOutput"] | components["schemas"]["ConditioningOutput"] | components["schemas"]["ControlOutput"] | components["schemas"]["DenoiseMaskOutput"] | components["schemas"]["FaceMaskOutput"] | components["schemas"]["FaceOffOutput"] | components["schemas"]["FloatCollectionOutput"] | components["schemas"]["FloatGeneratorOutput"] | components["schemas"]["FloatOutput"] | components["schemas"]["Flux2KleinLoRALoaderOutput"] | components["schemas"]["Flux2KleinModelLoaderOutput"] | components["schemas"]["FluxConditioningCollectionOutput"] | components["schemas"]["FluxConditioningOutput"] | components["schemas"]["FluxControlLoRALoaderOutput"] | components["schemas"]["FluxControlNetOutput"] | components["schemas"]["FluxFillOutput"] | components["schemas"]["FluxKontextOutput"] | components["schemas"]["FluxLoRALoaderOutput"] | components["schemas"]["FluxModelLoaderOutput"] | components["schemas"]["FluxReduxOutput"] | components["schemas"]["GradientMaskOutput"] | components["schemas"]["IPAdapterOutput"] | components["schemas"]["IdealSizeOutput"] | components["schemas"]["IfInvocationOutput"] | components["schemas"]["ImageCollectionOutput"] | components["schemas"]["ImageGeneratorOutput"] | components["schemas"]["ImageOutput"] | components["schemas"]["ImagePanelCoordinateOutput"] | components["schemas"]["IntegerCollectionOutput"] | components["schemas"]["IntegerGeneratorOutput"] | components["schemas"]["IntegerOutput"] | components["schemas"]["IterateInvocationOutput"] | components["schemas"]["LatentsCollectionOutput"] | components["schemas"]["LatentsMetaOutput"] | components["schemas"]["LatentsOutput"] | components["schemas"]["LoRALoaderOutput"] | components["schemas"]["LoRASelectorOutput"] | components["schemas"]["MDControlListOutput"] | components["schemas"]["MDIPAdapterListOutput"] | components["schemas"]["MDT2IAdapterListOutput"] | components["schemas"]["MaskOutput"] | components["schemas"]["MetadataItemOutput"] | components["schemas"]["MetadataOutput"] | components["schemas"]["MetadataToLorasCollectionOutput"] | components["schemas"]["MetadataToModelOutput"] | components["schemas"]["MetadataToSDXLModelOutput"] | components["schemas"]["ModelIdentifierOutput"] | components["schemas"]["ModelLoaderOutput"] | components["schemas"]["NoiseOutput"] | components["schemas"]["PBRMapsOutput"] | components["schemas"]["PairTileImageOutput"] | components["schemas"]["PromptTemplateOutput"] | components["schemas"]["QwenImageConditioningOutput"] | components["schemas"]["QwenImageLoRALoaderOutput"] | components["schemas"]["QwenImageModelLoaderOutput"] | components["schemas"]["SD3ConditioningOutput"] | components["schemas"]["SDXLLoRALoaderOutput"] | components["schemas"]["SDXLModelLoaderOutput"] | components["schemas"]["SDXLRefinerModelLoaderOutput"] | components["schemas"]["SchedulerOutput"] | components["schemas"]["Sd3ModelLoaderOutput"] | components["schemas"]["SeamlessModeOutput"] | components["schemas"]["String2Output"] | components["schemas"]["StringCollectionOutput"] | components["schemas"]["StringGeneratorOutput"] | components["schemas"]["StringOutput"] | components["schemas"]["StringPosNegOutput"] | components["schemas"]["T2IAdapterOutput"] | components["schemas"]["TileToPropertiesOutput"] | components["schemas"]["UNetOutput"] | components["schemas"]["VAEOutput"] | components["schemas"]["WorkflowReturnGetOutput"] | components["schemas"]["WorkflowReturnOutput"] | components["schemas"]["WorkflowReturnValueOutput"] | components["schemas"]["ZImageConditioningOutput"] | components["schemas"]["ZImageControlOutput"] | components["schemas"]["ZImageLoRALoaderOutput"] | components["schemas"]["ZImageModelLoaderOutput"];};/*** Errors@@ -12382,6 +12430,30 @@ export type components = {errors: {[key: string]: string;};+ /**+ * Workflow Call Stack+ * @description The nested workflow call stack inherited by this execution state.+ */+ workflow_call_stack: components["schemas"]["WorkflowCallFrame"][];+ /**+ * Workflow Call History+ * @description Completed or failed workflow-call relationships observed by this execution state.+ */+ workflow_call_history: components["schemas"]["WorkflowCallExecution"][];+ /** @description Parent workflow-call relationship metadata when this execution state is a child workflow session. */+ workflow_call_parent?: components["schemas"]["WorkflowCallParentRef"] | null;+ /** @description The child workflow call this execution state is currently waiting on, if any. */+ waiting_workflow_call?: components["schemas"]["WorkflowCallFrame"] | null;+ /** @description The active workflow-call relationship metadata for the current waiting child workflow, if any. */+ waiting_workflow_call_execution?: components["schemas"]["WorkflowCallExecution"] | null;+ /** @description The child workflow execution state spawned by the current waiting workflow call, if any. */+ waiting_workflow_call_child_session?: components["schemas"]["GraphExecutionState"] | null;+ /**+ * Max Workflow Call Depth+ * @description The maximum permitted workflow call depth for nested workflow execution.+ * @default 4+ */+ max_workflow_call_depth?: number;/*** Prepared Source Mapping* @description The map of prepared nodes to original graph nodes@@ -15789,7 +15861,7 @@ export type components = {* Invocation* @description The ID of the invocation*/- invocation: components["schemas"]["AddInvocation"] | components["schemas"]["AlibabaCloudImageGenerationInvocation"] | components["schemas"]["AlphaMaskToTensorInvocation"] | components["schemas"]["AnimaDenoiseInvocation"] | components["schemas"]["AnimaImageToLatentsInvocation"] | components["schemas"]["AnimaLatentsToImageInvocation"] | components["schemas"]["AnimaLoRACollectionLoader"] | components["schemas"]["AnimaLoRALoaderInvocation"] | components["schemas"]["AnimaModelLoaderInvocation"] | components["schemas"]["AnimaTextEncoderInvocation"] | components["schemas"]["ApplyMaskTensorToImageInvocation"] | components["schemas"]["ApplyMaskToImageInvocation"] | components["schemas"]["BlankImageInvocation"] | components["schemas"]["BlendLatentsInvocation"] | components["schemas"]["BooleanCollectionInvocation"] | components["schemas"]["BooleanInvocation"] | components["schemas"]["BoundingBoxInvocation"] | components["schemas"]["CLIPSkipInvocation"] | components["schemas"]["CV2InfillInvocation"] | components["schemas"]["CalculateImageTilesEvenSplitInvocation"] | components["schemas"]["CalculateImageTilesInvocation"] | components["schemas"]["CalculateImageTilesMinimumOverlapInvocation"] | components["schemas"]["CannyEdgeDetectionInvocation"] | components["schemas"]["CanvasOutputInvocation"] | components["schemas"]["CanvasPasteBackInvocation"] | components["schemas"]["CanvasV2MaskAndCropInvocation"] | components["schemas"]["CenterPadCropInvocation"] | components["schemas"]["CogView4DenoiseInvocation"] | components["schemas"]["CogView4ImageToLatentsInvocation"] | components["schemas"]["CogView4LatentsToImageInvocation"] | components["schemas"]["CogView4ModelLoaderInvocation"] | components["schemas"]["CogView4TextEncoderInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["ColorCorrectInvocation"] | components["schemas"]["ColorInvocation"] | components["schemas"]["ColorMapInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["ConditioningCollectionInvocation"] | components["schemas"]["ConditioningInvocation"] | components["schemas"]["ContentShuffleInvocation"] | components["schemas"]["ControlNetInvocation"] | components["schemas"]["CoreMetadataInvocation"] | components["schemas"]["CreateDenoiseMaskInvocation"] | components["schemas"]["CreateGradientMaskInvocation"] | components["schemas"]["CropImageToBoundingBoxInvocation"] | components["schemas"]["CropLatentsCoreInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["DWOpenposeDetectionInvocation"] | components["schemas"]["DecodeInvisibleWatermarkInvocation"] | components["schemas"]["DenoiseLatentsInvocation"] | components["schemas"]["DenoiseLatentsMetaInvocation"] | components["schemas"]["DepthAnythingDepthEstimationInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["ExpandMaskWithFadeInvocation"] | components["schemas"]["FLUXLoRACollectionLoader"] | components["schemas"]["FaceIdentifierInvocation"] | components["schemas"]["FaceMaskInvocation"] | components["schemas"]["FaceOffInvocation"] | components["schemas"]["FloatBatchInvocation"] | components["schemas"]["FloatCollectionInvocation"] | components["schemas"]["FloatGenerator"] | components["schemas"]["FloatInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["FloatMathInvocation"] | components["schemas"]["FloatToIntegerInvocation"] | components["schemas"]["Flux2DenoiseInvocation"] | components["schemas"]["Flux2KleinLoRACollectionLoader"] | components["schemas"]["Flux2KleinLoRALoaderInvocation"] | components["schemas"]["Flux2KleinModelLoaderInvocation"] | components["schemas"]["Flux2KleinTextEncoderInvocation"] | components["schemas"]["Flux2VaeDecodeInvocation"] | components["schemas"]["Flux2VaeEncodeInvocation"] | components["schemas"]["FluxControlLoRALoaderInvocation"] | components["schemas"]["FluxControlNetInvocation"] | components["schemas"]["FluxDenoiseInvocation"] | components["schemas"]["FluxDenoiseLatentsMetaInvocation"] | components["schemas"]["FluxFillInvocation"] | components["schemas"]["FluxIPAdapterInvocation"] | components["schemas"]["FluxKontextConcatenateImagesInvocation"] | components["schemas"]["FluxKontextInvocation"] | components["schemas"]["FluxLoRALoaderInvocation"] | components["schemas"]["FluxModelLoaderInvocation"] | components["schemas"]["FluxReduxInvocation"] | components["schemas"]["FluxTextEncoderInvocation"] | components["schemas"]["FluxVaeDecodeInvocation"] | components["schemas"]["FluxVaeEncodeInvocation"] | components["schemas"]["FreeUInvocation"] | components["schemas"]["GeminiImageGenerationInvocation"] | components["schemas"]["GetMaskBoundingBoxInvocation"] | components["schemas"]["GroundingDinoInvocation"] | components["schemas"]["HEDEdgeDetectionInvocation"] | components["schemas"]["HeuristicResizeInvocation"] | components["schemas"]["IPAdapterInvocation"] | components["schemas"]["IdealSizeInvocation"] | components["schemas"]["IfInvocation"] | components["schemas"]["ImageBatchInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageChannelMultiplyInvocation"] | components["schemas"]["ImageChannelOffsetInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImageGenerator"] | components["schemas"]["ImageHueAdjustmentInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageMaskToTensorInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageNoiseInvocation"] | components["schemas"]["ImagePanelLayoutInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["IntegerBatchInvocation"] | components["schemas"]["IntegerCollectionInvocation"] | components["schemas"]["IntegerGenerator"] | components["schemas"]["IntegerInvocation"] | components["schemas"]["IntegerMathInvocation"] | components["schemas"]["InvertTensorMaskInvocation"] | components["schemas"]["InvokeAdjustImageHuePlusInvocation"] | components["schemas"]["InvokeEquivalentAchromaticLightnessInvocation"] | components["schemas"]["InvokeImageBlendInvocation"] | components["schemas"]["InvokeImageCompositorInvocation"] | components["schemas"]["InvokeImageDilateOrErodeInvocation"] | components["schemas"]["InvokeImageEnhanceInvocation"] | components["schemas"]["InvokeImageValueThresholdsInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["LaMaInfillInvocation"] | components["schemas"]["LatentsCollectionInvocation"] | components["schemas"]["LatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["LineartAnimeEdgeDetectionInvocation"] | components["schemas"]["LineartEdgeDetectionInvocation"] | components["schemas"]["LlavaOnevisionVllmInvocation"] | components["schemas"]["LoRACollectionLoader"] | components["schemas"]["LoRALoaderInvocation"] | components["schemas"]["LoRASelectorInvocation"] | components["schemas"]["MLSDDetectionInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["MaskCombineInvocation"] | components["schemas"]["MaskEdgeInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["MaskFromIDInvocation"] | components["schemas"]["MaskTensorToImageInvocation"] | components["schemas"]["MediaPipeFaceDetectionInvocation"] | components["schemas"]["MergeMetadataInvocation"] | components["schemas"]["MergeTilesToImageInvocation"] | components["schemas"]["MetadataFieldExtractorInvocation"] | components["schemas"]["MetadataFromImageInvocation"] | components["schemas"]["MetadataInvocation"] | components["schemas"]["MetadataItemInvocation"] | components["schemas"]["MetadataItemLinkedInvocation"] | components["schemas"]["MetadataToBoolCollectionInvocation"] | components["schemas"]["MetadataToBoolInvocation"] | components["schemas"]["MetadataToControlnetsInvocation"] | components["schemas"]["MetadataToFloatCollectionInvocation"] | components["schemas"]["MetadataToFloatInvocation"] | components["schemas"]["MetadataToIPAdaptersInvocation"] | components["schemas"]["MetadataToIntegerCollectionInvocation"] | components["schemas"]["MetadataToIntegerInvocation"] | components["schemas"]["MetadataToLorasCollectionInvocation"] | components["schemas"]["MetadataToLorasInvocation"] | components["schemas"]["MetadataToModelInvocation"] | components["schemas"]["MetadataToSDXLLorasInvocation"] | components["schemas"]["MetadataToSDXLModelInvocation"] | components["schemas"]["MetadataToSchedulerInvocation"] | components["schemas"]["MetadataToStringCollectionInvocation"] | components["schemas"]["MetadataToStringInvocation"] | components["schemas"]["MetadataToT2IAdaptersInvocation"] | components["schemas"]["MetadataToVAEInvocation"] | components["schemas"]["ModelIdentifierInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["NormalMapInvocation"] | components["schemas"]["OklabUnsharpMaskInvocation"] | components["schemas"]["OklchImageHueAdjustmentInvocation"] | components["schemas"]["OpenAIImageGenerationInvocation"] | components["schemas"]["PBRMapsInvocation"] | components["schemas"]["PairTileImageInvocation"] | components["schemas"]["PasteImageIntoBoundingBoxInvocation"] | components["schemas"]["PiDiNetEdgeDetectionInvocation"] | components["schemas"]["PromptTemplateInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["QwenImageDenoiseInvocation"] | components["schemas"]["QwenImageImageToLatentsInvocation"] | components["schemas"]["QwenImageLatentsToImageInvocation"] | components["schemas"]["QwenImageLoRACollectionLoader"] | components["schemas"]["QwenImageLoRALoaderInvocation"] | components["schemas"]["QwenImageModelLoaderInvocation"] | components["schemas"]["QwenImageTextEncoderInvocation"] | components["schemas"]["RandomFloatInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RectangleMaskInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["RoundInvocation"] | components["schemas"]["SD3DenoiseInvocation"] | components["schemas"]["SD3ImageToLatentsInvocation"] | components["schemas"]["SD3LatentsToImageInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLLoRACollectionLoader"] | components["schemas"]["SDXLLoRALoaderInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SaveImageInvocation"] | components["schemas"]["SaveImageToFileInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["SchedulerInvocation"] | components["schemas"]["Sd3ModelLoaderInvocation"] | components["schemas"]["Sd3TextEncoderInvocation"] | components["schemas"]["SeamlessModeInvocation"] | components["schemas"]["SeedreamImageGenerationInvocation"] | components["schemas"]["SegmentAnythingInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["SpandrelImageToImageAutoscaleInvocation"] | components["schemas"]["SpandrelImageToImageInvocation"] | components["schemas"]["StringBatchInvocation"] | components["schemas"]["StringCollectionInvocation"] | components["schemas"]["StringGenerator"] | components["schemas"]["StringInvocation"] | components["schemas"]["StringJoinInvocation"] | components["schemas"]["StringJoinThreeInvocation"] | components["schemas"]["StringReplaceInvocation"] | components["schemas"]["StringSplitInvocation"] | components["schemas"]["StringSplitNegInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["T2IAdapterInvocation"] | components["schemas"]["TextLLMInvocation"] | components["schemas"]["TileToPropertiesInvocation"] | components["schemas"]["TiledMultiDiffusionDenoiseLatents"] | components["schemas"]["UnsharpMaskInvocation"] | components["schemas"]["VAELoaderInvocation"] | components["schemas"]["ZImageControlInvocation"] | components["schemas"]["ZImageDenoiseInvocation"] | components["schemas"]["ZImageDenoiseMetaInvocation"] | components["schemas"]["ZImageImageToLatentsInvocation"] | components["schemas"]["ZImageLatentsToImageInvocation"] | components["schemas"]["ZImageLoRACollectionLoader"] | components["schemas"]["ZImageLoRALoaderInvocation"] | components["schemas"]["ZImageModelLoaderInvocation"] | components["schemas"]["ZImageSeedVarianceEnhancerInvocation"] | components["schemas"]["ZImageTextEncoderInvocation"];+ invocation: components["schemas"]["AddInvocation"] | components["schemas"]["AlibabaCloudImageGenerationInvocation"] | components["schemas"]["AlphaMaskToTensorInvocation"] | components["schemas"]["AnimaDenoiseInvocation"] | components["schemas"]["AnimaImageToLatentsInvocation"] | components["schemas"]["AnimaLatentsToImageInvocation"] | components["schemas"]["AnimaLoRACollectionLoader"] | components["schemas"]["AnimaLoRALoaderInvocation"] | components["schemas"]["AnimaModelLoaderInvocation"] | components["schemas"]["AnimaTextEncoderInvocation"] | components["schemas"]["ApplyMaskTensorToImageInvocation"] | components["schemas"]["ApplyMaskToImageInvocation"] | components["schemas"]["BlankImageInvocation"] | components["schemas"]["BlendLatentsInvocation"] | components["schemas"]["BooleanCollectionInvocation"] | components["schemas"]["BooleanInvocation"] | components["schemas"]["BoundingBoxInvocation"] | components["schemas"]["CLIPSkipInvocation"] | components["schemas"]["CV2InfillInvocation"] | components["schemas"]["CalculateImageTilesEvenSplitInvocation"] | components["schemas"]["CalculateImageTilesInvocation"] | components["schemas"]["CalculateImageTilesMinimumOverlapInvocation"] | components["schemas"]["CallSavedWorkflowInvocation"] | components["schemas"]["CannyEdgeDetectionInvocation"] | components["schemas"]["CanvasOutputInvocation"] | components["schemas"]["CanvasPasteBackInvocation"] | components["schemas"]["CanvasV2MaskAndCropInvocation"] | components["schemas"]["CenterPadCropInvocation"] | components["schemas"]["CogView4DenoiseInvocation"] | components["schemas"]["CogView4ImageToLatentsInvocation"] | components["schemas"]["CogView4LatentsToImageInvocation"] | components["schemas"]["CogView4ModelLoaderInvocation"] | components["schemas"]["CogView4TextEncoderInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["ColorCorrectInvocation"] | components["schemas"]["ColorInvocation"] | components["schemas"]["ColorMapInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["ConditioningCollectionInvocation"] | components["schemas"]["ConditioningInvocation"] | components["schemas"]["ContentShuffleInvocation"] | components["schemas"]["ControlNetInvocation"] | components["schemas"]["CoreMetadataInvocation"] | components["schemas"]["CreateDenoiseMaskInvocation"] | components["schemas"]["CreateGradientMaskInvocation"] | components["schemas"]["CropImageToBoundingBoxInvocation"] | components["schemas"]["CropLatentsCoreInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["DWOpenposeDetectionInvocation"] | components["schemas"]["DecodeInvisibleWatermarkInvocation"] | components["schemas"]["DenoiseLatentsInvocation"] | components["schemas"]["DenoiseLatentsMetaInvocation"] | components["schemas"]["DepthAnythingDepthEstimationInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["ExpandMaskWithFadeInvocation"] | components["schemas"]["FLUXLoRACollectionLoader"] | components["schemas"]["FaceIdentifierInvocation"] | components["schemas"]["FaceMaskInvocation"] | components["schemas"]["FaceOffInvocation"] | components["schemas"]["FloatBatchInvocation"] | components["schemas"]["FloatCollectionInvocation"] | components["schemas"]["FloatGenerator"] | components["schemas"]["FloatInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["FloatMathInvocation"] | components["schemas"]["FloatToIntegerInvocation"] | components["schemas"]["Flux2DenoiseInvocation"] | components["schemas"]["Flux2KleinLoRACollectionLoader"] | components["schemas"]["Flux2KleinLoRALoaderInvocation"] | components["schemas"]["Flux2KleinModelLoaderInvocation"] | components["schemas"]["Flux2KleinTextEncoderInvocation"] | components["schemas"]["Flux2VaeDecodeInvocation"] | components["schemas"]["Flux2VaeEncodeInvocation"] | components["schemas"]["FluxControlLoRALoaderInvocation"] | components["schemas"]["FluxControlNetInvocation"] | components["schemas"]["FluxDenoiseInvocation"] | components["schemas"]["FluxDenoiseLatentsMetaInvocation"] | components["schemas"]["FluxFillInvocation"] | components["schemas"]["FluxIPAdapterInvocation"] | components["schemas"]["FluxKontextConcatenateImagesInvocation"] | components["schemas"]["FluxKontextInvocation"] | components["schemas"]["FluxLoRALoaderInvocation"] | components["schemas"]["FluxModelLoaderInvocation"] | components["schemas"]["FluxReduxInvocation"] | components["schemas"]["FluxTextEncoderInvocation"] | components["schemas"]["FluxVaeDecodeInvocation"] | components["schemas"]["FluxVaeEncodeInvocation"] | components["schemas"]["FreeUInvocation"] | components["schemas"]["GeminiImageGenerationInvocation"] | components["schemas"]["GetMaskBoundingBoxInvocation"] | components["schemas"]["GroundingDinoInvocation"] | components["schemas"]["HEDEdgeDetectionInvocation"] | components["schemas"]["HeuristicResizeInvocation"] | components["schemas"]["IPAdapterInvocation"] | components["schemas"]["IdealSizeInvocation"] | components["schemas"]["IfInvocation"] | components["schemas"]["ImageBatchInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageChannelMultiplyInvocation"] | components["schemas"]["ImageChannelOffsetInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImageGenerator"] | components["schemas"]["ImageHueAdjustmentInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageMaskToTensorInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageNoiseInvocation"] | components["schemas"]["ImagePanelLayoutInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["IntegerBatchInvocation"] | components["schemas"]["IntegerCollectionInvocation"] | components["schemas"]["IntegerGenerator"] | components["schemas"]["IntegerInvocation"] | components["schemas"]["IntegerMathInvocation"] | components["schemas"]["InvertTensorMaskInvocation"] | components["schemas"]["InvokeAdjustImageHuePlusInvocation"] | components["schemas"]["InvokeEquivalentAchromaticLightnessInvocation"] | components["schemas"]["InvokeImageBlendInvocation"] | components["schemas"]["InvokeImageCompositorInvocation"] | components["schemas"]["InvokeImageDilateOrErodeInvocation"] | components["schemas"]["InvokeImageEnhanceInvocation"] | components["schemas"]["InvokeImageValueThresholdsInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["LaMaInfillInvocation"] | components["schemas"]["LatentsCollectionInvocation"] | components["schemas"]["LatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["LineartAnimeEdgeDetectionInvocation"] | components["schemas"]["LineartEdgeDetectionInvocation"] | components["schemas"]["LlavaOnevisionVllmInvocation"] | components["schemas"]["LoRACollectionLoader"] | components["schemas"]["LoRALoaderInvocation"] | components["schemas"]["LoRASelectorInvocation"] | components["schemas"]["MLSDDetectionInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["MaskCombineInvocation"] | components["schemas"]["MaskEdgeInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["MaskFromIDInvocation"] | components["schemas"]["MaskTensorToImageInvocation"] | components["schemas"]["MediaPipeFaceDetectionInvocation"] | components["schemas"]["MergeMetadataInvocation"] | components["schemas"]["MergeTilesToImageInvocation"] | components["schemas"]["MetadataFieldExtractorInvocation"] | components["schemas"]["MetadataFromImageInvocation"] | components["schemas"]["MetadataInvocation"] | components["schemas"]["MetadataItemInvocation"] | components["schemas"]["MetadataItemLinkedInvocation"] | components["schemas"]["MetadataToBoolCollectionInvocation"] | components["schemas"]["MetadataToBoolInvocation"] | components["schemas"]["MetadataToControlnetsInvocation"] | components["schemas"]["MetadataToFloatCollectionInvocation"] | components["schemas"]["MetadataToFloatInvocation"] | components["schemas"]["MetadataToIPAdaptersInvocation"] | components["schemas"]["MetadataToIntegerCollectionInvocation"] | components["schemas"]["MetadataToIntegerInvocation"] | components["schemas"]["MetadataToLorasCollectionInvocation"] | components["schemas"]["MetadataToLorasInvocation"] | components["schemas"]["MetadataToModelInvocation"] | components["schemas"]["MetadataToSDXLLorasInvocation"] | components["schemas"]["MetadataToSDXLModelInvocation"] | components["schemas"]["MetadataToSchedulerInvocation"] | components["schemas"]["MetadataToStringCollectionInvocation"] | components["schemas"]["MetadataToStringInvocation"] | components["schemas"]["MetadataToT2IAdaptersInvocation"] | components["schemas"]["MetadataToVAEInvocation"] | components["schemas"]["ModelIdentifierInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["NormalMapInvocation"] | components["schemas"]["OklabUnsharpMaskInvocation"] | components["schemas"]["OklchImageHueAdjustmentInvocation"] | components["schemas"]["OpenAIImageGenerationInvocation"] | components["schemas"]["PBRMapsInvocation"] | components["schemas"]["PairTileImageInvocation"] | components["schemas"]["PasteImageIntoBoundingBoxInvocation"] | components["schemas"]["PiDiNetEdgeDetectionInvocation"] | components["schemas"]["PromptTemplateInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["QwenImageDenoiseInvocation"] | components["schemas"]["QwenImageImageToLatentsInvocation"] | components["schemas"]["QwenImageLatentsToImageInvocation"] | components["schemas"]["QwenImageLoRACollectionLoader"] | components["schemas"]["QwenImageLoRALoaderInvocation"] | components["schemas"]["QwenImageModelLoaderInvocation"] | components["schemas"]["QwenImageTextEncoderInvocation"] | components["schemas"]["RandomFloatInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RectangleMaskInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["RoundInvocation"] | components["schemas"]["SD3DenoiseInvocation"] | components["schemas"]["SD3ImageToLatentsInvocation"] | components["schemas"]["SD3LatentsToImageInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLLoRACollectionLoader"] | components["schemas"]["SDXLLoRALoaderInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SaveImageInvocation"] | components["schemas"]["SaveImageToFileInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["SchedulerInvocation"] | components["schemas"]["Sd3ModelLoaderInvocation"] | components["schemas"]["Sd3TextEncoderInvocation"] | components["schemas"]["SeamlessModeInvocation"] | components["schemas"]["SeedreamImageGenerationInvocation"] | components["schemas"]["SegmentAnythingInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["SpandrelImageToImageAutoscaleInvocation"] | components["schemas"]["SpandrelImageToImageInvocation"] | components["schemas"]["StringBatchInvocation"] | components["schemas"]["StringCollectionInvocation"] | components["schemas"]["StringGenerator"] | components["schemas"]["StringInvocation"] | components["schemas"]["StringJoinInvocation"] | components["schemas"]["StringJoinThreeInvocation"] | components["schemas"]["StringReplaceInvocation"] | components["schemas"]["StringSplitInvocation"] | components["schemas"]["StringSplitNegInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["T2IAdapterInvocation"] | components["schemas"]["TextLLMInvocation"] | components["schemas"]["TileToPropertiesInvocation"] | components["schemas"]["TiledMultiDiffusionDenoiseLatents"] | components["schemas"]["UnsharpMaskInvocation"] | components["schemas"]["VAELoaderInvocation"] | components["schemas"]["WorkflowReturnGetInvocation"] | components["schemas"]["WorkflowReturnInvocation"] | components["schemas"]["WorkflowReturnValueInvocation"] | components["schemas"]["ZImageControlInvocation"] | components["schemas"]["ZImageDenoiseInvocation"] | components["schemas"]["ZImageDenoiseMetaInvocation"] | components["schemas"]["ZImageImageToLatentsInvocation"] | components["schemas"]["ZImageLatentsToImageInvocation"] | components["schemas"]["ZImageLoRACollectionLoader"] | components["schemas"]["ZImageLoRALoaderInvocation"] | components["schemas"]["ZImageModelLoaderInvocation"] | components["schemas"]["ZImageSeedVarianceEnhancerInvocation"] | components["schemas"]["ZImageTextEncoderInvocation"];/*** Invocation Source Id* @description The ID of the prepared invocation's source node@@ -15799,7 +15871,7 @@ export type components = {* Result* @description The result of the invocation*/- result: components["schemas"]["AnimaConditioningOutput"] | components["schemas"]["AnimaLoRALoaderOutput"] | components["schemas"]["AnimaModelLoaderOutput"] | components["schemas"]["BooleanCollectionOutput"] | components["schemas"]["BooleanOutput"] | components["schemas"]["BoundingBoxCollectionOutput"] | components["schemas"]["BoundingBoxOutput"] | components["schemas"]["CLIPOutput"] | components["schemas"]["CLIPSkipInvocationOutput"] | components["schemas"]["CalculateImageTilesOutput"] | components["schemas"]["CogView4ConditioningOutput"] | components["schemas"]["CogView4ModelLoaderOutput"] | components["schemas"]["CollectInvocationOutput"] | components["schemas"]["ColorCollectionOutput"] | components["schemas"]["ColorOutput"] | components["schemas"]["ConditioningCollectionOutput"] | components["schemas"]["ConditioningOutput"] | components["schemas"]["ControlOutput"] | components["schemas"]["DenoiseMaskOutput"] | components["schemas"]["FaceMaskOutput"] | components["schemas"]["FaceOffOutput"] | components["schemas"]["FloatCollectionOutput"] | components["schemas"]["FloatGeneratorOutput"] | components["schemas"]["FloatOutput"] | components["schemas"]["Flux2KleinLoRALoaderOutput"] | components["schemas"]["Flux2KleinModelLoaderOutput"] | components["schemas"]["FluxConditioningCollectionOutput"] | components["schemas"]["FluxConditioningOutput"] | components["schemas"]["FluxControlLoRALoaderOutput"] | components["schemas"]["FluxControlNetOutput"] | components["schemas"]["FluxFillOutput"] | components["schemas"]["FluxKontextOutput"] | components["schemas"]["FluxLoRALoaderOutput"] | components["schemas"]["FluxModelLoaderOutput"] | components["schemas"]["FluxReduxOutput"] | components["schemas"]["GradientMaskOutput"] | components["schemas"]["IPAdapterOutput"] | components["schemas"]["IdealSizeOutput"] | components["schemas"]["IfInvocationOutput"] | components["schemas"]["ImageCollectionOutput"] | components["schemas"]["ImageGeneratorOutput"] | components["schemas"]["ImageOutput"] | components["schemas"]["ImagePanelCoordinateOutput"] | components["schemas"]["IntegerCollectionOutput"] | components["schemas"]["IntegerGeneratorOutput"] | components["schemas"]["IntegerOutput"] | components["schemas"]["IterateInvocationOutput"] | components["schemas"]["LatentsCollectionOutput"] | components["schemas"]["LatentsMetaOutput"] | components["schemas"]["LatentsOutput"] | components["schemas"]["LoRALoaderOutput"] | components["schemas"]["LoRASelectorOutput"] | components["schemas"]["MDControlListOutput"] | components["schemas"]["MDIPAdapterListOutput"] | components["schemas"]["MDT2IAdapterListOutput"] | components["schemas"]["MaskOutput"] | components["schemas"]["MetadataItemOutput"] | components["schemas"]["MetadataOutput"] | components["schemas"]["MetadataToLorasCollectionOutput"] | components["schemas"]["MetadataToModelOutput"] | components["schemas"]["MetadataToSDXLModelOutput"] | components["schemas"]["ModelIdentifierOutput"] | components["schemas"]["ModelLoaderOutput"] | components["schemas"]["NoiseOutput"] | components["schemas"]["PBRMapsOutput"] | components["schemas"]["PairTileImageOutput"] | components["schemas"]["PromptTemplateOutput"] | components["schemas"]["QwenImageConditioningOutput"] | components["schemas"]["QwenImageLoRALoaderOutput"] | components["schemas"]["QwenImageModelLoaderOutput"] | components["schemas"]["SD3ConditioningOutput"] | components["schemas"]["SDXLLoRALoaderOutput"] | components["schemas"]["SDXLModelLoaderOutput"] | components["schemas"]["SDXLRefinerModelLoaderOutput"] | components["schemas"]["SchedulerOutput"] | components["schemas"]["Sd3ModelLoaderOutput"] | components["schemas"]["SeamlessModeOutput"] | components["schemas"]["String2Output"] | components["schemas"]["StringCollectionOutput"] | components["schemas"]["StringGeneratorOutput"] | components["schemas"]["StringOutput"] | components["schemas"]["StringPosNegOutput"] | components["schemas"]["T2IAdapterOutput"] | components["schemas"]["TileToPropertiesOutput"] | components["schemas"]["UNetOutput"] | components["schemas"]["VAEOutput"] | components["schemas"]["ZImageConditioningOutput"] | components["schemas"]["ZImageControlOutput"] | components["schemas"]["ZImageLoRALoaderOutput"] | components["schemas"]["ZImageModelLoaderOutput"];+ result: components["schemas"]["AnimaConditioningOutput"] | components["schemas"]["AnimaLoRALoaderOutput"] | components["schemas"]["AnimaModelLoaderOutput"] | components["schemas"]["BooleanCollectionOutput"] | components["schemas"]["BooleanOutput"] | components["schemas"]["BoundingBoxCollectionOutput"] | components["schemas"]["BoundingBoxOutput"] | components["schemas"]["CLIPOutput"] | components["schemas"]["CLIPSkipInvocationOutput"] | components["schemas"]["CalculateImageTilesOutput"] | components["schemas"]["CogView4ConditioningOutput"] | components["schemas"]["CogView4ModelLoaderOutput"] | components["schemas"]["CollectInvocationOutput"] | components["schemas"]["ColorCollectionOutput"] | components["schemas"]["ColorOutput"] | components["schemas"]["ConditioningCollectionOutput"] | components["schemas"]["ConditioningOutput"] | components["schemas"]["ControlOutput"] | components["schemas"]["DenoiseMaskOutput"] | components["schemas"]["FaceMaskOutput"] | components["schemas"]["FaceOffOutput"] | components["schemas"]["FloatCollectionOutput"] | components["schemas"]["FloatGeneratorOutput"] | components["schemas"]["FloatOutput"] | components["schemas"]["Flux2KleinLoRALoaderOutput"] | components["schemas"]["Flux2KleinModelLoaderOutput"] | components["schemas"]["FluxConditioningCollectionOutput"] | components["schemas"]["FluxConditioningOutput"] | components["schemas"]["FluxControlLoRALoaderOutput"] | components["schemas"]["FluxControlNetOutput"] | components["schemas"]["FluxFillOutput"] | components["schemas"]["FluxKontextOutput"] | components["schemas"]["FluxLoRALoaderOutput"] | components["schemas"]["FluxModelLoaderOutput"] | components["schemas"]["FluxReduxOutput"] | components["schemas"]["GradientMaskOutput"] | components["schemas"]["IPAdapterOutput"] | components["schemas"]["IdealSizeOutput"] | components["schemas"]["IfInvocationOutput"] | components["schemas"]["ImageCollectionOutput"] | components["schemas"]["ImageGeneratorOutput"] | components["schemas"]["ImageOutput"] | components["schemas"]["ImagePanelCoordinateOutput"] | components["schemas"]["IntegerCollectionOutput"] | components["schemas"]["IntegerGeneratorOutput"] | components["schemas"]["IntegerOutput"] | components["schemas"]["IterateInvocationOutput"] | components["schemas"]["LatentsCollectionOutput"] | components["schemas"]["LatentsMetaOutput"] | components["schemas"]["LatentsOutput"] | components["schemas"]["LoRALoaderOutput"] | components["schemas"]["LoRASelectorOutput"] | components["schemas"]["MDControlListOutput"] | components["schemas"]["MDIPAdapterListOutput"] | components["schemas"]["MDT2IAdapterListOutput"] | components["schemas"]["MaskOutput"] | components["schemas"]["MetadataItemOutput"] | components["schemas"]["MetadataOutput"] | components["schemas"]["MetadataToLorasCollectionOutput"] | components["schemas"]["MetadataToModelOutput"] | components["schemas"]["MetadataToSDXLModelOutput"] | components["schemas"]["ModelIdentifierOutput"] | components["schemas"]["ModelLoaderOutput"] | components["schemas"]["NoiseOutput"] | components["schemas"]["PBRMapsOutput"] | components["schemas"]["PairTileImageOutput"] | components["schemas"]["PromptTemplateOutput"] | components["schemas"]["QwenImageConditioningOutput"] | components["schemas"]["QwenImageLoRALoaderOutput"] | components["schemas"]["QwenImageModelLoaderOutput"] | components["schemas"]["SD3ConditioningOutput"] | components["schemas"]["SDXLLoRALoaderOutput"] | components["schemas"]["SDXLModelLoaderOutput"] | components["schemas"]["SDXLRefinerModelLoaderOutput"] | components["schemas"]["SchedulerOutput"] | components["schemas"]["Sd3ModelLoaderOutput"] | components["schemas"]["SeamlessModeOutput"] | components["schemas"]["String2Output"] | components["schemas"]["StringCollectionOutput"] | components["schemas"]["StringGeneratorOutput"] | components["schemas"]["StringOutput"] | components["schemas"]["StringPosNegOutput"] | components["schemas"]["T2IAdapterOutput"] | components["schemas"]["TileToPropertiesOutput"] | components["schemas"]["UNetOutput"] | components["schemas"]["VAEOutput"] | components["schemas"]["WorkflowReturnGetOutput"] | components["schemas"]["WorkflowReturnOutput"] | components["schemas"]["WorkflowReturnValueOutput"] | components["schemas"]["ZImageConditioningOutput"] | components["schemas"]["ZImageControlOutput"] | components["schemas"]["ZImageLoRALoaderOutput"] | components["schemas"]["ZImageModelLoaderOutput"];};/*** InvocationErrorEvent@@ -15853,7 +15925,7 @@ export type components = {* Invocation* @description The ID of the invocation*/- invocation: components["schemas"]["AddInvocation"] | components["schemas"]["AlibabaCloudImageGenerationInvocation"] | components["schemas"]["AlphaMaskToTensorInvocation"] | components["schemas"]["AnimaDenoiseInvocation"] | components["schemas"]["AnimaImageToLatentsInvocation"] | components["schemas"]["AnimaLatentsToImageInvocation"] | components["schemas"]["AnimaLoRACollectionLoader"] | components["schemas"]["AnimaLoRALoaderInvocation"] | components["schemas"]["AnimaModelLoaderInvocation"] | components["schemas"]["AnimaTextEncoderInvocation"] | components["schemas"]["ApplyMaskTensorToImageInvocation"] | components["schemas"]["ApplyMaskToImageInvocation"] | components["schemas"]["BlankImageInvocation"] | components["schemas"]["BlendLatentsInvocation"] | components["schemas"]["BooleanCollectionInvocation"] | components["schemas"]["BooleanInvocation"] | components["schemas"]["BoundingBoxInvocation"] | components["schemas"]["CLIPSkipInvocation"] | components["schemas"]["CV2InfillInvocation"] | components["schemas"]["CalculateImageTilesEvenSplitInvocation"] | components["schemas"]["CalculateImageTilesInvocation"] | components["schemas"]["CalculateImageTilesMinimumOverlapInvocation"] | components["schemas"]["CannyEdgeDetectionInvocation"] | components["schemas"]["CanvasOutputInvocation"] | components["schemas"]["CanvasPasteBackInvocation"] | components["schemas"]["CanvasV2MaskAndCropInvocation"] | components["schemas"]["CenterPadCropInvocation"] | components["schemas"]["CogView4DenoiseInvocation"] | components["schemas"]["CogView4ImageToLatentsInvocation"] | components["schemas"]["CogView4LatentsToImageInvocation"] | components["schemas"]["CogView4ModelLoaderInvocation"] | components["schemas"]["CogView4TextEncoderInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["ColorCorrectInvocation"] | components["schemas"]["ColorInvocation"] | components["schemas"]["ColorMapInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["ConditioningCollectionInvocation"] | components["schemas"]["ConditioningInvocation"] | components["schemas"]["ContentShuffleInvocation"] | components["schemas"]["ControlNetInvocation"] | components["schemas"]["CoreMetadataInvocation"] | components["schemas"]["CreateDenoiseMaskInvocation"] | components["schemas"]["CreateGradientMaskInvocation"] | components["schemas"]["CropImageToBoundingBoxInvocation"] | components["schemas"]["CropLatentsCoreInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["DWOpenposeDetectionInvocation"] | components["schemas"]["DecodeInvisibleWatermarkInvocation"] | components["schemas"]["DenoiseLatentsInvocation"] | components["schemas"]["DenoiseLatentsMetaInvocation"] | components["schemas"]["DepthAnythingDepthEstimationInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["ExpandMaskWithFadeInvocation"] | components["schemas"]["FLUXLoRACollectionLoader"] | components["schemas"]["FaceIdentifierInvocation"] | components["schemas"]["FaceMaskInvocation"] | components["schemas"]["FaceOffInvocation"] | components["schemas"]["FloatBatchInvocation"] | components["schemas"]["FloatCollectionInvocation"] | components["schemas"]["FloatGenerator"] | components["schemas"]["FloatInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["FloatMathInvocation"] | components["schemas"]["FloatToIntegerInvocation"] | components["schemas"]["Flux2DenoiseInvocation"] | components["schemas"]["Flux2KleinLoRACollectionLoader"] | components["schemas"]["Flux2KleinLoRALoaderInvocation"] | components["schemas"]["Flux2KleinModelLoaderInvocation"] | components["schemas"]["Flux2KleinTextEncoderInvocation"] | components["schemas"]["Flux2VaeDecodeInvocation"] | components["schemas"]["Flux2VaeEncodeInvocation"] | components["schemas"]["FluxControlLoRALoaderInvocation"] | components["schemas"]["FluxControlNetInvocation"] | components["schemas"]["FluxDenoiseInvocation"] | components["schemas"]["FluxDenoiseLatentsMetaInvocation"] | components["schemas"]["FluxFillInvocation"] | components["schemas"]["FluxIPAdapterInvocation"] | components["schemas"]["FluxKontextConcatenateImagesInvocation"] | components["schemas"]["FluxKontextInvocation"] | components["schemas"]["FluxLoRALoaderInvocation"] | components["schemas"]["FluxModelLoaderInvocation"] | components["schemas"]["FluxReduxInvocation"] | components["schemas"]["FluxTextEncoderInvocation"] | components["schemas"]["FluxVaeDecodeInvocation"] | components["schemas"]["FluxVaeEncodeInvocation"] | components["schemas"]["FreeUInvocation"] | components["schemas"]["GeminiImageGenerationInvocation"] | components["schemas"]["GetMaskBoundingBoxInvocation"] | components["schemas"]["GroundingDinoInvocation"] | components["schemas"]["HEDEdgeDetectionInvocation"] | components["schemas"]["HeuristicResizeInvocation"] | components["schemas"]["IPAdapterInvocation"] | components["schemas"]["IdealSizeInvocation"] | components["schemas"]["IfInvocation"] | components["schemas"]["ImageBatchInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageChannelMultiplyInvocation"] | components["schemas"]["ImageChannelOffsetInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImageGenerator"] | components["schemas"]["ImageHueAdjustmentInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageMaskToTensorInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageNoiseInvocation"] | components["schemas"]["ImagePanelLayoutInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["IntegerBatchInvocation"] | components["schemas"]["IntegerCollectionInvocation"] | components["schemas"]["IntegerGenerator"] | components["schemas"]["IntegerInvocation"] | components["schemas"]["IntegerMathInvocation"] | components["schemas"]["InvertTensorMaskInvocation"] | components["schemas"]["InvokeAdjustImageHuePlusInvocation"] | components["schemas"]["InvokeEquivalentAchromaticLightnessInvocation"] | components["schemas"]["InvokeImageBlendInvocation"] | components["schemas"]["InvokeImageCompositorInvocation"] | components["schemas"]["InvokeImageDilateOrErodeInvocation"] | components["schemas"]["InvokeImageEnhanceInvocation"] | components["schemas"]["InvokeImageValueThresholdsInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["LaMaInfillInvocation"] | components["schemas"]["LatentsCollectionInvocation"] | components["schemas"]["LatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["LineartAnimeEdgeDetectionInvocation"] | components["schemas"]["LineartEdgeDetectionInvocation"] | components["schemas"]["LlavaOnevisionVllmInvocation"] | components["schemas"]["LoRACollectionLoader"] | components["schemas"]["LoRALoaderInvocation"] | components["schemas"]["LoRASelectorInvocation"] | components["schemas"]["MLSDDetectionInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["MaskCombineInvocation"] | components["schemas"]["MaskEdgeInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["MaskFromIDInvocation"] | components["schemas"]["MaskTensorToImageInvocation"] | components["schemas"]["MediaPipeFaceDetectionInvocation"] | components["schemas"]["MergeMetadataInvocation"] | components["schemas"]["MergeTilesToImageInvocation"] | components["schemas"]["MetadataFieldExtractorInvocation"] | components["schemas"]["MetadataFromImageInvocation"] | components["schemas"]["MetadataInvocation"] | components["schemas"]["MetadataItemInvocation"] | components["schemas"]["MetadataItemLinkedInvocation"] | components["schemas"]["MetadataToBoolCollectionInvocation"] | components["schemas"]["MetadataToBoolInvocation"] | components["schemas"]["MetadataToControlnetsInvocation"] | components["schemas"]["MetadataToFloatCollectionInvocation"] | components["schemas"]["MetadataToFloatInvocation"] | components["schemas"]["MetadataToIPAdaptersInvocation"] | components["schemas"]["MetadataToIntegerCollectionInvocation"] | components["schemas"]["MetadataToIntegerInvocation"] | components["schemas"]["MetadataToLorasCollectionInvocation"] | components["schemas"]["MetadataToLorasInvocation"] | components["schemas"]["MetadataToModelInvocation"] | components["schemas"]["MetadataToSDXLLorasInvocation"] | components["schemas"]["MetadataToSDXLModelInvocation"] | components["schemas"]["MetadataToSchedulerInvocation"] | components["schemas"]["MetadataToStringCollectionInvocation"] | components["schemas"]["MetadataToStringInvocation"] | components["schemas"]["MetadataToT2IAdaptersInvocation"] | components["schemas"]["MetadataToVAEInvocation"] | components["schemas"]["ModelIdentifierInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["NormalMapInvocation"] | components["schemas"]["OklabUnsharpMaskInvocation"] | components["schemas"]["OklchImageHueAdjustmentInvocation"] | components["schemas"]["OpenAIImageGenerationInvocation"] | components["schemas"]["PBRMapsInvocation"] | components["schemas"]["PairTileImageInvocation"] | components["schemas"]["PasteImageIntoBoundingBoxInvocation"] | components["schemas"]["PiDiNetEdgeDetectionInvocation"] | components["schemas"]["PromptTemplateInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["QwenImageDenoiseInvocation"] | components["schemas"]["QwenImageImageToLatentsInvocation"] | components["schemas"]["QwenImageLatentsToImageInvocation"] | components["schemas"]["QwenImageLoRACollectionLoader"] | components["schemas"]["QwenImageLoRALoaderInvocation"] | components["schemas"]["QwenImageModelLoaderInvocation"] | components["schemas"]["QwenImageTextEncoderInvocation"] | components["schemas"]["RandomFloatInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RectangleMaskInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["RoundInvocation"] | components["schemas"]["SD3DenoiseInvocation"] | components["schemas"]["SD3ImageToLatentsInvocation"] | components["schemas"]["SD3LatentsToImageInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLLoRACollectionLoader"] | components["schemas"]["SDXLLoRALoaderInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SaveImageInvocation"] | components["schemas"]["SaveImageToFileInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["SchedulerInvocation"] | components["schemas"]["Sd3ModelLoaderInvocation"] | components["schemas"]["Sd3TextEncoderInvocation"] | components["schemas"]["SeamlessModeInvocation"] | components["schemas"]["SeedreamImageGenerationInvocation"] | components["schemas"]["SegmentAnythingInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["SpandrelImageToImageAutoscaleInvocation"] | components["schemas"]["SpandrelImageToImageInvocation"] | components["schemas"]["StringBatchInvocation"] | components["schemas"]["StringCollectionInvocation"] | components["schemas"]["StringGenerator"] | components["schemas"]["StringInvocation"] | components["schemas"]["StringJoinInvocation"] | components["schemas"]["StringJoinThreeInvocation"] | components["schemas"]["StringReplaceInvocation"] | components["schemas"]["StringSplitInvocation"] | components["schemas"]["StringSplitNegInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["T2IAdapterInvocation"] | components["schemas"]["TextLLMInvocation"] | components["schemas"]["TileToPropertiesInvocation"] | components["schemas"]["TiledMultiDiffusionDenoiseLatents"] | components["schemas"]["UnsharpMaskInvocation"] | components["schemas"]["VAELoaderInvocation"] | components["schemas"]["ZImageControlInvocation"] | components["schemas"]["ZImageDenoiseInvocation"] | components["schemas"]["ZImageDenoiseMetaInvocation"] | components["schemas"]["ZImageImageToLatentsInvocation"] | components["schemas"]["ZImageLatentsToImageInvocation"] | components["schemas"]["ZImageLoRACollectionLoader"] | components["schemas"]["ZImageLoRALoaderInvocation"] | components["schemas"]["ZImageModelLoaderInvocation"] | components["schemas"]["ZImageSeedVarianceEnhancerInvocation"] | components["schemas"]["ZImageTextEncoderInvocation"];+ invocation: components["schemas"]["AddInvocation"] | components["schemas"]["AlibabaCloudImageGenerationInvocation"] | components["schemas"]["AlphaMaskToTensorInvocation"] | components["schemas"]["AnimaDenoiseInvocation"] | components["schemas"]["AnimaImageToLatentsInvocation"] | components["schemas"]["AnimaLatentsToImageInvocation"] | components["schemas"]["AnimaLoRACollectionLoader"] | components["schemas"]["AnimaLoRALoaderInvocation"] | components["schemas"]["AnimaModelLoaderInvocation"] | components["schemas"]["AnimaTextEncoderInvocation"] | components["schemas"]["ApplyMaskTensorToImageInvocation"] | components["schemas"]["ApplyMaskToImageInvocation"] | components["schemas"]["BlankImageInvocation"] | components["schemas"]["BlendLatentsInvocation"] | components["schemas"]["BooleanCollectionInvocation"] | components["schemas"]["BooleanInvocation"] | components["schemas"]["BoundingBoxInvocation"] | components["schemas"]["CLIPSkipInvocation"] | components["schemas"]["CV2InfillInvocation"] | components["schemas"]["CalculateImageTilesEvenSplitInvocation"] | components["schemas"]["CalculateImageTilesInvocation"] | components["schemas"]["CalculateImageTilesMinimumOverlapInvocation"] | components["schemas"]["CallSavedWorkflowInvocation"] | components["schemas"]["CannyEdgeDetectionInvocation"] | components["schemas"]["CanvasOutputInvocation"] | components["schemas"]["CanvasPasteBackInvocation"] | components["schemas"]["CanvasV2MaskAndCropInvocation"] | components["schemas"]["CenterPadCropInvocation"] | components["schemas"]["CogView4DenoiseInvocation"] | components["schemas"]["CogView4ImageToLatentsInvocation"] | components["schemas"]["CogView4LatentsToImageInvocation"] | components["schemas"]["CogView4ModelLoaderInvocation"] | components["schemas"]["CogView4TextEncoderInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["ColorCorrectInvocation"] | components["schemas"]["ColorInvocation"] | components["schemas"]["ColorMapInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["ConditioningCollectionInvocation"] | components["schemas"]["ConditioningInvocation"] | components["schemas"]["ContentShuffleInvocation"] | components["schemas"]["ControlNetInvocation"] | components["schemas"]["CoreMetadataInvocation"] | components["schemas"]["CreateDenoiseMaskInvocation"] | components["schemas"]["CreateGradientMaskInvocation"] | components["schemas"]["CropImageToBoundingBoxInvocation"] | components["schemas"]["CropLatentsCoreInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["DWOpenposeDetectionInvocation"] | components["schemas"]["DecodeInvisibleWatermarkInvocation"] | components["schemas"]["DenoiseLatentsInvocation"] | components["schemas"]["DenoiseLatentsMetaInvocation"] | components["schemas"]["DepthAnythingDepthEstimationInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["ExpandMaskWithFadeInvocation"] | components["schemas"]["FLUXLoRACollectionLoader"] | components["schemas"]["FaceIdentifierInvocation"] | components["schemas"]["FaceMaskInvocation"] | components["schemas"]["FaceOffInvocation"] | components["schemas"]["FloatBatchInvocation"] | components["schemas"]["FloatCollectionInvocation"] | components["schemas"]["FloatGenerator"] | components["schemas"]["FloatInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["FloatMathInvocation"] | components["schemas"]["FloatToIntegerInvocation"] | components["schemas"]["Flux2DenoiseInvocation"] | components["schemas"]["Flux2KleinLoRACollectionLoader"] | components["schemas"]["Flux2KleinLoRALoaderInvocation"] | components["schemas"]["Flux2KleinModelLoaderInvocation"] | components["schemas"]["Flux2KleinTextEncoderInvocation"] | components["schemas"]["Flux2VaeDecodeInvocation"] | components["schemas"]["Flux2VaeEncodeInvocation"] | components["schemas"]["FluxControlLoRALoaderInvocation"] | components["schemas"]["FluxControlNetInvocation"] | components["schemas"]["FluxDenoiseInvocation"] | components["schemas"]["FluxDenoiseLatentsMetaInvocation"] | components["schemas"]["FluxFillInvocation"] | components["schemas"]["FluxIPAdapterInvocation"] | components["schemas"]["FluxKontextConcatenateImagesInvocation"] | components["schemas"]["FluxKontextInvocation"] | components["schemas"]["FluxLoRALoaderInvocation"] | components["schemas"]["FluxModelLoaderInvocation"] | components["schemas"]["FluxReduxInvocation"] | components["schemas"]["FluxTextEncoderInvocation"] | components["schemas"]["FluxVaeDecodeInvocation"] | components["schemas"]["FluxVaeEncodeInvocation"] | components["schemas"]["FreeUInvocation"] | components["schemas"]["GeminiImageGenerationInvocation"] | components["schemas"]["GetMaskBoundingBoxInvocation"] | components["schemas"]["GroundingDinoInvocation"] | components["schemas"]["HEDEdgeDetectionInvocation"] | components["schemas"]["HeuristicResizeInvocation"] | components["schemas"]["IPAdapterInvocation"] | components["schemas"]["IdealSizeInvocation"] | components["schemas"]["IfInvocation"] | components["schemas"]["ImageBatchInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageChannelMultiplyInvocation"] | components["schemas"]["ImageChannelOffsetInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImageGenerator"] | components["schemas"]["ImageHueAdjustmentInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageMaskToTensorInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageNoiseInvocation"] | components["schemas"]["ImagePanelLayoutInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["IntegerBatchInvocation"] | components["schemas"]["IntegerCollectionInvocation"] | components["schemas"]["IntegerGenerator"] | components["schemas"]["IntegerInvocation"] | components["schemas"]["IntegerMathInvocation"] | components["schemas"]["InvertTensorMaskInvocation"] | components["schemas"]["InvokeAdjustImageHuePlusInvocation"] | components["schemas"]["InvokeEquivalentAchromaticLightnessInvocation"] | components["schemas"]["InvokeImageBlendInvocation"] | components["schemas"]["InvokeImageCompositorInvocation"] | components["schemas"]["InvokeImageDilateOrErodeInvocation"] | components["schemas"]["InvokeImageEnhanceInvocation"] | components["schemas"]["InvokeImageValueThresholdsInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["LaMaInfillInvocation"] | components["schemas"]["LatentsCollectionInvocation"] | components["schemas"]["LatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["LineartAnimeEdgeDetectionInvocation"] | components["schemas"]["LineartEdgeDetectionInvocation"] | components["schemas"]["LlavaOnevisionVllmInvocation"] | components["schemas"]["LoRACollectionLoader"] | components["schemas"]["LoRALoaderInvocation"] | components["schemas"]["LoRASelectorInvocation"] | components["schemas"]["MLSDDetectionInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["MaskCombineInvocation"] | components["schemas"]["MaskEdgeInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["MaskFromIDInvocation"] | components["schemas"]["MaskTensorToImageInvocation"] | components["schemas"]["MediaPipeFaceDetectionInvocation"] | components["schemas"]["MergeMetadataInvocation"] | components["schemas"]["MergeTilesToImageInvocation"] | components["schemas"]["MetadataFieldExtractorInvocation"] | components["schemas"]["MetadataFromImageInvocation"] | components["schemas"]["MetadataInvocation"] | components["schemas"]["MetadataItemInvocation"] | components["schemas"]["MetadataItemLinkedInvocation"] | components["schemas"]["MetadataToBoolCollectionInvocation"] | components["schemas"]["MetadataToBoolInvocation"] | components["schemas"]["MetadataToControlnetsInvocation"] | components["schemas"]["MetadataToFloatCollectionInvocation"] | components["schemas"]["MetadataToFloatInvocation"] | components["schemas"]["MetadataToIPAdaptersInvocation"] | components["schemas"]["MetadataToIntegerCollectionInvocation"] | components["schemas"]["MetadataToIntegerInvocation"] | components["schemas"]["MetadataToLorasCollectionInvocation"] | components["schemas"]["MetadataToLorasInvocation"] | components["schemas"]["MetadataToModelInvocation"] | components["schemas"]["MetadataToSDXLLorasInvocation"] | components["schemas"]["MetadataToSDXLModelInvocation"] | components["schemas"]["MetadataToSchedulerInvocation"] | components["schemas"]["MetadataToStringCollectionInvocation"] | components["schemas"]["MetadataToStringInvocation"] | components["schemas"]["MetadataToT2IAdaptersInvocation"] | components["schemas"]["MetadataToVAEInvocation"] | components["schemas"]["ModelIdentifierInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["NormalMapInvocation"] | components["schemas"]["OklabUnsharpMaskInvocation"] | components["schemas"]["OklchImageHueAdjustmentInvocation"] | components["schemas"]["OpenAIImageGenerationInvocation"] | components["schemas"]["PBRMapsInvocation"] | components["schemas"]["PairTileImageInvocation"] | components["schemas"]["PasteImageIntoBoundingBoxInvocation"] | components["schemas"]["PiDiNetEdgeDetectionInvocation"] | components["schemas"]["PromptTemplateInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["QwenImageDenoiseInvocation"] | components["schemas"]["QwenImageImageToLatentsInvocation"] | components["schemas"]["QwenImageLatentsToImageInvocation"] | components["schemas"]["QwenImageLoRACollectionLoader"] | components["schemas"]["QwenImageLoRALoaderInvocation"] | components["schemas"]["QwenImageModelLoaderInvocation"] | components["schemas"]["QwenImageTextEncoderInvocation"] | components["schemas"]["RandomFloatInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RectangleMaskInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["RoundInvocation"] | components["schemas"]["SD3DenoiseInvocation"] | components["schemas"]["SD3ImageToLatentsInvocation"] | components["schemas"]["SD3LatentsToImageInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLLoRACollectionLoader"] | components["schemas"]["SDXLLoRALoaderInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SaveImageInvocation"] | components["schemas"]["SaveImageToFileInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["SchedulerInvocation"] | components["schemas"]["Sd3ModelLoaderInvocation"] | components["schemas"]["Sd3TextEncoderInvocation"] | components["schemas"]["SeamlessModeInvocation"] | components["schemas"]["SeedreamImageGenerationInvocation"] | components["schemas"]["SegmentAnythingInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["SpandrelImageToImageAutoscaleInvocation"] | components["schemas"]["SpandrelImageToImageInvocation"] | components["schemas"]["StringBatchInvocation"] | components["schemas"]["StringCollectionInvocation"] | components["schemas"]["StringGenerator"] | components["schemas"]["StringInvocation"] | components["schemas"]["StringJoinInvocation"] | components["schemas"]["StringJoinThreeInvocation"] | components["schemas"]["StringReplaceInvocation"] | components["schemas"]["StringSplitInvocation"] | components["schemas"]["StringSplitNegInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["T2IAdapterInvocation"] | components["schemas"]["TextLLMInvocation"] | components["schemas"]["TileToPropertiesInvocation"] | components["schemas"]["TiledMultiDiffusionDenoiseLatents"] | components["schemas"]["UnsharpMaskInvocation"] | components["schemas"]["VAELoaderInvocation"] | components["schemas"]["WorkflowReturnGetInvocation"] | components["schemas"]["WorkflowReturnInvocation"] | components["schemas"]["WorkflowReturnValueInvocation"] | components["schemas"]["ZImageControlInvocation"] | components["schemas"]["ZImageDenoiseInvocation"] | components["schemas"]["ZImageDenoiseMetaInvocation"] | components["schemas"]["ZImageImageToLatentsInvocation"] | components["schemas"]["ZImageLatentsToImageInvocation"] | components["schemas"]["ZImageLoRACollectionLoader"] | components["schemas"]["ZImageLoRALoaderInvocation"] | components["schemas"]["ZImageModelLoaderInvocation"] | components["schemas"]["ZImageSeedVarianceEnhancerInvocation"] | components["schemas"]["ZImageTextEncoderInvocation"];/*** Invocation Source Id* @description The ID of the prepared invocation's source node@@ -15895,6 +15967,7 @@ export type components = {calculate_image_tiles: components["schemas"]["CalculateImageTilesOutput"];calculate_image_tiles_even_split: components["schemas"]["CalculateImageTilesOutput"];calculate_image_tiles_min_overlap: components["schemas"]["CalculateImageTilesOutput"];+ call_saved_workflow: components["schemas"]["WorkflowReturnOutput"];canny_edge_detection: components["schemas"]["ImageOutput"];canvas_output: components["schemas"]["ImageOutput"];canvas_paste_back: components["schemas"]["ImageOutput"];@@ -16121,6 +16194,9 @@ export type components = {unsharp_mask: components["schemas"]["ImageOutput"];unsharp_mask_oklab: components["schemas"]["ImageOutput"];vae_loader: components["schemas"]["VAEOutput"];+ workflow_return: components["schemas"]["WorkflowReturnOutput"];+ workflow_return_get: components["schemas"]["WorkflowReturnGetOutput"];+ workflow_return_value: components["schemas"]["WorkflowReturnValueOutput"];z_image_control: components["schemas"]["ZImageControlOutput"];z_image_denoise: components["schemas"]["LatentsOutput"];z_image_denoise_meta: components["schemas"]["LatentsMetaOutput"];@@ -16184,7 +16260,7 @@ export type components = {* Invocation* @description The ID of the invocation*/- invocation: components["schemas"]["AddInvocation"] | components["schemas"]["AlibabaCloudImageGenerationInvocation"] | components["schemas"]["AlphaMaskToTensorInvocation"] | components["schemas"]["AnimaDenoiseInvocation"] | components["schemas"]["AnimaImageToLatentsInvocation"] | components["schemas"]["AnimaLatentsToImageInvocation"] | components["schemas"]["AnimaLoRACollectionLoader"] | components["schemas"]["AnimaLoRALoaderInvocation"] | components["schemas"]["AnimaModelLoaderInvocation"] | components["schemas"]["AnimaTextEncoderInvocation"] | components["schemas"]["ApplyMaskTensorToImageInvocation"] | components["schemas"]["ApplyMaskToImageInvocation"] | components["schemas"]["BlankImageInvocation"] | components["schemas"]["BlendLatentsInvocation"] | components["schemas"]["BooleanCollectionInvocation"] | components["schemas"]["BooleanInvocation"] | components["schemas"]["BoundingBoxInvocation"] | components["schemas"]["CLIPSkipInvocation"] | components["schemas"]["CV2InfillInvocation"] | components["schemas"]["CalculateImageTilesEvenSplitInvocation"] | components["schemas"]["CalculateImageTilesInvocation"] | components["schemas"]["CalculateImageTilesMinimumOverlapInvocation"] | components["schemas"]["CannyEdgeDetectionInvocation"] | components["schemas"]["CanvasOutputInvocation"] | components["schemas"]["CanvasPasteBackInvocation"] | components["schemas"]["CanvasV2MaskAndCropInvocation"] | components["schemas"]["CenterPadCropInvocation"] | components["schemas"]["CogView4DenoiseInvocation"] | components["schemas"]["CogView4ImageToLatentsInvocation"] | components["schemas"]["CogView4LatentsToImageInvocation"] | components["schemas"]["CogView4ModelLoaderInvocation"] | components["schemas"]["CogView4TextEncoderInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["ColorCorrectInvocation"] | components["schemas"]["ColorInvocation"] | components["schemas"]["ColorMapInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["ConditioningCollectionInvocation"] | components["schemas"]["ConditioningInvocation"] | components["schemas"]["ContentShuffleInvocation"] | components["schemas"]["ControlNetInvocation"] | components["schemas"]["CoreMetadataInvocation"] | components["schemas"]["CreateDenoiseMaskInvocation"] | components["schemas"]["CreateGradientMaskInvocation"] | components["schemas"]["CropImageToBoundingBoxInvocation"] | components["schemas"]["CropLatentsCoreInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["DWOpenposeDetectionInvocation"] | components["schemas"]["DecodeInvisibleWatermarkInvocation"] | components["schemas"]["DenoiseLatentsInvocation"] | components["schemas"]["DenoiseLatentsMetaInvocation"] | components["schemas"]["DepthAnythingDepthEstimationInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["ExpandMaskWithFadeInvocation"] | components["schemas"]["FLUXLoRACollectionLoader"] | components["schemas"]["FaceIdentifierInvocation"] | components["schemas"]["FaceMaskInvocation"] | components["schemas"]["FaceOffInvocation"] | components["schemas"]["FloatBatchInvocation"] | components["schemas"]["FloatCollectionInvocation"] | components["schemas"]["FloatGenerator"] | components["schemas"]["FloatInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["FloatMathInvocation"] | components["schemas"]["FloatToIntegerInvocation"] | components["schemas"]["Flux2DenoiseInvocation"] | components["schemas"]["Flux2KleinLoRACollectionLoader"] | components["schemas"]["Flux2KleinLoRALoaderInvocation"] | components["schemas"]["Flux2KleinModelLoaderInvocation"] | components["schemas"]["Flux2KleinTextEncoderInvocation"] | components["schemas"]["Flux2VaeDecodeInvocation"] | components["schemas"]["Flux2VaeEncodeInvocation"] | components["schemas"]["FluxControlLoRALoaderInvocation"] | components["schemas"]["FluxControlNetInvocation"] | components["schemas"]["FluxDenoiseInvocation"] | components["schemas"]["FluxDenoiseLatentsMetaInvocation"] | components["schemas"]["FluxFillInvocation"] | components["schemas"]["FluxIPAdapterInvocation"] | components["schemas"]["FluxKontextConcatenateImagesInvocation"] | components["schemas"]["FluxKontextInvocation"] | components["schemas"]["FluxLoRALoaderInvocation"] | components["schemas"]["FluxModelLoaderInvocation"] | components["schemas"]["FluxReduxInvocation"] | components["schemas"]["FluxTextEncoderInvocation"] | components["schemas"]["FluxVaeDecodeInvocation"] | components["schemas"]["FluxVaeEncodeInvocation"] | components["schemas"]["FreeUInvocation"] | components["schemas"]["GeminiImageGenerationInvocation"] | components["schemas"]["GetMaskBoundingBoxInvocation"] | components["schemas"]["GroundingDinoInvocation"] | components["schemas"]["HEDEdgeDetectionInvocation"] | components["schemas"]["HeuristicResizeInvocation"] | components["schemas"]["IPAdapterInvocation"] | components["schemas"]["IdealSizeInvocation"] | components["schemas"]["IfInvocation"] | components["schemas"]["ImageBatchInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageChannelMultiplyInvocation"] | components["schemas"]["ImageChannelOffsetInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImageGenerator"] | components["schemas"]["ImageHueAdjustmentInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageMaskToTensorInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageNoiseInvocation"] | components["schemas"]["ImagePanelLayoutInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["IntegerBatchInvocation"] | components["schemas"]["IntegerCollectionInvocation"] | components["schemas"]["IntegerGenerator"] | components["schemas"]["IntegerInvocation"] | components["schemas"]["IntegerMathInvocation"] | components["schemas"]["InvertTensorMaskInvocation"] | components["schemas"]["InvokeAdjustImageHuePlusInvocation"] | components["schemas"]["InvokeEquivalentAchromaticLightnessInvocation"] | components["schemas"]["InvokeImageBlendInvocation"] | components["schemas"]["InvokeImageCompositorInvocation"] | components["schemas"]["InvokeImageDilateOrErodeInvocation"] | components["schemas"]["InvokeImageEnhanceInvocation"] | components["schemas"]["InvokeImageValueThresholdsInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["LaMaInfillInvocation"] | components["schemas"]["LatentsCollectionInvocation"] | components["schemas"]["LatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["LineartAnimeEdgeDetectionInvocation"] | components["schemas"]["LineartEdgeDetectionInvocation"] | components["schemas"]["LlavaOnevisionVllmInvocation"] | components["schemas"]["LoRACollectionLoader"] | components["schemas"]["LoRALoaderInvocation"] | components["schemas"]["LoRASelectorInvocation"] | components["schemas"]["MLSDDetectionInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["MaskCombineInvocation"] | components["schemas"]["MaskEdgeInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["MaskFromIDInvocation"] | components["schemas"]["MaskTensorToImageInvocation"] | components["schemas"]["MediaPipeFaceDetectionInvocation"] | components["schemas"]["MergeMetadataInvocation"] | components["schemas"]["MergeTilesToImageInvocation"] | components["schemas"]["MetadataFieldExtractorInvocation"] | components["schemas"]["MetadataFromImageInvocation"] | components["schemas"]["MetadataInvocation"] | components["schemas"]["MetadataItemInvocation"] | components["schemas"]["MetadataItemLinkedInvocation"] | components["schemas"]["MetadataToBoolCollectionInvocation"] | components["schemas"]["MetadataToBoolInvocation"] | components["schemas"]["MetadataToControlnetsInvocation"] | components["schemas"]["MetadataToFloatCollectionInvocation"] | components["schemas"]["MetadataToFloatInvocation"] | components["schemas"]["MetadataToIPAdaptersInvocation"] | components["schemas"]["MetadataToIntegerCollectionInvocation"] | components["schemas"]["MetadataToIntegerInvocation"] | components["schemas"]["MetadataToLorasCollectionInvocation"] | components["schemas"]["MetadataToLorasInvocation"] | components["schemas"]["MetadataToModelInvocation"] | components["schemas"]["MetadataToSDXLLorasInvocation"] | components["schemas"]["MetadataToSDXLModelInvocation"] | components["schemas"]["MetadataToSchedulerInvocation"] | components["schemas"]["MetadataToStringCollectionInvocation"] | components["schemas"]["MetadataToStringInvocation"] | components["schemas"]["MetadataToT2IAdaptersInvocation"] | components["schemas"]["MetadataToVAEInvocation"] | components["schemas"]["ModelIdentifierInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["NormalMapInvocation"] | components["schemas"]["OklabUnsharpMaskInvocation"] | components["schemas"]["OklchImageHueAdjustmentInvocation"] | components["schemas"]["OpenAIImageGenerationInvocation"] | components["schemas"]["PBRMapsInvocation"] | components["schemas"]["PairTileImageInvocation"] | components["schemas"]["PasteImageIntoBoundingBoxInvocation"] | components["schemas"]["PiDiNetEdgeDetectionInvocation"] | components["schemas"]["PromptTemplateInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["QwenImageDenoiseInvocation"] | components["schemas"]["QwenImageImageToLatentsInvocation"] | components["schemas"]["QwenImageLatentsToImageInvocation"] | components["schemas"]["QwenImageLoRACollectionLoader"] | components["schemas"]["QwenImageLoRALoaderInvocation"] | components["schemas"]["QwenImageModelLoaderInvocation"] | components["schemas"]["QwenImageTextEncoderInvocation"] | components["schemas"]["RandomFloatInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RectangleMaskInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["RoundInvocation"] | components["schemas"]["SD3DenoiseInvocation"] | components["schemas"]["SD3ImageToLatentsInvocation"] | components["schemas"]["SD3LatentsToImageInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLLoRACollectionLoader"] | components["schemas"]["SDXLLoRALoaderInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SaveImageInvocation"] | components["schemas"]["SaveImageToFileInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["SchedulerInvocation"] | components["schemas"]["Sd3ModelLoaderInvocation"] | components["schemas"]["Sd3TextEncoderInvocation"] | components["schemas"]["SeamlessModeInvocation"] | components["schemas"]["SeedreamImageGenerationInvocation"] | components["schemas"]["SegmentAnythingInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["SpandrelImageToImageAutoscaleInvocation"] | components["schemas"]["SpandrelImageToImageInvocation"] | components["schemas"]["StringBatchInvocation"] | components["schemas"]["StringCollectionInvocation"] | components["schemas"]["StringGenerator"] | components["schemas"]["StringInvocation"] | components["schemas"]["StringJoinInvocation"] | components["schemas"]["StringJoinThreeInvocation"] | components["schemas"]["StringReplaceInvocation"] | components["schemas"]["StringSplitInvocation"] | components["schemas"]["StringSplitNegInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["T2IAdapterInvocation"] | components["schemas"]["TextLLMInvocation"] | components["schemas"]["TileToPropertiesInvocation"] | components["schemas"]["TiledMultiDiffusionDenoiseLatents"] | components["schemas"]["UnsharpMaskInvocation"] | components["schemas"]["VAELoaderInvocation"] | components["schemas"]["ZImageControlInvocation"] | components["schemas"]["ZImageDenoiseInvocation"] | components["schemas"]["ZImageDenoiseMetaInvocation"] | components["schemas"]["ZImageImageToLatentsInvocation"] | components["schemas"]["ZImageLatentsToImageInvocation"] | components["schemas"]["ZImageLoRACollectionLoader"] | components["schemas"]["ZImageLoRALoaderInvocation"] | components["schemas"]["ZImageModelLoaderInvocation"] | components["schemas"]["ZImageSeedVarianceEnhancerInvocation"] | components["schemas"]["ZImageTextEncoderInvocation"];+ invocation: components["schemas"]["AddInvocation"] | components["schemas"]["AlibabaCloudImageGenerationInvocation"] | components["schemas"]["AlphaMaskToTensorInvocation"] | components["schemas"]["AnimaDenoiseInvocation"] | components["schemas"]["AnimaImageToLatentsInvocation"] | components["schemas"]["AnimaLatentsToImageInvocation"] | components["schemas"]["AnimaLoRACollectionLoader"] | components["schemas"]["AnimaLoRALoaderInvocation"] | components["schemas"]["AnimaModelLoaderInvocation"] | components["schemas"]["AnimaTextEncoderInvocation"] | components["schemas"]["ApplyMaskTensorToImageInvocation"] | components["schemas"]["ApplyMaskToImageInvocation"] | components["schemas"]["BlankImageInvocation"] | components["schemas"]["BlendLatentsInvocation"] | components["schemas"]["BooleanCollectionInvocation"] | components["schemas"]["BooleanInvocation"] | components["schemas"]["BoundingBoxInvocation"] | components["schemas"]["CLIPSkipInvocation"] | components["schemas"]["CV2InfillInvocation"] | components["schemas"]["CalculateImageTilesEvenSplitInvocation"] | components["schemas"]["CalculateImageTilesInvocation"] | components["schemas"]["CalculateImageTilesMinimumOverlapInvocation"] | components["schemas"]["CallSavedWorkflowInvocation"] | components["schemas"]["CannyEdgeDetectionInvocation"] | components["schemas"]["CanvasOutputInvocation"] | components["schemas"]["CanvasPasteBackInvocation"] | components["schemas"]["CanvasV2MaskAndCropInvocation"] | components["schemas"]["CenterPadCropInvocation"] | components["schemas"]["CogView4DenoiseInvocation"] | components["schemas"]["CogView4ImageToLatentsInvocation"] | components["schemas"]["CogView4LatentsToImageInvocation"] | components["schemas"]["CogView4ModelLoaderInvocation"] | components["schemas"]["CogView4TextEncoderInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["ColorCorrectInvocation"] | components["schemas"]["ColorInvocation"] | components["schemas"]["ColorMapInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["ConditioningCollectionInvocation"] | components["schemas"]["ConditioningInvocation"] | components["schemas"]["ContentShuffleInvocation"] | components["schemas"]["ControlNetInvocation"] | components["schemas"]["CoreMetadataInvocation"] | components["schemas"]["CreateDenoiseMaskInvocation"] | components["schemas"]["CreateGradientMaskInvocation"] | components["schemas"]["CropImageToBoundingBoxInvocation"] | components["schemas"]["CropLatentsCoreInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["DWOpenposeDetectionInvocation"] | components["schemas"]["DecodeInvisibleWatermarkInvocation"] | components["schemas"]["DenoiseLatentsInvocation"] | components["schemas"]["DenoiseLatentsMetaInvocation"] | components["schemas"]["DepthAnythingDepthEstimationInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["ExpandMaskWithFadeInvocation"] | components["schemas"]["FLUXLoRACollectionLoader"] | components["schemas"]["FaceIdentifierInvocation"] | components["schemas"]["FaceMaskInvocation"] | components["schemas"]["FaceOffInvocation"] | components["schemas"]["FloatBatchInvocation"] | components["schemas"]["FloatCollectionInvocation"] | components["schemas"]["FloatGenerator"] | components["schemas"]["FloatInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["FloatMathInvocation"] | components["schemas"]["FloatToIntegerInvocation"] | components["schemas"]["Flux2DenoiseInvocation"] | components["schemas"]["Flux2KleinLoRACollectionLoader"] | components["schemas"]["Flux2KleinLoRALoaderInvocation"] | components["schemas"]["Flux2KleinModelLoaderInvocation"] | components["schemas"]["Flux2KleinTextEncoderInvocation"] | components["schemas"]["Flux2VaeDecodeInvocation"] | components["schemas"]["Flux2VaeEncodeInvocation"] | components["schemas"]["FluxControlLoRALoaderInvocation"] | components["schemas"]["FluxControlNetInvocation"] | components["schemas"]["FluxDenoiseInvocation"] | components["schemas"]["FluxDenoiseLatentsMetaInvocation"] | components["schemas"]["FluxFillInvocation"] | components["schemas"]["FluxIPAdapterInvocation"] | components["schemas"]["FluxKontextConcatenateImagesInvocation"] | components["schemas"]["FluxKontextInvocation"] | components["schemas"]["FluxLoRALoaderInvocation"] | components["schemas"]["FluxModelLoaderInvocation"] | components["schemas"]["FluxReduxInvocation"] | components["schemas"]["FluxTextEncoderInvocation"] | components["schemas"]["FluxVaeDecodeInvocation"] | components["schemas"]["FluxVaeEncodeInvocation"] | components["schemas"]["FreeUInvocation"] | components["schemas"]["GeminiImageGenerationInvocation"] | components["schemas"]["GetMaskBoundingBoxInvocation"] | components["schemas"]["GroundingDinoInvocation"] | components["schemas"]["HEDEdgeDetectionInvocation"] | components["schemas"]["HeuristicResizeInvocation"] | components["schemas"]["IPAdapterInvocation"] | components["schemas"]["IdealSizeInvocation"] | components["schemas"]["IfInvocation"] | components["schemas"]["ImageBatchInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageChannelMultiplyInvocation"] | components["schemas"]["ImageChannelOffsetInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImageGenerator"] | components["schemas"]["ImageHueAdjustmentInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageMaskToTensorInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageNoiseInvocation"] | components["schemas"]["ImagePanelLayoutInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["IntegerBatchInvocation"] | components["schemas"]["IntegerCollectionInvocation"] | components["schemas"]["IntegerGenerator"] | components["schemas"]["IntegerInvocation"] | components["schemas"]["IntegerMathInvocation"] | components["schemas"]["InvertTensorMaskInvocation"] | components["schemas"]["InvokeAdjustImageHuePlusInvocation"] | components["schemas"]["InvokeEquivalentAchromaticLightnessInvocation"] | components["schemas"]["InvokeImageBlendInvocation"] | components["schemas"]["InvokeImageCompositorInvocation"] | components["schemas"]["InvokeImageDilateOrErodeInvocation"] | components["schemas"]["InvokeImageEnhanceInvocation"] | components["schemas"]["InvokeImageValueThresholdsInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["LaMaInfillInvocation"] | components["schemas"]["LatentsCollectionInvocation"] | components["schemas"]["LatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["LineartAnimeEdgeDetectionInvocation"] | components["schemas"]["LineartEdgeDetectionInvocation"] | components["schemas"]["LlavaOnevisionVllmInvocation"] | components["schemas"]["LoRACollectionLoader"] | components["schemas"]["LoRALoaderInvocation"] | components["schemas"]["LoRASelectorInvocation"] | components["schemas"]["MLSDDetectionInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["MaskCombineInvocation"] | components["schemas"]["MaskEdgeInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["MaskFromIDInvocation"] | components["schemas"]["MaskTensorToImageInvocation"] | components["schemas"]["MediaPipeFaceDetectionInvocation"] | components["schemas"]["MergeMetadataInvocation"] | components["schemas"]["MergeTilesToImageInvocation"] | components["schemas"]["MetadataFieldExtractorInvocation"] | components["schemas"]["MetadataFromImageInvocation"] | components["schemas"]["MetadataInvocation"] | components["schemas"]["MetadataItemInvocation"] | components["schemas"]["MetadataItemLinkedInvocation"] | components["schemas"]["MetadataToBoolCollectionInvocation"] | components["schemas"]["MetadataToBoolInvocation"] | components["schemas"]["MetadataToControlnetsInvocation"] | components["schemas"]["MetadataToFloatCollectionInvocation"] | components["schemas"]["MetadataToFloatInvocation"] | components["schemas"]["MetadataToIPAdaptersInvocation"] | components["schemas"]["MetadataToIntegerCollectionInvocation"] | components["schemas"]["MetadataToIntegerInvocation"] | components["schemas"]["MetadataToLorasCollectionInvocation"] | components["schemas"]["MetadataToLorasInvocation"] | components["schemas"]["MetadataToModelInvocation"] | components["schemas"]["MetadataToSDXLLorasInvocation"] | components["schemas"]["MetadataToSDXLModelInvocation"] | components["schemas"]["MetadataToSchedulerInvocation"] | components["schemas"]["MetadataToStringCollectionInvocation"] | components["schemas"]["MetadataToStringInvocation"] | components["schemas"]["MetadataToT2IAdaptersInvocation"] | components["schemas"]["MetadataToVAEInvocation"] | components["schemas"]["ModelIdentifierInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["NormalMapInvocation"] | components["schemas"]["OklabUnsharpMaskInvocation"] | components["schemas"]["OklchImageHueAdjustmentInvocation"] | components["schemas"]["OpenAIImageGenerationInvocation"] | components["schemas"]["PBRMapsInvocation"] | components["schemas"]["PairTileImageInvocation"] | components["schemas"]["PasteImageIntoBoundingBoxInvocation"] | components["schemas"]["PiDiNetEdgeDetectionInvocation"] | components["schemas"]["PromptTemplateInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["QwenImageDenoiseInvocation"] | components["schemas"]["QwenImageImageToLatentsInvocation"] | components["schemas"]["QwenImageLatentsToImageInvocation"] | components["schemas"]["QwenImageLoRACollectionLoader"] | components["schemas"]["QwenImageLoRALoaderInvocation"] | components["schemas"]["QwenImageModelLoaderInvocation"] | components["schemas"]["QwenImageTextEncoderInvocation"] | components["schemas"]["RandomFloatInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RectangleMaskInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["RoundInvocation"] | components["schemas"]["SD3DenoiseInvocation"] | components["schemas"]["SD3ImageToLatentsInvocation"] | components["schemas"]["SD3LatentsToImageInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLLoRACollectionLoader"] | components["schemas"]["SDXLLoRALoaderInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SaveImageInvocation"] | components["schemas"]["SaveImageToFileInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["SchedulerInvocation"] | components["schemas"]["Sd3ModelLoaderInvocation"] | components["schemas"]["Sd3TextEncoderInvocation"] | components["schemas"]["SeamlessModeInvocation"] | components["schemas"]["SeedreamImageGenerationInvocation"] | components["schemas"]["SegmentAnythingInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["SpandrelImageToImageAutoscaleInvocation"] | components["schemas"]["SpandrelImageToImageInvocation"] | components["schemas"]["StringBatchInvocation"] | components["schemas"]["StringCollectionInvocation"] | components["schemas"]["StringGenerator"] | components["schemas"]["StringInvocation"] | components["schemas"]["StringJoinInvocation"] | components["schemas"]["StringJoinThreeInvocation"] | components["schemas"]["StringReplaceInvocation"] | components["schemas"]["StringSplitInvocation"] | components["schemas"]["StringSplitNegInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["T2IAdapterInvocation"] | components["schemas"]["TextLLMInvocation"] | components["schemas"]["TileToPropertiesInvocation"] | components["schemas"]["TiledMultiDiffusionDenoiseLatents"] | components["schemas"]["UnsharpMaskInvocation"] | components["schemas"]["VAELoaderInvocation"] | components["schemas"]["WorkflowReturnGetInvocation"] | components["schemas"]["WorkflowReturnInvocation"] | components["schemas"]["WorkflowReturnValueInvocation"] | components["schemas"]["ZImageControlInvocation"] | components["schemas"]["ZImageDenoiseInvocation"] | components["schemas"]["ZImageDenoiseMetaInvocation"] | components["schemas"]["ZImageImageToLatentsInvocation"] | components["schemas"]["ZImageLatentsToImageInvocation"] | components["schemas"]["ZImageLoRACollectionLoader"] | components["schemas"]["ZImageLoRALoaderInvocation"] | components["schemas"]["ZImageModelLoaderInvocation"] | components["schemas"]["ZImageSeedVarianceEnhancerInvocation"] | components["schemas"]["ZImageTextEncoderInvocation"];/*** Invocation Source Id* @description The ID of the prepared invocation's source node@@ -16259,7 +16335,7 @@ export type components = {* Invocation* @description The ID of the invocation*/- invocation: components["schemas"]["AddInvocation"] | components["schemas"]["AlibabaCloudImageGenerationInvocation"] | components["schemas"]["AlphaMaskToTensorInvocation"] | components["schemas"]["AnimaDenoiseInvocation"] | components["schemas"]["AnimaImageToLatentsInvocation"] | components["schemas"]["AnimaLatentsToImageInvocation"] | components["schemas"]["AnimaLoRACollectionLoader"] | components["schemas"]["AnimaLoRALoaderInvocation"] | components["schemas"]["AnimaModelLoaderInvocation"] | components["schemas"]["AnimaTextEncoderInvocation"] | components["schemas"]["ApplyMaskTensorToImageInvocation"] | components["schemas"]["ApplyMaskToImageInvocation"] | components["schemas"]["BlankImageInvocation"] | components["schemas"]["BlendLatentsInvocation"] | components["schemas"]["BooleanCollectionInvocation"] | components["schemas"]["BooleanInvocation"] | components["schemas"]["BoundingBoxInvocation"] | components["schemas"]["CLIPSkipInvocation"] | components["schemas"]["CV2InfillInvocation"] | components["schemas"]["CalculateImageTilesEvenSplitInvocation"] | components["schemas"]["CalculateImageTilesInvocation"] | components["schemas"]["CalculateImageTilesMinimumOverlapInvocation"] | components["schemas"]["CannyEdgeDetectionInvocation"] | components["schemas"]["CanvasOutputInvocation"] | components["schemas"]["CanvasPasteBackInvocation"] | components["schemas"]["CanvasV2MaskAndCropInvocation"] | components["schemas"]["CenterPadCropInvocation"] | components["schemas"]["CogView4DenoiseInvocation"] | components["schemas"]["CogView4ImageToLatentsInvocation"] | components["schemas"]["CogView4LatentsToImageInvocation"] | components["schemas"]["CogView4ModelLoaderInvocation"] | components["schemas"]["CogView4TextEncoderInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["ColorCorrectInvocation"] | components["schemas"]["ColorInvocation"] | components["schemas"]["ColorMapInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["ConditioningCollectionInvocation"] | components["schemas"]["ConditioningInvocation"] | components["schemas"]["ContentShuffleInvocation"] | components["schemas"]["ControlNetInvocation"] | components["schemas"]["CoreMetadataInvocation"] | components["schemas"]["CreateDenoiseMaskInvocation"] | components["schemas"]["CreateGradientMaskInvocation"] | components["schemas"]["CropImageToBoundingBoxInvocation"] | components["schemas"]["CropLatentsCoreInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["DWOpenposeDetectionInvocation"] | components["schemas"]["DecodeInvisibleWatermarkInvocation"] | components["schemas"]["DenoiseLatentsInvocation"] | components["schemas"]["DenoiseLatentsMetaInvocation"] | components["schemas"]["DepthAnythingDepthEstimationInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["ExpandMaskWithFadeInvocation"] | components["schemas"]["FLUXLoRACollectionLoader"] | components["schemas"]["FaceIdentifierInvocation"] | components["schemas"]["FaceMaskInvocation"] | components["schemas"]["FaceOffInvocation"] | components["schemas"]["FloatBatchInvocation"] | components["schemas"]["FloatCollectionInvocation"] | components["schemas"]["FloatGenerator"] | components["schemas"]["FloatInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["FloatMathInvocation"] | components["schemas"]["FloatToIntegerInvocation"] | components["schemas"]["Flux2DenoiseInvocation"] | components["schemas"]["Flux2KleinLoRACollectionLoader"] | components["schemas"]["Flux2KleinLoRALoaderInvocation"] | components["schemas"]["Flux2KleinModelLoaderInvocation"] | components["schemas"]["Flux2KleinTextEncoderInvocation"] | components["schemas"]["Flux2VaeDecodeInvocation"] | components["schemas"]["Flux2VaeEncodeInvocation"] | components["schemas"]["FluxControlLoRALoaderInvocation"] | components["schemas"]["FluxControlNetInvocation"] | components["schemas"]["FluxDenoiseInvocation"] | components["schemas"]["FluxDenoiseLatentsMetaInvocation"] | components["schemas"]["FluxFillInvocation"] | components["schemas"]["FluxIPAdapterInvocation"] | components["schemas"]["FluxKontextConcatenateImagesInvocation"] | components["schemas"]["FluxKontextInvocation"] | components["schemas"]["FluxLoRALoaderInvocation"] | components["schemas"]["FluxModelLoaderInvocation"] | components["schemas"]["FluxReduxInvocation"] | components["schemas"]["FluxTextEncoderInvocation"] | components["schemas"]["FluxVaeDecodeInvocation"] | components["schemas"]["FluxVaeEncodeInvocation"] | components["schemas"]["FreeUInvocation"] | components["schemas"]["GeminiImageGenerationInvocation"] | components["schemas"]["GetMaskBoundingBoxInvocation"] | components["schemas"]["GroundingDinoInvocation"] | components["schemas"]["HEDEdgeDetectionInvocation"] | components["schemas"]["HeuristicResizeInvocation"] | components["schemas"]["IPAdapterInvocation"] | components["schemas"]["IdealSizeInvocation"] | components["schemas"]["IfInvocation"] | components["schemas"]["ImageBatchInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageChannelMultiplyInvocation"] | components["schemas"]["ImageChannelOffsetInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImageGenerator"] | components["schemas"]["ImageHueAdjustmentInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageMaskToTensorInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageNoiseInvocation"] | components["schemas"]["ImagePanelLayoutInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["IntegerBatchInvocation"] | components["schemas"]["IntegerCollectionInvocation"] | components["schemas"]["IntegerGenerator"] | components["schemas"]["IntegerInvocation"] | components["schemas"]["IntegerMathInvocation"] | components["schemas"]["InvertTensorMaskInvocation"] | components["schemas"]["InvokeAdjustImageHuePlusInvocation"] | components["schemas"]["InvokeEquivalentAchromaticLightnessInvocation"] | components["schemas"]["InvokeImageBlendInvocation"] | components["schemas"]["InvokeImageCompositorInvocation"] | components["schemas"]["InvokeImageDilateOrErodeInvocation"] | components["schemas"]["InvokeImageEnhanceInvocation"] | components["schemas"]["InvokeImageValueThresholdsInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["LaMaInfillInvocation"] | components["schemas"]["LatentsCollectionInvocation"] | components["schemas"]["LatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["LineartAnimeEdgeDetectionInvocation"] | components["schemas"]["LineartEdgeDetectionInvocation"] | components["schemas"]["LlavaOnevisionVllmInvocation"] | components["schemas"]["LoRACollectionLoader"] | components["schemas"]["LoRALoaderInvocation"] | components["schemas"]["LoRASelectorInvocation"] | components["schemas"]["MLSDDetectionInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["MaskCombineInvocation"] | components["schemas"]["MaskEdgeInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["MaskFromIDInvocation"] | components["schemas"]["MaskTensorToImageInvocation"] | components["schemas"]["MediaPipeFaceDetectionInvocation"] | components["schemas"]["MergeMetadataInvocation"] | components["schemas"]["MergeTilesToImageInvocation"] | components["schemas"]["MetadataFieldExtractorInvocation"] | components["schemas"]["MetadataFromImageInvocation"] | components["schemas"]["MetadataInvocation"] | components["schemas"]["MetadataItemInvocation"] | components["schemas"]["MetadataItemLinkedInvocation"] | components["schemas"]["MetadataToBoolCollectionInvocation"] | components["schemas"]["MetadataToBoolInvocation"] | components["schemas"]["MetadataToControlnetsInvocation"] | components["schemas"]["MetadataToFloatCollectionInvocation"] | components["schemas"]["MetadataToFloatInvocation"] | components["schemas"]["MetadataToIPAdaptersInvocation"] | components["schemas"]["MetadataToIntegerCollectionInvocation"] | components["schemas"]["MetadataToIntegerInvocation"] | components["schemas"]["MetadataToLorasCollectionInvocation"] | components["schemas"]["MetadataToLorasInvocation"] | components["schemas"]["MetadataToModelInvocation"] | components["schemas"]["MetadataToSDXLLorasInvocation"] | components["schemas"]["MetadataToSDXLModelInvocation"] | components["schemas"]["MetadataToSchedulerInvocation"] | components["schemas"]["MetadataToStringCollectionInvocation"] | components["schemas"]["MetadataToStringInvocation"] | components["schemas"]["MetadataToT2IAdaptersInvocation"] | components["schemas"]["MetadataToVAEInvocation"] | components["schemas"]["ModelIdentifierInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["NormalMapInvocation"] | components["schemas"]["OklabUnsharpMaskInvocation"] | components["schemas"]["OklchImageHueAdjustmentInvocation"] | components["schemas"]["OpenAIImageGenerationInvocation"] | components["schemas"]["PBRMapsInvocation"] | components["schemas"]["PairTileImageInvocation"] | components["schemas"]["PasteImageIntoBoundingBoxInvocation"] | components["schemas"]["PiDiNetEdgeDetectionInvocation"] | components["schemas"]["PromptTemplateInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["QwenImageDenoiseInvocation"] | components["schemas"]["QwenImageImageToLatentsInvocation"] | components["schemas"]["QwenImageLatentsToImageInvocation"] | components["schemas"]["QwenImageLoRACollectionLoader"] | components["schemas"]["QwenImageLoRALoaderInvocation"] | components["schemas"]["QwenImageModelLoaderInvocation"] | components["schemas"]["QwenImageTextEncoderInvocation"] | components["schemas"]["RandomFloatInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RectangleMaskInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["RoundInvocation"] | components["schemas"]["SD3DenoiseInvocation"] | components["schemas"]["SD3ImageToLatentsInvocation"] | components["schemas"]["SD3LatentsToImageInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLLoRACollectionLoader"] | components["schemas"]["SDXLLoRALoaderInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SaveImageInvocation"] | components["schemas"]["SaveImageToFileInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["SchedulerInvocation"] | components["schemas"]["Sd3ModelLoaderInvocation"] | components["schemas"]["Sd3TextEncoderInvocation"] | components["schemas"]["SeamlessModeInvocation"] | components["schemas"]["SeedreamImageGenerationInvocation"] | components["schemas"]["SegmentAnythingInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["SpandrelImageToImageAutoscaleInvocation"] | components["schemas"]["SpandrelImageToImageInvocation"] | components["schemas"]["StringBatchInvocation"] | components["schemas"]["StringCollectionInvocation"] | components["schemas"]["StringGenerator"] | components["schemas"]["StringInvocation"] | components["schemas"]["StringJoinInvocation"] | components["schemas"]["StringJoinThreeInvocation"] | components["schemas"]["StringReplaceInvocation"] | components["schemas"]["StringSplitInvocation"] | components["schemas"]["StringSplitNegInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["T2IAdapterInvocation"] | components["schemas"]["TextLLMInvocation"] | components["schemas"]["TileToPropertiesInvocation"] | components["schemas"]["TiledMultiDiffusionDenoiseLatents"] | components["schemas"]["UnsharpMaskInvocation"] | components["schemas"]["VAELoaderInvocation"] | components["schemas"]["ZImageControlInvocation"] | components["schemas"]["ZImageDenoiseInvocation"] | components["schemas"]["ZImageDenoiseMetaInvocation"] | components["schemas"]["ZImageImageToLatentsInvocation"] | components["schemas"]["ZImageLatentsToImageInvocation"] | components["schemas"]["ZImageLoRACollectionLoader"] | components["schemas"]["ZImageLoRALoaderInvocation"] | components["schemas"]["ZImageModelLoaderInvocation"] | components["schemas"]["ZImageSeedVarianceEnhancerInvocation"] | components["schemas"]["ZImageTextEncoderInvocation"];+ invocation: components["schemas"]["AddInvocation"] | components["schemas"]["AlibabaCloudImageGenerationInvocation"] | components["schemas"]["AlphaMaskToTensorInvocation"] | components["schemas"]["AnimaDenoiseInvocation"] | components["schemas"]["AnimaImageToLatentsInvocation"] | components["schemas"]["AnimaLatentsToImageInvocation"] | components["schemas"]["AnimaLoRACollectionLoader"] | components["schemas"]["AnimaLoRALoaderInvocation"] | components["schemas"]["AnimaModelLoaderInvocation"] | components["schemas"]["AnimaTextEncoderInvocation"] | components["schemas"]["ApplyMaskTensorToImageInvocation"] | components["schemas"]["ApplyMaskToImageInvocation"] | components["schemas"]["BlankImageInvocation"] | components["schemas"]["BlendLatentsInvocation"] | components["schemas"]["BooleanCollectionInvocation"] | components["schemas"]["BooleanInvocation"] | components["schemas"]["BoundingBoxInvocation"] | components["schemas"]["CLIPSkipInvocation"] | components["schemas"]["CV2InfillInvocation"] | components["schemas"]["CalculateImageTilesEvenSplitInvocation"] | components["schemas"]["CalculateImageTilesInvocation"] | components["schemas"]["CalculateImageTilesMinimumOverlapInvocation"] | components["schemas"]["CallSavedWorkflowInvocation"] | components["schemas"]["CannyEdgeDetectionInvocation"] | components["schemas"]["CanvasOutputInvocation"] | components["schemas"]["CanvasPasteBackInvocation"] | components["schemas"]["CanvasV2MaskAndCropInvocation"] | components["schemas"]["CenterPadCropInvocation"] | components["schemas"]["CogView4DenoiseInvocation"] | components["schemas"]["CogView4ImageToLatentsInvocation"] | components["schemas"]["CogView4LatentsToImageInvocation"] | components["schemas"]["CogView4ModelLoaderInvocation"] | components["schemas"]["CogView4TextEncoderInvocation"] | components["schemas"]["CollectInvocation"] | components["schemas"]["ColorCorrectInvocation"] | components["schemas"]["ColorInvocation"] | components["schemas"]["ColorMapInvocation"] | components["schemas"]["CompelInvocation"] | components["schemas"]["ConditioningCollectionInvocation"] | components["schemas"]["ConditioningInvocation"] | components["schemas"]["ContentShuffleInvocation"] | components["schemas"]["ControlNetInvocation"] | components["schemas"]["CoreMetadataInvocation"] | components["schemas"]["CreateDenoiseMaskInvocation"] | components["schemas"]["CreateGradientMaskInvocation"] | components["schemas"]["CropImageToBoundingBoxInvocation"] | components["schemas"]["CropLatentsCoreInvocation"] | components["schemas"]["CvInpaintInvocation"] | components["schemas"]["DWOpenposeDetectionInvocation"] | components["schemas"]["DecodeInvisibleWatermarkInvocation"] | components["schemas"]["DenoiseLatentsInvocation"] | components["schemas"]["DenoiseLatentsMetaInvocation"] | components["schemas"]["DepthAnythingDepthEstimationInvocation"] | components["schemas"]["DivideInvocation"] | components["schemas"]["DynamicPromptInvocation"] | components["schemas"]["ESRGANInvocation"] | components["schemas"]["ExpandMaskWithFadeInvocation"] | components["schemas"]["FLUXLoRACollectionLoader"] | components["schemas"]["FaceIdentifierInvocation"] | components["schemas"]["FaceMaskInvocation"] | components["schemas"]["FaceOffInvocation"] | components["schemas"]["FloatBatchInvocation"] | components["schemas"]["FloatCollectionInvocation"] | components["schemas"]["FloatGenerator"] | components["schemas"]["FloatInvocation"] | components["schemas"]["FloatLinearRangeInvocation"] | components["schemas"]["FloatMathInvocation"] | components["schemas"]["FloatToIntegerInvocation"] | components["schemas"]["Flux2DenoiseInvocation"] | components["schemas"]["Flux2KleinLoRACollectionLoader"] | components["schemas"]["Flux2KleinLoRALoaderInvocation"] | components["schemas"]["Flux2KleinModelLoaderInvocation"] | components["schemas"]["Flux2KleinTextEncoderInvocation"] | components["schemas"]["Flux2VaeDecodeInvocation"] | components["schemas"]["Flux2VaeEncodeInvocation"] | components["schemas"]["FluxControlLoRALoaderInvocation"] | components["schemas"]["FluxControlNetInvocation"] | components["schemas"]["FluxDenoiseInvocation"] | components["schemas"]["FluxDenoiseLatentsMetaInvocation"] | components["schemas"]["FluxFillInvocation"] | components["schemas"]["FluxIPAdapterInvocation"] | components["schemas"]["FluxKontextConcatenateImagesInvocation"] | components["schemas"]["FluxKontextInvocation"] | components["schemas"]["FluxLoRALoaderInvocation"] | components["schemas"]["FluxModelLoaderInvocation"] | components["schemas"]["FluxReduxInvocation"] | components["schemas"]["FluxTextEncoderInvocation"] | components["schemas"]["FluxVaeDecodeInvocation"] | components["schemas"]["FluxVaeEncodeInvocation"] | components["schemas"]["FreeUInvocation"] | components["schemas"]["GeminiImageGenerationInvocation"] | components["schemas"]["GetMaskBoundingBoxInvocation"] | components["schemas"]["GroundingDinoInvocation"] | components["schemas"]["HEDEdgeDetectionInvocation"] | components["schemas"]["HeuristicResizeInvocation"] | components["schemas"]["IPAdapterInvocation"] | components["schemas"]["IdealSizeInvocation"] | components["schemas"]["IfInvocation"] | components["schemas"]["ImageBatchInvocation"] | components["schemas"]["ImageBlurInvocation"] | components["schemas"]["ImageChannelInvocation"] | components["schemas"]["ImageChannelMultiplyInvocation"] | components["schemas"]["ImageChannelOffsetInvocation"] | components["schemas"]["ImageCollectionInvocation"] | components["schemas"]["ImageConvertInvocation"] | components["schemas"]["ImageCropInvocation"] | components["schemas"]["ImageGenerator"] | components["schemas"]["ImageHueAdjustmentInvocation"] | components["schemas"]["ImageInverseLerpInvocation"] | components["schemas"]["ImageInvocation"] | components["schemas"]["ImageLerpInvocation"] | components["schemas"]["ImageMaskToTensorInvocation"] | components["schemas"]["ImageMultiplyInvocation"] | components["schemas"]["ImageNSFWBlurInvocation"] | components["schemas"]["ImageNoiseInvocation"] | components["schemas"]["ImagePanelLayoutInvocation"] | components["schemas"]["ImagePasteInvocation"] | components["schemas"]["ImageResizeInvocation"] | components["schemas"]["ImageScaleInvocation"] | components["schemas"]["ImageToLatentsInvocation"] | components["schemas"]["ImageWatermarkInvocation"] | components["schemas"]["InfillColorInvocation"] | components["schemas"]["InfillPatchMatchInvocation"] | components["schemas"]["InfillTileInvocation"] | components["schemas"]["IntegerBatchInvocation"] | components["schemas"]["IntegerCollectionInvocation"] | components["schemas"]["IntegerGenerator"] | components["schemas"]["IntegerInvocation"] | components["schemas"]["IntegerMathInvocation"] | components["schemas"]["InvertTensorMaskInvocation"] | components["schemas"]["InvokeAdjustImageHuePlusInvocation"] | components["schemas"]["InvokeEquivalentAchromaticLightnessInvocation"] | components["schemas"]["InvokeImageBlendInvocation"] | components["schemas"]["InvokeImageCompositorInvocation"] | components["schemas"]["InvokeImageDilateOrErodeInvocation"] | components["schemas"]["InvokeImageEnhanceInvocation"] | components["schemas"]["InvokeImageValueThresholdsInvocation"] | components["schemas"]["IterateInvocation"] | components["schemas"]["LaMaInfillInvocation"] | components["schemas"]["LatentsCollectionInvocation"] | components["schemas"]["LatentsInvocation"] | components["schemas"]["LatentsToImageInvocation"] | components["schemas"]["LineartAnimeEdgeDetectionInvocation"] | components["schemas"]["LineartEdgeDetectionInvocation"] | components["schemas"]["LlavaOnevisionVllmInvocation"] | components["schemas"]["LoRACollectionLoader"] | components["schemas"]["LoRALoaderInvocation"] | components["schemas"]["LoRASelectorInvocation"] | components["schemas"]["MLSDDetectionInvocation"] | components["schemas"]["MainModelLoaderInvocation"] | components["schemas"]["MaskCombineInvocation"] | components["schemas"]["MaskEdgeInvocation"] | components["schemas"]["MaskFromAlphaInvocation"] | components["schemas"]["MaskFromIDInvocation"] | components["schemas"]["MaskTensorToImageInvocation"] | components["schemas"]["MediaPipeFaceDetectionInvocation"] | components["schemas"]["MergeMetadataInvocation"] | components["schemas"]["MergeTilesToImageInvocation"] | components["schemas"]["MetadataFieldExtractorInvocation"] | components["schemas"]["MetadataFromImageInvocation"] | components["schemas"]["MetadataInvocation"] | components["schemas"]["MetadataItemInvocation"] | components["schemas"]["MetadataItemLinkedInvocation"] | components["schemas"]["MetadataToBoolCollectionInvocation"] | components["schemas"]["MetadataToBoolInvocation"] | components["schemas"]["MetadataToControlnetsInvocation"] | components["schemas"]["MetadataToFloatCollectionInvocation"] | components["schemas"]["MetadataToFloatInvocation"] | components["schemas"]["MetadataToIPAdaptersInvocation"] | components["schemas"]["MetadataToIntegerCollectionInvocation"] | components["schemas"]["MetadataToIntegerInvocation"] | components["schemas"]["MetadataToLorasCollectionInvocation"] | components["schemas"]["MetadataToLorasInvocation"] | components["schemas"]["MetadataToModelInvocation"] | components["schemas"]["MetadataToSDXLLorasInvocation"] | components["schemas"]["MetadataToSDXLModelInvocation"] | components["schemas"]["MetadataToSchedulerInvocation"] | components["schemas"]["MetadataToStringCollectionInvocation"] | components["schemas"]["MetadataToStringInvocation"] | components["schemas"]["MetadataToT2IAdaptersInvocation"] | components["schemas"]["MetadataToVAEInvocation"] | components["schemas"]["ModelIdentifierInvocation"] | components["schemas"]["MultiplyInvocation"] | components["schemas"]["NoiseInvocation"] | components["schemas"]["NormalMapInvocation"] | components["schemas"]["OklabUnsharpMaskInvocation"] | components["schemas"]["OklchImageHueAdjustmentInvocation"] | components["schemas"]["OpenAIImageGenerationInvocation"] | components["schemas"]["PBRMapsInvocation"] | components["schemas"]["PairTileImageInvocation"] | components["schemas"]["PasteImageIntoBoundingBoxInvocation"] | components["schemas"]["PiDiNetEdgeDetectionInvocation"] | components["schemas"]["PromptTemplateInvocation"] | components["schemas"]["PromptsFromFileInvocation"] | components["schemas"]["QwenImageDenoiseInvocation"] | components["schemas"]["QwenImageImageToLatentsInvocation"] | components["schemas"]["QwenImageLatentsToImageInvocation"] | components["schemas"]["QwenImageLoRACollectionLoader"] | components["schemas"]["QwenImageLoRALoaderInvocation"] | components["schemas"]["QwenImageModelLoaderInvocation"] | components["schemas"]["QwenImageTextEncoderInvocation"] | components["schemas"]["RandomFloatInvocation"] | components["schemas"]["RandomIntInvocation"] | components["schemas"]["RandomRangeInvocation"] | components["schemas"]["RangeInvocation"] | components["schemas"]["RangeOfSizeInvocation"] | components["schemas"]["RectangleMaskInvocation"] | components["schemas"]["ResizeLatentsInvocation"] | components["schemas"]["RoundInvocation"] | components["schemas"]["SD3DenoiseInvocation"] | components["schemas"]["SD3ImageToLatentsInvocation"] | components["schemas"]["SD3LatentsToImageInvocation"] | components["schemas"]["SDXLCompelPromptInvocation"] | components["schemas"]["SDXLLoRACollectionLoader"] | components["schemas"]["SDXLLoRALoaderInvocation"] | components["schemas"]["SDXLModelLoaderInvocation"] | components["schemas"]["SDXLRefinerCompelPromptInvocation"] | components["schemas"]["SDXLRefinerModelLoaderInvocation"] | components["schemas"]["SaveImageInvocation"] | components["schemas"]["SaveImageToFileInvocation"] | components["schemas"]["ScaleLatentsInvocation"] | components["schemas"]["SchedulerInvocation"] | components["schemas"]["Sd3ModelLoaderInvocation"] | components["schemas"]["Sd3TextEncoderInvocation"] | components["schemas"]["SeamlessModeInvocation"] | components["schemas"]["SeedreamImageGenerationInvocation"] | components["schemas"]["SegmentAnythingInvocation"] | components["schemas"]["ShowImageInvocation"] | components["schemas"]["SpandrelImageToImageAutoscaleInvocation"] | components["schemas"]["SpandrelImageToImageInvocation"] | components["schemas"]["StringBatchInvocation"] | components["schemas"]["StringCollectionInvocation"] | components["schemas"]["StringGenerator"] | components["schemas"]["StringInvocation"] | components["schemas"]["StringJoinInvocation"] | components["schemas"]["StringJoinThreeInvocation"] | components["schemas"]["StringReplaceInvocation"] | components["schemas"]["StringSplitInvocation"] | components["schemas"]["StringSplitNegInvocation"] | components["schemas"]["SubtractInvocation"] | components["schemas"]["T2IAdapterInvocation"] | components["schemas"]["TextLLMInvocation"] | components["schemas"]["TileToPropertiesInvocation"] | components["schemas"]["TiledMultiDiffusionDenoiseLatents"] | components["schemas"]["UnsharpMaskInvocation"] | components["schemas"]["VAELoaderInvocation"] | components["schemas"]["WorkflowReturnGetInvocation"] | components["schemas"]["WorkflowReturnInvocation"] | components["schemas"]["WorkflowReturnValueInvocation"] | components["schemas"]["ZImageControlInvocation"] | components["schemas"]["ZImageDenoiseInvocation"] | components["schemas"]["ZImageDenoiseMetaInvocation"] | components["schemas"]["ZImageImageToLatentsInvocation"] | components["schemas"]["ZImageLatentsToImageInvocation"] | components["schemas"]["ZImageLoRACollectionLoader"] | components["schemas"]["ZImageLoRALoaderInvocation"] | components["schemas"]["ZImageModelLoaderInvocation"] | components["schemas"]["ZImageSeedVarianceEnhancerInvocation"] | components["schemas"]["ZImageTextEncoderInvocation"];/*** Invocation Source Id* @description The ID of the prepared invocation's source node@@ -24171,7 +24247,7 @@ export type components = {* Value* @description The value to substitute into the node/field.*/- value: string | number | components["schemas"]["ImageField"];+ value: string | number | components["schemas"]["ImageField"] | (string | number | components["schemas"]["ImageField"])[];};/*** NodePackInfo@@ -25179,7 +25255,7 @@ export type components = {* @description The new status of the queue item* @enum {string}*/- status: "pending" | "in_progress" | "completed" | "failed" | "canceled";+ status: "pending" | "in_progress" | "waiting" | "completed" | "failed" | "canceled";/*** Status Sequence* @description A monotonically increasing version for this queue item's visible status lifecycle@@ -25256,6 +25332,18 @@ export type components = {* @description The IDs of the queue items that were retried*/retried_item_ids: number[];+ /**+ * User Ids+ * @description The IDs of the users who own the retried root queue items+ */+ user_ids: string[];+ /**+ * Retried Item Ids By User+ * @description The retried root queue item IDs keyed by owner user ID.+ */+ retried_item_ids_by_user: {+ [key: string]: number[];+ };};/*** Qwen3EncoderField@@ -28265,6 +28353,11 @@ export type components = {* @description Number of queue items with status 'in_progress' for the destination*/in_progress: number;+ /**+ * Waiting+ * @description Number of queue items with status 'waiting' for the destination+ */+ waiting: number;/*** Completed* @description Number of queue items with status 'complete' for the destination@@ -28302,7 +28395,7 @@ export type components = {* @default pending* @enum {string}*/- status: "pending" | "in_progress" | "completed" | "failed" | "canceled";+ status: "pending" | "in_progress" | "waiting" | "completed" | "failed" | "canceled";/*** Status Sequence* @description A monotonically increasing version for this queue item's visible status lifecycle@@ -28400,6 +28493,31 @@ export type components = {* @description The item_id of the queue item that this item was retried from*/retried_from_item_id?: number | null;+ /**+ * Workflow Call Id+ * @description The active workflow-call relationship id when this queue item is a child execution.+ */+ workflow_call_id?: string | null;+ /**+ * Parent Item Id+ * @description The parent queue item id when this queue item is a child workflow execution.+ */+ parent_item_id?: number | null;+ /**+ * Parent Session Id+ * @description The parent session id when this queue item is a child workflow execution.+ */+ parent_session_id?: string | null;+ /**+ * Root Item Id+ * @description The root queue item id for this workflow call chain, if any.+ */+ root_item_id?: number | null;+ /**+ * Workflow Call Depth+ * @description The 1-based workflow-call depth for this queue item when it is a child execution.+ */+ workflow_call_depth?: number | null;/** @description The fully-populated session to be executed */session: components["schemas"]["GraphExecutionState"];/** @description The workflow associated with this queue item */@@ -28437,6 +28555,11 @@ export type components = {* @description Number of queue items with status 'in_progress'*/in_progress: number;+ /**+ * Waiting+ * @description Number of queue items with status 'waiting'+ */+ waiting: number;/*** Completed* @description Number of queue items with status 'complete'@@ -30871,7 +30994,7 @@ export type components = {* used, and the type will be ignored. They are included here for backwards compatibility.* @enum {string}*/- UIType: "SchedulerField" | "AnyField" | "CollectionField" | "CollectionItemField" | "IsIntermediate" | "DEPRECATED_Boolean" | "DEPRECATED_Color" | "DEPRECATED_Conditioning" | "DEPRECATED_Control" | "DEPRECATED_Float" | "DEPRECATED_Image" | "DEPRECATED_Integer" | "DEPRECATED_Latents" | "DEPRECATED_String" | "DEPRECATED_BooleanCollection" | "DEPRECATED_ColorCollection" | "DEPRECATED_ConditioningCollection" | "DEPRECATED_ControlCollection" | "DEPRECATED_FloatCollection" | "DEPRECATED_ImageCollection" | "DEPRECATED_IntegerCollection" | "DEPRECATED_LatentsCollection" | "DEPRECATED_StringCollection" | "DEPRECATED_BooleanPolymorphic" | "DEPRECATED_ColorPolymorphic" | "DEPRECATED_ConditioningPolymorphic" | "DEPRECATED_ControlPolymorphic" | "DEPRECATED_FloatPolymorphic" | "DEPRECATED_ImagePolymorphic" | "DEPRECATED_IntegerPolymorphic" | "DEPRECATED_LatentsPolymorphic" | "DEPRECATED_StringPolymorphic" | "DEPRECATED_UNet" | "DEPRECATED_Vae" | "DEPRECATED_CLIP" | "DEPRECATED_Collection" | "DEPRECATED_CollectionItem" | "DEPRECATED_Enum" | "DEPRECATED_WorkflowField" | "DEPRECATED_BoardField" | "DEPRECATED_MetadataItem" | "DEPRECATED_MetadataItemCollection" | "DEPRECATED_MetadataItemPolymorphic" | "DEPRECATED_MetadataDict" | "DEPRECATED_MainModelField" | "DEPRECATED_CogView4MainModelField" | "DEPRECATED_FluxMainModelField" | "DEPRECATED_SD3MainModelField" | "DEPRECATED_SDXLMainModelField" | "DEPRECATED_SDXLRefinerModelField" | "DEPRECATED_ONNXModelField" | "DEPRECATED_VAEModelField" | "DEPRECATED_FluxVAEModelField" | "DEPRECATED_LoRAModelField" | "DEPRECATED_ControlNetModelField" | "DEPRECATED_IPAdapterModelField" | "DEPRECATED_T2IAdapterModelField" | "DEPRECATED_T5EncoderModelField" | "DEPRECATED_CLIPEmbedModelField" | "DEPRECATED_CLIPLEmbedModelField" | "DEPRECATED_CLIPGEmbedModelField" | "DEPRECATED_SpandrelImageToImageModelField" | "DEPRECATED_ControlLoRAModelField" | "DEPRECATED_SigLipModelField" | "DEPRECATED_FluxReduxModelField" | "DEPRECATED_LLaVAModelField" | "DEPRECATED_Imagen3ModelField" | "DEPRECATED_Imagen4ModelField" | "DEPRECATED_ChatGPT4oModelField" | "DEPRECATED_Gemini2_5ModelField" | "DEPRECATED_FluxKontextModelField" | "DEPRECATED_Veo3ModelField" | "DEPRECATED_RunwayModelField";+ UIType: "SchedulerField" | "AnyField" | "SavedWorkflowField" | "CollectionField" | "CollectionItemField" | "IsIntermediate" | "DEPRECATED_Boolean" | "DEPRECATED_Color" | "DEPRECATED_Conditioning" | "DEPRECATED_Control" | "DEPRECATED_Float" | "DEPRECATED_Image" | "DEPRECATED_Integer" | "DEPRECATED_Latents" | "DEPRECATED_String" | "DEPRECATED_BooleanCollection" | "DEPRECATED_ColorCollection" | "DEPRECATED_ConditioningCollection" | "DEPRECATED_ControlCollection" | "DEPRECATED_FloatCollection" | "DEPRECATED_ImageCollection" | "DEPRECATED_IntegerCollection" | "DEPRECATED_LatentsCollection" | "DEPRECATED_StringCollection" | "DEPRECATED_BooleanPolymorphic" | "DEPRECATED_ColorPolymorphic" | "DEPRECATED_ConditioningPolymorphic" | "DEPRECATED_ControlPolymorphic" | "DEPRECATED_FloatPolymorphic" | "DEPRECATED_ImagePolymorphic" | "DEPRECATED_IntegerPolymorphic" | "DEPRECATED_LatentsPolymorphic" | "DEPRECATED_StringPolymorphic" | "DEPRECATED_UNet" | "DEPRECATED_Vae" | "DEPRECATED_CLIP" | "DEPRECATED_Collection" | "DEPRECATED_CollectionItem" | "DEPRECATED_Enum" | "DEPRECATED_WorkflowField" | "DEPRECATED_BoardField" | "DEPRECATED_MetadataItem" | "DEPRECATED_MetadataItemCollection" | "DEPRECATED_MetadataItemPolymorphic" | "DEPRECATED_MetadataDict" | "DEPRECATED_MainModelField" | "DEPRECATED_CogView4MainModelField" | "DEPRECATED_FluxMainModelField" | "DEPRECATED_SD3MainModelField" | "DEPRECATED_SDXLMainModelField" | "DEPRECATED_SDXLRefinerModelField" | "DEPRECATED_ONNXModelField" | "DEPRECATED_VAEModelField" | "DEPRECATED_FluxVAEModelField" | "DEPRECATED_LoRAModelField" | "DEPRECATED_ControlNetModelField" | "DEPRECATED_IPAdapterModelField" | "DEPRECATED_T2IAdapterModelField" | "DEPRECATED_T5EncoderModelField" | "DEPRECATED_CLIPEmbedModelField" | "DEPRECATED_CLIPLEmbedModelField" | "DEPRECATED_CLIPGEmbedModelField" | "DEPRECATED_SpandrelImageToImageModelField" | "DEPRECATED_ControlLoRAModelField" | "DEPRECATED_SigLipModelField" | "DEPRECATED_FluxReduxModelField" | "DEPRECATED_LLaVAModelField" | "DEPRECATED_Imagen3ModelField" | "DEPRECATED_Imagen4ModelField" | "DEPRECATED_ChatGPT4oModelField" | "DEPRECATED_Gemini2_5ModelField" | "DEPRECATED_FluxKontextModelField" | "DEPRECATED_Veo3ModelField" | "DEPRECATED_RunwayModelField";/** UNetField */UNetField: {/** @description Info to load unet submodel */@@ -32157,6 +32280,27 @@ export type components = {*/id: string;};+ /**+ * WorkflowAccessRevokedEvent+ * @description Event model for workflow_access_revoked.+ */+ WorkflowAccessRevokedEvent: {+ /**+ * Timestamp+ * @description The timestamp of the event+ */+ timestamp: number;+ /**+ * Workflow Id+ * @description The ID of the workflow+ */+ workflow_id: string;+ /**+ * User Id+ * @description The owner of the workflow+ */+ user_id: string;+ };/** WorkflowAndGraphResponse */WorkflowAndGraphResponse: {/**@@ -32170,11 +32314,234 @@ export type components = {*/graph: string | null;};+ /** WorkflowCallCompatibility */+ WorkflowCallCompatibility: {+ /**+ * Is Callable+ * @description Whether the workflow can currently be executed by call_saved_workflow.+ */+ is_callable: boolean;+ /** @description Structured compatibility result. */+ reason: components["schemas"]["WorkflowCallCompatibilityReason"];+ /**+ * Message+ * @description Human-readable compatibility detail when unavailable.+ */+ message?: string | null;+ };+ /**+ * WorkflowCallCompatibilityReason+ * @enum {string}+ */+ WorkflowCallCompatibilityReason: "ok" | "missing_workflow_return" | "multiple_workflow_return" | "unsupported_node" | "unsupported_batch_input" | "invalid_graph" | "invalid_inputs" | "exceeds_capacity" | "unknown";+ /**+ * WorkflowCallExecution+ * @description Tracks one parent/child workflow-call relationship and its lifecycle.+ */+ WorkflowCallExecution: {+ /**+ * Id+ * @description The workflow-call execution id.+ */+ id?: string;+ /**+ * Parent Session Id+ * @description The parent graph execution state id.+ */+ parent_session_id: string;+ /**+ * Child Session Id+ * @description The child graph execution state id, if any.+ */+ child_session_id?: string | null;+ /**+ * Prepared Call Node Id+ * @description The prepared exec node id for the parent call site.+ */+ prepared_call_node_id: string;+ /**+ * Source Call Node Id+ * @description The source graph node id for the parent call site.+ */+ source_call_node_id: string;+ /**+ * Workflow Id+ * @description The saved workflow being called.+ */+ workflow_id: string;+ /**+ * Depth+ * @description The 1-based depth of this call frame.+ */+ depth: number;+ /**+ * Status+ * @description The current workflow-call lifecycle state.+ * @enum {string}+ */+ status: "waiting_for_child" | "running_child" | "completed" | "failed";+ /**+ * Error Message+ * @description Failure reason, if the call failed.+ */+ error_message?: string | null;+ /**+ * Child Session Ids+ * @description All child graph execution state ids.+ */+ child_session_ids?: string[];+ /**+ * Child Item Ids+ * @description Child queue item ids in enqueue order.+ */+ child_item_ids?: number[];+ /**+ * Expected Child Count+ * @description The number of child executions for this call.+ * @default 1+ */+ expected_child_count?: number;+ /**+ * Completed Child Item Ids+ * @description The child queue item ids whose workflow_return outputs have been aggregated.+ */+ completed_child_item_ids?: number[];+ /**+ * Aggregated Values+ * @description The aggregated workflow_return values accumulated from child executions.+ */+ aggregated_values?: {+ [key: string]: unknown[];+ };+ /**+ * Child Outputs+ * @description Workflow return values keyed by child queue item id.+ */+ child_outputs?: {+ [key: string]: {+ [key: string]: unknown;+ };+ };+ };+ /**+ * WorkflowCallFrame+ * @description Represents one workflow-call frame in a nested call chain.+ */+ WorkflowCallFrame: {+ /**+ * Prepared Call Node Id+ * @description The prepared exec node id for the call site.+ */+ prepared_call_node_id: string;+ /**+ * Source Call Node Id+ * @description The source graph node id for the call site.+ */+ source_call_node_id: string;+ /**+ * Workflow Id+ * @description The saved workflow being called.+ */+ workflow_id: string;+ /**+ * Depth+ * @description The 1-based depth of this call frame.+ */+ depth: number;+ };+ /**+ * WorkflowCallParentRef+ * @description Reference from a child execution state back to its parent workflow-call relationship.+ */+ WorkflowCallParentRef: {+ /**+ * Workflow Call Id+ * @description The workflow-call execution id.+ */+ workflow_call_id: string;+ /**+ * Parent Session Id+ * @description The parent graph execution state id.+ */+ parent_session_id: string;+ /**+ * Prepared Call Node Id+ * @description The prepared exec node id for the parent call site.+ */+ prepared_call_node_id: string;+ /**+ * Source Call Node Id+ * @description The source graph node id for the parent call site.+ */+ source_call_node_id: string;+ /**+ * Workflow Id+ * @description The saved workflow being called.+ */+ workflow_id: string;+ /**+ * Depth+ * @description The 1-based depth of this call frame.+ */+ depth: number;+ };/*** WorkflowCategory* @enum {string}*/WorkflowCategory: "user" | "default";+ /**+ * WorkflowCreatedEvent+ * @description Event model for workflow_created+ */+ WorkflowCreatedEvent: {+ /**+ * Timestamp+ * @description The timestamp of the event+ */+ timestamp: number;+ /**+ * Workflow Id+ * @description The ID of the workflow+ */+ workflow_id: string;+ /**+ * User Id+ * @description The owner of the workflow+ */+ user_id: string;+ /**+ * Is Public+ * @description Whether the workflow is shared with all users+ */+ is_public: boolean;+ };+ /**+ * WorkflowDeletedEvent+ * @description Event model for workflow_deleted+ */+ WorkflowDeletedEvent: {+ /**+ * Timestamp+ * @description The timestamp of the event+ */+ timestamp: number;+ /**+ * Workflow Id+ * @description The ID of the workflow+ */+ workflow_id: string;+ /**+ * User Id+ * @description The owner of the workflow+ */+ user_id: string;+ /**+ * Is Public+ * @description Whether the workflow was shared when it was deleted+ */+ is_public: boolean;+ };/** WorkflowMeta */WorkflowMeta: {/**@@ -32279,6 +32646,8 @@ export type components = {* @description The URL of the workflow thumbnail.*/thumbnail_url?: string | null;+ /** @description Whether this workflow is currently callable by call_saved_workflow. */+ call_saved_workflow_compatibility?: components["schemas"]["WorkflowCallCompatibility"] | null;};/*** WorkflowRecordOrderBy@@ -32330,6 +32699,229 @@ export type components = {* @description The URL of the workflow thumbnail.*/thumbnail_url?: string | null;+ /** @description Whether this workflow is currently callable by call_saved_workflow. */+ call_saved_workflow_compatibility?: components["schemas"]["WorkflowCallCompatibility"] | null;+ };+ /**+ * Get Workflow Return Value+ * @description Extracts one named value from a callable workflow return.+ */+ WorkflowReturnGetInvocation: {+ /**+ * Id+ * @description The id of this instance of an invocation. Must be unique among all instances of invocations.+ */+ id: string;+ /**+ * Is Intermediate+ * @description Whether or not this is an intermediate invocation.+ * @default false+ */+ is_intermediate?: boolean;+ /**+ * Use Cache+ * @description Whether or not to use the cache+ * @default false+ */+ use_cache?: boolean;+ /**+ * Values+ * @description The named workflow return values.+ * @default {}+ */+ values?: {+ [key: string]: unknown;+ };+ /**+ * Key+ * @description The return key to extract.+ * @default+ */+ key?: string;+ /**+ * type+ * @default workflow_return_get+ * @constant+ */+ type: "workflow_return_get";+ };+ /**+ * WorkflowReturnGetOutput+ * @description A value extracted from named workflow return values.+ */+ WorkflowReturnGetOutput: {+ /**+ * Value+ * @description The extracted workflow return value.+ */+ value: unknown;+ /**+ * type+ * @default workflow_return_get_output+ * @constant+ */+ type: "workflow_return_get_output";+ };+ /**+ * Workflow Return+ * @description Defines the explicit named result returned by a callable workflow.+ */+ WorkflowReturnInvocation: {+ /**+ * Id+ * @description The id of this instance of an invocation. Must be unique among all instances of invocations.+ */+ id: string;+ /**+ * Is Intermediate+ * @description Whether or not this is an intermediate invocation.+ * @default false+ */+ is_intermediate?: boolean;+ /**+ * Use Cache+ * @description Whether or not to use the cache+ * @default false+ */+ use_cache?: boolean;+ /**+ * Values+ * @description The named values returned to a calling workflow.+ * @default []+ */+ values?: components["schemas"]["WorkflowReturnValueField"] | components["schemas"]["WorkflowReturnValueField"][];+ /**+ * type+ * @default workflow_return+ * @constant+ */+ type: "workflow_return";+ };+ /**+ * WorkflowReturnOutput+ * @description The explicit named values returned from a callable workflow.+ */+ WorkflowReturnOutput: {+ /**+ * Values+ * @description The workflow return values, keyed by return name.+ * @default {}+ */+ values: {+ [key: string]: unknown;+ };+ /**+ * type+ * @default workflow_return_output+ * @constant+ */+ type: "workflow_return_output";+ };+ /**+ * WorkflowReturnValueField+ * @description One named workflow return value.+ */+ WorkflowReturnValueField: {+ /**+ * Key+ * @description The workflow return key.+ */+ key: string;+ /**+ * Value+ * @description The workflow return value.+ * @default null+ */+ value?: unknown;+ };+ /**+ * Workflow Return Value+ * @description Creates one named value for a callable workflow return.+ */+ WorkflowReturnValueInvocation: {+ /**+ * Id+ * @description The id of this instance of an invocation. Must be unique among all instances of invocations.+ */+ id: string;+ /**+ * Is Intermediate+ * @description Whether or not this is an intermediate invocation.+ * @default false+ */+ is_intermediate?: boolean;+ /**+ * Use Cache+ * @description Whether or not to use the cache+ * @default false+ */+ use_cache?: boolean;+ /**+ * Key+ * @description The return key.+ * @default+ */+ key?: string;+ /**+ * Value+ * @description The value returned under this key.+ * @default null+ */+ value?: unknown | null;+ /**+ * type+ * @default workflow_return_value+ * @constant+ */+ type: "workflow_return_value";+ };+ /**+ * WorkflowReturnValueOutput+ * @description A named workflow return value.+ */+ WorkflowReturnValueOutput: {+ /**+ * Return Value+ * @description The named workflow return value.+ */+ value: components["schemas"]["WorkflowReturnValueField"];+ /**+ * type+ * @default workflow_return_value_output+ * @constant+ */+ type: "workflow_return_value_output";+ };+ /**+ * WorkflowUpdatedEvent+ * @description Event model for workflow_updated+ */+ WorkflowUpdatedEvent: {+ /**+ * Timestamp+ * @description The timestamp of the event+ */+ timestamp: number;+ /**+ * Workflow Id+ * @description The ID of the workflow+ */+ workflow_id: string;+ /**+ * User Id+ * @description The owner of the workflow+ */+ user_id: string;+ /**+ * Old Is Public+ * @description Whether the workflow was shared before the update+ */+ old_is_public: boolean;+ /**+ * New Is Public+ * @description Whether the workflow is shared after the update+ */+ new_is_public: boolean;};/** WorkflowWithoutID */WorkflowWithoutID: {diff --git a/invokeai/frontend/web/src/services/events/nodeExecutionState.test.ts b/invokeai/frontend/web/src/services/events/nodeExecutionState.test.tsindex 8ce96bbc8a..70726a9d27 100644--- a/invokeai/frontend/web/src/services/events/nodeExecutionState.test.ts+++ b/invokeai/frontend/web/src/services/events/nodeExecutionState.test.ts@@ -6,6 +6,7 @@ import { describe, expect, it } from 'vitest';import {getCompletedInvocationIdsFromCompletedSession,getNodeExecutionStatesFromCompletedSession,+ getResetNodeExecutionStatesOnQueueItemStarted,getUpdatedNodeExecutionStateOnInvocationComplete,getUpdatedNodeExecutionStateOnInvocationError,getUpdatedNodeExecutionStateOnInvocationProgress,@@ -110,6 +111,49 @@ const buildInvocationErrorEvent = (overrides: Partial<S['InvocationErrorEvent']>...overrides,}) as S['InvocationErrorEvent'];+describe(getResetNodeExecutionStatesOnQueueItemStarted.name, () => {+ it('resets node execution states when a queue item starts for the first time', () => {+ const updated = getResetNodeExecutionStatesOnQueueItemStarted(+ {+ 'node-1': buildNodeExecutionState({+ status: zNodeStatus.enum.COMPLETED,+ progress: 1,+ outputs: [{ type: 'integer_output', value: 3 } as unknown as S['InvocationCompleteEvent']['result']],+ }),+ },+ 1,+ new Map()+ );++ expect(updated?.['node-1']).toEqual({+ nodeId: 'node-1',+ status: zNodeStatus.enum.PENDING,+ progress: null,+ progressImage: null,+ outputs: [],+ error: null,+ });+ });++ it('does not reset node execution states when a workflow-call parent queue item resumes', () => {+ const workflowReturnOutput = {+ type: 'workflow_return_output',+ values: { result: [3] },+ } as unknown as S['InvocationCompleteEvent']['result'];+ const existing = {+ 'call-node': buildNodeExecutionState({+ nodeId: 'call-node',+ status: zNodeStatus.enum.COMPLETED,+ outputs: [workflowReturnOutput],+ }),+ };++ const updated = getResetNodeExecutionStatesOnQueueItemStarted(existing, 1, new Map([[1, new Set(['call-node'])]]));++ expect(updated).toBeUndefined();+ });+});+describe(getUpdatedNodeExecutionStateOnInvocationStarted.name, () => {it('creates an execution state when started arrives before initialization', () => {const event = buildInvocationStartedEvent();diff --git a/invokeai/frontend/web/src/services/events/nodeExecutionState.ts b/invokeai/frontend/web/src/services/events/nodeExecutionState.tsindex dbd1bc0492..d0e175ddf8 100644--- a/invokeai/frontend/web/src/services/events/nodeExecutionState.ts+++ b/invokeai/frontend/web/src/services/events/nodeExecutionState.ts@@ -1,4 +1,5 @@import { deepClone } from 'common/util/deepClone';+import type { NodeExecutionStates } from 'features/nodes/store/types';import type { NodeExecutionState } from 'features/nodes/types/invocation';import { zNodeStatus } from 'features/nodes/types/invocation';import type { S } from 'services/api/types';@@ -15,6 +16,32 @@ const getInitialNodeExecutionState = (nodeId: string): NodeExecutionState => ({error: null,});+export const getResetNodeExecutionStatesOnQueueItemStarted = (+ nodeExecutionStates: NodeExecutionStates,+ itemId: number,+ completedInvocationKeysByItemId: CompletedInvocationKeysByItemId+): NodeExecutionStates | undefined => {+ if (completedInvocationKeysByItemId.has(itemId)) {+ return;+ }++ const next: NodeExecutionStates = {};+ for (const [nodeId, nodeExecutionState] of Object.entries(nodeExecutionStates)) {+ if (!nodeExecutionState) {+ next[nodeId] = nodeExecutionState;+ continue;+ }+ const clone = deepClone(nodeExecutionState);+ clone.status = zNodeStatus.enum.PENDING;+ clone.error = null;+ clone.progress = null;+ clone.progressImage = null;+ clone.outputs = [];+ next[nodeId] = clone;+ }+ return next;+};+export const getUpdatedNodeExecutionStateOnInvocationStarted = (nodeExecutionState: NodeExecutionState | undefined,data: S['InvocationStartedEvent'],diff --git a/invokeai/frontend/web/src/services/events/queueStatusEvents.test.ts b/invokeai/frontend/web/src/services/events/queueStatusEvents.test.tsnew file mode 100644index 0000000000..9c7dab37c9--- /dev/null+++ b/invokeai/frontend/web/src/services/events/queueStatusEvents.test.ts@@ -0,0 +1,128 @@+import type { S } from 'services/api/types';+import { beforeEach, describe, expect, it } from 'vitest';++import {+ getQueueStatusWithObservedEvents,+ getUpdatedQueueStatusOnQueueItemStatusChanged,+ resetObservedQueueStatusEventsForTests,+} from './queueStatusEvents';++const buildQueueStatus = (overrides: Partial<S['SessionQueueStatus']> = {}): S['SessionQueueAndProcessorStatus'] => ({+ queue: {+ queue_id: 'default',+ item_id: 1,+ batch_id: 'batch-1',+ session_id: 'session-1',+ pending: 0,+ in_progress: 1,+ waiting: 0,+ completed: 0,+ failed: 0,+ canceled: 0,+ total: 1,+ ...overrides,+ },+ processor: {+ is_started: true,+ is_processing: true,+ },+});++const buildQueueStatusChangedEvent = (+ overrides: Partial<S['QueueItemStatusChangedEvent']> = {}+): S['QueueItemStatusChangedEvent'] =>+ ({+ item_id: 1,+ status: 'completed',+ status_sequence: 2,+ queue_status: {+ queue_id: 'default',+ item_id: null,+ batch_id: null,+ session_id: null,+ pending: 0,+ in_progress: 0,+ waiting: 0,+ completed: 1,+ failed: 0,+ canceled: 0,+ total: 1,+ },+ ...overrides,+ }) as S['QueueItemStatusChangedEvent'];++beforeEach(() => {+ resetObservedQueueStatusEventsForTests();+});++describe(getUpdatedQueueStatusOnQueueItemStatusChanged.name, () => {+ it('uses the queue status from the socket event while preserving processor status', () => {+ const current = buildQueueStatus();+ const event = buildQueueStatusChangedEvent();++ expect(getUpdatedQueueStatusOnQueueItemStatusChanged(current, event)).toEqual({+ queue: event.queue_status,+ processor: current.processor,+ });+ });+});++describe(getQueueStatusWithObservedEvents.name, () => {+ it('does not let a stale current-item queue status response regress a terminal socket event', () => {+ const current = buildQueueStatus();+ const completedEvent = buildQueueStatusChangedEvent();+ getUpdatedQueueStatusOnQueueItemStatusChanged(current, completedEvent);++ const staleResponse = buildQueueStatus({ item_id: 1, in_progress: 1, completed: 0 });++ expect(getQueueStatusWithObservedEvents(staleResponse)).toEqual({+ ...staleResponse,+ queue: completedEvent.queue_status,+ });+ });++ it('accepts a later status event for the same item when its status sequence increases', () => {+ const current = buildQueueStatus();+ getUpdatedQueueStatusOnQueueItemStatusChanged(current, buildQueueStatusChangedEvent());+ const retryEvent = buildQueueStatusChangedEvent({+ status: 'in_progress',+ status_sequence: 3,+ queue_status: {+ queue_id: 'default',+ item_id: 1,+ batch_id: 'batch-1',+ session_id: 'session-1',+ pending: 0,+ in_progress: 1,+ waiting: 0,+ completed: 1,+ failed: 0,+ canceled: 0,+ total: 2,+ },+ });++ getUpdatedQueueStatusOnQueueItemStatusChanged(current, retryEvent);+ const latestResponse = buildQueueStatus({ item_id: 1, in_progress: 1, completed: 1, total: 2 });++ expect(getQueueStatusWithObservedEvents(latestResponse)).toBe(latestResponse);+ });++ it('ignores an older status event for an item with a newer terminal event', () => {+ const current = buildQueueStatus();+ const completedEvent = buildQueueStatusChangedEvent({ status_sequence: 2 });+ getUpdatedQueueStatusOnQueueItemStatusChanged(current, completedEvent);+ const staleInProgressEvent = buildQueueStatusChangedEvent({+ status: 'in_progress',+ status_sequence: 1,+ queue_status: buildQueueStatus({ item_id: 1, in_progress: 1, completed: 0 }).queue,+ });++ getUpdatedQueueStatusOnQueueItemStatusChanged(current, staleInProgressEvent);++ expect(getQueueStatusWithObservedEvents(buildQueueStatus({ item_id: 1 }))).toEqual({+ ...current,+ queue: completedEvent.queue_status,+ });+ });+});diff --git a/invokeai/frontend/web/src/services/events/queueStatusEvents.ts b/invokeai/frontend/web/src/services/events/queueStatusEvents.tsnew file mode 100644index 0000000000..01b635a3ad--- /dev/null+++ b/invokeai/frontend/web/src/services/events/queueStatusEvents.ts@@ -0,0 +1,71 @@+import type { S } from 'services/api/types';++type QueueStatusResponse = S['SessionQueueAndProcessorStatus'];+type QueueItemStatusChangedEvent = S['QueueItemStatusChangedEvent'];++const TERMINAL_QUEUE_ITEM_STATUSES = new Set<QueueItemStatusChangedEvent['status']>([+ 'completed',+ 'failed',+ 'canceled',+]);++let latestObservedQueueStatus: S['SessionQueueStatus'] | null = null;+const observedItemStatusSequences = new Map<number, number>();+const observedTerminalItemIds = new Set<number>();++const shouldAcceptQueueItemStatusEvent = (event: QueueItemStatusChangedEvent): boolean => {+ const statusSequence = event.status_sequence ?? undefined;+ if (statusSequence === undefined) {+ return true;+ }++ const previousSequence = observedItemStatusSequences.get(event.item_id);+ return previousSequence === undefined || statusSequence >= previousSequence;+};++const recordQueueItemStatusChangedEvent = (event: QueueItemStatusChangedEvent): void => {+ if (!shouldAcceptQueueItemStatusEvent(event)) {+ return;+ }++ if (event.status_sequence !== null && event.status_sequence !== undefined) {+ observedItemStatusSequences.set(event.item_id, event.status_sequence);+ }++ if (TERMINAL_QUEUE_ITEM_STATUSES.has(event.status)) {+ observedTerminalItemIds.add(event.item_id);+ } else {+ observedTerminalItemIds.delete(event.item_id);+ }++ latestObservedQueueStatus = event.queue_status;+};++export const getQueueStatusWithObservedEvents = (queueStatus: QueueStatusResponse): QueueStatusResponse => {+ const currentItemId = queueStatus.queue.item_id;+ if (latestObservedQueueStatus && currentItemId !== null && observedTerminalItemIds.has(currentItemId)) {+ return {+ ...queueStatus,+ queue: latestObservedQueueStatus,+ };+ }++ return queueStatus;+};++export const getUpdatedQueueStatusOnQueueItemStatusChanged = (+ queueStatus: QueueStatusResponse,+ event: QueueItemStatusChangedEvent+): QueueStatusResponse => {+ recordQueueItemStatusChangedEvent(event);+ return {+ ...queueStatus,+ queue: event.queue_status,+ };+};++export const resetObservedQueueStatusEventsForTests = (): void => {+ latestObservedQueueStatus = null;+ observedItemStatusSequences.clear();+ observedTerminalItemIds.clear();+};diff --git a/invokeai/frontend/web/src/services/events/setEventListeners.test.ts b/invokeai/frontend/web/src/services/events/setEventListeners.test.tsnew file mode 100644index 0000000000..5b69bc49f6--- /dev/null+++ b/invokeai/frontend/web/src/services/events/setEventListeners.test.ts@@ -0,0 +1,300 @@+import { LIST_TAG } from 'services/api';+import { describe, expect, it, vi } from 'vitest';++import { setEventListeners } from './setEventListeners';++vi.mock('app/logging/logger', () => ({+ logger: () => ({+ debug: vi.fn(),+ trace: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ }),+}));++vi.mock('features/toast/toast', () => ({+ toast: vi.fn(),+}));++vi.mock('./onInvocationComplete', () => ({+ buildOnInvocationComplete: () => vi.fn(),+}));++vi.mock('./onModelInstallError', () => ({+ buildOnModelInstallError: () => vi.fn(),+ DiscordLink: () => null,+ GitHubIssuesLink: () => null,+}));++const createMockSocket = () => {+ const handlers = new Map<string, (...args: Array<unknown>) => void>();++ return {+ on: vi.fn((event: string, handler: (...args: Array<unknown>) => void) => {+ handlers.set(event, handler);+ }),+ emit: vi.fn(),+ trigger: (event: string, payload?: unknown) => {+ const handler = handlers.get(event);+ if (!handler) {+ throw new Error(`No handler registered for ${event}`);+ }+ handler(payload);+ },+ };+};++describe('setEventListeners workflow live updates', () => {+ it('invalidates workflow list caches on workflow_created', () => {+ const socket = createMockSocket();+ const dispatch = vi.fn();+ const store = {+ dispatch,+ getState: vi.fn(() => ({})),+ };++ setEventListeners({+ socket: socket as never,+ store: store as never,+ setIsConnected: vi.fn(),+ });++ socket.trigger('workflow_created', { workflow_id: 'wf-1', is_public: true });++ expect(dispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.arrayContaining([+ { type: 'Workflow', id: LIST_TAG },+ 'WorkflowTags',+ 'WorkflowTagCounts',+ 'WorkflowCategoryCounts',+ ]),+ })+ );+ });++ it('ignores unrelated events for workflow cache invalidation', () => {+ const socket = createMockSocket();+ const dispatch = vi.fn();+ const store = {+ dispatch,+ getState: vi.fn(() => ({})),+ };++ setEventListeners({+ socket: socket as never,+ store: store as never,+ setIsConnected: vi.fn(),+ });++ socket.trigger('download_started', { source: 'x', download_path: '/tmp/x' });++ expect(dispatch).not.toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.arrayContaining([{ type: 'Workflow', id: LIST_TAG }]),+ })+ );+ });++ it('clears selected workflow ids from call_saved_workflow nodes on workflow_deleted', () => {+ const socket = createMockSocket();+ const dispatch = vi.fn();+ const store = {+ dispatch,+ getState: vi.fn(() => ({+ nodes: {+ present: {+ nodes: [+ {+ id: 'call-saved-workflows-node',+ type: 'invocation',+ data: {+ id: 'call-saved-workflows-node',+ type: 'call_saved_workflow',+ inputs: {+ workflow_id: {+ value: 'wf-1',+ },+ },+ },+ },+ ],+ },+ },+ })),+ };++ setEventListeners({+ socket: socket as never,+ store: store as never,+ setIsConnected: vi.fn(),+ });++ socket.trigger('workflow_deleted', { workflow_id: 'wf-1', is_public: false });++ expect(dispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ nodeId: 'call-saved-workflows-node',+ fieldName: 'workflow_id',+ value: '',+ }),+ })+ );+ });++ it('does not clear selected workflow ids from call_saved_workflow nodes on workflow_updated', () => {+ const socket = createMockSocket();+ const dispatch = vi.fn();+ const store = {+ dispatch,+ getState: vi.fn(() => ({+ nodes: {+ present: {+ nodes: [+ {+ id: 'call-saved-workflows-node',+ type: 'invocation',+ data: {+ id: 'call-saved-workflows-node',+ type: 'call_saved_workflow',+ inputs: {+ workflow_id: {+ value: 'wf-1',+ },+ },+ },+ },+ ],+ },+ },+ })),+ };++ setEventListeners({+ socket: socket as never,+ store: store as never,+ setIsConnected: vi.fn(),+ });++ socket.trigger('workflow_updated', {+ workflow_id: 'wf-1',+ user_id: 'owner-1',+ old_is_public: true,+ new_is_public: true,+ });++ expect(dispatch).not.toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ nodeId: 'call-saved-workflows-node',+ fieldName: 'workflow_id',+ value: '',+ }),+ })+ );+ expect(dispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.arrayContaining([{ type: 'Workflow', id: LIST_TAG }]),+ })+ );+ });++ it('clears selected workflow ids when another user revokes shared access', () => {+ const socket = createMockSocket();+ const dispatch = vi.fn();+ const store = {+ dispatch,+ getState: vi.fn(() => ({+ auth: {+ user: { user_id: 'viewer-1', is_admin: false },+ },+ nodes: {+ present: {+ nodes: [+ {+ id: 'call-saved-workflows-node',+ type: 'invocation',+ data: {+ id: 'call-saved-workflows-node',+ type: 'call_saved_workflow',+ inputs: {+ workflow_id: {+ value: 'wf-shared',+ },+ },+ },+ },+ ],+ },+ },+ })),+ };++ setEventListeners({+ socket: socket as never,+ store: store as never,+ setIsConnected: vi.fn(),+ });++ socket.trigger('workflow_access_revoked', { workflow_id: 'wf-shared', user_id: 'owner-1' });++ expect(dispatch).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ nodeId: 'call-saved-workflows-node',+ fieldName: 'workflow_id',+ value: '',+ }),+ })+ );+ });++ it.each([+ { user_id: 'owner-1', is_admin: false },+ { user_id: 'admin-1', is_admin: true },+ ])('keeps selected workflow ids when access remains for $user_id', (user) => {+ const socket = createMockSocket();+ const dispatch = vi.fn();+ const store = {+ dispatch,+ getState: vi.fn(() => ({+ auth: { user },+ nodes: {+ present: {+ nodes: [+ {+ id: 'call-saved-workflows-node',+ type: 'invocation',+ data: {+ id: 'call-saved-workflows-node',+ type: 'call_saved_workflow',+ inputs: { workflow_id: { value: 'wf-shared' } },+ },+ },+ ],+ },+ },+ })),+ };++ setEventListeners({+ socket: socket as never,+ store: store as never,+ setIsConnected: vi.fn(),+ });++ socket.trigger('workflow_access_revoked', { workflow_id: 'wf-shared', user_id: 'owner-1' });++ expect(dispatch).not.toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ nodeId: 'call-saved-workflows-node',+ fieldName: 'workflow_id',+ value: '',+ }),+ })+ );+ });+});diff --git a/invokeai/frontend/web/src/services/events/setEventListeners.tsx b/invokeai/frontend/web/src/services/events/setEventListeners.tsxindex 774d0aa910..30f705d670 100644--- a/invokeai/frontend/web/src/services/events/setEventListeners.tsx+++ b/invokeai/frontend/web/src/services/events/setEventListeners.tsx@@ -26,6 +26,8 @@ import type {} from 'features/controlLayers/store/types';import { getControlLayerState, getReferenceImageState } from 'features/controlLayers/store/util';import { $nodeExecutionStates, upsertExecutionState } from 'features/nodes/hooks/useNodeExecutionState';+import { fieldValueReset } from 'features/nodes/store/nodesSlice';+import { selectNodesSlice } from 'features/nodes/store/selectors';import { modelSelected } from 'features/parameters/store/actions';import ErrorToastDescription, { getTitle } from 'features/toast/ErrorToastDescription';import { toast, toastApi } from 'features/toast/toast';@@ -38,6 +40,7 @@ import { modelsApi } from 'services/api/endpoints/models';import { queueApi } from 'services/api/endpoints/queue';import { buildOnInvocationComplete } from 'services/events/onInvocationComplete';import { buildOnModelInstallError, DiscordLink, GitHubIssuesLink } from 'services/events/onModelInstallError';+import { getUpdatedQueueStatusOnQueueItemStatusChanged } from 'services/events/queueStatusEvents';import type { ClientToServerEvents, ServerToClientEvents } from 'services/events/types';import { createWorkflowExecutionCoordinator } from 'services/events/workflowExecutionCoordinator';import type { Socket } from 'socket.io-client';@@ -115,6 +118,65 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLissetIsConnected(false);});+ const invalidateWorkflowLibrary = () => {+ dispatch(+ api.util.invalidateTags([+ { type: 'Workflow', id: LIST_TAG },+ 'WorkflowTags',+ 'WorkflowTagCounts',+ 'WorkflowCategoryCounts',+ ])+ );+ };++ const clearSavedWorkflowSelection = (workflowId: string) => {+ const nodes = selectNodesSlice(getState()).nodes;++ for (const node of nodes) {+ if (node.type !== 'invocation' || node.data.type !== 'call_saved_workflow') {+ continue;+ }++ if (node.data.inputs.workflow_id?.value !== workflowId) {+ continue;+ }++ dispatch(+ fieldValueReset({+ nodeId: node.id,+ fieldName: 'workflow_id',+ value: '',+ })+ );+ }+ };++ socket.on('workflow_created', (data) => {+ log.debug({ data }, 'Workflow created');+ invalidateWorkflowLibrary();+ });++ socket.on('workflow_updated', (data) => {+ log.debug({ data }, 'Workflow updated');+ invalidateWorkflowLibrary();+ });++ socket.on('workflow_deleted', (data) => {+ log.debug({ data }, 'Workflow deleted');+ invalidateWorkflowLibrary();+ clearSavedWorkflowSelection(data.workflow_id);+ });++ socket.on('workflow_access_revoked', (data) => {+ log.debug({ data }, 'Workflow access revoked');+ invalidateWorkflowLibrary();+ const currentUser = getState().auth.user;+ if (currentUser?.is_admin || currentUser?.user_id === data.user_id) {+ return;+ }+ clearSavedWorkflowSelection(data.workflow_id);+ });+socket.on('invocation_started', (data) => {const { invocation_source_id, invocation } = data;log.debug({ data } as JsonObject, `Invocation started (${invocation.type}, ${invocation_source_id})`);@@ -434,6 +496,11 @@ export const setEventListeners = ({ socket, store, setIsConnected }: SetEventLis}));}+ dispatch(+ queueApi.util.updateQueryData('getQueueStatus', undefined, (draft) =>+ getUpdatedQueueStatusOnQueueItemStatusChanged(draft, data)+ )+ );// Invalidate caches for things we cannot easily update// Invalidate SessionQueueStatus to refetch with user-specific countsdiff --git a/invokeai/frontend/web/src/services/events/types.ts b/invokeai/frontend/web/src/services/events/types.tsindex 8937dcc451..72239986fb 100644--- a/invokeai/frontend/web/src/services/events/types.ts+++ b/invokeai/frontend/web/src/services/events/types.ts@@ -5,6 +5,10 @@ type ClientEmitSubscribeQueue = { queue_id: string };type ClientEmitUnsubscribeQueue = ClientEmitSubscribeQueue;type ClientEmitSubscribeBulkDownload = { bulk_download_id: string };type ClientEmitUnsubscribeBulkDownload = ClientEmitSubscribeBulkDownload;+type WorkflowCreatedEvent = S['WorkflowCreatedEvent'];+type WorkflowUpdatedEvent = S['WorkflowUpdatedEvent'];+type WorkflowDeletedEvent = S['WorkflowDeletedEvent'];+type WorkflowAccessRevokedEvent = S['WorkflowAccessRevokedEvent'];export type ServerToClientEvents = {invocation_progress: (payload: S['InvocationProgressEvent']) => void;@@ -33,6 +37,10 @@ export type ServerToClientEvents = {bulk_download_started: (payload: S['BulkDownloadStartedEvent']) => void;bulk_download_complete: (payload: S['BulkDownloadCompleteEvent']) => void;bulk_download_error: (payload: S['BulkDownloadErrorEvent']) => void;+ workflow_created: (payload: WorkflowCreatedEvent) => void;+ workflow_updated: (payload: WorkflowUpdatedEvent) => void;+ workflow_deleted: (payload: WorkflowDeletedEvent) => void;+ workflow_access_revoked: (payload: WorkflowAccessRevokedEvent) => void;};export type ClientToServerEvents = {diff --git a/invokeai/frontend/web/src/services/events/workflowExecutionCoordinator.test.ts b/invokeai/frontend/web/src/services/events/workflowExecutionCoordinator.test.tsindex fd0524ece1..00c48c8a37 100644--- a/invokeai/frontend/web/src/services/events/workflowExecutionCoordinator.test.ts+++ b/invokeai/frontend/web/src/services/events/workflowExecutionCoordinator.test.ts@@ -173,6 +173,7 @@ const createCoordinatorHarness = () => {return {clearCanvasWorkflowIntegrationProcessing,+ completedInvocationKeysByItemId,coordinator,nodeExecutionStates,onInvocationComplete,@@ -206,6 +207,29 @@ describe(createWorkflowExecutionCoordinator.name, () => {expect(nodeExecutionStates['node-1']?.outputs).toEqual([]);});+ it('does not reset node execution states when a workflow-call parent queue item resumes', () => {+ const { completedInvocationKeysByItemId, coordinator, nodeExecutionStates } = createCoordinatorHarness();+ nodeExecutionStates['call-node'] = {+ nodeId: 'call-node',+ status: zNodeStatus.enum.COMPLETED,+ progress: null,+ progressImage: null,+ outputs: [+ {+ type: 'workflow_return_output',+ values: { result: [3] },+ } as unknown as S['InvocationCompleteEvent']['result'],+ ],+ error: null,+ };+ completedInvocationKeysByItemId.set(1, new Set(['prepared-call-node']));++ coordinator.onQueueItemStatusChanged(buildQueueStatusEvent({ item_id: 1, status: 'in_progress' }));++ expect(nodeExecutionStates['call-node']?.status).toBe(zNodeStatus.enum.COMPLETED);+ expect(nodeExecutionStates['call-node']?.outputs).toHaveLength(1);+ });+it('does not let a late invocation_complete from an old workflow item overwrite the active workflow item', () => {const { coordinator, nodeExecutionStates, onInvocationComplete } = createCoordinatorHarness();diff --git a/invokeai/frontend/web/src/services/events/workflowExecutionCoordinator.ts b/invokeai/frontend/web/src/services/events/workflowExecutionCoordinator.tsindex 2b97777453..fceb117d87 100644--- a/invokeai/frontend/web/src/services/events/workflowExecutionCoordinator.ts+++ b/invokeai/frontend/web/src/services/events/workflowExecutionCoordinator.ts@@ -1,6 +1,4 @@-import { deepClone } from 'common/util/deepClone';import type { NodeExecutionState } from 'features/nodes/types/invocation';-import { zNodeStatus } from 'features/nodes/types/invocation';import { LRUCache } from 'lru-cache';import type { S } from 'services/api/types';import {@@ -10,6 +8,7 @@ import {import {getCompletedInvocationIdsFromCompletedSession,getNodeExecutionStatesFromCompletedSession,+ getResetNodeExecutionStatesOnQueueItemStarted,getUpdatedNodeExecutionStateOnInvocationError,getUpdatedNodeExecutionStateOnInvocationProgress,getUpdatedNodeExecutionStateOnInvocationStarted,@@ -215,17 +214,19 @@ export const createWorkflowExecutionCoordinator = (deps: WorkflowExecutionCoordi}if (data.status === 'in_progress') {- for (const nes of Object.values(deps.getAllNodeExecutionStates())) {+ const nextNodeExecutionStates = getResetNodeExecutionStatesOnQueueItemStarted(+ deps.getAllNodeExecutionStates(),+ data.item_id,+ deps.completedInvocationKeysByItemId+ );+ if (!nextNodeExecutionStates) {+ return true;+ }+ for (const nes of Object.values(nextNodeExecutionStates)) {if (!nes) {continue;}- const clone = deepClone(nes);- clone.status = zNodeStatus.enum.PENDING;- clone.error = null;- clone.progress = null;- clone.progressImage = null;- clone.outputs = [];- deps.setNodeExecutionState(clone.nodeId, clone);+ deps.setNodeExecutionState(nes.nodeId, nes);}} else if (data.status === 'completed' || data.status === 'failed' || data.status === 'canceled') {if (data.origin === 'workflows') {diff --git a/tests/app/invocations/test_call_saved_workflows.py b/tests/app/invocations/test_call_saved_workflows.pynew file mode 100644index 0000000000..cb5cde5ca9--- /dev/null+++ b/tests/app/invocations/test_call_saved_workflows.py@@ -0,0 +1,421 @@+from types import SimpleNamespace+from unittest.mock import Mock++import pytest++from invokeai.app.services.users.users_common import UserDTO+from invokeai.app.services.workflow_records.workflow_records_common import (+ Workflow,+ WorkflowCategory,+ WorkflowMeta,+ WorkflowNotFoundError,+ WorkflowRecordDTO,+ WorkflowWithoutIDValidator,+)+++def build_workflow_record_dto(+ *,+ workflow_id: str = "workflow-123",+ user_id: str = "owner-1",+ category: WorkflowCategory = WorkflowCategory.User,+ is_public: bool = False,+) -> WorkflowRecordDTO:+ workflow = Workflow(+ id=workflow_id,+ name="Saved Workflow",+ author="Tester",+ description="",+ version="1.0.0",+ contact="",+ tags="",+ notes="",+ exposedFields=[],+ meta=WorkflowMeta(version="1.0.0", category=category),+ nodes=[],+ edges=[],+ form=None,+ )++ return WorkflowRecordDTO(+ workflow_id=workflow_id,+ workflow=workflow,+ name=workflow.name,+ created_at="2026-04-08T00:00:00Z",+ updated_at="2026-04-08T00:00:00Z",+ opened_at=None,+ user_id=user_id,+ is_public=is_public,+ )+++def build_user_dto(*, user_id: str = "user-1", is_admin: bool = False) -> UserDTO:+ return UserDTO(+ user_id=user_id,+ email=f"{user_id}@example.test",+ display_name=user_id,+ is_admin=is_admin,+ is_active=True,+ created_at="2026-04-08T00:00:00Z",+ updated_at="2026-04-08T00:00:00Z",+ last_login_at=None,+ )+++def build_context(+ *,+ workflow_record: WorkflowRecordDTO | None = None,+ queue_user_id: str = "owner-1",+ multiuser: bool = False,+ user_is_admin: bool = False,+ user_exists: bool = True,+ workflow_not_found: bool = False,+):+ services = SimpleNamespace(+ configuration=SimpleNamespace(multiuser=multiuser),+ users=Mock(),+ workflow_records=Mock(),+ )+ services.users.get.return_value = (+ build_user_dto(user_id=queue_user_id, is_admin=user_is_admin) if user_exists else None+ )++ if workflow_not_found:+ services.workflow_records.get.side_effect = WorkflowNotFoundError("missing")+ else:+ services.workflow_records.get.return_value = workflow_record or build_workflow_record_dto()++ context = Mock()+ context._services = services+ context._data = SimpleNamespace(queue_item=SimpleNamespace(user_id=queue_user_id))+ return context+++def test_call_saved_workflow_invocation_contract():+ from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation+ from invokeai.app.invocations.workflow_return import WorkflowReturnOutput++ invocation = CallSavedWorkflowInvocation(id="test-node", workflow_id="workflow-123")++ assert invocation.get_type() == "call_saved_workflow"+ assert invocation.workflow_id == "workflow-123"++ output = invocation.invoke(build_context())++ assert isinstance(output, WorkflowReturnOutput)+ assert output.values == {}+++def test_call_saved_workflow_invocation_raises_when_workflow_id_is_empty():+ from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation++ invocation = CallSavedWorkflowInvocation(id="test-node")++ with pytest.raises(ValueError, match="saved workflow must be selected"):+ invocation.invoke(build_context())+++def test_call_saved_workflow_invocation_raises_when_workflow_does_not_exist():+ from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation++ invocation = CallSavedWorkflowInvocation(id="test-node", workflow_id="missing-workflow")++ with pytest.raises(ValueError, match="could not be found"):+ invocation.invoke(build_context(workflow_not_found=True))+++def test_call_saved_workflow_invocation_raises_when_workflow_is_not_accessible():+ from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation++ invocation = CallSavedWorkflowInvocation(id="test-node", workflow_id="private-workflow")++ with pytest.raises(ValueError, match="is not accessible"):+ invocation.invoke(+ build_context(+ workflow_record=build_workflow_record_dto(+ workflow_id="private-workflow",+ user_id="owner-1",+ category=WorkflowCategory.User,+ is_public=False,+ ),+ queue_user_id="other-user",+ multiuser=True,+ user_is_admin=False,+ )+ )+++def test_call_saved_workflow_invocation_allows_shared_workflow_for_non_owner():+ from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation++ invocation = CallSavedWorkflowInvocation(id="test-node", workflow_id="shared-workflow")++ output = invocation.invoke(+ build_context(+ workflow_record=build_workflow_record_dto(+ workflow_id="shared-workflow",+ user_id="owner-1",+ category=WorkflowCategory.User,+ is_public=True,+ ),+ queue_user_id="other-user",+ multiuser=True,+ user_is_admin=False,+ )+ )++ assert output.values == {}+++def test_call_saved_workflow_invocation_allows_default_workflow_for_non_owner():+ from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation++ invocation = CallSavedWorkflowInvocation(id="test-node", workflow_id="default-workflow")++ output = invocation.invoke(+ build_context(+ workflow_record=build_workflow_record_dto(+ workflow_id="default-workflow",+ user_id="system",+ category=WorkflowCategory.Default,+ is_public=False,+ ),+ queue_user_id="other-user",+ multiuser=True,+ user_is_admin=False,+ )+ )++ assert output.values == {}+++def test_call_saved_workflow_invocation_allows_admin_to_access_private_workflow():+ from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation++ invocation = CallSavedWorkflowInvocation(id="test-node", workflow_id="private-workflow")++ output = invocation.invoke(+ build_context(+ workflow_record=build_workflow_record_dto(+ workflow_id="private-workflow",+ user_id="owner-1",+ category=WorkflowCategory.User,+ is_public=False,+ ),+ queue_user_id="admin-user",+ multiuser=True,+ user_is_admin=True,+ )+ )++ assert output.values == {}+++def test_call_saved_workflow_invocation_raises_when_private_workflow_user_record_is_missing():+ from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation++ invocation = CallSavedWorkflowInvocation(id="test-node", workflow_id="private-workflow")++ with pytest.raises(ValueError, match="is not accessible"):+ invocation.invoke(+ build_context(+ workflow_record=build_workflow_record_dto(+ workflow_id="private-workflow",+ user_id="owner-1",+ category=WorkflowCategory.User,+ is_public=False,+ ),+ queue_user_id="other-user",+ multiuser=True,+ user_exists=False,+ )+ )+++def test_call_saved_workflow_invocation_schema_declares_saved_workflow_ui_type():+ from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation++ schema = CallSavedWorkflowInvocation.model_json_schema()+ workflow_id = schema["properties"]["workflow_id"]+ workflow_inputs = schema["properties"]["workflow_inputs"]++ assert workflow_id["default"] == ""+ assert workflow_id["input"] == "any"+ assert workflow_id["ui_type"] == "SavedWorkflowField"+ assert workflow_inputs["default"] == {}+ assert workflow_inputs["ui_hidden"] is True+++def test_workflow_return_invocation_contract():+ from invokeai.app.invocations.workflow_return import (+ WorkflowReturnInvocation,+ WorkflowReturnOutput,+ WorkflowReturnValueField,+ )++ invocation = WorkflowReturnInvocation(+ id="return-node",+ values=[+ WorkflowReturnValueField(key="prompt", value="a"),+ WorkflowReturnValueField(key="count", value=1),+ WorkflowReturnValueField(key="metadata", value={"x": True}),+ ],+ )++ assert invocation.get_type() == "workflow_return"++ output = invocation.invoke(build_context())++ assert isinstance(output, WorkflowReturnOutput)+ assert output.values == {"prompt": "a", "count": 1, "metadata": {"x": True}}+ assert not hasattr(output, "collection")+++def test_workflow_return_invocation_accepts_single_return_value():+ from invokeai.app.invocations.workflow_return import WorkflowReturnInvocation, WorkflowReturnValueField++ invocation = WorkflowReturnInvocation(id="return-node", values=WorkflowReturnValueField(key="sum", value=3))++ output = invocation.invoke(build_context())++ assert output.values == {"sum": 3}+++def test_workflow_return_values_schema_preserves_single_or_list_cardinality():+ from invokeai.app.invocations.workflow_return import WorkflowReturnInvocation++ values_schema = WorkflowReturnInvocation.model_json_schema()["properties"]["values"]++ assert values_schema["anyOf"] == [+ {"$ref": "#/$defs/WorkflowReturnValueField"},+ {"items": {"$ref": "#/$defs/WorkflowReturnValueField"}, "type": "array"},+ ]+ assert values_schema.get("ui_type") != "CollectionField"+++def test_workflow_return_value_invocation_contract():+ from invokeai.app.invocations.workflow_return import WorkflowReturnValueField, WorkflowReturnValueInvocation++ invocation = WorkflowReturnValueInvocation(id="return-value-node", key="image", value={"image_name": "image-a"})++ output = invocation.invoke(build_context())++ assert output.value == WorkflowReturnValueField(key="image", value={"image_name": "image-a"})+++def test_workflow_return_value_field_survives_exclude_none_session_roundtrip():+ from invokeai.app.invocations.workflow_return import (+ WorkflowReturnInvocation,+ WorkflowReturnValueField,+ WorkflowReturnValueOutput,+ )+ from invokeai.app.services.shared.graph import Graph, GraphExecutionState++ graph = Graph()+ graph.add_node(+ WorkflowReturnInvocation(id="return-node", values=WorkflowReturnValueField(key="nullable", value=None))+ )+ session = GraphExecutionState(graph=graph)+ session.execution_graph.add_node(+ WorkflowReturnInvocation(id="return-node", values=WorkflowReturnValueField(key="nullable", value=None))+ )+ session.results["return-value-node"] = WorkflowReturnValueOutput(+ value=WorkflowReturnValueField(key="nullable", value=None)+ )++ reloaded = GraphExecutionState.model_validate_json(session.model_dump_json(warnings=False, exclude_none=True))++ assert reloaded.execution_graph.nodes["return-node"].values == WorkflowReturnValueField(key="nullable", value=None)+ assert reloaded.results["return-value-node"].value == WorkflowReturnValueField(key="nullable", value=None)+++def test_workflow_return_invocation_rejects_duplicate_keys():+ from invokeai.app.invocations.workflow_return import WorkflowReturnInvocation, WorkflowReturnValueField++ invocation = WorkflowReturnInvocation(+ id="return-node",+ values=[+ WorkflowReturnValueField(key="image", value="image-a"),+ WorkflowReturnValueField(key="image", value="image-b"),+ ],+ )++ with pytest.raises(ValueError, match="Duplicate workflow return key 'image'"):+ invocation.invoke(build_context())+++def test_workflow_return_get_invocation_contract():+ from invokeai.app.invocations.workflow_return import WorkflowReturnGetInvocation++ invocation = WorkflowReturnGetInvocation(id="return-get-node", values={"image": "image-a"}, key="image")++ output = invocation.invoke(build_context())++ assert output.value == "image-a"+++def test_workflow_return_get_invocation_rejects_missing_key():+ from invokeai.app.invocations.workflow_return import WorkflowReturnGetInvocation++ invocation = WorkflowReturnGetInvocation(id="return-get-node", values={"image": "image-a"}, key="mask")++ with pytest.raises(ValueError, match="Workflow return key 'mask' was not found"):+ invocation.invoke(build_context())+++def test_workflow_return_get_invocation_rejects_empty_key():+ from invokeai.app.invocations.workflow_return import WorkflowReturnGetInvocation++ invocation = WorkflowReturnGetInvocation(id="return-get-node", values={"image": "image-a"}, key=" ")++ with pytest.raises(ValueError, match="Workflow return key must not be empty"):+ invocation.invoke(build_context())+++def test_workflow_return_invocation_schema_declares_named_values_contract():+ from invokeai.app.invocations.workflow_return import WorkflowReturnGetInvocation, WorkflowReturnInvocation++ schema = WorkflowReturnInvocation.model_json_schema()+ assert "collection" not in schema["properties"]+ values = schema["properties"]["values"]++ assert values["input"] == "connection"+ assert "ui_type" not in values++ get_schema = WorkflowReturnGetInvocation.model_json_schema()+ get_values = get_schema["properties"]["values"]+ assert get_values["input"] == "connection"+ assert get_values["ui_type"] == "AnyField"+++def test_workflow_without_id_validator_rejects_duplicate_workflow_return_nodes():+ with pytest.raises(ValueError, match="workflow_return"):+ WorkflowWithoutIDValidator.validate_python(+ {+ "name": "Workflow With Duplicate Returns",+ "author": "Tester",+ "description": "",+ "version": "1.0.0",+ "contact": "",+ "tags": "",+ "notes": "",+ "exposedFields": [],+ "meta": {"version": "1.0.0", "category": "user"},+ "nodes": [+ {+ "id": "return-1",+ "type": "invocation",+ "data": {"id": "return-1", "type": "workflow_return"},+ "position": {"x": 0, "y": 0},+ },+ {+ "id": "return-2",+ "type": "invocation",+ "data": {"id": "return-2", "type": "workflow_return"},+ "position": {"x": 100, "y": 0},+ },+ ],+ "edges": [],+ "form": None,+ }+ )diff --git a/tests/app/routers/conftest.py b/tests/app/routers/conftest.pyindex 73cd38e45f..1355f618be 100644--- a/tests/app/routers/conftest.py+++ b/tests/app/routers/conftest.py@@ -55,6 +55,7 @@ _PATCHED_API_DEPENDENCIES_MODULES = ("invokeai.app.api.routers.utilities","invokeai.app.api.routers.virtual_boards","invokeai.app.api.routers.images",+ "invokeai.app.api.routers.workflows","invokeai.app.api.routers._access",)@@ -105,6 +106,7 @@ def enable_multiuser(monkeypatch: Any, mock_invoker: Invoker):mock_invoker.services.style_preset_image_files = MagicMock()mock_invoker.services.model_relationships = MagicMock()mock_invoker.services.model_manager = MagicMock()+ mock_invoker.services.workflow_thumbnails = MagicMock()# Style preset records uses a real SQLite-backed storage on the same in-memory# database that image_records was wired up against. This lets cross-user testsdiff --git a/tests/app/routers/test_multiuser_authorization.py b/tests/app/routers/test_multiuser_authorization.pyindex 95efbf6690..f1ae8defa1 100644--- a/tests/app/routers/test_multiuser_authorization.py+++ b/tests/app/routers/test_multiuser_authorization.py@@ -10,7 +10,7 @@ These tests verify the security fixes for:import loggingfrom typing import Any-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMockimport pytestfrom fastapi import status@@ -1349,6 +1349,7 @@ class TestQueueStatusScoping:batch_id=None,pending=2,in_progress=0,+ waiting=0,completed=1,failed=0,canceled=0,@@ -1378,6 +1379,7 @@ class TestQueueStatusScoping:batch_id=None,pending=5,in_progress=1,+ waiting=0,completed=0,failed=0,canceled=0,@@ -1680,11 +1682,15 @@ class TestWebSocketAuth:import asynciomock_invoker.services.configuration.multiuser = False+ socketio._sio.enter_room = AsyncMock()result = asyncio.run(socketio._handle_connect("sid-single-1", environ={}, auth=None))assert result is Trueassert socketio._socket_users["sid-single-1"]["user_id"] == "system"assert socketio._socket_users["sid-single-1"]["is_admin"] is True+ socketio._sio.enter_room.assert_any_call("sid-single-1", "user:system")+ socketio._sio.enter_room.assert_any_call("sid-single-1", "workflows:shared")+ socketio._sio.enter_room.assert_any_call("sid-single-1", "admin")def test_connect_accepted_with_valid_token_in_multiuser_mode(self,@@ -1699,6 +1705,7 @@ class TestWebSocketAuth:from invokeai.app.services.users.users_common import UserCreateRequestmock_invoker.services.configuration.multiuser = True+ socketio._sio.enter_room = AsyncMock()# Create the user in the database so the active-user check passesuser = mock_invoker.services.users.create(@@ -1847,6 +1854,7 @@ class TestWebSocketAuth:destination="canvas",pending=0,in_progress=1,+ waiting=0,completed=0,failed=0,canceled=0,@@ -1859,6 +1867,7 @@ class TestWebSocketAuth:batch_id="batch-private",pending=0,in_progress=1,+ waiting=0,completed=0,failed=0,canceled=0,@@ -1974,6 +1983,83 @@ class TestWebSocketAuth:assert "sid-admin" in skip_sidassert "sid-other" not in skip_sid+ def test_queue_items_retried_event_carries_user_ids(self) -> None:+ """QueueItemsRetriedEvent must carry owner identity so retry notifications are+ routed privately instead of broadcast to all queue subscribers."""+ from invokeai.app.services.events.events_common import QueueItemsRetriedEvent+ from invokeai.app.services.session_queue.session_queue_common import RetryItemsResult++ retry_result = RetryItemsResult(queue_id="default", retried_item_ids=[10])+ event = QueueItemsRetriedEvent.build(+ retry_result, user_ids=["owner-123"], retried_item_ids_by_user={"owner-123": [10]}+ )++ assert event.user_ids == ["owner-123"]+ assert event.retried_item_ids == [10]+ assert event.retried_item_ids_by_user == {"owner-123": [10]}+ assert event.queue_id == "default"++ def test_queue_items_retried_routed_privately(self, socketio: Any) -> None:+ """Verify that queue_items_retried is emitted only to owner/admin rooms."""+ import asyncio+ from unittest.mock import AsyncMock++ from invokeai.app.services.events.events_common import QueueItemsRetriedEvent+ from invokeai.app.services.session_queue.session_queue_common import RetryItemsResult++ event = QueueItemsRetriedEvent.build(+ RetryItemsResult(queue_id="default", retried_item_ids=[10]),+ user_ids=["owner-123", "owner-456"],+ retried_item_ids_by_user={"owner-123": [10], "owner-456": []},+ )++ mock_emit = AsyncMock()+ socketio._sio.emit = mock_emit++ asyncio.run(socketio._handle_queue_event(("queue_items_retried", event)))++ rooms_emitted_to = [call.kwargs.get("room") for call in mock_emit.call_args_list]+ assert "user:owner-123" in rooms_emitted_to+ assert "user:owner-456" in rooms_emitted_to+ assert "admin" in rooms_emitted_to+ assert "default" not in rooms_emitted_to++ def test_queue_items_retried_payload_is_filtered_per_owner_room(self, socketio: Any) -> None:+ """Each owner room should only receive retry payload for that owner."""+ import asyncio+ from unittest.mock import AsyncMock++ from invokeai.app.services.events.events_common import QueueItemsRetriedEvent+ from invokeai.app.services.session_queue.session_queue_common import RetryItemsResult++ event = QueueItemsRetriedEvent.build(+ RetryItemsResult(queue_id="default", retried_item_ids=[10, 20]),+ user_ids=["owner-123", "owner-456"],+ retried_item_ids_by_user={"owner-123": [10], "owner-456": [20]},+ )++ mock_emit = AsyncMock()+ socketio._sio.emit = mock_emit++ asyncio.run(socketio._handle_queue_event(("queue_items_retried", event)))++ owner_123_calls = [call for call in mock_emit.call_args_list if call.kwargs.get("room") == "user:owner-123"]+ owner_456_calls = [call for call in mock_emit.call_args_list if call.kwargs.get("room") == "user:owner-456"]+ admin_calls = [call for call in mock_emit.call_args_list if call.kwargs.get("room") == "admin"]++ assert len(owner_123_calls) == 1+ assert len(owner_456_calls) == 1+ assert len(admin_calls) == 1+ assert owner_123_calls[0].kwargs["data"]["retried_item_ids"] == [10]+ assert owner_123_calls[0].kwargs["data"]["user_ids"] == ["owner-123"]+ assert owner_123_calls[0].kwargs["data"]["retried_item_ids_by_user"] == {"owner-123": [10]}+ assert owner_456_calls[0].kwargs["data"]["retried_item_ids"] == [20]+ assert owner_456_calls[0].kwargs["data"]["user_ids"] == ["owner-456"]+ assert owner_456_calls[0].kwargs["data"]["retried_item_ids_by_user"] == {"owner-456": [20]}+ assert admin_calls[0].kwargs["data"]["retried_item_ids"] == [10, 20]+ assert admin_calls[0].kwargs["data"]["user_ids"] == ["owner-123", "owner-456"]+ assert admin_calls[0].kwargs["data"]["retried_item_ids_by_user"] == {"owner-123": [10], "owner-456": [20]}+def test_queue_cleared_still_broadcast(self, socketio: Any) -> None:"""QueueClearedEvent does not carry user identity and should still be broadcastto all queue subscribers — this is a sanity check that we haven't over-scoped."""diff --git a/tests/app/routers/test_session_queue_sanitization.py b/tests/app/routers/test_session_queue_sanitization.pyindex 1cd7a4953d..9fe1551058 100644--- a/tests/app/routers/test_session_queue_sanitization.py+++ b/tests/app/routers/test_session_queue_sanitization.py@@ -52,6 +52,11 @@ def sample_session_queue_item() -> SessionQueueItem:],session=session,workflow=None,+ workflow_call_id="workflow-call-1",+ parent_item_id=99,+ parent_session_id="parent-session-1",+ root_item_id=1,+ workflow_call_depth=2,created_at=now,updated_at=now,started_at=None,@@ -139,6 +144,20 @@ def test_sanitize_preserves_non_sensitive_fields(sample_session_queue_item):assert result.user_email is None+def test_sanitize_redacts_workflow_call_metadata_for_different_user(sample_session_queue_item):+ result = sanitize_queue_item_for_user(+ queue_item=sample_session_queue_item,+ current_user_id="different_user",+ is_admin=False,+ )++ assert result.workflow_call_id is None+ assert result.parent_item_id is None+ assert result.parent_session_id is None+ assert result.root_item_id is None+ assert result.workflow_call_depth is None++def test_sanitize_system_user_item_for_non_admin(sample_session_queue_item):"""Test that non-admin users cannot see sensitive data from System user's queue items."""# Simulate a legacy System user queue itemdiff --git a/tests/app/routers/test_session_queue_workflow_call.py b/tests/app/routers/test_session_queue_workflow_call.pynew file mode 100644index 0000000000..d8fd465d8d--- /dev/null+++ b/tests/app/routers/test_session_queue_workflow_call.py@@ -0,0 +1,430 @@+"""Tests for session queue API behavior with workflow-call queue items."""++import logging+import uuid+from typing import Any+from unittest.mock import MagicMock++import pytest+from fastapi.testclient import TestClient++from invokeai.app.api.dependencies import ApiDependencies+from invokeai.app.api_app import app+from invokeai.app.services.config.config_default import InvokeAIAppConfig+from invokeai.app.services.invocation_services import InvocationServices+from invokeai.app.services.invoker import Invoker+from invokeai.app.services.session_processor.session_processor_common import SessionProcessorStatus+from invokeai.app.services.session_queue.session_queue_sqlite import SqliteSessionQueue+from invokeai.app.services.shared.graph import Graph, GraphExecutionState+from invokeai.app.services.users.users_common import UserCreateRequest+from invokeai.app.services.workflow_records.workflow_records_sqlite import SqliteWorkflowRecordsStorage+from invokeai.backend.util.logging import InvokeAILogger+from tests.fixtures.sqlite_database import create_mock_sqlite_database+++class MockApiDependencies(ApiDependencies):+ invoker: Invoker++ def __init__(self, invoker: Invoker) -> None:+ self.invoker = invoker+++def setup_jwt_secret():+ from invokeai.app.services.auth.token_service import set_jwt_secret++ set_jwt_secret("test-secret-key-for-unit-tests-only-do-not-use-in-production")+++def client():+ return TestClient(app)+++def mock_services() -> InvocationServices:+ from invokeai.app.services.board_image_records.board_image_records_sqlite import SqliteBoardImageRecordStorage+ from invokeai.app.services.board_records.board_records_sqlite import SqliteBoardRecordStorage+ from invokeai.app.services.boards.boards_default import BoardService+ from invokeai.app.services.bulk_download.bulk_download_default import BulkDownloadService+ from invokeai.app.services.client_state_persistence.client_state_persistence_sqlite import (+ ClientStatePersistenceSqlite,+ )+ from invokeai.app.services.image_records.image_records_sqlite import SqliteImageRecordStorage+ from invokeai.app.services.images.images_default import ImageService+ from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache+ from invokeai.app.services.invocation_stats.invocation_stats_default import InvocationStatsService+ from invokeai.app.services.users.users_default import UserService+ from tests.test_nodes import TestEventService++ configuration = InvokeAIAppConfig(use_memory_db=True, node_cache_size=0)+ logger = InvokeAILogger.get_logger()+ db = create_mock_sqlite_database(configuration, logger)++ return InvocationServices(+ board_image_records=SqliteBoardImageRecordStorage(db=db),+ board_images=None, # type: ignore+ board_records=SqliteBoardRecordStorage(db=db),+ boards=BoardService(),+ bulk_download=BulkDownloadService(),+ configuration=configuration,+ events=TestEventService(),+ image_files=None, # type: ignore+ image_records=SqliteImageRecordStorage(db=db),+ images=ImageService(),+ invocation_cache=MemoryInvocationCache(max_cache_size=0),+ logger=logging, # type: ignore+ model_images=None, # type: ignore+ model_manager=None, # type: ignore+ download_queue=None, # type: ignore+ names=None, # type: ignore+ performance_statistics=InvocationStatsService(),+ session_processor=None, # type: ignore+ session_queue=None, # type: ignore+ urls=None, # type: ignore+ workflow_records=SqliteWorkflowRecordsStorage(db=db),+ tensors=None, # type: ignore+ conditioning=None, # type: ignore+ style_preset_records=None, # type: ignore+ style_preset_image_files=None, # type: ignore+ workflow_thumbnails=None, # type: ignore+ model_relationship_records=None, # type: ignore+ model_relationships=None, # type: ignore+ client_state_persistence=ClientStatePersistenceSqlite(db=db),+ users=UserService(db),+ external_generation=None, # type: ignore+ )+++def mock_invoker(mock_services: InvocationServices) -> Invoker:+ invoker = Invoker(services=mock_services)+ queue = SqliteSessionQueue(db=mock_services.board_records._db)+ mock_services.session_queue = queue+ mock_services.session_processor = MagicMock()+ mock_services.session_processor.get_status.return_value = SessionProcessorStatus(+ is_started=True, is_processing=False+ )+ queue.start(invoker)+ return invoker+++def _create_user(mock_invoker: Invoker, email: str, display_name: str, is_admin: bool = False) -> str:+ user = mock_invoker.services.users.create(+ UserCreateRequest(email=email, display_name=display_name, password="TestPass123", is_admin=is_admin)+ )+ return user.user_id+++def _login(client: TestClient, email: str) -> str:+ response = client.post("/api/v1/auth/login", json={"email": email, "password": "TestPass123", "remember_me": False})+ assert response.status_code == 200+ return response.json()["token"]+++def _auth(token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {token}"}+++def enable_multiuser(monkeypatch: Any, mock_invoker: Invoker):+ mock_invoker.services.configuration.multiuser = True+ mock_deps = MockApiDependencies(mock_invoker)+ monkeypatch.setattr("invokeai.app.api.routers.auth.ApiDependencies", mock_deps)+ monkeypatch.setattr("invokeai.app.api.auth_dependencies.ApiDependencies", mock_deps)+ monkeypatch.setattr("invokeai.app.api.routers.session_queue.ApiDependencies", mock_deps)+ yield+++def admin_token(setup_jwt_secret: None, enable_multiuser: Any, mock_invoker: Invoker, client: TestClient):+ _create_user(mock_invoker, "[email protected]", "Admin", is_admin=True)+ return _login(client, "[email protected]")+++def user1_token(enable_multiuser: Any, mock_invoker: Invoker, client: TestClient, admin_token: str):+ _create_user(mock_invoker, "[email protected]", "User One")+ return _login(client, "[email protected]")+++def user2_token(enable_multiuser: Any, mock_invoker: Invoker, client: TestClient, admin_token: str):+ _create_user(mock_invoker, "[email protected]", "User Two")+ return _login(client, "[email protected]")+++def _insert_queue_item(+ session_queue: SqliteSessionQueue,+ *,+ queue_id: str = "default",+ user_id: str,+ status: str,+ session: GraphExecutionState | None = None,+ workflow_call_id: str | None = None,+ parent_item_id: int | None = None,+ parent_session_id: str | None = None,+ root_item_id: int | None = None,+ workflow_call_depth: int | None = None,+) -> int:+ session = session or GraphExecutionState(graph=Graph())+ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, field_values, priority, workflow, origin, destination,+ retried_from_item_id, user_id, status, workflow_call_id, parent_item_id, parent_session_id,+ root_item_id, workflow_call_depth+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ queue_id,+ session.model_dump_json(warnings=False),+ session.id,+ str(uuid.uuid4()),+ None,+ 0,+ None,+ None,+ None,+ None,+ user_id,+ status,+ workflow_call_id,+ parent_item_id,+ parent_session_id,+ root_item_id,+ workflow_call_depth,+ ),+ )+ return cursor.lastrowid+++def test_get_queue_status_reports_waiting_for_owner(+ client: TestClient, mock_invoker: Invoker, user1_token: str, user2_token: str+) -> None:+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ user2 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None and user2 is not None++ _insert_queue_item(mock_invoker.services.session_queue, user_id=user1.user_id, status="waiting")+ _insert_queue_item(mock_invoker.services.session_queue, user_id=user2.user_id, status="pending")++ response = client.get("/api/v1/queue/default/status", headers=_auth(user1_token))++ assert response.status_code == 200+ payload = response.json()+ assert payload["queue"]["waiting"] == 1+ assert payload["queue"]["pending"] == 1+ assert payload["queue"]["in_progress"] == 0+ assert payload["queue"]["total"] == 2+ assert payload["queue"]["user_pending"] == 0+ assert payload["queue"]["user_in_progress"] == 0+ assert payload["queue"]["item_id"] is None+++def test_get_queue_item_sanitizes_workflow_call_metadata_for_non_owner(+ client: TestClient, mock_invoker: Invoker, user1_token: str, user2_token: str+) -> None:+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None++ item_id = _insert_queue_item(+ mock_invoker.services.session_queue,+ user_id=user1.user_id,+ status="waiting",+ workflow_call_id="workflow-call-1",+ parent_item_id=41,+ parent_session_id="parent-session-1",+ root_item_id=17,+ workflow_call_depth=2,+ )++ response = client.get(f"/api/v1/queue/default/i/{item_id}", headers=_auth(user2_token))++ assert response.status_code == 200+ payload = response.json()+ assert payload["status"] == "waiting"+ assert payload["item_id"] == item_id+ assert payload["user_id"] == "redacted"+ assert payload["batch_id"] == "redacted"+ assert payload["session_id"] == "redacted"+ assert payload.get("workflow_call_id") is None+ assert payload.get("parent_item_id") is None+ assert payload.get("parent_session_id") is None+ assert payload.get("root_item_id") is None+ assert payload.get("workflow_call_depth") is None+++def test_retry_items_by_id_normalizes_child_to_root_at_router(+ client: TestClient, mock_invoker: Invoker, user1_token: str+) -> None:+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None++ root_item_id = _insert_queue_item(mock_invoker.services.session_queue, user_id=user1.user_id, status="failed")+ child_item_id = _insert_queue_item(+ mock_invoker.services.session_queue,+ user_id=user1.user_id,+ status="failed",+ workflow_call_id="workflow-call-1",+ parent_item_id=root_item_id,+ parent_session_id="parent-session-1",+ root_item_id=root_item_id,+ workflow_call_depth=1,+ )++ response = client.put("/api/v1/queue/default/retry_items_by_id", headers=_auth(user1_token), json=[child_item_id])++ assert response.status_code == 200+ assert response.json()["retried_item_ids"] == [root_item_id]+++def test_retry_items_by_id_rejects_items_from_other_queue(+ client: TestClient, mock_invoker: Invoker, user1_token: str+) -> None:+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None++ item_id = _insert_queue_item(+ mock_invoker.services.session_queue,+ queue_id="secondary",+ user_id=user1.user_id,+ status="failed",+ )++ response = client.put("/api/v1/queue/default/retry_items_by_id", headers=_auth(user1_token), json=[item_id])++ assert response.status_code == 404+++def test_retry_items_by_id_authorizes_workflow_call_root_owner(+ client: TestClient, mock_invoker: Invoker, user1_token: str, user2_token: str+) -> None:+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ user2 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None and user2 is not None++ root_item_id = _insert_queue_item(mock_invoker.services.session_queue, user_id=user2.user_id, status="failed")+ child_item_id = _insert_queue_item(+ mock_invoker.services.session_queue,+ user_id=user1.user_id,+ status="failed",+ workflow_call_id="workflow-call-1",+ parent_item_id=root_item_id,+ parent_session_id="parent-session-1",+ root_item_id=root_item_id,+ workflow_call_depth=1,+ )++ response = client.put("/api/v1/queue/default/retry_items_by_id", headers=_auth(user1_token), json=[child_item_id])++ assert response.status_code == 403+ assert mock_invoker.services.session_queue.get_queue_item(root_item_id).status == "failed"+++def test_retry_items_by_id_skips_missing_items_and_retries_valid_items(+ client: TestClient, mock_invoker: Invoker, user1_token: str+) -> None:+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None++ root_item_id = _insert_queue_item(mock_invoker.services.session_queue, user_id=user1.user_id, status="failed")++ response = client.put(+ "/api/v1/queue/default/retry_items_by_id",+ headers=_auth(user1_token),+ json=[root_item_id + 9999, root_item_id],+ )++ assert response.status_code == 200+ assert response.json()["retried_item_ids"] == [root_item_id]+++def test_cancel_queue_item_cascades_to_waiting_parent_via_router(+ client: TestClient, mock_invoker: Invoker, user1_token: str+) -> None:+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None++ parent_item_id = _insert_queue_item(mock_invoker.services.session_queue, user_id=user1.user_id, status="waiting")+ child_item_id = _insert_queue_item(+ mock_invoker.services.session_queue,+ user_id=user1.user_id,+ status="pending",+ workflow_call_id="workflow-call-1",+ parent_item_id=parent_item_id,+ parent_session_id="parent-session-1",+ root_item_id=parent_item_id,+ workflow_call_depth=1,+ )++ response = client.put(f"/api/v1/queue/default/i/{child_item_id}/cancel", headers=_auth(user1_token))++ assert response.status_code == 200+ assert response.json()["status"] == "canceled"+ assert mock_invoker.services.session_queue.get_queue_item(parent_item_id).status == "canceled"+ assert mock_invoker.services.session_queue.get_queue_item(child_item_id).status == "canceled"+++def test_cancel_queue_item_rejects_item_from_other_queue(+ client: TestClient, mock_invoker: Invoker, user1_token: str+) -> None:+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None++ item_id = _insert_queue_item(+ mock_invoker.services.session_queue,+ queue_id="secondary",+ user_id=user1.user_id,+ status="pending",+ )++ response = client.put(f"/api/v1/queue/default/i/{item_id}/cancel", headers=_auth(user1_token))++ assert response.status_code == 404+++def test_delete_queue_item_rejects_item_from_other_queue(+ client: TestClient, mock_invoker: Invoker, user1_token: str+) -> None:+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None++ item_id = _insert_queue_item(+ mock_invoker.services.session_queue,+ queue_id="secondary",+ user_id=user1.user_id,+ status="failed",+ )++ response = client.delete(f"/api/v1/queue/default/i/{item_id}", headers=_auth(user1_token))++ assert response.status_code == 404+++def test_delete_queue_item_authorizes_workflow_call_root_owner(+ client: TestClient, mock_invoker: Invoker, user1_token: str, user2_token: str+) -> None:+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ user2 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None and user2 is not None++ root_item_id = _insert_queue_item(mock_invoker.services.session_queue, user_id=user2.user_id, status="failed")+ child_item_id = _insert_queue_item(+ mock_invoker.services.session_queue,+ user_id=user1.user_id,+ status="failed",+ workflow_call_id="workflow-call-1",+ parent_item_id=root_item_id,+ parent_session_id="parent-session-1",+ root_item_id=root_item_id,+ workflow_call_depth=1,+ )++ response = client.delete(f"/api/v1/queue/default/i/{child_item_id}", headers=_auth(user1_token))++ assert response.status_code == 403+ assert mock_invoker.services.session_queue.get_queue_item(root_item_id).status == "failed"+ assert mock_invoker.services.session_queue.get_queue_item(child_item_id).status == "failed"diff --git a/tests/app/routers/test_workflow_live_updates.py b/tests/app/routers/test_workflow_live_updates.pynew file mode 100644index 0000000000..e98c5ce231--- /dev/null+++ b/tests/app/routers/test_workflow_live_updates.py@@ -0,0 +1,118 @@+"""Tests for workflow CRUD live-update events with multiuser visibility rules."""++from typing import Any++from fastapi.testclient import TestClient++from tests.app.routers.test_workflows_multiuser import WORKFLOW_BODY++pytest_plugins = ("tests.app.routers.test_workflows_multiuser",)+++def _auth(token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {token}"}+++def _event_names(events: list[Any]) -> list[str]:+ return [event.__event_name__ for event in events]+++def _get_last_event(events: list[Any], event_name: str) -> Any:+ matching = [event for event in events if event.__event_name__ == event_name]+ assert matching, f"Expected event '{event_name}' to be emitted"+ return matching[-1]+++def test_create_private_workflow_emits_owner_scoped_created_event(+ client: TestClient, user1_token: str, mock_invoker: Any+) -> None:+ response = client.post("/api/v1/workflows/", json={"workflow": WORKFLOW_BODY}, headers=_auth(user1_token))++ assert response.status_code == 200++ event = _get_last_event(mock_invoker.services.events.events, "workflow_created")+ assert event.workflow_id == response.json()["workflow_id"]+ assert event.user_id == response.json()["user_id"]+ assert event.is_public is False+++def test_update_workflow_emits_updated_event_with_previous_visibility(+ client: TestClient, user1_token: str, mock_invoker: Any+) -> None:+ create_response = client.post("/api/v1/workflows/", json={"workflow": WORKFLOW_BODY}, headers=_auth(user1_token))+ workflow_id = create_response.json()["workflow_id"]++ update_response = client.patch(+ f"/api/v1/workflows/i/{workflow_id}",+ json={"workflow": {**WORKFLOW_BODY, "id": workflow_id, "name": "Renamed Workflow"}},+ headers=_auth(user1_token),+ )++ assert update_response.status_code == 200++ event = _get_last_event(mock_invoker.services.events.events, "workflow_updated")+ assert event.workflow_id == workflow_id+ assert event.user_id == create_response.json()["user_id"]+ assert event.old_is_public is False+ assert event.new_is_public is False+++def test_update_workflow_is_public_emits_visibility_transition_event(+ client: TestClient, user1_token: str, mock_invoker: Any+) -> None:+ create_response = client.post("/api/v1/workflows/", json={"workflow": WORKFLOW_BODY}, headers=_auth(user1_token))+ workflow_id = create_response.json()["workflow_id"]++ update_response = client.patch(+ f"/api/v1/workflows/i/{workflow_id}/is_public",+ json={"is_public": True},+ headers=_auth(user1_token),+ )++ assert update_response.status_code == 200++ event = _get_last_event(mock_invoker.services.events.events, "workflow_updated")+ assert event.workflow_id == workflow_id+ assert event.user_id == create_response.json()["user_id"]+ assert event.old_is_public is False+ assert event.new_is_public is True+++def test_delete_workflow_emits_deleted_event_with_last_known_visibility(+ client: TestClient, user1_token: str, mock_invoker: Any+) -> None:+ create_response = client.post("/api/v1/workflows/", json={"workflow": WORKFLOW_BODY}, headers=_auth(user1_token))+ workflow_id = create_response.json()["workflow_id"]++ share_response = client.patch(+ f"/api/v1/workflows/i/{workflow_id}/is_public",+ json={"is_public": True},+ headers=_auth(user1_token),+ )+ assert share_response.status_code == 200++ delete_response = client.delete(f"/api/v1/workflows/i/{workflow_id}", headers=_auth(user1_token))++ assert delete_response.status_code == 200++ event = _get_last_event(mock_invoker.services.events.events, "workflow_deleted")+ assert event.workflow_id == workflow_id+ assert event.user_id == create_response.json()["user_id"]+ assert event.is_public is True+++def test_failed_update_does_not_emit_workflow_live_update_event(+ client: TestClient, user1_token: str, user2_token: str, mock_invoker: Any+) -> None:+ create_response = client.post("/api/v1/workflows/", json={"workflow": WORKFLOW_BODY}, headers=_auth(user1_token))+ workflow_id = create_response.json()["workflow_id"]+ before_event_names = _event_names(mock_invoker.services.events.events)++ update_response = client.patch(+ f"/api/v1/workflows/i/{workflow_id}",+ json={"workflow": {**WORKFLOW_BODY, "id": workflow_id, "name": "Hijacked"}},+ headers=_auth(user2_token),+ )++ assert update_response.status_code == 403+ assert _event_names(mock_invoker.services.events.events) == before_event_namesdiff --git a/tests/app/routers/test_workflows_multiuser.py b/tests/app/routers/test_workflows_multiuser.pyindex a1fa5ed5ad..372a34b870 100644--- a/tests/app/routers/test_workflows_multiuser.py+++ b/tests/app/routers/test_workflows_multiuser.py@@ -158,10 +158,10 @@ def user2_token(enable_multiuser: Any, mock_invoker: Invoker, client: TestClientreturn get_user_token(client, "[email protected]")-def create_workflow(client: TestClient, token: str) -> str:+def create_workflow(client: TestClient, token: str, workflow_body: dict[str, Any] | None = None) -> str:response = client.post("/api/v1/workflows/",- json={"workflow": WORKFLOW_BODY},+ json={"workflow": workflow_body or WORKFLOW_BODY},headers={"Authorization": f"Bearer {token}"},)assert response.status_code == 200, response.text@@ -242,6 +242,41 @@ def test_admin_can_delete_any_workflow(client: TestClient, admin_token: str, useassert response.status_code == 200+def test_list_workflows_skips_stale_workflow_rows(+ client: TestClient, user1_token: str, mock_invoker: Invoker, monkeypatch: Any+):+ workflow_id = create_workflow(client, user1_token)+ stale_id = "stale-workflow"+ workflow_records = mock_invoker.services.workflow_records+ existing = workflow_records.get(workflow_id)++ original_get_many = workflow_records.get_many+ original_get = workflow_records.get++ def fake_get_many(*args, **kwargs):+ results = original_get_many(*args, **kwargs)+ return results.model_copy(+ update={"items": [*results.items, results.items[0].model_copy(update={"workflow_id": stale_id})]}+ )++ def fake_get(requested_workflow_id: str):+ if requested_workflow_id == stale_id:+ from invokeai.app.services.workflow_records.workflow_records_common import WorkflowNotFoundError++ raise WorkflowNotFoundError("stale")+ return original_get(requested_workflow_id)++ monkeypatch.setattr(workflow_records, "get_many", fake_get_many)+ monkeypatch.setattr(workflow_records, "get", fake_get)++ response = client.get("/api/v1/workflows/?categories=user", headers={"Authorization": f"Bearer {user1_token}"})++ assert response.status_code == 200, response.text+ payload = response.json()+ assert payload["total"] == 1+ assert [item["workflow_id"] for item in payload["items"]] == [existing.workflow_id]++# ---------------------------------------------------------------------------# Shared workflow (is_public)# ---------------------------------------------------------------------------@@ -335,6 +370,71 @@ def test_workflow_has_user_id_and_is_public_fields(client: TestClient, user1_tokassert data["is_public"] is False+def test_list_workflows_includes_call_saved_workflow_compatibility(client: TestClient, user1_token: str):+ compatible_workflow_id = create_workflow(+ client,+ user1_token,+ {+ **WORKFLOW_BODY,+ "nodes": [+ {+ "id": "return",+ "type": "invocation",+ "position": {"x": 0, "y": 0},+ "data": {+ "id": "return",+ "type": "workflow_return",+ "version": "1.0.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "isOpen": True,+ "isIntermediate": False,+ "useCache": True,+ "dynamicInputTemplates": {},+ "inputs": {"collection": {"value": []}},+ },+ }+ ],+ },+ )+ incompatible_workflow_id = create_workflow(client, user1_token)++ response = client.get(+ "/api/v1/workflows/?categories=user",+ headers={"Authorization": f"Bearer {user1_token}"},+ )++ assert response.status_code == 200+ items_by_id = {item["workflow_id"]: item for item in response.json()["items"]}+ assert items_by_id[compatible_workflow_id]["call_saved_workflow_compatibility"] == {+ "is_callable": True,+ "reason": "ok",+ "message": None,+ }+ assert items_by_id[incompatible_workflow_id]["call_saved_workflow_compatibility"] == {+ "is_callable": False,+ "reason": "missing_workflow_return",+ "message": "The workflow must contain exactly one workflow_return node.",+ }+++def test_get_workflow_includes_call_saved_workflow_compatibility(client: TestClient, user1_token: str):+ workflow_id = create_workflow(client, user1_token)++ response = client.get(+ f"/api/v1/workflows/i/{workflow_id}",+ headers={"Authorization": f"Bearer {user1_token}"},+ )++ assert response.status_code == 200+ assert response.json()["call_saved_workflow_compatibility"] == {+ "is_callable": False,+ "reason": "missing_workflow_return",+ "message": "The workflow must contain exactly one workflow_return node.",+ }++# ---------------------------------------------------------------------------# System-owned workflow visibility (regression tests for migration 30 fix)# ---------------------------------------------------------------------------diff --git a/tests/app/services/auth/conftest.py b/tests/app/services/auth/conftest.pynew file mode 100644index 0000000000..83285fbfe2--- /dev/null+++ b/tests/app/services/auth/conftest.py@@ -0,0 +1,8 @@+import pytest++from invokeai.app.services.auth.token_service import set_jwt_secret++[email protected](autouse=True)+def setup_jwt_secret() -> None:+ set_jwt_secret("test-secret-key-for-unit-tests-only-do-not-use-in-production")diff --git a/tests/app/services/image_moves/test_image_moves_default.py b/tests/app/services/image_moves/test_image_moves_default.pyindex 0d4bb1ca99..e9ec55d101 100644--- a/tests/app/services/image_moves/test_image_moves_default.py+++ b/tests/app/services/image_moves/test_image_moves_default.py@@ -423,6 +423,7 @@ def test_background_move_rejects_active_queue_work(tmp_path: Path, pending: int,session_id=None,pending=pending,in_progress=in_progress,+ waiting=0,completed=0,failed=0,canceled=0,@@ -448,6 +449,7 @@ def test_background_move_is_reserved_before_queue_check(tmp_path: Path) -> None:session_id=None,pending=1,in_progress=0,+ waiting=0,completed=0,failed=0,canceled=0,diff --git a/tests/app/services/session_queue/test_session_queue_status_event_isolation.py b/tests/app/services/session_queue/test_session_queue_status_event_isolation.pyindex af7fdd8931..ecef76f1eb 100644--- a/tests/app/services/session_queue/test_session_queue_status_event_isolation.py+++ b/tests/app/services/session_queue/test_session_queue_status_event_isolation.py@@ -11,6 +11,7 @@ from typing import Optionalimport pytest+from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocationfrom invokeai.app.services.events.events_common import QueueItemStatusChangedEventfrom invokeai.app.services.invoker import Invokerfrom invokeai.app.services.session_queue.session_queue_common import SessionQueueItem@@ -47,6 +48,48 @@ def _insert_queue_item(session_queue: SqliteSessionQueue, user_id: str) -> int:return cursor.lastrowid # type: ignore[return-value]+def _insert_waiting_workflow_call_parent(+ session_queue: SqliteSessionQueue, user_id: str+) -> tuple[int, GraphExecutionState]:+ parent_graph = Graph()+ parent_graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))+ parent_session = GraphExecutionState(graph=parent_graph)+ invocation = parent_session.next()+ assert isinstance(invocation, CallSavedWorkflowInvocation)++ frame = parent_session.build_workflow_call_frame(invocation.id, invocation.workflow_id)+ child_session = parent_session.create_child_workflow_execution_state(Graph(), frame)+ parent_session.begin_waiting_on_workflow_call(frame)+ parent_session.attach_waiting_workflow_call_child_session(child_session)++ batch_id = str(uuid.uuid4())+ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, field_values,+ priority, workflow, origin, destination, retried_from_item_id, user_id, status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ parent_session.model_dump_json(warnings=False, exclude_none=True),+ parent_session.id,+ batch_id,+ None,+ 0,+ None,+ None,+ None,+ None,+ user_id,+ "waiting",+ ),+ )+ return cursor.lastrowid, child_session # type: ignore[return-value]++def _last_status_event_for_item(event_bus: TestEventService, item_id: int) -> QueueItemStatusChangedEvent:matches = [e for e in event_bus.events if isinstance(e, QueueItemStatusChangedEvent) and e.item_id == item_id]assert matches, f"No QueueItemStatusChangedEvent found for item {item_id}"@@ -208,3 +251,33 @@ def test_event_preserves_identifiers_when_current_item_is_the_changed_item(assert a_event.queue_status.item_id == a_item_idassert a_event.queue_status.session_id == in_progress.session_idassert a_event.queue_status.batch_id == in_progress.batch_id+++def test_workflow_call_child_enqueue_event_redacts_other_users_current_item_identifiers(+ session_queue: SqliteSessionQueue, mock_invoker: Invoker+) -> None:+ """The child enqueue path emits QueueItemStatusChangedEvent without going through+ _set_queue_item_status, so it must apply the same per-owner current-item redaction."""+ user_a = "user-a"+ user_b = "user-b"++ b_item_id = _insert_queue_item(session_queue, user_id=user_b)+ parent_item_id, child_session = _insert_waiting_workflow_call_parent(session_queue, user_id=user_a)++ in_progress = session_queue.dequeue()+ assert in_progress is not None and in_progress.item_id == b_item_id+ assert in_progress.user_id == user_b++ event_bus: TestEventService = mock_invoker.services.events+ event_bus.events.clear()++ parent_queue_item = session_queue.get_queue_item(parent_item_id)+ child_queue_item = session_queue.enqueue_workflow_call_child(parent_queue_item, child_session)++ child_event = _last_status_event_for_item(event_bus, child_queue_item.item_id)+ assert child_event.user_id == user_a+ assert child_event.queue_status.item_id is None, "must not leak other user's current item_id"+ assert child_event.queue_status.session_id is None, "must not leak other user's current session_id"+ assert child_event.queue_status.batch_id is None, "must not leak other user's current batch_id"+ assert child_event.queue_status.in_progress == 1+ assert child_event.queue_status.waiting == 1diff --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.pynew file mode 100644index 0000000000..8c17d71055--- /dev/null+++ b/tests/app/services/session_queue/test_session_queue_workflow_call_metadata.py@@ -0,0 +1,1323 @@+"""Tests for workflow-call relationship metadata on session_queue items."""++import uuid++import pytest++from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation+from invokeai.app.services.events.events_common import QueueItemsRetriedEvent, QueueItemStatusChangedEvent+from invokeai.app.services.invoker import Invoker+from invokeai.app.services.session_queue.session_queue_common import (+ NodeFieldValue,+ SessionQueueItemNotFoundError,+ TooManySessionsError,+)+from invokeai.app.services.session_queue.session_queue_sqlite import SqliteSessionQueue+from invokeai.app.services.shared.graph import Graph, GraphExecutionState+from tests.test_nodes import TestEventService+++def session_queue(mock_invoker: Invoker) -> SqliteSessionQueue:+ db = mock_invoker.services.board_records._db+ queue = SqliteSessionQueue(db=db)+ queue.start(mock_invoker)+ return queue+++def event_bus(mock_invoker: Invoker) -> TestEventService:+ assert isinstance(mock_invoker.services.events, TestEventService)+ return mock_invoker.services.events+++def _insert_queue_item(+ session_queue: SqliteSessionQueue,+ *,+ session: GraphExecutionState,+ status: str,+ queue_id: str = "default",+ batch_id: str | None = None,+ destination: str | None = None,+ user_id: str = "user-1",+ workflow_call_id: str | None = None,+ parent_item_id: int | None = None,+ parent_session_id: str | None = None,+ root_item_id: int | None = None,+ workflow_call_depth: int | None = None,+) -> int:+ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id,+ session,+ session_id,+ batch_id,+ field_values,+ priority,+ workflow,+ origin,+ destination,+ retried_from_item_id,+ user_id,+ workflow_call_id,+ parent_item_id,+ parent_session_id,+ root_item_id,+ workflow_call_depth,+ status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ queue_id,+ session.model_dump_json(warnings=False),+ session.id,+ batch_id or str(uuid.uuid4()),+ None,+ 0,+ None,+ None,+ destination,+ None,+ user_id,+ workflow_call_id,+ parent_item_id,+ parent_session_id,+ root_item_id,+ workflow_call_depth,+ status,+ ),+ )+ return cursor.lastrowid+++def test_get_queue_item_round_trips_workflow_call_metadata(session_queue: SqliteSessionQueue) -> None:+ session = GraphExecutionState(graph=Graph())+ session_json = session.model_dump_json(warnings=False)++ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id,+ session,+ session_id,+ batch_id,+ field_values,+ priority,+ workflow,+ origin,+ destination,+ retried_from_item_id,+ user_id,+ workflow_call_id,+ parent_item_id,+ parent_session_id,+ root_item_id,+ workflow_call_depth+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ session_json,+ session.id,+ str(uuid.uuid4()),+ None,+ 0,+ None,+ None,+ None,+ None,+ "user-1",+ "workflow-call-1",+ 11,+ "parent-session-1",+ 7,+ 3,+ ),+ )+ item_id = cursor.lastrowid++ queue_item = session_queue.get_queue_item(item_id)++ assert queue_item.workflow_call_id == "workflow-call-1"+ assert queue_item.parent_item_id == 11+ assert queue_item.parent_session_id == "parent-session-1"+ assert queue_item.root_item_id == 7+ assert queue_item.workflow_call_depth == 3+++def test_enqueue_workflow_call_child_persists_pending_child_queue_item(session_queue: SqliteSessionQueue) -> None:+ parent_graph = Graph()+ parent_graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))+ parent_session = GraphExecutionState(graph=parent_graph)+ invocation = parent_session.next()+ assert isinstance(invocation, CallSavedWorkflowInvocation)++ frame = parent_session.build_workflow_call_frame(invocation.id, invocation.workflow_id)+ child_session = parent_session.create_child_workflow_execution_state(Graph(), frame)+ parent_session.begin_waiting_on_workflow_call(frame)+ parent_session.attach_waiting_workflow_call_child_session(child_session)++ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id,+ session,+ session_id,+ batch_id,+ field_values,+ priority,+ workflow,+ origin,+ destination,+ retried_from_item_id,+ user_id,+ status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ parent_session.model_dump_json(warnings=False),+ parent_session.id,+ str(uuid.uuid4()),+ None,+ 0,+ None,+ None,+ None,+ None,+ "user-1",+ "in_progress",+ ),+ )+ parent_item_id = cursor.lastrowid++ parent_queue_item = session_queue.get_queue_item(parent_item_id)+ child_queue_item = session_queue.enqueue_workflow_call_child(parent_queue_item, child_session)++ assert child_queue_item.status == "pending"+ assert child_queue_item.workflow_call_id == parent_session.waiting_workflow_call_execution.id+ assert child_queue_item.parent_item_id == parent_item_id+ assert child_queue_item.parent_session_id == parent_session.id+ 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+++def test_enqueue_workflow_call_child_rejects_full_pending_queue(session_queue: SqliteSessionQueue) -> None:+ parent_graph = Graph()+ parent_graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))+ parent_session = GraphExecutionState(graph=parent_graph)+ invocation = parent_session.next()+ assert isinstance(invocation, CallSavedWorkflowInvocation)++ frame = parent_session.build_workflow_call_frame(invocation.id, invocation.workflow_id)+ child_session = parent_session.create_child_workflow_execution_state(Graph(), frame)+ parent_session.begin_waiting_on_workflow_call(frame)+ parent_session.attach_waiting_workflow_call_child_session(child_session)++ parent_item_id = _insert_queue_item(session_queue, session=parent_session, status="waiting")+ _insert_queue_item(session_queue, session=GraphExecutionState(graph=Graph()), status="pending")+ parent_queue_item = session_queue.get_queue_item(parent_item_id)+ session_queue._SqliteSessionQueue__invoker.services.configuration.max_queue_size = 1++ with pytest.raises(TooManySessionsError, match="remaining queue capacity"):+ session_queue.enqueue_workflow_call_child(parent_queue_item, child_session)++ assert session_queue.get_queue_status("default").pending == 1+++def test_enqueue_workflow_call_child_persists_batch_field_values(session_queue: SqliteSessionQueue) -> None:+ parent_graph = Graph()+ parent_graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))+ parent_session = GraphExecutionState(graph=parent_graph)+ invocation = parent_session.next()+ assert isinstance(invocation, CallSavedWorkflowInvocation)++ frame = parent_session.build_workflow_call_frame(invocation.id, invocation.workflow_id)+ child_session = parent_session.create_child_workflow_execution_state(Graph(), frame)+ parent_session.begin_waiting_on_workflow_call(frame)+ parent_session.attach_waiting_workflow_call_child_session(child_session)++ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id,+ session,+ session_id,+ batch_id,+ field_values,+ priority,+ workflow,+ origin,+ destination,+ retried_from_item_id,+ user_id,+ status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ parent_session.model_dump_json(warnings=False),+ parent_session.id,+ str(uuid.uuid4()),+ None,+ 0,+ None,+ None,+ None,+ None,+ "user-1",+ "in_progress",+ ),+ )+ parent_item_id = cursor.lastrowid++ child_queue_item = session_queue.enqueue_workflow_call_child(+ parent_queue_item=session_queue.get_queue_item(parent_item_id),+ child_session=child_session,+ field_values=[NodeFieldValue(node_path="target", field_name="value", value=2)],+ )++ assert child_queue_item.field_values == [NodeFieldValue(node_path="target", field_name="value", value=2)]+++def test_suspend_and_enqueue_child_emit_waiting_then_pending_status_events(+ session_queue: SqliteSessionQueue, event_bus: TestEventService+) -> None:+ parent_graph = Graph()+ parent_graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))+ parent_session = GraphExecutionState(graph=parent_graph)+ invocation = parent_session.next()+ assert isinstance(invocation, CallSavedWorkflowInvocation)++ frame = parent_session.build_workflow_call_frame(invocation.id, invocation.workflow_id)+ child_session = parent_session.create_child_workflow_execution_state(Graph(), frame)+ parent_session.begin_waiting_on_workflow_call(frame)+ parent_session.attach_waiting_workflow_call_child_session(child_session)++ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id,+ session,+ session_id,+ batch_id,+ field_values,+ priority,+ workflow,+ origin,+ destination,+ retried_from_item_id,+ user_id,+ status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ parent_session.model_dump_json(warnings=False),+ parent_session.id,+ str(uuid.uuid4()),+ None,+ 0,+ None,+ None,+ None,+ None,+ "user-1",+ "in_progress",+ ),+ )+ parent_item_id = cursor.lastrowid++ parent_queue_item = session_queue.suspend_queue_item(parent_item_id)+ child_queue_item = session_queue.enqueue_workflow_call_child(parent_queue_item, child_session)++ queue_events = [event for event in event_bus.events if isinstance(event, QueueItemStatusChangedEvent)]+ assert len(queue_events) == 2++ waiting_event = queue_events[0]+ assert waiting_event.item_id == parent_item_id+ assert waiting_event.status == "waiting"+ assert waiting_event.queue_status.waiting == 1+ assert waiting_event.queue_status.pending == 0+ assert waiting_event.queue_status.item_id is None++ child_pending_event = queue_events[1]+ assert child_pending_event.item_id == child_queue_item.item_id+ assert child_pending_event.status == "pending"+ assert child_pending_event.queue_status.waiting == 1+ assert child_pending_event.queue_status.pending == 1+ assert child_pending_event.queue_status.total == 2+ assert child_pending_event.queue_status.item_id is None+++def test_get_queue_status_counts_waiting_items(session_queue: SqliteSessionQueue) -> None:+ session = GraphExecutionState(graph=Graph())+ session_json = session.model_dump_json(warnings=False)++ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id,+ session,+ session_id,+ batch_id,+ field_values,+ priority,+ workflow,+ origin,+ destination,+ retried_from_item_id,+ user_id,+ status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ session_json,+ session.id,+ str(uuid.uuid4()),+ None,+ 0,+ None,+ None,+ None,+ None,+ "user-1",+ "waiting",+ ),+ )++ queue_status = session_queue.get_queue_status("default")++ assert queue_status.waiting == 1+ assert queue_status.total == 1+++def test_startup_cancellation_cancels_waiting_workflow_call_chain(session_queue: SqliteSessionQueue) -> None:+ parent_session = GraphExecutionState(graph=Graph())+ child_session = GraphExecutionState(graph=Graph())+ sibling_session = GraphExecutionState(graph=Graph())+ batch_id = str(uuid.uuid4())++ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id,+ session,+ session_id,+ batch_id,+ field_values,+ priority,+ workflow,+ origin,+ destination,+ retried_from_item_id,+ user_id,+ status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ parent_session.model_dump_json(warnings=False),+ parent_session.id,+ batch_id,+ None,+ 0,+ None,+ None,+ None,+ None,+ "user-1",+ "waiting",+ ),+ )+ parent_item_id = cursor.lastrowid+ for child_status, session in (("in_progress", child_session), ("pending", sibling_session)):+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id,+ session,+ session_id,+ batch_id,+ field_values,+ priority,+ workflow,+ origin,+ destination,+ retried_from_item_id,+ user_id,+ workflow_call_id,+ parent_item_id,+ parent_session_id,+ root_item_id,+ workflow_call_depth,+ status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ session.model_dump_json(warnings=False),+ session.id,+ batch_id,+ None,+ 0,+ None,+ None,+ None,+ None,+ "user-1",+ "workflow-call-1",+ parent_item_id,+ parent_session.id,+ parent_item_id,+ 1,+ child_status,+ ),+ )++ session_queue._set_in_progress_to_canceled()++ assert session_queue.get_queue_item(parent_item_id).status == "canceled"+ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ SELECT status+ FROM session_queue+ WHERE parent_item_id = ?+ ORDER BY item_id ASC+ """,+ (parent_item_id,),+ )+ child_statuses = [row[0] for row in cursor.fetchall()]+ assert child_statuses == ["canceled", "canceled"]+++def test_cancel_queue_item_cascades_from_waiting_parent_to_child_chain(session_queue: SqliteSessionQueue) -> None:+ parent_session = GraphExecutionState(graph=Graph())+ child_session = GraphExecutionState(graph=Graph())+ grandchild_session = GraphExecutionState(graph=Graph())++ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ parent_session.model_dump_json(warnings=False),+ parent_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "waiting",+ ),+ )+ parent_item_id = cursor.lastrowid+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status,+ workflow_call_id, parent_item_id, parent_session_id, root_item_id, workflow_call_depth+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ child_session.model_dump_json(warnings=False),+ child_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "waiting",+ "workflow-call-1",+ parent_item_id,+ parent_session.id,+ parent_item_id,+ 1,+ ),+ )+ child_item_id = cursor.lastrowid+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status,+ workflow_call_id, parent_item_id, parent_session_id, root_item_id, workflow_call_depth+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ grandchild_session.model_dump_json(warnings=False),+ grandchild_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "pending",+ "workflow-call-2",+ child_item_id,+ child_session.id,+ parent_item_id,+ 2,+ ),+ )+ grandchild_item_id = cursor.lastrowid++ session_queue.cancel_queue_item(parent_item_id)++ assert session_queue.get_queue_item(parent_item_id).status == "canceled"+ assert session_queue.get_queue_item(child_item_id).status == "canceled"+ assert session_queue.get_queue_item(grandchild_item_id).status == "canceled"+++def test_cancel_queue_item_cascades_from_child_to_waiting_parents(session_queue: SqliteSessionQueue) -> None:+ parent_session = GraphExecutionState(graph=Graph())+ child_session = GraphExecutionState(graph=Graph())++ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ parent_session.model_dump_json(warnings=False),+ parent_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "waiting",+ ),+ )+ parent_item_id = cursor.lastrowid+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status,+ workflow_call_id, parent_item_id, parent_session_id, root_item_id, workflow_call_depth+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ child_session.model_dump_json(warnings=False),+ child_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "pending",+ "workflow-call-1",+ parent_item_id,+ parent_session.id,+ parent_item_id,+ 1,+ ),+ )+ child_item_id = cursor.lastrowid++ session_queue.cancel_queue_item(child_item_id)++ assert session_queue.get_queue_item(child_item_id).status == "canceled"+ assert session_queue.get_queue_item(parent_item_id).status == "canceled"+++def test_delete_queue_item_removes_entire_workflow_call_chain(session_queue: SqliteSessionQueue) -> None:+ parent_session = GraphExecutionState(graph=Graph())+ child_session = GraphExecutionState(graph=Graph())+ grandchild_session = GraphExecutionState(graph=Graph())++ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ parent_session.model_dump_json(warnings=False),+ parent_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "failed",+ ),+ )+ parent_item_id = cursor.lastrowid+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status,+ workflow_call_id, parent_item_id, parent_session_id, root_item_id, workflow_call_depth+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ child_session.model_dump_json(warnings=False),+ child_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "canceled",+ "workflow-call-1",+ parent_item_id,+ parent_session.id,+ parent_item_id,+ 1,+ ),+ )+ child_item_id = cursor.lastrowid+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status,+ workflow_call_id, parent_item_id, parent_session_id, root_item_id, workflow_call_depth+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ grandchild_session.model_dump_json(warnings=False),+ grandchild_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "canceled",+ "workflow-call-2",+ child_item_id,+ child_session.id,+ parent_item_id,+ 2,+ ),+ )+ grandchild_item_id = cursor.lastrowid++ session_queue.delete_queue_item(child_item_id)++ with pytest.raises(SessionQueueItemNotFoundError):+ session_queue.get_queue_item(parent_item_id)+ with pytest.raises(SessionQueueItemNotFoundError):+ session_queue.get_queue_item(child_item_id)+ with pytest.raises(SessionQueueItemNotFoundError):+ session_queue.get_queue_item(grandchild_item_id)+++def test_delete_queue_item_cancels_active_workflow_call_chain_before_deleting(+ session_queue: SqliteSessionQueue, event_bus: TestEventService+) -> None:+ parent_session = GraphExecutionState(graph=Graph())+ child_session = GraphExecutionState(graph=Graph())++ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ parent_session.model_dump_json(warnings=False),+ parent_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "waiting",+ ),+ )+ parent_item_id = cursor.lastrowid+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status,+ workflow_call_id, parent_item_id, parent_session_id, root_item_id, workflow_call_depth+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ child_session.model_dump_json(warnings=False),+ child_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "in_progress",+ "workflow-call-1",+ parent_item_id,+ parent_session.id,+ parent_item_id,+ 1,+ ),+ )+ child_item_id = cursor.lastrowid++ session_queue.delete_queue_item(child_item_id)++ canceled_events = [event for event in event_bus.events if isinstance(event, QueueItemStatusChangedEvent)]+ assert [event.item_id for event in canceled_events if event.status == "canceled"] == [parent_item_id, child_item_id]++ with pytest.raises(SessionQueueItemNotFoundError):+ session_queue.get_queue_item(parent_item_id)+ with pytest.raises(SessionQueueItemNotFoundError):+ session_queue.get_queue_item(child_item_id)+++def test_cancel_queue_item_cascade_emits_canceled_events_for_waiting_parent_and_running_child(+ session_queue: SqliteSessionQueue, event_bus: TestEventService+) -> None:+ parent_session = GraphExecutionState(graph=Graph())+ child_session = GraphExecutionState(graph=Graph())++ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ parent_session.model_dump_json(warnings=False),+ parent_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "waiting",+ ),+ )+ parent_item_id = cursor.lastrowid+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status,+ workflow_call_id, parent_item_id, parent_session_id, root_item_id, workflow_call_depth+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ child_session.model_dump_json(warnings=False),+ child_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "in_progress",+ "workflow-call-1",+ parent_item_id,+ parent_session.id,+ parent_item_id,+ 1,+ ),+ )+ child_item_id = cursor.lastrowid++ session_queue.cancel_queue_item(child_item_id)++ queue_events = [event for event in event_bus.events if isinstance(event, QueueItemStatusChangedEvent)]+ canceled_events = [event for event in queue_events if event.status == "canceled"]++ assert [event.item_id for event in canceled_events] == [parent_item_id, child_item_id]+ assert canceled_events[-1].queue_status.canceled == 2+ assert canceled_events[-1].queue_status.waiting == 0+ assert canceled_events[-1].queue_status.in_progress == 0+++def test_cancel_workflow_call_children_cancels_nested_descendants(session_queue: SqliteSessionQueue) -> None:+ root_session = GraphExecutionState(graph=Graph())+ waiting_child_session = GraphExecutionState(graph=Graph())+ nested_child_session = GraphExecutionState(graph=Graph())+ sibling_session = GraphExecutionState(graph=Graph())++ root_item_id = _insert_queue_item(session_queue, session=root_session, status="waiting")+ waiting_child_item_id = _insert_queue_item(+ session_queue,+ session=waiting_child_session,+ status="waiting",+ workflow_call_id="workflow-call-1",+ parent_item_id=root_item_id,+ parent_session_id=root_session.id,+ root_item_id=root_item_id,+ workflow_call_depth=1,+ )+ nested_child_item_id = _insert_queue_item(+ session_queue,+ session=nested_child_session,+ status="in_progress",+ workflow_call_id="workflow-call-2",+ parent_item_id=waiting_child_item_id,+ parent_session_id=waiting_child_session.id,+ root_item_id=root_item_id,+ workflow_call_depth=2,+ )+ sibling_item_id = _insert_queue_item(+ session_queue,+ session=sibling_session,+ status="pending",+ workflow_call_id="workflow-call-1",+ parent_item_id=root_item_id,+ parent_session_id=root_session.id,+ root_item_id=root_item_id,+ workflow_call_depth=1,+ )++ canceled_item_ids = session_queue.cancel_workflow_call_children("workflow-call-1")++ assert canceled_item_ids == [waiting_child_item_id, nested_child_item_id, sibling_item_id]+ assert session_queue.get_queue_item(waiting_child_item_id).status == "canceled"+ assert session_queue.get_queue_item(nested_child_item_id).status == "canceled"+ assert session_queue.get_queue_item(sibling_item_id).status == "canceled"+++def test_cancel_all_except_current_cancels_waiting_chains_outside_current_chain(+ session_queue: SqliteSessionQueue,+) -> None:+ current_parent_session = GraphExecutionState(graph=Graph())+ current_child_session = GraphExecutionState(graph=Graph())+ other_parent_session = GraphExecutionState(graph=Graph())+ other_child_session = GraphExecutionState(graph=Graph())++ current_parent_item_id = _insert_queue_item(session_queue, session=current_parent_session, status="waiting")+ current_child_item_id = _insert_queue_item(+ session_queue,+ session=current_child_session,+ status="in_progress",+ workflow_call_id="workflow-call-current",+ parent_item_id=current_parent_item_id,+ parent_session_id=current_parent_session.id,+ root_item_id=current_parent_item_id,+ workflow_call_depth=1,+ )+ other_parent_item_id = _insert_queue_item(session_queue, session=other_parent_session, status="waiting")+ other_child_item_id = _insert_queue_item(+ session_queue,+ session=other_child_session,+ status="pending",+ workflow_call_id="workflow-call-other",+ parent_item_id=other_parent_item_id,+ parent_session_id=other_parent_session.id,+ root_item_id=other_parent_item_id,+ workflow_call_depth=1,+ )++ result = session_queue.cancel_all_except_current("default")++ assert result.canceled == 2+ assert session_queue.get_queue_item(current_parent_item_id).status == "waiting"+ assert session_queue.get_queue_item(current_child_item_id).status == "in_progress"+ assert session_queue.get_queue_item(other_parent_item_id).status == "canceled"+ assert session_queue.get_queue_item(other_child_item_id).status == "canceled"+++def test_delete_all_except_current_deletes_waiting_chains_outside_current_chain(+ session_queue: SqliteSessionQueue,+) -> None:+ current_parent_session = GraphExecutionState(graph=Graph())+ current_child_session = GraphExecutionState(graph=Graph())+ other_parent_session = GraphExecutionState(graph=Graph())+ other_child_session = GraphExecutionState(graph=Graph())++ current_parent_item_id = _insert_queue_item(session_queue, session=current_parent_session, status="waiting")+ current_child_item_id = _insert_queue_item(+ session_queue,+ session=current_child_session,+ status="in_progress",+ workflow_call_id="workflow-call-current",+ parent_item_id=current_parent_item_id,+ parent_session_id=current_parent_session.id,+ root_item_id=current_parent_item_id,+ workflow_call_depth=1,+ )+ other_parent_item_id = _insert_queue_item(session_queue, session=other_parent_session, status="waiting")+ other_child_item_id = _insert_queue_item(+ session_queue,+ session=other_child_session,+ status="pending",+ workflow_call_id="workflow-call-other",+ parent_item_id=other_parent_item_id,+ parent_session_id=other_parent_session.id,+ root_item_id=other_parent_item_id,+ workflow_call_depth=1,+ )++ result = session_queue.delete_all_except_current("default")++ assert result.deleted == 2+ assert session_queue.get_queue_item(current_parent_item_id).status == "waiting"+ assert session_queue.get_queue_item(current_child_item_id).status == "in_progress"+ with pytest.raises(SessionQueueItemNotFoundError):+ session_queue.get_queue_item(other_parent_item_id)+ with pytest.raises(SessionQueueItemNotFoundError):+ session_queue.get_queue_item(other_child_item_id)+++def test_cancel_all_except_current_preserves_waiting_chain_during_pending_child_handoff(+ session_queue: SqliteSessionQueue,+) -> None:+ parent_session = GraphExecutionState(graph=Graph())+ child_session = GraphExecutionState(graph=Graph())+ unrelated_session = GraphExecutionState(graph=Graph())++ parent_item_id = _insert_queue_item(session_queue, session=parent_session, status="waiting")+ child_item_id = _insert_queue_item(+ session_queue,+ session=child_session,+ status="pending",+ workflow_call_id="workflow-call-current",+ parent_item_id=parent_item_id,+ parent_session_id=parent_session.id,+ root_item_id=parent_item_id,+ workflow_call_depth=1,+ )+ unrelated_item_id = _insert_queue_item(session_queue, session=unrelated_session, status="pending")++ result = session_queue.cancel_all_except_current("default")++ assert result.canceled == 1+ assert session_queue.get_queue_item(parent_item_id).status == "waiting"+ assert session_queue.get_queue_item(child_item_id).status == "pending"+ assert session_queue.get_queue_item(unrelated_item_id).status == "canceled"+++def test_delete_all_except_current_preserves_waiting_chain_during_pending_child_handoff(+ session_queue: SqliteSessionQueue,+) -> None:+ parent_session = GraphExecutionState(graph=Graph())+ child_session = GraphExecutionState(graph=Graph())+ unrelated_session = GraphExecutionState(graph=Graph())++ parent_item_id = _insert_queue_item(session_queue, session=parent_session, status="waiting")+ child_item_id = _insert_queue_item(+ session_queue,+ session=child_session,+ status="pending",+ workflow_call_id="workflow-call-current",+ parent_item_id=parent_item_id,+ parent_session_id=parent_session.id,+ root_item_id=parent_item_id,+ workflow_call_depth=1,+ )+ unrelated_item_id = _insert_queue_item(session_queue, session=unrelated_session, status="pending")++ result = session_queue.delete_all_except_current("default")++ assert result.deleted == 1+ assert session_queue.get_queue_item(parent_item_id).status == "waiting"+ assert session_queue.get_queue_item(child_item_id).status == "pending"+ with pytest.raises(SessionQueueItemNotFoundError):+ session_queue.get_queue_item(unrelated_item_id)+++def test_cancel_by_queue_id_cancels_current_workflow_call_descendants(session_queue: SqliteSessionQueue) -> None:+ parent_session = GraphExecutionState(graph=Graph())+ child_session = GraphExecutionState(graph=Graph())+ nested_child_session = GraphExecutionState(graph=Graph())++ parent_item_id = _insert_queue_item(session_queue, session=parent_session, status="waiting")+ child_item_id = _insert_queue_item(+ session_queue,+ session=child_session,+ status="in_progress",+ workflow_call_id="workflow-call-1",+ parent_item_id=parent_item_id,+ parent_session_id=parent_session.id,+ root_item_id=parent_item_id,+ workflow_call_depth=1,+ )+ nested_child_item_id = _insert_queue_item(+ session_queue,+ session=nested_child_session,+ status="pending",+ workflow_call_id="workflow-call-2",+ parent_item_id=child_item_id,+ parent_session_id=child_session.id,+ root_item_id=parent_item_id,+ workflow_call_depth=2,+ )++ session_queue.cancel_by_queue_id("default")++ assert session_queue.get_queue_item(parent_item_id).status == "canceled"+ assert session_queue.get_queue_item(child_item_id).status == "canceled"+ assert session_queue.get_queue_item(nested_child_item_id).status == "canceled"+++def test_cancel_by_batch_ids_cancels_waiting_parent_and_in_progress_child(+ session_queue: SqliteSessionQueue,+) -> None:+ batch_id = str(uuid.uuid4())+ parent_session = GraphExecutionState(graph=Graph())+ child_session = GraphExecutionState(graph=Graph())++ parent_item_id = _insert_queue_item(+ session_queue,+ session=parent_session,+ status="waiting",+ batch_id=batch_id,+ )+ child_item_id = _insert_queue_item(+ session_queue,+ session=child_session,+ status="in_progress",+ batch_id=batch_id,+ workflow_call_id="workflow-call-1",+ parent_item_id=parent_item_id,+ parent_session_id=parent_session.id,+ root_item_id=parent_item_id,+ workflow_call_depth=1,+ )++ session_queue.cancel_by_batch_ids("default", [batch_id])++ assert session_queue.get_queue_item(parent_item_id).status == "canceled"+ assert session_queue.get_queue_item(child_item_id).status == "canceled"+++def test_cancel_by_destination_cancels_waiting_parent_and_in_progress_child(+ session_queue: SqliteSessionQueue,+) -> None:+ destination = "gallery"+ parent_session = GraphExecutionState(graph=Graph())+ child_session = GraphExecutionState(graph=Graph())++ parent_item_id = _insert_queue_item(+ session_queue,+ session=parent_session,+ status="waiting",+ destination=destination,+ )+ child_item_id = _insert_queue_item(+ session_queue,+ session=child_session,+ status="in_progress",+ destination=destination,+ workflow_call_id="workflow-call-1",+ parent_item_id=parent_item_id,+ parent_session_id=parent_session.id,+ root_item_id=parent_item_id,+ workflow_call_depth=1,+ )++ session_queue.cancel_by_destination("default", destination)++ assert session_queue.get_queue_item(parent_item_id).status == "canceled"+ assert session_queue.get_queue_item(child_item_id).status == "canceled"+++def test_retry_items_by_id_retries_root_once_for_child_chain_item(session_queue: SqliteSessionQueue) -> None:+ root_session = GraphExecutionState(graph=Graph())+ child_session = GraphExecutionState(graph=Graph())++ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ root_session.model_dump_json(warnings=False),+ root_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "failed",+ ),+ )+ root_item_id = cursor.lastrowid+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status,+ workflow_call_id, parent_item_id, parent_session_id, root_item_id, workflow_call_depth+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ child_session.model_dump_json(warnings=False),+ child_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "failed",+ "workflow-call-1",+ root_item_id,+ root_session.id,+ root_item_id,+ 1,+ ),+ )+ child_item_id = cursor.lastrowid++ retry_result = session_queue.retry_items_by_id("default", [child_item_id, root_item_id])++ assert retry_result.retried_item_ids == [root_item_id]++ all_items = session_queue.list_all_queue_items("default")+ retried_items = [item for item in all_items if item.retried_from_item_id == root_item_id]+ assert len(retried_items) == 1+ assert retried_items[0].status == "pending"+ assert retried_items[0].workflow_call_id is None+ assert retried_items[0].parent_item_id is None+ assert retried_items[0].root_item_id is None+++def test_retry_items_by_id_emits_root_only_retry_event_for_nested_failure_chain(+ session_queue: SqliteSessionQueue, event_bus: TestEventService+) -> None:+ root_session = GraphExecutionState(graph=Graph())+ child_session = GraphExecutionState(graph=Graph())+ grandchild_session = GraphExecutionState(graph=Graph())++ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ root_session.model_dump_json(warnings=False),+ root_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "failed",+ ),+ )+ root_item_id = cursor.lastrowid+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status,+ workflow_call_id, parent_item_id, parent_session_id, root_item_id, workflow_call_depth+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ child_session.model_dump_json(warnings=False),+ child_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "failed",+ "workflow-call-1",+ root_item_id,+ root_session.id,+ root_item_id,+ 1,+ ),+ )+ child_item_id = cursor.lastrowid+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status,+ workflow_call_id, parent_item_id, parent_session_id, root_item_id, workflow_call_depth+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ grandchild_session.model_dump_json(warnings=False),+ grandchild_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "canceled",+ "workflow-call-2",+ child_item_id,+ child_session.id,+ root_item_id,+ 2,+ ),+ )+ grandchild_item_id = cursor.lastrowid++ retry_result = session_queue.retry_items_by_id("default", [grandchild_item_id, child_item_id, root_item_id])++ assert retry_result.retried_item_ids == [root_item_id]++ retry_events = [event for event in event_bus.events if isinstance(event, QueueItemsRetriedEvent)]+ assert len(retry_events) == 1+ assert retry_events[0].retried_item_ids == [root_item_id]+++def test_retry_items_by_id_respects_remaining_queue_capacity(session_queue: SqliteSessionQueue) -> None:+ root_session = GraphExecutionState(graph=Graph())+ pending_session = GraphExecutionState(graph=Graph())++ with session_queue._db.transaction() as cursor:+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ pending_session.model_dump_json(warnings=False),+ pending_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "pending",+ ),+ )+ cursor.execute(+ """--sql+ INSERT INTO session_queue (+ queue_id, session, session_id, batch_id, priority, user_id, status+ )+ VALUES (?, ?, ?, ?, ?, ?, ?)+ """,+ (+ "default",+ root_session.model_dump_json(warnings=False),+ root_session.id,+ str(uuid.uuid4()),+ 0,+ "user-1",+ "failed",+ ),+ )+ root_item_id = cursor.lastrowid++ session_queue._SqliteSessionQueue__invoker.services.configuration.max_queue_size = 1+ retry_result = session_queue.retry_items_by_id("default", [root_item_id])++ assert retry_result.retried_item_ids == []+ assert session_queue.get_queue_status("default").pending == 1diff --git a/tests/app/services/session_queue/test_session_queue_workflow_call_retry.py b/tests/app/services/session_queue/test_session_queue_workflow_call_retry.pynew file mode 100644index 0000000000..3b9c85183d--- /dev/null+++ b/tests/app/services/session_queue/test_session_queue_workflow_call_retry.py@@ -0,0 +1,133 @@+"""Tests for workflow-call retry semantics in the session queue."""++from datetime import datetime++import pytest++from invokeai.app.services.events.events_common import QueueItemsRetriedEvent+from invokeai.app.services.invoker import Invoker+from invokeai.app.services.session_queue.session_queue_common import SessionQueueItem+from invokeai.app.services.session_queue.session_queue_sqlite import SqliteSessionQueue+from invokeai.app.services.shared.graph import Graph, GraphExecutionState+from tests.test_nodes import TestEventService+++def session_queue(mock_invoker: Invoker) -> SqliteSessionQueue:+ db = mock_invoker.services.board_records._db+ queue = SqliteSessionQueue(db=db)+ queue.start(mock_invoker)+ return queue+++def event_bus(mock_invoker: Invoker) -> TestEventService:+ assert isinstance(mock_invoker.services.events, TestEventService)+ return mock_invoker.services.events+++def _build_queue_item(+ *,+ item_id: int,+ session: GraphExecutionState,+ user_id: str,+ status: str,+ root_item_id: int | None = None,+ retried_from_item_id: int | None = None,+) -> SessionQueueItem:+ now = datetime.now()+ return SessionQueueItem(+ item_id=item_id,+ status=status,+ priority=0,+ batch_id=f"batch-{item_id}",+ origin=None,+ destination=None,+ session_id=session.id,+ error_type=None,+ error_message=None,+ error_traceback=None,+ created_at=now,+ updated_at=now,+ started_at=None,+ completed_at=None,+ queue_id="default",+ user_id=user_id,+ user_display_name=None,+ user_email=None,+ field_values=None,+ retried_from_item_id=retried_from_item_id,+ workflow_call_id=None,+ parent_item_id=None,+ parent_session_id=None,+ root_item_id=root_item_id,+ workflow_call_depth=None,+ session=session,+ workflow=None,+ )+++def test_retry_items_by_id_retries_root_once_for_child_chain_item(+ session_queue: SqliteSessionQueue, event_bus: TestEventService, monkeypatch: pytest.MonkeyPatch+) -> None:+ root_session = GraphExecutionState(graph=Graph())+ child_session = GraphExecutionState(graph=Graph())++ root_item = _build_queue_item(item_id=10, session=root_session, user_id="user-1", status="failed")+ child_item = _build_queue_item(+ item_id=11,+ session=child_session,+ user_id="user-1",+ status="failed",+ root_item_id=root_item.item_id,+ )++ items = {root_item.item_id: root_item, child_item.item_id: child_item}+ monkeypatch.setattr(session_queue, "get_queue_item", lambda item_id: items[item_id])++ retry_result = session_queue.retry_items_by_id("default", [child_item.item_id, root_item.item_id])++ assert retry_result.retried_item_ids == [root_item.item_id]++ all_items = session_queue.list_all_queue_items("default")+ retried_items = [item for item in all_items if item.retried_from_item_id == root_item.item_id]+ assert len(retried_items) == 1+ assert retried_items[0].status == "pending"+ assert retried_items[0].workflow_call_id is None+ assert retried_items[0].parent_item_id is None+ assert retried_items[0].root_item_id is None++ retry_events = [event for event in event_bus.events if isinstance(event, QueueItemsRetriedEvent)]+ assert len(retry_events) == 1+ assert retry_events[0].retried_item_ids == [root_item.item_id]+ assert retry_events[0].user_ids == ["user-1"]+ assert retry_events[0].retried_item_ids_by_user == {"user-1": [root_item.item_id]}+++def test_retry_items_by_id_emits_unique_owner_ids_for_multiple_roots(+ session_queue: SqliteSessionQueue, event_bus: TestEventService, monkeypatch: pytest.MonkeyPatch+) -> None:+ first_root_item = _build_queue_item(+ item_id=20, session=GraphExecutionState(graph=Graph()), user_id="user-1", status="failed"+ )+ second_root_item = _build_queue_item(+ item_id=21, session=GraphExecutionState(graph=Graph()), user_id="user-2", status="canceled"+ )++ items = {+ first_root_item.item_id: first_root_item,+ second_root_item.item_id: second_root_item,+ }+ monkeypatch.setattr(session_queue, "get_queue_item", lambda item_id: items[item_id])++ retry_result = session_queue.retry_items_by_id("default", [first_root_item.item_id, second_root_item.item_id])++ assert retry_result.retried_item_ids == [first_root_item.item_id, second_root_item.item_id]++ retry_events = [event for event in event_bus.events if isinstance(event, QueueItemsRetriedEvent)]+ assert len(retry_events) == 1+ assert retry_events[0].user_ids == ["user-1", "user-2"]+ assert retry_events[0].retried_item_ids_by_user == {+ "user-1": [first_root_item.item_id],+ "user-2": [second_root_item.item_id],+ }diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_07_01_add_workflow_call_queue_metadata.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_07_01_add_workflow_call_queue_metadata.pynew file mode 100644index 0000000000..e31510108e--- /dev/null+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_07_01_add_workflow_call_queue_metadata.py@@ -0,0 +1,70 @@+import sqlite3++from invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_07_01_add_workflow_call_queue_metadata import (+ AddWorkflowCallQueueMetadataCallback,+ build_migration,+)+++def _get_columns(cursor: sqlite3.Cursor, table_name: str) -> set[str]:+ cursor.execute(f"PRAGMA table_info({table_name});")+ return {row[1] for row in cursor.fetchall()}+++def _get_indexes(cursor: sqlite3.Cursor) -> set[str]:+ cursor.execute("SELECT name FROM sqlite_master WHERE type = 'index';")+ return {row[0] for row in cursor.fetchall()}+++def test_adds_workflow_call_columns_and_indexes_to_session_queue() -> None:+ db = sqlite3.connect(":memory:")+ cursor = db.cursor()+ cursor.execute("CREATE TABLE session_queue (item_id INTEGER PRIMARY KEY);")++ AddWorkflowCallQueueMetadataCallback()(cursor)++ assert _get_columns(cursor, "session_queue") >= {+ "workflow_call_id",+ "parent_item_id",+ "parent_session_id",+ "root_item_id",+ "workflow_call_depth",+ }+ assert _get_indexes(cursor) >= {+ "idx_session_queue_workflow_call_id",+ "idx_session_queue_parent_item_id",+ "idx_session_queue_parent_session_id",+ "idx_session_queue_root_item_id",+ "idx_session_queue_workflow_call_depth",+ }++ db.close()+++def test_migration_is_idempotent_and_tolerates_missing_session_queue() -> None:+ db = sqlite3.connect(":memory:")+ cursor = db.cursor()++ AddWorkflowCallQueueMetadataCallback()(cursor)+ cursor.execute("CREATE TABLE session_queue (item_id INTEGER PRIMARY KEY, workflow_call_id TEXT);")+ AddWorkflowCallQueueMetadataCallback()(cursor)+ AddWorkflowCallQueueMetadataCallback()(cursor)++ assert _get_columns(cursor, "session_queue") >= {+ "workflow_call_id",+ "parent_item_id",+ "parent_session_id",+ "root_item_id",+ "workflow_call_depth",+ }++ db.close()+++def test_build_migration_declares_stable_id_and_dependency() -> None:+ migration = build_migration()++ assert migration.id == "2026_07_01_add_workflow_call_queue_metadata"+ assert migration.depends_on == "migration_33"+ assert migration.from_version is None+ assert migration.to_version is Nonediff --git a/tests/app/services/test_session_processor_shutdown.py b/tests/app/services/test_session_processor_shutdown.pyindex 7c321510ed..6d2d2879a4 100644--- a/tests/app/services/test_session_processor_shutdown.py+++ b/tests/app/services/test_session_processor_shutdown.py@@ -1,185 +1,13 @@-from contextlib import contextmanager-from threading import Event+from tests.app.services import workflow_call_test_utils as workflow_call_tests-import pytest-from invokeai.app.invocations.baseinvocation import BaseInvocation, BaseInvocationOutput, invocation, invocation_output-from invokeai.app.services.session_processor.session_processor_default import DefaultSessionRunner-from tests.dangerously_run_function_in_subprocess import dangerously_run_function_in_subprocess---@invocation_output("test_interrupt_output")-class InterruptTestOutput(BaseInvocationOutput):- pass---@invocation("test_keyboard_interrupt", version="1.0.0")-class KeyboardInterruptInvocation(BaseInvocation):- def invoke(self, context) -> InterruptTestOutput:- raise KeyboardInterrupt---class _DummyStats:- @contextmanager- def collect_stats(self, invocation: BaseInvocation, graph_execution_state_id: str):- yield---class _DummyEvents:- def emit_invocation_started(self, queue_item, invocation) -> None:- pass-- def emit_invocation_complete(self, invocation, queue_item, output) -> None:- pass-- def emit_invocation_error(self, queue_item, invocation, error_type, error_message, error_traceback) -> None:- pass---class _DummyLogger:- def debug(self, msg) -> None:- pass-- def error(self, msg) -> None:- pass---class _DummyConfig:- node_cache_size = 0---def _build_runner(monkeypatch: pytest.MonkeyPatch) -> DefaultSessionRunner:- monkeypatch.setattr(- "invokeai.app.services.session_processor.session_processor_default.build_invocation_context",- lambda data, services, is_canceled: None,- )-- runner = DefaultSessionRunner()- runner.start(- services=type(- "Services",- (),- {- "performance_statistics": _DummyStats(),- "events": _DummyEvents(),- "logger": _DummyLogger(),- "configuration": _DummyConfig(),- },- )(),- cancel_event=Event(),- )- return runner---def _build_queue_item(invocation: BaseInvocation):- return type(- "QueueItem",- (),- {- "item_id": 1,- "session_id": "test-session",- "session": type("Session", (), {"prepared_source_mapping": {invocation.id: invocation.id}})(),- },- )()---def test_run_node_propagates_keyboard_interrupt(monkeypatch: pytest.MonkeyPatch) -> None:- runner = _build_runner(monkeypatch)- invocation = KeyboardInterruptInvocation(id="node")- queue_item = _build_queue_item(invocation)-- with pytest.raises(KeyboardInterrupt):- runner.run_node(invocation=invocation, queue_item=queue_item)+def test_run_node_propagates_keyboard_interrupt(monkeypatch) -> None:+ workflow_call_tests.test_run_node_propagates_keyboard_interrupt(monkeypatch)def test_run_node_does_not_swallow_sigint_in_subprocess() -> None:- def test_func():- import os- import signal- import threading- import time- from contextlib import contextmanager- from threading import Event-- import invokeai.app.services.session_processor.session_processor_default as session_processor_default- from invokeai.app.invocations.baseinvocation import (- BaseInvocation,- BaseInvocationOutput,- invocation,- invocation_output,- )- from invokeai.app.services.session_processor.session_processor_default import DefaultSessionRunner-- @invocation_output("test_interrupt_output_subprocess")- class InterruptTestOutput(BaseInvocationOutput):- pass-- @invocation("test_sigint_during_node", version="1.0.0")- class SigIntDuringNodeInvocation(BaseInvocation):- def invoke(self, context) -> InterruptTestOutput:- timer = threading.Thread(target=lambda: (time.sleep(0.1), os.kill(os.getpid(), signal.SIGINT)))- timer.daemon = True- timer.start()- time.sleep(5)- return InterruptTestOutput()-- class DummyStats:- @contextmanager- def collect_stats(self, invocation: BaseInvocation, graph_execution_state_id: str):- yield-- class DummyEvents:- def emit_invocation_started(self, queue_item, invocation) -> None:- pass-- def emit_invocation_complete(self, invocation, queue_item, output) -> None:- pass-- def emit_invocation_error(self, queue_item, invocation, error_type, error_message, error_traceback) -> None:- pass-- class DummyLogger:- def debug(self, msg) -> None:- pass-- def error(self, msg) -> None:- pass-- class DummyConfig:- node_cache_size = 0-- session_processor_default.build_invocation_context = lambda data, services, is_canceled: None-- runner = DefaultSessionRunner()- runner.start(- services=type(- "Services",- (),- {- "performance_statistics": DummyStats(),- "events": DummyEvents(),- "logger": DummyLogger(),- "configuration": DummyConfig(),- },- )(),- cancel_event=Event(),- )-- invocation = SigIntDuringNodeInvocation(id="node")- queue_item = type(- "QueueItem",- (),- {- "item_id": 1,- "session_id": "test-session",- "session": type("Session", (), {"prepared_source_mapping": {invocation.id: invocation.id}})(),- },- )()-- runner.run_node(invocation=invocation, queue_item=queue_item)- print("swallowed")+ workflow_call_tests.test_run_node_does_not_swallow_sigint_in_subprocess()- stdout, stderr, returncode = dangerously_run_function_in_subprocess(test_func)- assert stdout.strip() == ""- assert returncode != 0, stderr+def test_on_after_run_session_does_not_complete_incomplete_session(monkeypatch) -> None:+ workflow_call_tests.test_on_after_run_session_does_not_complete_incomplete_session(monkeypatch)diff --git a/tests/app/services/test_workflow_call_batch.py b/tests/app/services/test_workflow_call_batch.pynew file mode 100644index 0000000000..9d623b11db--- /dev/null+++ b/tests/app/services/test_workflow_call_batch.py@@ -0,0 +1,1422 @@+from typing import Any++import pytest++from invokeai.app.services.session_processor.workflow_call_batch import (+ build_child_workflow_session_results,+ build_child_workflow_sessions,+)+from invokeai.app.services.session_queue.session_queue_common import TooManySessionsError+from invokeai.app.services.shared.graph import Graph, GraphExecutionState, WorkflowCallFrame+from invokeai.app.services.shared.workflow_graph_builder import UnsupportedWorkflowNodeError+++def _invocation_node(node_id: str, invocation_type: str, inputs: dict[str, Any]) -> dict[str, Any]:+ return {+ "id": node_id,+ "type": "invocation",+ "position": {"x": 0, "y": 0},+ "data": {+ "id": node_id,+ "type": invocation_type,+ "version": "1.0.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "isOpen": True,+ "isIntermediate": False,+ "useCache": True,+ "dynamicInputTemplates": {},+ "inputs": inputs,+ },+ }+++def _workflow_dump(+ *,+ nodes: list[dict[str, Any]],+ edges: list[dict[str, Any]],+ exposed_fields: list[dict[str, str]] | None = None,+) -> dict[str, Any]:+ nodes = list(nodes)+ edges = list(edges)+ for node in list(nodes):+ data = node.get("data", {})+ if data.get("type") != "workflow_return":+ continue+ inputs = data.get("inputs", {})+ if "collection" not in inputs:+ continue++ return_node_id = data["id"]+ value_node_id = f"{return_node_id}-value"+ collect_node_id = f"{return_node_id}-collect"+ data["inputs"] = {"values": {"value": []}}+ nodes.extend(+ [+ _invocation_node(+ value_node_id,+ "workflow_return_value",+ {"key": {"value": "result"}, "value": {"value": None}},+ ),+ _invocation_node(collect_node_id, "collect", {"collection": {"value": []}}),+ ]+ )+ for edge in edges:+ if edge.get("target") == return_node_id and edge.get("targetHandle") == "collection":+ edge["target"] = value_node_id+ edge["targetHandle"] = "value"+ edges.extend(+ [+ {+ "id": f"edge-{value_node_id}-collect",+ "type": "default",+ "source": value_node_id,+ "sourceHandle": "value",+ "target": collect_node_id,+ "targetHandle": "item",+ },+ {+ "id": f"edge-{collect_node_id}-return",+ "type": "default",+ "source": collect_node_id,+ "sourceHandle": "collection",+ "target": return_node_id,+ "targetHandle": "values",+ },+ ]+ )++ return {+ "name": "Child Workflow",+ "author": "Tester",+ "description": "",+ "version": "1.0.0",+ "contact": "",+ "tags": "",+ "notes": "",+ "exposedFields": exposed_fields or [],+ "meta": {"category": "user", "version": "1.0.0"},+ "nodes": nodes,+ "edges": edges,+ "form": None,+ }+++def _call_frame() -> WorkflowCallFrame:+ return WorkflowCallFrame(+ prepared_call_node_id="prepared-call",+ source_call_node_id="source-call",+ workflow_id="workflow-batch",+ depth=1,+ )+++def test_build_child_workflow_sessions_expands_direct_integer_batch() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "batch",+ "integer_batch",+ {"integers": {"value": [2, 4, 6]}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "integer", {"value": {"value": 0}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "integers",+ "target": "target",+ "targetHandle": "value",+ },+ {+ "id": "edge-target-collect",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-collect-return",+ "type": "default",+ "source": "collect",+ "sourceHandle": "collection",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )++ parent_session = GraphExecutionState(graph=Graph())+ child_sessions = build_child_workflow_sessions(+ parent_session=parent_session,+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ )++ assert len(child_sessions) == 3+ assert [child_session.graph.nodes["target"].value for child_session in child_sessions] == [2, 4, 6]+++def test_build_child_workflow_session_results_preserves_batch_field_values() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "batch",+ "integer_batch",+ {"integers": {"value": [2, 4]}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "integer", {"value": {"value": 0}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "integers",+ "target": "target",+ "targetHandle": "value",+ }+ ],+ )++ child_results = build_child_workflow_session_results(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ )++ assert [result.session.graph.nodes["target"].value for result in child_results] == [2, 4]+ assert [+ [+ (field_value.node_path, field_value.field_name, field_value.value)+ for field_value in result.field_values or []+ ]+ for result in child_results+ ] == [[("target", "value", 2)], [("target", "value", 4)]]+++def test_build_child_workflow_sessions_expands_direct_integer_batch_into_named_return_value() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "batch",+ "integer_batch",+ {"integers": {"value": [2, 4, 6]}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-batch-return",+ "type": "default",+ "source": "batch",+ "sourceHandle": "integers",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )++ child_sessions = build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ )++ assert len(child_sessions) == 3+ assert [child_session.graph.nodes["return-value"].value for child_session in child_sessions] == [2, 4, 6]+++def test_build_child_workflow_sessions_rejects_inaccessible_image_generator_board() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "generator",+ "image_generator",+ {+ "generator": {+ "value": {+ "type": "image_generator_images_from_board",+ "board_id": "private-board",+ "category": "images",+ }+ }+ },+ ),+ _invocation_node(+ "batch",+ "image_batch",+ {"images": {"value": []}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "img_paste", {"image": {"value": None}, "board": {"value": None}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-generator-batch",+ "type": "default",+ "source": "generator",+ "sourceHandle": "images",+ "target": "batch",+ "targetHandle": "images",+ },+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "images",+ "target": "target",+ "targetHandle": "image",+ },+ {+ "id": "edge-target-return",+ "type": "default",+ "source": "target",+ "sourceHandle": "image",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )++ services = type(+ "Services",+ (),+ {+ "board_images": type(+ "BoardImages",+ (),+ {+ "get_all_board_image_names_for_board": staticmethod(+ lambda board_id, categories, is_intermediate: ["img-a"]+ )+ },+ )(),+ "board_records": type(+ "BoardRecords",+ (),+ {+ "get": staticmethod(+ lambda board_id: type(+ "BoardRecord",+ (),+ {"board_id": board_id, "user_id": "owner-1", "board_visibility": "private"},+ )()+ )+ },+ )(),+ "users": type(+ "Users",+ (),+ {"get": staticmethod(lambda user_id: type("User", (), {"is_admin": False})())},+ )(),+ },+ )()++ with pytest.raises(UnsupportedWorkflowNodeError, match="does not have access to board 'private-board'"):+ build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ services=services,+ user_id="caller-1",+ )+++def test_build_child_workflow_sessions_allows_shared_image_generator_board() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "generator",+ "image_generator",+ {+ "generator": {+ "value": {+ "type": "image_generator_images_from_board",+ "board_id": "shared-board",+ "category": "images",+ }+ }+ },+ ),+ _invocation_node(+ "batch",+ "image_batch",+ {"images": {"value": []}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "img_paste", {"image": {"value": None}, "board": {"value": None}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-generator-batch",+ "type": "default",+ "source": "generator",+ "sourceHandle": "images",+ "target": "batch",+ "targetHandle": "images",+ },+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "images",+ "target": "target",+ "targetHandle": "image",+ },+ {+ "id": "edge-target-return",+ "type": "default",+ "source": "target",+ "sourceHandle": "image",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )++ services = type(+ "Services",+ (),+ {+ "board_images": type(+ "BoardImages",+ (),+ {+ "get_all_board_image_names_for_board": staticmethod(+ lambda board_id, categories, is_intermediate: ["img-a", "img-b"]+ )+ },+ )(),+ "board_records": type(+ "BoardRecords",+ (),+ {+ "get": staticmethod(+ lambda board_id: type(+ "BoardRecord",+ (),+ {"board_id": board_id, "user_id": "owner-1", "board_visibility": "shared"},+ )()+ )+ },+ )(),+ "users": type(+ "Users",+ (),+ {"get": staticmethod(lambda user_id: type("User", (), {"is_admin": False})())},+ )(),+ },+ )()++ child_sessions = build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ services=services,+ user_id="caller-1",+ )++ assert len(child_sessions) == 2+++def test_build_child_workflow_sessions_zips_grouped_batches() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "batch-a",+ "integer_batch",+ {"integers": {"value": [1, 2, 3]}, "batch_group_id": {"value": "Group 1"}},+ ),+ _invocation_node(+ "batch-b",+ "integer_batch",+ {"integers": {"value": [10, 20, 30]}, "batch_group_id": {"value": "Group 1"}},+ ),+ _invocation_node("target", "add", {"a": {"value": 0}, "b": {"value": 0}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-a",+ "type": "default",+ "source": "batch-a",+ "sourceHandle": "integers",+ "target": "target",+ "targetHandle": "a",+ },+ {+ "id": "edge-b",+ "type": "default",+ "source": "batch-b",+ "sourceHandle": "integers",+ "target": "target",+ "targetHandle": "b",+ },+ {+ "id": "edge-target-collect",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-collect-return",+ "type": "default",+ "source": "collect",+ "sourceHandle": "collection",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )++ child_sessions = build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ )++ assert len(child_sessions) == 3+ assert [(child.graph.nodes["target"].a, child.graph.nodes["target"].b) for child in child_sessions] == [+ (1, 10),+ (2, 20),+ (3, 30),+ ]+++def test_build_child_workflow_sessions_expands_cartesian_batches() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "batch-a",+ "integer_batch",+ {"integers": {"value": [1, 2]}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node(+ "batch-b",+ "integer_batch",+ {"integers": {"value": [10, 20]}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "add", {"a": {"value": 0}, "b": {"value": 0}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-a",+ "type": "default",+ "source": "batch-a",+ "sourceHandle": "integers",+ "target": "target",+ "targetHandle": "a",+ },+ {+ "id": "edge-b",+ "type": "default",+ "source": "batch-b",+ "sourceHandle": "integers",+ "target": "target",+ "targetHandle": "b",+ },+ {+ "id": "edge-target-collect",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-collect-return",+ "type": "default",+ "source": "collect",+ "sourceHandle": "collection",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )++ child_sessions = build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ )++ assert len(child_sessions) == 4+ assert [(child.graph.nodes["target"].a, child.graph.nodes["target"].b) for child in child_sessions] == [+ (1, 10),+ (1, 20),+ (2, 10),+ (2, 20),+ ]+++def test_build_child_workflow_sessions_applies_parent_inputs_before_batch_expansion() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "batch",+ "integer_batch",+ {"integers": {"value": [1]}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "integer", {"value": {"value": 0}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "integers",+ "target": "target",+ "targetHandle": "value",+ },+ {+ "id": "edge-target-collect",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-collect-return",+ "type": "default",+ "source": "collect",+ "sourceHandle": "collection",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ exposed_fields=[{"nodeId": "batch", "fieldName": "integers"}],+ )++ child_sessions = build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={"saved_workflow_input::batch::integers": [9, 10]},+ call_frame=_call_frame(),+ maximum_children=10,+ )++ assert [child_session.graph.nodes["target"].value for child_session in child_sessions] == [9, 10]+++def test_build_child_workflow_sessions_rejects_non_generator_connected_batch_nodes() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node("generator", "integer", {"value": {"value": 7}}),+ _invocation_node(+ "batch",+ "integer_batch",+ {"integers": {"value": []}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "integer", {"value": {"value": 0}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-generator-batch",+ "type": "default",+ "source": "generator",+ "sourceHandle": "integers",+ "target": "batch",+ "targetHandle": "integers",+ }+ ],+ )++ with pytest.raises(UnsupportedWorkflowNodeError, match="connected batch child workflow inputs"):+ build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ )+++def test_build_child_workflow_sessions_supports_generator_backed_batch_input_through_connector() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "generator",+ "integer_generator",+ {+ "generator": {+ "value": {+ "type": "integer_generator_arithmetic_sequence",+ "start": 1,+ "step": 1,+ "count": 3,+ }+ }+ },+ ),+ {+ "id": "connector",+ "type": "connector",+ "position": {"x": 0, "y": 0},+ "data": {"id": "connector", "type": "connector", "label": "Connector", "isOpen": True},+ },+ _invocation_node(+ "batch",+ "integer_batch",+ {"integers": {"value": []}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "integer", {"value": {"value": 0}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-generator-connector",+ "type": "default",+ "source": "generator",+ "sourceHandle": "integers",+ "target": "connector",+ "targetHandle": "in",+ },+ {+ "id": "edge-connector-batch",+ "type": "default",+ "source": "connector",+ "sourceHandle": "out",+ "target": "batch",+ "targetHandle": "integers",+ },+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "integers",+ "target": "target",+ "targetHandle": "value",+ },+ {+ "id": "edge-target-collect",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-collect-return",+ "type": "default",+ "source": "collect",+ "sourceHandle": "collection",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )++ child_sessions = build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ )++ assert [child_session.graph.nodes["target"].value for child_session in child_sessions] == [1, 2, 3]+++def test_build_child_workflow_sessions_rejects_hybrid_child_workflows_with_unrelated_generator_nodes() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "batch",+ "integer_batch",+ {"integers": {"value": [2, 4]}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node(+ "side-generator",+ "integer_generator",+ {+ "generator": {+ "value": {+ "type": "integer_generator_arithmetic_sequence",+ "start": 5,+ "step": 1,+ "count": 2,+ }+ }+ },+ ),+ _invocation_node("target", "integer", {"value": {"value": 0}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "integers",+ "target": "target",+ "targetHandle": "value",+ },+ {+ "id": "edge-target-collect",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-collect-return",+ "type": "default",+ "source": "collect",+ "sourceHandle": "collection",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )++ with pytest.raises(+ UnsupportedWorkflowNodeError,+ match="mix supported batch nodes with unrelated generator nodes",+ ):+ build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ )+++def test_build_child_workflow_sessions_supports_integer_generator() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "generator",+ "integer_generator",+ {+ "generator": {+ "value": {+ "type": "integer_generator_arithmetic_sequence",+ "start": 3,+ "step": 2,+ "count": 3,+ }+ }+ },+ ),+ _invocation_node(+ "batch",+ "integer_batch",+ {"integers": {"value": []}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "integer", {"value": {"value": 0}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-generator-batch",+ "type": "default",+ "source": "generator",+ "sourceHandle": "integers",+ "target": "batch",+ "targetHandle": "integers",+ },+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "integers",+ "target": "target",+ "targetHandle": "value",+ },+ {+ "id": "edge-target-collect",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-collect-return",+ "type": "default",+ "source": "collect",+ "sourceHandle": "collection",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )++ child_sessions = build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ )++ assert [child_session.graph.nodes["target"].value for child_session in child_sessions] == [3, 5, 7]+++def test_build_child_workflow_sessions_rejects_oversized_generator_before_resolution(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "generator",+ "integer_generator",+ {+ "generator": {+ "value": {+ "type": "integer_generator_arithmetic_sequence",+ "start": 0,+ "step": 1,+ "count": 1_000_000,+ }+ }+ },+ ),+ _invocation_node(+ "batch",+ "integer_batch",+ {"integers": {"value": []}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "integer", {"value": {"value": 0}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-generator-batch",+ "type": "default",+ "source": "generator",+ "sourceHandle": "integers",+ "target": "batch",+ "targetHandle": "integers",+ },+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "integers",+ "target": "target",+ "targetHandle": "value",+ },+ {+ "id": "edge-target-return",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )+ monkeypatch.setattr(+ "invokeai.app.services.session_processor.workflow_call_batch._resolve_integer_generator",+ lambda value: pytest.fail("oversized generators must be rejected before resolution"),+ )++ with pytest.raises(TooManySessionsError, match="remaining queue capacity"):+ build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ )+++def test_build_child_workflow_sessions_supports_float_generator() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "generator",+ "float_generator",+ {+ "generator": {+ "value": {+ "type": "float_generator_linear_distribution",+ "start": 0.5,+ "end": 1.5,+ "count": 3,+ }+ }+ },+ ),+ _invocation_node(+ "batch",+ "float_batch",+ {"floats": {"value": []}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "float", {"value": {"value": 0.0}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-generator-batch",+ "type": "default",+ "source": "generator",+ "sourceHandle": "floats",+ "target": "batch",+ "targetHandle": "floats",+ },+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "floats",+ "target": "target",+ "targetHandle": "value",+ },+ {+ "id": "edge-target-collect",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-collect-return",+ "type": "default",+ "source": "collect",+ "sourceHandle": "collection",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )++ child_sessions = build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ )++ assert [child_session.graph.nodes["target"].value for child_session in child_sessions] == [0.5, 1.0, 1.5]+++def test_build_child_workflow_sessions_supports_string_generator() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "generator",+ "string_generator",+ {+ "generator": {+ "value": {+ "type": "string_generator_parse_string",+ "input": "alpha,beta,gamma",+ "splitOn": ",",+ }+ }+ },+ ),+ _invocation_node(+ "batch",+ "string_batch",+ {"strings": {"value": []}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "string", {"value": {"value": ""}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-generator-batch",+ "type": "default",+ "source": "generator",+ "sourceHandle": "strings",+ "target": "batch",+ "targetHandle": "strings",+ },+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "strings",+ "target": "target",+ "targetHandle": "value",+ },+ {+ "id": "edge-target-collect",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-collect-return",+ "type": "default",+ "source": "collect",+ "sourceHandle": "collection",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )++ child_sessions = build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ )++ assert [child_session.graph.nodes["target"].value for child_session in child_sessions] == [+ "alpha",+ "beta",+ "gamma",+ ]+++def test_build_child_workflow_sessions_supports_string_dynamic_prompts_generator() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "generator",+ "string_generator",+ {+ "generator": {+ "value": {+ "type": "string_generator_dynamic_prompts_combinatorial",+ "input": "a {red|blue} cube",+ "maxPrompts": 10,+ }+ }+ },+ ),+ _invocation_node(+ "batch",+ "string_batch",+ {"strings": {"value": []}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "string", {"value": {"value": ""}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-generator-batch",+ "type": "default",+ "source": "generator",+ "sourceHandle": "strings",+ "target": "batch",+ "targetHandle": "strings",+ },+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "strings",+ "target": "target",+ "targetHandle": "value",+ },+ {+ "id": "edge-target-collect",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-collect-return",+ "type": "default",+ "source": "collect",+ "sourceHandle": "collection",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )++ child_sessions = build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ )++ assert [child_session.graph.nodes["target"].value for child_session in child_sessions] == [+ "a red cube",+ "a blue cube",+ ]+++def test_build_child_workflow_sessions_supports_seeded_uniform_random_generators() -> None:+ integer_workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "generator",+ "integer_generator",+ {+ "generator": {+ "value": {+ "type": "integer_generator_random_distribution_uniform",+ "min": 1,+ "max": 3,+ "count": 3,+ "seed": 4,+ }+ }+ },+ ),+ _invocation_node(+ "batch",+ "integer_batch",+ {"integers": {"value": []}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "integer", {"value": {"value": 0}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-generator-batch",+ "type": "default",+ "source": "generator",+ "sourceHandle": "integers",+ "target": "batch",+ "targetHandle": "integers",+ },+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "integers",+ "target": "target",+ "targetHandle": "value",+ },+ {+ "id": "edge-target-collect",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-collect-return",+ "type": "default",+ "source": "collect",+ "sourceHandle": "collection",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )+ float_workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "generator",+ "float_generator",+ {+ "generator": {+ "value": {+ "type": "float_generator_random_distribution_uniform",+ "min": 0.0,+ "max": 1.0,+ "count": 2,+ "seed": 4,+ }+ }+ },+ ),+ _invocation_node(+ "batch",+ "float_batch",+ {"floats": {"value": []}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "float", {"value": {"value": 0.0}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-generator-batch",+ "type": "default",+ "source": "generator",+ "sourceHandle": "floats",+ "target": "batch",+ "targetHandle": "floats",+ },+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "floats",+ "target": "target",+ "targetHandle": "value",+ },+ {+ "id": "edge-target-collect",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-collect-return",+ "type": "default",+ "source": "collect",+ "sourceHandle": "collection",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )++ integer_sessions = build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=integer_workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ )+ float_sessions = build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=float_workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ )++ assert [child_session.graph.nodes["target"].value for child_session in integer_sessions] == [1, 1, 2]+ assert [round(child_session.graph.nodes["target"].value, 6) for child_session in float_sessions] == [+ 0.236048,+ 0.103166,+ ]+++def test_build_child_workflow_sessions_supports_image_generator_from_board() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "generator",+ "image_generator",+ {+ "generator": {+ "value": {+ "type": "image_generator_images_from_board",+ "board_id": "board-1",+ "category": "images",+ }+ }+ },+ ),+ _invocation_node(+ "batch",+ "image_batch",+ {"images": {"value": []}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "image", {"image": {"value": None}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ _invocation_node("return", "workflow_return", {"collection": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-generator-batch",+ "type": "default",+ "source": "generator",+ "sourceHandle": "images",+ "target": "batch",+ "targetHandle": "images",+ },+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "images",+ "target": "target",+ "targetHandle": "image",+ },+ {+ "id": "edge-collect-return",+ "type": "default",+ "source": "target",+ "sourceHandle": "image",+ "target": "collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-target-return",+ "type": "default",+ "source": "collect",+ "sourceHandle": "collection",+ "target": "return",+ "targetHandle": "collection",+ },+ ],+ )++ services = type(+ "Services",+ (),+ {+ "board_images": type(+ "BoardImages",+ (),+ {+ "get_all_board_image_names_for_board": staticmethod(+ lambda board_id, categories, is_intermediate: ["img-a", "img-b"]+ )+ },+ )()+ },+ )()++ child_sessions = build_child_workflow_sessions(+ parent_session=GraphExecutionState(graph=Graph()),+ workflow=workflow,+ workflow_inputs={},+ call_frame=_call_frame(),+ maximum_children=10,+ services=services,+ user_id="user-1",+ )++ assert [child_session.graph.nodes["target"].image.image_name for child_session in child_sessions] == [+ "img-a",+ "img-b",+ ]diff --git a/tests/app/services/test_workflow_call_batch_runtime.py b/tests/app/services/test_workflow_call_batch_runtime.pynew file mode 100644index 0000000000..d21883e3db--- /dev/null+++ b/tests/app/services/test_workflow_call_batch_runtime.py@@ -0,0 +1,33 @@+from tests.app.services import workflow_call_test_utils as workflow_call_tests+++def test_run_node_fails_cleanly_for_invalid_batch_child_workflow(monkeypatch) -> None:+ workflow_call_tests.test_run_node_fails_cleanly_for_invalid_batch_child_workflow(monkeypatch)+++def test_run_completes_call_saved_workflow_with_batched_child_returns(monkeypatch) -> None:+ workflow_call_tests.test_run_completes_call_saved_workflow_with_batched_child_returns(monkeypatch)+++def test_run_zips_grouped_batch_children(monkeypatch) -> None:+ workflow_call_tests.test_run_zips_grouped_batch_children(monkeypatch)+++def test_run_expands_ungrouped_batch_children_as_cartesian_product(monkeypatch) -> None:+ workflow_call_tests.test_run_expands_ungrouped_batch_children_as_cartesian_product(monkeypatch)+++def test_run_fails_batched_child_workflow_and_cancels_remaining_siblings(monkeypatch) -> None:+ workflow_call_tests.test_run_fails_batched_child_workflow_and_cancels_remaining_siblings(monkeypatch)+++def test_run_supports_generator_backed_integer_batched_child_workflow(monkeypatch) -> None:+ workflow_call_tests.test_run_supports_generator_backed_integer_batched_child_workflow(monkeypatch)+++def test_run_supports_generator_backed_image_batched_child_workflow(monkeypatch) -> None:+ workflow_call_tests.test_run_supports_generator_backed_image_batched_child_workflow(monkeypatch)+++def test_run_rejects_non_generator_connected_batched_child_workflow(monkeypatch) -> None:+ workflow_call_tests.test_run_rejects_non_generator_connected_batched_child_workflow(monkeypatch)diff --git a/tests/app/services/test_workflow_call_compatibility.py b/tests/app/services/test_workflow_call_compatibility.pynew file mode 100644index 0000000000..56cac03939--- /dev/null+++ b/tests/app/services/test_workflow_call_compatibility.py@@ -0,0 +1,587 @@+from typing import Any++from invokeai.app.services.shared.workflow_call_compatibility import (+ WorkflowCallCompatibilityReason,+ get_workflow_call_compatibility,+)+++def _invocation_node(node_id: str, invocation_type: str, inputs: dict[str, Any]) -> dict[str, Any]:+ return {+ "id": node_id,+ "type": "invocation",+ "position": {"x": 0, "y": 0},+ "data": {+ "id": node_id,+ "type": invocation_type,+ "version": "1.0.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "isOpen": True,+ "isIntermediate": False,+ "useCache": True,+ "dynamicInputTemplates": {},+ "inputs": inputs,+ },+ }+++def _workflow_dump(*, nodes: list[dict[str, Any]], edges: list[dict[str, Any]]) -> dict[str, Any]:+ return {+ "name": "Child Workflow",+ "author": "Tester",+ "description": "",+ "version": "1.0.0",+ "contact": "",+ "tags": "",+ "notes": "",+ "exposedFields": [],+ "meta": {"category": "user", "version": "1.0.0"},+ "nodes": nodes,+ "edges": edges,+ "form": None,+ }+++def _return_nodes() -> list[dict[str, Any]]:+ return [+ _invocation_node(+ "return-value", "workflow_return_value", {"key": {"value": "result"}, "value": {"value": None}}+ ),+ _invocation_node("return-collect", "collect", {"collection": {"value": []}}),+ _invocation_node("return", "workflow_return", {"values": {"value": []}}),+ ]+++def _return_edges(source: str, source_handle: str) -> list[dict[str, str]]:+ return [+ {+ "id": "edge-return-value",+ "type": "default",+ "source": source,+ "sourceHandle": source_handle,+ "target": "return-value",+ "targetHandle": "value",+ },+ {+ "id": "edge-return-collect",+ "type": "default",+ "source": "return-value",+ "sourceHandle": "value",+ "target": "return-collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-return-values",+ "type": "default",+ "source": "return-collect",+ "sourceHandle": "collection",+ "target": "return",+ "targetHandle": "values",+ },+ ]+++def _services():+ return type(+ "Services",+ (),+ {+ "board_images": type(+ "BoardImages",+ (),+ {+ "get_all_board_image_names_for_board": staticmethod(+ lambda board_id, categories, is_intermediate: ["img-a", "img-b"]+ )+ },+ )(),+ },+ )()+++def _services_that_fail_on_image_enumeration():+ def fail(*args: Any, **kwargs: Any) -> list[str]:+ raise AssertionError("image names should not be enumerated for structural compatibility")++ return type(+ "Services",+ (),+ {+ "board_images": type(+ "BoardImages",+ (),+ {"get_all_board_image_names_for_board": staticmethod(fail)},+ )(),+ },+ )()+++def test_get_workflow_call_compatibility_returns_ok_for_simple_callable_workflow() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node("collection", "integer_collection", {"collection": {"value": [1]}}),+ *_return_nodes(),+ ],+ edges=_return_edges("collection", "collection"),+ )++ compatibility = get_workflow_call_compatibility(+ workflow=workflow,+ workflow_id="workflow-a",+ services=_services(),+ user_id="user-1",+ maximum_children=1000,+ )++ assert compatibility.is_callable is True+ assert compatibility.reason is WorkflowCallCompatibilityReason.Ok+ assert compatibility.message is None+++def test_get_workflow_call_compatibility_allows_single_return_value_connected_directly() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node("sum", "add", {"a": {"value": 1}, "b": {"value": 2}}),+ _invocation_node(+ "return-value", "workflow_return_value", {"key": {"value": "sum"}, "value": {"value": None}}+ ),+ _invocation_node("return", "workflow_return", {"values": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-sum-return-value",+ "type": "default",+ "source": "sum",+ "sourceHandle": "value",+ "target": "return-value",+ "targetHandle": "value",+ },+ {+ "id": "edge-return-value-return",+ "type": "default",+ "source": "return-value",+ "sourceHandle": "value",+ "target": "return",+ "targetHandle": "values",+ },+ ],+ )++ compatibility = get_workflow_call_compatibility(+ workflow=workflow,+ workflow_id="workflow-a",+ services=_services(),+ user_id="user-1",+ maximum_children=1000,+ )++ assert compatibility.is_callable is True+ assert compatibility.reason is WorkflowCallCompatibilityReason.Ok+ assert compatibility.message is None+++def test_get_workflow_call_compatibility_reports_missing_workflow_return() -> None:+ workflow = _workflow_dump(nodes=[_invocation_node("add", "add", {"a": {"value": 1}, "b": {"value": 2}})], edges=[])++ compatibility = get_workflow_call_compatibility(+ workflow=workflow,+ workflow_id="workflow-a",+ services=_services(),+ user_id="user-1",+ maximum_children=1000,+ )++ assert compatibility.is_callable is False+ assert compatibility.reason is WorkflowCallCompatibilityReason.MissingWorkflowReturn+ assert compatibility.message == "The workflow must contain exactly one workflow_return node."+++def test_get_workflow_call_compatibility_reports_multiple_workflow_return_nodes() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node("return-a", "workflow_return", {"values": {"value": []}}),+ _invocation_node("return-b", "workflow_return", {"values": {"value": []}}),+ ],+ edges=[],+ )++ compatibility = get_workflow_call_compatibility(+ workflow=workflow,+ workflow_id="workflow-a",+ services=_services(),+ user_id="user-1",+ maximum_children=1000,+ )++ assert compatibility.is_callable is False+ assert compatibility.reason is WorkflowCallCompatibilityReason.MultipleWorkflowReturn+ assert compatibility.message == "The workflow must not contain more than one workflow_return node."+++def test_get_workflow_call_compatibility_reports_generator_capacity_limit() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "generator",+ "integer_generator",+ {+ "generator": {+ "value": {+ "type": "integer_generator_arithmetic_sequence",+ "start": 0,+ "step": 1,+ "count": 1_000_000,+ }+ }+ },+ ),+ _invocation_node(+ "batch",+ "integer_batch",+ {"integers": {"value": []}, "batch_group_id": {"value": "None"}},+ ),+ _invocation_node("target", "integer", {"value": {"value": 0}}),+ *_return_nodes(),+ ],+ edges=[+ {+ "id": "edge-generator-batch",+ "type": "default",+ "source": "generator",+ "sourceHandle": "integers",+ "target": "batch",+ "targetHandle": "integers",+ },+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "integers",+ "target": "target",+ "targetHandle": "value",+ },+ *_return_edges("target", "value"),+ ],+ )++ compatibility = get_workflow_call_compatibility(+ workflow=workflow,+ workflow_id="workflow-a",+ services=_services(),+ user_id="user-1",+ maximum_children=10,+ )++ assert compatibility.is_callable is False+ assert compatibility.reason is WorkflowCallCompatibilityReason.ExceedsCapacity+ assert compatibility.message == "call_saved_workflow exceeds remaining queue capacity for child workflow executions"+++def test_get_workflow_call_compatibility_does_not_report_present_malformed_workflow_return_as_missing() -> None:+ workflow = _workflow_dump(+ nodes=[+ {+ "id": "return",+ "type": "invocation",+ "position": {"x": 0, "y": 0},+ "data": {+ "type": "workflow_return",+ "version": "1.0.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "isOpen": True,+ "isIntermediate": False,+ "useCache": True,+ "dynamicInputTemplates": {},+ "inputs": {"values": {"value": []}},+ },+ }+ ],+ edges=[],+ )++ compatibility = get_workflow_call_compatibility(+ workflow=workflow,+ workflow_id="workflow-a",+ services=_services(),+ user_id="user-1",+ maximum_children=1000,+ )++ assert compatibility.is_callable is False+ assert compatibility.reason is WorkflowCallCompatibilityReason.InvalidGraph+ assert compatibility.message != "The workflow must contain exactly one workflow_return node."+++def test_get_workflow_call_compatibility_reports_unsupported_connected_batch_input() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node("source", "integer", {"value": {"value": 7}}),+ _invocation_node(+ "batch", "integer_batch", {"integers": {"value": []}, "batch_group_id": {"value": "None"}}+ ),+ _invocation_node("target", "integer", {"value": {"value": 0}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ *_return_nodes(),+ ],+ edges=[+ {+ "id": "edge-source-batch",+ "type": "default",+ "source": "source",+ "sourceHandle": "value",+ "target": "batch",+ "targetHandle": "integers",+ },+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "integers",+ "target": "target",+ "targetHandle": "value",+ },+ {+ "id": "edge-target-collect",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "collect",+ "targetHandle": "item",+ },+ *_return_edges("collect", "collection"),+ ],+ )++ compatibility = get_workflow_call_compatibility(+ workflow=workflow,+ workflow_id="workflow-a",+ services=_services(),+ user_id="user-1",+ maximum_children=1000,+ )++ assert compatibility.is_callable is False+ assert compatibility.reason is WorkflowCallCompatibilityReason.UnsupportedBatchInput+ assert "connected batch child workflow inputs" in (compatibility.message or "")+++def test_get_workflow_call_compatibility_allows_batch_returned_by_name() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "batch", "integer_batch", {"integers": {"value": [2, 4]}, "batch_group_id": {"value": "None"}}+ ),+ *_return_nodes(),+ ],+ edges=[+ {+ "id": "edge-batch-return",+ "type": "default",+ "source": "batch",+ "sourceHandle": "integers",+ "target": "return-value",+ "targetHandle": "value",+ },+ *_return_edges("return-value", "value")[1:],+ ],+ )++ compatibility = get_workflow_call_compatibility(+ workflow=workflow,+ workflow_id="workflow-a",+ services=_services(),+ user_id="user-1",+ maximum_children=1000,+ )++ assert compatibility.is_callable is True+ assert compatibility.reason is WorkflowCallCompatibilityReason.Ok+ assert compatibility.message is None+++def test_get_workflow_call_compatibility_can_skip_generator_expansion_for_list_views() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node(+ "generator",+ "image_generator",+ {+ "generator": {+ "value": {+ "type": "image_generator_images_from_board",+ "board_id": "board-a",+ "category": "images",+ }+ }+ },+ ),+ _invocation_node("batch", "image_batch", {"images": {"value": []}, "batch_group_id": {"value": "None"}}),+ *_return_nodes(),+ ],+ edges=[+ {+ "id": "edge-generator-batch",+ "type": "default",+ "source": "generator",+ "sourceHandle": "collection",+ "target": "batch",+ "targetHandle": "images",+ },+ {+ "id": "edge-batch-return",+ "type": "default",+ "source": "batch",+ "sourceHandle": "images",+ "target": "return-value",+ "targetHandle": "value",+ },+ *_return_edges("return-value", "value")[1:],+ ],+ )++ compatibility = get_workflow_call_compatibility(+ workflow=workflow,+ workflow_id="workflow-a",+ services=_services_that_fail_on_image_enumeration(),+ user_id="user-1",+ maximum_children=1000,+ resolve_generator_items=False,+ )++ assert compatibility.is_callable is True+ assert compatibility.reason is WorkflowCallCompatibilityReason.Ok+ assert compatibility.message is None+++def test_get_workflow_call_compatibility_reports_multiple_batch_inputs_as_unsupported_batch_input() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node("source-a", "integer", {"value": {"value": 7}}),+ _invocation_node("source-b", "integer", {"value": {"value": 8}}),+ _invocation_node(+ "batch", "integer_batch", {"integers": {"value": []}, "batch_group_id": {"value": "None"}}+ ),+ _invocation_node("target", "integer", {"value": {"value": 0}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ *_return_nodes(),+ ],+ edges=[+ {+ "id": "edge-source-a-batch",+ "type": "default",+ "source": "source-a",+ "sourceHandle": "value",+ "target": "batch",+ "targetHandle": "integers",+ },+ {+ "id": "edge-source-b-batch",+ "type": "default",+ "source": "source-b",+ "sourceHandle": "value",+ "target": "batch",+ "targetHandle": "integers",+ },+ {+ "id": "edge-batch-target",+ "type": "default",+ "source": "batch",+ "sourceHandle": "integers",+ "target": "target",+ "targetHandle": "value",+ },+ {+ "id": "edge-target-collect",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "collect",+ "targetHandle": "item",+ },+ *_return_edges("collect", "collection"),+ ],+ )++ compatibility = get_workflow_call_compatibility(+ workflow=workflow,+ workflow_id="workflow-a",+ services=_services(),+ user_id="user-1",+ maximum_children=1000,+ )++ assert compatibility.is_callable is False+ assert compatibility.reason is WorkflowCallCompatibilityReason.UnsupportedBatchInput+ assert "multiple connected batch inputs" in (compatibility.message or "")+++def test_get_workflow_call_compatibility_allows_workflow_with_required_exposed_input() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node("target", "integer", {"value": {}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ *_return_nodes(),+ ],+ edges=[+ {+ "id": "edge-target-collect",+ "type": "default",+ "source": "target",+ "sourceHandle": "value",+ "target": "collect",+ "targetHandle": "item",+ },+ *_return_edges("collect", "collection"),+ ],+ )+ workflow["exposedFields"] = [{"nodeId": "target", "fieldName": "value"}]++ compatibility = get_workflow_call_compatibility(+ workflow=workflow,+ workflow_id="workflow-a",+ services=_services(),+ user_id="user-1",+ maximum_children=1000,+ )++ assert compatibility.is_callable is True+ assert compatibility.reason is WorkflowCallCompatibilityReason.Ok+ assert compatibility.message is None+++def test_get_workflow_call_compatibility_allows_workflow_with_required_structured_exposed_input() -> None:+ workflow = _workflow_dump(+ nodes=[+ _invocation_node("template", "prompt_template", {"style_preset": {}}),+ _invocation_node("collect", "collect", {"collection": {"value": []}}),+ *_return_nodes(),+ ],+ edges=[+ {+ "id": "edge-template-collect",+ "type": "default",+ "source": "template",+ "sourceHandle": "positive_prompt",+ "target": "collect",+ "targetHandle": "item",+ },+ *_return_edges("collect", "collection"),+ ],+ )+ workflow["exposedFields"] = [{"nodeId": "template", "fieldName": "style_preset"}]++ compatibility = get_workflow_call_compatibility(+ workflow=workflow,+ workflow_id="workflow-a",+ services=_services(),+ user_id="user-1",+ maximum_children=1000,+ )++ assert compatibility.is_callable is True+ assert compatibility.reason is WorkflowCallCompatibilityReason.Ok+ assert compatibility.message is Nonediff --git a/tests/app/services/test_workflow_call_runtime.py b/tests/app/services/test_workflow_call_runtime.pynew file mode 100644index 0000000000..1edaaaae00--- /dev/null+++ b/tests/app/services/test_workflow_call_runtime.py@@ -0,0 +1,133 @@+from tests.app.services import workflow_call_test_utils as workflow_call_tests+++def test_run_node_enters_waiting_state_without_executing_child_inline(monkeypatch) -> None:+ workflow_call_tests.test_run_node_enters_waiting_state_without_executing_child_inline(monkeypatch)+++def test_run_persists_waiting_session_without_completing_queue_item(monkeypatch) -> None:+ workflow_call_tests.test_run_persists_waiting_session_without_completing_queue_item(monkeypatch)+++def test_workflow_call_coordinator_suspends_parent_and_enqueues_child_queue_item(monkeypatch) -> None:+ workflow_call_tests.test_workflow_call_coordinator_suspends_parent_and_enqueues_child_queue_item(monkeypatch)+++def test_workflow_call_queue_lifecycle_leaves_non_call_workflows_on_normal_execution_path(monkeypatch) -> None:+ workflow_call_tests.test_workflow_call_queue_lifecycle_leaves_non_call_workflows_on_normal_execution_path(+ monkeypatch+ )+++def test_default_session_processor_uses_runner_workflow_call_lifecycle(monkeypatch) -> None:+ workflow_call_tests.test_default_session_processor_uses_runner_workflow_call_lifecycle(monkeypatch)+++def test_workflow_call_queue_lifecycle_resumes_parent_from_completed_child(monkeypatch) -> None:+ workflow_call_tests.test_workflow_call_queue_lifecycle_resumes_parent_from_completed_child(monkeypatch)+++def test_run_preserves_canceled_child_workflow_chain_without_failing_parent(monkeypatch) -> None:+ workflow_call_tests.test_run_preserves_canceled_child_workflow_chain_without_failing_parent(monkeypatch)+++def test_run_does_not_resume_canceled_parent_after_completed_child(monkeypatch) -> None:+ workflow_call_tests.test_run_does_not_resume_canceled_parent_after_completed_child(monkeypatch)+++def test_run_does_not_fail_canceled_parent_after_child_return_error(monkeypatch) -> None:+ workflow_call_tests.test_run_does_not_fail_canceled_parent_after_child_return_error(monkeypatch)+++def test_workflow_call_coordinator_builds_child_queue_item_with_relationship_metadata(monkeypatch) -> None:+ workflow_call_tests.test_workflow_call_coordinator_builds_child_queue_item_with_relationship_metadata(monkeypatch)+++def test_workflow_call_coordinator_cleans_up_enqueued_children_when_boundary_setup_fails(monkeypatch) -> None:+ workflow_call_tests.test_workflow_call_coordinator_cleans_up_enqueued_children_when_boundary_setup_fails(+ monkeypatch+ )+++def test_workflow_call_coordinator_rejects_child_expansion_that_exceeds_remaining_queue_capacity(monkeypatch) -> None:+ workflow_call_tests.test_workflow_call_coordinator_rejects_child_expansion_that_exceeds_remaining_queue_capacity(+ monkeypatch+ )+++def test_run_completes_call_saved_workflow_and_runs_downstream_nodes(monkeypatch) -> None:+ workflow_call_tests.test_run_completes_call_saved_workflow_and_runs_downstream_nodes(monkeypatch)+++def test_run_completes_parent_queue_item_when_return_get_is_terminal(monkeypatch) -> None:+ workflow_call_tests.test_run_completes_parent_queue_item_when_return_get_is_terminal(monkeypatch)+++def test_run_node_records_child_execution_state_for_call_saved_workflow(monkeypatch) -> None:+ workflow_call_tests.test_run_node_records_child_execution_state_for_call_saved_workflow(monkeypatch)+++def test_run_executes_child_workflow_and_completes_parent_queue_item(monkeypatch) -> None:+ workflow_call_tests.test_run_executes_child_workflow_and_completes_parent_queue_item(monkeypatch)+++def test_run_completes_call_saved_workflow_with_child_return_collection(monkeypatch) -> None:+ workflow_call_tests.test_run_completes_call_saved_workflow_with_child_return_collection(monkeypatch)+++def test_run_extracts_named_call_saved_workflow_return(monkeypatch) -> None:+ workflow_call_tests.test_run_extracts_named_call_saved_workflow_return(monkeypatch)+++def test_workflow_call_batch_aggregation_rejects_inconsistent_return_keys() -> None:+ workflow_call_tests.test_workflow_call_batch_aggregation_rejects_inconsistent_return_keys()+++def test_workflow_call_return_aggregation_failure_cancels_remaining_siblings(monkeypatch) -> None:+ workflow_call_tests.test_workflow_call_return_aggregation_failure_cancels_remaining_siblings(monkeypatch)+++def test_run_fails_call_saved_workflow_when_child_has_no_workflow_return(monkeypatch) -> None:+ workflow_call_tests.test_run_fails_call_saved_workflow_when_child_has_no_workflow_return(monkeypatch)+++def test_run_respects_child_dependency_readiness(monkeypatch) -> None:+ workflow_call_tests.test_run_respects_child_dependency_readiness(monkeypatch)+++def test_run_respects_child_if_branching(monkeypatch) -> None:+ workflow_call_tests.test_run_respects_child_if_branching(monkeypatch)+++def test_run_supports_nested_call_saved_workflow_execution(monkeypatch) -> None:+ workflow_call_tests.test_run_supports_nested_call_saved_workflow_execution(monkeypatch)+++def test_run_cascades_nested_child_workflow_failures_to_all_parents(monkeypatch) -> None:+ workflow_call_tests.test_run_cascades_nested_child_workflow_failures_to_all_parents(monkeypatch)+++def test_run_forwards_literal_dynamic_workflow_inputs_to_child_workflow(monkeypatch) -> None:+ workflow_call_tests.test_run_forwards_literal_dynamic_workflow_inputs_to_child_workflow(monkeypatch)+++def test_run_forwards_connected_dynamic_workflow_inputs_to_child_workflow(monkeypatch) -> None:+ workflow_call_tests.test_run_forwards_connected_dynamic_workflow_inputs_to_child_workflow(monkeypatch)+++def test_run_rejects_non_exposed_dynamic_workflow_inputs(monkeypatch) -> None:+ workflow_call_tests.test_run_rejects_non_exposed_dynamic_workflow_inputs(monkeypatch)+++def test_run_fails_call_saved_workflow_when_child_workflow_graph_cannot_be_built(monkeypatch) -> None:+ workflow_call_tests.test_run_fails_call_saved_workflow_when_child_workflow_graph_cannot_be_built(monkeypatch)+++def test_run_fails_call_saved_workflow_with_invalid_selection_without_entering_waiting_state(monkeypatch) -> None:+ workflow_call_tests.test_run_fails_call_saved_workflow_with_invalid_selection_without_entering_waiting_state(+ monkeypatch+ )+++def test_run_fails_call_saved_workflow_when_depth_limit_is_exceeded(monkeypatch) -> None:+ workflow_call_tests.test_run_fails_call_saved_workflow_when_depth_limit_is_exceeded(monkeypatch)diff --git a/tests/app/services/test_workflow_graph_builder.py b/tests/app/services/test_workflow_graph_builder.pynew file mode 100644index 0000000000..071f55e46f--- /dev/null+++ b/tests/app/services/test_workflow_graph_builder.py@@ -0,0 +1,205 @@+import pytest++from invokeai.app.services.shared.graph import Graph+from invokeai.app.services.shared.workflow_graph_builder import (+ UnsupportedWorkflowNodeError,+ build_graph_from_workflow,+)+++def _build_workflow_node(+ node_id: str,+ invocation_type: str,+ inputs: dict[str, object],+ *,+ is_intermediate: bool = False,+ use_cache: bool = True,+):+ return {+ "id": node_id,+ "type": "invocation",+ "position": {"x": 0, "y": 0},+ "data": {+ "id": node_id,+ "type": invocation_type,+ "version": "1.0.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "isOpen": True,+ "isIntermediate": is_intermediate,+ "useCache": use_cache,+ "dynamicInputTemplates": {},+ "inputs": {name: {"value": value} for name, value in inputs.items()},+ },+ }+++def _build_connector_node(node_id: str):+ return {+ "id": node_id,+ "type": "connector",+ "position": {"x": 0, "y": 0},+ "data": {+ "id": node_id,+ "type": "connector",+ "label": "Connector",+ "isOpen": True,+ },+ }+++def _build_workflow(edges: list[dict], nodes: list[dict]):+ return {+ "name": "Child Workflow",+ "author": "Tester",+ "description": "",+ "version": "1.0.0",+ "contact": "",+ "tags": "",+ "notes": "",+ "exposedFields": [],+ "meta": {"version": "1.0.0", "category": "user"},+ "nodes": nodes,+ "edges": edges,+ "form": None,+ }+++def _build_named_return_nodes():+ return [+ _build_workflow_node("return-value-1", "workflow_return_value", {"key": "result", "value": None}),+ _build_workflow_node("return-collect-1", "collect", {"collection": []}),+ _build_workflow_node("return-1", "workflow_return", {"values": []}),+ ]+++def _build_named_return_edges(source: str, source_handle: str):+ return [+ {+ "id": "edge-return-value",+ "type": "default",+ "source": source,+ "sourceHandle": source_handle,+ "target": "return-value-1",+ "targetHandle": "value",+ },+ {+ "id": "edge-return-collect",+ "type": "default",+ "source": "return-value-1",+ "sourceHandle": "value",+ "target": "return-collect-1",+ "targetHandle": "item",+ },+ {+ "id": "edge-return-values",+ "type": "default",+ "source": "return-collect-1",+ "sourceHandle": "collection",+ "target": "return-1",+ "targetHandle": "values",+ },+ ]+++def test_build_graph_from_workflow_converts_invocation_nodes():+ workflow = _build_workflow(+ nodes=[+ _build_workflow_node("add-1", "add", {"a": 1, "b": 2}),+ _build_workflow_node("return-1", "workflow_return", {"values": []}),+ ],+ edges=[],+ )++ graph = build_graph_from_workflow(workflow)++ assert isinstance(graph, Graph)+ assert set(graph.nodes.keys()) == {"add-1", "return-1"}+ assert graph.nodes["add-1"].get_type() == "add"+ assert graph.nodes["add-1"].a == 1+ assert graph.nodes["add-1"].b == 2+ assert graph.nodes["return-1"].get_type() == "workflow_return"+++def test_build_graph_from_workflow_flattens_connector_edges():+ workflow = _build_workflow(+ nodes=[+ _build_workflow_node("add-1", "add", {"a": 1, "b": 2}),+ _build_connector_node("connector-1"),+ _build_workflow_node("add-2", "add", {"a": 999, "b": 3}),+ *_build_named_return_nodes(),+ ],+ edges=[+ {+ "id": "edge-1",+ "type": "default",+ "source": "add-1",+ "sourceHandle": "value",+ "target": "connector-1",+ "targetHandle": "in",+ },+ {+ "id": "edge-2",+ "type": "default",+ "source": "connector-1",+ "sourceHandle": "out",+ "target": "add-2",+ "targetHandle": "a",+ },+ *_build_named_return_edges("add-2", "value"),+ ],+ )++ graph = build_graph_from_workflow(workflow)++ assert len(graph.edges) == 4+ first_edge, second_edge, third_edge, fourth_edge = graph.edges+ assert first_edge.source.node_id == "add-1"+ assert first_edge.source.field == "value"+ assert first_edge.destination.node_id == "add-2"+ assert first_edge.destination.field == "a"+ assert second_edge.source.node_id == "add-2"+ assert second_edge.source.field == "value"+ assert second_edge.destination.node_id == "return-value-1"+ assert second_edge.destination.field == "value"+ assert third_edge.destination.node_id == "return-collect-1"+ assert third_edge.destination.field == "item"+ assert fourth_edge.destination.node_id == "return-1"+ assert fourth_edge.destination.field == "values"+ assert graph.nodes["add-2"].a == 0+ assert graph.nodes["add-2"].b == 3+ assert graph.nodes["return-1"].values == []+++def test_build_graph_from_workflow_rejects_batch_special_nodes_with_clear_error():+ workflow = _build_workflow(+ nodes=[_build_workflow_node("image-batch-1", "image_batch", {"images": []})],+ edges=[],+ )++ with pytest.raises(UnsupportedWorkflowNodeError, match="call_saved_workflow does not yet support batch-special"):+ build_graph_from_workflow(workflow)+++def test_build_graph_from_workflow_rejects_workflows_without_workflow_return():+ workflow = _build_workflow(+ nodes=[_build_workflow_node("add-1", "add", {"a": 1, "b": 2})],+ edges=[],+ )++ with pytest.raises(UnsupportedWorkflowNodeError, match="exactly one workflow_return"):+ build_graph_from_workflow(workflow)+++def test_build_graph_from_workflow_rejects_workflows_with_multiple_workflow_return_nodes():+ workflow = _build_workflow(+ nodes=[+ _build_workflow_node("return-1", "workflow_return", {"values": []}),+ _build_workflow_node("return-2", "workflow_return", {"values": []}),+ ],+ edges=[],+ )++ with pytest.raises(UnsupportedWorkflowNodeError, match="exactly one workflow_return"):+ build_graph_from_workflow(workflow)diff --git a/tests/app/services/workflow_call_test_utils.py b/tests/app/services/workflow_call_test_utils.pynew file mode 100644index 0000000000..cbe94707e9--- /dev/null+++ b/tests/app/services/workflow_call_test_utils.py@@ -0,0 +1,2825 @@+from contextlib import contextmanager+from threading import Event+from types import SimpleNamespace+from typing import Any++import pytest++from invokeai.app.invocations.baseinvocation import BaseInvocation, BaseInvocationOutput, invocation, invocation_output+from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation+from invokeai.app.invocations.fields import InputField, OutputField+from invokeai.app.invocations.logic import IfInvocation+from invokeai.app.invocations.math import AddInvocation+from invokeai.app.invocations.workflow_return import (+ WorkflowReturnGetInvocation,+ WorkflowReturnInvocation,+ WorkflowReturnOutput,+)+from invokeai.app.services.session_processor.session_processor_default import (+ DefaultSessionProcessor,+ DefaultSessionRunner,+)+from invokeai.app.services.session_processor.workflow_call_runtime import (+ WorkflowCallCoordinator,+ WorkflowCallQueueLifecycle,+)+from invokeai.app.services.shared.graph import Graph, GraphExecutionState, WorkflowCallFrame+from invokeai.app.services.workflow_records.workflow_records_common import WorkflowCategory+from tests.dangerously_run_function_in_subprocess import dangerously_run_function_in_subprocess+from tests.test_nodes import create_edge+++@invocation_output("test_interrupt_output")+class InterruptTestOutput(BaseInvocationOutput):+ pass+++@invocation("test_keyboard_interrupt", version="1.0.0")+class KeyboardInterruptInvocation(BaseInvocation):+ def invoke(self, context) -> InterruptTestOutput:+ raise KeyboardInterrupt+++@invocation_output("test_fail_on_integer_output")+class FailOnIntegerOutput(BaseInvocationOutput):+ value: int = OutputField(description="The validated integer")+++@invocation("test_fail_on_integer", version="1.0.0")+class FailOnIntegerInvocation(BaseInvocation):+ value: int = InputField(default=0, description="The integer to validate")++ def invoke(self, context) -> FailOnIntegerOutput:+ if self.value == 2:+ raise ValueError("Refusing integer value 2")+ return FailOnIntegerOutput(value=self.value)+++class _DummyStats:+ @contextmanager+ def collect_stats(self, invocation: BaseInvocation, graph_execution_state_id: str):+ yield++ def log_stats(self, graph_execution_state_id: str) -> None:+ pass++ def reset_stats(self, graph_execution_state_id: str) -> None:+ pass+++class _DummyEvents:+ def __init__(self) -> None:+ self.started: list[tuple[object, object]] = []+ self.completed: list[tuple[object, object, object]] = []+ self.errors: list[tuple[object, object, str, str, str]] = []++ def emit_invocation_started(self, queue_item, invocation) -> None:+ self.started.append((queue_item, invocation))++ def emit_invocation_complete(self, invocation, queue_item, output) -> None:+ self.completed.append((invocation, queue_item, output))++ def emit_invocation_error(self, queue_item, invocation, error_type, error_message, error_traceback) -> None:+ self.errors.append((queue_item, invocation, error_type, error_message, error_traceback))+++class _DummyLogger:+ def debug(self, msg) -> None:+ pass++ def error(self, msg) -> None:+ pass+++class _DummyConfig:+ node_cache_size = 0+ multiuser = False+ max_queue_size = 1000+++class _DummyWorkflowRecords:+ def __init__(self) -> None:+ self.return_invalid_workflow = False+ self.return_batch_special_workflow = False+ self.exposed_field_name = "a"++ @staticmethod+ def _invocation_node(node_id: str, invocation_type: str, inputs: dict[str, Any]) -> dict[str, Any]:+ return {+ "id": node_id,+ "type": "invocation",+ "position": {"x": 0, "y": 0},+ "data": {+ "id": node_id,+ "type": invocation_type,+ "version": "1.0.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "isOpen": True,+ "isIntermediate": False,+ "useCache": True,+ "dynamicInputTemplates": {},+ "inputs": inputs,+ },+ }++ @classmethod+ def _return_value_nodes(+ cls,+ *,+ key: str = "result",+ value_node_id: str = "child-return-value",+ collect_node_id: str = "child-return-collect",+ return_node_id: str = "child-return",+ ) -> list[dict[str, Any]]:+ return [+ cls._invocation_node(+ value_node_id,+ "workflow_return_value",+ {"key": {"value": key}, "value": {"value": None}},+ ),+ cls._invocation_node(collect_node_id, "collect", {"collection": {"value": []}}),+ cls._invocation_node(return_node_id, "workflow_return", {"values": {"value": []}}),+ ]++ @staticmethod+ def _return_value_edges(+ *,+ source: str,+ source_handle: str,+ value_node_id: str = "child-return-value",+ collect_node_id: str = "child-return-collect",+ return_node_id: str = "child-return",+ ) -> list[dict[str, str]]:+ return [+ {+ "id": f"edge-{source}-return-value",+ "type": "default",+ "source": source,+ "sourceHandle": source_handle,+ "target": value_node_id,+ "targetHandle": "value",+ },+ {+ "id": f"edge-{value_node_id}-collect",+ "type": "default",+ "source": value_node_id,+ "sourceHandle": "value",+ "target": collect_node_id,+ "targetHandle": "item",+ },+ {+ "id": f"edge-{collect_node_id}-return",+ "type": "default",+ "source": collect_node_id,+ "sourceHandle": "collection",+ "target": return_node_id,+ "targetHandle": "values",+ },+ ]++ @classmethod+ def _workflow_dump(+ cls,+ *,+ nodes: list[dict[str, Any]],+ edges: list[dict[str, Any]],+ exposed_fields: list[dict[str, str]] | None = None,+ ) -> dict[str, Any]:+ return {+ "name": "Child Workflow",+ "author": "Tester",+ "description": "",+ "version": "1.0.0",+ "contact": "",+ "tags": "",+ "notes": "",+ "exposedFields": exposed_fields or [],+ "meta": {"category": WorkflowCategory.User, "version": "1.0.0"},+ "nodes": nodes,+ "edges": edges,+ "form": None,+ }++ def get(self, workflow_id: str):+ workflow_dump = self._workflow_dump(+ nodes=[+ self._invocation_node(+ "child-add",+ "add",+ {+ "a": {"value": 1},+ "b": {"value": 2},+ },+ ),+ self._invocation_node(+ "child-collection",+ "integer_collection",+ {"collection": {"value": [3]}},+ ),+ *self._return_value_nodes(),+ ],+ edges=self._return_value_edges(source="child-collection", source_handle="collection"),+ exposed_fields=[{"nodeId": "child-add", "fieldName": self.exposed_field_name}],+ )+ if self.return_invalid_workflow:+ workflow_dump = {+ **workflow_dump,+ "edges": [+ {+ "id": "edge-invalid",+ "type": "default",+ "source": "child-add",+ "sourceHandle": "value",+ "target": "child-add",+ "targetHandle": "missing_input",+ }+ ],+ }+ if self.return_batch_special_workflow:+ workflow_dump = {+ **workflow_dump,+ "nodes": [+ self._invocation_node(+ "child-image-batch",+ "image_batch",+ {+ "images": {"value": []},+ },+ )+ ],+ "edges": [],+ }+ if workflow_id == "workflow-dependent":+ workflow_dump = self._workflow_dump(+ nodes=[+ self._invocation_node("child-add-1", "add", {"a": {"value": 1}, "b": {"value": 2}}),+ self._invocation_node("child-add-2", "add", {"a": {"value": 0}, "b": {"value": 4}}),+ self._invocation_node(+ "child-collection",+ "integer_collection",+ {"collection": {"value": [7]}},+ ),+ *self._return_value_nodes(),+ ],+ edges=[+ {+ "id": "edge-dependent",+ "type": "default",+ "source": "child-add-1",+ "sourceHandle": "value",+ "target": "child-add-2",+ "targetHandle": "a",+ },+ *self._return_value_edges(source="child-collection", source_handle="collection"),+ ],+ )+ elif workflow_id == "workflow-if":+ workflow_dump = self._workflow_dump(+ nodes=[+ self._invocation_node("child-bool", "boolean", {"value": {"value": True}}),+ self._invocation_node("child-add", "add", {"a": {"value": 2}, "b": {"value": 3}}),+ self._invocation_node(+ "child-collection",+ "integer_collection",+ {"collection": {"value": [5]}},+ ),+ self._invocation_node(+ "child-if",+ "if",+ {+ "condition": {"value": False},+ "true_input": {"value": None},+ "false_input": {"value": 11},+ },+ ),+ *self._return_value_nodes(),+ ],+ edges=[+ {+ "id": "edge-if-condition",+ "type": "default",+ "source": "child-bool",+ "sourceHandle": "value",+ "target": "child-if",+ "targetHandle": "condition",+ },+ {+ "id": "edge-if-true",+ "type": "default",+ "source": "child-add",+ "sourceHandle": "value",+ "target": "child-if",+ "targetHandle": "true_input",+ },+ *self._return_value_edges(source="child-collection", source_handle="collection"),+ ],+ )+ elif workflow_id == "workflow-nested":+ workflow_dump = self._workflow_dump(+ nodes=[+ self._invocation_node(+ "nested-call",+ "call_saved_workflow",+ {+ "workflow_id": {"value": "workflow-leaf"},+ "workflow_inputs": {"value": {}},+ },+ ),+ self._invocation_node("nested-add", "add", {"a": {"value": 0}, "b": {"value": 4}}),+ self._invocation_node(+ "nested-collection",+ "integer_collection",+ {"collection": {"value": [4]}},+ ),+ *self._return_value_nodes(+ value_node_id="nested-return-value",+ collect_node_id="nested-return-collect",+ return_node_id="nested-return",+ ),+ ],+ edges=self._return_value_edges(+ source="nested-collection",+ source_handle="collection",+ value_node_id="nested-return-value",+ collect_node_id="nested-return-collect",+ return_node_id="nested-return",+ ),+ )+ elif workflow_id == "workflow-leaf":+ workflow_dump = self._workflow_dump(+ nodes=[+ self._invocation_node("leaf-add", "add", {"a": {"value": 5}, "b": {"value": 6}}),+ self._invocation_node(+ "leaf-collection",+ "integer_collection",+ {"collection": {"value": [11]}},+ ),+ *self._return_value_nodes(+ value_node_id="leaf-return-value",+ collect_node_id="leaf-return-collect",+ return_node_id="leaf-return",+ ),+ ],+ edges=self._return_value_edges(+ source="leaf-collection",+ source_handle="collection",+ value_node_id="leaf-return-value",+ collect_node_id="leaf-return-collect",+ return_node_id="leaf-return",+ ),+ )+ elif workflow_id == "workflow-nested-no-return":+ workflow_dump = self._workflow_dump(+ nodes=[+ self._invocation_node(+ "nested-call",+ "call_saved_workflow",+ {+ "workflow_id": {"value": "workflow-no-return"},+ "workflow_inputs": {"value": {}},+ },+ ),+ self._invocation_node(+ "nested-collection",+ "integer_collection",+ {"collection": {"value": [4]}},+ ),+ *self._return_value_nodes(+ value_node_id="nested-return-value",+ collect_node_id="nested-return-collect",+ return_node_id="nested-return",+ ),+ ],+ edges=self._return_value_edges(+ source="nested-collection",+ source_handle="collection",+ value_node_id="nested-return-value",+ collect_node_id="nested-return-collect",+ return_node_id="nested-return",+ ),+ )+ elif workflow_id == "workflow-return":+ workflow_dump = self._workflow_dump(+ nodes=[+ self._invocation_node(+ "child-value",+ "integer_collection",+ {"collection": {"value": [7, 8]}},+ ),+ self._invocation_node(+ "child-return-value",+ "workflow_return_value",+ {"key": {"value": "numbers"}, "value": {"value": None}},+ ),+ self._invocation_node("child-return-collect", "collect", {"collection": {"value": []}}),+ self._invocation_node(+ "child-return",+ "workflow_return",+ {"values": {"value": []}},+ ),+ ],+ edges=[+ {+ "id": "edge-return-value",+ "type": "default",+ "source": "child-value",+ "sourceHandle": "collection",+ "target": "child-return-value",+ "targetHandle": "value",+ },+ {+ "id": "edge-return-collect",+ "type": "default",+ "source": "child-return-value",+ "sourceHandle": "value",+ "target": "child-return-collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-return-values",+ "type": "default",+ "source": "child-return-collect",+ "sourceHandle": "collection",+ "target": "child-return",+ "targetHandle": "values",+ },+ ],+ )+ elif workflow_id == "workflow-no-return":+ workflow_dump = self._workflow_dump(+ nodes=[+ self._invocation_node(+ "child-add",+ "add",+ {+ "a": {"value": 1},+ "b": {"value": 2},+ },+ )+ ],+ edges=[],+ exposed_fields=[{"nodeId": "child-add", "fieldName": self.exposed_field_name}],+ )+ elif workflow_id == "workflow-batch-direct":+ workflow_dump = self._workflow_dump(+ nodes=[+ self._invocation_node(+ "child-batch",+ "integer_batch",+ {+ "integers": {"value": [2, 4, 6]},+ "batch_group_id": {"value": "None"},+ },+ ),+ self._invocation_node("child-int", "integer", {"value": {"value": 0}}),+ self._invocation_node(+ "child-return-value",+ "workflow_return_value",+ {"key": {"value": "number"}, "value": {"value": None}},+ ),+ self._invocation_node("child-return-collect", "collect", {"collection": {"value": []}}),+ self._invocation_node("child-return", "workflow_return", {"values": {"value": []}}),+ ],+ edges=[+ {+ "id": "edge-batch-int",+ "type": "default",+ "source": "child-batch",+ "sourceHandle": "integers",+ "target": "child-int",+ "targetHandle": "value",+ },+ {+ "id": "edge-int-return-value",+ "type": "default",+ "source": "child-int",+ "sourceHandle": "value",+ "target": "child-return-value",+ "targetHandle": "value",+ },+ {+ "id": "edge-return-value-collect",+ "type": "default",+ "source": "child-return-value",+ "sourceHandle": "value",+ "target": "child-return-collect",+ "targetHandle": "item",+ },+ {+ "id": "edge-return-values",+ "type": "default",+ "source": "child-return-collect",+ "sourceHandle": "collection",+ "target": "child-return",+ "targetHandle": "values",+ },+ ],+ )+ elif workflow_id == "workflow-batch-grouped":+ workflow_dump = self._workflow_dump(+ nodes=[+ self._invocation_node(+ "child-batch-a",+ "integer_batch",+ {+ "integers": {"value": [1, 2, 3]},+ "batch_group_id": {"value": "Group 1"},+ },+ ),+ self._invocation_node(+ "child-batch-b",+ "integer_batch",+ {+ "integers": {"value": [10, 20, 30]},+ "batch_group_id": {"value": "Group 1"},+ },+ ),+ self._invocation_node("child-add", "add", {"a": {"value": 0}, "b": {"value": 0}}),+ *self._return_value_nodes(),+ ],+ edges=[+ {+ "id": "edge-group-a",+ "type": "default",+ "source": "child-batch-a",+ "sourceHandle": "integers",+ "target": "child-add",+ "targetHandle": "a",+ },+ {+ "id": "edge-group-b",+ "type": "default",+ "source": "child-batch-b",+ "sourceHandle": "integers",+ "target": "child-add",+ "targetHandle": "b",+ },+ {+ **self._return_value_edges(source="child-add", source_handle="value")[0],+ "id": "edge-group-return-value",+ },+ *self._return_value_edges(source="child-add", source_handle="value")[1:],+ ],+ )+ elif workflow_id == "workflow-batch-cartesian":+ workflow_dump = self._workflow_dump(+ nodes=[+ self._invocation_node(+ "child-batch-a",+ "integer_batch",+ {+ "integers": {"value": [1, 2]},+ "batch_group_id": {"value": "None"},+ },+ ),+ self._invocation_node(+ "child-batch-b",+ "integer_batch",+ {+ "integers": {"value": [10, 20]},+ "batch_group_id": {"value": "None"},+ },+ ),+ self._invocation_node("child-add", "add", {"a": {"value": 0}, "b": {"value": 0}}),+ *self._return_value_nodes(),+ ],+ edges=[+ {+ "id": "edge-cart-a",+ "type": "default",+ "source": "child-batch-a",+ "sourceHandle": "integers",+ "target": "child-add",+ "targetHandle": "a",+ },+ {+ "id": "edge-cart-b",+ "type": "default",+ "source": "child-batch-b",+ "sourceHandle": "integers",+ "target": "child-add",+ "targetHandle": "b",+ },+ *self._return_value_edges(source="child-add", source_handle="value"),+ ],+ )+ elif workflow_id == "workflow-batch-failure":+ workflow_dump = self._workflow_dump(+ nodes=[+ self._invocation_node(+ "child-batch",+ "integer_batch",+ {+ "integers": {"value": [1, 2, 3]},+ "batch_group_id": {"value": "None"},+ },+ ),+ self._invocation_node("child-guard", "test_fail_on_integer", {"value": {"value": 0}}),+ *self._return_value_nodes(),+ ],+ edges=[+ {+ "id": "edge-failure-value",+ "type": "default",+ "source": "child-batch",+ "sourceHandle": "integers",+ "target": "child-guard",+ "targetHandle": "value",+ },+ *self._return_value_edges(source="child-guard", source_handle="value"),+ ],+ )+ elif workflow_id == "workflow-batch-generator":+ workflow_dump = self._workflow_dump(+ nodes=[+ self._invocation_node("child-int", "integer", {"value": {"value": 7}}),+ self._invocation_node(+ "child-batch",+ "integer_batch",+ {+ "integers": {"value": []},+ "batch_group_id": {"value": "None"},+ },+ ),+ self._invocation_node("child-int", "integer", {"value": {"value": 0}}),+ *self._return_value_nodes(),+ ],+ edges=[+ {+ "id": "edge-int-batch",+ "type": "default",+ "source": "child-int",+ "sourceHandle": "value",+ "target": "child-batch",+ "targetHandle": "integers",+ },+ {+ "id": "edge-generator-value",+ "type": "default",+ "source": "child-batch",+ "sourceHandle": "integers",+ "target": "child-int",+ "targetHandle": "value",+ },+ *self._return_value_edges(source="child-int", source_handle="value"),+ ],+ )+ elif workflow_id == "workflow-batch-generator-integer":+ workflow_dump = self._workflow_dump(+ nodes=[+ self._invocation_node(+ "child-generator",+ "integer_generator",+ {+ "generator": {+ "value": {+ "type": "integer_generator_arithmetic_sequence",+ "start": 2,+ "step": 2,+ "count": 3,+ }+ }+ },+ ),+ self._invocation_node(+ "child-batch",+ "integer_batch",+ {+ "integers": {"value": []},+ "batch_group_id": {"value": "None"},+ },+ ),+ self._invocation_node("child-int", "integer", {"value": {"value": 0}}),+ *self._return_value_nodes(),+ ],+ edges=[+ {+ "id": "edge-generator-batch",+ "type": "default",+ "source": "child-generator",+ "sourceHandle": "integers",+ "target": "child-batch",+ "targetHandle": "integers",+ },+ {+ "id": "edge-generator-value",+ "type": "default",+ "source": "child-batch",+ "sourceHandle": "integers",+ "target": "child-int",+ "targetHandle": "value",+ },+ *self._return_value_edges(source="child-int", source_handle="value"),+ ],+ )+ elif workflow_id == "workflow-batch-generator-image":+ workflow_dump = self._workflow_dump(+ nodes=[+ self._invocation_node(+ "child-generator",+ "image_generator",+ {+ "generator": {+ "value": {+ "type": "image_generator_images_from_board",+ "board_id": "board-1",+ "category": "images",+ }+ }+ },+ ),+ self._invocation_node(+ "child-batch",+ "image_batch",+ {+ "images": {"value": []},+ "batch_group_id": {"value": "None"},+ },+ ),+ self._invocation_node("child-image", "image", {"image": {"value": None}}),+ *self._return_value_nodes(),+ ],+ edges=[+ {+ "id": "edge-generator-batch",+ "type": "default",+ "source": "child-generator",+ "sourceHandle": "images",+ "target": "child-batch",+ "targetHandle": "images",+ },+ {+ "id": "edge-generator-value",+ "type": "default",+ "source": "child-batch",+ "sourceHandle": "images",+ "target": "child-image",+ "targetHandle": "image",+ },+ *self._return_value_edges(source="child-image", source_handle="image"),+ ],+ )++ workflow = SimpleNamespace(+ name="Child Workflow",+ author="Tester",+ description="",+ version="1.0.0",+ contact="",+ tags="",+ notes="",+ exposedFields=workflow_dump["exposedFields"],+ meta=SimpleNamespace(category=WorkflowCategory.User),+ form=workflow_dump["form"],+ nodes=workflow_dump["nodes"],+ edges=workflow_dump["edges"],+ )+ workflow.model_dump = lambda: workflow_dump+ return SimpleNamespace(+ user_id="user-1",+ is_public=False,+ workflow=workflow,+ )+++class _DummyUsers:+ def get(self, user_id: str):+ return None+++class _DummyBoardImages:+ def get_all_board_image_names_for_board(self, board_id: str, categories, is_intermediate: bool | None):+ if board_id == "board-1":+ return ["img-a", "img-b"]+ return []+++class _DummyImages:+ def get_dto(self, image_name: str):+ return SimpleNamespace(image_name=image_name, width=64, height=64)+++def _build_runner(monkeypatch: pytest.MonkeyPatch) -> DefaultSessionRunner:+ monkeypatch.setattr(+ "invokeai.app.services.session_processor.session_processor_default.build_invocation_context",+ lambda data, services, is_canceled: None,+ )++ runner = DefaultSessionRunner()+ runner.start(+ services=type(+ "Services",+ (),+ {+ "performance_statistics": _DummyStats(),+ "events": _DummyEvents(),+ "logger": _DummyLogger(),+ "configuration": _DummyConfig(),+ },+ )(),+ cancel_event=Event(),+ )+ return runner+++def _build_workflow_runner(monkeypatch: pytest.MonkeyPatch, session_queue=None):+ monkeypatch.setattr(+ "invokeai.app.services.session_processor.session_processor_default.build_invocation_context",+ lambda data, services, is_canceled: SimpleNamespace(+ _services=services,+ _data=data,+ images=SimpleNamespace(get_dto=services.images.get_dto),+ boards=SimpleNamespace(+ get_all_image_names_for_board=services.board_images.get_all_board_image_names_for_board+ ),+ ),+ )++ events = _DummyEvents()+ runner = DefaultSessionRunner()+ workflow_records = _DummyWorkflowRecords()+ runner.start(+ services=type(+ "Services",+ (),+ {+ "performance_statistics": _DummyStats(),+ "events": events,+ "logger": _DummyLogger(),+ "configuration": _DummyConfig(),+ "workflow_records": workflow_records,+ "users": _DummyUsers(),+ "board_images": _DummyBoardImages(),+ "images": _DummyImages(),+ "session_queue": session_queue or _DummySessionQueue(),+ },+ )(),+ cancel_event=Event(),+ )+ return runner, events, workflow_records+++def _build_queue_item(invocation: BaseInvocation):+ return type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "session_id": "test-session",+ "session": type("Session", (), {"prepared_source_mapping": {invocation.id: invocation.id}})(),+ },+ )()+++class _DummySessionQueue:+ def __init__(self) -> None:+ self.items: dict[int, object] = {}+ self.next_item_id = 100+ self.completed_item_ids: list[int] = []+ self.session_updates: list[tuple[int, object]] = []+ self.failed_item_ids: list[int] = []+ self.waiting_item_ids: list[int] = []+ self.resumed_item_ids: list[int] = []+ self.enqueued_child_item_ids: list[int] = []+ self.canceled_item_ids: list[int] = []+ self.deleted_item_ids: list[int] = []+ self.pending_count = 0+ self.fail_enqueue_after: int | None = None++ def add_queue_item(self, queue_item):+ self.items[queue_item.item_id] = queue_item+ return queue_item++ def _ensure_queue_item(self, item_id: int, session):+ queue_item = self.items.get(item_id)+ if queue_item is None:+ queue_item = SimpleNamespace(+ item_id=item_id,+ status="in_progress",+ session=session,+ session_id=getattr(session, "id", f"session-{item_id}"),+ user_id="user-1",+ queue_id="default",+ batch_id="batch-1",+ parent_item_id=None,+ parent_session_id=None,+ workflow_call_id=None,+ root_item_id=None,+ workflow_call_depth=None,+ )+ self.items[item_id] = queue_item+ return queue_item++ def get_queue_item(self, item_id: int):+ return self.items[item_id]++ def set_queue_item_session(self, item_id: int, session):+ queue_item = self._ensure_queue_item(item_id, session)+ queue_item.session = session+ self.session_updates.append((item_id, session))+ return queue_item++ def suspend_queue_item(self, item_id: int):+ queue_item = self._ensure_queue_item(item_id, None)+ queue_item.status = "waiting"+ self.waiting_item_ids.append(item_id)+ return queue_item++ def resume_queue_item(self, item_id: int):+ queue_item = self._ensure_queue_item(item_id, None)+ queue_item.status = "pending"+ self.resumed_item_ids.append(item_id)+ return queue_item++ def complete_queue_item(self, item_id: int):+ queue_item = self._ensure_queue_item(item_id, None)+ queue_item.status = "completed"+ self.completed_item_ids.append(item_id)+ return queue_item++ def fail_queue_item(self, item_id: int, error_type: str, error_message: str, error_traceback: str):+ queue_item = self._ensure_queue_item(item_id, None)+ queue_item.status = "failed"+ queue_item.error_type = error_type+ queue_item.error_message = error_message+ queue_item.error_traceback = error_traceback+ self.failed_item_ids.append(item_id)+ return queue_item++ def cancel_workflow_call_children(+ self, workflow_call_id: str, exclude_item_ids: set[int] | None = None+ ) -> list[int]:+ exclude_item_ids = exclude_item_ids or set()+ canceled_item_ids: list[int] = []+ for item_id, queue_item in self.items.items():+ if item_id in exclude_item_ids:+ continue+ if getattr(queue_item, "workflow_call_id", None) != workflow_call_id:+ continue+ if queue_item.status in {"completed", "failed", "canceled"}:+ continue+ queue_item.status = "canceled"+ canceled_item_ids.append(item_id)+ self.canceled_item_ids.append(item_id)+ return canceled_item_ids++ def enqueue_workflow_call_child(self, parent_queue_item, child_session, field_values=None):+ if self.fail_enqueue_after is not None and len(self.enqueued_child_item_ids) >= self.fail_enqueue_after:+ raise RuntimeError("Injected child enqueue failure")+ workflow_call_execution = parent_queue_item.session.waiting_workflow_call_execution+ item_id = self.next_item_id+ self.next_item_id += 1+ child_queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": item_id,+ "status": "pending",+ "session": child_session,+ "session_id": child_session.id,+ "user_id": getattr(parent_queue_item, "user_id", "user-1"),+ "queue_id": getattr(parent_queue_item, "queue_id", "default"),+ "batch_id": getattr(parent_queue_item, "batch_id", "batch-1"),+ "origin": getattr(parent_queue_item, "origin", None),+ "destination": getattr(parent_queue_item, "destination", None),+ "priority": getattr(parent_queue_item, "priority", 0),+ "field_values": field_values,+ "workflow_call_id": workflow_call_execution.id if workflow_call_execution is not None else None,+ "parent_item_id": parent_queue_item.item_id,+ "parent_session_id": parent_queue_item.session_id,+ "root_item_id": getattr(parent_queue_item, "root_item_id", None) or parent_queue_item.item_id,+ "workflow_call_depth": (workflow_call_execution.depth if workflow_call_execution is not None else None),+ "workflow": None,+ },+ )()+ self.add_queue_item(child_queue_item)+ self.enqueued_child_item_ids.append(item_id)+ return child_queue_item++ def delete_queue_items_by_id(self, item_ids: list[int]):+ for item_id in item_ids:+ if item_id in self.items:+ del self.items[item_id]+ self.deleted_item_ids.append(item_id)++ def get_queue_status(self, queue_id: str):+ return SimpleNamespace(pending=self.pending_count)++ def dequeue(self):+ pending_item_ids = sorted(item_id for item_id, item in self.items.items() if item.status == "pending")+ if not pending_item_ids:+ return None+ queue_item = self.items[pending_item_ids[0]]+ queue_item.status = "in_progress"+ return queue_item+++def _drain_workflow_call_queue(+ lifecycle: WorkflowCallQueueLifecycle, session_queue: _DummySessionQueue, queue_item+) -> None:+ session_queue.add_queue_item(queue_item)+ lifecycle.run_queue_item(queue_item)+ while True:+ next_queue_item = session_queue.dequeue()+ if next_queue_item is None:+ return+ lifecycle.run_queue_item(next_queue_item)+++class _WaitingSession:+ def __init__(self) -> None:+ self.id = "session-id"+ self.prepared_source_mapping = {}+ self._next_calls = 0+ self.waiting_workflow_call = WorkflowCallFrame(+ prepared_call_node_id="prepared-call",+ source_call_node_id="source-call",+ workflow_id="workflow-a",+ depth=1,+ )++ def next(self):+ self._next_calls += 1+ return None++ def is_complete(self) -> bool:+ return False+++class _WorkflowCallBoundarySession:+ def __init__(self, invocation_id: str) -> None:+ self.id = "session-id"+ self.prepared_source_mapping = {invocation_id: "source-call"}+ self.completed: list[tuple[str, object]] = []+ self.frames: list[WorkflowCallFrame] = []+ self.waiting: WorkflowCallFrame | None = None+ self.waiting_workflow_call_execution = None+ self.waiting_workflow_call_child_session = None+ self.errors: dict[str, str] = {}+ self.execution_graph = Graph()+ self.results = {}++ def build_workflow_call_frame(self, exec_node_id: str, workflow_id: str) -> WorkflowCallFrame:+ frame = WorkflowCallFrame(+ prepared_call_node_id=exec_node_id,+ source_call_node_id=self.prepared_source_mapping[exec_node_id],+ workflow_id=workflow_id,+ depth=1,+ )+ self.frames.append(frame)+ return frame++ def begin_waiting_on_workflow_call(self, frame: WorkflowCallFrame) -> None:+ self.waiting = frame++ def create_child_workflow_execution_state(self, graph: Graph, frame: WorkflowCallFrame):+ return GraphExecutionState(graph=graph, workflow_call_stack=[frame])++ def attach_waiting_workflow_call_child_session(self, child_session: GraphExecutionState) -> None:+ self.waiting_workflow_call_execution = SimpleNamespace(+ id="workflow-call-1", depth=1, expected_child_count=1, child_item_ids=[]+ )+ self.waiting_workflow_call_child_session = child_session++ def attach_waiting_workflow_call_child_sessions(self, child_sessions: list[GraphExecutionState]) -> None:+ self.waiting_workflow_call_execution = SimpleNamespace(+ id="workflow-call-1", depth=1, expected_child_count=len(child_sessions), child_item_ids=[]+ )+ self.waiting_workflow_call_child_session = child_sessions[0] if len(child_sessions) == 1 else None++ def set_waiting_workflow_call_child_item_ids(self, child_item_ids: list[int]) -> None:+ if self.waiting_workflow_call_execution is None:+ raise ValueError("Execution state is not waiting on a workflow call.")+ if len(child_item_ids) != self.waiting_workflow_call_execution.expected_child_count:+ raise ValueError("Workflow call child item count does not match expected child count.")+ self.waiting_workflow_call_execution.child_item_ids = list(child_item_ids)++ def end_waiting_on_workflow_call(self, status: str = "completed", error_message: str | None = None) -> None:+ self.waiting = None+ self.waiting_workflow_call_child_session = None++ def complete(self, node_id: str, output) -> None:+ self.completed.append((node_id, output))++ def is_waiting_on_workflow_call(self) -> bool:+ return self.waiting is not None++ def set_node_error(self, node_id: str, error: str) -> None:+ self.errors[node_id] = error+++def test_run_node_propagates_keyboard_interrupt(monkeypatch: pytest.MonkeyPatch) -> None:+ runner = _build_runner(monkeypatch)+ invocation = KeyboardInterruptInvocation(id="node")+ queue_item = _build_queue_item(invocation)++ with pytest.raises(KeyboardInterrupt):+ runner.run_node(invocation=invocation, queue_item=queue_item)+++def test_run_node_does_not_swallow_sigint_in_subprocess() -> None:+ def test_func():+ import os+ import signal+ import threading+ import time+ from contextlib import contextmanager+ from threading import Event++ import invokeai.app.services.session_processor.session_processor_default as session_processor_default+ from invokeai.app.invocations.baseinvocation import (+ BaseInvocation,+ BaseInvocationOutput,+ invocation,+ invocation_output,+ )+ from invokeai.app.services.session_processor.session_processor_default import DefaultSessionRunner++ @invocation_output("test_interrupt_output_subprocess")+ class InterruptTestOutput(BaseInvocationOutput):+ pass++ @invocation("test_sigint_during_node", version="1.0.0")+ class SigIntDuringNodeInvocation(BaseInvocation):+ def invoke(self, context) -> InterruptTestOutput:+ timer = threading.Thread(target=lambda: (time.sleep(0.1), os.kill(os.getpid(), signal.SIGINT)))+ timer.daemon = True+ timer.start()+ time.sleep(5)+ return InterruptTestOutput()++ class DummyStats:+ @contextmanager+ def collect_stats(self, invocation: BaseInvocation, graph_execution_state_id: str):+ yield++ class DummyEvents:+ def emit_invocation_started(self, queue_item, invocation) -> None:+ pass++ def emit_invocation_complete(self, invocation, queue_item, output) -> None:+ pass++ def emit_invocation_error(self, queue_item, invocation, error_type, error_message, error_traceback) -> None:+ pass++ class DummyLogger:+ def debug(self, msg) -> None:+ pass++ def error(self, msg) -> None:+ pass++ class DummyConfig:+ node_cache_size = 0++ session_processor_default.build_invocation_context = lambda data, services, is_canceled: None++ runner = DefaultSessionRunner()+ runner.start(+ services=type(+ "Services",+ (),+ {+ "performance_statistics": DummyStats(),+ "events": DummyEvents(),+ "logger": DummyLogger(),+ "configuration": DummyConfig(),+ },+ )(),+ cancel_event=Event(),+ )++ invocation = SigIntDuringNodeInvocation(id="node")+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "session_id": "test-session",+ "session": type("Session", (), {"prepared_source_mapping": {invocation.id: invocation.id}})(),+ },+ )()++ runner.run_node(invocation=invocation, queue_item=queue_item)+ print("swallowed")++ stdout, stderr, returncode = dangerously_run_function_in_subprocess(test_func)++ assert stdout.strip() == ""+ assert returncode != 0, stderr+++def test_on_after_run_session_does_not_complete_incomplete_session(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()++ runner = DefaultSessionRunner()+ runner.start(+ services=type(+ "Services",+ (),+ {+ "performance_statistics": _DummyStats(),+ "events": _DummyEvents(),+ "logger": _DummyLogger(),+ "configuration": _DummyConfig(),+ "session_queue": session_queue,+ },+ )(),+ cancel_event=Event(),+ )++ session = type("Session", (), {"id": "session-id", "is_complete": lambda self: False})()+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ },+ )()+ session_queue.add_queue_item(queue_item)++ runner._on_after_run_session(queue_item=queue_item)++ assert session_queue.session_updates == [(1, session)]+ assert session_queue.completed_item_ids == []+++def test_run_node_enters_waiting_state_without_executing_child_inline(monkeypatch: pytest.MonkeyPatch) -> None:+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch)+ invocation = CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a")+ session = _WorkflowCallBoundarySession(invocation.id)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "session_id": "test-session",+ "user_id": "user-1",+ "status": "in_progress",+ "session": session,+ "queue_id": "default",+ "batch_id": "batch-1",+ "priority": 0,+ "origin": None,+ "destination": None,+ "root_item_id": None,+ },+ )()++ monkeypatch.setattr(+ CallSavedWorkflowInvocation,+ "invoke_internal",+ lambda self, context, services: (_ for _ in ()).throw(AssertionError("invoke_internal should not be called")),+ )++ runner.run_node(invocation=invocation, queue_item=queue_item)++ assert len(session.frames) == 1+ assert session.waiting == session.frames[0]+ assert session.frames[0].prepared_call_node_id == invocation.id+ assert session.frames[0].workflow_id == "workflow-a"+ assert session.waiting_workflow_call_child_session is not None+ assert session.completed == []+ assert len(events.started) == 1+ assert events.completed == []+ assert events.errors == []+++def test_run_node_fails_cleanly_for_invalid_batch_child_workflow(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ runner, events, workflow_records = _build_workflow_runner(monkeypatch)+ workflow_records.return_batch_special_workflow = True+ invocation = CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a")+ session = _WorkflowCallBoundarySession(invocation.id)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "session_id": "test-session",+ "user_id": "user-1",+ "status": "in_progress",+ "session": session,+ "queue_id": "default",+ "batch_id": "batch-1",+ "priority": 0,+ "origin": None,+ "destination": None,+ "root_item_id": None,+ },+ )()+ runner._services.session_queue.add_queue_item(queue_item)++ runner.run_node(invocation=invocation, queue_item=queue_item)++ assert session.waiting is None+ assert session.waiting_workflow_call_child_session is None+ assert session.completed == []+ assert len(events.started) == 1+ assert events.completed == []+ assert len(events.errors) == 1+ _queue_item, _invocation, error_type, error_message, _traceback = events.errors[0]+ assert error_type == "UnsupportedWorkflowNodeError"+ assert "must provide at least one batch item" in error_message+++def test_run_persists_waiting_session_without_completing_queue_item(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner = DefaultSessionRunner()+ runner.start(+ services=type(+ "Services",+ (),+ {+ "performance_statistics": _DummyStats(),+ "events": _DummyEvents(),+ "logger": _DummyLogger(),+ "configuration": _DummyConfig(),+ "session_queue": session_queue,+ },+ )(),+ cancel_event=Event(),+ )++ session = _WaitingSession()+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ },+ )()+ session_queue.add_queue_item(queue_item)++ runner.run(queue_item=queue_item)++ assert session._next_calls == 1+ assert session_queue.session_updates == [(1, session)]+ assert session_queue.completed_item_ids == []+++def test_workflow_call_coordinator_suspends_parent_and_enqueues_child_queue_item(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))+ graph.add_node(WorkflowReturnGetInvocation(id="get-return", key="result"))+ graph.add_node(IfInvocation(id="downstream-if", condition=True, false_input=0))+ graph.add_edge(create_edge("call-node", "values", "get-return", "values"))+ graph.add_edge(create_edge("get-return", "value", "downstream-if", "true_input"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ session_queue.add_queue_item(queue_item)+ runner.run(queue_item)++ assert session.is_waiting_on_workflow_call()+ assert session_queue.waiting_item_ids == [1]+ assert session_queue.enqueued_child_item_ids == [100]+ child_queue_item = session_queue.get_queue_item(100)+ assert child_queue_item.status == "pending"+ assert child_queue_item.parent_item_id == queue_item.item_id+ assert child_queue_item.workflow_call_id == session.waiting_workflow_call_execution.id+ assert "downstream-if" not in session.executed+ assert events.completed == []+ child_started_queue_items = [+ child_queue_item+ for child_queue_item, invocation in events.started+ if invocation.get_type() != "call_saved_workflow" and child_queue_item.session_id != queue_item.session_id+ ]+ assert child_started_queue_items == []+ assert session.workflow_call_history == []+ assert events.errors == []+++def test_workflow_call_queue_lifecycle_leaves_non_call_workflows_on_normal_execution_path(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ lifecycle = WorkflowCallQueueLifecycle(runner)++ graph = Graph()+ graph.add_node(AddInvocation(id="source-add", a=2, b=3))+ graph.add_node(IfInvocation(id="downstream-if", condition=True, false_input=0))+ graph.add_edge(create_edge("source-add", "value", "downstream-if", "true_input"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ session_queue.add_queue_item(queue_item)+ lifecycle.run_queue_item(queue_item)++ assert not session.is_waiting_on_workflow_call()+ assert "source-add" in session.executed+ assert "downstream-if" in session.executed+ assert session_queue.enqueued_child_item_ids == []+ assert session_queue.waiting_item_ids == []+ assert session_queue.resumed_item_ids == []+ assert session_queue.completed_item_ids == [1]+ assert [invocation.get_type() for _queue_item, invocation in events.started] == ["add", "if"]+ assert [invocation.get_type() for invocation, _queue_item, _output in events.completed] == ["add", "if"]+ assert events.errors == []+++def test_default_session_processor_uses_runner_workflow_call_lifecycle(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, _events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ queue_item = SimpleNamespace(item_id=1, session_id="session-id")+ calls: list[object] = []+ runner.workflow_call_queue_lifecycle.run_queue_item = calls.append++ processor.workflow_call_queue_lifecycle.run_queue_item(queue_item)++ assert calls == [queue_item]+++def test_workflow_call_queue_lifecycle_resumes_parent_from_completed_child(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ assert session_queue.completed_item_ids == [100, 1]+ assert session_queue.resumed_item_ids == []+ parent_outputs = [+ output for invocation, _queue_item, output in events.completed if invocation.get_type() == "call_saved_workflow"+ ]+ assert len(parent_outputs) == 1+ assert parent_outputs[0].values == {"result": [3]}+++def test_workflow_call_coordinator_cleans_up_enqueued_children_when_boundary_setup_fails(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_queue = _DummySessionQueue()+ session_queue.fail_enqueue_after = 1+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ coordinator = WorkflowCallCoordinator(runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-batch-direct"))+ session = GraphExecutionState(graph=graph)+ invocation = session.next()+ assert isinstance(invocation, CallSavedWorkflowInvocation)+ queue_item = SimpleNamespace(+ item_id=1,+ status="in_progress",+ session=session,+ session_id="session-id",+ user_id="user-1",+ queue_id="default",+ batch_id="batch-1",+ priority=0,+ origin=None,+ destination=None,+ root_item_id=None,+ )+ session_queue.add_queue_item(queue_item)+ workflow_record = runner._services.workflow_records.get(invocation.workflow_id)++ with pytest.raises(RuntimeError, match="Injected child enqueue failure"):+ coordinator.begin_workflow_call_boundary(invocation, queue_item, workflow_record)++ assert session_queue.enqueued_child_item_ids == [100]+ assert session_queue.deleted_item_ids == [100]+ assert session_queue.items[1].status == "in_progress"+ assert session.waiting_workflow_call is None+ assert session.waiting_workflow_call_execution is None+ assert session.waiting_workflow_call_child_session is None+ assert events.completed == []+ assert events.errors == []+++def test_workflow_call_coordinator_rejects_child_expansion_that_exceeds_remaining_queue_capacity(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_queue = _DummySessionQueue()+ session_queue.pending_count = 999+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ runner._services.configuration.max_queue_size = 1000+ coordinator = WorkflowCallCoordinator(runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-batch-direct"))+ session = GraphExecutionState(graph=graph)+ invocation = session.next()+ assert isinstance(invocation, CallSavedWorkflowInvocation)+ queue_item = SimpleNamespace(+ item_id=1,+ status="in_progress",+ session=session,+ session_id="session-id",+ user_id="user-1",+ queue_id="default",+ batch_id="batch-1",+ priority=0,+ origin=None,+ destination=None,+ root_item_id=None,+ )+ session_queue.add_queue_item(queue_item)+ workflow_record = runner._services.workflow_records.get(invocation.workflow_id)++ with pytest.raises(ValueError, match="remaining queue capacity"):+ coordinator.begin_workflow_call_boundary(invocation, queue_item, workflow_record)++ assert session_queue.enqueued_child_item_ids == []+ assert session_queue.waiting_item_ids == []+ assert session.waiting_workflow_call is None+ assert session.waiting_workflow_call_execution is None+ assert events.completed == []+ assert events.errors == []+++def test_workflow_call_coordinator_builds_child_queue_item_with_relationship_metadata(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_queue = _DummySessionQueue()+ runner, _events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ coordinator = WorkflowCallCoordinator(runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))+ parent_session = GraphExecutionState(graph=graph)+ invocation = parent_session.next()+ assert isinstance(invocation, CallSavedWorkflowInvocation)++ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 42,+ "status": "in_progress",+ "session": parent_session,+ "session_id": parent_session.id,+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ "priority": 0,+ "origin": None,+ "destination": None,+ "workflow_call_id": None,+ "parent_item_id": None,+ "parent_session_id": None,+ "root_item_id": None,+ "workflow_call_depth": None,+ },+ )()++ workflow_record = runner._services.workflow_records.get(invocation.workflow_id)+ coordinator.begin_workflow_call_boundary(invocation, queue_item, workflow_record)+ child_session = parent_session.waiting_workflow_call_child_session+ assert child_session is not None++ child_queue_item = coordinator.build_child_queue_item(queue_item, child_session)++ assert child_queue_item.workflow_call_id == parent_session.waiting_workflow_call_execution.id+ assert child_queue_item.parent_item_id == queue_item.item_id+ assert child_queue_item.parent_session_id == queue_item.session_id+ assert child_queue_item.root_item_id == queue_item.item_id+ assert child_queue_item.workflow_call_depth == 1+ assert child_queue_item.session_id == child_session.id+++def test_run_completes_call_saved_workflow_and_runs_downstream_nodes(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))+ graph.add_node(WorkflowReturnGetInvocation(id="get-return", key="result"))+ graph.add_node(IfInvocation(id="downstream-if", condition=True, false_input=0))+ graph.add_edge(create_edge("call-node", "values", "get-return", "values"))+ graph.add_edge(create_edge("get-return", "value", "downstream-if", "true_input"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ assert not session.is_waiting_on_workflow_call()+ assert "downstream-if" in session.executed+ assert [invocation.get_type() for _queue_item, invocation in events.started] == [+ "call_saved_workflow",+ "add",+ "integer_collection",+ "workflow_return_value",+ "collect",+ "workflow_return",+ "workflow_return_get",+ "if",+ ]+ assert len(events.completed) == 8+ parent_outputs = [+ output for invocation, _queue_item, output in events.completed if invocation.get_type() == "call_saved_workflow"+ ]+ downstream_outputs = [+ output for invocation, _queue_item, output in events.completed if invocation.get_type() == "if"+ ]+ assert len(parent_outputs) == 1+ assert parent_outputs[0].values == {"result": [3]}+ assert len(downstream_outputs) == 1+ assert downstream_outputs[0].value == [3]+ assert events.errors == []+ assert session_queue.completed_item_ids == [100, 1]+ assert session_queue.waiting_item_ids == [1]+ assert session_queue.resumed_item_ids == [1]+++def test_run_completes_parent_queue_item_when_return_get_is_terminal(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))+ graph.add_node(WorkflowReturnGetInvocation(id="get-return", key="result"))+ graph.add_edge(create_edge("call-node", "values", "get-return", "values"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ assert not session.is_waiting_on_workflow_call()+ assert session.is_complete()+ assert session_queue.get_queue_item(1).status == "completed"+ assert session_queue.completed_item_ids == [100, 1]+ assert session_queue.waiting_item_ids == [1]+ assert session_queue.resumed_item_ids == [1]+ assert [invocation.get_type() for _queue_item, invocation in events.started] == [+ "call_saved_workflow",+ "add",+ "integer_collection",+ "workflow_return_value",+ "collect",+ "workflow_return",+ "workflow_return_get",+ ]+ assert events.errors == []+++def test_run_node_records_child_execution_state_for_call_saved_workflow(monkeypatch: pytest.MonkeyPatch) -> None:+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))+ session = GraphExecutionState(graph=graph)+ invocation = session.next()+ assert invocation is not None++ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "session_id": "session-id",+ "user_id": "user-1",+ "status": "in_progress",+ "session": session,+ "queue_id": "default",+ "batch_id": "batch-1",+ "priority": 0,+ "origin": None,+ "destination": None,+ "root_item_id": None,+ },+ )()++ runner.run_node(invocation=invocation, queue_item=queue_item)++ assert session.is_waiting_on_workflow_call()+ assert session.waiting_workflow_call_child_session is not None+ assert invocation.id not in session.executed+ assert len(events.started) == 1+ assert events.completed == []+ assert events.errors == []+++def test_run_executes_child_workflow_and_completes_parent_queue_item(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ assert not session.is_waiting_on_workflow_call()+ assert session_queue.completed_item_ids == [100, 1]+ assert "call-node" in session.executed+ child_add_outputs = [+ output+ for invocation, child_queue_item, output in events.completed+ if invocation.get_type() == "add"+ and child_queue_item.session.prepared_source_mapping[invocation.id] == "child-add"+ ]+ assert len(child_add_outputs) == 1+ assert child_add_outputs[0].value == 3+ parent_outputs = [+ output for invocation, _queue_item, output in events.completed if invocation.get_type() == "call_saved_workflow"+ ]+ assert len(parent_outputs) == 1+ assert parent_outputs[0].values == {"result": [3]}+ assert events.errors == []+++def test_run_completes_call_saved_workflow_with_child_return_collection(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-return"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ child_return_outputs = [+ output+ for invocation, child_queue_item, output in events.completed+ if child_queue_item.session is not session+ and child_queue_item.session.prepared_source_mapping[invocation.id] == "child-return"+ ]+ parent_outputs = [+ output for invocation, _queue_item, output in events.completed if invocation.get_type() == "call_saved_workflow"+ ]++ assert len(child_return_outputs) == 1+ assert child_return_outputs[0].values == {"numbers": [7, 8]}+ assert len(parent_outputs) == 1+ assert parent_outputs[0].values == {"numbers": [7, 8]}+ assert session_queue.completed_item_ids == [100, 1]+ assert events.errors == []+++def test_run_extracts_named_call_saved_workflow_return(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-return"))+ graph.add_node(WorkflowReturnGetInvocation(id="get-return", key="numbers"))+ graph.add_edge(create_edge("call-node", "values", "get-return", "values"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ extracted_outputs = [+ output for invocation, _queue_item, output in events.completed if invocation.get_type() == "workflow_return_get"+ ]++ assert len(extracted_outputs) == 1+ assert extracted_outputs[0].value == [7, 8]+ assert events.errors == []+++def test_run_completes_call_saved_workflow_with_batched_child_returns(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-batch-direct"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ parent_outputs = [+ output for invocation, _queue_item, output in events.completed if invocation.get_type() == "call_saved_workflow"+ ]++ assert session_queue.enqueued_child_item_ids == [100, 101, 102]+ assert [+ [+ (field_value.node_path, field_value.field_name, field_value.value)+ for field_value in session_queue.items[item_id].field_values+ ]+ for item_id in session_queue.enqueued_child_item_ids+ ] == [[("child-int", "value", 2)], [("child-int", "value", 4)], [("child-int", "value", 6)]]+ assert session_queue.completed_item_ids == [100, 101, 102, 1]+ assert len(parent_outputs) == 1+ assert parent_outputs[0].values == {"number": [2, 4, 6]}+ assert events.errors == []+++def test_workflow_call_batch_aggregation_rejects_inconsistent_return_keys() -> None:+ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))+ session = GraphExecutionState(graph=graph)+ session.begin_waiting_on_workflow_call(+ WorkflowCallFrame(+ prepared_call_node_id="call-node",+ source_call_node_id="call-node",+ workflow_id="workflow-a",+ depth=1,+ )+ )+ session.waiting_workflow_call_execution.expected_child_count = 2++ session.record_waiting_workflow_call_child_completion(100, {"image": "image-a"})++ with pytest.raises(ValueError, match="returned different workflow return keys"):+ session.record_waiting_workflow_call_child_completion(101, {"mask": "mask-a"})+++def test_workflow_call_return_aggregation_failure_cancels_remaining_siblings(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ lifecycle = WorkflowCallQueueLifecycle(runner)++ parent_graph = Graph()+ parent_graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))+ parent_session = GraphExecutionState(graph=parent_graph)+ parent_invocation = parent_session.next()+ assert isinstance(parent_invocation, CallSavedWorkflowInvocation)+ parent_session.begin_waiting_on_workflow_call(+ parent_session.build_workflow_call_frame(parent_invocation.id, "workflow-a")+ )+ parent_session.waiting_workflow_call_execution.expected_child_count = 2+ parent_session.record_waiting_workflow_call_child_completion(100, {"image": "image-a"})+ workflow_call_id = parent_session.waiting_workflow_call_execution.id+ parent_queue_item = SimpleNamespace(+ item_id=1,+ status="waiting",+ session=parent_session,+ session_id=parent_session.id,+ user_id="user-1",+ queue_id="default",+ batch_id="batch-1",+ )+ session_queue.add_queue_item(parent_queue_item)++ child_graph = Graph()+ child_graph.add_node(WorkflowReturnInvocation(id="return"))+ child_session = GraphExecutionState(graph=child_graph)+ return_invocation = child_session.next()+ assert isinstance(return_invocation, WorkflowReturnInvocation)+ child_session.complete(return_invocation.id, WorkflowReturnOutput(values={"mask": "mask-a"}))+ child_queue_item = SimpleNamespace(+ item_id=101,+ status="completed",+ session=child_session,+ session_id=child_session.id,+ parent_item_id=1,+ workflow_call_id=workflow_call_id,+ )+ sibling_queue_item = SimpleNamespace(+ item_id=102,+ status="pending",+ session=GraphExecutionState(graph=Graph()),+ session_id="sibling-session",+ parent_item_id=1,+ workflow_call_id=workflow_call_id,+ )+ session_queue.add_queue_item(child_queue_item)+ session_queue.add_queue_item(sibling_queue_item)++ lifecycle._resume_parent_from_completed_child(child_queue_item)++ assert session_queue.failed_item_ids == [1]+ assert session_queue.canceled_item_ids == [102]+ assert len(events.errors) == 1+ assert "different workflow return keys" in events.errors[0][3]+++def test_run_zips_grouped_batch_children(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-batch-grouped"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ parent_outputs = [+ output for invocation, _queue_item, output in events.completed if invocation.get_type() == "call_saved_workflow"+ ]++ assert session_queue.enqueued_child_item_ids == [100, 101, 102]+ assert len(parent_outputs) == 1+ assert parent_outputs[0].values == {"result": [11, 22, 33]}+++def test_run_expands_ungrouped_batch_children_as_cartesian_product(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-batch-cartesian"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ parent_outputs = [+ output for invocation, _queue_item, output in events.completed if invocation.get_type() == "call_saved_workflow"+ ]++ assert session_queue.enqueued_child_item_ids == [100, 101, 102, 103]+ assert len(parent_outputs) == 1+ assert parent_outputs[0].values == {"result": [11, 21, 12, 22]}+++def test_run_fails_batched_child_workflow_and_cancels_remaining_siblings(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-batch-failure"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ assert session.has_error()+ assert session_queue.failed_item_ids == [101, 1]+ assert session_queue.canceled_item_ids == [102]+ assert len(events.errors) == 2+ assert "Refusing integer value 2" in events.errors[0][3]+++def test_run_supports_generator_backed_integer_batched_child_workflow(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-batch-generator-integer"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ parent_outputs = [+ output for invocation, _queue_item, output in events.completed if invocation.get_type() == "call_saved_workflow"+ ]++ assert session_queue.enqueued_child_item_ids == [100, 101, 102]+ assert len(parent_outputs) == 1+ assert parent_outputs[0].values == {"result": [2, 4, 6]}+ assert events.errors == []+++def test_run_supports_generator_backed_image_batched_child_workflow(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-batch-generator-image"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ parent_outputs = [+ output for invocation, _queue_item, output in events.completed if invocation.get_type() == "call_saved_workflow"+ ]++ assert session_queue.enqueued_child_item_ids == [100, 101]+ assert len(parent_outputs) == 1+ assert [item.image_name for item in parent_outputs[0].values["result"]] == ["img-a", "img-b"]+ assert events.errors == []+++def test_run_rejects_non_generator_connected_batched_child_workflow(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-batch-generator"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ session_queue.add_queue_item(queue_item)+ runner.run(queue_item=queue_item)++ assert session.has_error()+ assert session_queue.enqueued_child_item_ids == []+ assert session_queue.failed_item_ids == [1]+ assert len(events.errors) == 1+ assert "connected batch child workflow inputs" in events.errors[0][3]+++def test_run_fails_call_saved_workflow_when_child_has_no_workflow_return(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-no-return"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ session_queue.add_queue_item(queue_item)+ runner.run(queue_item=queue_item)++ assert not session.is_waiting_on_workflow_call()+ assert session.waiting_workflow_call_child_session is None+ assert session.has_error()+ assert session.workflow_call_history == []+ assert session_queue.enqueued_child_item_ids == []+ assert session_queue.waiting_item_ids == []+ assert session_queue.completed_item_ids == []+ assert session_queue.failed_item_ids == [1]+ assert len(events.errors) == 1+ assert "workflow_return" in events.errors[0][3]+++def test_run_respects_child_dependency_readiness(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-dependent"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ child_completions = [+ (child_queue_item.session.prepared_source_mapping[invocation.id], output)+ for invocation, child_queue_item, output in events.completed+ if child_queue_item.session is not session and invocation.get_type() == "add"+ ]+ assert [source_id for source_id, _output in child_completions] == ["child-add-1", "child-add-2"]+ assert child_completions[0][1].value == 3+ assert child_completions[1][1].value == 7+ assert session_queue.completed_item_ids == [100, 1]+ assert events.errors == []+++def test_run_respects_child_if_branching(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-if"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ child_if_outputs = [+ output+ for invocation, child_queue_item, output in events.completed+ if child_queue_item.session is not session and invocation.get_type() == "if"+ ]+ assert len(child_if_outputs) == 1+ assert child_if_outputs[0].value == 5+ assert session_queue.completed_item_ids == [100, 1]+ assert events.errors == []+++def test_run_supports_nested_call_saved_workflow_execution(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-nested"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ call_started = [+ queue_item.session.prepared_source_mapping[invocation.id]+ for queue_item, invocation in events.started+ if invocation.get_type() == "call_saved_workflow"+ ]+ call_completed = [+ queue_item.session.prepared_source_mapping[invocation.id]+ for invocation, queue_item, _output in events.completed+ if invocation.get_type() == "call_saved_workflow"+ ]+ nested_add_outputs = [+ output+ for invocation, child_queue_item, output in events.completed+ if child_queue_item.session is not session+ and child_queue_item.session.prepared_source_mapping[invocation.id] == "nested-add"+ ]+ leaf_add_outputs = [+ output+ for invocation, child_queue_item, output in events.completed+ if child_queue_item.session is not session+ and child_queue_item.session.prepared_source_mapping[invocation.id] == "leaf-add"+ ]++ assert call_started == ["call-node", "nested-call"]+ assert call_completed == ["nested-call", "call-node"]+ assert len(leaf_add_outputs) == 1+ assert leaf_add_outputs[0].value == 11+ assert len(nested_add_outputs) == 1+ assert nested_add_outputs[0].value == 4+ assert session_queue.completed_item_ids == [101, 100, 1]+ assert events.errors == []+++def test_run_cascades_nested_child_workflow_failures_to_all_parents(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-nested-no-return"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ assert session.has_error()+ assert session_queue.completed_item_ids == []+ assert session_queue.failed_item_ids == [100, 1]+ assert len(events.errors) == 2+ assert "workflow_return" in events.errors[0][3]+ assert "workflow_return" in events.errors[1][3]+++def test_run_preserves_canceled_child_workflow_chain_without_failing_parent(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ lifecycle = WorkflowCallQueueLifecycle(runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))++ session = GraphExecutionState(graph=graph)+ invocation = session.next()+ assert isinstance(invocation, CallSavedWorkflowInvocation)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ "priority": 0,+ "origin": None,+ "destination": None,+ "root_item_id": None,+ },+ )()++ workflow_record = runner._services.workflow_records.get(invocation.workflow_id)+ child_queue_item = runner.workflow_call_coordinator.begin_workflow_call_boundary(+ invocation, queue_item, workflow_record+ )++ session_queue.items[queue_item.item_id].status = "canceled"+ session_queue.items[child_queue_item.item_id].status = "canceled"+ monkeypatch.setattr(runner, "run", lambda queue_item: None)++ lifecycle.run_queue_item(child_queue_item)++ assert not session.has_error()+ assert session_queue.failed_item_ids == []+ assert events.errors == []+++def test_run_does_not_resume_canceled_parent_after_completed_child(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ lifecycle = WorkflowCallQueueLifecycle(runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))++ session = GraphExecutionState(graph=graph)+ invocation = session.next()+ assert isinstance(invocation, CallSavedWorkflowInvocation)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ "priority": 0,+ "origin": None,+ "destination": None,+ "root_item_id": None,+ },+ )()++ workflow_record = runner._services.workflow_records.get("workflow-a")+ child_queue_item = runner.workflow_call_coordinator.begin_workflow_call_boundary(+ invocation, queue_item, workflow_record+ )+ original_run = runner.run++ def run_child_then_cancel_parent(queue_item):+ original_run(queue_item)+ session_queue.items[1].status = "canceled"++ monkeypatch.setattr(runner, "run", run_child_then_cancel_parent)++ lifecycle.run_queue_item(child_queue_item)++ assert session_queue.items[1].status == "canceled"+ assert session_queue.completed_item_ids == [child_queue_item.item_id]+ assert session_queue.resumed_item_ids == []+ assert [event for event in events.completed if event[0].get_type() == "call_saved_workflow"] == []+++def test_run_does_not_fail_canceled_parent_after_child_return_error(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ lifecycle = WorkflowCallQueueLifecycle(runner)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))++ session = GraphExecutionState(graph=graph)+ invocation = session.next()+ assert isinstance(invocation, CallSavedWorkflowInvocation)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ "priority": 0,+ "origin": None,+ "destination": None,+ "root_item_id": None,+ },+ )()++ workflow_record = runner._services.workflow_records.get("workflow-a")+ child_queue_item = runner.workflow_call_coordinator.begin_workflow_call_boundary(+ invocation, queue_item, workflow_record+ )++ def fail_child_after_parent_canceled(queue_item):+ queue_item.status = "failed"+ queue_item.error_message = "child failed after parent cancel"+ session_queue.items[queue_item.item_id] = queue_item+ session_queue.items[1].status = "canceled"++ monkeypatch.setattr(runner, "run", fail_child_after_parent_canceled)++ lifecycle.run_queue_item(child_queue_item)++ assert session_queue.items[1].status == "canceled"+ assert session_queue.failed_item_ids == []+ assert session.errors == {}+ assert [event for event in events.errors if event[1].get_type() == "call_saved_workflow"] == []+++def test_run_forwards_literal_dynamic_workflow_inputs_to_child_workflow(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(+ CallSavedWorkflowInvocation(+ id="call-node",+ workflow_id="workflow-a",+ workflow_inputs={"saved_workflow_input::child-add::a": 7},+ )+ )++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ child_add_outputs = [+ output+ for invocation, child_queue_item, output in events.completed+ if invocation.get_type() == "add"+ and child_queue_item.session.prepared_source_mapping[invocation.id] == "child-add"+ ]+ assert len(child_add_outputs) == 1+ assert child_add_outputs[0].value == 9+ assert session_queue.completed_item_ids == [100, 1]+ assert events.errors == []+++def test_run_forwards_connected_dynamic_workflow_inputs_to_child_workflow(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ processor = DefaultSessionProcessor(session_runner=runner)++ graph = Graph()+ graph.add_node(AddInvocation(id="source-add", a=2, b=3))+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))+ graph.add_edge(create_edge("source-add", "value", "call-node", "saved_workflow_input::child-add::a"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ _drain_workflow_call_queue(processor.session_runner.workflow_call_queue_lifecycle, session_queue, queue_item)++ child_add_outputs = [+ output+ for invocation, child_queue_item, output in events.completed+ if invocation.get_type() == "add"+ and child_queue_item.session.prepared_source_mapping[invocation.id] == "child-add"+ ]+ assert len(child_add_outputs) == 1+ assert child_add_outputs[0].value == 7+ assert session_queue.completed_item_ids == [100, 1]+ assert events.errors == []+++def test_run_rejects_non_exposed_dynamic_workflow_inputs(monkeypatch: pytest.MonkeyPatch) -> None:+ session_queue = _DummySessionQueue()+ runner, events, workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ workflow_records.exposed_field_name = "a"++ graph = Graph()+ graph.add_node(+ CallSavedWorkflowInvocation(+ id="call-node",+ workflow_id="workflow-a",+ workflow_inputs={"saved_workflow_input::child-add::b": 11},+ )+ )++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ session_queue.add_queue_item(queue_item)+ runner.run(queue_item=queue_item)++ assert session.has_error()+ assert session_queue.failed_item_ids == [1]+ assert events.completed == []+ assert len(events.errors) == 1+ assert "not exposed" in events.errors[0][3]+++def test_run_fails_call_saved_workflow_when_child_workflow_graph_cannot_be_built(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_queue = _DummySessionQueue()+ runner, events, workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)+ workflow_records.return_invalid_workflow = True++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ session_queue.add_queue_item(queue_item)+ runner.run(queue_item=queue_item)++ assert not session.is_waiting_on_workflow_call()+ assert session.waiting_workflow_call_child_session is None+ assert session.has_error()+ assert session_queue.failed_item_ids == [1]+ assert len(events.started) == 1+ assert events.completed == []+ assert len(events.errors) == 1+++def test_run_fails_call_saved_workflow_with_invalid_selection_without_entering_waiting_state(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id=""))++ session = GraphExecutionState(graph=graph)+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ session_queue.add_queue_item(queue_item)+ runner.run(queue_item=queue_item)++ assert not session.is_waiting_on_workflow_call()+ assert session.has_error()+ assert session_queue.failed_item_ids == [1]+ assert len(events.started) == 1+ assert events.completed == []+ assert len(events.errors) == 1+ assert events.errors[0][2] == "ValueError"+++def test_run_fails_call_saved_workflow_when_depth_limit_is_exceeded(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session_queue = _DummySessionQueue()+ runner, events, _workflow_records = _build_workflow_runner(monkeypatch, session_queue=session_queue)++ graph = Graph()+ graph.add_node(CallSavedWorkflowInvocation(id="call-node", workflow_id="workflow-a"))++ session = GraphExecutionState(+ graph=graph,+ workflow_call_stack=[+ WorkflowCallFrame(+ prepared_call_node_id=f"prepared-{i}",+ source_call_node_id=f"source-{i}",+ workflow_id=f"workflow-{i}",+ depth=i + 1,+ )+ for i in range(4)+ ],+ )+ queue_item = type(+ "QueueItem",+ (),+ {+ "item_id": 1,+ "status": "in_progress",+ "session": session,+ "session_id": "session-id",+ "user_id": "user-1",+ "queue_id": "default",+ "batch_id": "batch-1",+ },+ )()++ session_queue.add_queue_item(queue_item)+ runner.run(queue_item=queue_item)++ assert not session.is_waiting_on_workflow_call()+ assert session.has_error()+ assert session_queue.failed_item_ids == [1]+ assert len(events.started) == 1+ assert events.completed == []+ assert len(events.errors) == 1+ assert events.errors[0][2] == "ValueError"diff --git a/tests/app/test_workflow_socketio.py b/tests/app/test_workflow_socketio.pynew file mode 100644index 0000000000..ba317e3588--- /dev/null+++ b/tests/app/test_workflow_socketio.py@@ -0,0 +1,180 @@+from types import SimpleNamespace+from unittest.mock import ANY, AsyncMock++import pytest+from fastapi import FastAPI++from invokeai.app.api.sockets import SocketIO+++def anyio_backend() -> str:+ return "asyncio"+++def _patch_multiuser_context(monkeypatch: pytest.MonkeyPatch, *, user_id: str, is_admin: bool) -> None:+ user = SimpleNamespace(user_id=user_id, is_active=True)+ invoker = SimpleNamespace(+ services=SimpleNamespace(+ configuration=SimpleNamespace(multiuser=True),+ users=SimpleNamespace(get=lambda candidate_user_id: user if candidate_user_id == user_id else None),+ )+ )+ monkeypatch.setattr("invokeai.app.api.dependencies.ApiDependencies", SimpleNamespace(invoker=invoker))+ monkeypatch.setattr(+ "invokeai.app.api.sockets.verify_token",+ lambda token: SimpleNamespace(user_id=user_id, is_admin=is_admin) if token == "valid-token" else None,+ )+++def _patch_single_user_context(monkeypatch: pytest.MonkeyPatch) -> None:+ invoker = SimpleNamespace(services=SimpleNamespace(configuration=SimpleNamespace(multiuser=False)))+ monkeypatch.setattr("invokeai.app.api.dependencies.ApiDependencies", SimpleNamespace(invoker=invoker))+++async def test_authenticated_user_joins_workflow_rooms_on_connect(monkeypatch: pytest.MonkeyPatch) -> None:+ socketio = SocketIO(FastAPI())+ socketio._sio.enter_room = AsyncMock()+ _patch_multiuser_context(monkeypatch, user_id="user-1", is_admin=False)++ accepted = await socketio._handle_connect("sid-1", {}, {"token": "valid-token"})++ assert accepted is True+ socketio._sio.enter_room.assert_any_call("sid-1", "user:user-1")+ socketio._sio.enter_room.assert_any_call("sid-1", "workflows:shared")+++async def test_admin_joins_admin_room_on_connect(monkeypatch: pytest.MonkeyPatch) -> None:+ socketio = SocketIO(FastAPI())+ socketio._sio.enter_room = AsyncMock()+ _patch_multiuser_context(monkeypatch, user_id="admin-1", is_admin=True)++ accepted = await socketio._handle_connect("sid-1", {}, {"token": "valid-token"})++ assert accepted is True+ socketio._sio.enter_room.assert_any_call("sid-1", "user:admin-1")+ socketio._sio.enter_room.assert_any_call("sid-1", "workflows:shared")+ socketio._sio.enter_room.assert_any_call("sid-1", "admin")+++async def test_single_user_socket_joins_workflow_rooms_on_connect(monkeypatch: pytest.MonkeyPatch) -> None:+ socketio = SocketIO(FastAPI())+ socketio._sio.enter_room = AsyncMock()+ _patch_single_user_context(monkeypatch)++ accepted = await socketio._handle_connect("sid-1", {}, None)++ assert accepted is True+ socketio._sio.enter_room.assert_any_call("sid-1", "user:system")+ socketio._sio.enter_room.assert_any_call("sid-1", "workflows:shared")+ socketio._sio.enter_room.assert_any_call("sid-1", "admin")+++async def test_private_workflow_event_is_emitted_only_to_owner_and_admin() -> None:+ socketio = SocketIO(FastAPI())+ socketio._sio.emit = AsyncMock()++ event_payload = SimpleNamespace(+ __event_name__="workflow_created",+ workflow_id="wf-1",+ user_id="owner-1",+ is_public=False,+ model_dump=lambda mode="json": {"workflow_id": "wf-1", "user_id": "owner-1", "is_public": False},+ )++ await socketio._handle_workflow_event(("workflow_created", event_payload))++ socketio._sio.emit.assert_any_call(+ event="workflow_created",+ data={"workflow_id": "wf-1", "user_id": "owner-1", "is_public": False},+ room="user:owner-1",+ )+ socketio._sio.emit.assert_any_call(+ event="workflow_created",+ data={"workflow_id": "wf-1", "user_id": "owner-1", "is_public": False},+ room="admin",+ )+ assert socketio._sio.emit.await_count == 2+++async def test_single_user_workflow_event_is_emitted_once_to_admin_room(monkeypatch: pytest.MonkeyPatch) -> None:+ socketio = SocketIO(FastAPI())+ socketio._sio.emit = AsyncMock()+ _patch_single_user_context(monkeypatch)++ event_payload = SimpleNamespace(+ __event_name__="workflow_created",+ workflow_id="wf-1",+ user_id="system",+ is_public=False,+ model_dump=lambda mode="json": {"workflow_id": "wf-1", "user_id": "system", "is_public": False},+ )++ await socketio._handle_workflow_event(("workflow_created", event_payload))++ socketio._sio.emit.assert_awaited_once_with(+ event="workflow_created",+ data={"workflow_id": "wf-1", "user_id": "system", "is_public": False},+ room="admin",+ )+++async def test_shared_workflow_event_is_emitted_to_shared_room() -> None:+ socketio = SocketIO(FastAPI())+ socketio._sio.emit = AsyncMock()++ event_payload = SimpleNamespace(+ __event_name__="workflow_updated",+ workflow_id="wf-1",+ user_id="owner-1",+ old_is_public=False,+ new_is_public=True,+ model_dump=lambda mode="json": {+ "workflow_id": "wf-1",+ "user_id": "owner-1",+ "old_is_public": False,+ "new_is_public": True,+ },+ )++ await socketio._handle_workflow_event(("workflow_updated", event_payload))++ socketio._sio.emit.assert_any_call(+ event="workflow_updated",+ data={"workflow_id": "wf-1", "user_id": "owner-1", "old_is_public": False, "new_is_public": True},+ room="workflows:shared",+ )+++async def test_shared_to_private_transition_emits_access_revoked_to_shared_room() -> None:+ socketio = SocketIO(FastAPI())+ socketio._sio.emit = AsyncMock()++ event_payload = SimpleNamespace(+ __event_name__="workflow_updated",+ workflow_id="wf-1",+ user_id="owner-1",+ old_is_public=True,+ new_is_public=False,+ model_dump=lambda mode="json": {+ "workflow_id": "wf-1",+ "user_id": "owner-1",+ "old_is_public": True,+ "new_is_public": False,+ },+ )++ await socketio._handle_workflow_event(("workflow_updated", event_payload))++ socketio._sio.emit.assert_any_call(+ event="workflow_access_revoked",+ data={"workflow_id": "wf-1", "user_id": "owner-1", "timestamp": ANY},+ room="workflows:shared",+ )diff --git a/tests/conftest.py b/tests/conftest.pyindex 92f42375ed..80df0aa93e 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -24,6 +24,7 @@ from invokeai.app.services.invocation_services import InvocationServicesfrom invokeai.app.services.invocation_stats.invocation_stats_default import InvocationStatsServicefrom invokeai.app.services.invoker import Invokerfrom invokeai.app.services.users.users_default import UserService+from invokeai.app.services.workflow_records.workflow_records_sqlite import SqliteWorkflowRecordsStoragefrom invokeai.backend.util.logging import InvokeAILoggerfrom tests.backend.model_manager.model_manager_fixtures import * # noqa: F403from tests.fixtures.sqlite_database import create_mock_sqlite_database # noqa: F401@@ -59,7 +60,7 @@ def mock_services() -> InvocationServices:session_processor=None, # type: ignoresession_queue=None, # type: ignoreurls=None, # type: ignore- workflow_records=None, # type: ignore+ workflow_records=SqliteWorkflowRecordsStorage(db=db),tensors=None, # type: ignoreconditioning=None, # type: ignorestyle_preset_records=None, # type: ignorediff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.pyindex 140e982d77..3ef77b90a1 100644--- a/tests/test_graph_execution_state.py+++ b/tests/test_graph_execution_state.py@@ -19,6 +19,7 @@ from invokeai.app.services.shared.graph import (Graph,GraphExecutionState,IterateInvocation,+ WorkflowCallFrame,)# This import must happen before other invoke imports or test in other files(!!) break@@ -97,6 +98,292 @@ def test_graph_is_not_complete(simple_graph: Graph):assert not g.is_complete()+def test_graph_waiting_on_workflow_call_blocks_other_ready_nodes():+ graph = Graph()+ graph.add_node(PromptTestInvocation(id="prompt_a", prompt="a"))+ graph.add_node(PromptTestInvocation(id="prompt_b", prompt="b"))++ g = GraphExecutionState(graph=graph)++ first = g.next()+ assert first is not None++ waiting_frame = g.build_workflow_call_frame(exec_node_id=first.id, workflow_id="workflow-a")+ g.begin_waiting_on_workflow_call(waiting_frame)++ assert g.next() is None+ assert not g.is_complete()+ assert g.is_waiting_on_workflow_call()+++def test_graph_build_workflow_call_frame_uses_prepared_and_source_ids():+ g = GraphExecutionState(graph=Graph())+ g.execution_graph.add_node(PromptTestInvocation(id="prepared-call", prompt="a"))+ g.prepared_source_mapping["prepared-call"] = "source-call"++ frame = g.build_workflow_call_frame(exec_node_id="prepared-call", workflow_id="workflow-a")++ assert frame.prepared_call_node_id == "prepared-call"+ assert frame.source_call_node_id == "source-call"+ assert frame.workflow_id == "workflow-a"+ assert frame.depth == 1+++def test_graph_build_workflow_call_frame_rejects_depth_over_limit():+ graph = Graph()+ graph.add_node(PromptTestInvocation(id="source-call", prompt="a"))+ g = GraphExecutionState(+ graph=graph,+ workflow_call_stack=[+ WorkflowCallFrame(+ prepared_call_node_id=f"prepared-{i}",+ source_call_node_id=f"source-{i}",+ workflow_id=f"workflow-{i}",+ depth=i + 1,+ )+ for i in range(4)+ ],+ )+ g.execution_graph.add_node(PromptTestInvocation(id="prepared-call", prompt="a"))+ g.prepared_source_mapping["prepared-call"] = "source-call"++ with pytest.raises(ValueError, match="Maximum workflow call depth"):+ g.build_workflow_call_frame(exec_node_id="prepared-call", workflow_id="workflow-a")+++def test_graph_execution_state_serializes_workflow_call_state():+ graph = Graph()+ graph.add_node(PromptTestInvocation(id="source-call", prompt="a"))+ g = GraphExecutionState(graph=graph)+ g.execution_graph.add_node(PromptTestInvocation(id="prepared-call", prompt="a"))+ g.prepared_source_mapping["prepared-call"] = "source-call"++ frame = g.build_workflow_call_frame(exec_node_id="prepared-call", workflow_id="workflow-a")+ g.workflow_call_stack.append(frame)+ g.begin_waiting_on_workflow_call(frame)++ restored = GraphExecutionState.model_validate(g.model_dump(warnings=False))++ assert restored.workflow_call_stack == [frame]+ assert restored.waiting_workflow_call == frame+ assert restored.max_workflow_call_depth == 4+++def test_graph_waiting_on_workflow_call_blocks_until_suspended_node_is_completed():+ graph = Graph()+ graph.add_node(PromptTestInvocation(id="prompt_a", prompt="a"))+ graph.add_node(PromptTestInvocation(id="prompt_b", prompt="b"))++ g = GraphExecutionState(graph=graph)++ first = g.next()+ assert first is not None++ waiting_frame = g.build_workflow_call_frame(exec_node_id=first.id, workflow_id="workflow-a")+ g.begin_waiting_on_workflow_call(waiting_frame)+ assert g.next() is None++ g.end_waiting_on_workflow_call()+ g.complete(first.id, first.invoke(Mock(InvocationContext)))++ resumed = g.next()+ assert resumed is not None+ assert resumed.id != first.id+ assert g.prepared_source_mapping[resumed.id] == "prompt_b"+++def test_graph_begin_waiting_on_workflow_call_rejects_double_entry():+ g = GraphExecutionState(graph=Graph())+ g.execution_graph.add_node(PromptTestInvocation(id="prepared-call", prompt="a"))+ g.prepared_source_mapping["prepared-call"] = "source-call"++ first_frame = g.build_workflow_call_frame(exec_node_id="prepared-call", workflow_id="workflow-a")+ g.begin_waiting_on_workflow_call(first_frame)++ with pytest.raises(ValueError, match="already waiting"):+ g.begin_waiting_on_workflow_call(first_frame)+++def test_graph_build_workflow_call_frame_rejects_missing_execution_node():+ g = GraphExecutionState(graph=Graph())++ with pytest.raises(Exception, match="not found in execution graph"):+ g.build_workflow_call_frame(exec_node_id="missing-node", workflow_id="workflow-a")+++def test_graph_build_workflow_call_frame_rejects_unprepared_execution_node():+ g = GraphExecutionState(graph=Graph())+ g.execution_graph.add_node(PromptTestInvocation(id="prepared-call", prompt="a"))++ with pytest.raises(ValueError, match="not a prepared execution node"):+ g.build_workflow_call_frame(exec_node_id="prepared-call", workflow_id="workflow-a")+++def test_graph_child_workflow_execution_state_inherits_stack_and_isolates_runtime_state():+ parent_graph = Graph()+ child_graph = Graph()++ parent = GraphExecutionState(graph=parent_graph)+ parent.execution_graph.add_node(PromptTestInvocation(id="prepared-parent", prompt="a"))+ parent.prepared_source_mapping["prepared-parent"] = "source-parent"+ parent.results["prepared-parent"] = PromptTestInvocation(id="result-node", prompt="existing").invoke(+ Mock(InvocationContext)+ )+ parent.executed.add("prepared-parent")++ root_frame = parent.build_workflow_call_frame(exec_node_id="prepared-parent", workflow_id="workflow-a")+ parent.workflow_call_stack.append(root_frame)++ parent.execution_graph.add_node(PromptTestInvocation(id="prepared-child", prompt="b"))+ parent.prepared_source_mapping["prepared-child"] = "source-child"+ child_frame = parent.build_workflow_call_frame(exec_node_id="prepared-child", workflow_id="workflow-b")++ child_state = parent.create_child_workflow_execution_state(graph=child_graph, frame=child_frame)++ assert child_state.graph == child_graph+ assert child_state.workflow_call_stack == [root_frame, child_frame]+ assert child_state.max_workflow_call_depth == parent.max_workflow_call_depth+ assert child_state.waiting_workflow_call is None+ assert child_state.results == {}+ assert child_state.executed == set()+++def test_graph_waiting_workflow_call_tracks_parent_child_metadata():+ parent = GraphExecutionState(graph=Graph())+ parent.execution_graph.add_node(PromptTestInvocation(id="prepared-parent", prompt="a"))+ parent.prepared_source_mapping["prepared-parent"] = "source-parent"+ frame = parent.build_workflow_call_frame(exec_node_id="prepared-parent", workflow_id="workflow-a")++ child = parent.create_child_workflow_execution_state(graph=Graph(), frame=frame)+ parent.begin_waiting_on_workflow_call(frame)+ parent.attach_waiting_workflow_call_child_session(child)++ assert parent.waiting_workflow_call_execution is not None+ assert parent.waiting_workflow_call_execution.parent_session_id == parent.id+ assert parent.waiting_workflow_call_execution.child_session_id == child.id+ assert parent.waiting_workflow_call_execution.status == "running_child"+ assert child.workflow_call_parent is not None+ assert child.workflow_call_parent.workflow_call_id == parent.waiting_workflow_call_execution.id+ assert child.workflow_call_parent.parent_session_id == parent.id+++def test_graph_attach_waiting_workflow_call_child_sessions_tracks_fan_out_metadata():+ parent = GraphExecutionState(graph=Graph())+ parent.execution_graph.add_node(AddInvocation(id="prepared-parent", a=1, b=2))+ parent.prepared_source_mapping["prepared-parent"] = "source-parent"++ frame = parent.build_workflow_call_frame(exec_node_id="prepared-parent", workflow_id="workflow-a")+ child_a = parent.create_child_workflow_execution_state(Graph(), frame)+ child_b = parent.create_child_workflow_execution_state(Graph(), frame)++ parent.begin_waiting_on_workflow_call(frame)+ parent.attach_waiting_workflow_call_child_sessions([child_a, child_b])++ assert parent.waiting_workflow_call_execution is not None+ assert parent.waiting_workflow_call_execution.child_session_ids == [child_a.id, child_b.id]+ assert parent.waiting_workflow_call_execution.expected_child_count == 2+ assert parent.waiting_workflow_call_child_session is None+ assert child_a.workflow_call_parent is not None+ assert child_b.workflow_call_parent is not None+++def test_graph_record_waiting_workflow_call_child_completion_aggregates_named_values():+ parent = GraphExecutionState(graph=Graph())+ parent.execution_graph.add_node(AddInvocation(id="prepared-parent", a=1, b=2))+ parent.prepared_source_mapping["prepared-parent"] = "source-parent"++ frame = parent.build_workflow_call_frame(exec_node_id="prepared-parent", workflow_id="workflow-a")+ child_a = parent.create_child_workflow_execution_state(Graph(), frame)+ child_b = parent.create_child_workflow_execution_state(Graph(), frame)++ parent.begin_waiting_on_workflow_call(frame)+ parent.attach_waiting_workflow_call_child_sessions([child_a, child_b])++ is_complete, aggregated_values = parent.record_waiting_workflow_call_child_completion(+ 101, {"sum": 3, "images": "image-a"}+ )+ assert is_complete is False+ assert aggregated_values == {"sum": [3], "images": ["image-a"]}++ is_complete, aggregated_values = parent.record_waiting_workflow_call_child_completion(+ 102, {"sum": 7, "images": "image-b"}+ )+ assert is_complete is True+ assert aggregated_values == {"sum": [3, 7], "images": ["image-a", "image-b"]}+ assert parent.waiting_workflow_call_execution is not None+ assert parent.waiting_workflow_call_execution.completed_child_item_ids == [101, 102]+++def test_graph_record_waiting_workflow_call_child_completion_preserves_enqueue_order():+ parent = GraphExecutionState(graph=Graph())+ parent.execution_graph.add_node(AddInvocation(id="prepared-parent", a=1, b=2))+ parent.prepared_source_mapping["prepared-parent"] = "source-parent"++ frame = parent.build_workflow_call_frame(exec_node_id="prepared-parent", workflow_id="workflow-a")+ child_a = parent.create_child_workflow_execution_state(Graph(), frame)+ child_b = parent.create_child_workflow_execution_state(Graph(), frame)+ parent.begin_waiting_on_workflow_call(frame)+ parent.attach_waiting_workflow_call_child_sessions([child_a, child_b])+ parent.set_waiting_workflow_call_child_item_ids([101, 102])++ parent.record_waiting_workflow_call_child_completion(102, {"sum": 7})+ is_complete, aggregated_values = parent.record_waiting_workflow_call_child_completion(101, {"sum": 3})++ assert is_complete is True+ assert aggregated_values == {"sum": [3, 7]}+++def test_graph_end_waiting_on_workflow_call_records_lifecycle_history():+ parent = GraphExecutionState(graph=Graph())+ parent.execution_graph.add_node(PromptTestInvocation(id="prepared-parent", prompt="a"))+ parent.prepared_source_mapping["prepared-parent"] = "source-parent"+ frame = parent.build_workflow_call_frame(exec_node_id="prepared-parent", workflow_id="workflow-a")++ child = parent.create_child_workflow_execution_state(graph=Graph(), frame=frame)+ parent.begin_waiting_on_workflow_call(frame)+ parent.attach_waiting_workflow_call_child_session(child)+ parent.end_waiting_on_workflow_call(status="failed", error_message="child failed")++ assert parent.waiting_workflow_call is None+ assert parent.waiting_workflow_call_execution is None+ assert parent.waiting_workflow_call_child_session is None+ assert len(parent.workflow_call_history) == 1+ assert parent.workflow_call_history[0].status == "failed"+ assert parent.workflow_call_history[0].error_message == "child failed"+ assert parent.workflow_call_history[0].parent_session_id == parent.id+ assert parent.workflow_call_history[0].child_session_id == child.id+++def test_graph_execution_state_serializes_recursive_workflow_call_stack():+ g = GraphExecutionState(+ graph=Graph(),+ workflow_call_stack=[+ WorkflowCallFrame(+ prepared_call_node_id="prepared-a",+ source_call_node_id="source-a",+ workflow_id="workflow-a",+ depth=1,+ ),+ WorkflowCallFrame(+ prepared_call_node_id="prepared-b",+ source_call_node_id="source-b",+ workflow_id="workflow-b",+ depth=2,+ ),+ WorkflowCallFrame(+ prepared_call_node_id="prepared-a-2",+ source_call_node_id="source-a-2",+ workflow_id="workflow-a",+ depth=3,+ ),+ ],+ )++ restored = GraphExecutionState.model_validate(g.model_dump(warnings=False))++ assert restored.workflow_call_stack == g.workflow_call_stack++# TODO: test completion with iterators/subgraphsdiff --git a/tests/test_session_queue.py b/tests/test_session_queue.pyindex a3f0b8c803..40116422ff 100644--- a/tests/test_session_queue.py+++ b/tests/test_session_queue.py@@ -122,6 +122,18 @@ def test_calc_session_count(batch_data_collection, batch_graph):assert calc_session_count(batch=b) == 8+def test_calc_session_count_does_not_materialize_cartesian_product(+ batch_data_collection, batch_graph, monkeypatch: pytest.MonkeyPatch+):+ monkeypatch.setattr(+ "invokeai.app.services.session_queue.session_queue_common.product",+ lambda *args: pytest.fail("calc_session_count must not enumerate the cartesian product"),+ )+ batch = Batch(graph=batch_graph, data=batch_data_collection, runs=2)++ assert calc_session_count(batch=batch) == 8++def test_prepare_values_to_insert(batch_data_collection, batch_graph):b = Batch(graph=batch_graph, data=batch_data_collection, runs=2)values = prepare_values_to_insert(queue_id="default", batch=b, priority=0, max_new_queue_items=1000)