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: address For loop review findings
JPPhotoad54fc0d4d61
diff --git a/docs/src/content/docs/features/Workflows/loop-nodes.mdx b/docs/src/content/docs/features/Workflows/loop-nodes.mdxindex ffb856cf43..fb05cd2364 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-08-30+lastUpdated: 2026-09-03---Loop nodes let a workflow repeat the same group of steps for every item in a collection. For example, a workflow can@@ -39,6 +39,10 @@ The loop is not executable until its two boundary nodes are paired. Connect `For`ForReturn.loop_linkage`. When you add `ForReturn` from an iteration-output connection in the node picker, the editor cancreate this association for you. Replacing either boundary node requires pairing the replacement again.+Deleting a connector preserves its through-connections by reconnecting the upstream source to surviving downstream+targets. Deleting a complete loop-linkage alias collapses it to a direct `loop_linkage` edge; ordinary connector paths+remain ordinary data edges.+### A Simple ExampleTo process every image in a collection:@@ -146,7 +150,7 @@ These nodes make the collection relationship explicit before the loop:collections may have different lengths.- **Zip Collections** pairs items by position. Both collections must have the same length; a mismatch is an error.- **Cartesian Product of Collections** creates every possible pair, one item from each collection. The collections may- have different lengths. The result is limited to 100,000 pairs.+ have different lengths. Products larger than 100,000 pairs fail with an error.Choose based on the relationship between the items:diff --git a/invokeai/app/invocations/loops.py b/invokeai/app/invocations/loops.pyindex 4c472b352b..019e71e8c5 100644--- a/invokeai/app/invocations/loops.py+++ b/invokeai/app/invocations/loops.py@@ -29,7 +29,7 @@ class LoopStateOutput(BaseInvocationOutput):class LoopStateValueOutput(BaseInvocationOutput):value: Optional[Any] = OutputField(default=None,- description="The value read from the loop state, or None when the key is missing",+ description="The value read from the loop state, or the configured default when the key is missing",ui_type=UIType.Any,)@@ -42,7 +42,7 @@ class StateEmptyInvocation(BaseInvocation):return LoopStateOutput(state=LoopState())-@invocation("state_get", title="Get Loop State Value", tags=["loop", "state"], category="workflow", version="1.0.2")+@invocation("state_get", title="Get Loop State Value", tags=["loop", "state"], category="workflow", version="1.0.3")class StateGetInvocation(BaseInvocation):"""Reads a value from loop state."""diff --git a/invokeai/app/services/shared/graph.py b/invokeai/app/services/shared/graph.pyindex ec3bc12fe4..ef63d8c3ec 100644--- a/invokeai/app/services/shared/graph.py+++ b/invokeai/app/services/shared/graph.py@@ -99,6 +99,14 @@ class _SupportedNestedForBody:continuation_nodes: frozenset[str]+@dataclass(frozen=True)+class _SupportedNestedIterateBody:+ body_path_nodes: set[str]+ return_node_id: str+ iterate_node_id: str+ collect_node_id: str++class EdgeConnection(BaseModel):model_config = ConfigDict(frozen=True)@@ -381,7 +389,8 @@ class _IfBranchScheduler:if all(n in self._state.executed for n in prepared_nodes):if source_node_id not in self._state.executed:self._state.executed.add(source_node_id)- self._state.executed_history.append(source_node_id)+ if source_node_id not in self._state.executed_history:+ self._state.executed_history.append(source_node_id)def try_resolve_if_node(self, exec_node_id: str) -> None:if exec_node_id in self._state._resolved_if_exec_branches:@@ -955,9 +964,12 @@ class _ExecutionMaterializer:prepared_for_id: str,graph: "nx.DiGraph",execution_graph: "nx.DiGraph",- nested_body: tuple[set[str], str, str, str],+ nested_body: _SupportedNestedIterateBody,) -> Optional[str]:- body_path_nodes, source_return_id, source_iterate_id, source_collect_id = nested_body+ body_path_nodes = nested_body.body_path_nodes+ source_return_id = nested_body.return_node_id+ source_iterate_id = nested_body.iterate_node_id+ source_collect_id = nested_body.collect_node_idprepared_for_node = self._state.execution_graph.get_node(prepared_for_id)outer_iteration_path = self._state._get_iteration_path(prepared_for_id)if isinstance(prepared_for_node, ForInvocation) and prepared_for_node.index >= 0:@@ -1362,7 +1374,8 @@ class _ExecutionMaterializer:def _mark_source_node_empty(self, source_node_id: str) -> None:self._state.source_prepared_mapping[source_node_id] = set()self._state.executed.add(source_node_id)- self._state.executed_history.append(source_node_id)+ if source_node_id not in self._state.executed_history:+ self._state.executed_history.append(source_node_id)def _index_prepared_nodes_by_iteration_path(self, prepared_nodes: set[str], input_edges: list[Edge]@@ -1885,8 +1898,8 @@ class _ExecutionScheduler:nested_body = self._state.graph._get_supported_for_nested_iterate_body(source_for_id, graph)nested_for_body = self._state.graph._get_supported_for_nested_for_body(source_for_id, graph)if nested_body is not None:- body_path_nodes, _return_id, iterate_id, _collect_id = nested_body- deferred_node_ids = (iterate_id,)+ body_path_nodes = nested_body.body_path_nodes+ deferred_node_ids = (nested_body.iterate_node_id,)elif nested_for_body is None:continueelse:@@ -2033,7 +2046,9 @@ class _ExecutionScheduler:(iterate_path := self._state._get_iteration_path(prepared_iterate_id))[: len(prepared_for_path)]== prepared_for_pathand len(iterate_path) > len(prepared_for_path)- for prepared_iterate_id in self._state._prepared_registry().get_prepared_ids(nested_body[2])+ for prepared_iterate_id in self._state._prepared_registry().get_prepared_ids(+ nested_body.iterate_node_id+ )):self._state._materializer().create_for_body_iteration(source_for_id=source_for_id, prepared_for_id=exec_node_id@@ -2042,7 +2057,7 @@ class _ExecutionScheduler:self._try_materialize_deferred_nested_for_body(exec_node_id)else:self._try_materialize_deferred_nested_for_body(exec_node_id)- if len(self._state.executed_history) == len(self._state.graph.nodes):+ if self._state.is_complete():self._state.execution_graph._invalidate_edge_indexes()self._state._ready_queues = {}self._state._ready_node_ids = set()@@ -3203,7 +3218,7 @@ class Graph(BaseModel):def _get_supported_for_nested_iterate_body(self, node_id: str, graph: "nx.DiGraph"- ) -> tuple[set[str], str, str, str] | None:+ ) -> _SupportedNestedIterateBody | None:"""Returns the bounded internal Iterate body contract, if this For uses it."""body_path_to_return = self._get_for_body_path_to_return(node_id, graph)if body_path_to_return is None:@@ -3267,7 +3282,12 @@ class Graph(BaseModel):):return None- return body_path_nodes, return_node_id, iterate_node_id, collect_node_id+ return _SupportedNestedIterateBody(+ body_path_nodes=body_path_nodes,+ return_node_id=return_node_id,+ iterate_node_id=iterate_node_id,+ collect_node_id=collect_node_id,+ )def _get_supported_for_nested_for_body(self, node_id: str, graph: "nx.DiGraph") -> _SupportedNestedForBody | None:"""Returns the supported recursive nested For contract, if this For uses it.@@ -4005,7 +4025,8 @@ class GraphExecutionState(BaseModel):for source_node_id in source_node_ids:if source_node_id not in self.executed:self.executed.add(source_node_id)- self.executed_history.append(source_node_id)+ if source_node_id not in self.executed_history:+ self.executed_history.append(source_node_id)def _get_for_parent_iteration_paths(self, source_for_id: str) -> set[tuple[int, ...]]:return {@@ -4211,7 +4232,8 @@ class GraphExecutionState(BaseModel):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)- self.executed_history.append(source_node_id)+ if source_node_id not in self.executed_history:+ self.executed_history.append(source_node_id)return completedef has_error(self) -> bool:diff --git a/invokeai/app/services/shared/workflow_graph_builder.py b/invokeai/app/services/shared/workflow_graph_builder.pyindex 712de8d064..16ce64ce7f 100644--- a/invokeai/app/services/shared/workflow_graph_builder.py+++ b/invokeai/app/services/shared/workflow_graph_builder.py@@ -1,4 +1,5 @@from collections.abc import Mapping, MutableMapping, Sequence+from dataclasses import dataclassfrom typing import Anyfrom invokeai.app.invocations.baseinvocation import Classification, InvocationRegistry@@ -20,6 +21,13 @@ class InvalidWorkflowInputError(ValueError):pass+@dataclass(frozen=True)+class _ConnectorLoopLinkagePath:+ source_id: str+ target_id: str+ edge_path: tuple[Mapping[str, Any], ...]++def _is_mapping(value: Any) -> bool:return isinstance(value, Mapping)@@ -298,7 +306,7 @@ def _resolve_connector_source(def _resolve_for_connector_loop_linkage_path(edge: Mapping[str, Any], workflow_nodes: dict[str, Mapping[str, Any]], workflow_edges: Sequence[Mapping[str, Any]]-) -> tuple[str, str, list[Mapping[str, Any]]] | None:+) -> _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:return None@@ -340,7 +348,7 @@ def _resolve_for_connector_loop_linkage_path(if _is_invocation_node(target_node):if target_node.get("data", {}).get("type") != "for_return" or target_handle != "loop_linkage":return None- return source_id, target_id, path_edges+ return _ConnectorLoopLinkagePath(source_id=source_id, target_id=target_id, edge_path=tuple(path_edges))if (not isinstance(target_id, str)or not _is_connector_node(target_node)@@ -362,7 +370,7 @@ def build_graph_from_workflow(workflow: Mapping[str, Any]) -> Graph:default_edges = _get_default_edges(workflow_edges)loop_linkage_edges = _get_loop_linkage_edges(workflow_edges)- connector_loop_linkage_paths: list[tuple[str, str, list[Mapping[str, Any]]]] = []+ connector_loop_linkage_paths: list[_ConnectorLoopLinkagePath] = []connector_loop_linkage_edge_ids: set[int] = set()linked_for_ids = {edge.get("source")@@ -393,14 +401,14 @@ def build_graph_from_workflow(workflow: Mapping[str, Any]) -> Graph:raise InvalidWorkflowInputError("loop_linkage connector path must resolve to exactly one For and one ForReturn without branching")- if path[0] in linked_for_ids or path[1] in linked_return_ids:+ 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")connector_loop_linkage_paths.append(path)- connector_loop_linkage_edge_ids.update(id(path_edge) for path_edge in path[2])- linked_for_ids.add(path[0])- linked_return_ids.add(path[1])+ connector_loop_linkage_edge_ids.update(id(path_edge) for path_edge in path.edge_path)+ linked_for_ids.add(path.source_id)+ linked_return_ids.add(path.target_id)parsed_nodes: dict[str, dict[str, Any]] = {}for node in workflow_nodes.values():@@ -502,12 +510,12 @@ def build_graph_from_workflow(workflow: Mapping[str, Any]) -> Graph:})- for source_id, target_id, _ in connector_loop_linkage_paths:+ for path in connector_loop_linkage_paths:parsed_edges.append({"type": "loop_linkage",- "source": {"node_id": source_id, "field": "loop_linkage"},- "destination": {"node_id": target_id, "field": "loop_linkage"},+ "source": {"node_id": path.source_id, "field": "loop_linkage"},+ "destination": {"node_id": path.target_id, "field": "loop_linkage"},})diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 74324c4bce..ebe972e571 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -60165,7 +60165,7 @@}],"default": null,- "description": "The value read from the loop state, or None when the key is missing",+ "description": "The value read from the loop state, or the configured default when the key is missing","field_kind": "output","title": "Value","ui_hidden": false,@@ -89319,7 +89319,7 @@"tags": ["loop", "state"],"title": "Get Loop State Value","type": "object",- "version": "1.0.2",+ "version": "1.0.3","output": {"$ref": "#/components/schemas/LoopStateValueOutput"}diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex 7219615714..56b337bdd7 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -24562,7 +24562,7 @@ export type components = {LoopStateValueOutput: {/*** Value- * @description The value read from the loop state, or None when the key is missing+ * @description The value read from the loop state, or the configured default when the key is missing* @default null*/value: unknown | null;diff --git a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.tsindex 6623468000..1c36115105 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts@@ -461,4 +461,96 @@ describe('compileProjectGraph', () => {},]);});++ it('rejects a loop-linkage source reused as ordinary connector data', () => {+ const forTemplate: InvocationTemplate = {+ ...template('for', {+ collection: input('collection', {+ default: [],+ type: { batch: false, cardinality: 'COLLECTION', name: 'CollectionField' },+ }),+ }),+ outputs: {+ item: {+ description: '',+ name: 'item',+ outputScope: 'iteration',+ title: 'Item',+ type: { batch: false, cardinality: 'SINGLE', name: 'CollectionItemField' },+ },+ loop_linkage: {+ description: '',+ name: 'loop_linkage',+ title: 'Loop linkage',+ type: { batch: false, cardinality: 'SINGLE', name: 'AnyField' },+ },+ output_collection: {+ description: '',+ name: 'output_collection',+ outputScope: 'final',+ title: 'Output collection',+ type: { batch: false, cardinality: 'COLLECTION', name: 'CollectionField' },+ },+ },+ };+ const returnTemplate: InvocationTemplate = {+ ...template('for_return', {+ loop_linkage: input('loop_linkage', {+ input: 'connection',+ type: { batch: false, cardinality: 'SINGLE', name: 'AnyField' },+ }),+ output: input('output', { type: { batch: false, cardinality: 'SINGLE', name: 'CollectionItemField' } }),+ }),+ outputs: {},+ };+ const sinkTemplate = template('sink', { value: input('value') });+ const forNode = buildInvocationNode(forTemplate, { x: 0, y: 0 });+ const returnNode = buildInvocationNode(returnTemplate, { x: 100, y: 0 });+ const sinkNode = buildInvocationNode(sinkTemplate, { x: 200, y: 0 });+ const connector = buildConnectorNode({ x: 50, y: 0 });+ const document: ProjectGraphState = {+ ...createProjectGraph('invalid-loop-linkage-source'),+ edges: [+ {+ id: 'item',+ source: forNode.id,+ sourceHandle: 'item',+ target: returnNode.id,+ targetHandle: 'output',+ type: 'default',+ },+ {+ id: 'linkage',+ source: forNode.id,+ sourceHandle: 'loop_linkage',+ target: returnNode.id,+ targetHandle: 'loop_linkage',+ type: 'loop_linkage',+ },+ {+ id: 'connector-in',+ source: forNode.id,+ sourceHandle: 'loop_linkage',+ target: connector.id,+ targetHandle: 'in',+ type: 'default',+ },+ {+ id: 'connector-out',+ source: connector.id,+ sourceHandle: 'out',+ target: sinkNode.id,+ targetHandle: 'value',+ type: 'default',+ },+ ],+ nodes: [forNode, returnNode, sinkNode, connector],+ };+ const loopTemplates = { for: forTemplate, for_return: returnTemplate, sink: sinkTemplate };++ expect(getProjectGraphReadiness(document, { error: null, status: 'loaded', templates: loopTemplates })).toEqual({+ canInvoke: false,+ reasons: ['For loop validation failed: nodes.forLoopLinkageInvalid.'],+ });+ });});diff --git a/invokeai/frontend/webv2/src/features/workflow/core/forLoops.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/forLoops.test.tsindex e54d4702b4..f069f199f4 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/forLoops.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/forLoops.test.ts@@ -3,7 +3,13 @@ import { describe, expect, it } from 'vitest';import type { WorkflowEdge, WorkflowInvocationNode } from './types';import { createProjectGraph } from './document';-import { getCanonicalWorkflowEdges, localizeForLoopValidationReason, validateForLoopGraph } from './forLoops';+import {+ getCanonicalWorkflowEdges,+ getForLoopBodyBoundaries,+ localizeForLoopValidationReason,+ shouldAddForReturnLoopLinkage,+ validateForLoopGraph,+} from './forLoops';const node = (id: string, type: string): WorkflowInvocationNode => ({data: {@@ -64,6 +70,43 @@ describe('For/ForReturn graph contracts', () => {);});+ it('promotes connector-routed For iteration output to direct loop linkage', () => {+ const forNode = node('for', 'for');++ expect(shouldAddForReturnLoopLinkage('for_return', { fieldName: 'item', nodeId: forNode.id }, forNode, [])).toBe(+ true+ );+ });++ it('scopes duplicate linkage status to the affected loop', () => {+ const document = {+ ...createProjectGraph('duplicate-boundary-test'),+ nodes: [+ node('for-a', 'for'),+ node('body-a', 'number'),+ node('return-a', 'for_return'),+ node('for-b', 'for'),+ node('body-b', 'number'),+ node('return-b', 'for_return'),+ node('stray-return', 'for_return'),+ ],+ edges: [+ edge('a-item', 'for-a', 'item', 'body-a', 'value'),+ edge('a-output', 'body-a', 'value', 'return-a', 'output'),+ edge('a-linkage', 'for-a', 'loop_linkage', 'return-a', 'loop_linkage', 'loop_linkage'),+ edge('a-duplicate', 'for-a', 'loop_linkage', 'stray-return', 'loop_linkage', 'loop_linkage'),+ edge('b-item', 'for-b', 'item', 'body-b', 'value'),+ edge('b-output', 'body-b', 'value', 'return-b', 'output'),+ edge('b-linkage', 'for-b', 'loop_linkage', 'return-b', 'loop_linkage', 'loop_linkage'),+ ],+ };++ const boundaries = getForLoopBodyBoundaries(document.nodes, document.edges);++ expect(boundaries.find((boundary) => boundary.forNodeId === 'for-a')?.status).toBe('duplicate_linkage');+ expect(boundaries.find((boundary) => boundary.forNodeId === 'for-b')?.status).toBe('complete');+ });+it('accepts a direct loop linkage and excludes it from data-flow traversal', () => {const { document } = linkedGraph();diff --git a/invokeai/frontend/webv2/src/features/workflow/core/forLoops.ts b/invokeai/frontend/webv2/src/features/workflow/core/forLoops.tsindex dc605ac144..df6f75104f 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/forLoops.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/forLoops.ts@@ -3,6 +3,7 @@ import type { WorkflowEdge, WorkflowNode, ProjectGraphState } from './types';import { getResolvedWorkflowEdgesIndexed, resolveLoopLinkagePath } from './connectors';import { createWorkflowGraphIndex } from './graphIndex';import { isInvocationNode } from './types';+import { LOOP_LINKAGE_FIELD } from './validation';export type ForLoopGraphError =| 'nodes.forLoopMissingIterationOutput'@@ -67,10 +68,21 @@ export interface LoopBodyBoundary {status: LoopBodyBoundaryStatus;}-const LOOP_LINKAGE_FIELD = 'loop_linkage';const ITERATION_OUTPUT_FIELDS = new Set(['item', 'index', 'total', 'state']);const FINAL_OUTPUT_FIELDS = new Set(['output_collection', 'final_state']);+export const shouldAddForReturnLoopLinkage = (+ targetType: string,+ resolvedSource: { fieldName: string; nodeId: string } | null,+ resolvedSourceNode: WorkflowNode | undefined,+ edges: readonly WorkflowEdge[]+): boolean =>+ targetType === 'for_return' &&+ ITERATION_OUTPUT_FIELDS.has(resolvedSource?.fieldName ?? '') &&+ resolvedSourceNode?.type === 'invocation' &&+ resolvedSourceNode.data.type === 'for' &&+ !edges.some((edge) => edge.source === resolvedSourceNode.id && edge.sourceHandle === LOOP_LINKAGE_FIELD);+type LoopNode = { id: string; type: string };type LoopEdge = {id: string;@@ -182,11 +194,17 @@ export const getForLoopBodyBoundaries = (nodes: WorkflowNode[], edges: WorkflowEconst linkedReturnByForId = new Map<string, string>();const linkedForByReturnId = new Map<string, string>();- let duplicateLinkage = false;+ const duplicateForIds = new Set<string>();+ const duplicateReturnIds = new Set<string>();for (const edge of canonicalEdges.filter((candidate) => candidate.type === 'loop_linkage')) {- if (linkedReturnByForId.has(edge.source.node_id) || linkedForByReturnId.has(edge.destination.node_id)) {- duplicateLinkage = true;+ const existingForId = linkedForByReturnId.get(edge.destination.node_id);+ if (linkedReturnByForId.has(edge.source.node_id) || existingForId !== undefined) {+ duplicateForIds.add(edge.source.node_id);+ if (existingForId !== undefined) {+ duplicateForIds.add(existingForId);+ duplicateReturnIds.add(edge.destination.node_id);+ }continue;}linkedReturnByForId.set(edge.source.node_id, edge.destination.node_id);@@ -209,7 +227,7 @@ export const getForLoopBodyBoundaries = (nodes: WorkflowNode[], edges: WorkflowEconst returnNodeId = linkedReturnId ?? (reachableReturns.length === 1 ? reachableReturns[0] : undefined);let status: LoopBodyBoundaryStatus;- if (duplicateLinkage && linkedReturnId !== undefined) {+ if (duplicateForIds.has(forNode.id) || (linkedReturnId !== undefined && duplicateReturnIds.has(linkedReturnId))) {status = 'duplicate_linkage';} else if (linkedReturnId === undefined) {status = 'missing_linkage';@@ -259,8 +277,7 @@ export const validateForLoopGraph = (allEdges.some((edge) =>edge.type === 'default' &&- edge.source.field === LOOP_LINKAGE_FIELD &&- edge.destination.field === LOOP_LINKAGE_FIELD &&+ (edge.source.field === LOOP_LINKAGE_FIELD || edge.destination.field === LOOP_LINKAGE_FIELD) &&nodesById.has(edge.source.node_id) &&nodesById.has(edge.destination.node_id))diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsxindex d8bc78a56c..a74f5ff703 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx@@ -16,6 +16,7 @@ import {getCompatibleOutputTemplate,LOOP_LINKAGE_FIELD,resolveConnectorSource,+ shouldAddForReturnLoopLinkage,parseWorkflowJson,serializeWorkflowJson,} from '@features/workflow/utility';@@ -451,16 +452,12 @@ export const WorkflowDialogHost = () => {? { fieldName: addNodeConnection.sourceHandle, nodeId: sourceNode.id, type: null }: null;const resolvedSourceNode = currentGraph.nodes.find((candidate) => candidate.id === resolvedSource?.nodeId);- const shouldAddLoopLinkage =- template.type === 'for_return' &&- addNodeConnection.sourceHandle !== LOOP_LINKAGE_FIELD &&- ['item', 'index', 'total', 'state'].includes(addNodeConnection.sourceHandle) &&- ['item', 'index', 'total', 'state'].includes(resolvedSource?.fieldName ?? '') &&- resolvedSourceNode?.type === 'invocation' &&- resolvedSourceNode.data.type === 'for' &&- !currentGraph.edges.some(- (candidate) => candidate.source === resolvedSourceNode.id && candidate.sourceHandle === LOOP_LINKAGE_FIELD- );+ const shouldAddLoopLinkage = shouldAddForReturnLoopLinkage(+ template.type,+ resolvedSource,+ resolvedSourceNode,+ currentGraph.edges+ );if (shouldAddLoopLinkage && resolvedSourceNode?.type === 'invocation') {editGraph({diff --git a/tests/app/invocations/test_loop_nodes.py b/tests/app/invocations/test_loop_nodes.pyindex 7ba0d27cf3..6fb3825585 100644--- a/tests/app/invocations/test_loop_nodes.py+++ b/tests/app/invocations/test_loop_nodes.py@@ -73,6 +73,13 @@ def test_state_get_output_schema_exposes_any_value_output() -> None:assert schema["properties"]["value"]["ui_type"] == "AnyField"+def test_state_get_output_schema_describes_configured_default() -> None:+ schema = LoopStateValueOutput.model_json_schema()++ assert StateGetInvocation.UIConfig.version == "1.0.3"+ assert "configured default" in schema["properties"]["value"]["description"]++def test_state_merge_invocation_schema_exposes_any_values_input() -> None:schema = StateMergeInvocation.model_json_schema()diff --git a/tests/app/services/test_for_loop_session_runner.py b/tests/app/services/test_for_loop_session_runner.pyindex 4ec8ba32f8..39f0e14cf1 100644--- a/tests/app/services/test_for_loop_session_runner.py+++ b/tests/app/services/test_for_loop_session_runner.py@@ -110,6 +110,7 @@ def _build_nested_for_graph(collection: list[list[int]] | None = None,break_inner_after_first: bool = False,break_outer_after_first: bool = False,+ include_after: bool = True,) -> Graph:graph = Graph()graph.add_node(@@ -131,7 +132,8 @@ def _build_nested_for_graph(graph.add_node(ForRunnerConditionInvocation(id="outer_condition", continue_condition=not break_outer_after_first))graph.add_node(ForRunnerCollectionInvocation(id="outer_output"))graph.add_node(ForReturnInvocation(id="outer_return"))- graph.add_node(ForRunnerCollectionInvocation(id="after"))+ if include_after:+ graph.add_node(ForRunnerCollectionInvocation(id="after"))graph.add_edge(create_edge("outer_for", "item", "inner_collection", "value"))graph.add_edge(create_edge("inner_collection", "collection", "inner_for", "collection"))graph.add_edge(create_edge("inner_for", "item", "inner_body", "value"))@@ -141,7 +143,8 @@ def _build_nested_for_graph(graph.add_edge(create_edge("inner_for", "output_collection", "outer_condition", "value"))graph.add_edge(create_edge("outer_condition", "value", "outer_return", "continue_condition"))graph.add_edge(create_edge("outer_for", "state", "outer_return", "state"))- graph.add_edge(create_edge("outer_for", "output_collection", "after", "collection"))+ if include_after:+ graph.add_edge(create_edge("outer_for", "output_collection", "after", "collection"))graph.add_edge(create_loop_linkage("outer_for", "outer_return"))graph.add_edge(create_loop_linkage("inner_for", "inner_return"))return graph@@ -407,6 +410,35 @@ def test_session_runner_completes_nested_for_and_releases_outer_final_outputs(assert session.results[after_exec_id] == ForRunnerCollectionOutput(collection=[[1, 2], [3, 4]])+def test_session_runner_completes_nested_for_without_downstream_consumer(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session = GraphExecutionState(graph=_build_nested_for_graph(include_after=False))+ runner, _cancel_event, session_queue, _events = _build_runner(monkeypatch)+ queue_item = _build_queue_item(session)+ session_queue.add_queue_item(queue_item)++ runner.run(queue_item)++ assert queue_item.status == "completed"+ assert session_queue.completed_item_ids == [queue_item.item_id]+ assert session.is_complete()+++def test_session_runner_does_not_duplicate_empty_nested_loop_history(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ session = GraphExecutionState(graph=_build_nested_for_graph(collection=[[], []]))+ runner, _cancel_event, session_queue, _events = _build_runner(monkeypatch)+ queue_item = _build_queue_item(session)+ session_queue.add_queue_item(queue_item)++ runner.run(queue_item)++ assert queue_item.status == "completed"+ assert len(session.executed_history) == len(set(session.executed_history))++def test_session_runner_completes_nested_for_with_empty_inner_collection(monkeypatch: pytest.MonkeyPatch,) -> None: