Skip to content

Automate browser based workflows with AI

feat(SKY-8771): while_loop script generation and caching (#5869)

Shuchang Zheng228b30cd9477
diff --git a/skyvern/__init__.py b/skyvern/__init__.py
index ee16269e4..da736e0b0 100644
--- a/skyvern/__init__.py
+++ b/skyvern/__init__.py
@@ -32,6 +32,7 @@ _server_lazy_imports = {
"goto": "skyvern.services.script_service",
"login": "skyvern.services.script_service",
"loop": "skyvern.services.script_service",
+ "while_loop": "skyvern.services.script_service",
"parse_file": "skyvern.services.script_service",
"parse_pdf": "skyvern.services.script_service",
"prompt": "skyvern.services.script_service",
diff --git a/skyvern/core/script_generations/generate_script.py b/skyvern/core/script_generations/generate_script.py
index 58a246fce..e8e5f24ce 100644
--- a/skyvern/core/script_generations/generate_script.py
+++ b/skyvern/core/script_generations/generate_script.py
@@ -13,7 +13,7 @@ import re
import zlib
from collections import deque
from dataclasses import dataclass
-from typing import Any
+from typing import Any, Callable
import libcst as cst
import structlog
@@ -2692,7 +2692,56 @@ def _build_for_loop_statement(block_title: str, block: dict[str, Any]) -> cst.Fo
return for_loop
+def _while_loop_condition_expression(block: dict[str, Any]) -> str:
+ cond = block.get("condition")
+ if isinstance(cond, dict):
+ return str(cond.get("expression") or "")
+ return ""
+
+
+def _while_loop_condition_criteria_type(block: dict[str, Any]) -> str:
+ """Discriminator for while-loop condition; must match script_service.while_loop(replay)."""
+ cond = block.get("condition")
+ if isinstance(cond, dict):
+ ct = cond.get("criteria_type")
+ if ct is None or ct == "jinja2_template":
+ return "jinja2_template"
+ if ct == "prompt":
+ return "prompt"
+ raise ValueError(
+ f"while_loop codegen: unsupported condition criteria_type {ct!r} (expected 'jinja2_template' or 'prompt')"
+ )
+ return "jinja2_template"
+
+
+def _build_while_loop_statement(block_title: str, block: dict[str, Any]) -> cst.For:
+ """Build `async for ... in skyvern.while_loop(condition=..., criteria_type=..., label=...):`."""
+ loop_blocks = block.get("loop_blocks", [])
+ body_statements = [_build_block_statement(loop_block) for loop_block in loop_blocks]
+ condition_expr = _while_loop_condition_expression(block)
+ criteria_type = _while_loop_condition_criteria_type(block)
+ while_call = cst.Call(
+ func=cst.Attribute(value=cst.Name("skyvern"), attr=cst.Name("while_loop")),
+ args=[
+ cst.Arg(keyword=cst.Name("condition"), value=_value(condition_expr)),
+ cst.Arg(keyword=cst.Name("criteria_type"), value=_value(criteria_type)),
+ cst.Arg(keyword=cst.Name("label"), value=_value(block_title)),
+ ],
+ )
+ return cst.For(
+ target=cst.Name("current_value"),
+ iter=while_call,
+ body=cst.IndentedBlock(body=body_statements),
+ asynchronous=cst.Asynchronous(),
+ whitespace_after_for=cst.SimpleWhitespace(" "),
+ whitespace_before_in=cst.SimpleWhitespace(" "),
+ whitespace_after_in=cst.SimpleWhitespace(" "),
+ whitespace_before_colon=cst.SimpleWhitespace(""),
+ )
+
+
_FOR_LOOP_CACHED_CODE_RE = re.compile(r"^async for\b.*\bin\s+skyvern\.loop\s*\(")
+_WHILE_LOOP_CACHED_CODE_RE = re.compile(r"^async for\b.*\bin\s+skyvern\.while_loop\s*\(")
def _is_for_loop_cached_code(code: str) -> bool:
@@ -2710,6 +2759,20 @@ def _is_for_loop_cached_code(code: str) -> bool:
return False
+def _is_while_loop_cached_code(code: str) -> bool:
+ """True if *code* is a bare `async for ... in skyvern.while_loop(...):` (module-invalid)."""
+ for line in code.splitlines():
+ stripped = line.lstrip()
+ if not stripped or stripped.startswith("#"):
+ continue
+ return _WHILE_LOOP_CACHED_CODE_RE.match(stripped) is not None
+ return False
+
+
+def _is_inline_only_loop_cached_code(code: str) -> bool:
+ return _is_for_loop_cached_code(code) or _is_while_loop_cached_code(code)
+
+
def _mark_last_arg_as_comma(args: list[cst.Arg]) -> None:
if not args:
return
@@ -2921,6 +2984,8 @@ def _build_block_statement(
stmt = _build_wait_statement(block)
elif block_type == "for_loop":
stmt = _build_for_loop_statement(block_title, block)
+ elif block_type == "while_loop":
+ stmt = _build_while_loop_statement(block_title, block)
elif block_type == "goto_url":
stmt = _build_goto_statement(block, data_variable_name)
elif block_type == "code":
@@ -3320,203 +3385,210 @@ async def generate_workflow_script_python_code(
append_block_code(block_code)
- # Handle for_loop blocks
- # ForLoop blocks need script_block entries with run_signature so they can be executed via cached scripts
- for_loop_blocks = [block for block in blocks if block["block_type"] == "for_loop"]
- for for_loop_block in for_loop_blocks:
- for_loop_label = for_loop_block.get("label") or f"for_loop_{for_loop_block.get('workflow_run_block_id')}"
+ # Handle for_loop and while_loop blocks
+ _SCRIPT_LOOP_BUILDERS: list[tuple[str, Callable[[str, dict[str, Any]], cst.For]]] = [
+ ("for_loop", _build_for_loop_statement),
+ ("while_loop", _build_while_loop_statement),
+ ]
+ for sl_type, build_sl_stmt in _SCRIPT_LOOP_BUILDERS:
+ sl_typed_blocks = [block for block in blocks if block["block_type"] == sl_type]
+ sl_prefix = "for_loop" if sl_type == "for_loop" else "while_loop"
+ for sl_block in sl_typed_blocks:
+ sl_label = sl_block.get("label") or f"{sl_prefix}_{sl_block.get('workflow_run_block_id')}"
+
+ cached_source = cached_blocks.get(sl_label)
+ use_cached = cached_source is not None and sl_label not in updated_block_labels
+
+ block_workflow_run_id = sl_block.get("workflow_run_id") or run_id
+ block_workflow_run_block_id = sl_block.get("workflow_run_block_id")
+
+ if use_cached:
+ assert cached_source is not None
+ block_code = cached_source.code
+ run_signature = cached_source.run_signature
+ block_workflow_run_id = cached_source.workflow_run_id
+ block_workflow_run_block_id = cached_source.workflow_run_block_id
+ else:
+ sl_stmt = build_sl_stmt(sl_label, sl_block)
+ temp_module = cst.Module(body=[sl_stmt])
+ block_code = temp_module.code
+ run_signature = block_code.strip()
- cached_source = cached_blocks.get(for_loop_label)
- use_cached = cached_source is not None and for_loop_label not in updated_block_labels
+ if script_id and script_revision_id and organization_id:
+ ok = await create_or_update_script_block(
+ block_code=block_code,
+ script_revision_id=script_revision_id,
+ script_id=script_id,
+ organization_id=organization_id,
+ block_label=sl_label,
+ update=pending,
+ run_signature=run_signature,
+ workflow_run_id=block_workflow_run_id,
+ workflow_run_block_id=block_workflow_run_block_id,
+ input_fields=None,
+ )
+ if ok:
+ blocks_created += 1
+ else:
+ blocks_failed += 1
- block_workflow_run_id = for_loop_block.get("workflow_run_id") or run_id
- block_workflow_run_block_id = for_loop_block.get("workflow_run_block_id")
+ # NOTE: Do NOT call append_block_code() for for_loop / while_loop blocks.
+ # Unlike task blocks (which produce function definitions valid at module level),
+ # loop blocks produce bare `async for` statements that cause SyntaxError
+ # at module level ("async for outside async function"). Loop code is
+ # already correctly inlined inside run_workflow() via _build_block_statement().
+
+ # Generate cached function bodies for inner blocks nested in loop_blocks.
+ # Uses a BFS queue to recursively handle nested loops (SKY-8757).
+ loop_block_queue: deque[tuple[dict[str, Any], str]] = deque(
+ (lb, sl_label) for lb in sl_block.get("loop_blocks", [])
+ )
+ while loop_block_queue:
+ loop_block, parent_fl_label = loop_block_queue.popleft()
+ loop_block_type = loop_block.get("block_type")
+
+ # block_type is a string here (from dict.get on model_dump output),
+ # not a BlockType enum — unlike transform_workflow_run.py which
+ # works with ORM objects. Both compare correctly to string literals.
+ #
+ # Nested for-loop: create script_block for the inner for-loop itself,
+ # then push its children onto the queue for processing.
+ # NOTE: Do NOT call append_block_code() for nested for_loop blocks
+ # (same as top-level for_loops) — they produce bare `async for`
+ # statements that cause SyntaxError at module level.
+ if loop_block_type in ("for_loop", "while_loop"):
+ nested_prefix = "for_loop" if loop_block_type == "for_loop" else "while_loop"
+ nested_label = (
+ loop_block.get("label") or f"{nested_prefix}_{loop_block.get('workflow_run_block_id')}"
+ )
+ nested_build: Callable[[str, dict[str, Any]], cst.For] = (
+ _build_for_loop_statement if loop_block_type == "for_loop" else _build_while_loop_statement
+ )
- if use_cached:
- assert cached_source is not None
- block_code = cached_source.code
- run_signature = cached_source.run_signature
- block_workflow_run_id = cached_source.workflow_run_id
- block_workflow_run_block_id = cached_source.workflow_run_block_id
- else:
- # Build the for loop statement
- for_loop_stmt = _build_for_loop_statement(for_loop_label, for_loop_block)
- temp_module = cst.Module(body=[for_loop_stmt])
- block_code = temp_module.code
- run_signature = block_code.strip()
+ cached_nested = cached_blocks.get(nested_label)
+ # Force rebuild when the nested label OR its immediate parent
+ # loop is marked for regeneration (invalidation propagates
+ # down at every nesting depth, not just from the top-level).
+ use_nested_cached = (
+ cached_nested is not None
+ and nested_label not in updated_block_labels
+ and parent_fl_label not in updated_block_labels
+ )
- if script_id and script_revision_id and organization_id:
- ok = await create_or_update_script_block(
- block_code=block_code,
- script_revision_id=script_revision_id,
- script_id=script_id,
- organization_id=organization_id,
- block_label=for_loop_label,
- update=pending,
- run_signature=run_signature,
- workflow_run_id=block_workflow_run_id,
- workflow_run_block_id=block_workflow_run_block_id,
- input_fields=None,
- )
- if ok:
- blocks_created += 1
- else:
- blocks_failed += 1
+ nested_wrbi = loop_block.get("workflow_run_block_id")
+ nested_wri = loop_block.get("workflow_run_id") or run_id
+
+ # use_nested_cached already guarantees cached_nested is not None;
+ # the explicit check is retained only for mypy type narrowing.
+ if (
+ use_nested_cached
+ and cached_nested is not None
+ and cached_nested.code
+ and cached_nested.run_signature
+ ):
+ nested_code = cached_nested.code
+ nested_sig = cached_nested.run_signature
+ nested_wrbi = cached_nested.workflow_run_block_id
+ nested_wri = cached_nested.workflow_run_id
+ else:
+ # No usable cache entry (missing, incomplete, or needs update)
+ # — rebuild from current run data. Mark this label as updated
+ # so invalidation cascades to deeper descendants.
+ updated_block_labels.add(nested_label)
+ nested_stmt = nested_build(nested_label, loop_block)
+ temp_mod = cst.Module(body=[nested_stmt])
+ nested_code = temp_mod.code
+ nested_sig = nested_code.strip()
+
+ if script_id and script_revision_id and organization_id:
+ ok = await create_or_update_script_block(
+ block_code=nested_code,
+ script_revision_id=script_revision_id,
+ script_id=script_id,
+ organization_id=organization_id,
+ block_label=nested_label,
+ update=pending,
+ run_signature=nested_sig,
+ workflow_run_id=nested_wri,
+ workflow_run_block_id=nested_wrbi,
+ input_fields=None,
+ )
+ if ok:
+ blocks_created += 1
+ else:
+ blocks_failed += 1
+
+ # Push nested loop's children with this loop as their parent
+ loop_block_queue.extend((child, nested_label) for child in loop_block.get("loop_blocks", []))
+ continue
- # NOTE: Do NOT call append_block_code() for for_loop blocks.
- # Unlike task blocks (which produce function definitions valid at module level),
- # for_loop blocks produce bare `async for` statements that cause SyntaxError
- # at module level ("async for outside async function"). The for-loop code is
- # already correctly inlined inside run_workflow() via _build_block_statement().
-
- # Generate cached function bodies for for_loop inner blocks.
- # Inner blocks (e.g. extraction inside a loop) are nested in loop_blocks and
- # are NOT in the top-level blocks list, so they need separate processing here.
- # This follows the same pattern as task_v2 child block handling (lines 2704-2714).
- # Uses a BFS queue to recursively handle nested for-loops (SKY-8757).
- # Each queue entry is (block_dict, parent_forloop_label) so cache
- # invalidation propagates from the correct parent at any depth.
- loop_block_queue: deque[tuple[dict[str, Any], str]] = deque(
- (lb, for_loop_label) for lb in for_loop_block.get("loop_blocks", [])
- )
- while loop_block_queue:
- loop_block, parent_fl_label = loop_block_queue.popleft()
- loop_block_type = loop_block.get("block_type")
-
- # block_type is a string here (from dict.get on model_dump output),
- # not a BlockType enum — unlike transform_workflow_run.py which
- # works with ORM objects. Both compare correctly to string literals.
- #
- # Nested for-loop: create script_block for the inner for-loop itself,
- # then push its children onto the queue for processing.
- # NOTE: Do NOT call append_block_code() for nested for_loop blocks
- # (same as top-level for_loops) — they produce bare `async for`
- # statements that cause SyntaxError at module level.
- if loop_block_type == "for_loop":
- nested_label = loop_block.get("label") or f"for_loop_{loop_block.get('workflow_run_block_id')}"
-
- cached_nested = cached_blocks.get(nested_label)
- # Force rebuild when the nested label OR its immediate parent
- # for-loop is marked for regeneration (invalidation propagates
- # down at every nesting depth, not just from the top-level).
- use_nested_cached = (
- cached_nested is not None
- and nested_label not in updated_block_labels
- and parent_fl_label not in updated_block_labels
+ if loop_block_type not in SCRIPT_TASK_BLOCKS:
+ continue
+
+ inner_label = (
+ loop_block.get("label")
+ or loop_block.get("title")
+ or f"block_{loop_block.get('workflow_run_block_id')}"
)
- nested_wrbi = loop_block.get("workflow_run_block_id")
- nested_wri = loop_block.get("workflow_run_id") or run_id
-
- # use_nested_cached already guarantees cached_nested is not None;
- # the explicit check is retained only for mypy type narrowing.
- if (
- use_nested_cached
- and cached_nested is not None
- and cached_nested.code
- and cached_nested.run_signature
- ):
- nested_code = cached_nested.code
- nested_sig = cached_nested.run_signature
- nested_wrbi = cached_nested.workflow_run_block_id
- nested_wri = cached_nested.workflow_run_id
+ # Check if already cached (for progressive caching)
+ cached_inner = cached_blocks.get(inner_label)
+ use_inner_cached = cached_inner is not None and inner_label not in updated_block_labels
+
+ if use_inner_cached:
+ assert cached_inner is not None
+ inner_block_code = cached_inner.code
+ inner_run_signature = cached_inner.run_signature
+ inner_wrbi = cached_inner.workflow_run_block_id
+ inner_wri = cached_inner.workflow_run_id
else:
- # No usable cache entry (missing, incomplete, or needs update)
- # — rebuild from current run data. Mark this label as updated
- # so invalidation cascades to deeper descendants.
- updated_block_labels.add(nested_label)
- nested_stmt = _build_for_loop_statement(nested_label, loop_block)
- temp_mod = cst.Module(body=[nested_stmt])
- nested_code = temp_mod.code
- nested_sig = nested_code.strip()
+ inner_actions = actions_by_task.get(loop_block.get("task_id", ""), [])
+ if not inner_actions:
+ # No actions from agent run = can't generate cached function.
+ # No script_block row is created; the block will be cached on
+ # a future run when actions become available. This is intentional
+ # — generating a stub would produce broken code.
+ continue
+
+ inner_fn_def = _build_block_fn(
+ loop_block,
+ inner_actions,
+ value_to_param=value_to_param,
+ use_semantic_selectors=use_semantic_selectors,
+ is_in_for_loop=True,
+ credential_param_keys=credential_param_keys,
+ )
+ inner_block_code = cst.Module(body=[inner_fn_def]).code
+ inner_stmt = _build_block_statement(loop_block, value_to_param=None)
+ inner_run_signature = cst.Module(body=[inner_stmt]).code.strip()
+
+ inner_wrbi = loop_block.get("workflow_run_block_id")
+ inner_wri = loop_block.get("workflow_run_id") or run_id
+
+ # Create script_block entry for preservation across regenerations
if script_id and script_revision_id and organization_id:
+ inner_input_fields = _collect_block_input_fields(loop_block, actions_by_task)
+ if not inner_input_fields and cached_inner and cached_inner.input_fields:
+ inner_input_fields = cached_inner.input_fields
ok = await create_or_update_script_block(
- block_code=nested_code,
+ block_code=inner_block_code,
script_revision_id=script_revision_id,
script_id=script_id,
organization_id=organization_id,
- block_label=nested_label,
+ block_label=inner_label,
update=pending,
- run_signature=nested_sig,
- workflow_run_id=nested_wri,
- workflow_run_block_id=nested_wrbi,
- input_fields=None,
+ run_signature=inner_run_signature,
+ workflow_run_id=inner_wri,
+ workflow_run_block_id=inner_wrbi,
+ input_fields=inner_input_fields,
)
if ok:
blocks_created += 1
else:
blocks_failed += 1
- # Push nested for-loop's children with this loop as their parent
- loop_block_queue.extend((child, nested_label) for child in loop_block.get("loop_blocks", []))
- continue
-
- if loop_block_type not in SCRIPT_TASK_BLOCKS:
- continue
-
- inner_label = (
- loop_block.get("label") or loop_block.get("title") or f"block_{loop_block.get('workflow_run_block_id')}"
- )
-
- # Check if already cached (for progressive caching)
- cached_inner = cached_blocks.get(inner_label)
- use_inner_cached = cached_inner is not None and inner_label not in updated_block_labels
-
- if use_inner_cached:
- assert cached_inner is not None
- inner_block_code = cached_inner.code
- inner_run_signature = cached_inner.run_signature
- inner_wrbi = cached_inner.workflow_run_block_id
- inner_wri = cached_inner.workflow_run_id
- else:
- inner_actions = actions_by_task.get(loop_block.get("task_id", ""), [])
- if not inner_actions:
- # No actions from agent run = can't generate cached function.
- # No script_block row is created; the block will be cached on
- # a future run when actions become available. This is intentional
- # — generating a stub would produce broken code.
- continue
-
- inner_fn_def = _build_block_fn(
- loop_block,
- inner_actions,
- value_to_param=value_to_param,
- use_semantic_selectors=use_semantic_selectors,
- is_in_for_loop=True,
- credential_param_keys=credential_param_keys,
- )
- inner_block_code = cst.Module(body=[inner_fn_def]).code
-
- inner_stmt = _build_block_statement(loop_block, value_to_param=None)
- inner_run_signature = cst.Module(body=[inner_stmt]).code.strip()
-
- inner_wrbi = loop_block.get("workflow_run_block_id")
- inner_wri = loop_block.get("workflow_run_id") or run_id
-
- # Create script_block entry for preservation across regenerations
- if script_id and script_revision_id and organization_id:
- inner_input_fields = _collect_block_input_fields(loop_block, actions_by_task)
- if not inner_input_fields and cached_inner and cached_inner.input_fields:
- inner_input_fields = cached_inner.input_fields
- ok = await create_or_update_script_block(
- block_code=inner_block_code,
- script_revision_id=script_revision_id,
- script_id=script_id,
- organization_id=organization_id,
- block_label=inner_label,
- update=pending,
- run_signature=inner_run_signature,
- workflow_run_id=inner_wri,
- workflow_run_block_id=inner_wrbi,
- input_fields=inner_input_fields,
- )
- if ok:
- blocks_created += 1
- else:
- blocks_failed += 1
-
- append_block_code(inner_block_code)
+ append_block_code(inner_block_code)
# --- agent-required blocks (adaptive caching) -----------------------
# Structural blocks (conditional, text_prompt, wait) can't be code-generated
@@ -3583,24 +3655,25 @@ async def generate_workflow_script_python_code(
for task_v2 in task_v2_blocks:
label = task_v2.get("label") or f"task_v2_{task_v2.get('workflow_run_block_id')}"
processed_labels.add(label)
- for flb in for_loop_blocks:
- label = flb.get("label") or f"for_loop_{flb.get('workflow_run_block_id')}"
+ for slb in [b for b in blocks if b["block_type"] in ("for_loop", "while_loop")]:
+ slb_type = slb["block_type"]
+ label = slb.get("label") or (
+ f"for_loop_{slb.get('workflow_run_block_id')}"
+ if slb_type == "for_loop"
+ else f"while_loop_{slb.get('workflow_run_block_id')}"
+ )
processed_labels.add(label)
- # Recursively track all inner block labels (including nested for-loops)
- # to prevent duplication in the "preserve unexecuted branch" section below.
- # Use the same label derivation as the main code generation loop to ensure
- # labels match (e.g., for_loop blocks without explicit labels get the
- # "for_loop_{workflow_run_block_id}" fallback).
- inner_queue: deque[dict[str, Any]] = deque(flb.get("loop_blocks", []))
+ inner_queue: deque[dict[str, Any]] = deque(slb.get("loop_blocks", []))
while inner_queue:
lb = inner_queue.popleft()
lb_type = lb.get("block_type")
if lb_type == "for_loop":
inner_lbl = lb.get("label") or f"for_loop_{lb.get('workflow_run_block_id')}"
inner_queue.extend(lb.get("loop_blocks", []))
+ elif lb_type == "while_loop":
+ inner_lbl = lb.get("label") or f"while_loop_{lb.get('workflow_run_block_id')}"
+ inner_queue.extend(lb.get("loop_blocks", []))
else:
- # Use the same 3-fallback chain as the main generation loop
- # (label → title → block_{wrb_id}) so labels always match.
inner_lbl = lb.get("label") or lb.get("title") or f"block_{lb.get('workflow_run_block_id')}"
if inner_lbl:
processed_labels.add(inner_lbl)
@@ -3640,7 +3713,7 @@ async def generate_workflow_script_python_code(
# async run_workflow body via _build_block_statement — which only happens
# for for_loops in the current run's `blocks`. Skip appending to main.py
# for for_loop cached code from unexecuted branches to avoid the error.
- if _is_for_loop_cached_code(cached_source.code):
+ if _is_inline_only_loop_cached_code(cached_source.code):
continue
append_block_code(cached_source.code)
@@ -3656,7 +3729,7 @@ async def generate_workflow_script_python_code(
if label not in processed_labels
and source.code
and source.run_signature
- and not _is_for_loop_cached_code(source.code)
+ and not _is_inline_only_loop_cached_code(source.code)
],
)
diff --git a/skyvern/core/script_generations/real_skyvern_page_ai.py b/skyvern/core/script_generations/real_skyvern_page_ai.py
index ec1202417..af157f3c1 100644
--- a/skyvern/core/script_generations/real_skyvern_page_ai.py
+++ b/skyvern/core/script_generations/real_skyvern_page_ai.py
@@ -133,9 +133,9 @@ def render_template(template: str, data: dict[str, Any] | None = None) -> str:
if template in template_data:
return template_data[template]
- # Inject for_loop metadata (current_value, current_index, current_item) so
- # that cached function bodies inside for_loops can resolve {{ current_value }}
- # in page.goto() and other template-rendered calls.
+ # Inject loop metadata from script `skyvern.loop()` / `skyvern.while_loop()`
+ # (current_value, current_index, current_item) so cached function bodies inside
+ # loops can resolve templates. while_loop yields null current_value; index is set.
if context and context.loop_metadata:
for key in ("current_value", "current_index", "current_item"):
if key in context.loop_metadata:
diff --git a/skyvern/core/script_generations/transform_workflow_run.py b/skyvern/core/script_generations/transform_workflow_run.py
index 4c8e99ce3..671ce838e 100644
--- a/skyvern/core/script_generations/transform_workflow_run.py
+++ b/skyvern/core/script_generations/transform_workflow_run.py
@@ -116,8 +116,8 @@ def _process_forloop_children(
existing_completed = str(existing.status) == "completed"
if b_completed and not existing_completed:
child_run_blocks_by_label[b.label] = b
- elif b.block_type == BlockType.FOR_LOOP:
- # Prefer the nested for-loop iteration that produced grandchildren.
+ elif b.block_type in (BlockType.FOR_LOOP, BlockType.WHILE_LOOP):
+ # Prefer the nested loop iteration that produced grandchildren.
# On ties, break by total deep-descendant action count so the
# iteration with usable actions wins even at 3+ nesting levels.
existing_children = children_by_parent.get(existing.workflow_run_block_id, [])
@@ -188,9 +188,9 @@ def _process_forloop_children(
forloop_label=forloop_run_block.label,
)
- # Recursively process nested for-loops so their inner blocks
+ # Recursively process nested for / while loops so their inner blocks
# also get task_id and actions merged (SKY-8757).
- if child_run_block and child_run_block.block_type == BlockType.FOR_LOOP:
+ if child_run_block and child_run_block.block_type in (BlockType.FOR_LOOP, BlockType.WHILE_LOOP):
nested_forloop_count += 1
inner_loop_blocks = loop_block_dump.get("loop_blocks", [])
if inner_loop_blocks:
@@ -202,7 +202,7 @@ def _process_forloop_children(
actions_by_task_id=actions_by_task_id,
actions_by_task=actions_by_task,
)
- # Always set run block metadata for the inner for-loop, even when
+ # Always set run block metadata for the inner loop block, even when
# loop_blocks is empty. generate_script.py needs workflow_run_block_id
# for script_block creation and label fallback derivation.
loop_block_dump["workflow_run_block_id"] = child_run_block.workflow_run_block_id
@@ -383,7 +383,7 @@ async def transform_workflow_run_to_code_gen_input(workflow_run_id: str, organiz
task_v2_label=run_block.label,
)
- if run_block.block_type == BlockType.FOR_LOOP:
+ if run_block.block_type in (BlockType.FOR_LOOP, BlockType.WHILE_LOOP):
final_dump["loop_blocks"] = _process_forloop_children(
forloop_run_block=run_block,
loop_blocks_def=final_dump.get("loop_blocks", []),
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
index 64c542132..1a1838c94 100644
--- a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
@@ -78,10 +78,11 @@ When a run fails with "Access Denied", an Akamai/Cloudflare/Imperva reference, o
1. Do NOT declare infeasible from a single challenge page.
2. IMPORTANT: Do NOT add a wait/delay block — timing does not fix IP-based bans.
3. IMPORTANT: Do NOT switch to an HTTP_REQUEST block to the same URL — a request from the same server IP will receive the same block.
-4. Instead, try: setting proxy_location on the workflow to route through a different IP, or using a different entry URL that may not trigger the WAF.
+4. Instead, try: setting proxy_location on the workflow to route through a different IP (use `RESIDENTIAL` by default, or a US-state value like `US-CA`/`US-NY`; do NOT use bare country codes like `US` — they are not valid ProxyLocation members), or using a different entry URL that may not trigger the WAF.
5. For interactive challenges (Cloudflare "verify you are human" checkbox), attempt automated resolution via workflow goals/steps.
-6. Try at least two genuinely distinct approaches before concluding infeasible.
-7. If still blocked, explain to the user that the site has anti-bot protection that requires proxy configuration, and describe exactly what you tried.
+6. Do NOT put an unconditional anti-bot/challenge block at the front of every workflow. If you add challenge handling, make it conditional on visible evidence such as Cloudflare, Access Denied, CAPTCHA, security check, or "verify you are human" text. The unblocked path should proceed directly to the normal requested task.
+7. Try at least two genuinely distinct approaches before concluding infeasible.
+8. If still blocked, explain the specific anti-bot evidence observed (for example Cloudflare, CAPTCHA, "verify you are human", Access Denied, or a blank "Just a moment..." page), describe exactly what you tried, and ask whether to try a different proxy/location, entry URL, or alternate source.
MANDATORY: After every workflow update, you MUST test it. Prefer update_and_run_blocks (single call) over separate update_workflow + run_blocks_and_collect_debug calls. Never skip testing. Grow the workflow incrementally (known-good blocks + next block) unless the user explicitly asks for a one-shot full draft. Feasibility decisions must be based on the latest test result. If you conclude the request is infeasible, explain the specific evidence from that latest run.
MANDATORY: The Accept/Reject proposal UI only appears when your latest run_blocks_and_collect_debug or update_and_run_blocks returned ok=true this turn. An untested update_workflow is silently dropped from the user-visible proposal — if you want the user to be able to accept your change, you MUST verify it with a passing test in this same turn. If testing is impossible for any reason (missing credentials, required human input), stop and ask a clarifying question instead of leaving an untested draft.
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index ce052b09c..0e7e42c37 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -278,9 +278,19 @@ POST_ANTI_BOT_FAILED_TEST_NUDGE = (
"- A simple wait/delay block (timing does not fix IP bans)\n"
"- A raw HTTP_REQUEST to the same URL (same IP = same block)\n"
"Instead, try:\n"
- "1. Set proxy_location on the workflow to route through a different IP.\n"
- "2. If proxy is not available, explain to the user that the site has "
- "anti-bot protection that requires proxy configuration.\n"
+ "1. Set proxy_location on the workflow to route through a different IP "
+ "(use `RESIDENTIAL` by default, or a US-state value like `US-CA`/`US-NY`; "
+ "do NOT use bare country codes like `US` — they are not valid "
+ "ProxyLocation members).\n"
+ "2. If you add anti-bot handling blocks, make them conditional on visible "
+ "challenge evidence (for example Cloudflare, Access Denied, CAPTCHA, or "
+ "verify-you-are-human text). Do NOT assume every run starts on a challenge "
+ "page; normal, unblocked runs should proceed directly to the requested task.\n"
+ "3. If still blocked, explain the specific anti-bot evidence observed "
+ "(for example Cloudflare, CAPTCHA, verify-you-are-human text, Access "
+ "Denied, or a blank Just-a-moment page); describe exactly what you tried; "
+ "and ask whether to try a different proxy/location, entry URL, or "
+ "alternate source.\n"
"Do NOT resubmit the same workflow with trivial changes."
)
diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.py
index 1f14623cc..7c5f1668c 100644
--- a/skyvern/forge/sdk/copilot/tools.py
+++ b/skyvern/forge/sdk/copilot/tools.py
@@ -581,6 +581,7 @@ async def _update_workflow(params: dict[str, Any], ctx: AgentContext) -> dict[st
organization_id=ctx.organization_id,
workflow_yaml=workflow_yaml,
)
+ _record_workflow_proxy_location_span(workflow_yaml, workflow)
created_by_stamp = await resolve_copilot_created_by_stamp(ctx.workflow_id, ctx.organization_id)
@@ -1958,6 +1959,41 @@ def _record_banned_block_reject_span(source_tool: str, items: list[tuple[str, st
pass
+def _proxy_location_trace_value(proxy_location: Any) -> Any:
+ if proxy_location is None:
+ return None
+ if hasattr(proxy_location, "value"):
+ return proxy_location.value
+ if hasattr(proxy_location, "model_dump"):
+ return proxy_location.model_dump(mode="json")
+ return proxy_location
+
+
+def _raw_yaml_proxy_location(workflow_yaml: str) -> tuple[bool, Any]:
+ try:
+ parsed_yaml = safe_load_no_dates(workflow_yaml)
+ except yaml.YAMLError:
+ return False, None
+
+ if not isinstance(parsed_yaml, dict) or "proxy_location" not in parsed_yaml:
+ return False, None
+ return True, _proxy_location_trace_value(parsed_yaml.get("proxy_location"))
+
+
+def _record_workflow_proxy_location_span(workflow_yaml: str, workflow: Workflow) -> None:
+ input_present, input_proxy_location = _raw_yaml_proxy_location(workflow_yaml)
+ effective_proxy_location = _proxy_location_trace_value(workflow.proxy_location)
+ with copilot_span(
+ "workflow_proxy_location_normalized",
+ data={
+ "input_proxy_location_present": input_present,
+ "input_proxy_location": input_proxy_location,
+ "effective_proxy_location": effective_proxy_location,
+ },
+ ):
+ pass
+
+
def _collect_banned_block_items(blocks: list[Any]) -> list[tuple[str, str]]:
"""Recursively walk ``blocks`` (mirroring
:func:`skyvern.forge.sdk.copilot.block_goal_wrapping._wrap_blocks_in_place`)
diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.py
index e08cd412a..dab3b5d1c 100644
--- a/skyvern/forge/sdk/routes/workflow_copilot.py
+++ b/skyvern/forge/sdk/routes/workflow_copilot.py
@@ -50,6 +50,7 @@ from skyvern.forge.sdk.workflow.exceptions import BaseWorkflowHTTPException
from skyvern.forge.sdk.workflow.models.parameter import ParameterType
from skyvern.forge.sdk.workflow.models.workflow import Workflow
from skyvern.forge.sdk.workflow.workflow_definition_converter import convert_workflow_definition
+from skyvern.schemas.runs import ProxyLocation
from skyvern.schemas.workflows import (
BlockYAML,
BranchConditionYAML,
@@ -69,6 +70,51 @@ CHAT_HISTORY_CONTEXT_MESSAGES = 10
LOG = structlog.get_logger()
+def _proxy_location_alias_key(value: str) -> str:
+ return "_".join(value.strip().upper().replace("-", "_").split())
+
+
+def _build_copilot_proxy_location_aliases() -> dict[str, str]:
+ aliases: dict[str, str] = {}
+
+ def add(alias: str, proxy_location: ProxyLocation) -> None:
+ aliases[_proxy_location_alias_key(alias)] = proxy_location.value
+
+ for proxy_location in ProxyLocation:
+ add(proxy_location.name, proxy_location)
+ add(proxy_location.value, proxy_location)
+
+ for proxy_location in ProxyLocation.residential_country_locations():
+ add(ProxyLocation.get_country_code(proxy_location), proxy_location)
+
+ add("USA", ProxyLocation.RESIDENTIAL)
+ add("United States", ProxyLocation.RESIDENTIAL)
+ add("United States of America", ProxyLocation.RESIDENTIAL)
+ add("RESIDENTIAL_US", ProxyLocation.RESIDENTIAL)
+ add("UK", ProxyLocation.RESIDENTIAL_GB)
+ add("United Kingdom", ProxyLocation.RESIDENTIAL_GB)
+
+ return aliases
+
+
+_COPILOT_PROXY_LOCATION_ALIASES = _build_copilot_proxy_location_aliases()
+
+
+def _canonicalize_copilot_proxy_location(parsed_yaml: dict[str, Any]) -> None:
+ if "proxy_location" not in parsed_yaml:
+ return
+
+ proxy_location = parsed_yaml.get("proxy_location")
+ if not isinstance(proxy_location, str):
+ return
+
+ canonical = _COPILOT_PROXY_LOCATION_ALIASES.get(_proxy_location_alias_key(proxy_location))
+ if canonical is None:
+ return
+
+ parsed_yaml["proxy_location"] = canonical
+
+
async def _resolve_copilot_agent_handler(
workflow_permanent_id: str,
organization_id: str,
@@ -968,6 +1014,7 @@ def _normalize_copilot_yaml(workflow_yaml: str) -> WorkflowCreateYAMLRequest:
if isinstance(parsed_yaml, dict):
# title is schema-required; coerce rather than force a self-healing round-trip.
parsed_yaml.setdefault("title", "")
+ _canonicalize_copilot_proxy_location(parsed_yaml)
workflow_definition = parsed_yaml.get("workflow_definition", None)
if workflow_definition:
blocks = workflow_definition.get("blocks", []) or []
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index d3c181510..6d93d2f78 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -173,6 +173,7 @@ BLOCK_TYPES_THAT_SHOULD_BE_CACHED = {
BlockType.LOGIN,
BlockType.FILE_DOWNLOAD,
BlockType.FOR_LOOP,
+ BlockType.WHILE_LOOP,
}
diff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.py
index a260793a3..92f32f9e3 100644
--- a/skyvern/services/script_service.py
+++ b/skyvern/services/script_service.py
@@ -45,6 +45,8 @@ from skyvern.forge.sdk.models import Step, StepStatus
from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.schemas.tasks import Task, TaskOutput, TaskStatus
from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock
+from skyvern.forge.sdk.workflow.context_manager import BlockMetadata
+from skyvern.forge.sdk.workflow.exceptions import FailedToFormatJinjaStyleParameter, MissingJinjaVariables
from skyvern.forge.sdk.workflow.loop_download_filter import (
filter_downloaded_files_for_current_iteration as _filter_downloaded_files_for_current_iteration,
)
@@ -52,6 +54,7 @@ from skyvern.forge.sdk.workflow.loop_download_filter import (
to_downloaded_file_signature as _to_downloaded_file_signature,
)
from skyvern.forge.sdk.workflow.models.block import (
+ DEFAULT_MAX_LOOP_ITERATIONS,
ActionBlock,
CodeBlock,
ExtractionBlock,
@@ -60,14 +63,17 @@ from skyvern.forge.sdk.workflow.models.block import (
FileUploadBlock,
ForLoopBlock,
HttpRequestBlock,
+ JinjaBranchCriteria,
LoginBlock,
NavigationBlock,
PDFParserBlock,
+ PromptBranchCriteria,
SendEmailBlock,
TaskBlock,
TextPromptBlock,
UrlBlock,
ValidationBlock,
+ WhileLoopBlock,
WorkflowTriggerBlock,
)
from skyvern.forge.sdk.workflow.models.parameter import PARAMETER_TYPE, OutputParameter, ParameterType
@@ -2687,9 +2693,9 @@ def render_template(template: str, data: dict[str, Any] | None = None) -> str:
template_data.update(workflow_run_context.values)
if template in template_data:
return template_data[template]
- # Inject for_loop metadata (current_value, current_index, current_item) so
- # that cached function bodies inside for_loops can resolve {{ current_value }}
- # in page.goto() and other template-rendered calls.
+ # Inject for_loop / while_loop metadata (current_value, current_index, current_item) so
+ # that cached function bodies inside script loops can resolve {{ current_value }}
+ # in page.goto() and other template-rendered calls. while_loop only sets current_index.
if context.loop_metadata:
for key in ("current_value", "current_index", "current_item"):
if key in context.loop_metadata:
@@ -3197,7 +3203,150 @@ async def loop(
output=block_validation_output.context.loop_output_values,
label=label,
)
- raise e
+ raise
+ finally:
+ block_validation_output.context.parent_workflow_run_block_id = None
+ block_validation_output.context.loop_metadata = None
+ block_validation_output.context.loop_internal_state = None
+ block_validation_output.context.loop_output_values = None
+
+
+def _while_loop_branch_criteria(
+ condition: str, criteria_type: str | None
+) -> JinjaBranchCriteria | PromptBranchCriteria:
+ """Rehydrate persisted branch criteria for cached script replay (must match workflow definition)."""
+ ct = "jinja2_template" if criteria_type is None else criteria_type
+ if ct == "jinja2_template":
+ return JinjaBranchCriteria(expression=condition)
+ if ct == "prompt":
+ return PromptBranchCriteria(expression=condition)
+ raise ValueError(
+ f"skyvern.while_loop: unsupported criteria_type {criteria_type!r} (expected 'jinja2_template' or 'prompt')"
+ )
+
+
+async def while_loop(
+ condition: str,
+ label: str | None = None,
+ *,
+ criteria_type: str | None = None,
+) -> AsyncGenerator[SkyvernLoopItem, None]:
+ workflow_run_block_id, _, _ = await _create_workflow_block_run_and_task(
+ block_type=BlockType.WHILE_LOOP,
+ label=label,
+ )
+ block_validation_output = await _validate_and_get_output_parameter(label)
+ workflow_run_id = block_validation_output.workflow_run_id
+ organization_id = block_validation_output.organization_id
+
+ workflow_run_context = app.WORKFLOW_CONTEXT_MANAGER.get_workflow_run_context(workflow_run_id)
+ while_block = WhileLoopBlock(
+ label=block_validation_output.label,
+ output_parameter=block_validation_output.output_parameter,
+ condition=_while_loop_branch_criteria(condition, criteria_type),
+ loop_blocks=[],
+ )
+
+ block_validation_output.context.parent_workflow_run_block_id = workflow_run_block_id
+ block_validation_output.context.loop_output_values = []
+
+ loop_idx = 0
+ try:
+ while True:
+ condition_metadata: BlockMetadata = {
+ "current_index": loop_idx,
+ "current_value": None,
+ "current_item": None,
+ }
+ workflow_run_context.update_block_metadata(block_validation_output.label, condition_metadata)
+
+ try:
+ should_continue = await while_block._evaluate_condition(
+ workflow_run_context,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id or "",
+ organization_id=organization_id,
+ browser_session_id=block_validation_output.browser_session_id,
+ )
+ except (FailedToFormatJinjaStyleParameter, MissingJinjaVariables) as exc:
+ if workflow_run_block_id:
+ await _update_workflow_block(
+ workflow_run_block_id,
+ BlockStatus.failed,
+ failure_reason=f"Failed to evaluate while-loop condition: {exc}",
+ output=block_validation_output.context.loop_output_values,
+ label=label,
+ )
+ raise Exception(f"Failed to evaluate while-loop condition: {exc}") from exc
+
+ if not should_continue:
+ break
+
+ if loop_idx >= DEFAULT_MAX_LOOP_ITERATIONS:
+ failure_reason = f"Reached max_loop_iterations limit of {DEFAULT_MAX_LOOP_ITERATIONS}"
+ if workflow_run_block_id:
+ await _update_workflow_block(
+ workflow_run_block_id,
+ BlockStatus.failed,
+ failure_reason=failure_reason,
+ output=block_validation_output.context.loop_output_values,
+ label=label,
+ )
+ raise Exception(failure_reason)
+
+ downloaded_file_signatures_before_iteration: list[tuple[str | None, str | None, str | None]] = []
+ baseline_timed_out = False
+ try:
+ async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
+ downloaded_file_signatures_before_iteration = [
+ _to_downloaded_file_signature(file_info)
+ for file_info in await app.STORAGE.get_downloaded_files(
+ organization_id=organization_id or "",
+ run_id=workflow_run_id,
+ )
+ ]
+ except asyncio.TimeoutError:
+ baseline_timed_out = True
+ LOG.warning(
+ "Timeout getting baseline downloaded files for while loop iteration",
+ workflow_run_id=workflow_run_id,
+ loop_index=loop_idx,
+ )
+
+ loop_metadata: BlockMetadata = {
+ "current_index": loop_idx,
+ "current_value": None,
+ "current_item": None,
+ }
+ block_validation_output.context.loop_metadata = loop_metadata
+ if baseline_timed_out:
+ block_validation_output.context.loop_internal_state = None
+ else:
+ block_validation_output.context.loop_internal_state = {
+ "downloaded_file_signatures_before_iteration": downloaded_file_signatures_before_iteration,
+ }
+ workflow_run_context.update_block_metadata(block_validation_output.label, loop_metadata)
+
+ yield SkyvernLoopItem(loop_idx, None)
+ loop_idx += 1
+
+ if workflow_run_block_id:
+ await _update_workflow_block(
+ workflow_run_block_id,
+ BlockStatus.completed,
+ output=block_validation_output.context.loop_output_values,
+ label=label,
+ )
+ except Exception as e:
+ if workflow_run_block_id:
+ await _update_workflow_block(
+ workflow_run_block_id,
+ BlockStatus.failed,
+ failure_reason=str(e),
+ output=block_validation_output.context.loop_output_values,
+ label=label,
+ )
+ raise
finally:
block_validation_output.context.parent_workflow_run_block_id = None
block_validation_output.context.loop_metadata = None
diff --git a/tests/unit/test_copilot_task_block_rejection.py b/tests/unit/test_copilot_task_block_rejection.py
index 40e10e09d..5f0dcd1c5 100644
--- a/tests/unit/test_copilot_task_block_rejection.py
+++ b/tests/unit/test_copilot_task_block_rejection.py
@@ -17,7 +17,13 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
import yaml
-from skyvern.forge.sdk.copilot.tools import _detect_new_banned_blocks, _update_workflow
+from skyvern.forge.sdk.copilot.tools import (
+ _detect_new_banned_blocks,
+ _proxy_location_trace_value,
+ _raw_yaml_proxy_location,
+ _update_workflow,
+)
+from skyvern.schemas.runs import ProxyLocation
def _yaml(*blocks: dict) -> str:
@@ -27,6 +33,19 @@ def _yaml(*blocks: dict) -> str:
)
+def test_raw_yaml_proxy_location_reports_absent_value() -> None:
+ assert _raw_yaml_proxy_location(_yaml({"block_type": "navigation", "label": "n"})) == (False, None)
+
+
+def test_raw_yaml_proxy_location_reports_explicit_values() -> None:
+ assert _raw_yaml_proxy_location("title: wf\nproxy_location: US\n") == (True, "US")
+ assert _raw_yaml_proxy_location("title: wf\nproxy_location: null\n") == (True, None)
+
+
+def test_proxy_location_trace_value_serializes_enum_values() -> None:
+ assert _proxy_location_trace_value(ProxyLocation.RESIDENTIAL) == "RESIDENTIAL"
+
+
# ---------- Flat shapes ----------
@@ -301,6 +320,7 @@ async def test_update_workflow_preserves_legacy_task_block_under_unchanged_label
with (
patch("skyvern.forge.sdk.copilot.tools._process_workflow_yaml", return_value=fake_workflow),
+ patch("skyvern.forge.sdk.copilot.tools._record_workflow_proxy_location_span") as mock_proxy_span,
patch("skyvern.forge.sdk.copilot.tools.app") as mock_app,
):
mock_app.WORKFLOW_SERVICE.get_workflow = AsyncMock(return_value=None)
@@ -308,6 +328,7 @@ async def test_update_workflow_preserves_legacy_task_block_under_unchanged_label
result = await _update_workflow({"workflow_yaml": submitted}, ctx)
assert result["ok"] is True
+ mock_proxy_span.assert_called_once_with(submitted, fake_workflow)
# The new YAML was accepted and assigned to ctx as the current workflow state.
assert ctx.workflow_yaml == submitted
diff --git a/tests/unit/test_navigation_in_while_loop_codegen.py b/tests/unit/test_navigation_in_while_loop_codegen.py
new file mode 100644
index 000000000..1eedcdbad
--- /dev/null
+++ b/tests/unit/test_navigation_in_while_loop_codegen.py
@@ -0,0 +1,26 @@
+"""Navigation / download codegen inside while_loop uses same loop body path as for_loop."""
+
+from skyvern.core.script_generations.generate_script import _build_block_fn
+
+
+def _click() -> dict:
+ return {
+ "action_type": "click",
+ "xpath": "//a",
+ "element_id": "e1",
+ "reasoning": "go",
+ }
+
+
+def test_navigation_while_body_uses_loop_item_selector() -> None:
+ block = {
+ "label": "nav",
+ "block_type": "navigation",
+ "url": "https://example.com",
+ "navigation_goal": "Open link",
+ }
+ fn = _build_block_fn(block, [_click()], is_in_for_loop=True)
+ import libcst as cst
+
+ code = cst.Module(body=[fn]).code
+ assert "context.loop_item_selector()" in code
diff --git a/tests/unit/test_nested_while_loop_script_generation.py b/tests/unit/test_nested_while_loop_script_generation.py
new file mode 100644
index 000000000..bf616dc94
--- /dev/null
+++ b/tests/unit/test_nested_while_loop_script_generation.py
@@ -0,0 +1,128 @@
+"""Nested while_loop handling in transform (_process_forloop_children)."""
+
+from typing import Any
+from unittest.mock import MagicMock
+
+from skyvern.core.script_generations.transform_workflow_run import (
+ _build_children_by_parent,
+ _process_forloop_children,
+)
+from skyvern.schemas.workflows import BlockType
+from skyvern.webeye.actions.actions import Action
+
+
+def test_while_outer_merges_inner_while_recursively() -> None:
+ outer = MagicMock()
+ outer.workflow_run_block_id = "w_outer"
+ outer.label = "outer_while"
+
+ inner_run = MagicMock()
+ inner_run.workflow_run_block_id = "w_inner_block"
+ inner_run.parent_workflow_run_block_id = "w_outer"
+ inner_run.block_type = BlockType.WHILE_LOOP
+ inner_run.label = "inner_while"
+ inner_run.task_id = None
+ inner_run.workflow_run_id = "wr_1"
+
+ grand = MagicMock()
+ grand.workflow_run_block_id = "w_gc"
+ grand.parent_workflow_run_block_id = "w_inner_block"
+ grand.block_type = "extraction"
+ grand.label = "deep_ex"
+ grand.task_id = "t_deep"
+ grand.status = "completed"
+ grand.output = {}
+ grand.workflow_run_id = "wr_1"
+
+ mock_task = MagicMock()
+ mock_task.model_dump.return_value = {"task_id": "t_deep"}
+
+ mock_action = MagicMock(spec=Action)
+ mock_action.model_dump.return_value = {"action_type": "extract"}
+ mock_action.get_xpath.return_value = "//d"
+ mock_action.has_mini_agent = False
+ mock_action.action_type = "extract"
+ mock_action.task_id = "t_deep"
+
+ loop_blocks_def: list[dict[str, Any]] = [
+ {
+ "block_type": "while_loop",
+ "label": "inner_while",
+ "condition": {"criteria_type": "jinja2_template", "expression": "{{ false }}"},
+ "loop_blocks": [
+ {"block_type": "extraction", "label": "deep_ex", "data_extraction_goal": "d"},
+ ],
+ },
+ ]
+ actions_by_task: dict[str, list[dict[str, Any]]] = {}
+ all_blocks = [outer, inner_run, grand]
+
+ result = _process_forloop_children(
+ forloop_run_block=outer,
+ loop_blocks_def=loop_blocks_def,
+ children_by_parent=_build_children_by_parent(all_blocks),
+ tasks_by_id={"t_deep": mock_task},
+ actions_by_task_id={"t_deep": [mock_action]},
+ actions_by_task=actions_by_task,
+ )
+ assert len(result) == 1
+ inner = result[0]
+ assert inner["block_type"] == "while_loop"
+ assert inner["workflow_run_block_id"] == "w_inner_block"
+ kids = inner["loop_blocks"]
+ assert len(kids) == 1
+ assert kids[0]["task_id"] == "t_deep"
+
+
+def test_for_inside_while_nested_merge() -> None:
+ outer_while = MagicMock()
+ outer_while.workflow_run_block_id = "w_o"
+ outer_while.label = "outer"
+
+ inner_for = MagicMock()
+ inner_for.workflow_run_block_id = "f_i"
+ inner_for.parent_workflow_run_block_id = "w_o"
+ inner_for.block_type = BlockType.FOR_LOOP
+ inner_for.label = "inner_for"
+ inner_for.task_id = None
+
+ task_child = MagicMock()
+ task_child.workflow_run_block_id = "c1"
+ task_child.parent_workflow_run_block_id = "f_i"
+ task_child.block_type = "task"
+ task_child.label = "t_block"
+ task_child.task_id = "tid"
+ task_child.status = "completed"
+ task_child.output = {}
+
+ mock_task = MagicMock()
+ mock_task.model_dump.return_value = {"task_id": "tid"}
+
+ mock_action = MagicMock(spec=Action)
+ mock_action.model_dump.return_value = {"action_type": "click"}
+ mock_action.get_xpath.return_value = "//b"
+ mock_action.has_mini_agent = False
+ mock_action.action_type = "click"
+ mock_action.task_id = "tid"
+
+ loop_def: list[dict[str, Any]] = [
+ {
+ "block_type": "for_loop",
+ "label": "inner_for",
+ "loop_variable_reference": "items",
+ "loop_blocks": [{"block_type": "task", "label": "t_block", "url": "https://x.test"}],
+ },
+ ]
+ actions_by_task: dict[str, list[dict[str, Any]]] = {}
+ blocks = [outer_while, inner_for, task_child]
+
+ out = _process_forloop_children(
+ forloop_run_block=outer_while,
+ loop_blocks_def=loop_def,
+ children_by_parent=_build_children_by_parent(blocks),
+ tasks_by_id={"tid": mock_task},
+ actions_by_task_id={"tid": [mock_action]},
+ actions_by_task=actions_by_task,
+ )
+ assert out[0]["workflow_run_block_id"] == "f_i"
+ assert out[0]["loop_blocks"][0]["task_id"] == "tid"
diff --git a/tests/unit/test_while_loop_child_caching_tracking.py b/tests/unit/test_while_loop_child_caching_tracking.py
new file mode 100644
index 000000000..1929aa8cc
--- /dev/null
+++ b/tests/unit/test_while_loop_child_caching_tracking.py
@@ -0,0 +1,74 @@
+"""Track while-loop child blocks for script caching (mirrors for-loop SKY-7751 pattern)."""
+
+from datetime import datetime, timezone
+
+from skyvern.forge.sdk.workflow.models.block import (
+ BlockType,
+ FileDownloadBlock,
+ JinjaBranchCriteria,
+ TaskBlock,
+ WhileLoopBlock,
+)
+from skyvern.forge.sdk.workflow.models.parameter import OutputParameter
+from skyvern.forge.sdk.workflow.service import BLOCK_TYPES_THAT_SHOULD_BE_CACHED
+
+
+def _make_output_param(label: str) -> OutputParameter:
+ now = datetime.now(tz=timezone.utc)
+ return OutputParameter(
+ key=f"{label}_output",
+ parameter_type="output",
+ output_parameter_id=f"op_{label}",
+ workflow_id="wf_test",
+ created_at=now,
+ modified_at=now,
+ )
+
+
+def test_while_loop_is_cacheable() -> None:
+ assert BlockType.WHILE_LOOP in BLOCK_TYPES_THAT_SHOULD_BE_CACHED
+
+
+def test_while_loop_child_labels_collected() -> None:
+ inner = TaskBlock(label="inner_task", output_parameter=_make_output_param("inner_task"), url="https://x.test")
+ wloop = WhileLoopBlock(
+ label="w",
+ output_parameter=_make_output_param("w"),
+ loop_blocks=[inner],
+ condition=JinjaBranchCriteria(expression="{{ true }}"),
+ )
+ script_blocks_by_label: dict[str, object] = {}
+ blocks_to_update: set[str] = set()
+ for loop_child in wloop.loop_blocks:
+ if (
+ loop_child.label
+ and loop_child.label not in script_blocks_by_label
+ and loop_child.block_type in BLOCK_TYPES_THAT_SHOULD_BE_CACHED
+ ):
+ blocks_to_update.add(loop_child.label)
+ assert "inner_task" in blocks_to_update
+
+
+def test_while_loop_file_download_child() -> None:
+ dl = FileDownloadBlock(
+ label="dl",
+ output_parameter=_make_output_param("dl"),
+ url="http://example.com",
+ navigation_goal="get file",
+ )
+ wloop = WhileLoopBlock(
+ label="w",
+ output_parameter=_make_output_param("w"),
+ loop_blocks=[dl],
+ condition=JinjaBranchCriteria(expression="{{ false }}"),
+ )
+ script_blocks_by_label: dict[str, object] = {}
+ blocks_to_update: set[str] = set()
+ for loop_child in wloop.loop_blocks:
+ if (
+ loop_child.label
+ and loop_child.label not in script_blocks_by_label
+ and loop_child.block_type in BLOCK_TYPES_THAT_SHOULD_BE_CACHED
+ ):
+ blocks_to_update.add(loop_child.label)
+ assert "dl" in blocks_to_update
diff --git a/tests/unit/test_while_loop_incremental_persist.py b/tests/unit/test_while_loop_incremental_persist.py
new file mode 100644
index 000000000..d21894c63
--- /dev/null
+++ b/tests/unit/test_while_loop_incremental_persist.py
@@ -0,0 +1,37 @@
+"""WhileLoopBlock incremental DB persistence mirrors for-loop script path expectations."""
+
+from datetime import UTC, datetime
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from skyvern.forge.sdk.workflow.models.block import WhileLoopBlock
+from skyvern.forge.sdk.workflow.models.parameter import OutputParameter
+
+
+def _op(label: str) -> OutputParameter:
+ now = datetime.now(UTC)
+ return OutputParameter(
+ output_parameter_id=f"op_{label}",
+ key=f"{label}_out",
+ workflow_id="wf",
+ created_at=now,
+ modified_at=now,
+ )
+
+
+async def test_persist_partial_while_loop_output_calls_db() -> None:
+ from skyvern.forge.sdk.workflow.models.block import JinjaBranchCriteria, TaskBlock
+
+ inner = TaskBlock(label="in", output_parameter=_op("in"), url="https://z.test")
+ loop = WhileLoopBlock(
+ label="wl",
+ output_parameter=_op("wl"),
+ loop_blocks=[inner],
+ condition=JinjaBranchCriteria(expression="{{ false }}"),
+ )
+ with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
+ mock_app.DATABASE.workflow_runs.create_or_update_workflow_run_output_parameter = AsyncMock()
+ await loop._persist_partial_loop_output("wr1", [[]], loop_idx=0)
+ mock_app.DATABASE.workflow_runs.create_or_update_workflow_run_output_parameter.assert_awaited_once()
diff --git a/tests/unit/test_while_loop_script_generation.py b/tests/unit/test_while_loop_script_generation.py
new file mode 100644
index 000000000..3bfba28f4
--- /dev/null
+++ b/tests/unit/test_while_loop_script_generation.py
@@ -0,0 +1,296 @@
+"""Unit tests for WhileLoop script generation and caching (SKY-8771 / #10624)."""
+
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import libcst as cst
+import pytest
+
+from skyvern.core.script_generations.generate_script import (
+ _build_while_loop_statement,
+ _is_inline_only_loop_cached_code,
+ _is_while_loop_cached_code,
+)
+from skyvern.core.script_generations.transform_workflow_run import transform_workflow_run_to_code_gen_input
+from skyvern.forge.sdk.workflow.service import BLOCK_TYPES_THAT_SHOULD_BE_CACHED
+from skyvern.schemas.workflows import BlockType
+
+
+class TestWhileLoopBranchCriteriaRehydration:
+ def test_branch_criteria_jinja_defaults_and_prompt(self) -> None:
+ from skyvern.forge.sdk.workflow.models.block import JinjaBranchCriteria, PromptBranchCriteria
+ from skyvern.services.script_service import _while_loop_branch_criteria
+
+ assert isinstance(_while_loop_branch_criteria("{{ x }}", None), JinjaBranchCriteria)
+ assert isinstance(_while_loop_branch_criteria("{{ x }}", "jinja2_template"), JinjaBranchCriteria)
+ p = _while_loop_branch_criteria("still has bills on this page", "prompt")
+ assert isinstance(p, PromptBranchCriteria)
+ assert p.expression == "still has bills on this page"
+
+ def test_branch_criteria_rejects_unknown_type(self) -> None:
+ from skyvern.services.script_service import _while_loop_branch_criteria
+
+ with pytest.raises(ValueError, match="unsupported criteria_type"):
+ _while_loop_branch_criteria("x", "wat")
+
+
+class TestWhileLoopConditionCriteriaTypeCodegen:
+ def test_codegen_rejects_unknown_criteria_type(self) -> None:
+ from skyvern.core.script_generations.generate_script import _while_loop_condition_criteria_type
+
+ with pytest.raises(ValueError, match="unsupported condition criteria_type"):
+ _while_loop_condition_criteria_type(
+ {"condition": {"criteria_type": "future_type", "expression": "x"}, "block_type": "while_loop"}
+ )
+
+
+class TestWhileLoopInCacheableBlocks:
+ def test_while_loop_in_block_types_that_should_be_cached(self) -> None:
+ assert BlockType.WHILE_LOOP in BLOCK_TYPES_THAT_SHOULD_BE_CACHED
+
+
+class TestWhileLoopScriptGeneration:
+ def test_build_while_loop_statement_structure(self) -> None:
+ block: dict[str, Any] = {
+ "block_type": "while_loop",
+ "label": "paginate",
+ "condition": {"criteria_type": "jinja2_template", "expression": "{{ current_index == 0 or has_next }}"},
+ "loop_blocks": [
+ {
+ "block_type": "extraction",
+ "label": "extract_page",
+ "data_extraction_goal": "Extract rows",
+ },
+ ],
+ }
+ result = _build_while_loop_statement("paginate", block)
+ assert hasattr(result, "target")
+ assert hasattr(result, "iter")
+ code = cst.Module(body=[result]).code
+ assert "skyvern.while_loop" in code
+ assert "condition" in code
+ assert "criteria_type" in code
+ assert "'jinja2_template'" in code or '"jinja2_template"' in code
+ assert "label" in code
+
+ def test_build_while_loop_statement_prompt_criteria_type(self) -> None:
+ block: dict[str, Any] = {
+ "block_type": "while_loop",
+ "label": "paginate",
+ "condition": {"criteria_type": "prompt", "expression": "there is a next page of bills"},
+ "loop_blocks": [],
+ }
+ result = _build_while_loop_statement("paginate", block)
+ code = cst.Module(body=[result]).code
+ assert "'prompt'" in code or '"prompt"' in code
+
+
+class TestWhileLoopCachedCodeDetection:
+ def test_is_while_loop_cached_code_positive(self) -> None:
+ code = "async for current_value in skyvern.while_loop(condition='{{ x }}', label='w'):\n pass\n"
+ assert _is_while_loop_cached_code(code) is True
+
+ def test_is_inline_only_loop_cached_code_unions_for_and_while(self) -> None:
+ assert _is_inline_only_loop_cached_code("async for x in skyvern.loop(values='', label='a'):") is True
+ assert (
+ _is_inline_only_loop_cached_code(
+ "async for current_value in skyvern.while_loop(condition='{{ 1 }}', label='b'):"
+ )
+ is True
+ )
+ assert _is_inline_only_loop_cached_code("def foo():\n return 1\n") is False
+
+
+class TestWhileLoopTransformation:
+ def test_while_child_blocks_identified_by_parent_id(self) -> None:
+ while_block = MagicMock()
+ while_block.workflow_run_block_id = "wfrb_while_1"
+ while_block.parent_workflow_run_block_id = None
+ while_block.block_type = BlockType.WHILE_LOOP
+ while_block.label = "wloop"
+
+ child = MagicMock()
+ child.parent_workflow_run_block_id = "wfrb_while_1"
+ child.label = "inner_extraction"
+ child.block_type = "extraction"
+ child.task_id = "t1"
+
+ children = [
+ b for b in [while_block, child] if b.parent_workflow_run_block_id == while_block.workflow_run_block_id
+ ]
+ assert len(children) == 1
+ assert children[0].task_id == "t1"
+
+
+async def test_transform_whileloop_block_with_mocked_db() -> None:
+ mock_workflow_run_resp = MagicMock()
+ mock_workflow_run_resp.run_request = MagicMock()
+ mock_workflow_run_resp.run_request.workflow_id = "wpid_w"
+ mock_workflow_run_resp.run_request.model_dump = MagicMock(return_value={"workflow_id": "wpid_w", "parameters": {}})
+
+ mock_while_def = MagicMock()
+ mock_while_def.block_type = BlockType.WHILE_LOOP
+ mock_while_def.label = "wloop"
+ mock_while_def.model_dump = MagicMock(
+ return_value={
+ "block_type": "while_loop",
+ "label": "wloop",
+ "condition": {"criteria_type": "jinja2_template", "expression": "{{ ok }}"},
+ "loop_blocks": [
+ {"block_type": "extraction", "label": "extract_data", "data_extraction_goal": "Get data"},
+ ],
+ }
+ )
+
+ mock_workflow = MagicMock()
+ mock_workflow.model_dump = MagicMock(return_value={"workflow_id": "wf_w", "workflow_definition": {"blocks": []}})
+ mock_workflow.workflow_definition.blocks = [mock_while_def]
+
+ mock_while_run = MagicMock()
+ mock_while_run.workflow_run_block_id = "wfrb_while_parent"
+ mock_while_run.parent_workflow_run_block_id = None
+ mock_while_run.block_type = BlockType.WHILE_LOOP
+ mock_while_run.label = "wloop"
+ mock_while_run.task_id = None
+ mock_while_run.created_at = 1
+
+ mock_child = MagicMock()
+ mock_child.workflow_run_block_id = "wfrb_child"
+ mock_child.parent_workflow_run_block_id = "wfrb_while_parent"
+ mock_child.block_type = "extraction"
+ mock_child.label = "extract_data"
+ mock_child.task_id = "task_w_1"
+ mock_child.status = "completed"
+ mock_child.output = {"extracted": "x"}
+ mock_child.created_at = 2
+
+ mock_task = MagicMock()
+ mock_task.model_dump = MagicMock(return_value={"task_id": "task_w_1"})
+ mock_task.task_id = "task_w_1"
+
+ mock_action = MagicMock()
+ mock_action.action_type = "extract"
+ mock_action.model_dump = MagicMock(return_value={"action_type": "extract", "action_id": "a1"})
+ mock_action.get_xpath = MagicMock(return_value="//div")
+ mock_action.has_mini_agent = False
+
+ with (
+ patch("skyvern.services.workflow_service.get_workflow_run_response", new_callable=AsyncMock) as mock_get,
+ patch("skyvern.core.script_generations.transform_workflow_run.app") as mock_app,
+ ):
+ mock_get.return_value = mock_workflow_run_resp
+ mock_app.WORKFLOW_SERVICE.get_workflow_by_permanent_id = AsyncMock(return_value=mock_workflow)
+ mock_app.DATABASE.observer.get_workflow_run_blocks = AsyncMock(return_value=[mock_while_run, mock_child])
+ mock_app.DATABASE.tasks.get_tasks_by_ids = AsyncMock(return_value=[mock_task])
+ mock_app.DATABASE.tasks.get_tasks_actions = AsyncMock(return_value=[mock_action])
+
+ result = await transform_workflow_run_to_code_gen_input(
+ workflow_run_id="wr_w",
+ organization_id="org_w",
+ )
+
+ assert len(result.workflow_blocks) == 1
+ wb = result.workflow_blocks[0]
+ assert wb["block_type"] == "while_loop"
+ lbs = wb.get("loop_blocks", [])
+ assert len(lbs) == 1
+ assert lbs[0].get("task_id") == "task_w_1"
+ assert "task_w_1" in result.actions_by_task
+
+
+async def test_whileloop_script_compiles() -> None:
+ from skyvern.core.script_generations.generate_script import generate_workflow_script_python_code
+
+ blocks = [
+ {
+ "block_type": "while_loop",
+ "label": "w",
+ "condition": {"criteria_type": "jinja2_template", "expression": "{{ false }}"},
+ "loop_blocks": [
+ {
+ "block_type": "extraction",
+ "label": "ex",
+ "data_extraction_goal": "x",
+ },
+ ],
+ },
+ ]
+ workflow = {
+ "workflow_id": "wf_w",
+ "title": "W",
+ "workflow_definition": {"parameters": []},
+ }
+ with (
+ patch(
+ "skyvern.core.script_generations.generate_script.generate_workflow_parameters_schema",
+ new_callable=AsyncMock,
+ return_value=("", {}),
+ ),
+ patch(
+ "skyvern.core.script_generations.generate_script.create_or_update_script_block",
+ new_callable=AsyncMock,
+ ),
+ ):
+ result = await generate_workflow_script_python_code(
+ file_name="w.py",
+ workflow_run_request={"workflow_id": "wp_w"},
+ workflow=workflow,
+ blocks=blocks,
+ actions_by_task={},
+ script_id="s1",
+ script_revision_id="r1",
+ organization_id="o1",
+ )
+ assert compile(result.source_code, "<w>", "exec")
+ assert "async for current_value in skyvern.while_loop" in result.source_code
+ assert "criteria_type" in result.source_code
+ assert "def run_workflow" in result.source_code
+
+
+async def test_cached_whileloop_unexecuted_branch_not_at_module_level() -> None:
+ from skyvern.core.script_generations.generate_script import generate_workflow_script_python_code
+ from skyvern.services.workflow_script_service import ScriptBlockSource
+
+ blocks = [
+ {"block_type": "task", "label": "t1", "task_id": "tsk", "title": "T"},
+ ]
+ cached_blocks = {
+ "wlab": ScriptBlockSource(
+ label="wlab",
+ code=("async for current_value in skyvern.while_loop(condition='{{ false }}', label='wlab'):\n pass\n"),
+ run_signature="async for current_value in skyvern.while_loop(condition='{{ false }}', label='wlab'):",
+ workflow_run_id="wr_p",
+ workflow_run_block_id="wrb_p",
+ input_fields=None,
+ requires_agent=False,
+ ),
+ }
+ workflow = {"workflow_id": "wf", "title": "X", "workflow_definition": {"parameters": []}}
+ with (
+ patch(
+ "skyvern.core.script_generations.generate_script.generate_workflow_parameters_schema",
+ new_callable=AsyncMock,
+ return_value=("", {}),
+ ),
+ patch(
+ "skyvern.core.script_generations.generate_script.create_or_update_script_block",
+ new_callable=AsyncMock,
+ return_value=True,
+ ),
+ ):
+ result = await generate_workflow_script_python_code(
+ file_name="x.py",
+ workflow_run_request={"workflow_id": "wp"},
+ workflow=workflow,
+ blocks=blocks,
+ actions_by_task={"tsk": []},
+ script_id="s",
+ script_revision_id="r",
+ organization_id="o",
+ cached_blocks=cached_blocks,
+ )
+ compile(result.source_code, "<x>", "exec")
+ assert "async for current_value in skyvern.while_loop" not in result.source_code
diff --git a/tests/unit/test_workflow_copilot_route_helpers.py b/tests/unit/test_workflow_copilot_route_helpers.py
index 08bb6d801..13337cbfb 100644
--- a/tests/unit/test_workflow_copilot_route_helpers.py
+++ b/tests/unit/test_workflow_copilot_route_helpers.py
@@ -13,11 +13,15 @@ from __future__ import annotations
from typing import Any
from unittest.mock import MagicMock
+import pytest
+from pydantic import ValidationError
+
from skyvern.forge.sdk.routes.workflow_copilot import (
_effective_auto_accept,
_normalize_copilot_yaml,
_should_restore_persisted_workflow,
)
+from skyvern.schemas.runs import ProxyLocation
def _agent_result(
@@ -108,3 +112,51 @@ class TestNormalizeCopilotYamlTitleCoercion:
yaml_str = "title: My Workflow\nworkflow_definition:\n blocks: []\n parameters: []\n"
request = _normalize_copilot_yaml(yaml_str)
assert request.title == "My Workflow"
+
+
+class TestNormalizeCopilotYamlProxyLocation:
+ def test_missing_proxy_location_is_preserved(self) -> None:
+ yaml_str = "title: Proxy Workflow\nworkflow_definition:\n blocks: []\n parameters: []\n"
+
+ request = _normalize_copilot_yaml(yaml_str)
+
+ assert request.proxy_location is None
+
+ def test_explicit_null_proxy_location_is_preserved(self) -> None:
+ yaml_str = "title: Proxy Workflow\nproxy_location: null\nworkflow_definition:\n blocks: []\n parameters: []\n"
+
+ request = _normalize_copilot_yaml(yaml_str)
+
+ assert request.proxy_location is None
+
+ @pytest.mark.parametrize(
+ ("raw_value", "expected"),
+ [
+ ("US", ProxyLocation.RESIDENTIAL),
+ ("USA", ProxyLocation.RESIDENTIAL),
+ ("RESIDENTIAL_US", ProxyLocation.RESIDENTIAL),
+ ("UK", ProxyLocation.RESIDENTIAL_GB),
+ ("GB", ProxyLocation.RESIDENTIAL_GB),
+ ("CA", ProxyLocation.RESIDENTIAL_CA),
+ ("US_CA", ProxyLocation.US_CA),
+ ("us-ny", ProxyLocation.US_NY),
+ ],
+ )
+ def test_known_proxy_location_shorthands_are_canonicalized(self, raw_value: str, expected: ProxyLocation) -> None:
+ yaml_str = (
+ f"title: Proxy Workflow\n"
+ f"proxy_location: {raw_value}\n"
+ f"workflow_definition:\n"
+ f" blocks: []\n"
+ f" parameters: []\n"
+ )
+
+ request = _normalize_copilot_yaml(yaml_str)
+
+ assert request.proxy_location == expected
+
+ def test_unknown_proxy_location_still_fails_validation(self) -> None:
+ yaml_str = "title: Proxy Workflow\nproxy_location: MARS\nworkflow_definition:\n blocks: []\n parameters: []\n"
+
+ with pytest.raises(ValidationError):
+ _normalize_copilot_yaml(yaml_str)