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
fix: preserve For final-output contexts through If
JPPhoto5bd9f99b23af
diff --git a/docs/src/content/docs/contributing/loop-nodes.md b/docs/src/content/docs/contributing/loop-nodes.mdindex b68cee4a09..90a5717fc3 100644--- a/docs/src/content/docs/contributing/loop-nodes.md+++ b/docs/src/content/docs/contributing/loop-nodes.md@@ -84,6 +84,9 @@ Iteration-scoped outputs (`item`, `index`, `total`, and `state`) define the loopterminate at the linked `ForReturn`; they cannot escape directly to after-loop nodes. Final outputs cannot feed backinto the loop body.+Downstream consumers, including a selected `If` branch, may consume `output_collection` directly. Its parent-frame scope+is preserved through branch selection, so a `final_state` edge is not needed just to make those consumers run.+`ForReturn.output` and `ForReturn.state` are scheduler-facing result fields and are hidden as downstream editoroutputs. They are still retained in execution results for aggregation, persistence, and resume. Ordinary state helpernodes (`state_empty`, `state_get`, `state_set`, and `state_merge`) carry explicit `LoopState` values through the body.diff --git a/docs/src/content/docs/features/Workflows/loop-nodes.mdx b/docs/src/content/docs/features/Workflows/loop-nodes.mdxindex 3b82c16395..d9466a29a9 100644--- a/docs/src/content/docs/features/Workflows/loop-nodes.mdx+++ b/docs/src/content/docs/features/Workflows/loop-nodes.mdx@@ -3,7 +3,7 @@ title: Loop Nodesdescription: Repeat workflow steps over a collection and optionally carry values from one iteration to the next.sidebar:order: 4-lastUpdated: 2026-09-03+lastUpdated: 2026-09-28---Loop nodes let a workflow repeat the same group of steps for every item in a collection. For example, a workflow can@@ -31,6 +31,9 @@ and `state` outputs contain values for that iteration. The work nodes run, thenThe `For` node does not send its per-item `item` output directly to nodes after the loop. To run a node once after alliterations finish, connect that node to `For.output_collection` or `For.final_state`.+You can connect `For.output_collection` directly to a branch input on an `If`. If that branch is selected, its consumer+runs in the parent frame after the loop finishes; you do not need a `For.final_state` edge just to make it run.+The editor draws a dashed green boundary around the loop body. This is a visual guide showing which nodes repeat; theboundary does not carry data. The dashed green line between `For.loop_linkage` and `ForReturn.loop_linkage` is arequired association, not a data value. The remaining values move through the ports and edges you connect.diff --git a/invokeai/app/services/shared/graph_if_runtime.py b/invokeai/app/services/shared/graph_if_runtime.pyindex bc2d71efb8..bcec70767d 100644--- a/invokeai/app/services/shared/graph_if_runtime.py+++ b/invokeai/app/services/shared/graph_if_runtime.py@@ -1,17 +1,128 @@-"""Activation admission helpers operating on state-owned runtime and durable records."""+"""If activation and selected-branch context helpers operating on graph execution state."""-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Callable, Optionalfrom invokeai.app.invocations.logic import IfInvocationfrom invokeai.app.services.shared.execution_engine.primitives import ActivationGatefrom invokeai.app.services.shared.execution_engine.scheduler import ActivationDependency-from invokeai.app.services.shared.graph_models import ExecutionToken+from invokeai.app.services.shared.graph_models import Edge, ExecutionTokenfrom invokeai.app.services.shared.graph_validation import IterateInvocationif TYPE_CHECKING:from invokeai.app.services.shared.graph import GraphExecutionState+def _get_effective_iteration_paths_for_edge(+ state: "GraphExecutionState",+ edge: Edge,+ visited_source_ids: set[str],+ get_prepared_nodes_for_source: Callable[[str], set[str]],+ get_prepared_edge_iteration_path: Callable[[Edge, str], tuple[int, ...]],+) -> set[tuple[int, ...]]:+ source_node_id = edge.source.node_id+ prepared_nodes: set[str] = set()+ if source_node_id in state.source_prepared_mapping:+ prepared_nodes = get_prepared_nodes_for_source(source_node_id)+ if not prepared_nodes and source_node_id in state.executed:+ return set()+ if prepared_nodes:+ return {get_prepared_edge_iteration_path(edge, prepared_id) for prepared_id in prepared_nodes}+ if source_node_id in visited_source_ids:+ return set()++ source_node = state.graph.get_node(source_node_id)+ if isinstance(source_node, IfInvocation):+ return set(+ _get_if_iteration_paths(+ state,+ source_node_id,+ visited_source_ids,+ get_prepared_nodes_for_source,+ get_prepared_edge_iteration_path,+ )+ )++ input_edges = state.graph._get_input_edges(source_node_id)+ if not input_edges:+ return {()}+ next_visited_source_ids = {*visited_source_ids, source_node_id}+ return set().union(+ *(+ _get_effective_iteration_paths_for_edge(+ state,+ input_edge,+ next_visited_source_ids,+ get_prepared_nodes_for_source,+ get_prepared_edge_iteration_path,+ )+ for input_edge in input_edges+ )+ )+++def _get_if_iteration_paths(+ state: "GraphExecutionState",+ node_id: str,+ visited_source_ids: set[str],+ get_prepared_nodes_for_source: Callable[[str], set[str]],+ get_prepared_edge_iteration_path: Callable[[Edge, str], tuple[int, ...]],+) -> list[tuple[int, ...]]:+ """Infer the selected branch's effective iteration paths for an If output."""+ node = state.graph.get_node(node_id)+ assert isinstance(node, IfInvocation)+ next_visited_source_ids = {*visited_source_ids, node_id}+ condition_edges = state.graph._get_input_edges(node_id, "condition")++ condition_selections: list[tuple[Optional[tuple[int, ...]], str]] = []+ if condition_edges:+ condition_edge = condition_edges[0]+ if condition_edge.source.node_id not in state.source_prepared_mapping:+ return []+ for prepared_id in get_prepared_nodes_for_source(condition_edge.source.node_id):+ if prepared_id not in state.results:+ return []+ condition_value = getattr(state.results[prepared_id], condition_edge.source.field)+ condition_path = get_prepared_edge_iteration_path(condition_edge, prepared_id)+ selected_field = "true_input" if condition_value else "false_input"+ condition_selections.append((condition_path, selected_field))+ else:+ selected_field = "true_input" if node.condition else "false_input"+ condition_selections.append((None, selected_field))++ paths: set[tuple[int, ...]] = set()+ has_selected_edges = False+ for condition_path, selected_field in condition_selections:+ selected_edges = state.graph._get_input_edges(node_id, selected_field)+ has_selected_edges = has_selected_edges or bool(selected_edges)+ if selected_edges:+ branch_paths = set().union(+ *(+ _get_effective_iteration_paths_for_edge(+ state,+ edge,+ next_visited_source_ids,+ get_prepared_nodes_for_source,+ get_prepared_edge_iteration_path,+ )+ for edge in selected_edges+ )+ )+ else:+ branch_paths = {condition_path or ()}++ for branch_path in branch_paths:+ if condition_path is None:+ paths.add(branch_path)+ elif condition_path[: len(branch_path)] == branch_path:+ paths.add(condition_path)+ elif branch_path[: len(condition_path)] == condition_path:+ paths.add(branch_path)++ if not paths:+ return [] if has_selected_edges else [()]+ return sorted(path for path in paths if not any(path != other and other[: len(path)] == path for other in paths))++def _record_activation_dependencies(state: "GraphExecutionState", exec_node_id: str) -> tuple[ActivationDependency, ...]:diff --git a/invokeai/app/services/shared/graph_materializer.py b/invokeai/app/services/shared/graph_materializer.pyindex a9504e2179..fe9a564b0f 100644--- a/invokeai/app/services/shared/graph_materializer.py+++ b/invokeai/app/services/shared/graph_materializer.py@@ -13,6 +13,7 @@ from invokeai.app.invocations.loops import (ForReturnInvocation,LoopState,)+from invokeai.app.services.shared import graph_if_runtimefrom invokeai.app.services.shared.graph_models import Edge, EdgeConnectionfrom invokeai.app.services.shared.graph_validation import (COLLECTION_FIELD,@@ -59,14 +60,24 @@ class _ExecutionNodeBuilder:self,iteration_index: int,iteration_node_map: list[tuple[str, str]],+ input_edges: Optional[list[Edge]] = None,) -> Optional[tuple[int, ...]]:parent_paths: list[tuple[int, ...]] = []parent_iteration_axes: list[tuple[str, ...]] = []registry = self._state._prepared_registry()+ input_edges_by_source: dict[str, list[Edge]] = {}+ for edge in input_edges or []:+ input_edges_by_source.setdefault(edge.source.node_id, []).append(edge)for source_node_id, prepared_id in iteration_node_map:parent_path = registry.get_iteration_path(prepared_id)if parent_path is None:return None+ source_edges = input_edges_by_source.get(source_node_id)+ if source_edges:+ parent_path = max(+ (self._get_prepared_edge_iteration_path(edge, prepared_id) for edge in source_edges),+ key=lambda path: (len(path), path),+ )if parent_path:parent_paths.append(parent_path)parent_iteration_axes.append(self._get_iteration_axes(source_node_id))@@ -202,7 +213,9 @@ class _ExecutionNodeBuilder:new_node = self._create_execution_node_copy(node, source_for_id, -1, deep_copy=False)assert isinstance(new_node, ForInvocation)new_edges = self._build_execution_edges(source_for_id, iteration_node_map)- iteration_path = self._get_known_iteration_path(-1, iteration_node_map)+ iteration_path = self._get_known_iteration_path(+ -1, iteration_node_map, self._state.graph._get_input_edges(source_for_id)+ )if iteration_path is not None:self._state._prepared_registry().set_iteration_path(new_node.id, iteration_path)self._attach_execution_edges(new_node.id, new_edges)@@ -1377,11 +1390,16 @@ class _ExecutionNodeBuilder:return []new_edges = self._build_execution_edges_for_fields(node_id, iteration_node_map, input_fields)+ input_edges = self._state.graph._get_input_edges(node_id)+ if input_fields is not None:+ input_edges = [edge for edge in input_edges if edge.destination.field in input_fields]new_nodes: list[str] = []for iteration_index in iteration_indexes:new_node_iteration_path = iteration_pathif new_node_iteration_path is None:- new_node_iteration_path = self._get_known_iteration_path(iteration_index, iteration_node_map)+ new_node_iteration_path = self._get_known_iteration_path(+ iteration_index, iteration_node_map, input_edges+ )elif isinstance(node, (ForInvocation, IterateInvocation)):new_node_iteration_path += (iteration_index,)if enforce_admission and not self._state._is_source_activation_admitted(@@ -1402,9 +1420,23 @@ class _ExecutionNodeBuilder:if not any(isinstance(node, IfInvocation) for node in self._state.graph.nodes.values()):return Trueif isinstance(self._state.graph.get_node(node_id), IfInvocation):+ condition_edges = self._state.graph._get_input_edges(node_id, "condition")+ if not condition_edges:+ return any(+ self._state._is_source_activation_admitted(node_id, iteration_path)+ for iteration_path in graph_if_runtime._get_if_iteration_paths(+ self._state,+ node_id,+ set(),+ self._get_prepared_nodes_for_source,+ self._get_prepared_edge_iteration_path,+ )+ )mappings = self._get_if_condition_iteration_mappings(node_id, graph)+ input_edges = condition_edgeselse:mappings = self._get_parent_iteration_mappings(node_id, graph)+ input_edges = self._state.graph._get_input_edges(node_id)mappings = list(mappings)if isinstance(self._state.graph.get_node(node_id), IfInvocation) and self.get_node_iterators(node_id, self.iterator_graph(graph)@@ -1422,7 +1454,7 @@ class _ExecutionNodeBuilder:return self._state._is_source_activation_admitted(node_id)return any(self._state._is_source_activation_admitted(- node_id, self._get_known_iteration_path(-1, iteration_mapping) or ()+ node_id, self._get_known_iteration_path(-1, iteration_mapping, input_edges) or ())for iteration_mapping in mappings)@@ -1733,6 +1765,55 @@ class _ExecutionNodeBuilder:for iteration_path, iteration_mappings in iteration_mapping_groups:create_results = self.create_execution_node(next_node_id, iteration_mappings, iteration_path)new_node_ids.extend(create_results)+ elif isinstance(next_node, IfInvocation):+ condition_paths = graph_if_runtime._get_if_iteration_paths(+ self._state,+ next_node_id,+ set(),+ self._get_prepared_nodes_for_source,+ self._get_prepared_edge_iteration_path,+ )+ condition_edges = self._state.graph._get_input_edges(next_node_id, "condition")+ if condition_edges:+ iteration_mappings = list(self._get_if_condition_iteration_mappings(next_node_id, g))+ if condition_paths:+ for iteration_path in condition_paths:+ matching_mappings = [+ iteration_mapping+ for iteration_mapping in iteration_mappings+ if (+ (+ condition_path := self._get_known_iteration_path(+ -1, iteration_mapping, condition_edges+ )+ or ()+ )[: len(iteration_path)]+ == iteration_path+ or iteration_path[: len(condition_path or ())] == (condition_path or ())+ )+ ]+ for iteration_mapping in matching_mappings:+ create_results = self.create_execution_node(+ next_node_id,+ iteration_mapping,+ iteration_path,+ input_fields={"condition"},+ )+ new_node_ids.extend(create_results)+ else:+ for iteration_mapping in iteration_mappings:+ iteration_path = self._get_known_iteration_path(-1, iteration_mapping, condition_edges)+ create_results = self.create_execution_node(+ next_node_id,+ iteration_mapping,+ iteration_path,+ input_fields={"condition"},+ )+ new_node_ids.extend(create_results)+ else:+ for iteration_path in condition_paths:+ create_results = self.create_execution_node(next_node_id, [], iteration_path)+ new_node_ids.extend(create_results)else:parent_iterator_nodes = self.get_node_iterators(next_node_id)iteration_mappings_iter = (diff --git a/tests/test_graph_execution_state.py b/tests/test_graph_execution_state.pyindex 36179cd771..fec0436673 100644--- a/tests/test_graph_execution_state.py+++ b/tests/test_graph_execution_state.py@@ -2951,6 +2951,74 @@ def test_graph_for_final_output_collection_materializes_after_last_direct_returnassert after_node.value == ["alpha", "beta"]+def test_graph_for_final_output_feeds_selected_if_branch_in_parent_frame():+ graph = Graph()+ graph.add_node(NestedAnyCollectionTestInvocation(id="outer_values", collection=[["alpha", "beta"], ["gamma"]]))+ graph.add_node(IterateInvocation(id="outer_iter"))+ graph.add_node(ForInvocation(id="inner_for"))+ graph.add_node(ForReturnInvocation(id="inner_return"))+ graph.add_node(AnyTypeTestInvocation(id="after"))+ graph.add_node(IfInvocation(id="if", condition=False))+ graph.add_edge(create_edge("outer_values", "collection", "outer_iter", "collection"))+ graph.add_edge(create_edge("outer_iter", "item", "inner_for", "collection"))+ graph.add_edge(create_edge("inner_for", "item", "inner_return", "output"))+ graph.add_edge(create_edge("inner_for", "output_collection", "after", "value"))+ graph.add_edge(create_edge("after", "value", "if", "false_input"))++ state = GraphExecutionState(graph=add_test_loop_linkages(graph))+ executed_source_ids = execute_all_nodes(state)++ assert executed_source_ids.count("after") == 2+ assert executed_source_ids.count("if") == 2+ assert state.is_complete()+ if_exec_ids = state.source_prepared_mapping["if"]+ assert {+ state._get_iteration_path(if_exec_id): tuple(state.results[if_exec_id].value) for if_exec_id in if_exec_ids+ } == {+ (0,): ("alpha", "beta"),+ (1,): ("gamma",),+ }+++def test_graph_static_nested_ifs_ignore_unselected_loop_branch_context():+ graph = Graph()+ graph.add_node(NestedAnyCollectionTestInvocation(id="a_values", collection=[["a0", "a1"], ["a2"]]))+ graph.add_node(IterateInvocation(id="a_iter"))+ graph.add_node(ForInvocation(id="a_for"))+ graph.add_node(ForReturnInvocation(id="a_return"))+ graph.add_node(NestedAnyCollectionTestInvocation(id="b_values", collection=[["b0"], ["b1"], ["b2"]]))+ graph.add_node(IterateInvocation(id="b_iter"))+ graph.add_node(ForInvocation(id="b_for"))+ graph.add_node(ForReturnInvocation(id="b_return"))+ graph.add_node(IfInvocation(id="inner_if", condition=False))+ graph.add_node(IfInvocation(id="outer_if", condition=False))+ graph.add_node(AnyTypeTestInvocation(id="result"))+ graph.add_edge(create_edge("a_values", "collection", "a_iter", "collection"))+ graph.add_edge(create_edge("a_iter", "item", "a_for", "collection"))+ graph.add_edge(create_edge("a_for", "item", "a_return", "output"))+ graph.add_edge(create_edge("b_values", "collection", "b_iter", "collection"))+ graph.add_edge(create_edge("b_iter", "item", "b_for", "collection"))+ graph.add_edge(create_edge("b_for", "item", "b_return", "output"))+ graph.add_edge(create_edge("a_for", "output_collection", "inner_if", "false_input"))+ graph.add_edge(create_edge("b_for", "output_collection", "inner_if", "true_input"))+ graph.add_edge(create_edge("inner_if", "value", "outer_if", "false_input"))+ graph.add_edge(create_edge("outer_if", "value", "result", "value"))++ state = GraphExecutionState(graph=add_test_loop_linkages(graph))+ executed_source_ids = execute_all_nodes(state)++ result_exec_ids = state.source_prepared_mapping["result"]+ assert {+ state._get_iteration_path(result_exec_id): tuple(state.results[result_exec_id].value)+ for result_exec_id in result_exec_ids+ } == {+ (0,): ("a0", "a1"),+ (1,): ("a2",),+ }+ assert executed_source_ids.count("outer_if") == 2+ assert state.is_complete()++def test_graph_for_final_state_materializes_after_last_direct_return():graph = Graph()graph.add_node(ForInvocation(id="for", collection=["alpha", "beta"]))