Skip to content

Automate browser based workflows with AI

Run each Copilot build test in a browser that matches where the test starts (SKY-16164) (#8586)

Andrew Neilsona93ad7831656
diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.py
index fc9d345a2..d9e9b72c7 100644
--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py
+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py
@@ -2938,15 +2938,6 @@ def code_contains_credential_fill(code: str) -> bool:
return CREDENTIAL_FILL_CODE_PATTERN.search(code) is not None
-def trajectory_has_credential_fill(trajectory: Sequence[Mapping[str, Any]]) -> bool:
- for interaction in trajectory:
- if str(interaction.get("tool_name") or "") != CREDENTIAL_FILL_TOOL_NAME:
- continue
- if str(interaction.get("credential_field") or "").strip() in _CREDENTIAL_FIELDS:
- return True
- return False
-
-
def trajectory_has_browser_fill_interaction(trajectory: Sequence[Mapping[str, Any]]) -> bool:
for interaction in trajectory:
tool_name = str(interaction.get("tool_name") or "")
diff --git a/skyvern/forge/sdk/copilot/frontier_provenance_dump.py b/skyvern/forge/sdk/copilot/frontier_provenance_dump.py
index d61453d28..7402d46db 100644
--- a/skyvern/forge/sdk/copilot/frontier_provenance_dump.py
+++ b/skyvern/forge/sdk/copilot/frontier_provenance_dump.py
@@ -4,7 +4,8 @@ Enabled by ``COPILOT_DUMP_FRONTIER_PROVENANCE=<directory>``; see
``dev_scripts/replay_frontier_provenance.py`` for the replayer that consumes these packets.
Local development only. Packets carry unredacted workflow definitions and extracted block
-outputs, so setting this anywhere real writes customer data to disk.
+outputs, so setting this anywhere real writes customer data to disk. A credential-bearing run
+keeps its browser position, so the block end URLs here can include post-login pages.
"""
from __future__ import annotations
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index 28f89d7c4..4c7816f74 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -462,6 +462,10 @@ class AgentContext:
# Set by the planner when it proved a resume against the browser above; the next run is
# threaded into that browser instead of the chat's. Consumed and cleared by that run.
frontier_resume_session_id: str | None = None
+ # Set by the planner for a mid-workflow start it cannot bind to a browser: its verified prefix
+ # cannot be resumed, the stored order is not the run order, or it refills credentials. The
+ # chat's browser is not a safe target for any of those. Consumed and cleared by that run.
+ frontier_requires_own_browser: bool = False
# Where the planned run starts from, stamped once per plan and consumed by that run. Only a
# non-``unanchored`` start can credit its labels as composition-verified.
frontier_start_provenance: FrontierStartProvenance | None = None
diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.py
index c6632007f..e792b3de1 100644
--- a/skyvern/forge/sdk/copilot/tools/__init__.py
+++ b/skyvern/forge/sdk/copilot/tools/__init__.py
@@ -981,10 +981,12 @@ async def run_blocks_tool(
return _diagnosis_repair_tool_error(copilot_ctx, "run_blocks_and_collect_debug", authority_error)
prior_definition = await _get_prior_workflow_definition(copilot_ctx)
- # No definition change on this path, so the frontier never reaches the edit-in-place branch
- # and a live page read would be spent on nothing.
labels_to_execute, block_outputs_to_seed, frontier_start_label, start_provenance = _plan_frontier(
- copilot_ctx, block_labels, prior_definition, prior_definition
+ copilot_ctx,
+ block_labels,
+ prior_definition,
+ prior_definition,
+ await _frontier_runtime_page_url(copilot_ctx),
)
copilot_ctx.frontier_start_provenance = start_provenance
with copilot_span(
diff --git a/skyvern/forge/sdk/copilot/tools/_shared.py b/skyvern/forge/sdk/copilot/tools/_shared.py
index bfc429821..693c3afac 100644
--- a/skyvern/forge/sdk/copilot/tools/_shared.py
+++ b/skyvern/forge/sdk/copilot/tools/_shared.py
@@ -336,6 +336,12 @@ def _workflow_definition_block_labels(workflow_definition: object | None) -> lis
return labels
+def _executable_workflow_block_labels(workflow_definition: object | None) -> list[str]:
+ """Block labels in traversal order. The finally block runs outside it, so it is never the head."""
+ finally_label = getattr(workflow_definition, "finally_block_label", None)
+ return [label for label in _workflow_definition_block_labels(workflow_definition) if label != finally_label]
+
+
def _current_workflow_block_labels(ctx: object) -> list[str]:
workflow = getattr(ctx, "last_workflow", None)
labels = _workflow_definition_block_labels(getattr(workflow, "workflow_definition", None))
@@ -418,13 +424,33 @@ def _artifact_entry_claims_terminal_criterion(entry: dict[str, Any]) -> bool:
def _unverified_current_workflow_labels(ctx: object) -> list[str]:
- labels = _current_workflow_block_labels(ctx)
+ labels = _current_executable_workflow_block_labels(ctx)
verified = set(getattr(ctx, "verified_prefix_labels", []) or [])
return [label for label in labels if label not in verified]
-def _composition_unverified_current_workflow_labels(ctx: object) -> list[str]:
+def _current_finally_block_label(ctx: object) -> str | None:
+ """The finally block of the workflow in context, from whichever source its labels came from."""
+ definition = getattr(getattr(ctx, "last_workflow", None), "workflow_definition", None)
+ finally_label = getattr(definition, "finally_block_label", None)
+ if isinstance(finally_label, str) and finally_label:
+ return finally_label
+ # Labels fall back to the YAML when no model object is loaded yet, so this has to as well;
+ # reading only the model would leave the fallback treating the finally block as body work.
+ parsed = _parse_workflow_definition(getattr(ctx, "last_workflow_yaml", None))
+ yaml_label = parsed.get("finally_block_label") if parsed else None
+ return yaml_label if isinstance(yaml_label, str) and yaml_label else None
+
+
+def _current_executable_workflow_block_labels(ctx: object) -> list[str]:
+ """Traversal order for the workflow in context; the finally block runs outside it."""
+ finally_label = _current_finally_block_label(ctx)
labels = _current_workflow_block_labels(ctx)
+ return [label for label in labels if label != finally_label] if finally_label else labels
+
+
+def _composition_unverified_current_workflow_labels(ctx: object) -> list[str]:
+ labels = _current_executable_workflow_block_labels(ctx)
verified = set(getattr(ctx, "composition_verified_labels", []) or [])
return [label for label in labels if label not in verified]
@@ -544,6 +570,22 @@ def _raw_yaml_proxy_location(workflow_yaml: str) -> tuple[bool, Any]:
return True, _proxy_location_trace_value(parsed_yaml.get("proxy_location"))
+def _parse_workflow_definition(yaml_str: str | None) -> dict[str, Any] | None:
+ """``workflow_definition`` as a plain dict, or None when the YAML cannot supply one."""
+ # The loader treats anything that is not a string as a stream and reads until it gets an empty
+ # chunk, so a non-string that never runs dry (a mocked context attribute) would never return.
+ if not isinstance(yaml_str, str) or not yaml_str:
+ return None
+ try:
+ parsed = safe_load_no_dates(yaml_str)
+ except yaml.YAMLError:
+ return None
+ if not isinstance(parsed, dict):
+ return None
+ definition = parsed.get("workflow_definition")
+ return definition if isinstance(definition, dict) else None
+
+
def _parse_workflow_blocks(yaml_str: str | None) -> list[Any] | None:
"""Parse ``yaml_str`` and return ``workflow_definition.blocks`` as a list,
or ``None`` if the YAML is missing, unparseable, or not in the expected
diff --git a/skyvern/forge/sdk/copilot/tools/frontier.py b/skyvern/forge/sdk/copilot/tools/frontier.py
index 5b3e11f5f..4b210d71e 100644
--- a/skyvern/forge/sdk/copilot/tools/frontier.py
+++ b/skyvern/forge/sdk/copilot/tools/frontier.py
@@ -51,6 +51,7 @@ from skyvern.schemas.workflows import BlockType
from ._shared import (
_block_type_name,
+ _executable_workflow_block_labels,
_fallback_page_info,
_valid_runtime_anchor_url,
_workflow_definition_block_labels,
@@ -64,6 +65,8 @@ FrontierPlan = tuple[list[str], dict[str, Any], str | None, FrontierStartProvena
_BLOCK_TYPES_STATE_ESTABLISHER = frozenset({"navigation", "login", "goto_url"})
+_BLOCK_TYPES_SIGN_IN = frozenset({"login"})
+
# Bounds the walk into nested blocks; workflows nest a few levels, not hundreds.
_MAX_BLOCK_NESTING_DEPTH = 10
@@ -569,17 +572,23 @@ def _block_and_descendants(block: object, *, depth: int = 0) -> list[object]:
def _frontier_replays_a_credential_fill(
requested_labels: list[str], frontier_label: str, new_definition: object | None
) -> bool:
- """A frontier that refills credentials is replayed into a fresh browser, not the one anchored."""
+ """A frontier that refills credentials cannot borrow the browser the prefix authenticated."""
by_label = _blocks_by_label(new_definition)
try:
idx = requested_labels.index(frontier_label)
except ValueError:
return True
- # A finally block runs alongside the frontier, and it is not in requested_labels to be scanned.
- if getattr(new_definition, "finally_block_label", None):
- return True
- for label in requested_labels[idx:]:
+ scanned = list(requested_labels[idx:])
+ # A finally block runs alongside the frontier without being in requested_labels.
+ finally_label = getattr(new_definition, "finally_block_label", None)
+ if isinstance(finally_label, str) and finally_label and finally_label not in scanned:
+ scanned.append(finally_label)
+ for label in scanned:
for block in _block_and_descendants(by_label.get(label)):
+ # A native login block signs in through its type and parameters and carries no code,
+ # so reading code alone would call the one block built to authenticate safe to replay.
+ if _block_type_name(block) in _BLOCK_TYPES_SIGN_IN:
+ return True
code = getattr(block, "code", None)
if isinstance(code, str) and code_contains_credential_fill(code):
return True
@@ -588,34 +597,28 @@ def _frontier_replays_a_credential_fill(
def _name_resume_session_for_plan(
ctx: AgentContext,
- plan: tuple[list[str], dict[str, Any], str],
+ labels_to_execute: list[str],
frontier_label: str,
new_definition: object | None,
runtime_page_url: str | None,
) -> bool:
- """Name the browser holding the verified state as the one this plan must run in.
-
- Takes the seeded plan rather than the request, because the seeder can veto the frontier and
- hand back a full re-run — which puts the skipped blocks back and must not borrow that browser.
- """
- labels_to_execute, _seed, planned_frontier = plan
- if planned_frontier != frontier_label:
+ """Name the browser holding the verified state as the one this plan must run in."""
+ session_id = ctx.verified_prefix_block_end_session_id
+ if not session_id:
return False
if not _live_session_is_at_frontier_anchor(ctx, frontier_label, new_definition, runtime_page_url):
return False
- # A frontier that refills credentials is replayed into a fresh browser, so naming one here
- # would suppress the mint it still needs.
if _frontier_replays_a_credential_fill(labels_to_execute, frontier_label, new_definition):
return False
- ctx.frontier_resume_session_id = ctx.verified_prefix_block_end_session_id
+ ctx.frontier_resume_session_id = session_id
return True
async def _frontier_runtime_page_url(ctx: AgentContext) -> str | None:
"""Live page of the browser holding the verified state, or None when it cannot be read.
- A login-first replay runs in a browser the chat does not keep, so that browser — not the
- chat's — is the one whose page can speak for where a resumed frontier would start.
+ A head start runs in a browser the chat does not keep, so that browser — not the chat's — is
+ the one whose page can speak for where a resumed frontier would start.
"""
if not ctx.verified_prefix_block_end_urls:
return None
@@ -654,23 +657,6 @@ def _block_can_start_browser_run(block: object) -> bool:
return _valid_runtime_anchor_url(getattr(block, "url", None)) is not None
-def _nearest_upstream_runnable_anchor(
- workflow_labels: list[str], target_label: str, new_definition: object | None
-) -> str | None:
- """The workflow head is a last resort, so a return is not proof the anchor can start a browser
- run; a caller needing that proof reads the plan's start provenance instead."""
- by_label = _blocks_by_label(new_definition)
- try:
- idx = workflow_labels.index(target_label)
- except ValueError:
- return None
- for candidate in reversed(workflow_labels[:idx]):
- block = by_label.get(candidate)
- if block is not None and _block_can_start_browser_run(block):
- return candidate
- return workflow_labels[0] if workflow_labels[:idx] else None
-
-
def _serialized_frontier_block_configs(frontier_labels: list[str], new_definition: object | None) -> list[str]:
by_label = _blocks_by_label(new_definition)
serialized_configs: list[str] = []
@@ -950,11 +936,92 @@ def _plan_start_provenance(
return "replayed" if start_establishes_state else "unanchored"
+def _storage_order_is_traversal_order(new_definition: object | None, before_label: str | None = None) -> bool:
+ """Whether a block's position in the stored list is its position in the run.
+
+ Default edges follow adjacent storage position, so the two agree for an ordinary linear
+ workflow. A branch or an explicit jump makes them disagree, and the planner's positional
+ questions — which block is the head, which precede a frontier — then have no honest answer.
+ With ``before_label`` only that block's prefix has to be ordered, so a workflow that branches
+ after a linear sign-in still knows what preceded it. An edge from later in the workflow back
+ into the prefix is read too: it means a stored predecessor can run after the frontier instead.
+ """
+ blocks = list(getattr(new_definition, "blocks", None) or [])
+ limit = len(blocks)
+ if before_label is not None:
+ labels = [getattr(block, "label", None) for block in blocks]
+ if before_label not in labels:
+ return False
+ limit = labels.index(before_label)
+ for index in range(limit):
+ block = blocks[index]
+ if getattr(block, "ordered_branches", None):
+ return False
+ next_label = getattr(block, "next_block_label", None)
+ successor = blocks[index + 1] if index + 1 < len(blocks) else None
+ if next_label and next_label != getattr(successor, "label", None):
+ return False
+ prefix_labels = {getattr(block, "label", None) for block in blocks[:limit]}
+ for block in blocks[limit:]:
+ targets = {getattr(block, "next_block_label", None)}
+ targets.update(
+ getattr(branch, "next_block_label", None) for branch in getattr(block, "ordered_branches", None) or []
+ )
+ if targets & prefix_labels:
+ return False
+ return True
+
+
def _anchored_plan(
+ ctx: AgentContext,
plan: tuple[list[str], dict[str, Any], str | None],
new_definition: object | None,
+ runtime_page_url: str | None,
+ requested_labels: list[str] | None = None,
) -> FrontierPlan:
+ """Bind a mid-workflow start to the browser holding its verified prefix, or give it a browser of
+ its own; the chat's browser is a build-test target only for an unanchored start.
+
+ The plan never gains a label the caller did not request: an earlier block can submit, send or
+ pay, and replaying one to rebuild state would repeat that effect.
+ """
labels_to_execute, block_outputs_to_seed, frontier_start_label = plan
+ # Traversal order, not storage order: the finally block runs outside it and is never the head.
+ workflow_labels = _executable_workflow_block_labels(new_definition)
+ if (
+ labels_to_execute
+ and frontier_start_label == labels_to_execute[0]
+ and frontier_start_label in workflow_labels[1:]
+ ):
+ # A definition whose stored order is not its run order cannot say which blocks precede
+ # this one, so nothing here may claim a prefix ran or that a browser holds its state.
+ positional = _storage_order_is_traversal_order(new_definition, frontier_start_label)
+ if positional and _has_verified_prefix_before_frontier(ctx, new_definition, frontier_start_label):
+ if _name_resume_session_for_plan(
+ ctx, labels_to_execute, frontier_start_label, new_definition, runtime_page_url
+ ):
+ return labels_to_execute, block_outputs_to_seed, frontier_start_label, "resumed"
+ needs_own_browser = True
+ else:
+ needs_own_browser = not positional or _frontier_replays_a_credential_fill(
+ labels_to_execute, frontier_start_label, new_definition
+ )
+ if needs_own_browser:
+ # No browser can be named for this start, and the chat's holds the page scouting left
+ # open. Run what was asked where nothing is signed in — all of what was asked, because
+ # a slice narrowed to where a previous attempt failed relies on state the earlier
+ # blocks of that same request established, and a blank browser holds none of it. The
+ # plan is restored to the request, so it still never gains a label the caller left out.
+ if requested_labels:
+ labels_to_execute = list(requested_labels)
+ block_outputs_to_seed = {}
+ frontier_start_label = requested_labels[0]
+ ctx.frontier_requires_own_browser = True
+ LOG.info(
+ "copilot_frontier_start_requires_own_browser",
+ frontier_start_label=frontier_start_label,
+ labels_to_execute=labels_to_execute,
+ )
return (
labels_to_execute,
block_outputs_to_seed,
@@ -1009,6 +1076,10 @@ def _plan_frontier_uncaptured(
and we seed verified outputs referenced by the suffix plus prior
browser-state outputs needed to start a downstream frontier.
"""
+ # Only the plan being dispatched may name a resume browser; one left by an earlier plan that
+ # never reached the seam would carry a head start into a browser it was never proven against.
+ ctx.frontier_resume_session_id = None
+ ctx.frontier_requires_own_browser = False
if not requested_labels:
return requested_labels, {}, None, "unanchored"
if new_definition is None:
@@ -1024,20 +1095,26 @@ def _plan_frontier_uncaptured(
if old_definition is None:
frontier = failed_frontier_label or requested_labels[0]
return _anchored_plan(
+ ctx,
_seed_for_frontier(requested_labels, frontier, verified_outputs, new_definition),
new_definition,
+ runtime_page_url,
+ requested_labels,
)
try:
invalidated = _find_invalidated_labels(old_definition, new_definition, requested_labels)
except Exception:
LOG.debug("Frontier diff failed, falling back to full run", exc_info=True)
- return _anchored_plan((requested_labels, {}, requested_labels[0]), new_definition)
+ return _anchored_plan(
+ ctx, (requested_labels, {}, requested_labels[0]), new_definition, runtime_page_url, requested_labels
+ )
earliest = _earliest_invalidated(requested_labels, invalidated)
if earliest is None:
if failed_frontier_label is not None:
return _anchored_plan(
+ ctx,
_seed_for_frontier(
requested_labels,
failed_frontier_label,
@@ -1045,6 +1122,8 @@ def _plan_frontier_uncaptured(
new_definition,
),
new_definition,
+ runtime_page_url,
+ requested_labels,
)
# No invalidation at all — unchanged request. Continue from the
# first unverified requested label so a model may keep passing the
@@ -1053,30 +1132,19 @@ def _plan_frontier_uncaptured(
next_frontier = _first_unverified_requested_label(requested_labels, verified_prefix_set)
if next_frontier is not None:
return _anchored_plan(
+ ctx,
_seed_for_frontier(requested_labels, next_frontier, verified_outputs, new_definition),
new_definition,
- )
-
- # If the model accidentally asks to rerun an already-verified prefix,
- # keep the browser moving forward instead of spending another tool call
- # on work the current session has already covered.
- workflow_labels = _workflow_definition_block_labels(new_definition)
- next_workflow_frontier = _first_unverified_requested_label(workflow_labels, verified_prefix_set)
- if next_workflow_frontier is not None:
- frontier_idx = workflow_labels.index(next_workflow_frontier)
- return _anchored_plan(
- _seed_for_frontier(
- workflow_labels[: frontier_idx + 1],
- next_workflow_frontier,
- verified_outputs,
- new_definition,
- ),
- new_definition,
+ runtime_page_url,
+ requested_labels,
)
return _anchored_plan(
+ ctx,
_seed_for_frontier(requested_labels, requested_labels[0], verified_outputs, new_definition),
new_definition,
+ runtime_page_url,
+ requested_labels,
)
earliest_idx = requested_labels.index(earliest)
@@ -1089,6 +1157,7 @@ def _plan_frontier_uncaptured(
and (failed_frontier_idx < earliest_idx or failed_frontier_label != _recorded_failed_attempted_label(ctx))
):
return _anchored_plan(
+ ctx,
_seed_for_frontier(
requested_labels,
failed_frontier_label,
@@ -1096,6 +1165,8 @@ def _plan_frontier_uncaptured(
new_definition,
),
new_definition,
+ runtime_page_url,
+ requested_labels,
)
# Ensure the prefix before the earliest invalidated label is all in the
@@ -1104,7 +1175,9 @@ def _plan_frontier_uncaptured(
prefix_in_requested = [label for label in requested_labels if label != earliest]
prefix_in_requested = prefix_in_requested[: requested_labels.index(earliest)]
if not all(label in verified_prefix_set for label in prefix_in_requested):
- return _anchored_plan((requested_labels, {}, requested_labels[0]), new_definition)
+ return _anchored_plan(
+ ctx, (requested_labels, {}, requested_labels[0]), new_definition, runtime_page_url, requested_labels
+ )
old_by_label = _blocks_by_label(old_definition)
is_append_only = earliest not in old_by_label
@@ -1112,47 +1185,42 @@ def _plan_frontier_uncaptured(
# Case A — append-after-success. The earliest invalidated label is a
# new block that didn't exist in the prior definition, so the verified
# prefix represents the browser state just before it. Start there.
- workflow_labels = _workflow_definition_block_labels(new_definition)
- if earliest in workflow_labels:
- workflow_prefix = workflow_labels[: workflow_labels.index(earliest)]
- if not all(label in verified_prefix_set for label in workflow_prefix):
- anchor = _nearest_upstream_runnable_anchor(workflow_labels, earliest, new_definition)
- if anchor is not None:
- return _anchored_plan(
- _seed_for_frontier(
- workflow_labels[workflow_labels.index(anchor) : workflow_labels.index(earliest) + 1],
- anchor,
- verified_outputs,
- new_definition,
- ),
- new_definition,
- )
+ # An unverified prefix is reported, not replayed: the blocks before an appended one can
+ # submit, send or pay, and the caller left them out. The run tells the model its browser
+ # started blank, and the model can ask for the prefix by name.
+ #
# The prefix ran somewhere; an appended block has to run there too, or it acts on a page
# that browser never reached. Naming it is safe only on the same evidence a resume needs.
- seeded = _seed_for_frontier(requested_labels, earliest, verified_outputs, new_definition)
- if _name_resume_session_for_plan(ctx, seeded, earliest, new_definition, runtime_page_url):
- return (*seeded, "resumed")
- return _anchored_plan(seeded, new_definition)
+ return _anchored_plan(
+ ctx,
+ _seed_for_frontier(requested_labels, earliest, verified_outputs, new_definition),
+ new_definition,
+ runtime_page_url,
+ requested_labels,
+ )
# Edit-in-place. The edited block can only be rerun alone when the live session is provably
# still on the page its predecessor ended on; otherwise walk back to the nearest upstream
# state establisher, or to the full requested list when there is no safe anchor.
if _live_session_is_at_frontier_anchor(ctx, earliest, new_definition, runtime_page_url):
- seeded = _seed_for_frontier(requested_labels, earliest, verified_outputs, new_definition)
- if _name_resume_session_for_plan(ctx, seeded, earliest, new_definition, runtime_page_url):
- LOG.info(
- "copilot_frontier_resumed_at_edited_block",
- frontier_start_label=earliest,
- requested_labels=requested_labels,
- resume_session_id=ctx.frontier_resume_session_id,
- )
- return (*seeded, "resumed")
+ return _anchored_plan(
+ ctx,
+ _seed_for_frontier(requested_labels, earliest, verified_outputs, new_definition),
+ new_definition,
+ runtime_page_url,
+ requested_labels,
+ )
anchor = _nearest_upstream_state_establisher(requested_labels, earliest, new_definition)
if anchor is None:
- return _anchored_plan((requested_labels, {}, requested_labels[0]), new_definition)
+ return _anchored_plan(
+ ctx, (requested_labels, {}, requested_labels[0]), new_definition, runtime_page_url, requested_labels
+ )
return _anchored_plan(
+ ctx,
_seed_for_frontier(requested_labels, anchor, verified_outputs, new_definition),
new_definition,
+ runtime_page_url,
+ requested_labels,
)
@@ -1350,11 +1418,12 @@ def _workflow_model_block_by_label(workflow_definition: object | None, label: st
def _has_verified_prefix_before_frontier(
- ctx: CopilotContext, workflow_definition: object | None, frontier_label: str | None
+ ctx: AgentContext, workflow_definition: object | None, frontier_label: str | None
) -> bool:
if not frontier_label:
return False
- workflow_labels = _workflow_definition_block_labels(workflow_definition)
+ # The finally block runs outside traversal, so it is never part of a frontier's prefix.
+ workflow_labels = _executable_workflow_block_labels(workflow_definition)
if frontier_label not in workflow_labels:
return False
prefix_labels = workflow_labels[: workflow_labels.index(frontier_label)]
@@ -1369,7 +1438,7 @@ def _has_verified_prefix_before_frontier(
def _has_recorded_failed_prefix_before_frontier(
- ctx: CopilotContext, workflow_definition: object | None, frontier_label: str | None
+ ctx: AgentContext, workflow_definition: object | None, frontier_label: str | None
) -> bool:
if not frontier_label:
return False
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index a2a470431..2e2bb873b 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -85,10 +85,6 @@ from skyvern.forge.sdk.copilot.code_block_security import (
CodeBlockSecurityInput,
runtime_code_security_errors,
)
-from skyvern.forge.sdk.copilot.code_block_synthesis import (
- code_contains_credential_fill,
- trajectory_has_credential_fill,
-)
from skyvern.forge.sdk.copilot.completion_output_grounding import page_evidence_prose_text
from skyvern.forge.sdk.copilot.completion_verification import (
CompletionVerificationResult,
@@ -169,6 +165,8 @@ from skyvern.forge.sdk.copilot.runtime import (
register_sensitive_origin_run_lease,
release_sensitive_origin_run_lease,
resolve_persistent_browser_state,
+ sensitive_origin_page_is_tainted,
+ sensitive_origin_runs_for_session,
verify_build_test_browser_session_by_attaching,
)
from skyvern.forge.sdk.copilot.runtime_authoring_repair import (
@@ -191,6 +189,7 @@ from skyvern.forge.sdk.copilot.secret_scrub import (
register_matching_origin_run_redaction_values,
register_secret_scrub_values_from_structure,
scrub_secrets_from_structure,
+ scrub_secrets_from_text,
)
from skyvern.forge.sdk.copilot.tracing_setup import copilot_span
from skyvern.forge.sdk.copilot.turn_halt import (
@@ -233,7 +232,10 @@ from ._shared import (
RUN_BLOCKS_SAFETY_CEILING_SECONDS,
_completed_run_block_labels,
_composition_unverified_current_workflow_labels,
+ _current_executable_workflow_block_labels,
+ _current_finally_block_label,
_current_workflow_block_labels,
+ _executable_workflow_block_labels,
_failed_run_block_labels,
_fallback_page_info,
_unverified_current_workflow_labels,
@@ -1324,30 +1326,9 @@ async def _workflow_from_prior_draft(ctx: CopilotContext, labels: list[str]) ->
return workflow if _workflow_covers_labels(workflow, labels) else None
-def _should_use_fresh_session_for_login_first_replay(
- ctx: AgentContext,
- labels_to_execute: list[str],
- workflow: Workflow | None,
-) -> bool:
- """Fresh session when this run replays a login fill into the scout's authenticated session.
-
- Keyed on two planes the agent cannot edit between runs — the scout trajectory authenticated
- via a credential fill and any executed block in this run fills one; frontier re-runs seeded
- past login carry no credential fill and keep reusing the scout session.
- """
- if not trajectory_has_credential_fill(ctx.scout_trajectory):
- return False
- return _labels_replay_login_fill(labels_to_execute, workflow)
-
-
-def _labels_replay_login_fill(labels_to_execute: list[str], workflow: Workflow | None) -> bool:
- if not labels_to_execute or workflow is None:
- return False
- code_inputs = _selected_code_security_inputs(
- _workflow_definition_blocks_for_code_security(workflow.workflow_definition),
- selected_labels=set(labels_to_execute),
- )
- return any(code_contains_credential_fill(code_input.code) for code_input in code_inputs)
+def _run_starts_at_workflow_head(frontier_start_label: str | None, workflow_labels: Sequence[str]) -> bool:
+ """A plan that starts at the first block is the workflow as production runs it: from a blank browser."""
+ return bool(workflow_labels) and frontier_start_label == workflow_labels[0]
def _runtime_code_security_failure_for_selected_labels(
@@ -1908,6 +1889,13 @@ def _attach_run_session_facts(
# A carried resume browser is also not the chat's, so detachment is the honest fact for
# "can I look at this run's page from here", not whether the session was minted.
data["run_detached_from_chat"] = run_detached_from_chat
+ if used_fresh_run_session:
+ # Say that the page was blank, so code that needed a signed-in state reads as started
+ # somewhere else rather than as broken, and the next request can bring the blocks it needs.
+ data.setdefault(
+ "browser_start",
+ {"kind": "separate_blank_context", "restored_saved_profile": False, "inherited_browser_state": False},
+ )
if not isinstance(page_evidence, Mapping):
return
data["challenge_stalled_fresh_session"] = (
@@ -2242,8 +2230,12 @@ async def _capture_and_store_post_run_page(
ctx, run_session_id=run_session_id, current_url=current_url
)
if evidence is not None and repair_page_evidence_is_admissible(evidence):
- if sensitive_origin_run:
- evidence = scrub_secrets_from_structure(ctx, evidence)
+ # Scrubbing is keyed to the values themselves, not to who ran: a run that fills no
+ # credential can still read a page an earlier run filled one into. It is a no-op when
+ # nothing is registered, so it is unconditional. A frame's pixels cannot be scrubbed, so it
+ # goes whenever the browser carries a sign-in — this run's or one it resumed.
+ evidence = scrub_secrets_from_structure(ctx, evidence)
+ if sensitive_origin_run or _run_browser_carries_a_sign_in(ctx, run_session_id):
captured_frame = None
_, preserved_stored_evidence = store_post_run_page_evidence(
ctx,
@@ -2464,6 +2456,11 @@ async def _capture_dispatched_terminal_page_evidence(
)
if evidence is None or not _dispatched_terminal_page_evidence_is_usable(evidence):
return
+ # Same rule as the inline capture: values are scrubbed whoever ran, and a frame whose pixels
+ # cannot be scrubbed goes whenever the browser carries a sign-in, including one this run resumed.
+ evidence = scrub_secrets_from_structure(ctx, evidence)
+ if _run_browser_carries_a_sign_in(ctx, run_session_id):
+ captured_frame = None
_, preserved_stored_evidence = store_post_run_page_evidence(
ctx,
evidence,
@@ -2728,6 +2725,16 @@ def terminal_ready_for_latch(
)
+def _run_browser_carries_a_sign_in(ctx: AgentContext, run_session_id: str | None) -> bool:
+ """Whether the browser a run executed in was signed in by any run, this one or an earlier one."""
+ # Only the run's own browser counts. The chat's browser is usually signed in after scouting, so
+ # asking about it would strip screenshots and locators from every clean run in a separate one.
+ # Taint is recorded and cleared for a session and its runs together, so this loses no coverage.
+ if run_session_id is None:
+ return sensitive_origin_page_is_tainted(ctx)
+ return bool(sensitive_origin_runs_for_session(ctx, run_session_id))
+
+
def _credit_composition_verified_labels(
ctx: AgentContext,
labels_to_execute: list[str],
@@ -2737,9 +2744,14 @@ def _credit_composition_verified_labels(
and executed exactly the workflow labels following the credit already earned."""
if start_provenance == "unanchored":
return
- workflow_labels = _current_workflow_block_labels(ctx)
+ workflow_labels = _current_executable_workflow_block_labels(ctx)
if not workflow_labels:
return
+ # A full run carries the finally block in its label list while the workflow's own order leaves
+ # it out, so comparing the two unfiltered would reject the very run that proves the body.
+ finally_label = _current_finally_block_label(ctx)
+ if finally_label:
+ labels_to_execute = [label for label in labels_to_execute if label != finally_label]
credited = list(ctx.composition_verified_labels or [])
# Credit is an ordered contiguous prefix, so a workflow that no longer opens with it has to
# re-earn the whole chain rather than keep set membership that says nothing about order.
@@ -2775,7 +2787,7 @@ async def acquire_build_test_browser_session(ctx: CopilotContext, *, fresh: bool
def _with_build_test_acquisition_context(
- result: dict[str, Any], *, requested_block_labels: Sequence[str], fresh: bool
+ result: dict[str, Any], *, requested_block_labels: Sequence[str]
) -> dict[str, Any]:
data = result.get("data")
if not isinstance(data, dict):
@@ -2783,7 +2795,8 @@ def _with_build_test_acquisition_context(
result["data"] = data
data["requested_block_labels"] = list(requested_block_labels)
data["executed_block_labels"] = []
- data["used_fresh_run_session"] = fresh
+ # Nothing was minted when acquisition fails, whichever route was attempted.
+ data["used_fresh_run_session"] = False
return result
@@ -2935,7 +2948,9 @@ async def _attach_post_run_browser_enrichment(
origin_redaction_registry=origin_registry,
)
- if not sensitive_origin_run:
+ # Ask about the browser this run executed in, not the one the chat holds: a continuation
+ # resuming a detached sign-in browser leaves the chat's session untainted and this one not.
+ if not sensitive_origin_run and not _run_browser_carries_a_sign_in(ctx, run_session_id):
locator_observations = await _observe_authored_locators(
ctx,
run_session_id=run_session_id,
@@ -2966,7 +2981,7 @@ async def _attach_post_run_browser_enrichment(
)
result_data["current_url"] = current_url
- result_data["page_title"] = page_title
+ result_data["page_title"] = scrub_secrets_from_text(ctx, page_title)
if locator_observations is not None:
result_data["authored_locator_observations"] = locator_observations
if not dispatch_to_worker and current_url:
@@ -3045,11 +3060,13 @@ async def _run_blocks_and_collect_debug(
# Read the planner's session choice before any exit path, so a run that bails cannot leave it
# set for a later run whose frontier was never proven against that browser.
resume_session_id = None if explicit_blank else ctx.frontier_resume_session_id
+ planner_requires_own_browser = not explicit_blank and ctx.frontier_requires_own_browser
start_provenance: FrontierStartProvenance = (
"initial" if explicit_blank else ctx.frontier_start_provenance or "unanchored"
)
if not explicit_blank:
ctx.frontier_resume_session_id = None
+ ctx.frontier_requires_own_browser = False
ctx.frontier_start_provenance = None
block_labels = params["block_labels"]
@@ -3227,16 +3244,17 @@ async def _run_blocks_and_collect_debug(
)
runtime_workflow = _workflow_with_runtime_block_goal_context(workflow, ctx)
- if explicit_blank:
- # Keep the authored profile configured, but never save this diagnostic browser over it.
- runtime_workflow = runtime_workflow.model_copy(update={"persist_browser_session": False})
- runtime_workflow, runtime_frontier_anchor_url = _workflow_with_runtime_frontier_anchor(
- runtime_workflow,
- ctx,
- labels_to_execute=labels_to_execute,
- frontier_start_label=frontier_start_label,
- block_outputs_to_seed=block_outputs_to_seed,
- )
+ # The page the verified prefix ended on exists only in the browser the planner named for this
+ # run; a run without one starts from wherever its own browser is, not from that page.
+ runtime_frontier_anchor_url: str | None = None
+ if resume_session_id is not None:
+ runtime_workflow, runtime_frontier_anchor_url = _workflow_with_runtime_frontier_anchor(
+ runtime_workflow,
+ ctx,
+ labels_to_execute=labels_to_execute,
+ frontier_start_label=frontier_start_label,
+ block_outputs_to_seed=block_outputs_to_seed,
+ )
runtime_frontier_starter_url_seeded = False
user_params: dict[str, Any] = params.get("parameters") or {}
@@ -3279,9 +3297,23 @@ async def _run_blocks_and_collect_debug(
# A resume proven against another browser has to run in that browser; minting or falling back
# to the chat's would drop the very state the resume was authorised against.
+ starts_at_workflow_head = _run_starts_at_workflow_head(
+ frontier_start_label, _executable_workflow_block_labels(workflow.workflow_definition)
+ )
use_fresh_session = resume_session_id is None and (
- force_fresh_session or _should_use_fresh_session_for_login_first_replay(ctx, labels_that_may_execute, workflow)
+ force_fresh_session or planner_requires_own_browser or starts_at_workflow_head
)
+ if use_fresh_session and starts_at_workflow_head:
+ # The planner reads a head block that establishes no state as unanchored because it would
+ # meet whatever page authoring left open. A browser minted for this run is that proof.
+ start_provenance = "initial"
+ resumes_a_build_test_browser = resume_session_id is not None and resume_session_id != ctx.browser_session_id
+ if explicit_blank or use_fresh_session or resumes_a_build_test_browser:
+ # Keep the authored profile configured, but never save a build test's browser over it: the
+ # workflow's stored state is the thing that would be replaced, by a browser that exists to
+ # be thrown away. Every route out of the chat's browser is one — minted here, resumed from
+ # a build test that minted it earlier, or the explicitly blank diagnostic run.
+ runtime_workflow = runtime_workflow.model_copy(update={"persist_browser_session": False})
# Reported as run evidence, so it stays literal: a browser minted for this run. A carried
# browser is not one, and reporting it as such would misattribute a challenge that stalled.
used_fresh_run_session = False
@@ -3293,18 +3325,14 @@ async def _run_blocks_and_collect_debug(
# Without a session, the workflow service launches the browser in-process,
# which only works in worker pods (cloakbrowser isn't in the API image).
if use_fresh_session:
- # The scout authenticated its debug session, so replaying the login-first
- # synthesized block into it meets a rehydrated authenticated view and the
- # login fill() waits out its full element timeout. Mint a fresh session for
- # this run only, then restore the scout's debug session as the context
- # session so the rest of the turn (scouting, narration, SKY-9328 reuse)
- # keeps it; the fresh id is threaded into the run calls explicitly.
+ # The chat's browser holds whatever page scouting left open, so a run from the head is
+ # given its own; the chat keeps its session and the minted id is threaded in explicitly.
debug_session_id = ctx.browser_session_id
acquisition_ctx = replace(ctx)
acquisition_ctx.browser_session_id = None
session_err = await acquire_build_test_browser_session(acquisition_ctx, fresh=True)
if session_err is not None:
- return _with_build_test_acquisition_context(session_err, requested_block_labels=block_labels, fresh=True)
+ return _with_build_test_acquisition_context(session_err, requested_block_labels=block_labels)
run_session_id = acquisition_ctx.browser_session_id
if explicit_blank and (
not isinstance(run_session_id, str) or not run_session_id or run_session_id == debug_session_id
@@ -3313,7 +3341,7 @@ async def _run_blocks_and_collect_debug(
used_fresh_run_session = True
run_detached_from_chat = True
LOG.info(
- "copilot_login_replay_fresh_session_minted",
+ "copilot_build_test_fresh_session_minted",
labels_to_execute=labels_to_execute,
frontier_start_label=frontier_start_label,
run_session_id=run_session_id,
@@ -3337,7 +3365,7 @@ async def _run_blocks_and_collect_debug(
# unverified session cannot be discovered later and must fail now instead.
session_err = await acquire_build_test_browser_session(ctx, fresh=False)
if session_err is not None:
- return _with_build_test_acquisition_context(session_err, requested_block_labels=block_labels, fresh=False)
+ return _with_build_test_acquisition_context(session_err, requested_block_labels=block_labels)
run_session_id = ctx.browser_session_id
seeded_runtime_workflow = await _workflow_with_runtime_frontier_starter_url_seed(
@@ -3993,8 +4021,6 @@ async def _run_blocks_and_collect_debug(
solver_attempt = _capture_solver_facts_and_strip_traces(results)
- block_end_urls = {} if sensitive_origin_run else _block_end_urls_by_label(run_block_rows)
-
result_data: dict[str, Any] = {
"workflow_run_id": workflow_run.workflow_run_id,
"workflow_id": snapshot.workflow.workflow_id,
@@ -4010,7 +4036,9 @@ async def _run_blocks_and_collect_debug(
"failing_code_line": failing_code_line,
"action_observations": action_observations,
}
- if runtime_frontier_anchor_url is not None:
+ # Reported for a plain run, withheld after a credential-bearing one for the same reason
+ # observed_block_end_urls is: a post-login address can carry a token or an account path.
+ if runtime_frontier_anchor_url is not None and not sensitive_origin_run:
result_data["runtime_frontier_anchor_url"] = runtime_frontier_anchor_url
if runtime_frontier_starter_url_seeded:
result_data["runtime_frontier_starter_url_seeded"] = True
@@ -4064,7 +4092,10 @@ async def _run_blocks_and_collect_debug(
and all(result_row.get("status") == "completed" for result_row in results)
)
if run_fully_completed and execution.source_is_current(ctx):
- existing_prefix = list(ctx.verified_prefix_labels or [])
+ # Credit belongs to a browser, not to the workflow. A run given its own browser proves
+ # only what it ran there; blocks proven in the browser this one replaced never touched
+ # it, and keeping them would let a later continuation resume here expecting their state.
+ existing_prefix = [] if used_fresh_run_session else list(ctx.verified_prefix_labels or [])
existing_set = set(existing_prefix)
for label in labels_to_execute:
if label not in existing_set:
@@ -4118,17 +4149,21 @@ async def _run_blocks_and_collect_debug(
if run_fully_completed and execution.source_is_current(ctx):
for label, output in block_outputs_by_label.items():
ctx.verified_block_outputs[label] = output
+ # Rebuilt from this run's rows alone: the position was forgotten at dispatch, and the
+ # browser these pages describe is the one this run used.
+ ctx.verified_prefix_block_end_urls = _block_end_urls_by_label(run_block_rows)
+ ctx.verified_prefix_block_end_session_id = run_session_id
+ # A finally block runs after the body and can move the browser without changing its URL
+ # (a client-side sign-out, say), so a run that executed one cannot say where the browser
+ # ended: leave the position unproven and let the next plan restart from the head.
+ finally_label = snapshot.workflow.workflow_definition.finally_block_label
+ finally_ran = bool(finally_label) and any(row.label == finally_label for row in run_block_rows)
+ ctx.verified_prefix_terminal_label = None if finally_ran or not run_block_rows else run_block_rows[-1].label
+ # The planner compares that position in place and never shows it; only the continuation
+ # URL is seeded into a later run's workflow, so that alone is withheld after a credential run.
if sensitive_origin_run:
- # Preserve verified labels and outputs, but never carry browser-position URLs from
- # a credential-bearing run into a later frontier or model-visible result.
- _forget_browser_position(ctx)
ctx.verified_prefix_current_url = None
else:
- # Rebuilt from this run's rows alone: the position was forgotten at dispatch, and the
- # browser these pages describe is the one this run used.
- ctx.verified_prefix_block_end_urls = dict(block_end_urls)
- ctx.verified_prefix_block_end_session_id = run_session_id
- ctx.verified_prefix_terminal_label = run_block_rows[-1].label if run_block_rows else None
verified_current_url = _valid_runtime_anchor_url(current_url)
if verified_current_url is not None:
ctx.verified_prefix_current_url = verified_current_url
@@ -4286,7 +4321,7 @@ async def _get_run_results(
workflow_permanent_id=ctx.workflow_permanent_id,
)
locator_observations: list[AuthoredLocatorObservationRow] | None = None
- if not sensitive_origin_run:
+ if not sensitive_origin_run and not _run_browser_carries_a_sign_in(ctx, run.browser_session_id):
failed_block_code = _failed_block_code(run_workflow, newest_failed) if run_workflow is not None else None
locator_observations = await _observe_authored_locators(
ctx,
@@ -4313,7 +4348,7 @@ async def _get_run_results(
if not dispatch_to_worker:
result_data["current_url_live_observed"] = True
if page_title:
- result_data["page_title"] = page_title
+ result_data["page_title"] = scrub_secrets_from_text(ctx, page_title)
if dispatch_to_worker and dispatched_end_url is None:
result_data["current_url_evidence"] = NO_PERSISTED_END_URL
if getattr(run, "failure_reason", None):
@@ -4978,6 +5013,7 @@ def _record_run_blocks_result(
{
"trust": trust_snapshot(copilot_ctx),
"current_workflow_labels": current_workflow_labels,
+ "finally_block_label": _current_finally_block_label(copilot_ctx),
"unverified": unverified,
"composition_unverified": composition_unverified,
"planned_block_labels": planned_labels,
diff --git a/tests/unit/test_copilot_build_test_outcome.py b/tests/unit/test_copilot_build_test_outcome.py
index 29fe554e8..c4c58a030 100644
--- a/tests/unit/test_copilot_build_test_outcome.py
+++ b/tests/unit/test_copilot_build_test_outcome.py
@@ -6889,9 +6889,10 @@ def test_a_selector_argument_built_at_runtime_cannot_prove_removal() -> None:
async def test_a_foreign_occupier_stops_the_dispatch_before_any_workflow_run_is_created(
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ # A mid-workflow block is the route that runs in the chat's browser; a head start mints its own.
harness = await install_run_blocks_harness(
monkeypatch,
- workflow_yaml=HANDBACK_WORKFLOW_YAML,
+ workflow_yaml=SEARCH_THEN_SELECT_WORKFLOW_YAML,
polled_status="running",
dispatch_to_worker=True,
)
@@ -6930,7 +6931,7 @@ async def test_a_foreign_occupier_stops_the_dispatch_before_any_workflow_run_is_
ctx.staged_workflow = harness["workflow"]
ctx.workflow_copilot_chat_id = "wcc_mine"
- result = await _run_blocks_and_collect_debug({"block_labels": ["extract_heading"], "parameters": {}}, ctx)
+ result = await _run_blocks_and_collect_debug({"block_labels": ["select_first_result"], "parameters": {}}, ctx)
workflow_service_module.prepare_workflow.assert_not_awaited()
harness["worker_execute"].assert_not_awaited()
diff --git a/tests/unit/test_copilot_diagnosis_repair_contract.py b/tests/unit/test_copilot_diagnosis_repair_contract.py
index 4c9b8c26f..8ef8255c8 100644
--- a/tests/unit/test_copilot_diagnosis_repair_contract.py
+++ b/tests/unit/test_copilot_diagnosis_repair_contract.py
@@ -58,6 +58,7 @@ from skyvern.forge.sdk.copilot.runtime import (
OriginRunRedactionRegistry,
bound_call_browser_session,
effective_browser_session_id,
+ record_sensitive_origin_run_taint,
)
from skyvern.forge.sdk.copilot.runtime_authoring_repair import (
OBSTRUCTION_SUMMARY_MAX_CHARS,
@@ -5323,3 +5324,111 @@ def test_a_run_that_fails_many_blocks_cannot_grow_the_contract_row_list() -> Non
)
assert len(contract.diagnosis_input.failed_block_labels) <= _MAX_ITEMS
assert contract.diagnosis_input.failed_block_labels
+
+
[email protected]("browser_signed_in_by_an_earlier_run", [False, True])
+async def test_a_post_run_frame_is_withheld_when_the_run_browser_carries_a_sign_in(
+ monkeypatch: pytest.MonkeyPatch, browser_signed_in_by_an_earlier_run: bool
+) -> None:
+ # This run fills no credential, so its own blocks say nothing is sensitive. A frame's pixels
+ # cannot be scrubbed, so what decides is whether the browser it read was signed in by any run.
+ # The clean case is the control: without it a withheld frame could not be told from a stub
+ # that never reached the queue.
+ ctx = _ctx()
+ if browser_signed_in_by_an_earlier_run:
+ record_sensitive_origin_run_taint(ctx, workflow_run_id="wr_signin", session_id="run_session")
+
+ frame = SimpleNamespace(
+ b64="cGl4ZWxz",
+ captured_url="https://example.test/account",
+ browser_session_id="run_session",
+ dispatch_url=None,
+ dispatch_browser_session_id=None,
+ producer_browser_session_id=None,
+ session_binding=None,
+ captured_at=None,
+ )
+ evidence = {"workflow_run_id": "wr_suffix", "observed_after_workflow_run": True}
+
+ async def read_page(_ctx: CopilotContext, *, run_session_id: str, current_url: str) -> tuple:
+ return evidence, run_session_id, None, frame
+
+ enqueued: list[str] = []
+ monkeypatch.setattr(run_execution_module, "_read_run_session_page_evidence", read_page)
+ monkeypatch.setattr(run_execution_module, "repair_page_evidence_is_admissible", lambda _e: True)
+ monkeypatch.setattr(run_execution_module, "store_post_run_page_evidence", lambda *_a, **_k: (None, False))
+ monkeypatch.setattr(run_execution_module, "_same_run_page_evidence_for_result", lambda *_a: evidence)
+ monkeypatch.setattr(run_execution_module, "enqueue_screenshot", lambda _ctx, b64, **_k: enqueued.append(b64))
+
+ await run_execution_module._capture_and_store_post_run_page(
+ ctx, run_session_id="run_session", run_id="wr_suffix", current_url="https://example.test/account"
+ )
+
+ assert enqueued == ([] if browser_signed_in_by_an_earlier_run else ["cGl4ZWxz"])
+
+
[email protected]("browser_signed_in_by_an_earlier_run", [False, True])
+async def test_a_dispatched_run_frame_is_withheld_when_the_run_browser_carries_a_sign_in(
+ monkeypatch: pytest.MonkeyPatch, browser_signed_in_by_an_earlier_run: bool
+) -> None:
+ # The worker-dispatch path applies the same rule as the inline capture. The clean case is the
+ # control that shows the frame would otherwise reach the queue.
+ ctx = _ctx()
+ if browser_signed_in_by_an_earlier_run:
+ record_sensitive_origin_run_taint(ctx, workflow_run_id="wr_signin", session_id="run_session")
+
+ frame = SimpleNamespace(
+ b64="cGl4ZWxz",
+ captured_url="https://example.test/account",
+ browser_session_id="run_session",
+ dispatch_url=None,
+ dispatch_browser_session_id=None,
+ producer_browser_session_id=None,
+ session_binding=None,
+ captured_at=None,
+ )
+ evidence = {"workflow_run_id": "wr_suffix", "observed_after_workflow_run": True}
+
+ async def read_page(_ctx: CopilotContext, *, run_session_id: str, current_url: str) -> tuple:
+ return evidence, run_session_id, None, frame
+
+ enqueued: list[str] = []
+ monkeypatch.setattr(run_execution_module, "_pre_run_baseline_is_provenance_valid", lambda _e: False)
+ monkeypatch.setattr(run_execution_module, "_read_run_session_page_evidence", read_page)
+ monkeypatch.setattr(run_execution_module, "_dispatched_terminal_page_evidence_is_usable", lambda _e: True)
+ monkeypatch.setattr(run_execution_module, "store_post_run_page_evidence", lambda *_a, **_k: (None, False))
+ monkeypatch.setattr(run_execution_module, "enqueue_screenshot", lambda _ctx, b64, **_k: enqueued.append(b64))
+
+ await run_execution_module._capture_dispatched_terminal_page_evidence(
+ ctx,
+ run_id="wr_suffix",
+ run_session_id="run_session",
+ organization_id="o",
+ current_url="https://example.test/account",
+ )
+
+ assert enqueued == ([] if browser_signed_in_by_an_earlier_run else ["cGl4ZWxz"])
+
+
+ ("tainted_session", "run_session_id", "chat_session", "withheld"),
+ [
+ # The run's own browser carries a sign-in: withhold.
+ ("pbs_run", "pbs_run", "pbs_chat", True),
+ # The chat's browser is signed in but this run used a clean one of its own: keep the
+ # diagnostics. Checking the chat's browser here stripped every clean run's evidence.
+ ("pbs_chat", "pbs_run", "pbs_chat", False),
+ # No browser named for the run: fall back to the browser the call acts in.
+ ("pbs_chat", None, "pbs_chat", True),
+ ],
+)
+def test_sign_in_taint_is_read_from_the_browser_the_run_used(
+ tainted_session: str, run_session_id: str | None, chat_session: str, withheld: bool
+) -> None:
+ ctx = _ctx()
+ ctx.browser_session_id = chat_session
+ record_sensitive_origin_run_taint(ctx, workflow_run_id="wr_signin", session_id=tainted_session)
+
+ assert run_execution_module._run_browser_carries_a_sign_in(ctx, run_session_id) is withheld
diff --git a/tests/unit/test_copilot_frontier.py b/tests/unit/test_copilot_frontier.py
index 460ccf8a4..169c6d0f8 100644
--- a/tests/unit/test_copilot_frontier.py
+++ b/tests/unit/test_copilot_frontier.py
@@ -45,6 +45,10 @@ from skyvern.forge.sdk.copilot.tools import (
)
from skyvern.forge.sdk.copilot.tools import frontier as frontier_module
from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module
+from skyvern.forge.sdk.copilot.tools._shared import (
+ _composition_unverified_current_workflow_labels,
+ _unverified_current_workflow_labels,
+)
from skyvern.forge.sdk.copilot.tools.run_execution import (
_credit_composition_verified_labels,
_record_run_blocks_result,
@@ -175,6 +179,14 @@ def _make_ctx(**kwargs: object) -> CopilotContext:
return CopilotContext(**defaults)
+def _prefix_ran_in(ctx: CopilotContext, session_id: str, end_urls: dict[str, str]) -> str:
+ """Record where the verified prefix's browser stopped; returns the page a resume has to see."""
+ ctx.verified_prefix_block_end_urls = dict(end_urls)
+ ctx.verified_prefix_block_end_session_id = session_id
+ ctx.verified_prefix_terminal_label = list(end_urls)[-1]
+ return end_urls[ctx.verified_prefix_terminal_label]
+
+
# --------------------------------------------------------------------------- #
# Frontier selection — core behavior #
# --------------------------------------------------------------------------- #
@@ -215,35 +227,42 @@ def test_plan_frontier_append_after_success_runs_only_appended() -> None:
ctx = _make_ctx()
ctx.verified_prefix_labels = ["a", "b"]
ctx.verified_block_outputs = {"a": "nav_ok", "b": {"title": "hi"}}
+ page = _prefix_ran_in(ctx, "pbs_prefix_run", {"a": "https://example.com/a", "b": "https://example.com/b"})
- labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["a", "b", "c"], old, new)
+ labels, _seed, frontier, provenance = _plan_frontier(ctx, ["a", "b", "c"], old, new, page)
assert labels == ["c"]
assert frontier == "c"
+ assert provenance == "resumed"
+ assert ctx.frontier_resume_session_id == "pbs_prefix_run"
-def test_plan_frontier_append_walks_back_when_workflow_prefix_is_not_verified() -> None:
+def test_plan_frontier_append_never_runs_an_unverified_prefix_the_caller_left_out() -> None:
+ # Appending a block after an unverified prefix is a request to run that block. Rebuilding the
+ # state it expects would place the order sitting in front of it, which nobody asked for.
old = _FakeDefinition(
[
- _FakeBlock("open", "goto_url", {"url": "https://example.com/search"}),
- _FakeBlock("set_search", "navigation", {"prompt": "Fill search fields"}),
+ _FakeBlock("open", "goto_url", {"url": "https://example.com/cart"}),
+ _FakeBlock("place_order", "navigation", {"prompt": "Click Place order"}),
]
)
new = _FakeDefinition(
[
- _FakeBlock("open", "goto_url", {"url": "https://example.com/search"}),
- _FakeBlock("set_search", "navigation", {"prompt": "Fill updated search fields"}),
- _FakeBlock("submit_search", "navigation", {"prompt": "Click Search"}),
+ _FakeBlock("open", "goto_url", {"url": "https://example.com/cart"}),
+ _FakeBlock("place_order", "navigation", {"prompt": "Click Place order"}),
+ _FakeBlock("read_receipt", "extraction", {"prompt": "Read the receipt number"}),
]
)
ctx = _make_ctx()
ctx.verified_prefix_labels = ["open"]
ctx.verified_block_outputs = {"open": "opened"}
- labels, seed, frontier, _provenance = _plan_frontier(ctx, ["submit_search"], old, new)
+ labels, seed, frontier, _provenance = _plan_frontier(ctx, ["read_receipt"], old, new)
- assert labels == ["open", "set_search", "submit_search"]
- assert seed == {}
- assert frontier == "open"
+ assert labels == ["read_receipt"]
+ assert frontier == "read_receipt"
+ # The recorded output of an earlier block is data the appended block may reference; handing it
+ # over is not the same as running that block again, and `place_order` supplies neither.
+ assert seed == {"open": "opened"}
def test_plan_frontier_unchanged_workflow_continues_from_first_unverified_label() -> None:
@@ -257,20 +276,23 @@ def test_plan_frontier_unchanged_workflow_continues_from_first_unverified_label(
)
ctx = _make_ctx()
ctx.verified_prefix_labels = ["open", "set_search"]
+ page = _prefix_ran_in(ctx, "pbs_prefix_run", {"open": "https://example.com", "set_search": "https://example.com/s"})
- labels, seed, frontier, _provenance = _plan_frontier(
+ labels, seed, frontier, provenance = _plan_frontier(
ctx,
["open", "set_search", "submit_search", "extract"],
definition,
definition,
+ page,
)
assert labels == ["submit_search", "extract"]
assert seed == {}
assert frontier == "submit_search"
+ assert provenance == "resumed"
-def test_plan_frontier_verified_only_request_advances_to_next_unverified_workflow_label() -> None:
+def test_plan_frontier_verified_only_request_reruns_only_what_was_requested() -> None:
definition = _FakeDefinition(
[
_FakeBlock("open", "goto_url"),
@@ -281,17 +303,20 @@ def test_plan_frontier_verified_only_request_advances_to_next_unverified_workflo
)
ctx = _make_ctx()
ctx.verified_prefix_labels = ["open", "set_search"]
+ page = _prefix_ran_in(ctx, "pbs_prefix_run", {"open": "https://example.com", "set_search": "https://example.com/s"})
- labels, seed, frontier, _provenance = _plan_frontier(
+ labels, seed, frontier, provenance = _plan_frontier(
ctx,
["open", "set_search"],
definition,
definition,
+ page,
)
- assert labels == ["submit_search"]
+ assert labels == ["open", "set_search"]
assert seed == {}
- assert frontier == "submit_search"
+ assert frontier == "open"
+ assert provenance == "initial"
def test_plan_frontier_suffix_only_request_seeds_prior_browser_state_outputs() -> None:
@@ -309,9 +334,15 @@ def test_plan_frontier_suffix_only_request_seeds_prior_browser_state_outputs() -
"open": {"current_url": "https://example.com/search"},
"search": {"current_url": "https://example.com/search/results"},
}
+ page = _prefix_ran_in(
+ ctx,
+ "pbs_prefix_run",
+ {"open": "https://example.com/search", "search": "https://example.com/search/results"},
+ )
- labels, seed, frontier, _provenance = _plan_frontier(ctx, ["expand"], definition, definition)
+ labels, seed, frontier, provenance = _plan_frontier(ctx, ["expand"], definition, definition, page)
+ assert provenance == "resumed"
assert labels == ["expand"]
assert seed == {
"open": {"current_url": "https://example.com/search"},
@@ -663,9 +694,10 @@ def test_plan_frontier_edit_resumes_at_edited_block_when_live_page_matches_recor
"login_to_site": "https://app.example.com/dashboard",
"inspect_summary": "https://app.example.com/dashboard/logs",
}
+ ctx.verified_prefix_block_end_session_id = "pbs_login_run"
ctx.verified_prefix_terminal_label = "inspect_summary"
- labels, _seed, frontier, _provenance = _plan_frontier(
+ labels, _seed, frontier, provenance = _plan_frontier(
ctx,
_LOGIN_THEN_INSPECT_LABELS,
old,
@@ -674,6 +706,30 @@ def test_plan_frontier_edit_resumes_at_edited_block_when_live_page_matches_recor
)
assert frontier == "inspect_summary"
assert labels == ["inspect_summary"]
+ assert provenance == "resumed"
+ assert ctx.frontier_resume_session_id == "pbs_login_run"
+
+
+def test_plan_frontier_edit_runs_in_its_own_browser_when_the_prefix_browser_is_unknown() -> None:
+ old, new = _login_then_inspect_edit()
+ ctx = _make_ctx()
+ ctx.verified_prefix_labels = list(_LOGIN_THEN_INSPECT_LABELS)
+ ctx.verified_block_outputs = {"open_site": "ok", "login_to_site": "ok"}
+ ctx.verified_prefix_block_end_urls = {"login_to_site": "https://app.example.com/dashboard"}
+ ctx.verified_prefix_terminal_label = "login_to_site"
+
+ labels, _seed, frontier, provenance = _plan_frontier(
+ ctx,
+ _LOGIN_THEN_INSPECT_LABELS,
+ old,
+ new,
+ "https://app.example.com/dashboard",
+ )
+ assert frontier == labels[0]
+ assert set(labels) <= set(_LOGIN_THEN_INSPECT_LABELS)
+ assert ctx.frontier_requires_own_browser is True
+ assert provenance != "resumed"
+ assert ctx.frontier_resume_session_id is None
def test_plan_frontier_edit_walks_back_when_a_loop_hides_a_credential_fill() -> None:
@@ -706,7 +762,10 @@ def test_plan_frontier_edit_walks_back_when_a_loop_hides_a_credential_fill() ->
"https://app.example.com/signin",
)
+ # The caller asked for the workflow from its head, so a run given its own browser runs all of
+ # what was asked rather than a slice a blank browser could not satisfy.
assert frontier == "open_site"
+ assert ctx.frontier_requires_own_browser is True
def test_plan_frontier_resume_names_the_browser_that_must_run_it() -> None:
@@ -763,6 +822,184 @@ def test_plan_frontier_append_names_the_browser_that_ran_the_prefix() -> None:
assert ctx.frontier_resume_session_id == "pbs_login_run"
+def test_plan_frontier_append_that_signs_in_again_runs_in_its_own_browser() -> None:
+ # The prefix's browser is already signed in, so the plan restarts from the head (where the run
+ # gets its own browser) and keeps every appended block after the second sign-in.
+ login = "await page.locator('#pw').fill(creds.password)"
+ open_site = _FakeBlock("open_site", "navigation", {"url": "https://app.example.com/signin"})
+ old = _FakeDefinition([open_site, _FakeBlock("login_to_site", "code", {"code": login})])
+ new = _FakeDefinition(
+ [
+ open_site,
+ _FakeBlock("login_to_site", "code", {"code": login}),
+ _FakeBlock("login_to_partner", "code", {"code": "await page.locator('#partner_pw').fill(creds.password)"}),
+ _FakeBlock("read_partner_total", "code", {"code": "result = {}"}),
+ ]
+ )
+ ctx = _make_ctx(browser_session_id="pbs_chat")
+ ctx.verified_prefix_labels = ["open_site", "login_to_site"]
+ ctx.verified_block_outputs = {"open_site": "ok", "login_to_site": "ok"}
+ ctx.verified_prefix_block_end_urls = {"login_to_site": "https://app.example.com/dashboard"}
+ ctx.verified_prefix_block_end_session_id = "pbs_login_run"
+ ctx.verified_prefix_terminal_label = "login_to_site"
+
+ labels, _seed, frontier, provenance = _plan_frontier(
+ ctx,
+ ["open_site", "login_to_site", "login_to_partner", "read_partner_total"],
+ old,
+ new,
+ "https://app.example.com/dashboard",
+ )
+
+ assert frontier == labels[0]
+ assert set(labels) <= {"open_site", "login_to_site", "login_to_partner", "read_partner_total"}
+ assert ctx.frontier_requires_own_browser is True
+ assert ctx.frontier_resume_session_id is None
+
+
+def test_plan_frontier_continue_at_an_unverified_sign_in_runs_in_its_own_browser() -> None:
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("sheets_read", "code", {"code": "result = rows"}),
+ _FakeBlock("sign_in", "code", {"code": "await page.locator('#pw').fill(creds.password)"}),
+ _FakeBlock("extract", "code", {"code": "result = {}"}),
+ ]
+ )
+ ctx = _make_ctx(browser_session_id="pbs_chat")
+ ctx.verified_prefix_labels = ["sheets_read"]
+ ctx.verified_block_outputs = {"sheets_read": "ok"}
+
+ labels, seed, frontier, _provenance = _plan_frontier(
+ ctx, ["sheets_read", "sign_in", "extract"], definition, definition, None
+ )
+
+ assert frontier == labels[0]
+ assert set(labels) <= {"sheets_read", "sign_in", "extract"}
+ assert ctx.frontier_requires_own_browser is True
+ assert ctx.frontier_resume_session_id is None
+
+
+def test_plan_frontier_edited_sign_in_block_alone_runs_in_its_own_browser() -> None:
+ open_site = _FakeBlock("open_site", "goto_url", {"url": "https://app.example.com/signin"})
+ old = _FakeDefinition(
+ [open_site, _FakeBlock("sign_in", "code", {"code": "await page.locator('#pw').fill(creds.password)"})]
+ )
+ new = _FakeDefinition(
+ [open_site, _FakeBlock("sign_in", "code", {"code": "await page.locator('#password').fill(creds.password)"})]
+ )
+ ctx = _make_ctx(browser_session_id="pbs_chat")
+ ctx.verified_prefix_labels = ["open_site"]
+ ctx.verified_block_outputs = {"open_site": "ok"}
+ ctx.verified_prefix_block_end_urls = {"open_site": "https://app.example.com/signin"}
+ ctx.verified_prefix_block_end_session_id = "pbs_login_run"
+ ctx.verified_prefix_terminal_label = "open_site"
+
+ labels, _seed, frontier, provenance = _plan_frontier(ctx, ["sign_in"], old, new, "https://app.example.com/signin")
+
+ assert frontier == labels[0]
+ assert labels == ["sign_in"]
+ assert ctx.frontier_requires_own_browser is True
+ assert ctx.frontier_resume_session_id is None
+
+
+def test_plan_frontier_append_beside_a_finally_block_that_does_not_sign_in_keeps_the_prefix_browser() -> None:
+ code = "await page.locator('#pw').fill(creds.password)"
+ cleanup = _FakeBlock("cleanup", "code", {"code": "await page.close()"})
+ old = _FakeDefinition(
+ [_FakeBlock("open_site", "navigation"), _FakeBlock("login_to_site", "code", {"code": code}), cleanup]
+ )
+ old.finally_block_label = "cleanup"
+ new = _FakeDefinition(
+ [
+ _FakeBlock("open_site", "navigation"),
+ _FakeBlock("login_to_site", "code", {"code": code}),
+ _FakeBlock("read_total", "code", {"code": "result = {}"}),
+ cleanup,
+ ]
+ )
+ new.finally_block_label = "cleanup"
+ ctx = _make_ctx(browser_session_id="pbs_chat")
+ ctx.verified_prefix_labels = ["open_site", "login_to_site"]
+ ctx.verified_block_outputs = {"open_site": "ok", "login_to_site": "ok"}
+ ctx.verified_prefix_block_end_urls = {"login_to_site": "https://app.example.com/dashboard"}
+ ctx.verified_prefix_block_end_session_id = "pbs_login_run"
+ ctx.verified_prefix_terminal_label = "login_to_site"
+
+ labels, _seed, frontier, provenance = _plan_frontier(
+ ctx,
+ ["open_site", "login_to_site", "read_total"],
+ old,
+ new,
+ "https://app.example.com/dashboard",
+ )
+
+ assert frontier == "read_total"
+ assert labels == ["read_total"]
+ assert provenance == "resumed"
+ assert ctx.frontier_resume_session_id == "pbs_login_run"
+
+
+def test_plan_frontier_append_beside_a_finally_block_that_signs_in_runs_in_its_own_browser() -> None:
+ code = "await page.locator('#pw').fill(creds.password)"
+ relogin = _FakeBlock("relogin", "code", {"code": code})
+ open_site = _FakeBlock("open_site", "navigation", {"url": "https://app.example.com/signin"})
+ old = _FakeDefinition([open_site, _FakeBlock("login_to_site", "code", {"code": code})])
+ new = _FakeDefinition(
+ [
+ open_site,
+ _FakeBlock("login_to_site", "code", {"code": code}),
+ _FakeBlock("read_total", "code", {"code": "result = {}"}),
+ relogin,
+ ]
+ )
+ new.finally_block_label = "relogin"
+ ctx = _make_ctx(browser_session_id="pbs_chat")
+ ctx.verified_prefix_labels = ["open_site", "login_to_site"]
+ ctx.verified_block_outputs = {"open_site": "ok", "login_to_site": "ok"}
+ page = _prefix_ran_in(ctx, "pbs_login_run", {"login_to_site": "https://app.example.com/dashboard"})
+
+ labels, _seed, frontier, provenance = _plan_frontier(
+ ctx, ["open_site", "login_to_site", "read_total"], old, new, page
+ )
+
+ assert frontier == labels[0]
+ assert set(labels) <= {"open_site", "login_to_site", "read_total"}
+ assert ctx.frontier_requires_own_browser is True
+ assert ctx.frontier_resume_session_id is None
+
+
+def test_plan_frontier_continuation_with_the_browser_position_forgotten_runs_in_its_own_browser() -> None:
+ # A credential-bearing run keeps its verified labels but forgets where its browser stopped,
+ # so the next frontier cannot be proven against any browser and the head is re-run.
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url", {"url": "https://example.com"}),
+ _FakeBlock("fill_search", "navigation", {"prompt": "search"}),
+ ]
+ )
+ ctx = _make_ctx(browser_session_id="pbs_chat")
+ ctx.verified_prefix_labels = ["open"]
+ ctx.verified_block_outputs = {"open": "ok"}
+
+ labels, seed, frontier, provenance = _plan_frontier(ctx, ["open", "fill_search"], definition, definition, None)
+
+ assert frontier == labels[0]
+ assert set(labels) <= {"open", "fill_search"}
+ assert ctx.frontier_requires_own_browser is True
+ assert ctx.frontier_resume_session_id is None
+
+
+def test_plan_frontier_drops_a_resume_browser_named_by_an_earlier_plan() -> None:
+ definition = _FakeDefinition([_FakeBlock("open_site", "goto_url", {"url": "https://app.example.com"})])
+ ctx = _make_ctx(browser_session_id="pbs_chat")
+ ctx.frontier_resume_session_id = "pbs_named_but_never_dispatched"
+
+ _labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["open_site"], None, definition)
+
+ assert frontier == "open_site"
+ assert ctx.frontier_resume_session_id is None
+
+
def test_plan_frontier_does_not_name_a_browser_when_the_seeder_vetoes_the_frontier() -> None:
# An unresolvable template makes the seeder hand back a full re-run, which puts the login block
# back into the executed list. Borrowing the already-signed-in browser for that would replay the
@@ -1273,12 +1510,18 @@ def test_plan_frontier_append_with_block_form_jinja_ref_seeds_the_prefix_output(
"open_page": "nav_ok",
"extract_article_info": {"extracted_information": {"abstract": "Prior output"}},
}
+ page = _prefix_ran_in(
+ ctx,
+ "pbs_prefix_run",
+ {"open_page": "https://example.com/article", "extract_article_info": "https://example.com/article"},
+ )
labels, seed, frontier, _provenance = _plan_frontier(
ctx,
["open_page", "extract_article_info", "summarize_article"],
old,
new,
+ page,
)
assert labels == ["summarize_article"]
@@ -1318,12 +1561,18 @@ def test_plan_frontier_append_seeds_output_parameter_jinja_ref() -> None:
"open_page": "nav_ok",
"extract_article_info": {"extracted_information": {"abstract": "Prior output"}},
}
+ page = _prefix_ran_in(
+ ctx,
+ "pbs_prefix_run",
+ {"open_page": "https://example.com/article", "extract_article_info": "https://example.com/article"},
+ )
labels, seed, frontier, _provenance = _plan_frontier(
ctx,
["open_page", "extract_article_info", "summarize_article"],
old,
new,
+ page,
)
assert labels == ["summarize_article"]
@@ -1673,8 +1922,9 @@ def test_plan_frontier_append_only_with_workflow_param_does_not_fall_back() -> N
ctx = _make_ctx()
ctx.verified_prefix_labels = ["open_page"]
ctx.verified_block_outputs = {"open_page": "nav_ok"}
+ page = _prefix_ran_in(ctx, "pbs_prefix_run", {"open_page": "https://example.com"})
- labels, seed, frontier, _provenance = _plan_frontier(ctx, ["open_page", "search"], old, new)
+ labels, seed, frontier, _provenance = _plan_frontier(ctx, ["open_page", "search"], old, new, page)
assert labels == ["search"]
assert seed == {"open_page": "nav_ok"}
@@ -1863,59 +2113,187 @@ def _recorded_failed_outcome(
)
-def test_plan_frontier_uses_recorded_failed_block_position_for_same_request_order() -> None:
+def test_plan_frontier_retry_after_a_failed_run_runs_in_its_own_browser() -> None:
+ # A failed run forgets the browser's position, so the retry cannot resume the failed block in
+ # the browser that reached it and the workflow is re-run from the head instead.
ctx = _make_ctx()
definition = _wf_def(
("open", "goto_url", {"url": "https://example.com"}),
("search", "navigation", {"url": None}),
("extract", "extraction", {"prompt": "extract"}),
)
+ ctx.verified_prefix_labels = ["open"]
+ ctx.verified_block_outputs = {"open": "opened"}
ctx.latest_recorded_build_test_outcome = _recorded_failed_outcome(
block_labels=["open", "search", "extract"],
attempted_block_label="search",
workflow_definition=definition,
)
- labels, seed, frontier, _provenance = _plan_frontier(
+ labels, seed, frontier, provenance = _plan_frontier(
ctx,
["open", "search", "extract"],
definition,
definition,
+ "https://example.com",
)
- assert labels == ["search", "extract"]
- assert seed == {}
- assert frontier == "search"
+ assert frontier == labels[0]
+ assert set(labels) <= {"open", "search", "extract"}
+ assert ctx.frontier_requires_own_browser is True
+ assert ctx.frontier_resume_session_id is None
-def test_plan_frontier_maps_recorded_failed_block_by_structure_across_label_churn() -> None:
- ctx = _make_ctx()
- old = _wf_def(
- ("open_old", "goto_url", {"url": "https://example.com"}),
- ("search_old", "navigation", {"url": None}),
- ("extract_old", "extraction", {"prompt": "extract"}),
+def test_plan_frontier_does_not_resume_when_stored_order_is_not_run_order() -> None:
+ # `read_total` is stored before the block that jumps to it, so position cannot say what ran
+ # first. Resuming here would put the run in whatever state the other block left behind.
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("read_total", "code", {"code": "result = rows"}),
+ _FakeBlock(
+ "open_site", "goto_url", {"url": "https://app.example.com/list", "next_block_label": "read_total"}
+ ),
+ ]
)
- new = _wf_def(
- ("open_new", "goto_url", {"url": "https://example.com"}),
- ("search_new", "navigation", {"url": None}),
- ("extract_new", "extraction", {"prompt": "extract"}),
+ ctx = _make_ctx(browser_session_id="pbs_chat")
+ ctx.verified_prefix_labels = ["read_total"]
+ ctx.verified_block_outputs = {"read_total": "ok"}
+ ctx.verified_prefix_block_end_urls = {"read_total": "https://app.example.com/list"}
+ ctx.verified_prefix_block_end_session_id = "pbs_prefix_run"
+ ctx.verified_prefix_terminal_label = "read_total"
+
+ labels, _seed, frontier, provenance = _plan_frontier(
+ ctx, ["open_site"], definition, definition, "https://app.example.com/list"
)
+
+ assert labels == ["open_site"]
+ assert frontier == "open_site"
+ assert provenance != "resumed"
+ assert ctx.frontier_resume_session_id is None
+ assert ctx.frontier_requires_own_browser is True
+
+
+def test_plan_frontier_resumes_when_the_workflow_branches_after_the_frontier() -> None:
+ # Most real workflows branch somewhere. A conditional downstream of the frontier cannot change
+ # which blocks ran before it, so it must not cost the continuation the browser holding that state.
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url", {"url": "https://app.example.com/"}),
+ _FakeBlock("read", "code", {"code": "result = rows"}),
+ _FakeBlock("branch", "conditional", {"ordered_branches": [{"label": "x"}]}),
+ ]
+ )
+ ctx = _make_ctx(browser_session_id="pbs_chat")
+ ctx.verified_prefix_labels = ["open"]
+ page = _prefix_ran_in(ctx, "pbs_prefix_run", {"open": "https://app.example.com/list"})
+
+ labels, _seed, frontier, provenance = _plan_frontier(ctx, ["read"], definition, definition, page)
+
+ assert labels == ["read"]
+ assert frontier == "read"
+ assert provenance == "resumed"
+ assert ctx.frontier_resume_session_id == "pbs_prefix_run"
+ assert ctx.frontier_requires_own_browser is False
+
+
+def test_plan_frontier_reads_traversal_order_when_the_finally_block_is_stored_first() -> None:
+ # Stored first, the finally block would otherwise count as part of every body block's prefix,
+ # so a verified body prefix would read as unverified and the continuation would lose its browser.
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("cleanup", "code", {"code": "await page.locator('#logout').click()"}),
+ _FakeBlock("open_site", "goto_url", {"url": "https://app.example.com/list"}),
+ _FakeBlock("read_total", "code", {"code": "result = rows"}),
+ ]
+ )
+ definition.finally_block_label = "cleanup"
+ ctx = _make_ctx(browser_session_id="pbs_chat")
+ ctx.verified_prefix_labels = ["open_site"]
+ ctx.verified_block_outputs = {"open_site": "ok"}
+
+ labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["read_total"], definition, definition, None)
+
+ assert labels == ["read_total"]
+ assert frontier == "read_total"
+ # Read as unverified, this plain continuation would have been handed the chat's page instead.
+ assert ctx.frontier_requires_own_browser is True
+
+
+def test_plan_frontier_never_adds_a_block_the_caller_did_not_request() -> None:
+ # An earlier block can submit, send or pay, so rebuilding state by replaying it would repeat an
+ # effect the caller left out of this request.
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("login", "code", {"code": "await page.locator('#pw').fill(creds.password)"}),
+ _FakeBlock("submit_order", "code", {"code": "await page.locator('#pay').click()"}),
+ _FakeBlock("read", "code", {"code": "result = {}"}),
+ ]
+ )
+ ctx = _make_ctx(browser_session_id="pbs_chat")
+ ctx.verified_prefix_labels = ["login", "submit_order"]
+ ctx.verified_block_outputs = {"login": "ok", "submit_order": "ok"}
+
+ labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["read"], definition, definition, None)
+
+ assert labels == ["read"]
+ assert frontier == "read"
+ assert ctx.frontier_requires_own_browser is True
+
+
+def test_plan_frontier_retry_of_a_head_request_keeps_every_requested_block() -> None:
+ # A blank browser cannot satisfy a suffix that assumed the earlier blocks ran, and the caller
+ # did ask for them, so the retry runs the list it was given.
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url", {"url": "https://example.com"}),
+ _FakeBlock("search", "code", {"code": "await page.locator('#q').fill('x')"}),
+ _FakeBlock("extract", "code", {"code": "result = {}"}),
+ ]
+ )
+ ctx = _make_ctx(browser_session_id="pbs_chat")
+ ctx.verified_prefix_labels = ["open"]
+ ctx.verified_block_outputs = {"open": "ok"}
ctx.latest_recorded_build_test_outcome = _recorded_failed_outcome(
- block_labels=["open_old", "search_old", "extract_old"],
- attempted_block_label="search_old",
- workflow_definition=old,
+ block_labels=["open", "search", "extract"],
+ attempted_block_label="search",
+ workflow_definition=definition,
)
- labels, seed, frontier, _provenance = _plan_frontier(
- ctx,
- ["open_new", "search_new", "extract_new"],
- old,
- new,
+ labels, _seed, frontier, _provenance = _plan_frontier(
+ ctx, ["open", "search", "extract"], definition, definition, None
)
- assert labels == ["search_new", "extract_new"]
- assert seed == {}
- assert frontier == "search_new"
+ assert labels == ["open", "search", "extract"]
+ assert frontier == "open"
+
+
+def test_plan_frontier_retry_of_a_partial_request_keeps_every_requested_block() -> None:
+ # Same reason as the head retry, for a request that starts mid-workflow: `search` established
+ # what `extract` needs, and narrowing the retry to the block that failed hands a blank browser
+ # a suffix whose state nothing produced. Both blocks were asked for, so both run.
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url", {"url": "https://example.com"}),
+ _FakeBlock("search", "code", {"code": "await page.locator('#q').fill('x')"}),
+ _FakeBlock("extract", "code", {"code": "result = {}"}),
+ ]
+ )
+ ctx = _make_ctx(browser_session_id="pbs_chat")
+ # `search` passed inside the attempt that failed at `extract`, and the browser it passed in is
+ # gone — so this retry is minted a blank one.
+ ctx.verified_prefix_labels = ["open", "search"]
+ ctx.verified_block_outputs = {"open": "ok"}
+ ctx.latest_recorded_build_test_outcome = _recorded_failed_outcome(
+ block_labels=["search", "extract"],
+ attempted_block_label="extract",
+ workflow_definition=definition,
+ )
+
+ labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["search", "extract"], definition, definition, None)
+
+ assert labels == ["search", "extract"]
+ assert frontier == "search"
+ assert ctx.frontier_requires_own_browser is True
def test_plan_frontier_fails_closed_when_recorded_failed_order_differs() -> None:
@@ -1978,38 +2356,6 @@ def test_plan_frontier_fails_closed_when_recorded_failed_shapes_are_ambiguous()
assert frontier == "second_new"
-def test_plan_frontier_does_not_index_suffix_failed_run_into_full_request() -> None:
- ctx = _make_ctx()
- ctx.verified_prefix_labels = ["open_new"]
- old = _wf_def(
- ("open_old", "goto_url", {"url": "https://example.com"}),
- ("search_old", "navigation", {"url": None}),
- ("extract_old", "extraction", {"prompt": "extract"}),
- )
- new = _wf_def(
- ("open_new", "goto_url", {"url": "https://example.com"}),
- ("search_new", "navigation", {"url": None}),
- ("extract_new", "extraction", {"prompt": "extract"}),
- )
- ctx.latest_recorded_build_test_outcome = _recorded_failed_outcome(
- block_labels=["search_old", "extract_old"],
- attempted_block_label="search_old",
- requested_block_labels=["open_old", "search_old", "extract_old"],
- workflow_definition=old,
- )
-
- labels, seed, frontier, _provenance = _plan_frontier(
- ctx,
- ["open_new", "search_new", "extract_new"],
- old,
- new,
- )
-
- assert labels == ["search_new", "extract_new"]
- assert seed == {}
- assert frontier == "search_new"
-
-
def test_recorded_failed_prefix_anchor_maps_relabels_from_recorded_shapes() -> None:
ctx = _make_ctx()
old = _wf_def(
@@ -2147,9 +2493,11 @@ def test_edit_invalidates_verified_goal_block_on_split_path() -> None:
# Split path: run_blocks passes old==new; the pruned prefix makes the edited
# block the frontier again instead of reusing it as verified.
- labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["open", "search", "extract"], new, new)
+ page = _prefix_ran_in(ctx, "pbs_prefix_run", {"open": "https://example.com", "search": "https://example.com/r"})
+ labels, _seed, frontier, provenance = _plan_frontier(ctx, ["open", "search", "extract"], new, new, page)
assert frontier == "extract"
assert "extract" in labels
+ assert provenance == "resumed"
def test_append_only_edit_keeps_prefix_but_drops_end_to_end_claim() -> None:
@@ -2530,9 +2878,11 @@ def test_appended_block_output_parameter_keeps_upstream_verified_prefix() -> Non
assert ctx.workflow_verification_evidence.full_workflow_verified is False
assert ctx.last_full_workflow_test_ok is False
- labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["sign_in", "read_summary"], prior, new)
+ page = _prefix_ran_in(ctx, "pbs_prefix_run", {"sign_in": "https://example.com/home"})
+ labels, _seed, frontier, provenance = _plan_frontier(ctx, ["sign_in", "read_summary"], prior, new, page)
assert labels == ["read_summary"]
assert frontier == "read_summary"
+ assert provenance == "resumed"
def test_parameter_named_only_by_workflow_system_prompt_resets_verified_trust() -> None:
@@ -2719,17 +3069,15 @@ def test_reorder_resets_verified_trust() -> None:
assert ctx.last_full_workflow_test_ok is False
-def test_unanchored_append_is_never_credited_as_composition_verified() -> None:
- prior = _wf_def(("open", "goto_url", {"url": "https://example.com"}))
+def test_unanchored_block_is_never_credited_as_composition_verified() -> None:
appended = _wf_def(
("open", "goto_url", {"url": "https://example.com"}),
("add_to_cart", "navigation", {"prompt": "add the item to the cart"}),
)
ctx = _make_ctx()
- _seed_verified(ctx, ["open"], current_url="https://example.com/list", full=False)
ctx.composition_verified_labels = ["open"]
- labels, _seed, frontier, provenance = _plan_frontier(ctx, ["open", "add_to_cart"], prior, appended)
+ labels, _seed, frontier, provenance = _plan_frontier(ctx, ["add_to_cart"], appended, appended)
assert frontier == "add_to_cart"
assert provenance == "unanchored"
@@ -2739,19 +3087,132 @@ def test_unanchored_append_is_never_credited_as_composition_verified() -> None:
assert "add_to_cart" not in ctx.composition_verified_labels
+def test_a_native_login_block_does_not_resume_the_browser_it_would_sign_into() -> None:
+ # A login block authenticates through its type and parameters and carries no code, so a guard
+ # reading code alone would call the one block built to sign in safe to replay in place.
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url", {"url": "https://app.example.com/"}),
+ _FakeBlock("sign_in", "login"),
+ _FakeBlock("read", "code", {"code": "result = rows"}),
+ ]
+ )
+ ctx = _make_ctx(browser_session_id="pbs_chat")
+ ctx.verified_prefix_labels = ["open"]
+ page = _prefix_ran_in(ctx, "pbs_prefix_run", {"open": "https://app.example.com/login"})
+
+ labels, _seed, frontier, provenance = _plan_frontier(ctx, ["sign_in"], definition, definition, page)
+
+ assert labels == ["sign_in"]
+ assert frontier == "sign_in"
+ assert provenance != "resumed"
+ assert ctx.frontier_resume_session_id is None
+ assert ctx.frontier_requires_own_browser is True
+
+
+def test_a_workflow_with_a_cleanup_block_can_be_declared_tested() -> None:
+ # The cleanup block runs on its own after the body, so no body run ever verifies it. Counted
+ # among the blocks still needing proof, it would keep every such workflow from being tested.
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url", {"url": "https://app.example.com/"}),
+ _FakeBlock("read", "code", {"code": "result = rows"}),
+ _FakeBlock("cleanup", "code", {"code": "await page.locator('#logout').click()"}),
+ ]
+ )
+ definition.finally_block_label = "cleanup"
+ ctx = _make_ctx()
+ ctx.last_workflow = _FakeWorkflow(definition)
+ ctx.verified_prefix_labels = ["open", "read"]
+ ctx.composition_verified_labels = ["open", "read"]
+
+ assert terminal_ready_for_latch(
+ current_workflow_labels=["open", "read"],
+ planned_block_labels=["open", "read"],
+ completed_block_labels=["open", "read"],
+ all_run_blocks_completed=True,
+ unverified=_unverified_current_workflow_labels(ctx),
+ composition_unverified=_composition_unverified_current_workflow_labels(ctx),
+ artifact_reason=None,
+ structured_blocker=None,
+ empty_data_blocks=False,
+ )
+
+
+def test_a_full_run_earns_credit_though_its_labels_carry_the_cleanup_block() -> None:
+ # A blank-browser run of the whole workflow executes the cleanup block too, so its label list
+ # holds one the workflow's own order leaves out. Compared unfiltered, the run proving the
+ # entire body would be the one rejected.
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url", {"url": "https://app.example.com/"}),
+ _FakeBlock("read", "code", {"code": "result = rows"}),
+ _FakeBlock("cleanup", "code", {"code": "await page.locator('#logout').click()"}),
+ ]
+ )
+ definition.finally_block_label = "cleanup"
+ ctx = _make_ctx()
+ ctx.last_workflow = _FakeWorkflow(definition)
+ ctx.composition_verified_labels = []
+
+ _credit_composition_verified_labels(ctx, ["open", "read", "cleanup"], "initial")
+
+ assert ctx.composition_verified_labels == ["open", "read"]
+ assert _composition_unverified_current_workflow_labels(ctx) == []
+
+
+def test_the_cleanup_block_is_recognised_from_the_workflow_yaml_alone() -> None:
+ # A saved workflow can be tested before its model object is loaded, when labels come from the
+ # YAML. Reading the cleanup block only from the model leaves that path treating it as body work.
+ ctx = _make_ctx()
+ ctx.last_workflow = None
+ ctx.last_workflow_yaml = (
+ "workflow_definition:\n"
+ " finally_block_label: cleanup\n"
+ " blocks:\n"
+ " - label: open\n"
+ " - label: read\n"
+ " - label: cleanup\n"
+ )
+ ctx.verified_prefix_labels = ["open", "read"]
+ ctx.composition_verified_labels = ["open", "read"]
+
+ assert _unverified_current_workflow_labels(ctx) == []
+ assert _composition_unverified_current_workflow_labels(ctx) == []
+
+
+def test_a_head_run_earns_composition_credit_when_the_finally_block_is_stored_first() -> None:
+ # Counted in stored order the finally block occupies position 0, so the body's own first block
+ # looks like it starts mid-chain and earns nothing — leaving the workflow never terminal-ready.
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("cleanup", "code", {"code": "await page.locator('#logout').click()"}),
+ _FakeBlock("open", "goto_url", {"url": "https://app.example.com/"}),
+ _FakeBlock("read", "code", {"code": "result = rows"}),
+ ]
+ )
+ definition.finally_block_label = "cleanup"
+ ctx = _make_ctx()
+ ctx.last_workflow = _FakeWorkflow(definition)
+ ctx.composition_verified_labels = []
+
+ _credit_composition_verified_labels(ctx, ["open"], "initial")
+
+ assert ctx.composition_verified_labels == ["open"]
+ assert _composition_unverified_current_workflow_labels(ctx) == ["read"]
+
+
def test_a_lone_mid_workflow_block_that_opens_a_page_is_not_a_replay() -> None:
- prior = _wf_def(("open", "goto_url", {"url": "https://example.com"}))
appended = _wf_def(
("open", "goto_url", {"url": "https://example.com"}),
("open_cart", "goto_url", {"url": "https://example.com/cart"}),
)
ctx = _make_ctx()
- _seed_verified(ctx, ["open"], current_url="https://example.com/list", full=False)
ctx.composition_verified_labels = ["open"]
ctx.last_workflow = _FakeWorkflow(appended)
ctx.last_workflow_yaml = "workflow: yaml"
- labels, _seed, frontier, provenance = _plan_frontier(ctx, ["open", "open_cart"], prior, appended)
+ labels, _seed, frontier, provenance = _plan_frontier(ctx, ["open_cart"], appended, appended)
assert frontier == "open_cart"
assert provenance == "unanchored"
@@ -3002,18 +3463,16 @@ def test_a_non_contiguous_run_credits_no_composition_labels() -> None:
def test_a_passing_unanchored_run_still_leaves_the_workflow_composition_unverified() -> None:
- prior = _wf_def(("open", "goto_url", {"url": "https://example.com"}))
appended = _wf_def(
("open", "goto_url", {"url": "https://example.com"}),
("add_to_cart", "navigation", {"prompt": "add the item to the cart"}),
)
ctx = _make_ctx()
- _seed_verified(ctx, ["open"], current_url="https://example.com/list", full=False)
ctx.composition_verified_labels = ["open"]
ctx.last_workflow = _FakeWorkflow(appended)
ctx.last_workflow_yaml = "workflow: yaml"
- labels, _seed, _frontier, provenance = _plan_frontier(ctx, ["open", "add_to_cart"], prior, appended)
+ labels, _seed, _frontier, provenance = _plan_frontier(ctx, ["add_to_cart"], appended, appended)
_credit_composition_verified_labels(ctx, labels, provenance)
ctx.verified_prefix_labels = ["open", "add_to_cart"]
@@ -3154,8 +3613,9 @@ def test_frontier_planning_adds_no_rerun_floor_or_goal_classifier() -> None:
)
ctx = _make_ctx()
_seed_verified(ctx, ["open"], current_url="https://example.com/list", full=False)
+ page = _prefix_ran_in(ctx, "pbs_prefix_run", {"open": "https://example.com/list"})
- labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["open", "extract"], definition, definition)
+ labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["open", "extract"], definition, definition, page)
assert labels == ["extract"]
assert frontier == "extract"