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
Address PR 189 loop review feedback
JPPhoto867305a4b729
diff --git a/docs/src/content/docs/features/Workflows/loop-nodes.mdx b/docs/src/content/docs/features/Workflows/loop-nodes.mdxindex fb05cd2364..5e867a50e6 100644--- a/docs/src/content/docs/features/Workflows/loop-nodes.mdx+++ b/docs/src/content/docs/features/Workflows/loop-nodes.mdx@@ -76,11 +76,15 @@ port for effects-only bodies.The `item`, `index`, `total`, and `state` outputs belong inside the loop body. The `output_collection` and `final_state`outputs become available after the loop finishes. `loop_linkage` is only for pairing the two boundary nodes.+Collection Cartesian products are limited to 100,000 item pairs. A product larger than 100,000 pairs fails with an+error instead of expanding without bound.+## Returning Results`ForReturn` closes the loop body. It has four useful inputs:- **Output** adds one value to `For.output_collection` for the current iteration.+ Null (`None`) values are retained, so collection positions continue to match iteration order.- **State** supplies the state for the next iteration.- **Continue Condition** controls whether another item should be processed. It continues by default; connecting `False`stops after the current iteration.diff --git a/invokeai/app/invocations/collections.py b/invokeai/app/invocations/collections.pyindex 0764ad4fd9..6761d577c2 100644--- a/invokeai/app/invocations/collections.py+++ b/invokeai/app/invocations/collections.py@@ -146,6 +146,7 @@ class CollectionCartesianInvocation(BaseInvocation):second: list[Any] = InputField(default=[], description="The second collection", ui_type=UIType._Collection)def invoke(self, context: InvocationContext) -> CollectionCartesianInvocationOutput:+ # Divide before multiplying so the comparison cannot overflow for very large input collections.if self.first and self.second and len(self.first) > MAX_CARTESIAN_PRODUCT_SIZE // len(self.second):raise ValueError(f"Cartesian product exceeds the maximum size of {MAX_CARTESIAN_PRODUCT_SIZE} pairs")return CollectionCartesianInvocationOutput(diff --git a/invokeai/app/invocations/loops.py b/invokeai/app/invocations/loops.pyindex 019e71e8c5..73e17f4102 100644--- a/invokeai/app/invocations/loops.py+++ b/invokeai/app/invocations/loops.py@@ -9,6 +9,8 @@ from invokeai.app.services.shared.invocation_context import InvocationContextT = TypeVar("T")+LOOP_LINKAGE_FIELD = "loop_linkage"+def _copy_value(value: T) -> T:if isinstance(value, BaseModel):@@ -137,7 +139,7 @@ class ForInvocationOutput(BaseInvocationOutput):)-@invocation("for", version="1.3.0")+@invocation("for", version="1.3.1")class ForInvocation(BaseInvocation):collection: list[Any] = InputField(description="The list of items to iterate over",@@ -157,11 +159,11 @@ class ForInvocation(BaseInvocation):def invoke(self, context: InvocationContext) -> ForInvocationOutput:if self.index < 0:- raise NotImplementedError("ForInvocation is scheduler-special and cannot be invoked directly")+ raise NotImplementedError("For loop nodes must be executed as part of a workflow graph")state = self.state or LoopState()return ForInvocationOutput(- loop_linkage="loop_linkage",+ loop_linkage=LOOP_LINKAGE_FIELD,item=self.collection[self.index],index=self.index,total=len(self.collection),diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.pyindex 4ab5e3b070..d969836c1e 100644--- a/invokeai/app/services/session_processor/session_processor_default.py+++ b/invokeai/app/services/session_processor/session_processor_default.py@@ -280,12 +280,21 @@ class DefaultSessionRunner(SessionRunnerBase):if self._on_after_run_node_callbacks and isinstance(invocation, (IterateInvocation, CollectInvocation)):control_collection = invocation.collection# Save output and history- queue_item.session.complete(invocation.id, output)+ finalized_outputs = queue_item.session.complete(invocation.id, output)if control_collection is not None:invocation.collection = control_collectiontry:self._on_after_run_node(invocation, queue_item, output)+ for finalized_invocation, finalized_output in finalized_outputs:+ # For output collections are finalized when their matching ForReturn completes. Emit a+ # follow-up event so listeners receive the materialized final collection, not the placeholder+ # produced when the For iteration started.+ self._services.events.emit_invocation_complete(+ invocation=finalized_invocation,+ queue_item=queue_item,+ output=finalized_output,+ )finally:if control_collection is not None:invocation.collection = []diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex ef63d8c3ec..222b422045 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -52,6 +52,7 @@ from invokeai.app.invocations.call_saved_workflow import (from invokeai.app.invocations.fields import Input, InputField, OutputField, OutputScope, UITypefrom invokeai.app.invocations.logic import IfInvocationfrom invokeai.app.invocations.loops import (+ LOOP_LINKAGE_FIELD,ForInvocation,ForInvocationOutput,ForReturnInvocation,@@ -88,7 +89,6 @@ NoneType = type(None)# Port name constantsITEM_FIELD = "item"COLLECTION_FIELD = "collection"-LOOP_LINKAGE_FIELD = "loop_linkage"@dataclass(frozen=True)@@ -209,11 +209,13 @@ class _PreparedExecRegistry:source_prepared_mapping: dict[str, set[str]],prepared_iteration_paths: dict[str, tuple[int, ...]],metadata: dict[str, _PreparedExecNodeMetadata],+ on_iteration_path_change: Callable[[str], None] | None = None,) -> None:self._prepared_source_mapping = prepared_source_mappingself._source_prepared_mapping = source_prepared_mappingself._prepared_iteration_paths = prepared_iteration_pathsself._metadata = metadata+ self._on_iteration_path_change = on_iteration_path_changedef register(self, exec_node_id: str, source_node_id: str) -> None:self._prepared_source_mapping[exec_node_id] = source_node_id@@ -254,6 +256,8 @@ class _PreparedExecRegistry:def set_iteration_path(self, exec_node_id: str, iteration_path: tuple[int, ...]) -> None:self._prepared_iteration_paths[exec_node_id] = iteration_pathself.get_metadata(exec_node_id).iteration_path = iteration_path+ if self._on_iteration_path_change is not None:+ self._on_iteration_path_change(exec_node_id)class _IfBranchScheduler:@@ -585,7 +589,7 @@ class _ExecutionMaterializer:new_node.state = initial_stateself._state.results[new_node.id] = ForInvocationOutput(- loop_linkage="loop_linkage",+ loop_linkage=LOOP_LINKAGE_FIELD,item=None,index=-1,total=0,@@ -605,9 +609,7 @@ class _ExecutionMaterializer:if isinstance(self._state.execution_graph.get_node(prepared_id), ForInvocation)and self._state.execution_graph.get_node(prepared_id).index == -1]- if not prepared_for_ids:- self._state.finalized_loop_contexts.add((source_for_id, ()))- self._state.finalized_loop_nodes.add(source_for_id)+ assert prepared_for_ids, f"Empty For '{source_for_id}' did not create a final execution node"for prepared_for_id in prepared_for_ids:self._state._mark_loop_context_finalized(source_for_id, prepared_for_id)@@ -704,18 +706,12 @@ class _ExecutionMaterializer:)def _get_final_prepared_for_id(self, source_for_id: str, parent_iteration_path: tuple[int, ...]) -> str:- candidates = [- prepared_id- for prepared_id in self._state._prepared_registry().get_prepared_ids(source_for_id)- if isinstance(self._state.execution_graph.get_node(prepared_id), ForInvocation)- and self._state._get_for_parent_iteration_path(prepared_id) == parent_iteration_path- ]- if not candidates:+ self._state._get_prepared_for_index()+ assert self._state._final_prepared_for_index is not None+ prepared_for_id = self._state._final_prepared_for_index.get((source_for_id, parent_iteration_path))+ if prepared_for_id is None:raise RuntimeError(f"Unable to find finalized nested For '{source_for_id}' for {parent_iteration_path}")- return max(- candidates,- key=lambda prepared_id: self._state.execution_graph.get_node(prepared_id).index,- )+ return prepared_for_iddef create_nested_for_return(self, inner_for_id: str, prepared_inner_for_id: str) -> Optional[str]:graph = self._state.graph.nx_graph_flat()@@ -849,6 +845,12 @@ class _ExecutionMaterializer:execution_graph: "nx.DiGraph",nested_body: _SupportedNestedForBody,) -> Optional[str]:+ """Materialize one nested-For body at the owning outer iteration path.++ The source graph is shaped as ``outer For -> inner For(s) -> outer ForReturn``. Existing execution nodes+ are reused at the current path; missing ordinary body nodes are copied, then each inner For is allowed to+ advance independently before the outer return is rematerialized.+ """body_path_nodes = nested_body.body_path_nodessource_return_id = nested_body.outer_return_idprepared_for_node = self._state.execution_graph.get_node(prepared_for_id)@@ -1683,9 +1685,9 @@ class _ExecutionMaterializer:new_node_ids.extend(create_results)if not new_node_ids:+ # No parent mappings means zero loop contexts, unlike a context with an empty collection.self._mark_source_node_empty(next_node_id)- if isinstance(next_node, ForInvocation):- self._mark_empty_for_complete(next_node_id)+ self._state._invalidate_loop_caches_for_source(next_node_id)return next_node_idif isinstance(next_node, ForInvocation) and all(@@ -1751,47 +1753,26 @@ class _ExecutionScheduler:self._state.executed_history.append(source_node_id)def _get_for_parent(self, exec_node_id: str) -> Optional[str]:- execution_graph = self._state.execution_graph.nx_graph_flat()-source_return_id = self._state._prepared_registry().get_source_node_id(exec_node_id)iteration_path = self._state._get_iteration_path(exec_node_id)- source_graph = self._state.graph.nx_graph_flat()- for source_for_id, source_for_node in self._state.graph.nodes.items():- if not isinstance(source_for_node, ForInvocation):- continue- body_path_to_return = self._state.graph._get_for_body_path_to_return(source_for_id, source_graph)- if body_path_to_return is None or body_path_to_return[1] != source_return_id:- continue- matching_for_ids = [- prepared_for_id- for prepared_for_id in self._state._prepared_registry().get_prepared_ids(source_for_id)- if isinstance(self._state.execution_graph.get_node(prepared_for_id), ForInvocation)- and iteration_path[: len(self._state._get_iteration_path(prepared_for_id))]- == self._state._get_iteration_path(prepared_for_id)- ]- if matching_for_ids:- return max(- matching_for_ids,- key=lambda prepared_for_id: (- len(self._state._get_iteration_path(prepared_for_id)),- self._state.execution_graph.get_node(prepared_for_id).index,- ),- )-+ source_for_id = self._state._get_for_source_by_return_id().get(source_return_id)+ if source_for_id is not None:+ prepared_for_id = self._state._get_prepared_for_index().get((source_for_id, iteration_path))+ if prepared_for_id is not None:+ return prepared_for_id++ # The indexed source/path lookup is the normal path. The ancestor fallback only covers legacy execution+ # graphs whose durable linkage was not materialized; keep it explicit so an unexpected miss is diagnosable.+ execution_graph = self._state.execution_graph.nx_graph_flat()for ancestor_id in nx.ancestors(execution_graph, exec_node_id):source_node = self._state.execution_graph.get_node(ancestor_id)if isinstance(source_node, ForInvocation):return ancestor_id# An empty nested Iterate has no item execution node, so its synthetic Collect and ForReturn have no- # execution-graph edge back to their owning For. Recover ownership from the durable source boundary and- # matching execution path so the outer loop can advance.- for source_for_id, source_for_node in self._state.graph.nodes.items():- if not isinstance(source_for_node, ForInvocation):- continue- body_path_to_return = self._state.graph._get_for_body_path_to_return(source_for_id, source_graph)- if body_path_to_return is None or body_path_to_return[1] != source_return_id:- continue+ # execution-graph edge back to their owning For. The same indexed lookup handles this case when the+ # synthetic node has been assigned its durable parent path.+ if source_for_id is not None:for prepared_for_id in self._state._prepared_registry().get_prepared_ids(source_for_id):prepared_for_node = self._state.execution_graph.get_node(prepared_for_id)if not isinstance(prepared_for_node, ForInvocation) or prepared_for_node.index < 0:@@ -1841,23 +1822,23 @@ class _ExecutionScheduler:returnreturn_outputs = self._get_ordered_for_return_outputs(for_exec_node_id, source_return_id)- for_output.output_collection = [output.output for output in return_outputs if output.output is not None]+ for_output.output_collection = [output.output for output in return_outputs]for_output.final_state = self._get_loop_state_for_next_iteration(for_exec_node_id, return_output)self._state._mark_loop_context_finalized(source_for_id, for_exec_node_id)- def _try_schedule_next_for_iteration(self, exec_node_id: str, output: BaseInvocationOutput) -> None:+ def _try_schedule_next_for_iteration(self, exec_node_id: str, output: BaseInvocationOutput) -> Optional[str]:if not isinstance(output, ForReturnInvocationOutput):- return+ return Noneif not isinstance(self._state.execution_graph.get_node(exec_node_id), ForReturnInvocation):- return+ return Nonefor_exec_node_id = self._get_for_parent(exec_node_id)if for_exec_node_id is None:- return+ return Nonefor_node = self._state.execution_graph.get_node(for_exec_node_id)if not isinstance(for_node, ForInvocation):- return+ return Noneregistry = self._state._prepared_registry()source_for_id = registry.get_source_node_id(for_exec_node_id)@@ -1873,7 +1854,7 @@ class _ExecutionScheduler:prepared_inner_for_id=for_exec_node_id,)for_node.collection = []- return+ return for_exec_node_idnext_state = self._get_loop_state_for_next_iteration(for_exec_node_id, output)parent_iteration_path = self._state._get_for_parent_iteration_path(for_exec_node_id)@@ -1888,6 +1869,7 @@ class _ExecutionScheduler:self._state.executed.discard(source_for_id)self._state._materializer().create_for_body_iteration(source_for_id=source_for_id, prepared_for_id=next_for_id)for_node.collection = []+ return Nonedef _try_materialize_deferred_nested_for_body(self, exec_node_id: str) -> None:completed_source_id = self._state._prepared_registry().get_source_node_id(exec_node_id)@@ -2021,12 +2003,14 @@ class _ExecutionScheduler:self._state._active_class = next_class- def complete(self, exec_node_id: str, output: BaseInvocationOutput) -> None:+ def complete(+ self, exec_node_id: str, output: BaseInvocationOutput+ ) -> list[tuple[BaseInvocation, BaseInvocationOutput]]:if exec_node_id not in self._state.execution_graph.nodes:- return+ return []self._record_completed_node(exec_node_id, output)- self._try_schedule_next_for_iteration(exec_node_id, output)+ finalized_for_exec_node_id = self._try_schedule_next_for_iteration(exec_node_id, output)self._mark_source_node_complete(exec_node_id)self._release_downstream_nodes(exec_node_id)completed_node = self._state.execution_graph.get_node(exec_node_id)@@ -2063,6 +2047,16 @@ class _ExecutionScheduler:self._state._ready_node_ids = set()self._state._active_class = None+ if finalized_for_exec_node_id is None:+ return []+ finalized_for_node = self._state.execution_graph.get_node(finalized_for_exec_node_id)+ finalized_for_output = self._state.results.get(finalized_for_exec_node_id)+ if not isinstance(finalized_for_node, ForInvocation) or not isinstance(+ finalized_for_output, ForInvocationOutput+ ):+ return []+ return [(finalized_for_node, finalized_for_output)]+class _ExecutionRuntime:"""Provides runtime-only helpers such as iteration-path lookup and input hydration."""@@ -3219,7 +3213,16 @@ class Graph(BaseModel):def _get_supported_for_nested_iterate_body(self, node_id: str, graph: "nx.DiGraph") -> _SupportedNestedIterateBody | None:- """Returns the bounded internal Iterate body contract, if this For uses it."""+ """Return the bounded internal Iterate body contract, if this For uses it.++ Supported shape::++ For.item -> Iterate.item -> body -> Collect.item+ Collect.collection -> ForReturn.output++ The Iterate and Collect nodes are scheduler-managed, so no other branch or final For output may escape this+ body contract.+ """body_path_to_return = self._get_for_body_path_to_return(node_id, graph)if body_path_to_return is None:return None@@ -3295,6 +3298,16 @@ class Graph(BaseModel):Each direct child loop has its own ForReturn. A single child may close the parent directly or through acontinuation. Multiple independent child loops must all feed an ordinary parent-scoped continuation, which actsas an explicit fan-in barrier after every child has finalized for the current parent iteration.++ Accepted shape (the child body can recursively contain this same shape)::++ outer For -> preparation -> inner For(s) -> continuation -> outer ForReturn+ | ^+ v |+ child body -> inner ForReturn++ Preparation, child bodies, and continuation partition the reachable outer body. Only finalized child outputs+ may cross into the continuation; iteration outputs stay inside their owning child body."""outer_node = self.get_node(node_id)if not isinstance(outer_node, ForInvocation):@@ -3925,10 +3938,6 @@ class GraphExecutionState(BaseModel):description="The map of original graph nodes to prepared nodes",default_factory=dict,)- finalized_loop_nodes: set[str] = Field(- description="Legacy set of top-level loop source nodes whose final outputs have been materialized",- default_factory=set,- )finalized_loop_contexts: set[tuple[str, tuple[int, ...]]] = Field(description="The finalized loop source and parent iteration contexts",default_factory=set,@@ -3953,6 +3962,15 @@ class GraphExecutionState(BaseModel):_execution_materializer: Optional[_ExecutionMaterializer] = PrivateAttr(default=None)_execution_scheduler: Optional[_ExecutionScheduler] = PrivateAttr(default=None)_execution_runtime: Optional[_ExecutionRuntime] = PrivateAttr(default=None)+ _for_parent_iteration_paths_cache: dict[str, set[tuple[int, ...]]] = PrivateAttr(default_factory=dict)+ _all_for_contexts_finalized_cache: dict[str, bool] = PrivateAttr(default_factory=dict)+ _prepared_for_index: Optional[dict[tuple[str, tuple[int, ...]], str]] = PrivateAttr(default=None)+ _final_prepared_for_index: Optional[dict[tuple[str, tuple[int, ...]], str]] = PrivateAttr(default=None)+ _prepared_for_index_by_exec: dict[str, tuple[str, tuple[int, ...], tuple[int, ...]]] = PrivateAttr(+ default_factory=dict+ )+ _source_graph_flat: Any | None = PrivateAttr(default=None)+ _for_source_by_return_id: Optional[dict[str, str]] = PrivateAttr(default=None)def _type_key(self, node_obj: BaseInvocation) -> str:return node_obj.__class__.__name__@@ -3964,6 +3982,7 @@ class GraphExecutionState(BaseModel):source_prepared_mapping=self.source_prepared_mapping,prepared_iteration_paths=self.prepared_iteration_paths,metadata=self._prepared_exec_metadata,+ on_iteration_path_change=self._invalidate_loop_caches_for_exec_node,)return self._prepared_exec_registry@@ -3972,6 +3991,27 @@ class GraphExecutionState(BaseModel):self._if_branch_scheduler = _IfBranchScheduler(self)return self._if_branch_scheduler+ def _get_source_graph_flat(self) -> Any:+ if self._source_graph_flat is None:+ self._source_graph_flat = self.graph.nx_graph_flat()+ return self._source_graph_flat++ def _get_for_source_by_return_id(self) -> dict[str, str]:+ if self._for_source_by_return_id is None:+ source_graph = self._get_source_graph_flat()+ self._for_source_by_return_id = {+ body_path_to_return[1]: source_for_id+ for source_for_id, source_for_node in self.graph.nodes.items()+ if isinstance(source_for_node, ForInvocation)+ and (body_path_to_return := self.graph._get_for_body_path_to_return(source_for_id, source_graph))+ is not None+ }+ return self._for_source_by_return_id++ def _invalidate_source_graph_cache(self) -> None:+ self._source_graph_flat = None+ self._for_source_by_return_id = None+def _materializer(self) -> _ExecutionMaterializer:if self._execution_materializer is None:self._execution_materializer = _ExecutionMaterializer(self)@@ -3989,6 +4029,27 @@ class GraphExecutionState(BaseModel):def _register_prepared_exec_node(self, exec_node_id: str, source_node_id: str) -> None:self._prepared_registry().register(exec_node_id, source_node_id)+ self._invalidate_loop_caches_for_source(source_node_id)+ if (+ self._prepared_for_index is not None+ and self._prepared_registry().get_iteration_path(exec_node_id) is not None+ ):+ self._update_prepared_for_index(exec_node_id)++ def _invalidate_loop_caches_for_source(self, source_node_id: str) -> None:+ self._all_for_contexts_finalized_cache.pop(source_node_id, None)++ def _invalidate_loop_caches_for_exec_node(self, exec_node_id: str) -> None:+ source_node_id = self.prepared_source_mapping.get(exec_node_id)+ if source_node_id is not None:+ self._invalidate_loop_caches_for_source(source_node_id)+ prepared_node = self.execution_graph.nodes.get(exec_node_id)+ if isinstance(prepared_node, ForInvocation):+ parent_iteration_path = self._get_for_parent_iteration_path(exec_node_id)+ cached_paths = self._for_parent_iteration_paths_cache.get(source_node_id)+ if cached_paths is not None:+ cached_paths.add(parent_iteration_path)+ self._update_prepared_for_index(exec_node_id)def _get_prepared_exec_metadata(self, exec_node_id: str) -> _PreparedExecNodeMetadata:return self._prepared_registry().get_metadata(exec_node_id)@@ -4006,11 +4067,78 @@ class GraphExecutionState(BaseModel):return iteration_pathreturn iteration_path[:-1]+ def _get_prepared_for_index(self) -> dict[tuple[str, tuple[int, ...]], str]:+ """Index For executions by exact iteration path and final candidates by parent context.++ The scheduler creates For executions in iteration order, so the highest index in a context is the current+ final candidate. Indexes are built lazily once and maintained as prepared paths are registered; repeated+ completion checks then use constant-time context lookups.+ """+ if self._prepared_for_index is not None:+ return self._prepared_for_index++ index: dict[tuple[str, tuple[int, ...]], str] = {}+ self._prepared_for_index_by_exec = {}+ self._final_prepared_for_index = {}+ for source_for_id, prepared_ids in self.source_prepared_mapping.items():+ for prepared_for_id in prepared_ids:+ self._prepared_for_index_by_exec[prepared_for_id] = (+ source_for_id,+ self._get_iteration_path(prepared_for_id),+ self._get_for_parent_iteration_path(prepared_for_id),+ )++ self._prepared_for_index = index+ for prepared_for_id in list(self._prepared_for_index_by_exec):+ self._update_prepared_for_index(prepared_for_id)+ assert self._prepared_for_index is not None+ return self._prepared_for_index++ def _update_prepared_for_index(self, prepared_for_id: str) -> None:+ if self._prepared_for_index is None:+ return++ old_key = self._prepared_for_index_by_exec.pop(prepared_for_id, None)+ if old_key is not None:+ old_source_id, old_path, old_parent_path = old_key+ if self._prepared_for_index.get((old_source_id, old_path)) == prepared_for_id:+ del self._prepared_for_index[(old_source_id, old_path)]+ if (+ self._final_prepared_for_index is not None+ and self._final_prepared_for_index.get((old_source_id, old_parent_path)) == prepared_for_id+ ):+ del self._final_prepared_for_index[(old_source_id, old_parent_path)]++ prepared_for_node = self.execution_graph.nodes.get(prepared_for_id)+ source_for_id = self.prepared_source_mapping.get(prepared_for_id)+ if not isinstance(prepared_for_node, ForInvocation) or source_for_id is None:+ return++ iteration_path = self._get_iteration_path(prepared_for_id)+ parent_iteration_path = self._get_for_parent_iteration_path(prepared_for_id)+ key = (source_for_id, iteration_path)+ existing_id = self._prepared_for_index.get(key)+ if existing_id is None:+ self._prepared_for_index[key] = prepared_for_id+ else:+ existing_node = self.execution_graph.get_node(existing_id)+ if isinstance(existing_node, ForInvocation) and prepared_for_node.index > existing_node.index:+ self._prepared_for_index[key] = prepared_for_id+ assert self._final_prepared_for_index is not None+ final_key = (source_for_id, parent_iteration_path)+ final_existing_id = self._final_prepared_for_index.get(final_key)+ if final_existing_id is None:+ self._final_prepared_for_index[final_key] = prepared_for_id+ else:+ final_existing_node = self.execution_graph.get_node(final_existing_id)+ if isinstance(final_existing_node, ForInvocation) and prepared_for_node.index > final_existing_node.index:+ self._final_prepared_for_index[final_key] = prepared_for_id+ self._prepared_for_index_by_exec[prepared_for_id] = (source_for_id, iteration_path, parent_iteration_path)+def _mark_loop_context_finalized(self, source_for_id: str, prepared_for_id: str) -> None:parent_iteration_path = self._get_for_parent_iteration_path(prepared_for_id)self.finalized_loop_contexts.add((source_for_id, parent_iteration_path))- if parent_iteration_path == ():- self.finalized_loop_nodes.add(source_for_id)+ self._all_for_contexts_finalized_cache.pop(source_for_id, None)def _mark_for_source_complete(self, source_for_id: str) -> None:if not self._all_for_contexts_finalized(source_for_id):@@ -4029,25 +4157,33 @@ class GraphExecutionState(BaseModel):self.executed_history.append(source_node_id)def _get_for_parent_iteration_paths(self, source_for_id: str) -> set[tuple[int, ...]]:- return {+ cached = self._for_parent_iteration_paths_cache.get(source_for_id)+ if cached is not None:+ return cached++ paths = {self._get_for_parent_iteration_path(prepared_for_id)for prepared_for_id in self._prepared_registry().get_prepared_ids(source_for_id)if isinstance(self.execution_graph.get_node(prepared_for_id), ForInvocation)}+ self._for_parent_iteration_paths_cache[source_for_id] = paths+ return pathsdef _is_loop_context_finalized(self, source_for_id: str, parent_iteration_path: tuple[int, ...]) -> bool:- return (source_for_id, parent_iteration_path) in self.finalized_loop_contexts or (- parent_iteration_path == () and source_for_id in self.finalized_loop_nodes- )+ return (source_for_id, parent_iteration_path) in self.finalized_loop_contextsdef _all_for_contexts_finalized(self, source_for_id: str) -> bool:+ cached = self._all_for_contexts_finalized_cache.get(source_for_id)+ if cached is not None:+ return cached+parent_iteration_paths = self._get_for_parent_iteration_paths(source_for_id)- if not parent_iteration_paths:- return source_for_id in self.finalized_loop_nodes- return all(+ finalized = (bool(parent_iteration_paths) or source_for_id in self.executed) and all(self._is_loop_context_finalized(source_for_id, parent_iteration_path)for parent_iteration_path in parent_iteration_paths)+ self._all_for_contexts_finalized_cache[source_for_id] = finalized+ return finalizeddef _queue_for(self, cls_name: str) -> Deque[str]:return self._scheduler().queue_for(cls_name)@@ -4094,6 +4230,11 @@ class GraphExecutionState(BaseModel):self._execution_materializer = Noneself._execution_scheduler = Noneself._execution_runtime = None+ self._for_parent_iteration_paths_cache = {}+ self._all_for_contexts_finalized_cache = {}+ self._prepared_for_index = None+ self._final_prepared_for_index = None+ self._prepared_for_index_by_exec = {}def _rehydrate_prepared_exec_metadata(self) -> None:registry = self._prepared_registry()@@ -4169,7 +4310,6 @@ class GraphExecutionState(BaseModel):"workflow_call_history","prepared_source_mapping","source_prepared_mapping",- "finalized_loop_nodes",]})@@ -4188,6 +4328,7 @@ class GraphExecutionState(BaseModel):if self.is_waiting_on_workflow_call():return None+ # Failed graphs stop scheduling immediately; is_complete() treats the error as terminal as well.if self.has_error():return None@@ -4206,9 +4347,11 @@ class GraphExecutionState(BaseModel):# If next is still none, there's no next node, return Nonereturn next_node- def complete(self, node_id: str, output: BaseInvocationOutput) -> None:+ def complete(self, node_id: str, output: BaseInvocationOutput) -> list[tuple[BaseInvocation, BaseInvocationOutput]]:"""Marks a node as complete"""- self._scheduler().complete(node_id, output)+ finalized_outputs = self._scheduler().complete(node_id, output)+ self._mark_completed_sources()+ return finalized_outputsdef set_node_error(self, node_id: str, error: str):"""Marks a node as errored"""@@ -4218,6 +4361,9 @@ class GraphExecutionState(BaseModel):"""Returns true if the graph is complete"""if self.is_waiting_on_workflow_call():return False+ return self._is_complete_with_completed_sources()++ def _completed_source_ids(self) -> set[str]:completed_source_ids = set(self.executed)for source_node_id, source_node in self.graph.nodes.items():prepared_node_ids = self._prepared_registry().get_prepared_ids(source_node_id)@@ -4226,15 +4372,25 @@ class GraphExecutionState(BaseModel):if isinstance(source_node, ForInvocation) and not self._all_for_contexts_finalized(source_node_id):continuecompleted_source_ids.add(source_node_id)+ return completed_source_ids++ def _is_complete_with_completed_sources(self) -> bool:+ if self.has_error():+ return True+ completed_source_ids = self._completed_source_ids()node_ids = set(self.graph.nx_graph_flat().nodes)- complete = self.has_error() or all((k in completed_source_ids for k in node_ids))- if complete and not self.has_error():- for source_node_id in nx.topological_sort(self.graph.nx_graph_flat()):- if source_node_id in completed_source_ids and source_node_id not in self.executed:- self.executed.add(source_node_id)- if source_node_id not in self.executed_history:- self.executed_history.append(source_node_id)- return complete+ return all(node_id in completed_source_ids for node_id in node_ids)++ def _mark_completed_sources(self) -> None:+ if not self._is_complete_with_completed_sources():+ return++ completed_source_ids = self._completed_source_ids()+ for source_node_id in nx.topological_sort(self.graph.nx_graph_flat()):+ if source_node_id in completed_source_ids and source_node_id not in self.executed:+ self.executed.add(source_node_id)+ if source_node_id not in self.executed_history:+ self.executed_history.append(source_node_id)def has_error(self) -> bool:"""Returns true if the graph has any errors"""@@ -4431,6 +4587,7 @@ class GraphExecutionState(BaseModel):def add_node(self, node: BaseInvocation) -> None:self.graph.add_node(node)+ self._invalidate_source_graph_cache()def update_node(self, node_id: str, new_node: BaseInvocation) -> None:if not self._is_node_updatable(node_id):@@ -4438,6 +4595,7 @@ class GraphExecutionState(BaseModel):f"Node {node_id} has already been prepared or executed and cannot be updated")self.graph.update_node(node_id, new_node)+ self._invalidate_source_graph_cache()def delete_node(self, node_id: str) -> None:if not self._is_node_updatable(node_id):@@ -4445,6 +4603,7 @@ class GraphExecutionState(BaseModel):f"Node {node_id} has already been prepared or executed and cannot be deleted")self.graph.delete_node(node_id)+ self._invalidate_source_graph_cache()def add_edge(self, edge: Edge) -> None:if not self._is_node_updatable(edge.destination.node_id):@@ -4452,6 +4611,7 @@ class GraphExecutionState(BaseModel):f"Destination node {edge.destination.node_id} has already been prepared or executed and cannot be linked to")self.graph.add_edge(edge)+ self._invalidate_source_graph_cache()def delete_edge(self, edge: Edge) -> None:if not self._is_node_updatable(edge.destination.node_id):@@ -4459,3 +4619,4 @@ class GraphExecutionState(BaseModel):f"Destination node {edge.destination.node_id} has already been prepared or executed and cannot have a source edge deleted")self.graph.delete_edge(edge)+ self._invalidate_source_graph_cache()diff --git a/invokeai/app/services/shared/workflow_graph_builder.py b/invokeai/app/services/shared/workflow_graph_builder.pyindex 16ce64ce7f..79297ed64b 100644--- a/invokeai/app/services/shared/workflow_graph_builder.py+++ b/invokeai/app/services/shared/workflow_graph_builder.py@@ -7,6 +7,7 @@ from invokeai.app.invocations.call_saved_workflow import (CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX,parse_call_saved_workflow_dynamic_input,)+from invokeai.app.invocations.loops import LOOP_LINKAGE_FIELDfrom invokeai.app.services.shared.graph import Edge, EdgeConnection, GraphCONNECTOR_INPUT_HANDLE = "in"@@ -40,6 +41,11 @@ def _is_connector_node(node: Any) -> bool:return _is_mapping(node) and node.get("type") == "connector"+def _workflow_edge_key(edge: Mapping[str, Any]) -> tuple[str, str, str, str] | None:+ values = (edge.get("source"), edge.get("sourceHandle"), edge.get("target"), edge.get("targetHandle"))+ return values if all(isinstance(value, str) for value in values) else None++def _build_dynamic_input_name(node_id: str, field_name: str) -> str:return f"{CALL_SAVED_WORKFLOW_DYNAMIC_FIELD_PREFIX}{node_id}::{field_name}"@@ -308,7 +314,7 @@ def _resolve_for_connector_loop_linkage_path(edge: Mapping[str, Any], workflow_nodes: dict[str, Mapping[str, Any]], workflow_edges: Sequence[Mapping[str, Any]]) -> _ConnectorLoopLinkagePath | None:"""Resolve one connector alias path from a For to its direct ForReturn association."""- if edge.get("sourceHandle") != "loop_linkage" or edge.get("targetHandle") != CONNECTOR_INPUT_HANDLE:+ if edge.get("sourceHandle") != LOOP_LINKAGE_FIELD or edge.get("targetHandle") != CONNECTOR_INPUT_HANDLE:return Nonesource_id = edge.get("source")@@ -346,7 +352,7 @@ def _resolve_for_connector_loop_linkage_path(target_handle = output_edge.get("targetHandle")target_node = workflow_nodes.get(target_id)if _is_invocation_node(target_node):- if target_node.get("data", {}).get("type") != "for_return" or target_handle != "loop_linkage":+ if target_node.get("data", {}).get("type") != "for_return" or target_handle != LOOP_LINKAGE_FIELD:return Nonereturn _ConnectorLoopLinkagePath(source_id=source_id, target_id=target_id, edge_path=tuple(path_edges))if (@@ -371,23 +377,23 @@ def build_graph_from_workflow(workflow: Mapping[str, Any]) -> Graph:loop_linkage_edges = _get_loop_linkage_edges(workflow_edges)connector_loop_linkage_paths: list[_ConnectorLoopLinkagePath] = []- connector_loop_linkage_edge_ids: set[int] = set()+ connector_loop_linkage_edge_keys: set[tuple[str, str, str, str]] = set()linked_for_ids = {edge.get("source")for edge in loop_linkage_edges- if isinstance(edge.get("source"), str) and edge.get("sourceHandle") == "loop_linkage"+ if isinstance(edge.get("source"), str) and edge.get("sourceHandle") == LOOP_LINKAGE_FIELD}linked_return_ids = {edge.get("target")for edge in loop_linkage_edges- if isinstance(edge.get("target"), str) and edge.get("targetHandle") == "loop_linkage"+ if isinstance(edge.get("target"), str) and edge.get("targetHandle") == LOOP_LINKAGE_FIELD}for edge in default_edges:source_id = edge.get("source")source_handle = edge.get("sourceHandle")target_id = edge.get("target")target_handle = edge.get("targetHandle")- if not isinstance(source_id, str) or source_handle != "loop_linkage":+ if not isinstance(source_id, str) or source_handle != LOOP_LINKAGE_FIELD:continuesource_node = workflow_nodes.get(source_id)if not _is_invocation_node(source_node) or source_node.get("data", {}).get("type") != "for":@@ -403,10 +409,12 @@ def build_graph_from_workflow(workflow: Mapping[str, Any]) -> Graph:)if path.source_id in linked_for_ids or path.target_id in linked_return_ids:raise InvalidWorkflowInputError(- "loop_linkage connector path must resolve to exactly one For and one ForReturn without branching"+ "loop_linkage connector path targets a For or ForReturn that already has a loop linkage")connector_loop_linkage_paths.append(path)- connector_loop_linkage_edge_ids.update(id(path_edge) for path_edge in path.edge_path)+ connector_loop_linkage_edge_keys.update(+ edge_key for path_edge in path.edge_path if (edge_key := _workflow_edge_key(path_edge)) is not None+ )linked_for_ids.add(path.source_id)linked_return_ids.add(path.target_id)@@ -448,7 +456,7 @@ def build_graph_from_workflow(workflow: Mapping[str, Any]) -> Graph:seen_edges: set[tuple[str, str, str, str]] = set()for edge in default_edges:- if id(edge) in connector_loop_linkage_edge_ids:+ if _workflow_edge_key(edge) in connector_loop_linkage_edge_keys:continuesource_id = edge.get("source")target_id = edge.get("target")@@ -514,8 +522,8 @@ def build_graph_from_workflow(workflow: Mapping[str, Any]) -> Graph:parsed_edges.append({"type": "loop_linkage",- "source": {"node_id": path.source_id, "field": "loop_linkage"},- "destination": {"node_id": path.target_id, "field": "loop_linkage"},+ "source": {"node_id": path.source_id, "field": LOOP_LINKAGE_FIELD},+ "destination": {"node_id": path.target_id, "field": LOOP_LINKAGE_FIELD},})diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex aedcdbcd32..69ef493b4b 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -36199,7 +36199,7 @@"required": ["type", "id"],"title": "ForInvocation","type": "object",- "version": "1.3.0",+ "version": "1.3.1","output": {"$ref": "#/components/schemas/ForInvocationOutput"}@@ -39148,15 +39148,6 @@"title": "Source Prepared Mapping","description": "The map of original graph nodes to prepared nodes"},- "finalized_loop_nodes": {- "items": {- "type": "string"- },- "type": "array",- "uniqueItems": true,- "title": "Finalized Loop Nodes",- "description": "Legacy set of top-level loop source nodes whose final outputs have been materialized"- },"finalized_loop_contexts": {"items": {"prefixItems": [@@ -39218,8 +39209,7 @@"workflow_call_stack","workflow_call_history","prepared_source_mapping",- "source_prepared_mapping",- "finalized_loop_nodes"+ "source_prepared_mapping"],"title": "GraphExecutionState","description": "Tracks source-graph expansion, execution progress, and runtime results."diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 2aba5e48cf..d48bfdc9e3 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -15754,11 +15754,6 @@ export type components = {source_prepared_mapping: {[key: string]: string[];};- /**- * Finalized Loop Nodes- * @description Legacy set of top-level loop source nodes whose final outputs have been materialized- */- finalized_loop_nodes: string[];/*** Finalized Loop Contexts* @description The finalized loop source and parent iteration contextsdiff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex 367704fa95..7b3d2f24de 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -1047,9 +1047,7 @@"src/features/queue/ui/launchpad/QueueStatusBand.tsx","src/workbench/launchpad/home/livePanels.ts"],- "editorForbiddenInitialChunkNames": [- "ag-psd"- ],+ "editorForbiddenInitialChunkNames": ["ag-psd"],"inactiveWidgetGateOwner": "deepen-widget-registry-loading"}}diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex e697ebed67..9549752764 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -25,13 +25,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 194.39999997615814,+ "domContentLoadedMedianMs": 191.60000002384186,"id": "launchpad","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 194.5,- "longestTaskMaxMs": 198,+ "loadMedianMs": 191.9000000357628,+ "longestTaskMaxMs": 194,"owner": "app","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:launchpad",@@ -41,24 +41,24 @@"fontRawBytes": 23664,"imageRawBytes": 0,"largestAssetRawBytes": 746121,- "otherRawBytes": 171238,+ "otherRawBytes": 172015,"requestCount": 37,- "scriptRawBytes": 1662375,+ "scriptRawBytes": 1662409,"scriptRequestCount": 33,- "totalRawBytes": 1859436+ "totalRawBytes": 1860247},"resourceLimits": {"cssRawBytes": 2181,"fontRawBytes": 23901,"imageRawBytes": 0,"largestAssetRawBytes": 753583,- "otherRawBytes": 172951,+ "otherRawBytes": 173736,"requestCount": 37,- "scriptRawBytes": 1678999,+ "scriptRawBytes": 1679034,"scriptRequestCount": 33,- "totalRawBytes": 1878031+ "totalRawBytes": 1878850},- "routeReadyMedianMs": 460.69999998807907,+ "routeReadyMedianMs": 439.5,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "empty"},@@ -85,13 +85,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 190,+ "domContentLoadedMedianMs": 190.5,"id": "launchpad","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 190.19999998807907,- "longestTaskMaxMs": 149,+ "loadMedianMs": 190.70000004768372,+ "longestTaskMaxMs": 162,"owner": "app","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:launchpad",@@ -101,24 +101,24 @@"fontRawBytes": 23664,"imageRawBytes": 0,"largestAssetRawBytes": 746121,- "otherRawBytes": 171238,+ "otherRawBytes": 172015,"requestCount": 37,- "scriptRawBytes": 1662375,+ "scriptRawBytes": 1662409,"scriptRequestCount": 33,- "totalRawBytes": 1859436+ "totalRawBytes": 1860247},"resourceLimits": {"cssRawBytes": 2181,"fontRawBytes": 23901,"imageRawBytes": 0,"largestAssetRawBytes": 753583,- "otherRawBytes": 172951,+ "otherRawBytes": 173736,"requestCount": 37,- "scriptRawBytes": 1678999,+ "scriptRawBytes": 1679034,"scriptRequestCount": 33,- "totalRawBytes": 1878031+ "totalRawBytes": 1878850},- "routeReadyMedianMs": 451.9000000357628,+ "routeReadyMedianMs": 473.9000000357628,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "representative"},@@ -145,15 +145,15 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 183.0999999642372,+ "domContentLoadedMedianMs": 193.69999998807907,"id": "editor-minimal","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 183.29999995231628,- "longestTaskMaxMs": 229,+ "loadMedianMs": 193.9000000357628,+ "longestTaskMaxMs": 251,"owner": "workbench",- "projectSwitchMedianMs": 58.30000001192093,+ "projectSwitchMedianMs": 54.69999998807907,"readyMark": "invokeai:ready:widget:center:preview","remediationTicket": "deepen-widget-registry-loading","resourceBaseline": {@@ -161,24 +161,24 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 746121,- "otherRawBytes": 171238,+ "otherRawBytes": 172015,"requestCount": 121,- "scriptRawBytes": 3455525,+ "scriptRawBytes": 3462443,"scriptRequestCount": 116,- "totalRawBytes": 3808962+ "totalRawBytes": 3816657},"resourceLimits": {"cssRawBytes": 2181,"fontRawBytes": 23901,"imageRawBytes": 157940,"largestAssetRawBytes": 753583,- "otherRawBytes": 172951,+ "otherRawBytes": 173736,"requestCount": 121,- "scriptRawBytes": 3490081,+ "scriptRawBytes": 3497068,"scriptRequestCount": 116,- "totalRawBytes": 3847052+ "totalRawBytes": 3854824},- "routeReadyMedianMs": 726.8999999761581,+ "routeReadyMedianMs": 769.0999999642372,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"},@@ -205,15 +205,15 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 190,+ "domContentLoadedMedianMs": 207.9000000357628,"id": "editor-minimal","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 190.19999998807907,- "longestTaskMaxMs": 252,+ "loadMedianMs": 208.10000002384186,+ "longestTaskMaxMs": 278,"owner": "workbench",- "projectSwitchMedianMs": 86.59999996423721,+ "projectSwitchMedianMs": 80.19999998807907,"readyMark": "invokeai:ready:widget:center:preview","remediationTicket": "deepen-widget-registry-loading","resourceBaseline": {@@ -221,24 +221,24 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 746121,- "otherRawBytes": 171238,+ "otherRawBytes": 172015,"requestCount": 121,- "scriptRawBytes": 3455525,+ "scriptRawBytes": 3462443,"scriptRequestCount": 116,- "totalRawBytes": 3808962+ "totalRawBytes": 3816657},"resourceLimits": {"cssRawBytes": 2181,"fontRawBytes": 23901,"imageRawBytes": 157940,"largestAssetRawBytes": 753583,- "otherRawBytes": 172951,+ "otherRawBytes": 173736,"requestCount": 121,- "scriptRawBytes": 3490081,+ "scriptRawBytes": 3497068,"scriptRequestCount": 116,- "totalRawBytes": 3847052+ "totalRawBytes": 3854824},- "routeReadyMedianMs": 761.6999999880791,+ "routeReadyMedianMs": 803.7999999523163,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"},@@ -247,31 +247,31 @@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 314585,+ "largestAssetRawBytes": 315682,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 481955,+ "scriptRawBytes": 483052,"scriptRequestCount": 7,- "totalRawBytes": 481955+ "totalRawBytes": 483052},"activatedResourceLimits": {"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 317731,+ "largestAssetRawBytes": 318839,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 486775,+ "scriptRawBytes": 487883,"scriptRequestCount": 7,- "totalRawBytes": 486775+ "totalRawBytes": 487883},- "domContentLoadedMedianMs": 186,+ "domContentLoadedMedianMs": 210.5,"id": "editor-canvas",- "layoutAckMedianMs": 5.199999988079071,- "layoutReturnSwitchMedianMs": 56.80000001192093,- "layoutSwitchMedianMs": 133,- "loadMedianMs": 186.29999995231628,- "longestTaskMaxMs": 239,+ "layoutAckMedianMs": 5.399999976158142,+ "layoutReturnSwitchMedianMs": 55.69999998807907,+ "layoutSwitchMedianMs": 132.19999998807907,+ "loadMedianMs": 211.0999999642372,+ "longestTaskMaxMs": 255,"owner": "canvas","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:canvas",@@ -281,24 +281,24 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 746121,- "otherRawBytes": 171238,+ "otherRawBytes": 172015,"requestCount": 128,- "scriptRawBytes": 3937480,+ "scriptRawBytes": 3945495,"scriptRequestCount": 123,- "totalRawBytes": 4290917+ "totalRawBytes": 4299709},"resourceLimits": {"cssRawBytes": 2181,"fontRawBytes": 23901,"imageRawBytes": 157940,"largestAssetRawBytes": 753583,- "otherRawBytes": 172951,+ "otherRawBytes": 173736,"requestCount": 128,- "scriptRawBytes": 3976855,+ "scriptRawBytes": 3984950,"scriptRequestCount": 123,- "totalRawBytes": 4333827+ "totalRawBytes": 4342707},- "routeReadyMedianMs": 1575.0999999642372,+ "routeReadyMedianMs": 1631.199999988079,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "empty"},@@ -307,31 +307,31 @@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 314585,+ "largestAssetRawBytes": 315682,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 481955,+ "scriptRawBytes": 483052,"scriptRequestCount": 7,- "totalRawBytes": 481955+ "totalRawBytes": 483052},"activatedResourceLimits": {"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 317731,+ "largestAssetRawBytes": 318839,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 486775,+ "scriptRawBytes": 487883,"scriptRequestCount": 7,- "totalRawBytes": 486775+ "totalRawBytes": 487883},- "domContentLoadedMedianMs": 190.30000001192093,+ "domContentLoadedMedianMs": 222.80000001192093,"id": "editor-canvas",- "layoutAckMedianMs": 5.900000035762787,- "layoutReturnSwitchMedianMs": 67.40000003576279,- "layoutSwitchMedianMs": 143.5,- "loadMedianMs": 190.4000000357628,- "longestTaskMaxMs": 325,+ "layoutAckMedianMs": 7.699999988079071,+ "layoutReturnSwitchMedianMs": 61.30000001192093,+ "layoutSwitchMedianMs": 167.5,+ "loadMedianMs": 223.10000002384186,+ "longestTaskMaxMs": 366,"owner": "canvas","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:canvas",@@ -341,24 +341,24 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 746121,- "otherRawBytes": 171238,+ "otherRawBytes": 172015,"requestCount": 128,- "scriptRawBytes": 3937480,+ "scriptRawBytes": 3945495,"scriptRequestCount": 123,- "totalRawBytes": 4290917+ "totalRawBytes": 4299709},"resourceLimits": {"cssRawBytes": 2181,"fontRawBytes": 23901,"imageRawBytes": 157940,"largestAssetRawBytes": 753583,- "otherRawBytes": 172951,+ "otherRawBytes": 173736,"requestCount": 128,- "scriptRawBytes": 3976855,+ "scriptRawBytes": 3984950,"scriptRequestCount": 123,- "totalRawBytes": 4333827+ "totalRawBytes": 4342707},- "routeReadyMedianMs": 1656.1000000238419,+ "routeReadyMedianMs": 1793.1000000238419,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "representative"},@@ -367,31 +367,31 @@"cssRawBytes": 15413,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 174186,+ "largestAssetRawBytes": 174131,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 367960,+ "scriptRawBytes": 368048,"scriptRequestCount": 6,- "totalRawBytes": 383373+ "totalRawBytes": 383461},"activatedResourceLimits": {"cssRawBytes": 15568,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 175928,+ "largestAssetRawBytes": 175873,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 371640,+ "scriptRawBytes": 371729,"scriptRequestCount": 6,- "totalRawBytes": 387207+ "totalRawBytes": 387296},- "domContentLoadedMedianMs": 186.19999998807907,+ "domContentLoadedMedianMs": 205.9000000357628,"id": "editor-workflow",- "layoutAckMedianMs": 5.199999988079071,- "layoutReturnSwitchMedianMs": 38.89999997615814,- "layoutSwitchMedianMs": 127.89999997615814,- "loadMedianMs": 186.30000001192093,- "longestTaskMaxMs": 247,+ "layoutAckMedianMs": 6.199999988079071,+ "layoutReturnSwitchMedianMs": 39.80000001192093,+ "layoutSwitchMedianMs": 135.5,+ "loadMedianMs": 206.20000004768372,+ "longestTaskMaxMs": 255,"owner": "workflow","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:workflow",@@ -401,24 +401,24 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 746121,- "otherRawBytes": 171238,+ "otherRawBytes": 172015,"requestCount": 128,- "scriptRawBytes": 3823485,+ "scriptRawBytes": 3830491,"scriptRequestCount": 122,- "totalRawBytes": 4192335+ "totalRawBytes": 4200118},"resourceLimits": {"cssRawBytes": 17748,"fontRawBytes": 23901,"imageRawBytes": 157940,"largestAssetRawBytes": 753583,- "otherRawBytes": 172951,+ "otherRawBytes": 173736,"requestCount": 128,- "scriptRawBytes": 3861720,+ "scriptRawBytes": 3868796,"scriptRequestCount": 122,- "totalRawBytes": 4234259+ "totalRawBytes": 4242120},- "routeReadyMedianMs": 1589.5,+ "routeReadyMedianMs": 1632.9000000357628,"scriptSourceOwnerSet": "editor-workflow-static","stateProfile": "empty"},@@ -427,31 +427,31 @@"cssRawBytes": 15413,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 174186,+ "largestAssetRawBytes": 174131,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 367960,+ "scriptRawBytes": 368048,"scriptRequestCount": 6,- "totalRawBytes": 383373+ "totalRawBytes": 383461},"activatedResourceLimits": {"cssRawBytes": 15568,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 175928,+ "largestAssetRawBytes": 175873,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 371640,+ "scriptRawBytes": 371729,"scriptRequestCount": 6,- "totalRawBytes": 387207+ "totalRawBytes": 387296},- "domContentLoadedMedianMs": 187.30000001192093,+ "domContentLoadedMedianMs": 216.0999999642372,"id": "editor-workflow",- "layoutAckMedianMs": 6.899999976158142,- "layoutReturnSwitchMedianMs": 50.90000003576279,- "layoutSwitchMedianMs": 250.80000001192093,- "loadMedianMs": 187.60000002384186,- "longestTaskMaxMs": 697,+ "layoutAckMedianMs": 10.700000047683716,+ "layoutReturnSwitchMedianMs": 53.299999952316284,+ "layoutSwitchMedianMs": 261.2000000476837,+ "loadMedianMs": 216.29999995231628,+ "longestTaskMaxMs": 663,"owner": "workflow","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:workflow",@@ -461,24 +461,24 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 746121,- "otherRawBytes": 171238,+ "otherRawBytes": 172015,"requestCount": 128,- "scriptRawBytes": 3823485,+ "scriptRawBytes": 3830491,"scriptRequestCount": 122,- "totalRawBytes": 4192335+ "totalRawBytes": 4200118},"resourceLimits": {"cssRawBytes": 17748,"fontRawBytes": 23901,"imageRawBytes": 157940,"largestAssetRawBytes": 753583,- "otherRawBytes": 172951,+ "otherRawBytes": 173736,"requestCount": 128,- "scriptRawBytes": 3861720,+ "scriptRawBytes": 3868796,"scriptRequestCount": 122,- "totalRawBytes": 4234259+ "totalRawBytes": 4242120},- "routeReadyMedianMs": 1784.9000000357628,+ "routeReadyMedianMs": 1773.9000000357628,"scriptSourceOwnerSet": "editor-workflow-static","stateProfile": "representative"},@@ -505,13 +505,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 186.5,+ "domContentLoadedMedianMs": 183,"id": "editor-gallery","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,- "layoutSwitchMedianMs": 40.90000003576279,- "loadMedianMs": 186.80000001192093,- "longestTaskMaxMs": 237,+ "layoutSwitchMedianMs": 41.799999952316284,+ "loadMedianMs": 183.30000001192093,+ "longestTaskMaxMs": 326,"owner": "gallery","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:gallery",@@ -521,24 +521,24 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 746121,- "otherRawBytes": 171238,+ "otherRawBytes": 172015,"requestCount": 121,- "scriptRawBytes": 3455525,+ "scriptRawBytes": 3462443,"scriptRequestCount": 116,- "totalRawBytes": 3808962+ "totalRawBytes": 3816657},"resourceLimits": {"cssRawBytes": 2181,"fontRawBytes": 23901,"imageRawBytes": 157940,"largestAssetRawBytes": 753583,- "otherRawBytes": 172951,+ "otherRawBytes": 173736,"requestCount": 121,- "scriptRawBytes": 3490081,+ "scriptRawBytes": 3497068,"scriptRequestCount": 116,- "totalRawBytes": 3847052+ "totalRawBytes": 3854824},- "routeReadyMedianMs": 1758.199999988079,+ "routeReadyMedianMs": 1807.4000000357628,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"},@@ -565,13 +565,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 193.0999999642372,+ "domContentLoadedMedianMs": 206,"id": "editor-gallery","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,- "layoutSwitchMedianMs": 64.10000002384186,- "loadMedianMs": 193.39999997615814,- "longestTaskMaxMs": 217,+ "layoutSwitchMedianMs": 60.30000001192093,+ "loadMedianMs": 206.19999998807907,+ "longestTaskMaxMs": 304,"owner": "gallery","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:gallery",@@ -581,24 +581,24 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 746121,- "otherRawBytes": 171238,+ "otherRawBytes": 172015,"requestCount": 121,- "scriptRawBytes": 3455525,+ "scriptRawBytes": 3462443,"scriptRequestCount": 116,- "totalRawBytes": 3808962+ "totalRawBytes": 3816657},"resourceLimits": {"cssRawBytes": 2181,"fontRawBytes": 23901,"imageRawBytes": 157940,"largestAssetRawBytes": 753583,- "otherRawBytes": 172951,+ "otherRawBytes": 173736,"requestCount": 121,- "scriptRawBytes": 3490081,+ "scriptRawBytes": 3497068,"scriptRequestCount": 116,- "totalRawBytes": 3847052+ "totalRawBytes": 3854824},- "routeReadyMedianMs": 1886.300000011921,+ "routeReadyMedianMs": 2033.300000011921,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"}@@ -1076,6 +1076,7 @@"source:src/features/gallery/data/queryCache.ts","source:src/features/gallery/data/videoUrls.ts","source:src/features/gallery/index.ts",+ "source:src/features/gallery/picker.ts","source:src/features/gallery/queries.ts","source:src/features/gallery/react.ts","source:src/features/gallery/ui/GalleryBoardCover.tsx",@@ -1098,6 +1099,7 @@"source:src/features/gallery/ui/GallerySplitHandle.tsx","source:src/features/gallery/ui/GalleryStackedLayout.tsx","source:src/features/gallery/ui/GalleryThumbnail.tsx",+ "source:src/features/gallery/ui/GalleryTileFrame.tsx","source:src/features/gallery/ui/GalleryUiContext.tsx","source:src/features/gallery/ui/GalleryUploadButton.tsx","source:src/features/gallery/ui/GalleryViewTabs.tsx",@@ -1113,6 +1115,7 @@"source:src/features/gallery/ui/galleryGridLayout.ts","source:src/features/gallery/ui/galleryMenuIds.ts","source:src/features/gallery/ui/galleryStateView.ts",+ "source:src/features/gallery/ui/picker/GalleryPickerPopover.tsx","source:src/features/gallery/ui/useGalleryActions.ts","source:src/features/gallery/ui/useGalleryData.ts","source:src/features/gallery/ui/useGalleryGridHotkeys.ts",@@ -2059,6 +2062,7 @@"source:src/features/gallery/data/queryCache.ts","source:src/features/gallery/data/videoUrls.ts","source:src/features/gallery/index.ts",+ "source:src/features/gallery/picker.ts","source:src/features/gallery/queries.ts","source:src/features/gallery/react.ts","source:src/features/gallery/ui/GalleryBoardCover.tsx",@@ -2081,6 +2085,7 @@"source:src/features/gallery/ui/GallerySplitHandle.tsx","source:src/features/gallery/ui/GalleryStackedLayout.tsx","source:src/features/gallery/ui/GalleryThumbnail.tsx",+ "source:src/features/gallery/ui/GalleryTileFrame.tsx","source:src/features/gallery/ui/GalleryUiContext.tsx","source:src/features/gallery/ui/GalleryUploadButton.tsx","source:src/features/gallery/ui/GalleryViewTabs.tsx",@@ -2096,6 +2101,7 @@"source:src/features/gallery/ui/galleryGridLayout.ts","source:src/features/gallery/ui/galleryMenuIds.ts","source:src/features/gallery/ui/galleryStateView.ts",+ "source:src/features/gallery/ui/picker/GalleryPickerPopover.tsx","source:src/features/gallery/ui/useGalleryActions.ts","source:src/features/gallery/ui/useGalleryData.ts","source:src/features/gallery/ui/useGalleryGridHotkeys.ts",@@ -3201,6 +3207,7 @@"source:src/features/gallery/data/queryCache.ts","source:src/features/gallery/data/videoUrls.ts","source:src/features/gallery/index.ts",+ "source:src/features/gallery/picker.ts","source:src/features/gallery/queries.ts","source:src/features/gallery/react.ts","source:src/features/gallery/ui/GalleryBoardCover.tsx",@@ -3223,6 +3230,7 @@"source:src/features/gallery/ui/GallerySplitHandle.tsx","source:src/features/gallery/ui/GalleryStackedLayout.tsx","source:src/features/gallery/ui/GalleryThumbnail.tsx",+ "source:src/features/gallery/ui/GalleryTileFrame.tsx","source:src/features/gallery/ui/GalleryUiContext.tsx","source:src/features/gallery/ui/GalleryUploadButton.tsx","source:src/features/gallery/ui/GalleryViewTabs.tsx",@@ -3238,6 +3246,7 @@"source:src/features/gallery/ui/galleryGridLayout.ts","source:src/features/gallery/ui/galleryMenuIds.ts","source:src/features/gallery/ui/galleryStateView.ts",+ "source:src/features/gallery/ui/picker/GalleryPickerPopover.tsx","source:src/features/gallery/ui/useGalleryActions.ts","source:src/features/gallery/ui/useGalleryData.ts","source:src/features/gallery/ui/useGalleryGridHotkeys.ts",@@ -3566,6 +3575,7 @@"source:src/features/workflow/ui/linear/WorkflowLinearPanel.tsx","source:src/features/workflow/ui/linear/formBuilderDnd.ts","source:src/features/workflow/ui/linear/formElementMeta.ts",+ "source:src/features/workflow/ui/loopLinkage.ts","source:src/features/workflow/ui/nodeChrome.tsx","source:src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.ts","source:src/features/workflow/ui/useProjectGraphCommands.ts",diff --git a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.tsindex 1c36115105..992eff22d4 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts@@ -550,7 +550,7 @@ describe('compileProjectGraph', () => {expect(getProjectGraphReadiness(document, { error: null, status: 'loaded', templates: loopTemplates })).toEqual({canInvoke: false,- reasons: ['For loop validation failed: nodes.forLoopLinkageInvalid.'],+ reasons: [{ key: 'nodes.forLoopLinkageInvalid' }],});});});diff --git a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.tsindex 682590c17e..7a78a2035b 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts@@ -9,7 +9,13 @@ import type {import { createWorkflowId } from './document';import { getWorkflowFieldInvalidReason } from './fields';-import { getCanonicalWorkflowEdges, validateForLoopGraph } from './forLoops';+import {+ createForLoopValidationReason,+ ForLoopGraphValidationError,+ getCanonicalWorkflowEdges,+ validateForLoopGraph,+ type ForLoopValidationReason,+} from './forLoops';import { isInvocationNode } from './types';import { hasAnyCycle } from './validation';@@ -57,7 +63,7 @@ const toBoardGraphValue = (value: unknown): unknown => {export interface ProjectGraphReadiness {canInvoke: boolean;- reasons: string[];+ reasons: Array<string | ForLoopValidationReason>;}export interface ProjectGraphReadinessOptions {@@ -86,7 +92,7 @@ export const getProjectGraphReadiness = (return { canInvoke: false, reasons: ['The project graph has no nodes. Add nodes in the Workflow view.'] };}- const reasons: string[] = [];+ const reasons: Array<string | ForLoopValidationReason> = [];const connectedInputs = new Set(canonicalEdges.filter((edge) => executableNodes.some((node) => node.id === edge.destination.node_id))@@ -153,7 +159,7 @@ export const getProjectGraphReadiness = (const forLoopError = validateForLoopGraph(document);if (forLoopError) {- reasons.push(`For loop validation failed: ${forLoopError}.`);+ reasons.push(createForLoopValidationReason(forLoopError));}return { canInvoke: reasons.length === 0, reasons };@@ -175,7 +181,7 @@ export const compileProjectGraph = (const forLoopError = validateForLoopGraph(document);if (forLoopError) {- throw new Error(`For loop validation failed: ${forLoopError}.`);+ throw new ForLoopGraphValidationError(forLoopError);}const executableNodes = getExecutableNodes(document).filter((node) => templates[node.data.type] !== undefined);diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.test.tsindex b57878d1d9..da4dd19172 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts@@ -129,6 +129,20 @@ describe('projectGraphReducer', () => {expect(next.edges).toEqual([createEdge(nodeAId, insertedNode.id)]);});+ it('adds a new node and multiple edges in one action', () => {+ const { doc, nodeAId, nodeBId } = createDocWithNodes();+ const insertedNode = buildInvocationNode(template, { x: 200, y: 0 });+ const firstEdge = createEdge(nodeAId, insertedNode.id);+ const secondEdge = { ...createEdge(nodeBId, insertedNode.id), targetHandle: 'b' };+ const next = projectGraphReducer(doc, {+ edge: [firstEdge, secondEdge],+ node: insertedNode,+ type: 'addNodeAndEdge',+ });++ expect(next.edges).toEqual([firstEdge, secondEdge]);+ });+it('addGraphElements drops colliding node ids and their edges', () => {const { doc, nodeAId, nodeBId } = createDocWithNodes();const existingNode = doc.nodes[0];diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.tsindex cdb49fb7cb..2c862cf38a 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/document.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.ts@@ -285,7 +285,7 @@ const removeNodeFieldElements = (form: WorkflowForm, removedNodeIds: Set<string>export type ProjectGraphAction =| { type: 'addNode'; node: WorkflowNode }- | { type: 'addNodeAndEdge'; node: WorkflowNode; edge: WorkflowEdge }+ | { type: 'addNodeAndEdge'; node: WorkflowNode; edge: WorkflowEdge | WorkflowEdge[] }| { type: 'addGraphElements'; nodes: WorkflowNode[]; edges: WorkflowEdge[] }| { type: 'removeNodes'; nodeIds: string[] }| { type: 'setNodePosition'; nodeId: string; position: XYPosition }@@ -395,7 +395,8 @@ const applyProjectGraphAction = (document: ProjectGraphState, action: ProjectGrareturn document;}- return addEdgeToDocument({ ...document, nodes: [...document.nodes, action.node] }, action.edge);+ const documentWithNode = { ...document, nodes: [...document.nodes, action.node] };+ return (Array.isArray(action.edge) ? action.edge : [action.edge]).reduce(addEdgeToDocument, documentWithNode);}case 'addGraphElements': {if (action.nodes.length === 0 && action.edges.length === 0) {diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fixtures/for-loop-invalid.json b/invokeai/frontend/webv2/src/features/workflow/core/fixtures/for-loop-invalid.jsonnew file mode 100644index 0000000000..64b563fafa--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/core/fixtures/for-loop-invalid.json@@ -0,0 +1,78 @@+{+ "fixture": "invalid",+ "name": "duplicate loop linkage",+ "nodes": [+ {+ "id": "for",+ "type": "invocation",+ "position": { "x": 0, "y": 0 },+ "data": {+ "id": "for",+ "type": "for",+ "version": "1.3.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "isOpen": true,+ "isIntermediate": false,+ "useCache": true,+ "dynamicInputTemplates": {},+ "inputs": { "collection": { "name": "collection", "value": [1] } }+ }+ },+ {+ "id": "return",+ "type": "invocation",+ "position": { "x": 220, "y": 0 },+ "data": {+ "id": "return",+ "type": "for_return",+ "version": "1.3.2",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "isOpen": true,+ "isIntermediate": false,+ "useCache": true,+ "dynamicInputTemplates": {},+ "inputs": {}+ }+ },+ {+ "id": "workflow-return",+ "type": "invocation",+ "position": { "x": 440, "y": 0 },+ "data": {+ "id": "workflow-return",+ "type": "workflow_return",+ "version": "1.0.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "isOpen": true,+ "isIntermediate": false,+ "useCache": true,+ "dynamicInputTemplates": {},+ "inputs": { "values": { "name": "values", "value": [] } }+ }+ }+ ],+ "edges": [+ {+ "id": "linkage-one",+ "type": "loop_linkage",+ "source": "for",+ "sourceHandle": "loop_linkage",+ "target": "return",+ "targetHandle": "loop_linkage"+ },+ {+ "id": "linkage-two",+ "type": "loop_linkage",+ "source": "for",+ "sourceHandle": "loop_linkage",+ "target": "return",+ "targetHandle": "loop_linkage"+ }+ ]+}diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fixtures/for-loop-valid.json b/invokeai/frontend/webv2/src/features/workflow/core/fixtures/for-loop-valid.jsonnew file mode 100644index 0000000000..56b90ae057--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/core/fixtures/for-loop-valid.json@@ -0,0 +1,104 @@+{+ "fixture": "valid",+ "name": "direct for loop",+ "nodes": [+ {+ "id": "for",+ "type": "invocation",+ "position": { "x": 0, "y": 0 },+ "data": {+ "id": "for",+ "type": "for",+ "version": "1.3.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "isOpen": true,+ "isIntermediate": false,+ "useCache": true,+ "dynamicInputTemplates": {},+ "inputs": { "collection": { "name": "collection", "value": [1, 2] } }+ }+ },+ {+ "id": "body",+ "type": "invocation",+ "position": { "x": 220, "y": 0 },+ "data": {+ "id": "body",+ "type": "integer",+ "version": "1.0.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "isOpen": true,+ "isIntermediate": false,+ "useCache": true,+ "dynamicInputTemplates": {},+ "inputs": { "value": { "name": "value", "value": 0 } }+ }+ },+ {+ "id": "return",+ "type": "invocation",+ "position": { "x": 440, "y": 0 },+ "data": {+ "id": "return",+ "type": "for_return",+ "version": "1.3.2",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "isOpen": true,+ "isIntermediate": false,+ "useCache": true,+ "dynamicInputTemplates": {},+ "inputs": {}+ }+ },+ {+ "id": "workflow-return",+ "type": "invocation",+ "position": { "x": 660, "y": 0 },+ "data": {+ "id": "workflow-return",+ "type": "workflow_return",+ "version": "1.0.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "isOpen": true,+ "isIntermediate": false,+ "useCache": true,+ "dynamicInputTemplates": {},+ "inputs": { "values": { "name": "values", "value": [] } }+ }+ }+ ],+ "edges": [+ {+ "id": "iteration",+ "type": "default",+ "source": "for",+ "sourceHandle": "item",+ "target": "body",+ "targetHandle": "value"+ },+ {+ "id": "body-output",+ "type": "default",+ "source": "body",+ "sourceHandle": "value",+ "target": "return",+ "targetHandle": "output"+ },+ {+ "id": "linkage",+ "type": "loop_linkage",+ "source": "for",+ "sourceHandle": "loop_linkage",+ "target": "return",+ "targetHandle": "loop_linkage"+ }+ ]+}diff --git a/invokeai/frontend/webv2/src/features/workflow/core/forLoops.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/forLoops.test.tsindex f069f199f4..46a28fb923 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/forLoops.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/forLoops.test.ts@@ -3,9 +3,12 @@ import { describe, expect, it } from 'vitest';import type { WorkflowEdge, WorkflowInvocationNode } from './types';import { createProjectGraph } from './document';+import invalidFixture from './fixtures/for-loop-invalid.json';+import validFixture from './fixtures/for-loop-valid.json';import {getCanonicalWorkflowEdges,getForLoopBodyBoundaries,+ createForLoopValidationReason,localizeForLoopValidationReason,shouldAddForReturnLoopLinkage,validateForLoopGraph,@@ -55,7 +58,14 @@ const linkedGraph = () => {};describe('For/ForReturn graph contracts', () => {- it('localizes scheduler validation reasons without changing unrelated messages', () => {+ it.each([+ [validFixture, null],+ [invalidFixture, 'nodes.forLoopLinkageDuplicate'],+ ] as const)('matches the shared backend validation fixture: %s', (fixture, expectedError) => {+ expect(validateForLoopGraph(fixture as never)).toBe(expectedError);+ });++ it('localizes structured scheduler validation reasons without changing unrelated messages', () => {const translate = (key: string) =>({'nodes.forLoopFinalOutputInBody': 'Final outputs cannot feed the loop body',@@ -63,7 +73,7 @@ describe('For/ForReturn graph contracts', () => {})[key] ?? key;expect(- localizeForLoopValidationReason('For loop validation failed: nodes.forLoopFinalOutputInBody.', translate)+ localizeForLoopValidationReason(createForLoopValidationReason('nodes.forLoopFinalOutputInBody'), translate)).toBe('For loop validation failed: Final outputs cannot feed the loop body.');expect(localizeForLoopValidationReason('The graph contains a cycle.', translate)).toBe('The graph contains a cycle.'diff --git a/invokeai/frontend/webv2/src/features/workflow/core/forLoops.ts b/invokeai/frontend/webv2/src/features/workflow/core/forLoops.tsindex df6f75104f..9bda02f515 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/forLoops.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/forLoops.ts@@ -5,24 +5,7 @@ import { createWorkflowGraphIndex } from './graphIndex';import { isInvocationNode } from './types';import { LOOP_LINKAGE_FIELD } from './validation';-export type ForLoopGraphError =- | 'nodes.forLoopMissingIterationOutput'- | 'nodes.forLoopReturnCount'- | 'nodes.forLoopUnterminatedBody'- | 'nodes.forLoopNestedUnsupported'- | 'nodes.forLoopIterateUnsupported'- | 'nodes.forLoopIteratorInputUnsupported'- | 'nodes.forLoopFinalOutputInBody'- | 'nodes.forLoopBodyEscape'- | 'nodes.forLoopInputCount'- | 'nodes.forReturnInputCount'- | 'nodes.forLoopLinkageMissing'- | 'nodes.forLoopLinkageInvalid'- | 'nodes.forLoopLinkageDuplicate'- | 'nodes.forReturnOwnership';--const FOR_LOOP_VALIDATION_PREFIX = 'For loop validation failed: ';-const FOR_LOOP_GRAPH_ERRORS: ReadonlySet<string> = new Set([+const FOR_LOOP_GRAPH_ERROR_CODES = ['nodes.forLoopMissingIterationOutput','nodes.forLoopReturnCount','nodes.forLoopUnterminatedBody',@@ -37,19 +20,35 @@ const FOR_LOOP_GRAPH_ERRORS: ReadonlySet<string> = new Set(['nodes.forLoopLinkageInvalid','nodes.forLoopLinkageDuplicate','nodes.forReturnOwnership',-]);+] as const;-export const localizeForLoopValidationReason = (reason: string, translate: (key: string) => string): string => {- if (!reason.startsWith(FOR_LOOP_VALIDATION_PREFIX) || !reason.endsWith('.')) {- return reason;+export type ForLoopGraphError = (typeof FOR_LOOP_GRAPH_ERROR_CODES)[number];++export interface ForLoopValidationReason {+ key: ForLoopGraphError;+}++export const createForLoopValidationReason = (key: ForLoopGraphError): ForLoopValidationReason => ({ key });++export class ForLoopGraphValidationError extends Error {+ readonly reason: ForLoopValidationReason;++ constructor(key: ForLoopGraphError) {+ super(`For loop validation failed: ${key}.`);+ this.name = 'ForLoopGraphValidationError';+ this.reason = createForLoopValidationReason(key);}+}- const error = reason.slice(FOR_LOOP_VALIDATION_PREFIX.length, -1);- if (!FOR_LOOP_GRAPH_ERRORS.has(error)) {+export const localizeForLoopValidationReason = (+ reason: string | ForLoopValidationReason,+ translate: (key: string) => string+): string => {+ if (typeof reason === 'string') {return reason;}- return `${translate('nodes.forLoopValidationFailed')}: ${translate(error)}.`;+ return `${translate('nodes.forLoopValidationFailed')}: ${translate(reason.key)}.`;};export type LoopBodyBoundaryStatus =diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsxindex e2a7a2f56e..adde409943 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx@@ -1,3 +1,4 @@+import type { ForLoopValidationReason } from '@features/workflow/core/forLoops';import type { ProjectGraphState } from '@features/workflow/core/types';import type { ReactNode } from 'react';@@ -41,7 +42,7 @@ export interface WorkflowReadPort<Snapshot> {export interface WorkflowGraphPreviewPort {getRoute(sourceId?: WorkflowInvocationSourceId- ): { canInvoke: boolean; label: string; validationMessage?: string } | null;+ ): { canInvoke: boolean; label: string; validationMessage?: string | ForLoopValidationReason } | null;invoke(sourceId?: WorkflowInvocationSourceId): Promise<boolean>;focusSource(sourceId?: WorkflowInvocationSourceId): void; // reveal the source's widget (provenance links)openWorkflowEditor(): void; // reveal the workflow editor widgetdiff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsxindex 7a374e7542..119a113cdd 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx@@ -377,12 +377,6 @@ export const WorkflowDialogHost = () => {: ('default' as const),};- editGraph({- edge,- node,- type: 'addNodeAndEdge',- });-const currentGraph = projectStore.getSnapshot().projectGraph;const sourceNode = currentGraph.nodes.find((candidate) => candidate.id === addNodeConnection.sourceNodeId);const resolvedSource =@@ -399,19 +393,19 @@ export const WorkflowDialogHost = () => {currentGraph.edges);+ const edges = [edge];if (shouldAddLoopLinkage && resolvedSourceNode?.type === 'invocation') {- editGraph({- edge: {- id: createWorkflowId('edge'),- source: resolvedSourceNode.id,- sourceHandle: LOOP_LINKAGE_FIELD,- target: node.id,- targetHandle: LOOP_LINKAGE_FIELD,- type: 'loop_linkage',- },- type: 'addEdge',+ edges.push({+ id: createWorkflowId('edge'),+ source: resolvedSourceNode.id,+ sourceHandle: LOOP_LINKAGE_FIELD,+ target: node.id,+ targetHandle: LOOP_LINKAGE_FIELD,+ type: 'loop_linkage',});}++ editGraph({ edge: edges, node, type: 'addNodeAndEdge' });return;}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.tsindex 287db4fbcc..dc395f6840 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts@@ -1,4 +1,5 @@import type { ProjectGraphAction } from '@features/workflow/core/document';+import type { ForLoopValidationReason } from '@features/workflow/core/forLoops';import type { ProjectGraphState, XYPosition } from '@features/workflow/core/types';export type WorkflowRegion = 'left' | 'right' | 'bottom' | 'center' | 'dialog' | 'popover' | 'floating';@@ -109,7 +110,7 @@ export interface GraphPreviewSourceState {graph: WorkflowPreviewGraph | null;/** Human-readable result destination (e.g. "Gallery"), set for every source by the builder. */destinationLabel: string | null;- invalidReasons: string[];+ invalidReasons: Array<string | ForLoopValidationReason>;isLive: boolean;notices: GraphPreviewNotice[];positionHints?: Record<string, XYPosition>;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.tsxindex 338cb60067..bce69e9ef9 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/AddNodeDialog.tsx@@ -1,5 +1,5 @@import type { InvocationTemplate, InvocationTemplates } from '@features/workflow/contracts';-import type { WorkflowNode } from '@features/workflow/core/types';+import type { WorkflowEdge, WorkflowNode } from '@features/workflow/core/types';import type { AddNodeConnectionFilter } from '@features/workflow/ui/workflowUiStore';import { Badge, Box, Dialog, HStack, Icon, Input, Portal, ScrollArea, Stack, Text } from '@chakra-ui/react';@@ -79,7 +79,7 @@ const isCompatibleConnectionTemplate = (const isForIterationOutputConnection = (connectionFilter: AddNodeConnectionFilter | null,nodes: WorkflowNode[],- edges: Parameters<typeof resolveConnectorSource>[2],+ edges: WorkflowEdge[],templates: InvocationTemplates): boolean => {if (!connectionFilter || connectionFilter.kind !== 'source') {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/LoopBodyBoundaryOverlay.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/LoopBodyBoundaryOverlay.tsxindex 9b95f9e5d3..3151b585ca 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/LoopBodyBoundaryOverlay.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/LoopBodyBoundaryOverlay.tsx@@ -2,7 +2,7 @@ import type { WorkflowEdge, WorkflowNode } from '@features/workflow/contracts';import { Box, Text } from '@chakra-ui/react';import { getForLoopBodyBoundaries, type LoopBodyBoundaryStatus } from '@features/workflow/utility';-import { useNodes, useReactFlow, ViewportPortal } from '@xyflow/react';+import { useReactFlow, ViewportPortal } from '@xyflow/react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -11,13 +11,13 @@ import type { WorkflowFlowEdge, WorkflowFlowNode } from './flowAdapters';const BOUNDARY_PADDING = 24;const getStatusColor = (status: LoopBodyBoundaryStatus) =>- status === 'complete' ? { border: 'green.400', text: 'green.200' } : { border: 'orange.400', text: 'orange.200' };+ status === 'complete'+ ? { border: 'border.success', text: 'fg.success' }+ : { border: 'border.warning', text: 'fg.warning' };-export const LoopBodyBoundaryOverlay = ({ edges }: { edges: WorkflowEdge[] }) => {+export const LoopBodyBoundaryOverlay = ({ nodes, edges }: { nodes: WorkflowNode[]; edges: WorkflowEdge[] }) => {const { t } = useTranslation();- const flowNodes = useNodes<WorkflowFlowNode>();const { getNodesBounds } = useReactFlow<WorkflowFlowNode, WorkflowFlowEdge>();- const nodes = useMemo<WorkflowNode[]>(() => flowNodes.map((node) => node.data.documentNode), [flowNodes]);const boundaries = useMemo(() => getForLoopBodyBoundaries(nodes, edges), [edges, nodes]);return (diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsxindex e13ca0fa54..b0809fcb51 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx@@ -1079,7 +1079,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {size={1.5}variant={BackgroundVariant.Dots}/>- <LoopBodyBoundaryOverlay edges={projectGraph.edges} />+ <LoopBodyBoundaryOverlay edges={projectGraph.edges} nodes={projectGraph.nodes} /><EditorToolbarnodeOpacity={nodeOpacity}tool={tool}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.tsindex eb88ca2107..c32e29c749 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.ts@@ -15,6 +15,7 @@ import type { Edge as FlowEdge, Node as FlowNode } from '@xyflow/react';import type { CSSProperties } from 'react';import { isExecutableInvocationType } from '@features/workflow/graph';+import { LOOP_LINKAGE_STROKE } from '@features/workflow/ui/loopLinkage';import {CONNECTOR_INPUT_HANDLE,CONNECTOR_OUTPUT_HANDLE,@@ -347,19 +348,22 @@ export const getWorkflowEdgeData = (templates?: InvocationTemplates,index: WorkflowGraphIndex = createWorkflowGraphIndex(document.nodes, document.edges)): WorkflowEdgeData => {+ if (edge.type === 'loop_linkage') {+ return {+ fieldTypeLabel: 'Loop linkage',+ isLoopLinkage: true,+ pathType,+ stroke: LOOP_LINKAGE_STROKE,+ strokeDasharray: '6 4',+ strokeWidth: 2,+ tooltip: 'Loop linkage',+ };+ }+const fieldType = getWorkflowEdgeFieldType(document, templates, edge, index);if (!fieldType) {- return edge.type === 'loop_linkage'- ? {- ...UNKNOWN_EDGE_DATA(pathType),- fieldTypeLabel: 'Loop linkage',- isLoopLinkage: true,- stroke: '#22c55e',- strokeDasharray: '6 4',- tooltip: 'Loop linkage',- }- : UNKNOWN_EDGE_DATA(pathType);+ return UNKNOWN_EDGE_DATA(pathType);}const fieldTypeLabel = getFieldTypeLabel(fieldType);@@ -371,18 +375,6 @@ export const getWorkflowEdgeData = (? '8 3 2 3': undefined;- if (edge.type === 'loop_linkage') {- return {- fieldTypeLabel: 'Loop linkage',- isLoopLinkage: true,- pathType,- stroke: '#22c55e',- strokeDasharray: '6 4',- strokeWidth: 2,- tooltip: 'Loop linkage',- };- }-return {fieldTypeLabel,pathType,diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsxindex 67f5d304bb..9b17def016 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx@@ -236,7 +236,7 @@ export const GraphPreviewDialog = ({{hasInvalidReasons ? (<InvalidBanner><Text>- {t('graphPreview.invalidTitle')} {source.invalidReasons[0]}+ {t('graphPreview.invalidTitle')} {localizeForLoopValidationReason(source.invalidReasons[0], t)}</Text></InvalidBanner>) : null}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsxindex c4a5915d5b..3cad5d86f8 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsx@@ -14,6 +14,7 @@ import { isInvocationNode, type ProjectGraphState, type XYPosition } from '@featimport { getCanonicalWorkflowEdges } from '@features/workflow/core/forLoops';import { getLayeredPositions } from '@features/workflow/core/graphLayout';import '@xyflow/react/dist/style.css';+import { LOOP_LINKAGE_STROKE } from '@features/workflow/ui/loopLinkage';import { useWorkflowPreferencesSelector } from '@features/workflow/ui/WorkflowUiContext';import { Background, BackgroundVariant, Handle, Position, ReactFlow } from '@xyflow/react';import { useCallback, useId, useMemo } from 'react';@@ -141,7 +142,9 @@ const toPreviewEdges = (graph: WorkflowPreviewGraph): FlowEdge[] =>source: edge.sourceNodeId,target: edge.targetNodeId,type: 'default',- ...(edge.type === 'loop_linkage' ? { style: { stroke: '#22c55e', strokeDasharray: '6 4', strokeWidth: 2 } } : {}),+ ...(edge.type === 'loop_linkage'+ ? { style: { stroke: LOOP_LINKAGE_STROKE, strokeDasharray: '6 4', strokeWidth: 2 } }+ : {}),}));export const GraphPreviewFlow = ({diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.tsindex 795a1f6138..266c8df183 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts@@ -1,5 +1,6 @@import type { GraphPreviewSourceState, InvocationTemplates, ProjectGraphState } from '@features/workflow/contracts';+import { ForLoopGraphValidationError } from '@features/workflow/core/forLoops';import { compileProjectGraph } from '@features/workflow/graph';/**@@ -36,7 +37,13 @@ export const buildLibraryGraphPreviewSource = (return {destinationLabel: null,graph: null,- invalidReasons: [error instanceof Error ? error.message : String(error)],+ invalidReasons: [+ error instanceof ForLoopGraphValidationError+ ? error.reason+ : error instanceof Error+ ? error.message+ : String(error),+ ],isLive: false,notices: [],summaryRows: [],diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/loopLinkage.ts b/invokeai/frontend/webv2/src/features/workflow/ui/loopLinkage.tsnew file mode 100644index 0000000000..cfd62903e2--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/loopLinkage.ts@@ -0,0 +1,2 @@+/** Shared stroke used for loop-linkage edges in editable and preview graphs. */+export const LOOP_LINKAGE_STROKE = '#22c55e';diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.tsindex 7b22fddf8e..ca0e15d739 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts@@ -1,5 +1,6 @@import type { ModelConfig } from '@features/models';import type { ProjectGraphState } from '@features/workflow/contracts';+import type { ForLoopValidationReason } from '@features/workflow/utility';import type { CanvasLayerContract } from '@workbench/canvas-engine/api';import type {InvocationMode,@@ -202,7 +203,7 @@ export const resolveInvocationRouteInput = (// templates store so the result stays live.const projectGraphReadiness =sourceId === 'workflow' ? getProjectGraphReadiness(input.projectGraph, getInvocationTemplatesSnapshot()) : null;- const validationReasons: string[] = [];+ const validationReasons: Array<string | ForLoopValidationReason> = [];if (!isInvocationSourceAvailable(sourceId)) {validationReasons.push(`${getSourceLabel(sourceId)} is not an available invocation source.`);diff --git a/invokeai/frontend/webv2/src/workbench/invocationContracts.ts b/invokeai/frontend/webv2/src/workbench/invocationContracts.tsindex 74c6fb093a..095190a739 100644--- a/invokeai/frontend/webv2/src/workbench/invocationContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/invocationContracts.ts@@ -1,3 +1,5 @@+import type { ForLoopValidationReason } from '@features/workflow/utility';+export type InvocationSourceId = 'generate' | 'workflow' | 'upscale' | 'video' | 'canvas';export type InvocationMode = 'global' | 'dialog';@@ -16,9 +18,9 @@ export interface ResolvedInvocationRoute extends InvocationRoute {sourceValid: boolean;destinationValid: boolean;/** The top validation issue, shown on the fixed Invoke control's secondary line. */- validationMessage?: string;+ validationMessage?: string | ForLoopValidationReason;/** Every reason the route cannot run right now (legacy `reasonsWhyCannotEnqueue` equivalent). */- validationReasons: string[];+ validationReasons: Array<string | ForLoopValidationReason>;}export interface InvocationControllerState extends InvocationRoute {diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.tsindex 2d885884a8..2fd6a2f6e4 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts@@ -12,6 +12,7 @@ import {} from '@features/generation/settings';import { ensureModelsLoaded, useModelsSelector } from '@features/models';import { useInvocationTemplatesSelector } from '@features/workflow/react';+import { localizeForLoopValidationReason } from '@features/workflow/utility';import { useMountEffect } from '@platform/react/useMountEffect';import { submitActiveInvocation } from '@workbench/activeInvocationSubmission';import { useIsCanvasInvocationPreparing } from '@workbench/canvasInvocationPreparation';@@ -31,33 +32,6 @@ import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';const selectInvocationRouteInput = createInvocationRouteInputSelector();-const FOR_LOOP_VALIDATION_PREFIX = 'For loop validation failed: ';-const FOR_LOOP_GRAPH_ERRORS: ReadonlySet<string> = new Set([- 'nodes.forLoopMissingIterationOutput',- 'nodes.forLoopReturnCount',- 'nodes.forLoopUnterminatedBody',- 'nodes.forLoopNestedUnsupported',- 'nodes.forLoopIterateUnsupported',- 'nodes.forLoopIteratorInputUnsupported',- 'nodes.forLoopFinalOutputInBody',- 'nodes.forLoopBodyEscape',- 'nodes.forLoopInputCount',- 'nodes.forReturnInputCount',- 'nodes.forLoopLinkageMissing',- 'nodes.forLoopLinkageInvalid',- 'nodes.forLoopLinkageDuplicate',- 'nodes.forReturnOwnership',-]);-const localizeForLoopValidationReason = (reason: string, translate: (key: string) => string): string => {- if (!reason.startsWith(FOR_LOOP_VALIDATION_PREFIX) || !reason.endsWith('.')) {- return reason;- }-- const error = reason.slice(FOR_LOOP_VALIDATION_PREFIX.length, -1);- return FOR_LOOP_GRAPH_ERRORS.has(error)- ? `${translate('nodes.forLoopValidationFailed')}: ${translate(error)}.`- : reason;-};const areTypeIdSetsEqual = (left: ReadonlySet<WidgetTypeId>, right: ReadonlySet<WidgetTypeId>): boolean =>left.size === right.size && [...left].every((typeId) => right.has(typeId));diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.tsindex 2828cca9d5..3ee9e6fd1b 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts@@ -13,6 +13,7 @@ import type { TFunction } from 'i18next';import { compileGeneratePreviewGraph, getGenerateNodeProvenance } from '@features/generation/preview';import { compileProjectGraph } from '@features/workflow/graph';+import { ForLoopGraphValidationError } from '@features/workflow/utility';import { getDestinationLabel } from '@workbench/invocation';import { getProjectWidgetValues } from '@workbench/widgetState';@@ -72,8 +73,20 @@ const buildWorkflowSource = (const graph = compileProjectGraph(project.projectGraph, templates.templates);return { ...EMPTY_SOURCE_BASE, graph, isLive: true, positionHints };- } catch {- return { ...EMPTY_SOURCE_BASE, graph: null, isLive: true, positionHints };+ } catch (error) {+ return {+ ...EMPTY_SOURCE_BASE,+ graph: null,+ invalidReasons: [+ error instanceof ForLoopGraphValidationError+ ? error.reason+ : error instanceof Error+ ? error.message+ : String(error),+ ],+ isLive: true,+ positionHints,+ };}};diff --git a/tests/app/services/session_processor/test_for_loop_processor.py b/tests/app/services/session_processor/test_for_loop_processor.pyindex 178caeb983..355a56a53b 100644--- a/tests/app/services/session_processor/test_for_loop_processor.py+++ b/tests/app/services/session_processor/test_for_loop_processor.py@@ -84,6 +84,7 @@ class _Events:def __init__(self) -> None:self.started: list[str] = []self.completed: list[str] = []+ self.completed_outputs: list[tuple[str, BaseInvocationOutput]] = []self.errors: list[tuple[str, str, str]] = []def emit_invocation_started(self, queue_item, invocation) -> None:@@ -91,6 +92,7 @@ class _Events:def emit_invocation_complete(self, invocation, queue_item, output) -> None:self.completed.append(invocation.id)+ self.completed_outputs.append((invocation.id, output.model_copy(deep=True)))def emit_invocation_error(self, queue_item, invocation, error_type, error_message, error_traceback) -> None:self.errors.append((invocation.id, error_type, error_message))@@ -294,11 +296,19 @@ def test_processor_completes_for_loop_in_worker_thread(monkeypatch: pytest.Monkeassert not queue.failed_item_idsassert item.session.is_complete()completed_source_ids = _completed_source_ids(item, events)- assert completed_source_ids.count("for") == 3+ assert completed_source_ids.count("for") == 4assert completed_source_ids.count("body") == 3assert completed_source_ids.count("return") == 3assert completed_source_ids[-1] == "after"+ final_for_outputs = [+ output+ for exec_id, output in events.completed_outputs+ if item.session.prepared_source_mapping[exec_id] == "for"+ and getattr(output, "output_collection", None) == [1, 2, 3]+ ]+ assert final_for_outputs+def test_processor_cancellation_event_stops_for_loop_without_final_output(monkeypatch: pytest.MonkeyPatch) -> None:item = _build_item()@@ -328,7 +338,7 @@ def test_processor_cancellation_event_stops_for_loop_without_final_output(monkeyassert completed_source_ids.count("return") == 1assert "after" not in completed_source_idsassert "after" not in item.session.source_prepared_mapping- assert not item.session.finalized_loop_nodes+ assert not item.session.finalized_loop_contextsdef test_processor_body_exception_fails_for_item_without_after_loop_execution(monkeypatch: pytest.MonkeyPatch) -> None:@@ -354,4 +364,4 @@ def test_processor_body_exception_fails_for_item_without_after_loop_execution(moassert completed_source_ids.count("return") == 1assert "after" not in completed_source_idsassert "after" not in item.session.source_prepared_mapping- assert not item.session.finalized_loop_nodes+ assert not item.session.finalized_loop_contextsdiff --git a/tests/app/services/session_processor/test_for_loop_processor_sqlite.py b/tests/app/services/session_processor/test_for_loop_processor_sqlite.pyindex 47ae6096c1..77ff58ffd9 100644--- a/tests/app/services/session_processor/test_for_loop_processor_sqlite.py+++ b/tests/app/services/session_processor/test_for_loop_processor_sqlite.py@@ -250,7 +250,7 @@ def test_processor_sqlite_queue_nested_iterate_for_cleanup(assert returns_seen == 2else:assert "after" not in queue_item.session.source_prepared_mapping- assert not queue_item.session.finalized_loop_nodes+ assert ("for", ()) not in queue_item.session.finalized_loop_contextsif outcome == "canceled":assert returns_seen == 1assert status_handler_called.wait(timeout=5)@@ -344,7 +344,7 @@ def test_processor_sqlite_queue_nested_for_cleanup(assert inner_returns_seen == 4else:assert "after" not in queue_item.session.source_prepared_mapping- assert not queue_item.session.finalized_loop_nodes+ assert ("outer_for", ()) not in queue_item.session.finalized_loop_contextsassert not any(getattr(queue_item.session.results.get(exec_id), "output_collection", [])for exec_id in queue_item.session.source_prepared_mapping.get("outer_for", [])diff --git a/tests/app/services/shared/test_for_scheduler_performance.py b/tests/app/services/shared/test_for_scheduler_performance.pynew file mode 100644index 0000000000..aefb387b88--- /dev/null+++ b/tests/app/services/shared/test_for_scheduler_performance.py@@ -0,0 +1,52 @@+"""Regression coverage for scheduler overhead with trivial loop bodies."""++import time+from unittest.mock import Mock++import pytest++from invokeai.app.invocations.collections import RangeInvocation+from invokeai.app.invocations.loops import ForInvocation, ForReturnInvocation+from invokeai.app.services.shared.graph import CollectInvocation, Graph, GraphExecutionState, IterateInvocation+from tests.test_nodes import AnyTypeTestInvocation, create_edge, create_loop_linkage++[email protected]("loop_type", ["for", "iterate"])+def test_trivial_loop_scheduler_overhead(loop_type: str) -> None:+ graph = Graph()+ graph.add_node(RangeInvocation(id="range", start=0, stop=600))+ graph.add_node(ForInvocation(id="loop") if loop_type == "for" else IterateInvocation(id="loop"))+ graph.add_node(AnyTypeTestInvocation(id="body"))+ graph.add_edge(create_edge("range", "collection", "loop", "collection"))+ graph.add_edge(create_edge("loop", "item", "body", "value"))+ if loop_type == "for":+ graph.add_node(ForReturnInvocation(id="return"))+ graph.add_edge(create_edge("body", "value", "return", "output"))+ graph.add_edge(create_loop_linkage("loop", "return"))+ else:+ graph.add_node(CollectInvocation(id="collect"))+ graph.add_edge(create_edge("body", "value", "collect", "item"))+ state = GraphExecutionState(graph=graph)+ context = Mock()+ started = time.perf_counter()+ while (node := state.next()) is not None:+ state.complete(node.id, node.invoke(context))+ elapsed = time.perf_counter() - started+ assert state.is_complete()+ # Generous headroom for shared CI hosts; the reported quadratic For regression took six seconds.+ assert elapsed < 4, f"{loop_type}: {elapsed:.3f}s for 600 items"+++def test_completion_predicate_preserves_durable_state() -> None:+ graph = Graph()+ graph.add_node(AnyTypeTestInvocation(id="value", value=1))+ state = GraphExecutionState(graph=graph)+ node = state.next()+ assert node is not None+ state.complete(node.id, node.invoke(Mock()))+ # A restored session may have completed executions without the derived source history yet.+ state.executed.discard("value")+ state.executed_history.clear()+ before = state.model_dump_json()+ assert state.is_complete()+ assert state.model_dump_json() == beforediff --git a/tests/app/services/test_for_loop_session_runner.py b/tests/app/services/test_for_loop_session_runner.pyindex 39f0e14cf1..a3db4d493c 100644--- a/tests/app/services/test_for_loop_session_runner.py+++ b/tests/app/services/test_for_loop_session_runner.py@@ -187,7 +187,8 @@ def _build_queue_item(session: GraphExecutionState) -> SimpleNamespace:def _completed_source_ids(events: _DummyEvents, session: GraphExecutionState) -> list[str]:- return [session.prepared_source_mapping[invocation.id] for invocation, _queue_item, _output in events.completed]+ # Final For output updates reuse the execution ID; count executions separately from output updates.+ return [session.prepared_source_mapping[exec_id] for exec_id in dict.fromkeys(i.id for i, _, _ in events.completed)]def test_session_runner_completes_for_loop_and_persists_final_outputs(monkeypatch: pytest.MonkeyPatch) -> None:@@ -248,7 +249,7 @@ def test_session_runner_cancellation_stops_for_loop_without_releasing_final_outpassert completed_source_ids.count("body") == 1assert completed_source_ids.count("return") == 1assert "after" not in session.source_prepared_mapping- assert "for" not in session.finalized_loop_nodes+ assert ("for", ()) not in session.finalized_loop_contextsassert len(session.source_prepared_mapping["for"]) == 2assert sum(exec_id in session.results for exec_id in session.source_prepared_mapping["for"]) == 1assert not any(@@ -282,7 +283,7 @@ def test_session_runner_body_exception_fails_and_cleans_up_for_loop(monkeypatch:assert completed_source_ids.count("body") == 1assert completed_source_ids.count("return") == 1assert "after" not in session.source_prepared_mapping- assert "for" not in session.finalized_loop_nodes+ assert ("for", ()) not in session.finalized_loop_contextsassert len(session.source_prepared_mapping["for"]) == 2assert session.next() is Noneassert not any(@@ -317,7 +318,7 @@ def test_session_runner_nested_iterate_cancellation_stops_outer_loop(monkeypatchassert completed_source_ids.count("collect") == 1assert completed_source_ids.count("return") == 1assert "after" not in session.source_prepared_mapping- assert not session.finalized_loop_nodes+ assert not session.finalized_loop_contextsdef test_session_runner_nested_for_cancellation_stops_outer_loop_without_final_outputs(@@ -352,7 +353,7 @@ def test_session_runner_nested_for_cancellation_stops_outer_loop_without_final_oassert completed_source_ids.count("inner_return") == 1assert "outer_return" not in completed_source_idsassert "after" not in session.source_prepared_mapping- assert not session.finalized_loop_nodes+ assert not session.finalized_loop_contextsassert len(session.source_prepared_mapping["inner_for"]) == 2assert sum(exec_id in session.results for exec_id in session.source_prepared_mapping["inner_for"]) == 1assert len(session.source_prepared_mapping["inner_body"]) == 2@@ -383,7 +384,7 @@ def test_session_runner_nested_iterate_body_exception_fails_outer_loop(monkeypatassert completed_source_ids.count("iterate") == 2assert completed_source_ids.count("body") == 1assert "after" not in session.source_prepared_mapping- assert not session.finalized_loop_nodes+ assert not session.finalized_loop_contextsdef test_session_runner_completes_nested_for_and_releases_outer_final_outputs(@@ -521,4 +522,4 @@ def test_session_runner_nested_for_body_exception_fails_without_outer_final_outpassert completed_source_ids.count("inner_body") == 2assert completed_source_ids.count("inner_return") == 2assert "after" not in session.source_prepared_mapping- assert not session.finalized_loop_nodes+ assert ("outer_for", ()) not in session.finalized_loop_contextsdiff --git a/tests/app/services/test_workflow_graph_builder.py b/tests/app/services/test_workflow_graph_builder.pyindex 697951462f..956e8957d7 100644--- a/tests/app/services/test_workflow_graph_builder.py+++ b/tests/app/services/test_workflow_graph_builder.py@@ -1,6 +1,9 @@+import json+from pathlib import Path+import pytest-from invokeai.app.services.shared.graph import Graph+from invokeai.app.services.shared.graph import Graph, InvalidEdgeErrorfrom invokeai.app.services.shared.workflow_graph_builder import (InvalidWorkflowInputError,UnsupportedWorkflowNodeError,@@ -104,6 +107,31 @@ def _build_named_return_edges(source: str, source_handle: str):]+FOR_LOOP_FIXTURE_DIR = (+ Path(__file__).parents[3]+ / "invokeai"+ / "frontend"+ / "webv2"+ / "src"+ / "features"+ / "workflow"+ / "core"+ / "fixtures"+)++[email protected]("fixture_path", sorted(FOR_LOOP_FIXTURE_DIR.glob("for-loop-*.json")))+def test_for_loop_fixtures_have_matching_backend_validation(fixture_path: Path):+ fixture = json.loads(fixture_path.read_text())+ graph = build_graph_from_workflow(fixture)++ if fixture["fixture"] == "valid":+ graph.validate_self()+ else:+ with pytest.raises(InvalidEdgeError):+ graph.validate_self()++def test_build_graph_from_workflow_converts_invocation_nodes():workflow = _build_workflow(nodes=[@@ -333,7 +361,7 @@ def test_build_graph_from_workflow_rejects_connector_loop_linkage_duplicate_owne],)- with pytest.raises(InvalidWorkflowInputError, match="loop_linkage connector path"):+ with pytest.raises(InvalidWorkflowInputError, match="already has a loop linkage"):build_graph_from_workflow(workflow)diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.pyindex 1103282eac..52959cf885 100644--- a/tests/test_graph_execution_state.py+++ b/tests/test_graph_execution_state.py@@ -2108,7 +2108,7 @@ def test_graph_for_empty_collection_with_indirect_body_completes_without_body_exassert state.is_complete()-def test_graph_for_return_omitted_output_is_not_collected():+def test_graph_for_return_none_output_is_collected():graph = Graph()graph.add_node(ForInvocation(id="for", collection=["alpha", "beta"]))graph.add_node(ForReturnInvocation(id="return"))@@ -2124,7 +2124,7 @@ def test_graph_for_return_omitted_output_is_not_collected():if source_node_id == "after")- assert state.results[after_exec_id].value == []+ assert state.results[after_exec_id].value == [None, None]def test_graph_for_multiple_final_edges_to_same_node_do_not_crash():