Skip to content

Automate browser based workflows with AI

SKY-15230 Stabilize browser failure repair custody (#8326)

Andrew Neilson3c2d14124d6c
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index fee60513f..14a05f990 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -52,6 +52,7 @@ from skyvern.forge.sdk.copilot.browser_ablation import (
from skyvern.forge.sdk.copilot.build_test_outcome import (
_VALUE_EXCERPT_MAX,
BuildTestEvidencePacket,
+ BuildTestFailedOperation,
RecordedBuildTestOutcome,
history_has_runtime_block_failure,
observed_value_extraction_scaffold_lines,
@@ -180,8 +181,10 @@ from skyvern.forge.sdk.copilot.streaming_adapter import (
)
from skyvern.forge.sdk.copilot.terminal_envelope import (
TerminalCause,
+ TerminalOutcomeEnvelope,
assemble_terminal_envelope,
reason_in_reply_shadow,
+ render_terminal_message,
select_run_outcome_anchor,
)
from skyvern.forge.sdk.copilot.todo_list import todo_list_prompt
@@ -213,6 +216,7 @@ from skyvern.forge.sdk.copilot.turn_outcome import (
)
from skyvern.forge.sdk.copilot.workflow_yaml import (
redact_credentials_in_workflow_yaml,
+ runner_code_block_associations,
stored_block_code,
stored_workflow_yaml,
)
@@ -1086,6 +1090,22 @@ def _recorded_build_test_outcome_prompt(ctx: CopilotContext | None) -> str:
lines.append(f"- {'; '.join(fields)}")
if outcome.workflow_run_id:
lines.append(f"workflow_run_id: {_clean_authoring_repair_prompt_atom(outcome.workflow_run_id)}")
+ failed_operation = outcome.failed_operation
+ if failed_operation is not None:
+ lines.append("failed_operation:")
+ lines.append(f"- kind={_clean_authoring_repair_prompt_atom(failed_operation.kind)}")
+ if failed_operation.workflow_run_block_id:
+ lines.append(
+ f"- workflow_run_block_id={_clean_authoring_repair_prompt_atom(failed_operation.workflow_run_block_id)}"
+ )
+ if failed_operation.block_label:
+ lines.append(f"- block_label={_clean_authoring_repair_prompt_atom(failed_operation.block_label)}")
+ if failed_operation.failing_line is not None:
+ lines.append(f"- failing_line={failed_operation.failing_line}")
+ lines.append(
+ "Repair the persisted code at this evidenced block/line, then test the changed attempt with "
+ "edit_block_and_run before reporting it."
+ )
# Facts render for every outcome; the two post-run page-path directives bind the model's next
# action, so they keep the authority check that gated this whole section before.
page_path_failure = outcome.page_path_failure
@@ -1462,6 +1482,9 @@ def _terminal_cause_for_context(ctx: CopilotContext) -> TerminalCause | None:
return "deadline_expired"
if ctx.copilot_max_turns_exceeded is True:
return "max_turns_exceeded"
+ failed_operation = _terminal_failed_operation(ctx)
+ if failed_operation is not None:
+ return failed_operation.kind
return None
@@ -1544,6 +1567,13 @@ def _turn_facts_for_context(ctx: CopilotContext, review: NarrativeReviewProjecti
)
+def _terminal_failed_operation(
+ ctx: CopilotContext,
+) -> BuildTestFailedOperation | None:
+ outcome = getattr(ctx, "latest_recorded_build_test_outcome", None)
+ return outcome.failed_operation if isinstance(outcome, RecordedBuildTestOutcome) else None
+
+
def _assemble_terminal_envelope_safe(
*,
response_type: str,
@@ -1559,6 +1589,8 @@ def _assemble_terminal_envelope_safe(
final_message: str,
terminal_cause: TerminalCause | None = None,
blocks_run_this_turn: int | None = None,
+ failed_operation: BuildTestFailedOperation | None = None,
+ proposal_present: bool = False,
) -> dict[str, Any] | None:
try:
envelope = assemble_terminal_envelope(
@@ -1574,6 +1606,8 @@ def _assemble_terminal_envelope_safe(
workflow_attempted=workflow_attempted,
terminal_cause=terminal_cause,
blocks_run_this_turn=blocks_run_this_turn,
+ failed_operation=failed_operation,
+ proposal_present=proposal_present,
)
except Exception:
LOG.warning("copilot terminal envelope assembly failed", exc_info=True)
@@ -1679,6 +1713,10 @@ def _make_agent_result(
result_has_workflow_attempt = bool(
ctx is not None and (result_carries_workflow or ctx.has_genuine_workflow_attempt())
)
+ failed_operation = _terminal_failed_operation(ctx) if ctx is not None else None
+ if failed_operation is not None and proposal_disposition == "auto_applicable":
+ proposal_disposition = "review_untested" if result_carries_workflow else "no_proposal"
+ kwargs["proposal_disposition"] = proposal_disposition
if isinstance(narrative_payload, dict):
payload_base = {
key: value for key, value in narrative_payload.items() if key != "deliveredUnverifiedObservedOutputs"
@@ -1792,7 +1830,25 @@ def _make_agent_result(
final_message=str(kwargs.get("user_response") or ""),
terminal_cause=terminal_cause,
blocks_run_this_turn=len(ctx.executed_block_labels),
+ failed_operation=failed_operation,
+ proposal_present=result_carries_workflow,
)
+ if terminal_envelope is not None and terminal_envelope.get("failed_operation") is not None:
+ envelope = TerminalOutcomeEnvelope.model_validate(terminal_envelope)
+ terminal_message, replaced = render_terminal_message(
+ envelope,
+ str(kwargs.get("user_response") or ""),
+ bool(kwargs.get("cancelled")),
+ )
+ if replaced:
+ kwargs["user_response"] = terminal_message
+ narrative = kwargs.get("narrative_payload")
+ if isinstance(narrative, dict):
+ kwargs["narrative_payload"] = {
+ **narrative,
+ "terminalMessage": terminal_message,
+ "narrativeSummary": terminal_message,
+ }
kwargs["terminal_envelope"] = terminal_envelope
if turn_facts is not None:
payload = kwargs.get("narrative_payload")
@@ -2056,16 +2112,17 @@ async def _run_end_to_end_test_turn(
setup_error_for_llm = "The end-to-end test could not be started."
result = {"ok": False, "error": setup_error_for_llm}
result_data = result.get("data")
- if result.get("ok") is False and (not isinstance(result_data, dict) or not result_data.get("workflow_run_id")):
- if not isinstance(result_data, dict):
- result_data = {}
- result["data"] = result_data
+ if not isinstance(result_data, dict):
+ result_data = {}
+ result["data"] = result_data
+ if result.get("ok") is False and not result_data.get("workflow_run_id"):
result_data.setdefault("overall_status", "setup_failed")
- finalize_build_test_result(
- ctx,
- source_tool="run_blocks_and_collect_debug",
- result=result,
- )
+ if BUILD_TEST_PACKET_KEY not in result_data:
+ finalize_build_test_result(
+ ctx,
+ source_tool="run_blocks_and_collect_debug",
+ result=result,
+ )
raw_packet = result["data"].get(BUILD_TEST_PACKET_KEY)
if isinstance(raw_packet, dict):
try:
@@ -3062,8 +3119,8 @@ def _build_cancelled_exit_result(ctx: CopilotContext, global_llm_context: str |
else:
result = _build_cancel_exit_result(ctx, global_llm_context)
result.cancellation_iteration = ctx.copilot_turn_cancelled_iteration
- outcome = ctx.latest_recorded_build_test_outcome
- result.cancellation_last_recorded_phase = outcome.phase if outcome is not None else None
+ outcome = getattr(ctx, "latest_recorded_build_test_outcome", None)
+ result.cancellation_last_recorded_phase = outcome.phase if isinstance(outcome, RecordedBuildTestOutcome) else None
return result
@@ -3485,6 +3542,7 @@ async def _translate_to_agent_result(
if resp_type == "REPLACE_WORKFLOW" and last_workflow is not ctx.last_workflow and not blocker_active:
ctx.last_workflow = last_workflow
ctx.last_workflow_yaml = last_workflow_yaml
+ ctx.runner_code_block_associations_by_label = runner_code_block_associations(last_workflow_yaml or "")
ctx.last_test_ok = None
ctx.last_full_workflow_test_ok = False
clear_active_run_evidence_on_workflow_edit(ctx)
diff --git a/skyvern/forge/sdk/copilot/build_test_outcome.py b/skyvern/forge/sdk/copilot/build_test_outcome.py
index cf124eea7..72b4af178 100644
--- a/skyvern/forge/sdk/copilot/build_test_outcome.py
+++ b/skyvern/forge/sdk/copilot/build_test_outcome.py
@@ -11,7 +11,7 @@ from urllib.parse import urlsplit
import structlog
import yaml
-from pydantic import BaseModel, ConfigDict, Field, JsonValue, model_validator
+from pydantic import BaseModel, ConfigDict, Field, JsonValue, field_validator, model_validator
from skyvern.forge.sdk.copilot.challenge_evidence import (
carrier_backed_anti_bot_categories,
@@ -27,7 +27,9 @@ from skyvern.forge.sdk.copilot.context import CodeAuthoringRepairContext, PageOb
from skyvern.forge.sdk.copilot.failure_tracking import selector_identities_in_text, selector_identity_from_failure
from skyvern.forge.sdk.copilot.request_policy import redact_raw_secrets_for_prompt
from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome
+from skyvern.forge.sdk.copilot.secret_scrub import scrub_all_registered_from_text
from skyvern.forge.sdk.schemas.copilot_turn_outcome import UnresolvedRuntimeFailure
+from skyvern.schemas.workflows import BlockStatus
LOG = structlog.get_logger()
@@ -71,6 +73,7 @@ BuildTestPacketWorkflowSource = Literal["accepted_write_readback", "turn_start_p
BuildTestPacketUnfinishedKind = Literal["unverified_block", "missing_requested_output"]
BuildTestPacketPageCaptureStatus = Literal["captured", "unavailable"]
BuildTestPacketPageCaptureOmission = Literal["screenshot_capture_failed", "page_capture_unavailable"]
+BuildTestFailedOperationKind = Literal["browser_operation_failed"]
BuildTestPacketLocatorUnobservedReason = Literal[
"worker_owned_run",
"run_browser_unavailable",
@@ -88,6 +91,8 @@ _VALUE_EXCERPT_MAX = 700
_HISTORY_LIMIT = 8
_INSPECT_PAGE_SOURCE_TOOL = "inspect_page_for_composition"
_UNRECOVERABLE_TOOL_ERROR_CATEGORY = "UNRECOVERABLE_TOOL_ERROR"
+_BROWSER_OPERATION_FAILED: BuildTestFailedOperationKind = "browser_operation_failed"
+_EXECUTED_BLOCK_STATUSES = frozenset(status.value for status in BlockStatus if status != BlockStatus.skipped)
_PLAYWRIGHT_LOCATOR_WAIT_RE = re.compile(
r"waiting for locator\((?P<quote>['\"])(?P<selector>.*?)(?P=quote)\)"
r"(?P<locator_chain>(?:\.[A-Za-z_][A-Za-z0-9_]*(?:\([^)]*\))?)*)\s+to be (?P<state>[a-z_]+)",
@@ -205,6 +210,24 @@ class BuildTestPacketLocatorObservation(BaseModel):
return self
+class BuildTestFailedOperation(BaseModel):
+ """Exact runner-owned operation failure and the identities recorded with it."""
+
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ kind: BuildTestFailedOperationKind
+ workflow_run_id: str | None = None
+ workflow_run_block_id: str | None = None
+ block_label: str | None = None
+ failing_line: int | None = None
+ block_association: str | None = Field(default=None, exclude=True, repr=False)
+
+ @field_validator("block_label")
+ @classmethod
+ def redact_block_label(cls, value: str | None) -> str | None:
+ return _redacted_terminal_text(value)
+
+
class BuildTestPacketFailure(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
@@ -217,6 +240,7 @@ class BuildTestPacketFailure(BaseModel):
reason: str | None = None
error_codes: list[str] = Field(default_factory=list)
failing_line: int | None = None
+ failed_operation: BuildTestFailedOperation | None = None
action_trace: list[str] = Field(default_factory=list)
page_state: BuildTestPacketPageState | None = None
locator_observations: list[BuildTestPacketLocatorObservation] = Field(default_factory=list)
@@ -305,6 +329,7 @@ class RecordedBuildTestOutcome(BaseModel):
workflow_run_id: str | None = None
block_labels: list[str] = Field(default_factory=list)
requested_block_labels: list[str] = Field(default_factory=list)
+ executed_block_labels: list[str] = Field(default_factory=list)
block_shape_hashes: dict[str, str] = Field(default_factory=dict)
structural_failure_identity: str = ""
verified_progress_marker: str = ""
@@ -314,6 +339,10 @@ class RecordedBuildTestOutcome(BaseModel):
missing_requested_output_facts: list[dict[str, object]] = Field(default_factory=list)
runtime_output_repair_facts: list[dict[str, object]] = Field(default_factory=list)
page_path_failure: PostRunPagePathFailure | None = None
+ failed_operation: BuildTestFailedOperation | None = None
+ failed_operation_call_signature: str | None = Field(default=None, exclude=True, repr=False)
+ failed_operation_code_signature: str | None = Field(default=None, exclude=True, repr=False)
+ executed_block_associations: tuple[str, ...] = Field(default=(), exclude=True, repr=False)
authored_structure_signature: str | None = None
display_text: str = ""
observed_page_value_excerpt: str = ""
@@ -375,18 +404,59 @@ class _RecordedBuildTestOutcomeContext(Protocol):
persisted_workflow_yaml: str | None
staged_workflow_yaml: str | None
latest_recorded_build_test_outcome: RecordedBuildTestOutcome | None
+ runner_code_block_associations_by_label: dict[str, str]
recorded_build_test_outcome_history: list[dict[str, object]]
recorded_persisted_block_run_workflow_run_id: str | None
def record_build_test_outcome(ctx: _RecordedBuildTestOutcomeContext, outcome: RecordedBuildTestOutcome | None) -> None:
if outcome is None:
- ctx.latest_recorded_build_test_outcome = None
+ latest = getattr(ctx, "latest_recorded_build_test_outcome", None)
+ if latest is None or latest.failed_operation is None:
+ ctx.latest_recorded_build_test_outcome = None
return
+ prior = getattr(ctx, "latest_recorded_build_test_outcome", None)
+ if not isinstance(prior, RecordedBuildTestOutcome):
+ prior = None
+ if outcome.failed_operation is not None:
+ source_yaml = _executed_workflow_yaml(ctx)
+ association = outcome.failed_operation.block_association
+ failed_code = _code_for_runner_association(ctx, source_yaml, association)
+ outcome = outcome.model_copy(
+ update={
+ "failed_operation_call_signature": _failed_operation_call_signature(
+ failed_code, outcome.failed_operation.failing_line
+ ),
+ "failed_operation_code_signature": _stable_hash(failed_code) if failed_code else None,
+ }
+ )
+ elif prior is not None and prior.failed_operation is not None:
+ source_yaml = _executed_workflow_yaml(ctx)
+ association = prior.failed_operation.block_association
+ tested_code = _code_for_runner_association(ctx, source_yaml, association)
+ changed_attempt_was_tested = (
+ outcome.phase == "persisted_block_run"
+ and outcome.verdict == "progress_observed"
+ and outcome.workflow_run_id not in (None, prior.failed_operation.workflow_run_id)
+ and association is not None
+ and association in outcome.executed_block_associations
+ and _failed_operation_changed(
+ tested_code,
+ prior.failed_operation_call_signature,
+ prior.failed_operation_code_signature,
+ )
+ )
+ if not changed_attempt_was_tested:
+ outcome = outcome.model_copy(
+ update={
+ "failed_operation": prior.failed_operation,
+ "failed_operation_call_signature": prior.failed_operation_call_signature,
+ "failed_operation_code_signature": prior.failed_operation_code_signature,
+ }
+ )
ctx.latest_recorded_build_test_outcome = outcome
- history = getattr(ctx, "recorded_build_test_outcome_history", None)
- if not isinstance(history, list):
- history = []
+ raw_history = getattr(ctx, "recorded_build_test_outcome_history", None)
+ history: list[dict[str, object]] = raw_history if isinstance(raw_history, list) else []
history.append(
{
"phase": outcome.phase,
@@ -400,6 +470,10 @@ def record_build_test_outcome(ctx: _RecordedBuildTestOutcomeContext, outcome: Re
"attempted_block_label": outcome.attempted_block_label,
"attempted_block_signature": _attempted_block_signature(ctx, outcome),
"attempted_call_ref": outcome.attempted_call_ref,
+ "failed_operation": (
+ outcome.failed_operation.model_dump(mode="json") if outcome.failed_operation is not None else None
+ ),
+ "failed_operation_call_signature": outcome.failed_operation_call_signature,
}
)
del history[:-_HISTORY_LIMIT]
@@ -428,11 +502,31 @@ def _attempted_block_signature(ctx: _RecordedBuildTestOutcomeContext, outcome: R
and never hashes equal to a YAML-derived signature."""
if outcome.reason_code != "runtime_block_failure" or not outcome.attempted_block_label:
return ""
- return authored_block_signatures_from_workflow(ctx.workflow_yaml).get(outcome.attempted_block_label, "")
+ return authored_block_signatures_from_workflow(_executed_workflow_yaml(ctx)).get(outcome.attempted_block_label, "")
+
+
+def _executed_workflow_yaml(ctx: _RecordedBuildTestOutcomeContext) -> str:
+ return ctx.staged_workflow_yaml or ctx.workflow_yaml
+
+
+def _code_for_runner_association(
+ ctx: _RecordedBuildTestOutcomeContext,
+ workflow_yaml: str | None,
+ association: str | None,
+) -> str | None:
+ if association is None:
+ return None
+ associations = getattr(ctx, "runner_code_block_associations_by_label", {})
+ if not isinstance(associations, dict):
+ return None
+ for label, candidate_association in associations.items():
+ if candidate_association == association:
+ return _code_blocks_by_label(workflow_yaml).get(label)
+ return None
def _code_blocks_by_label(workflow_yaml: str | None) -> dict[str, str]:
- """Code text for every code block in the draft, including blocks nested in containers or loops."""
+ """Code text keyed by raw label for legacy user-facing failure disclosure only."""
code_by_label: dict[str, str] = {}
if not isinstance(workflow_yaml, str) or not workflow_yaml.strip():
return code_by_label
@@ -448,11 +542,62 @@ def _code_blocks_by_label(workflow_yaml: str | None) -> dict[str, str]:
code_by_label[label] = code
walk(block.get("blocks"))
walk(block.get("loop_blocks"))
+ for branch in _mapping_list(block.get("branch_conditions")):
+ walk(branch.get("blocks"))
walk(_dict(parsed.get("workflow_definition")).get("blocks"))
return code_by_label
+def _failed_operation_call_signature(code: str | None, failing_line: int | None) -> str | None:
+ """Identity of the outermost browser operation covering the runner-stamped failing line."""
+ if not code or type(failing_line) is not int or failing_line < 1:
+ return None
+ wrapper = _parse_block_code(code)
+ if wrapper is None:
+ return None
+ wrapper_line = failing_line + 1
+ candidates = [
+ node
+ for node in ast.walk(wrapper)
+ if isinstance(node, ast.Call)
+ and node.lineno <= wrapper_line <= (node.end_lineno if node.end_lineno is not None else node.lineno)
+ ]
+ if not candidates:
+ return None
+ outermost = min(
+ candidates,
+ key=lambda node: (
+ node.lineno,
+ node.col_offset,
+ -(node.end_lineno or node.lineno),
+ -(node.end_col_offset or node.col_offset),
+ ),
+ )
+ return _stable_hash(ast.dump(outermost, include_attributes=False))
+
+
+def _failed_operation_changed(
+ tested_code: str | None,
+ prior_call_signature: str | None,
+ prior_code_signature: str | None,
+) -> bool:
+ """Prove the recorded operation changed, or use whole-block change for a typed line omission."""
+ if not tested_code:
+ return False
+ wrapper = _parse_block_code(tested_code)
+ if wrapper is None:
+ return False
+ current_call_signatures = {
+ _stable_hash(ast.dump(node, include_attributes=False))
+ for node in ast.walk(wrapper)
+ if isinstance(node, ast.Call)
+ }
+ if prior_call_signature is not None:
+ return prior_call_signature not in current_call_signatures
+ return prior_code_signature is not None and _stable_hash(tested_code) != prior_code_signature
+
+
# Every construct that can reach the end of a block without running something inside it, including
# expression-level ones: a zero-length comprehension skips its body exactly as an unentered loop does.
# Over-detection only costs a redundant note; a miss silently drops a real failure.
@@ -519,7 +664,8 @@ def unresolved_runtime_block_failure_with_disposition(
against a signed-out one, same lines, opposite precondition. Only evidence that the code itself
changed -- the failing call removed, or the block's signature changed -- clears the failure.
"""
- history = ctx.recorded_build_test_outcome_history
+ raw_history = getattr(ctx, "recorded_build_test_outcome_history", None)
+ history: list[dict[str, object]] = raw_history if isinstance(raw_history, list) else []
for index in range(len(history) - 1, -1, -1):
entry = history[index]
if entry.get("reason_code") != "runtime_block_failure":
@@ -580,7 +726,7 @@ def bind_post_run_page_path_failure(
page_evidence: Mapping[str, object],
) -> bool:
"""Bind a fresh same-run page-path condition without changing the outcome's structural identity."""
- latest = ctx.latest_recorded_build_test_outcome
+ latest = getattr(ctx, "latest_recorded_build_test_outcome", None)
if (
not isinstance(latest, RecordedBuildTestOutcome)
or not latest.is_authoritative
@@ -812,11 +958,13 @@ def _required_input_unbound_outcome(
failed_block: Mapping[str, object] | None,
block_labels: list[str],
requested_block_labels: list[str],
+ executed_block_labels: list[str],
block_shape_hashes: Mapping[str, str],
workflow_run_id: str | None,
page_capture: BuildTestPacketPageCapture | None,
authored_structure_signature: str | None,
referenced_unbound_keys: Sequence[str],
+ failed_operation: BuildTestFailedOperation | None = None,
) -> RecordedBuildTestOutcome:
return RecordedBuildTestOutcome(
phase="persisted_block_run",
@@ -827,10 +975,12 @@ def _required_input_unbound_outcome(
workflow_run_id=workflow_run_id or None,
block_labels=block_labels,
requested_block_labels=requested_block_labels,
+ executed_block_labels=executed_block_labels,
block_shape_hashes=dict(block_shape_hashes),
structural_failure_identity=_required_input_unbound_identity(failed_block, referenced_unbound_keys),
page_capture=page_capture,
authored_structure_signature=authored_structure_signature,
+ failed_operation=failed_operation,
observed_evidence_summary=_bounded_text(
"unbound required inputs: " + ", ".join(_clean_list(referenced_unbound_keys))
),
@@ -854,15 +1004,41 @@ def recorded_outcome_from_run_blocks_result(
unbound_required_parameter_keys: Sequence[str] | None = None,
block_parameter_keys: Mapping[str, Sequence[str]] | None = None,
block_shape_hashes: Mapping[str, str] | None = None,
+ block_associations_by_label: Mapping[str, str] | None = None,
) -> RecordedBuildTestOutcome | None:
data = _dict(result.get("data"))
workflow_run_id = _safe_str(data.get("workflow_run_id"))
blocks = _block_dicts(data.get("blocks"))
failed_block = _first_failed_block(blocks)
- block_labels = [_safe_str(block.get("label")) for block in blocks if _safe_str(block.get("label"))]
+ failed_operation = failed_operation_from_run_blocks_result(
+ result, block_associations_by_label=block_associations_by_label
+ )
+ block_labels = [
+ label for block in blocks if (label := _redacted_terminal_text(_safe_str(block.get("label")))) is not None
+ ]
requested = data.get("requested_block_labels")
requested_block_labels = (
- _clean_list([label for label in requested if isinstance(label, str)]) if isinstance(requested, list) else []
+ _clean_list(
+ [redacted for label in requested if isinstance(label, str) if (redacted := _redacted_terminal_text(label))]
+ )
+ if isinstance(requested, list)
+ else []
+ )
+ executed_block_labels = _clean_list(
+ [
+ redacted
+ for block in blocks
+ if _safe_str(block.get("status")) in _EXECUTED_BLOCK_STATUSES
+ if (redacted := _redacted_terminal_text(_safe_str(block.get("label"))))
+ ]
+ )
+ executed_block_associations = tuple(
+ dict.fromkeys(
+ association
+ for block in blocks
+ if _safe_str(block.get("status")) in _EXECUTED_BLOCK_STATUSES
+ if (association := (block_associations_by_label or {}).get(_safe_str(block.get("label"))))
+ )
)
block_shape_hashes = dict(block_shape_hashes or {})
referenced_unbound_keys = _referenced_unbound_input_keys(
@@ -935,9 +1111,12 @@ def recorded_outcome_from_run_blocks_result(
workflow_run_id=recorded_run_outcome.workflow_run_id or workflow_run_id or None,
block_labels=block_labels,
requested_block_labels=requested_block_labels,
+ executed_block_labels=executed_block_labels,
block_shape_hashes=block_shape_hashes,
+ executed_block_associations=executed_block_associations,
page_capture=page_capture,
authored_structure_signature=authored_structure_signature,
+ failed_operation=failed_operation,
observed_evidence_summary=recorded_run_outcome.display_reason or "",
key_provenance={"structural_failure_identity": "terminal blocker precedence suppresses repair prompt"},
)
@@ -950,11 +1129,14 @@ def recorded_outcome_from_run_blocks_result(
workflow_run_id=recorded_run_outcome.workflow_run_id or workflow_run_id or None,
block_labels=block_labels,
requested_block_labels=requested_block_labels,
+ executed_block_labels=executed_block_labels,
block_shape_hashes=block_shape_hashes,
+ executed_block_associations=executed_block_associations,
verified_progress_marker=verification_identity or "run_completed_verified",
page_capture=page_capture,
evidence_refs=output_refs,
authored_structure_signature=authored_structure_signature,
+ failed_operation=failed_operation,
observed_evidence_summary=recorded_run_outcome.display_reason or "Completion verification passed.",
key_provenance={
"verified_progress_marker": "CompletionVerificationResult satisfied criteria",
@@ -970,9 +1152,12 @@ def recorded_outcome_from_run_blocks_result(
workflow_run_id=recorded_run_outcome.workflow_run_id or workflow_run_id or None,
block_labels=block_labels,
requested_block_labels=requested_block_labels,
+ executed_block_labels=executed_block_labels,
block_shape_hashes=block_shape_hashes,
+ executed_block_associations=executed_block_associations,
page_capture=page_capture,
authored_structure_signature=authored_structure_signature,
+ failed_operation=failed_operation,
observed_evidence_summary=recorded_run_outcome.display_reason or "",
key_provenance={"structural_failure_identity": "run outcome was not evaluated"},
)
@@ -981,11 +1166,13 @@ def recorded_outcome_from_run_blocks_result(
failed_block,
block_labels,
requested_block_labels,
+ executed_block_labels,
block_shape_hashes,
recorded_run_outcome.workflow_run_id or workflow_run_id or None,
page_capture,
authored_structure_signature,
referenced_unbound_keys,
+ failed_operation,
)
structural_identity = verification_identity or _typed_omission_identity(missing_output_facts)
evidence_refs = output_refs
@@ -998,9 +1185,12 @@ def recorded_outcome_from_run_blocks_result(
workflow_run_id=recorded_run_outcome.workflow_run_id or workflow_run_id or None,
block_labels=block_labels,
requested_block_labels=requested_block_labels,
+ executed_block_labels=executed_block_labels,
block_shape_hashes=block_shape_hashes,
+ executed_block_associations=executed_block_associations,
page_capture=page_capture,
authored_structure_signature=authored_structure_signature,
+ failed_operation=failed_operation,
observed_evidence_summary=recorded_run_outcome.display_reason or "",
key_provenance={"structural_failure_identity": "no typed verification/page/output identity available"},
)
@@ -1017,9 +1207,12 @@ def recorded_outcome_from_run_blocks_result(
workflow_run_id=recorded_run_outcome.workflow_run_id or workflow_run_id or None,
block_labels=block_labels,
requested_block_labels=requested_block_labels,
+ executed_block_labels=executed_block_labels,
block_shape_hashes=block_shape_hashes,
+ executed_block_associations=executed_block_associations,
page_capture=page_capture,
authored_structure_signature=authored_structure_signature,
+ failed_operation=failed_operation,
observed_evidence_summary=recorded_run_outcome.display_reason or "",
key_provenance={"structural_failure_identity": "turn-unsatisfiable fallback floor, no reachable route"},
)
@@ -1031,6 +1224,7 @@ def recorded_outcome_from_run_blocks_result(
workflow_run_id=recorded_run_outcome.workflow_run_id or workflow_run_id or None,
block_labels=block_labels,
requested_block_labels=requested_block_labels,
+ executed_block_labels=executed_block_labels,
block_shape_hashes=block_shape_hashes,
structural_failure_identity=structural_identity,
page_evidence_refs=page_refs,
@@ -1040,6 +1234,8 @@ def recorded_outcome_from_run_blocks_result(
runtime_output_repair_facts=runtime_output_facts,
page_path_failure=page_path_failure,
authored_structure_signature=authored_structure_signature,
+ failed_operation=failed_operation,
+ executed_block_associations=executed_block_associations,
observed_evidence_summary=recorded_run_outcome.display_reason or "",
key_provenance={
"structural_failure_identity": (
@@ -1063,36 +1259,51 @@ def recorded_outcome_from_run_blocks_result(
failure_categories = _failure_category_refs(carrier_backed_anti_bot_categories(data.get("failure_categories")))
status = _safe_str(failed_block.get("status")) if failed_block is not None else run_status
runtime_failure_identity = _runtime_failure_identity(failed_block)
+ failed_operation_identity = (
+ _stable_hash(
+ {
+ "kind": failed_operation.kind,
+ "block_label": failed_operation.block_label,
+ "failing_line": failed_operation.failing_line,
+ }
+ )
+ if failed_operation is not None
+ else ""
+ )
if referenced_unbound_keys:
return _required_input_unbound_outcome(
failed_block,
block_labels,
requested_block_labels,
+ executed_block_labels,
block_shape_hashes,
workflow_run_id or None,
page_capture,
authored_structure_signature,
referenced_unbound_keys,
+ failed_operation,
)
if not (
failure_categories
or failure_type
or runtime_failure_identity
+ or failed_operation_identity
or page_refs
or output_refs
or missing_output_facts
):
return None
+ structural_identity_payload: dict[str, object] = {
+ "failure_type": failure_type,
+ "failure_categories": failure_categories,
+ "runtime_failure_identity": runtime_failure_identity,
+ "status": status,
+ }
+ if failed_operation_identity:
+ structural_identity_payload["failed_operation_identity"] = failed_operation_identity
structural_identity = (
- _stable_hash(
- {
- "failure_type": failure_type,
- "failure_categories": failure_categories,
- "runtime_failure_identity": runtime_failure_identity,
- "status": status,
- }
- )
- if failure_categories or failure_type or runtime_failure_identity
+ _stable_hash(structural_identity_payload)
+ if failure_categories or failure_type or runtime_failure_identity or failed_operation_identity
else ""
)
if not structural_identity:
@@ -1116,7 +1327,9 @@ def recorded_outcome_from_run_blocks_result(
reason_code = "unrecoverable_tool_error"
structural_identity = ""
page_refs = []
- has_runtime_failure_evidence = bool(failure_categories or failure_type or runtime_failure_identity or failed_block)
+ has_runtime_failure_evidence = bool(
+ failure_categories or failure_type or runtime_failure_identity or failed_operation_identity or failed_block
+ )
if (
verdict == "repairable_failure"
and not has_runtime_failure_evidence
@@ -1128,7 +1341,9 @@ def recorded_outcome_from_run_blocks_result(
return RecordedBuildTestOutcome(
phase="persisted_block_run",
attempted_tool="update_and_run_blocks",
- attempted_block_label=_safe_str(failed_block.get("label")) if failed_block is not None else "",
+ attempted_block_label=_redacted_terminal_text(_safe_str(failed_block.get("label"))) or ""
+ if failed_block is not None
+ else "",
attempted_call_ref=selector_identity_from_failure(
_safe_str(failed_block.get("failure_reason")) if failed_block is not None else ""
),
@@ -1137,6 +1352,7 @@ def recorded_outcome_from_run_blocks_result(
workflow_run_id=workflow_run_id or None,
block_labels=block_labels,
requested_block_labels=requested_block_labels,
+ executed_block_labels=executed_block_labels,
block_shape_hashes=block_shape_hashes,
structural_failure_identity=structural_identity,
page_evidence_refs=page_refs,
@@ -1144,11 +1360,13 @@ def recorded_outcome_from_run_blocks_result(
evidence_refs=output_refs,
missing_requested_output_facts=missing_output_facts,
authored_structure_signature=authored_structure_signature,
+ failed_operation=failed_operation,
+ executed_block_associations=executed_block_associations,
observed_evidence_summary=_bounded_text(run_status),
key_provenance={
"structural_failure_identity": (
"typed runtime failure structure"
- if runtime_failure_identity
+ if runtime_failure_identity or failed_operation_identity
else "typed failure categories or failure_type"
),
"page_evidence_refs": "bounded post-run page evidence",
@@ -1158,6 +1376,31 @@ def recorded_outcome_from_run_blocks_result(
)
+def failed_operation_from_run_blocks_result(
+ result: Mapping[str, object],
+ *,
+ block_associations_by_label: Mapping[str, str] | None = None,
+) -> BuildTestFailedOperation | None:
+ """Project the runner's exact browser-operation code without interpreting failure prose."""
+
+ data = _dict(result.get("data"))
+ failed_block = _first_failed_block(_block_dicts(data.get("blocks")))
+ if failed_block is None:
+ return None
+ error_codes = failed_block.get("error_codes")
+ if not isinstance(error_codes, list) or _BROWSER_OPERATION_FAILED not in error_codes:
+ return None
+ failing_line = data.get("failing_code_line")
+ return BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ workflow_run_id=_safe_str(data.get("workflow_run_id")) or None,
+ workflow_run_block_id=_safe_str(failed_block.get("workflow_run_block_id")) or None,
+ block_label=_safe_str(failed_block.get("label")) or None,
+ failing_line=failing_line if type(failing_line) is int else None,
+ block_association=(block_associations_by_label or {}).get(_safe_str(failed_block.get("label"))),
+ )
+
+
def _stable_hash(payload: object) -> str:
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
@@ -1326,6 +1569,13 @@ def _bounded_text(value: object, max_chars: int = _TEXT_MAX) -> str:
return text[:max_chars]
+def _redacted_terminal_text(value: str | None) -> str | None:
+ if not isinstance(value, str):
+ return None
+ redacted = redact_raw_secrets_for_prompt(scrub_all_registered_from_text(value))
+ return redacted or None
+
+
def _bounded_ref(value: object, max_chars: int = _REF_TEXT_MAX) -> str:
if not isinstance(value, str):
return ""
@@ -2150,4 +2400,7 @@ def _value_shape(value: object, *, depth: int = 0) -> object:
def history_has_runtime_block_failure(ctx: _RecordedBuildTestOutcomeContext) -> bool:
"""Whether this turn recorded any runtime block failure, resolved or not."""
- return any(entry.get("reason_code") == "runtime_block_failure" for entry in ctx.recorded_build_test_outcome_history)
+ history = getattr(ctx, "recorded_build_test_outcome_history", [])
+ return isinstance(history, list) and any(
+ isinstance(entry, dict) and entry.get("reason_code") == "runtime_block_failure" for entry in history
+ )
diff --git a/skyvern/forge/sdk/copilot/output_utils.py b/skyvern/forge/sdk/copilot/output_utils.py
index 813018c5f..273130643 100644
--- a/skyvern/forge/sdk/copilot/output_utils.py
+++ b/skyvern/forge/sdk/copilot/output_utils.py
@@ -16,6 +16,7 @@ from skyvern.forge.sdk.agents.context import sanitize_agent_tool_result_for_llm
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal, assert_clean_user_facing_text
from skyvern.forge.sdk.copilot.build_test_outcome import (
BuildTestEvidencePacket,
+ BuildTestFailedOperation,
BuildTestPacketLocatorObservation,
BuildTestPacketPageState,
BuildTestPacketRegisteredOutput,
@@ -331,6 +332,36 @@ def _bounded_packet_strings(
return rendered
+def _bounded_failed_operation(
+ operation: BuildTestFailedOperation | None,
+ notices: list[str],
+) -> BuildTestFailedOperation | None:
+ if operation is None:
+ return None
+ return operation.model_copy(
+ update={
+ "workflow_run_id": _bounded_packet_string(
+ operation.workflow_run_id,
+ field_name="failure.failed_operation.workflow_run_id",
+ max_chars=_BUILD_TEST_IDENTIFIER_MAX_CHARS,
+ notices=notices,
+ ),
+ "workflow_run_block_id": _bounded_packet_string(
+ operation.workflow_run_block_id,
+ field_name="failure.failed_operation.workflow_run_block_id",
+ max_chars=_BUILD_TEST_IDENTIFIER_MAX_CHARS,
+ notices=notices,
+ ),
+ "block_label": _bounded_packet_string(
+ operation.block_label,
+ field_name="failure.failed_operation.block_label",
+ max_chars=_BUILD_TEST_IDENTIFIER_MAX_CHARS,
+ notices=notices,
+ ),
+ }
+ )
+
+
def _bounded_obstruction_control(
control: PageObstructionControl,
*,
@@ -855,6 +886,7 @@ def project_build_test_packet_for_llm(packet: BuildTestEvidencePacket) -> BuildT
max_chars=_BUILD_TEST_FAILURE_REASON_MAX_CHARS,
notices=notices,
),
+ "failed_operation": _bounded_failed_operation(failure.failed_operation, notices),
"action_trace": action_trace,
"page_state": _bounded_packet_page_state(
failure.page_state, notices, field_prefix="failure.page_state"
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index e031ccad6..bbc1e6599 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -419,6 +419,9 @@ class AgentContext:
staged_workflow_yaml: str | None = None
staged_workflow: Any | None = None
has_staged_proposal: bool = False
+ # Server-owned only: maps current raw code-block labels to opaque identities. It is never
+ # serialized into the workflow YAML or model-facing repair evidence.
+ runner_code_block_associations_by_label: dict[str, str] = field(default_factory=dict)
# Prior turn's uncommitted draft; carries blocks even when the request body and canonical row are empty.
prior_copilot_workflow_yaml: str | None = None
canonical_was_persisted_due_to_param_change: bool = False
diff --git a/skyvern/forge/sdk/copilot/terminal_envelope.py b/skyvern/forge/sdk/copilot/terminal_envelope.py
index 728158d29..be87b4dd2 100644
--- a/skyvern/forge/sdk/copilot/terminal_envelope.py
+++ b/skyvern/forge/sdk/copilot/terminal_envelope.py
@@ -3,15 +3,16 @@ from __future__ import annotations
from collections.abc import Sequence
from typing import Literal
-from pydantic import BaseModel
+from pydantic import BaseModel, model_validator
from skyvern.forge.sdk.copilot.blocker_signal import assert_clean_user_facing_text
+from skyvern.forge.sdk.copilot.build_test_outcome import BuildTestFailedOperation
from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome
from skyvern.forge.sdk.copilot.secret_redaction import redact_raw_secrets_for_prompt
TerminalNextState = Literal["completed", "proposal_pending", "awaiting_user_input", "stopped"]
TerminalResponseKind = Literal["question", "update", "answer", "stopped"]
-TerminalCause = Literal["deadline_expired", "max_turns_exceeded"]
+TerminalCause = Literal["deadline_expired", "max_turns_exceeded", "browser_operation_failed"]
_FINAL_RUN_VERDICTS = frozenset({"not_demonstrated", "not_evaluated"})
_REVIEW_PROPOSAL_DISPOSITIONS = frozenset({"review_untested", "review_tested"})
_SHADOW_REASON_TRAILING_PUNCTUATION = ".,;:!?"
@@ -55,10 +56,19 @@ class TerminalOutcomeEnvelope(BaseModel):
attempted: str | None = None
response_kind: TerminalResponseKind
terminal_cause: TerminalCause | None = None
+ failed_operation: BuildTestFailedOperation | None = None
+ proposal_present: bool = False
interruption: InterruptedTurnFacts | None = None
rendered_from_envelope: bool = False
envelope_version: int = 1
+ @model_validator(mode="after")
+ def normalize_failed_operation_state(self) -> TerminalOutcomeEnvelope:
+ if self.failed_operation is not None:
+ self.verified = False
+ self.workflow_applied = False
+ return self
+
def assemble_terminal_envelope(
*,
@@ -74,6 +84,8 @@ def assemble_terminal_envelope(
workflow_attempted: bool,
terminal_cause: TerminalCause | None = None,
blocks_run_this_turn: int | None = None,
+ failed_operation: BuildTestFailedOperation | None = None,
+ proposal_present: bool = False,
) -> TerminalOutcomeEnvelope | None:
run_outcome = select_run_outcome_anchor(run_outcomes)
run_verdict = run_outcome.verdict if run_outcome is not None else None
@@ -84,6 +96,9 @@ def assemble_terminal_envelope(
run_display_reason = _clean_text(run_outcome.display_reason) if run_outcome is not None else None
run_output_report = _safe_output_report(run_outcome.output_report) if run_outcome is not None else None
user_action_required = response_type == "ASK_QUESTION"
+ if failed_operation is not None:
+ verified = False
+ workflow_applied = False
next_state = _derive_next_state(
user_action_required=user_action_required,
verified=verified,
@@ -97,6 +112,11 @@ def assemble_terminal_envelope(
workflow_attempted=workflow_attempted,
explicit_stop=bool(run_outcome or blocker_reason or halt_kind or terminal_cause),
)
+ if failed_operation is not None:
+ if not user_action_required:
+ next_state = "stopped"
+ response_kind = "stopped"
+ terminal_cause = terminal_cause or failed_operation.kind
return TerminalOutcomeEnvelope(
next_state=next_state,
verified=verified,
@@ -113,12 +133,27 @@ def assemble_terminal_envelope(
attempted=_clean_text(attempted),
response_kind=response_kind,
terminal_cause=terminal_cause,
+ failed_operation=failed_operation,
+ proposal_present=proposal_present,
)
def finalize_applied_state(
envelope: TerminalOutcomeEnvelope, *, applied: bool, proposal_present: bool = False
) -> TerminalOutcomeEnvelope:
+ if envelope.failed_operation is not None:
+ if envelope.user_action_required:
+ return envelope.model_copy(
+ update={
+ "verified": False,
+ "workflow_applied": False,
+ "next_state": "awaiting_user_input",
+ "response_kind": "question",
+ }
+ )
+ return envelope.model_copy(
+ update={"verified": False, "workflow_applied": False, "next_state": "stopped", "response_kind": "stopped"}
+ )
if envelope.user_action_required:
next_state: TerminalNextState = "awaiting_user_input"
elif envelope.verified and applied:
@@ -178,6 +213,27 @@ def render_interrupted_message(facts: InterruptedTurnFacts | None = None) -> str
def render_terminal_message(envelope: TerminalOutcomeEnvelope, agent_message: str, cancelled: bool) -> tuple[str, bool]:
output_report = _safe_output_report(envelope.run_output_report)
+ if envelope.failed_operation is not None and not cancelled:
+ message = "I stopped after a browser operation failed while testing the workflow."
+ if envelope.proposal_present:
+ message = _append_sentence(
+ message,
+ "The untested draft is available for review, but the requested work was not confirmed.",
+ )
+ else:
+ message = _append_sentence(message, "The requested work was not confirmed.")
+ if envelope.user_action_required:
+ pending_question_intro = "The pending question is quoted below; its premise is not confirmed"
+ # The route may render an AgentResult again when envelope-authoritative copy is enabled.
+ # Preserve the first server-authored rendering instead of quoting that whole rendering as
+ # though it were the model's pending question.
+ if _text_contains(agent_message, message) and _text_contains(agent_message, pending_question_intro):
+ return agent_message, False
+ message = _append_sentence(
+ message,
+ f"{pending_question_intro}: {agent_message}",
+ )
+ return message, True
# A deadline-expired turn already authored copy naming time and the draft's
# state; replaced=True is what syncs it to the surfaces hydration prefers.
# "completed" is excluded because replaced=True also overwrites a distinct
diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.py
index 69208faa1..a2a06a884 100644
--- a/skyvern/forge/sdk/copilot/tools/__init__.py
+++ b/skyvern/forge/sdk/copilot/tools/__init__.py
@@ -350,7 +350,7 @@ async def _persist_block_scoped_edit(
author-time check, so a block edit cannot slip past what a full submission must satisfy.
"""
prior_definition = await _get_prior_workflow_definition(copilot_ctx)
- params: dict[str, Any] = {"workflow_yaml": workflow_yaml}
+ params: dict[str, Any] = {"workflow_yaml": workflow_yaml, "_preserve_code_block_associations": True}
if code_artifact_metadata is not None:
params["code_artifact_metadata"] = _code_artifact_metadata_as_tool_argument(code_artifact_metadata)
params["raw_code_artifact_metadata"] = code_artifact_metadata
@@ -515,7 +515,7 @@ async def edit_block_and_run_tool(
prior_definition = await _get_prior_workflow_definition(copilot_ctx)
with copilot_span("edit_block_and_run.update", data={"yaml_length": len(workflow_yaml)}):
update_result = await _update_workflow(
- {"workflow_yaml": workflow_yaml},
+ {"workflow_yaml": workflow_yaml, "_preserve_code_block_associations": True},
copilot_ctx,
allow_missing_credentials=skip_run_after_update,
originating_call_id=_originating_call_id(ctx),
@@ -908,13 +908,14 @@ async def run_blocks_tool(
block_outputs_to_seed=block_outputs_to_seed,
frontier_start_label=frontier_start_label,
)
- await _verify_and_record_run_blocks_result(copilot_ctx, result, handler_start)
+ recorded_outcome = await _verify_and_record_run_blocks_result(copilot_ctx, result, handler_start)
_carry_unresolved_failure_into_result(copilot_ctx, result, "run_blocks_and_collect_debug")
record_tool_step_result_for_ctx(copilot_ctx, "run_blocks_and_collect_debug", arguments, result)
finalize_build_test_result(
copilot_ctx,
source_tool="run_blocks_and_collect_debug",
result=result,
+ recorded_outcome=recorded_outcome,
)
enqueue_screenshot_from_result(
copilot_ctx,
@@ -1173,7 +1174,7 @@ async def _run_updated_workflow_blocks(
block_outputs_to_seed=block_outputs_to_seed,
frontier_start_label=frontier_start_label,
)
- await _verify_and_record_run_blocks_result(copilot_ctx, run_result, handler_start)
+ recorded_outcome = await _verify_and_record_run_blocks_result(copilot_ctx, run_result, handler_start)
carry_author_time_findings(update_result, run_result)
_carry_unresolved_failure_into_result(copilot_ctx, run_result, tool_name)
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, run_result)
@@ -1182,6 +1183,7 @@ async def _run_updated_workflow_blocks(
source_tool=tool_name,
result=run_result,
workflow_updated=True,
+ recorded_outcome=recorded_outcome,
)
enqueue_screenshot_from_result(
copilot_ctx,
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index 71e46b1da..e58d279ca 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -45,6 +45,7 @@ from skyvern.forge.sdk.copilot.build_test_outcome import (
RecordedBuildTestOutcome,
authored_block_parameter_keys_from_workflow,
authored_structure_signature_from_workflow,
+ failed_operation_from_run_blocks_result,
post_run_page_capture_from_result,
record_build_test_outcome,
recorded_outcome_from_run_blocks_result,
@@ -143,7 +144,7 @@ from skyvern.forge.sdk.copilot.secret_redaction import redact_raw_secrets_for_pr
from skyvern.forge.sdk.copilot.secret_scrub import scrub_secrets_from_structure
from skyvern.forge.sdk.copilot.tracing_setup import copilot_span
from skyvern.forge.sdk.copilot.turn_halt import stash_turn_halt_from_blocker_signal
-from skyvern.forge.sdk.copilot.workflow_yaml import _process_workflow_yaml
+from skyvern.forge.sdk.copilot.workflow_yaml import _process_workflow_yaml, runner_code_block_associations
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.executor.factory import AsyncExecutorFactory
from skyvern.forge.sdk.schemas.credentials import CredentialVaultType, PasswordCredential
@@ -2299,6 +2300,11 @@ async def run_workflow_end_to_end(ctx: CopilotContext, workflow_yaml: str) -> di
if authority_error:
return {"ok": False, "error": authority_error}
+ ctx.runner_code_block_associations_by_label = runner_code_block_associations(
+ workflow_yaml,
+ prior_associations=ctx.runner_code_block_associations_by_label,
+ preserve_existing=True,
+ )
workflow = await _process_workflow_yaml(
workflow_id=ctx.workflow_id,
workflow_permanent_id=ctx.workflow_permanent_id,
@@ -2333,8 +2339,13 @@ async def run_workflow_end_to_end(ctx: CopilotContext, workflow_yaml: str) -> di
force_fresh_session=True,
definition_unpersisted=True,
)
- await _verify_and_record_run_blocks_result(ctx, result, time.monotonic())
- return result
+ recorded_outcome = await _verify_and_record_run_blocks_result(ctx, result, time.monotonic())
+ return finalize_build_test_result(
+ ctx,
+ source_tool="run_blocks_and_collect_debug",
+ result=result,
+ recorded_outcome=recorded_outcome,
+ )
async def _run_blocks_and_collect_debug(
@@ -2347,6 +2358,13 @@ async def _run_blocks_and_collect_debug(
force_fresh_session: bool = False,
definition_unpersisted: bool = False,
) -> dict[str, Any]:
+ # Older drafts predate server-owned block associations. Associate their current raw snapshot
+ # once before outcome collection without adding anything to model-controlled YAML.
+ if not ctx.runner_code_block_associations_by_label:
+ ctx.runner_code_block_associations_by_label = runner_code_block_associations(
+ ctx.staged_workflow_yaml or ctx.workflow_yaml
+ )
+
# 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 = ctx.frontier_resume_session_id
@@ -4246,6 +4264,7 @@ def _build_recorded_build_test_outcome(
code_artifact_metadata,
),
block_shape_hashes=block_shape_hashes,
+ block_associations_by_label=getattr(copilot_ctx, "runner_code_block_associations_by_label", {}),
)
@@ -4406,14 +4425,14 @@ def _carry_unresolved_failure_into_result(copilot_ctx: Any, result: dict[str, An
"copilot run result unresolved-failure disposition",
tool_name=tool_name,
workflow_run_id=this_run_id,
- retained_history=len(copilot_ctx.recorded_build_test_outcome_history),
+ retained_history=len(getattr(copilot_ctx, "recorded_build_test_outcome_history", [])),
disposition=disposition,
attached=unresolved is not None,
)
if unresolved is None:
return
failure_kind = ""
- for entry in reversed(copilot_ctx.recorded_build_test_outcome_history):
+ for entry in reversed(getattr(copilot_ctx, "recorded_build_test_outcome_history", [])):
if entry.get("workflow_run_id") == unresolved.workflow_run_id:
failure_kind = _safe_reason_code(entry.get("reason_code"))
break
@@ -4439,7 +4458,7 @@ def _safe_reason_code(value: object) -> str:
async def _verify_and_record_run_blocks_result(
copilot_ctx: Any, result: dict[str, Any], _handler_start: float
-) -> RecordedRunOutcome | None:
+) -> RecordedBuildTestOutcome | None:
"""Record and emit the run fact once; no authoring judge may rewrite it."""
await _resolve_captcha_solver_availability(copilot_ctx)
recorded = _record_run_blocks_result(copilot_ctx, result, completion_verification=None)
@@ -4455,7 +4474,12 @@ async def _verify_and_record_run_blocks_result(
reason_code=recorded.reason_code,
display_reason=recorded.display_reason,
)
- return recorded
+ build_test_outcome = getattr(copilot_ctx, "latest_recorded_build_test_outcome", None)
+ result_data = result.get("data")
+ result_run_id = result_data.get("workflow_run_id") if isinstance(result_data, dict) else None
+ if isinstance(build_test_outcome, RecordedBuildTestOutcome) and build_test_outcome.workflow_run_id == result_run_id:
+ return build_test_outcome
+ return None
def _record_diagnosis_repair_contract(
@@ -4750,7 +4774,8 @@ def _packet_unfinished_items(
recorded_outcome: RecordedBuildTestOutcome | None,
omission_notices: list[str],
) -> list[BuildTestPacketUnfinishedItem]:
- outcome = recorded_outcome or copilot_ctx.latest_recorded_build_test_outcome
+ latest_outcome = getattr(copilot_ctx, "latest_recorded_build_test_outcome", None)
+ outcome = recorded_outcome or (latest_outcome if isinstance(latest_outcome, RecordedBuildTestOutcome) else None)
if run_id is None:
if copilot_ctx.last_unverified_block_labels or outcome is not None:
omission_notices.append("unfinished_items omitted: recorded unfinished evidence is not bound to this run.")
@@ -4825,6 +4850,30 @@ def build_test_evidence_packet(
page_capture = recorded_outcome.page_capture
failure: BuildTestPacketFailure | None = None
if failed_block is not None or result.get("ok") is False:
+ if recorded_outcome is not None and recorded_outcome.workflow_run_id == run_id:
+ failed_operation = recorded_outcome.failed_operation
+ if failed_operation is not None and failed_operation.workflow_run_id != run_id:
+ failed_operation = None
+ else:
+ failed_operation = failed_operation_from_run_blocks_result(result)
+ if failed_operation is not None:
+ if failed_operation.workflow_run_id is None:
+ omission_notices.append(
+ "failure.failed_operation.workflow_run_id omitted: no run identity was recorded for the operation."
+ )
+ if failed_operation.workflow_run_block_id is None:
+ omission_notices.append(
+ "failure.failed_operation.workflow_run_block_id omitted: no run-block identity was recorded for "
+ "the operation."
+ )
+ if failed_operation.block_label is None:
+ omission_notices.append(
+ "failure.failed_operation.block_label omitted: no block label was recorded for the operation."
+ )
+ if failed_operation.failing_line is None:
+ omission_notices.append(
+ "failure.failed_operation.failing_line omitted: no failing code line was recorded for the operation."
+ )
failure = BuildTestPacketFailure(
workflow_run_block_id=(
_packet_string(failed_block.get("workflow_run_block_id")) if failed_block is not None else None
@@ -4841,6 +4890,7 @@ def build_test_evidence_packet(
),
error_codes=(_packet_string_list(failed_block.get("error_codes")) if failed_block is not None else []),
failing_line=data.get("failing_code_line") if type(data.get("failing_code_line")) is int else None,
+ failed_operation=failed_operation,
action_trace=action_trace,
page_state=page_state,
locator_observations=_packet_locator_observations(data, omission_notices),
@@ -4933,6 +4983,11 @@ def finalize_build_test_result(
recorded_outcome: RecordedBuildTestOutcome | None = None,
) -> dict[str, Any]:
"""Finalize diagnosis state and attach the one shared factual packet."""
+ # Tool seams sometimes deliberately suppress collection and return no recorded outcome.
+ # Treat any non-record as absent rather than allowing a test double or failed observer to
+ # contaminate the model-facing packet.
+ if not isinstance(recorded_outcome, RecordedBuildTestOutcome):
+ recorded_outcome = None
if diagnosis_shadow_eligible:
_record_diagnosis_repair_contract(
copilot_ctx,
diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.py
index 55d579ea7..de687113a 100644
--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py
+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py
@@ -109,6 +109,7 @@ from skyvern.forge.sdk.copilot.workflow_yaml import (
_process_workflow_yaml,
reconcile_workflow_completion_contract,
redact_credentials_in_workflow_yaml,
+ runner_code_block_associations,
)
from skyvern.forge.sdk.services import google_oauth_service
from skyvern.forge.sdk.workflow.exceptions import BaseWorkflowHTTPException, InsecureCodeDetected
@@ -4094,6 +4095,11 @@ async def _update_workflow(
ctx.has_staged_proposal = True
ctx.workflow_yaml = workflow_yaml
if isinstance(ctx, CopilotContext):
+ ctx.runner_code_block_associations_by_label = runner_code_block_associations(
+ workflow_yaml,
+ prior_associations=ctx.runner_code_block_associations_by_label,
+ preserve_existing=params.get("_preserve_code_block_associations") is True,
+ )
current_google_connection_bindings = google_sheet_connection_bindings(workflow)
turn_start_workflow = prior_workflow
if ctx.google_connection_turn_start_bindings is None:
diff --git a/skyvern/forge/sdk/copilot/workflow_yaml.py b/skyvern/forge/sdk/copilot/workflow_yaml.py
index 2ec7f5f1b..c2a932e09 100644
--- a/skyvern/forge/sdk/copilot/workflow_yaml.py
+++ b/skyvern/forge/sdk/copilot/workflow_yaml.py
@@ -3,6 +3,7 @@
from collections.abc import Collection
from datetime import datetime, timezone
from typing import Any
+from uuid import uuid4
import structlog
import yaml
@@ -37,6 +38,50 @@ LOG = structlog.get_logger()
_YAML_NO_FOLD_WIDTH = 1 << 30
+def runner_code_block_associations(
+ workflow_yaml: str,
+ *,
+ prior_associations: dict[str, str] | None = None,
+ preserve_existing: bool = False,
+) -> dict[str, str]:
+ """Assign opaque server-owned identities to code blocks without changing model-owned YAML.
+
+ A server-composed block edit can explicitly retain a label's prior identity. A complete model
+ replacement always receives fresh identities, even if it reproduces a prior label or source.
+ """
+ try:
+ parsed = safe_load_no_dates(workflow_yaml)
+ except yaml.YAMLError:
+ return {}
+ blocks = _workflow_blocks(parsed)
+ if blocks is None:
+ return {}
+ associations: dict[str, str] = {}
+ prior_associations = prior_associations or {}
+
+ def walk(value: object) -> None:
+ if not isinstance(value, list):
+ return
+ for block in value:
+ if not isinstance(block, dict):
+ continue
+ label = block.get("label")
+ if block.get("block_type") == "code" and isinstance(label, str) and label:
+ associations[label] = (
+ prior_associations[label]
+ if preserve_existing and label in prior_associations
+ else f"cba_{uuid4().hex}"
+ )
+ walk(block.get("blocks"))
+ walk(block.get("loop_blocks"))
+ for branch in block.get("branch_conditions", []):
+ if isinstance(branch, dict):
+ walk(branch.get("blocks"))
+
+ walk(blocks)
+ return associations
+
+
def reconcile_workflow_completion_contract(
workflow_yaml: str,
contract: dict[str, object] | None,
diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.py
index 5d28cb5b5..8b7cf24b8 100644
--- a/skyvern/forge/sdk/routes/workflow_copilot.py
+++ b/skyvern/forge/sdk/routes/workflow_copilot.py
@@ -439,7 +439,15 @@ def _effective_auto_accept(auto_accept: bool | None, agent_result: object | None
build never commits on the user's behalf; it lands as a pending proposal for
the review gate.
"""
- if getattr(agent_result, "cancelled", False) is True or _proposal_disposition(agent_result) != "auto_applicable":
+ terminal_envelope = getattr(agent_result, "terminal_envelope", None)
+ unresolved_failed_operation = (
+ isinstance(terminal_envelope, dict) and terminal_envelope.get("failed_operation") is not None
+ )
+ if (
+ getattr(agent_result, "cancelled", False) is True
+ or unresolved_failed_operation
+ or _proposal_disposition(agent_result) != "auto_applicable"
+ ):
return False
return auto_accept is True
diff --git a/tests/unit/test_copilot_build_test_outcome.py b/tests/unit/test_copilot_build_test_outcome.py
index 40fdc1668..5907da36d 100644
--- a/tests/unit/test_copilot_build_test_outcome.py
+++ b/tests/unit/test_copilot_build_test_outcome.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import copy
import json
from datetime import UTC, datetime
from types import SimpleNamespace
@@ -9,9 +10,16 @@ import pytest
from pydantic import ValidationError
from skyvern.forge.sdk.artifact.models import ArtifactType
-from skyvern.forge.sdk.copilot.agent import _build_dynamic_system_prompt, _build_user_context, _prior_run_debug_text
+from skyvern.forge.sdk.copilot import tools as tools_module
+from skyvern.forge.sdk.copilot.agent import (
+ _build_dynamic_system_prompt,
+ _build_user_context,
+ _prior_run_debug_text,
+ _recorded_build_test_outcome_prompt,
+)
from skyvern.forge.sdk.copilot.build_test_outcome import (
BuildTestEvidencePacket,
+ BuildTestFailedOperation,
BuildTestPacketDownload,
BuildTestPacketFailure,
BuildTestPacketLocatorObservation,
@@ -36,6 +44,7 @@ from skyvern.forge.sdk.copilot.failure_tracking import selector_identity_from_fa
from skyvern.forge.sdk.copilot.output_utils import project_build_test_packet_for_llm
from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome
from skyvern.forge.sdk.copilot.runtime_authoring_repair import inject_runtime_authoring_repair_context
+from skyvern.forge.sdk.copilot.secret_scrub import clear_session_scrub_values, register_secret_scrub_value
from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module
from skyvern.forge.sdk.copilot.tools.composition_capture import store_post_run_page_evidence
from skyvern.forge.sdk.copilot.tools.run_execution import (
@@ -47,6 +56,7 @@ from skyvern.forge.sdk.copilot.tools.run_execution import (
_recorded_run_block_result,
build_test_evidence_packet,
)
+from skyvern.forge.sdk.copilot.workflow_yaml import runner_code_block_associations
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter
from tests.unit.copilot_test_helpers import (
failed_second_factor_run,
@@ -2398,6 +2408,803 @@ def test_the_runners_typed_error_and_failing_line_reach_the_repair_turn() -> Non
assert packet.failure.failing_line == 6
+def test_browser_operation_failure_projects_same_row_run_and_block_identity() -> None:
+ result = _failed_run_result(None)
+ data = result["data"]
+ assert isinstance(data, dict)
+ data["workflow_run_id"] = "wr_browser_operation"
+ data["blocks"] = [
+ {
+ "workflow_run_block_id": "wrb_capture_failure",
+ "label": "collect_failure_rate",
+ "status": "failed",
+ "failure_reason": "browser operation failed",
+ "error_codes": ["browser_operation_failed"],
+ }
+ ]
+ data["failing_code_line"] = 11
+
+ outcome = recorded_outcome_from_run_blocks_result(result)
+ packet = build_test_evidence_packet(_locator_packet_ctx(), result, recorded_outcome=outcome)
+
+ assert outcome is not None
+ assert outcome.failed_operation is not None
+ assert outcome.failed_operation.model_dump() == {
+ "kind": "browser_operation_failed",
+ "workflow_run_id": "wr_browser_operation",
+ "workflow_run_block_id": "wrb_capture_failure",
+ "block_label": "collect_failure_rate",
+ "failing_line": 11,
+ }
+ assert packet.failure is not None
+ assert packet.failure.failed_operation == outcome.failed_operation
+ projected = project_build_test_packet_for_llm(packet)
+ assert projected.failure is not None
+ assert projected.failure.failed_operation == outcome.failed_operation
+
+
+def test_browser_operation_packet_uses_same_run_recorded_outcome_as_its_authority() -> None:
+ result = _failed_run_result(None)
+ data = result["data"]
+ assert isinstance(data, dict)
+ data["workflow_run_id"] = "wr_recorded_authority"
+ data["blocks"] = [
+ {
+ "workflow_run_block_id": "wrb_recorded_authority",
+ "label": "collect_failure_rate",
+ "status": "failed",
+ "error_codes": ["browser_operation_failed"],
+ }
+ ]
+ outcome = recorded_outcome_from_run_blocks_result(result)
+ assert outcome is not None
+ assert outcome.failed_operation is not None
+
+ blocks = data["blocks"]
+ assert isinstance(blocks, list)
+ assert isinstance(blocks[0], dict)
+ blocks[0]["workflow_run_block_id"] = "wrb_raw_result_changed_after_recording"
+ packet = build_test_evidence_packet(_locator_packet_ctx(), result, recorded_outcome=outcome)
+
+ assert packet.failure is not None
+ assert packet.failure.failed_operation == outcome.failed_operation
+ assert packet.failure.failed_operation.workflow_run_block_id == "wrb_recorded_authority"
+
+
+def test_browser_operation_producer_redacts_registered_block_label_secret() -> None:
+ session_id = "pbs_build_test_operation_redaction"
+ secret = "build-test-label-secret-value"
+ ctx = SimpleNamespace(browser_session_id=session_id, secret_scrub_values=[])
+ register_secret_scrub_value(ctx, secret)
+ try:
+ result = _failed_run_result(None)
+ data = result["data"]
+ assert isinstance(data, dict)
+ data["blocks"] = [
+ {
+ "label": f"collect_{secret}_rate",
+ "status": "failed",
+ "error_codes": ["browser_operation_failed"],
+ }
+ ]
+ outcome = recorded_outcome_from_run_blocks_result(result)
+ finally:
+ clear_session_scrub_values(session_id)
+
+ assert outcome is not None
+ assert outcome.failed_operation is not None
+ assert secret not in outcome.model_dump_json()
+ assert outcome.failed_operation.block_label == "collect_[REDACTED_SECRET]_rate"
+
+
+def test_browser_operation_structural_key_ignores_transient_run_and_block_ids() -> None:
+ first = _failed_run_result(None)
+ first_data = first["data"]
+ assert isinstance(first_data, dict)
+ first_data["workflow_run_id"] = "wr_first"
+ first_data["blocks"] = [
+ {
+ "workflow_run_block_id": "wrb_first",
+ "label": "collect_failure_rate",
+ "status": "failed",
+ "error_codes": ["browser_operation_failed"],
+ }
+ ]
+ first_data["failing_code_line"] = 11
+ second = copy.deepcopy(first)
+ second_data = second["data"]
+ assert isinstance(second_data, dict)
+ second_data["workflow_run_id"] = "wr_second"
+ blocks = second_data["blocks"]
+ assert isinstance(blocks, list)
+ assert isinstance(blocks[0], dict)
+ blocks[0]["workflow_run_block_id"] = "wrb_second"
+
+ first_outcome = recorded_outcome_from_run_blocks_result(first)
+ second_outcome = recorded_outcome_from_run_blocks_result(second)
+
+ assert first_outcome is not None
+ assert second_outcome is not None
+ assert first_outcome.failed_operation is not None
+ assert second_outcome.failed_operation is not None
+ assert first_outcome.failed_operation.workflow_run_id != second_outcome.failed_operation.workflow_run_id
+ assert first_outcome.structural_key == second_outcome.structural_key
+
+
+def test_browser_operation_failure_survives_non_clearing_outcomes_until_changed_attempt_is_tested() -> None:
+ failed_workflow = """title: retain browser failure
+workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: collect_failure_rate
+ code: |
+ return {"failure_rate": await page.locator("canvas.failure-rate").inner_text()}
+"""
+ repaired_workflow = failed_workflow.replace("canvas.failure-rate", "[data-testid='failure-rate']")
+ ctx = _locator_packet_ctx()
+ ctx.workflow_yaml = failed_workflow
+ ctx.persisted_workflow_yaml = failed_workflow
+ ctx.runner_code_block_associations_by_label = {"collect_failure_rate": "cba_collect_failure_rate"}
+ failed_operation = BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ workflow_run_id="wr_failed",
+ workflow_run_block_id="wrb_failed",
+ block_label="collect_failure_rate",
+ failing_line=1,
+ block_association="cba_collect_failure_rate",
+ )
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ attempted_tool="update_and_run_blocks",
+ verdict="repairable_failure",
+ reason_code="runtime_block_failure",
+ workflow_run_id="wr_failed",
+ block_labels=["collect_failure_rate"],
+ requested_block_labels=["collect_failure_rate"],
+ structural_failure_identity="browser-operation",
+ failed_operation=failed_operation,
+ ),
+ )
+
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="scout_evaluate",
+ attempted_tool="inspect_page_for_composition",
+ verdict="progress_observed",
+ reason_code="verified_success",
+ ),
+ )
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.failed_operation == failed_operation
+
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ attempted_tool="update_and_run_blocks",
+ verdict="progress_observed",
+ reason_code="verified_success",
+ workflow_run_id="wr_unchanged",
+ block_labels=["collect_failure_rate"],
+ requested_block_labels=["collect_failure_rate"],
+ verified_progress_marker="run-completed",
+ ),
+ )
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.failed_operation == failed_operation
+
+ ctx.workflow_yaml = repaired_workflow
+ ctx.persisted_workflow_yaml = repaired_workflow
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ attempted_tool="update_and_run_blocks",
+ verdict="progress_observed",
+ reason_code="verified_success",
+ workflow_run_id="wr_changed_but_not_executed",
+ block_labels=["collect_failure_rate"],
+ requested_block_labels=["collect_failure_rate"],
+ executed_block_labels=[],
+ verified_progress_marker="run-completed",
+ ),
+ )
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.failed_operation == failed_operation
+
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ attempted_tool="update_and_run_blocks",
+ verdict="progress_observed",
+ reason_code="verified_success",
+ workflow_run_id="wr_changed_and_tested",
+ block_labels=["collect_failure_rate"],
+ requested_block_labels=["collect_failure_rate"],
+ executed_block_labels=["collect_failure_rate"],
+ executed_block_associations=("cba_collect_failure_rate",),
+ verified_progress_marker="run-completed",
+ ),
+ )
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.failed_operation is None
+
+
+def test_existing_workflow_failure_and_retest_use_the_exact_unmasked_staged_snapshots() -> None:
+ turn_start_workflow = """workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: collect_failure_rate
+ code: |
+ return await page.locator("[data-testid='turn-start']").inner_text()
+"""
+ failed_snapshot = turn_start_workflow.replace("[data-testid='turn-start']", "canvas.failure-rate")
+ repaired_snapshot = turn_start_workflow.replace("[data-testid='turn-start']", "[data-testid='failure-rate']")
+ ctx = _locator_packet_ctx()
+ ctx.persisted_workflow_yaml = turn_start_workflow
+ ctx.workflow_yaml = failed_snapshot
+ ctx.staged_workflow_yaml = failed_snapshot
+ ctx.runner_code_block_associations_by_label = {"collect_failure_rate": "cba_collect_failure_rate"}
+ failed_operation = BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ workflow_run_id="wr_failed",
+ block_label="collect_failure_rate",
+ failing_line=1,
+ block_association="cba_collect_failure_rate",
+ )
+
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ verdict="repairable_failure",
+ reason_code="runtime_block_failure",
+ workflow_run_id="wr_failed",
+ structural_failure_identity="browser-operation",
+ failed_operation=failed_operation,
+ ),
+ )
+ ctx.workflow_yaml = repaired_snapshot
+ ctx.staged_workflow_yaml = repaired_snapshot
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ verdict="progress_observed",
+ reason_code="verified_success",
+ workflow_run_id="wr_retested",
+ executed_block_labels=["collect_failure_rate"],
+ executed_block_associations=("cba_collect_failure_rate",),
+ verified_progress_marker="run-completed",
+ ),
+ )
+
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.failed_operation is None
+
+
+def test_verified_retest_clears_a_changed_outer_browser_operation_not_its_nested_locator() -> None:
+ failed_workflow = """workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: submit
+ code: |
+ await page.locator("#submit").click(timeout=1000)
+"""
+ ctx = _locator_packet_ctx()
+ ctx.workflow_yaml = failed_workflow
+ ctx.persisted_workflow_yaml = failed_workflow
+ ctx.runner_code_block_associations_by_label = {"submit": "cba_submit"}
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ verdict="repairable_failure",
+ reason_code="runtime_block_failure",
+ workflow_run_id="wr_failed",
+ structural_failure_identity="browser-operation",
+ failed_operation=BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ workflow_run_id="wr_failed",
+ block_label="submit",
+ failing_line=1,
+ block_association="cba_submit",
+ ),
+ ),
+ )
+ ctx.workflow_yaml = failed_workflow.replace("timeout=1000", "timeout=5000")
+ ctx.persisted_workflow_yaml = ctx.workflow_yaml
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ verdict="progress_observed",
+ reason_code="verified_success",
+ workflow_run_id="wr_retested",
+ executed_block_associations=("cba_submit",),
+ verified_progress_marker="run-completed",
+ ),
+ )
+
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.failed_operation is None
+
+
+def test_browser_operation_failure_is_not_cleared_when_full_replacement_copies_its_old_association() -> None:
+ failed_workflow = """workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: collect_failure_rate
+ copilot_block_association: cba_original
+ code: |
+ return await page.locator("canvas.failure-rate").inner_text()
+ - block_type: code
+ label: summarize
+ code: |
+ return {"summary": "ready"}
+"""
+ replacement_workflow = """workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: summarize
+ code: |
+ return {"summary": "ready"}
+ - block_type: code
+ label: collect_failure_rate
+ copilot_block_association: cba_original
+ code: |
+ return {"unrelated": "replacement"}
+"""
+ ctx = _locator_packet_ctx()
+ ctx.workflow_yaml = failed_workflow
+ ctx.staged_workflow_yaml = failed_workflow
+ ctx.runner_code_block_associations_by_label = {"collect_failure_rate": "cba_original"}
+ failed_operation = BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ workflow_run_id="wr_failed",
+ block_label="collect_failure_rate",
+ failing_line=1,
+ block_association="cba_original",
+ )
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ verdict="repairable_failure",
+ reason_code="runtime_block_failure",
+ workflow_run_id="wr_failed",
+ structural_failure_identity="browser-operation",
+ failed_operation=failed_operation,
+ ),
+ )
+
+ ctx.workflow_yaml = replacement_workflow
+ ctx.staged_workflow_yaml = replacement_workflow
+ ctx.runner_code_block_associations_by_label = runner_code_block_associations(
+ replacement_workflow,
+ prior_associations=ctx.runner_code_block_associations_by_label,
+ preserve_existing=False,
+ )
+ replacement_association = ctx.runner_code_block_associations_by_label["collect_failure_rate"]
+ assert replacement_association != "cba_original"
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ verdict="progress_observed",
+ reason_code="verified_success",
+ workflow_run_id="wr_replacement",
+ executed_block_labels=["collect_failure_rate"],
+ executed_block_associations=(replacement_association,),
+ verified_progress_marker="run-completed",
+ ),
+ )
+
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.failed_operation == failed_operation
+
+
+def test_code_block_association_covers_conditional_blocks_without_entering_packet_projection() -> None:
+ workflow_yaml = """workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: conditional
+ label: inspect_state
+ branch_conditions:
+ - condition: "True"
+ blocks:
+ - block_type: code
+ label: read_failure_rate
+ code: |
+ return await page.locator("canvas.failure-rate").inner_text()
+"""
+ associations = runner_code_block_associations(workflow_yaml)
+
+ assert set(associations) == {"read_failure_rate"}
+ assert "copilot_block_association" not in workflow_yaml
+ outcome = recorded_outcome_from_run_blocks_result(
+ {
+ "ok": False,
+ "data": {
+ "workflow_run_id": "wr_conditional_failure",
+ "overall_status": "failed",
+ "failing_code_line": 1,
+ "blocks": [
+ {
+ "label": "read_failure_rate",
+ "status": "failed",
+ "error_codes": ["browser_operation_failed"],
+ }
+ ],
+ },
+ },
+ block_associations_by_label=associations,
+ )
+
+ assert outcome is not None
+ assert outcome.failed_operation is not None
+ assert outcome.failed_operation.block_association == associations["read_failure_rate"]
+ assert "copilot_block_association" not in outcome.model_dump_json()
+
+
+def test_recorded_outcome_execution_receipts_come_from_block_status_not_requested_labels() -> None:
+ result = {
+ "ok": False,
+ "data": {
+ "workflow_run_id": "wr_receipts",
+ "overall_status": "failed",
+ "requested_block_labels": ["requested_only", "executed"],
+ "executed_block_labels": ["requested_only", "executed"],
+ "blocks": [
+ {"label": "requested_only", "status": "skipped"},
+ {
+ "label": "executed",
+ "status": "failed",
+ "failure_reason": "browser operation failed",
+ "error_codes": ["browser_operation_failed"],
+ },
+ ],
+ },
+ }
+
+ outcome = recorded_outcome_from_run_blocks_result(result)
+
+ assert outcome is not None
+ assert outcome.requested_block_labels == ["requested_only", "executed"]
+ assert outcome.executed_block_labels == ["executed"]
+
+
+def test_browser_operation_failure_is_not_cleared_by_unrelated_edit_in_executed_block() -> None:
+ failed_workflow = """title: retain browser failure
+workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: collect_failure_rate
+ copilot_block_association: cba_collect_failure_rate
+ code: |
+ value = await page.locator("canvas.failure-rate").inner_text()
+ return {"failure_rate": value}
+"""
+ ctx = _locator_packet_ctx()
+ ctx.workflow_yaml = failed_workflow
+ ctx.persisted_workflow_yaml = failed_workflow
+ failed_operation = BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ workflow_run_id="wr_failed",
+ block_label="collect_failure_rate",
+ failing_line=1,
+ )
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ verdict="repairable_failure",
+ reason_code="runtime_block_failure",
+ workflow_run_id="wr_failed",
+ structural_failure_identity="browser-operation",
+ failed_operation=failed_operation,
+ ),
+ )
+
+ unrelated_edit = failed_workflow.replace(
+ 'return {"failure_rate": value}',
+ 'return {"failure_rate": value, "note": "unchanged locator"}',
+ )
+ ctx.workflow_yaml = unrelated_edit
+ ctx.persisted_workflow_yaml = unrelated_edit
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ verdict="progress_observed",
+ reason_code="verified_success",
+ workflow_run_id="wr_unrelated_edit",
+ requested_block_labels=["collect_failure_rate"],
+ executed_block_labels=["collect_failure_rate"],
+ verified_progress_marker="run-completed",
+ ),
+ )
+
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.failed_operation == failed_operation
+
+
+def test_browser_operation_failure_is_not_cleared_by_an_untested_persisted_edit() -> None:
+ failed_workflow = """title: retain browser failure
+workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: collect_failure_rate
+ code: |
+ return {"failure_rate": await page.locator("canvas.failure-rate").inner_text()}
+"""
+ ctx = _locator_packet_ctx()
+ ctx.workflow_yaml = failed_workflow
+ ctx.persisted_workflow_yaml = failed_workflow
+ failed_operation = BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ workflow_run_id="wr_failed",
+ block_label="collect_failure_rate",
+ failing_line=1,
+ )
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ attempted_tool="update_and_run_blocks",
+ verdict="repairable_failure",
+ reason_code="runtime_block_failure",
+ workflow_run_id="wr_failed",
+ requested_block_labels=["collect_failure_rate"],
+ structural_failure_identity="browser-operation",
+ failed_operation=failed_operation,
+ ),
+ )
+
+ ctx.workflow_yaml = failed_workflow.replace("canvas.failure-rate", "[data-testid='failure-rate']")
+ ctx.persisted_workflow_yaml = ctx.workflow_yaml
+ record_build_test_outcome(ctx, None)
+
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.failed_operation == failed_operation
+
+
+async def test_browser_operation_outcome_clears_after_server_composed_verified_retest(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ failed_workflow = """title: read the failure rate
+workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: collect_failure_rate
+ copilot_block_association: cba_collect_failure_rate
+ code: |
+ value = await page.locator("canvas.failure-rate").inner_text()
+ return {"failure_rate": value}
+"""
+ repaired_workflow = failed_workflow.replace(
+ 'page.locator("canvas.failure-rate")',
+ "page.locator(\"[data-testid='failure-rate']\")",
+ )
+ ctx = _locator_packet_ctx()
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.workflow_yaml = failed_workflow
+ ctx.persisted_workflow_yaml = failed_workflow
+ ctx.runner_code_block_associations_by_label = {"collect_failure_rate": "cba_collect_failure_rate"}
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ attempted_tool="update_and_run_blocks",
+ verdict="repairable_failure",
+ reason_code="runtime_block_failure",
+ workflow_run_id="wr_browser_operation",
+ block_labels=["collect_failure_rate"],
+ structural_failure_identity="browser-operation",
+ failed_operation=BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ workflow_run_id="wr_browser_operation",
+ workflow_run_block_id="wrb_browser_operation",
+ block_label="collect_failure_rate",
+ failing_line=1,
+ block_association="cba_collect_failure_rate",
+ ),
+ ),
+ )
+
+ prompt = _recorded_build_test_outcome_prompt(ctx)
+ persisted_attempts = [failed_workflow]
+ tested_attempts: list[str] = []
+
+ async def persist_workflow(
+ payload: dict[str, object], copilot_ctx: CopilotContext, **_kwargs: object
+ ) -> dict[str, object]:
+ candidate = payload["workflow_yaml"]
+ assert isinstance(candidate, str)
+ assert payload["_preserve_code_block_associations"] is True
+ persisted_attempts.append(candidate)
+ copilot_ctx.workflow_yaml = candidate
+ copilot_ctx.persisted_workflow_yaml = candidate
+ code = candidate.split("code: |", 1)[1]
+ workflow = SimpleNamespace(
+ proxy_location=None,
+ workflow_definition=SimpleNamespace(
+ blocks=[
+ SimpleNamespace(
+ label="collect_failure_rate",
+ block_type=SimpleNamespace(value="code"),
+ code=code,
+ )
+ ]
+ ),
+ )
+ return {"ok": True, "data": {"block_count": 1}, "_workflow": workflow}
+
+ async def test_persisted_workflow(
+ _params: dict[str, object], copilot_ctx: CopilotContext, **_kwargs: object
+ ) -> dict[str, object]:
+ persisted = copilot_ctx.persisted_workflow_yaml
+ assert isinstance(persisted, str)
+ tested_attempts.append(persisted)
+ repaired_selector_present = "[data-testid='failure-rate']" in persisted
+ return {
+ "ok": repaired_selector_present,
+ "data": {
+ "workflow_run_id": "wr_retested_repair",
+ "overall_status": "completed" if repaired_selector_present else "failed",
+ "requested_block_labels": ["collect_failure_rate"],
+ "executed_block_labels": ["collect_failure_rate"],
+ "blocks": [
+ {
+ "label": "collect_failure_rate",
+ "status": "completed" if repaired_selector_present else "failed",
+ "extracted_data": {"failure_rate": "16.67%"} if repaired_selector_present else None,
+ }
+ ],
+ },
+ }
+
+ async def observe_test_result(
+ copilot_ctx: CopilotContext, result: dict[str, object], _handler_start: float
+ ) -> object:
+ record_build_test_outcome(
+ copilot_ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ attempted_tool="edit_block_and_run",
+ verdict="progress_observed",
+ reason_code="verified_success",
+ workflow_run_id="wr_retested_repair",
+ executed_block_associations=("cba_collect_failure_rate",),
+ verified_progress_marker="run-completed",
+ ),
+ )
+ return copilot_ctx.latest_recorded_build_test_outcome
+
+ monkeypatch.setattr(tools_module, "_update_and_run_requires_skipped_run", lambda *args: False)
+ monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *args, **kwargs: None)
+ monkeypatch.setattr(tools_module, "_get_prior_workflow_definition", AsyncMock(return_value=None))
+ monkeypatch.setattr(tools_module, "_frontier_runtime_page_url", AsyncMock(return_value=None))
+ monkeypatch.setattr(
+ tools_module,
+ "_plan_frontier",
+ lambda *args: (["collect_failure_rate"], {}, "collect_failure_rate", "initial"),
+ )
+ monkeypatch.setattr(tools_module, "_update_workflow", persist_workflow)
+ monkeypatch.setattr(tools_module, "_run_blocks_and_collect_debug", test_persisted_workflow)
+ monkeypatch.setattr(tools_module, "_verify_and_record_run_blocks_result", observe_test_result)
+ monkeypatch.setattr(tools_module, "_record_diagnosis_repair_contract", lambda *args, **kwargs: None)
+ monkeypatch.setattr(tools_module, "enqueue_screenshot_from_result", lambda *args, **kwargs: None)
+
+ tool_result = await tools_module.edit_block_and_run_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="edit_block_and_run"),
+ json.dumps(
+ {
+ "label": "collect_failure_rate",
+ "expected_code": 'value = await page.locator("canvas.failure-rate").inner_text()\nreturn {"failure_rate": value}',
+ "replacement_code": (
+ "value = await page.locator(\"[data-testid='failure-rate']\").inner_text()\n"
+ 'return {"failure_rate": value}'
+ ),
+ "block_labels": ["collect_failure_rate"],
+ "parameters": {},
+ }
+ ),
+ )
+ parsed_result = json.loads(tool_result)
+
+ assert "browser_operation_failed" in prompt
+ assert "wrb_browser_operation" in prompt
+ assert "collect_failure_rate" in prompt
+ assert "failing_line=1" in prompt
+ assert persisted_attempts == [failed_workflow, repaired_workflow]
+ assert "canvas.failure-rate" in persisted_attempts[0]
+ assert "canvas.failure-rate" not in persisted_attempts[1]
+ assert tested_attempts == [repaired_workflow]
+ assert parsed_result["ok"] is True
+ assert parsed_result["data"]["workflow_run_id"] == "wr_retested_repair"
+ assert parsed_result["data"]["build_test_packet"]["run"] == {
+ "workflow_run_id": "wr_retested_repair",
+ "status": "completed",
+ }
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.workflow_run_id == "wr_retested_repair"
+ assert ctx.latest_recorded_build_test_outcome.failed_operation is None
+
+
+def test_browser_operation_identity_is_bounded_by_the_shared_packet_projection() -> None:
+ long_identity = "x" * 200
+ result = _failed_run_result(None)
+ data = result["data"]
+ assert isinstance(data, dict)
+ data["workflow_run_id"] = long_identity
+ data["blocks"] = [
+ {
+ "workflow_run_block_id": long_identity,
+ "label": long_identity,
+ "status": "failed",
+ "error_codes": ["browser_operation_failed"],
+ }
+ ]
+
+ projected = project_build_test_packet_for_llm(build_test_evidence_packet(_locator_packet_ctx(), result))
+
+ assert projected.failure is not None
+ assert projected.failure.failed_operation is not None
+ operation = projected.failure.failed_operation
+ assert len(operation.workflow_run_id or "") == 160
+ assert len(operation.workflow_run_block_id or "") == 160
+ assert len(operation.block_label or "") == 160
+ assert all(
+ value.endswith("...")
+ for value in (operation.workflow_run_id, operation.workflow_run_block_id, operation.block_label)
+ if value
+ )
+ assert any("failure.failed_operation.workflow_run_id shortened" in notice for notice in projected.omission_notices)
+ assert any(
+ "failure.failed_operation.workflow_run_block_id shortened" in notice for notice in projected.omission_notices
+ )
+ assert any("failure.failed_operation.block_label shortened" in notice for notice in projected.omission_notices)
+
+
+def test_browser_operation_packet_names_each_unavailable_operation_identity() -> None:
+ result = _failed_run_result(None)
+ data = result["data"]
+ assert isinstance(data, dict)
+ data.pop("workflow_run_id", None)
+ data["blocks"] = [
+ {
+ "label": None,
+ "status": "failed",
+ "error_codes": ["browser_operation_failed"],
+ }
+ ]
+ data.pop("failing_code_line", None)
+
+ packet = build_test_evidence_packet(_locator_packet_ctx(), result)
+
+ assert packet.failure is not None
+ assert packet.failure.failed_operation is not None
+ notices = packet.omission_notices
+ assert any("failure.failed_operation.workflow_run_id omitted" in notice for notice in notices)
+ assert any("failure.failed_operation.workflow_run_block_id omitted" in notice for notice in notices)
+ assert any("failure.failed_operation.block_label omitted" in notice for notice in notices)
+ assert any("failure.failed_operation.failing_line omitted" in notice for notice in notices)
+
+
def test_a_failure_the_runner_did_not_type_carries_neither_field() -> None:
packet = build_test_evidence_packet(_locator_packet_ctx(), _failed_run_result(None))
diff --git a/tests/unit/test_copilot_frontier.py b/tests/unit/test_copilot_frontier.py
index 6ad619689..d245be041 100644
--- a/tests/unit/test_copilot_frontier.py
+++ b/tests/unit/test_copilot_frontier.py
@@ -22,7 +22,7 @@ from openai.types.responses import Response, ResponseCompletedEvent, ResponseOut
from skyvern.forge.sdk.copilot import agent as agent_module
from skyvern.forge.sdk.copilot import tools
from skyvern.forge.sdk.copilot.agent import _verified_workflow_or_none
-from skyvern.forge.sdk.copilot.build_test_outcome import RecordedBuildTestOutcome
+from skyvern.forge.sdk.copilot.build_test_outcome import BuildTestFailedOperation, RecordedBuildTestOutcome
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy, CopilotConfig
from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.mcp_adapter import SkyvernOverlayMCPServer
@@ -2875,6 +2875,92 @@ async def test_test_end_to_end_runs_every_label_from_a_run_owned_browser(monkeyp
assert captured["provenance"] == "initial"
+async def test_test_end_to_end_preserves_existing_code_block_association(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def _fake_process(**kwargs: Any) -> _FakeWorkflow:
+ return _FakeWorkflow(_wf_def())
+
+ monkeypatch.setattr(run_execution_module, "_process_workflow_yaml", _fake_process)
+
+ ctx = _make_ctx()
+ ctx.runner_code_block_associations_by_label = {"collect_failure_rate": "cba_original"}
+ workflow_yaml = """\
+workflow_definition:
+ blocks:
+ - block_type: code
+ label: collect_failure_rate
+ code: |
+ return {"rate": 0.5}
+"""
+
+ result = await run_workflow_end_to_end(ctx, workflow_yaml)
+
+ assert result == {"ok": False, "error": "This workflow has no blocks to run."}
+ assert ctx.runner_code_block_associations_by_label == {"collect_failure_rate": "cba_original"}
+
+
+async def test_end_to_end_finalization_uses_the_exact_recorded_outcome_after_raw_result_mutation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ definition = _wf_def(("collect_failure_rate", "code", {"code": "return {}"}))
+ recorded_outcome = RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ verdict="repairable_failure",
+ reason_code="runtime_block_failure",
+ workflow_run_id="wr_recorded",
+ structural_failure_identity="browser-operation",
+ failed_operation=BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ workflow_run_id="wr_recorded",
+ workflow_run_block_id="wrb_recorded",
+ block_label="collect_failure_rate",
+ failing_line=1,
+ ),
+ )
+
+ async def _fake_process(**kwargs: Any) -> _FakeWorkflow:
+ return _FakeWorkflow(definition)
+
+ async def _fake_run(*args: Any, **kwargs: Any) -> dict[str, Any]:
+ return {
+ "ok": False,
+ "data": {
+ "workflow_run_id": "wr_recorded",
+ "overall_status": "failed",
+ "requested_block_labels": ["collect_failure_rate"],
+ "executed_block_labels": ["collect_failure_rate"],
+ "blocks": [
+ {
+ "label": "collect_failure_rate",
+ "status": "failed",
+ "workflow_run_block_id": "wrb_recorded",
+ "error_codes": ["browser_operation_failed"],
+ }
+ ],
+ },
+ }
+
+ async def _fake_verify(*args: Any, **kwargs: Any) -> RecordedBuildTestOutcome:
+ return recorded_outcome
+
+ real_finalize = run_execution_module.finalize_build_test_result
+
+ def _mutate_then_finalize(*args: Any, **kwargs: Any) -> dict[str, Any]:
+ result = kwargs["result"]
+ result["data"]["blocks"][0]["workflow_run_block_id"] = "wrb_mutated"
+ return real_finalize(*args, **kwargs)
+
+ monkeypatch.setattr(run_execution_module, "_process_workflow_yaml", _fake_process)
+ monkeypatch.setattr(run_execution_module, "_run_blocks_and_collect_debug", _fake_run)
+ monkeypatch.setattr(run_execution_module, "_verify_and_record_run_blocks_result", _fake_verify)
+ monkeypatch.setattr(run_execution_module, "finalize_build_test_result", _mutate_then_finalize)
+
+ result = await run_workflow_end_to_end(_make_ctx(), "workflow: yaml")
+
+ assert result["data"]["build_test_packet"]["failure"]["failed_operation"]["workflow_run_block_id"] == "wrb_recorded"
+
+
@pytest.mark.asyncio
async def test_test_end_to_end_builds_one_sanitized_paired_handoff(monkeypatch: pytest.MonkeyPatch) -> None:
workflow_yaml = """title: Example test
diff --git a/tests/unit/test_copilot_make_agent_result_backfill.py b/tests/unit/test_copilot_make_agent_result_backfill.py
index 1f16f55d3..79184a9ab 100644
--- a/tests/unit/test_copilot_make_agent_result_backfill.py
+++ b/tests/unit/test_copilot_make_agent_result_backfill.py
@@ -7,9 +7,17 @@ from types import SimpleNamespace
import pytest
-from skyvern.forge.sdk.copilot.agent import _finalize_result_with_blocker_override, _make_agent_result
+from skyvern.forge.sdk.copilot.agent import (
+ _finalize_result_with_blocker_override,
+ _make_agent_result,
+ _terminal_failed_operation,
+)
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal, contains_internal_machinery_leak
-from skyvern.forge.sdk.copilot.build_test_outcome import record_build_test_outcome
+from skyvern.forge.sdk.copilot.build_test_outcome import (
+ BuildTestFailedOperation,
+ RecordedBuildTestOutcome,
+ record_build_test_outcome,
+)
from skyvern.forge.sdk.copilot.context import (
AgentResult,
CopilotContext,
@@ -153,6 +161,138 @@ def test_backfill_tolerates_ctx_none() -> None:
assert result.narrative_payload["responseKind"] == "refuse"
+def test_recorded_browser_operation_failure_overrides_success_prose_but_keeps_draft() -> None:
+ ctx = _ctx()
+ failed_operation = BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ workflow_run_id="wr_browser_operation",
+ workflow_run_block_id="wrb_capture_failure",
+ block_label="collect_failure_rate",
+ failing_line=11,
+ )
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ attempted_tool="update_and_run_blocks",
+ attempted_block_label="collect_failure_rate",
+ verdict="repairable_failure",
+ reason_code="runtime_block_failure",
+ workflow_run_id="wr_browser_operation",
+ block_labels=["collect_failure_rate"],
+ structural_failure_identity="browser-operation",
+ failed_operation=failed_operation,
+ ),
+ )
+ draft = SimpleNamespace(name="untested draft")
+ assert _terminal_failed_operation(ctx) == failed_operation
+
+ result = _result(
+ ctx,
+ user_response="Destination write completed successfully.",
+ updated_workflow=draft,
+ workflow_yaml=two_page_login_yaml(),
+ proposal_disposition="auto_applicable",
+ turn_outcome=_outcome(ResponseKind.BUILD),
+ narrative_payload=_payload(
+ terminalMessage="Destination write completed successfully.",
+ narrativeSummary="Destination write completed successfully.",
+ ),
+ )
+
+ assert result.updated_workflow == draft
+ assert result.proposal_disposition == "review_untested"
+ assert result.terminal_envelope is not None
+ assert result.terminal_envelope["failed_operation"] == failed_operation.model_dump()
+ assert result.terminal_envelope["next_state"] == "stopped"
+ assert "browser operation failed" in result.user_response.lower()
+ assert "write completed" not in result.user_response.lower()
+ assert result.narrative_payload is not None
+ assert result.narrative_payload["terminalMessage"] == result.user_response
+ assert result.narrative_payload["narrativeSummary"] == result.user_response
+ assert result.narrative_payload["turnFacts"]["terminalCause"] == "browser_operation_failed"
+ assert result.narrative_payload["turnFacts"]["ranCleanOnCurrentSource"] is False
+
+
+def test_recorded_browser_operation_failure_survives_later_non_clearing_outcome() -> None:
+ ctx = _ctx()
+ failed_operation = BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ workflow_run_id="wr_browser_operation",
+ workflow_run_block_id="wrb_capture_failure",
+ block_label="collect_failure_rate",
+ failing_line=11,
+ )
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ attempted_tool="update_and_run_blocks",
+ attempted_block_label="collect_failure_rate",
+ verdict="repairable_failure",
+ reason_code="runtime_block_failure",
+ workflow_run_id="wr_browser_operation",
+ requested_block_labels=["collect_failure_rate"],
+ structural_failure_identity="browser-operation",
+ failed_operation=failed_operation,
+ ),
+ )
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="scout_evaluate",
+ attempted_tool="inspect_page_for_composition",
+ verdict="progress_observed",
+ reason_code="verified_success",
+ ),
+ )
+
+ assert _terminal_failed_operation(ctx) == failed_operation
+
+
+def test_recorded_browser_operation_failure_survives_auto_applicable_question_precedence() -> None:
+ ctx = _ctx()
+ failed_operation = BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ workflow_run_id="wr_browser_operation",
+ block_label="collect_failure_rate",
+ failing_line=1,
+ )
+ record_build_test_outcome(
+ ctx,
+ RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ verdict="repairable_failure",
+ reason_code="runtime_block_failure",
+ workflow_run_id="wr_browser_operation",
+ structural_failure_identity="browser-operation",
+ failed_operation=failed_operation,
+ ),
+ )
+
+ result = _result(
+ ctx,
+ response_type="ASK_QUESTION",
+ user_response="The destination write completed. Which account should I use?",
+ proposal_disposition="auto_applicable",
+ turn_outcome=_outcome(ResponseKind.CLARIFY),
+ narrative_payload=_payload(),
+ )
+
+ assert result.terminal_envelope is not None
+ assert result.terminal_envelope["failed_operation"] == failed_operation.model_dump()
+ assert result.terminal_envelope["verified"] is False
+ assert result.terminal_envelope["workflow_applied"] is False
+ assert result.terminal_envelope["next_state"] == "awaiting_user_input"
+ assert result.terminal_envelope["response_kind"] == "question"
+ assert result.proposal_disposition == "no_proposal"
+ assert "browser operation failed" in result.user_response.lower()
+ assert "which account should i use?" in result.user_response.lower()
+ assert result.narrative_payload is not None
+ assert result.narrative_payload["terminalMessage"] == result.user_response
+ assert result.narrative_payload["narrativeSummary"] == result.user_response
+
+
def test_result_carries_exact_model_contract_deletion_to_auto_accept() -> None:
ctx = _ctx()
ctx.clear_persisted_completion_contract = True
diff --git a/tests/unit/test_copilot_run_outcome_event.py b/tests/unit/test_copilot_run_outcome_event.py
index 30e5d59ca..b91ff8972 100644
--- a/tests/unit/test_copilot_run_outcome_event.py
+++ b/tests/unit/test_copilot_run_outcome_event.py
@@ -610,11 +610,77 @@ async def test_missing_run_id_does_not_reuse_prior_run_id() -> None:
def test_both_consumers_route_through_single_producer() -> None:
source = inspect.getsource(copilot_tools)
assert source.count("await _verify_and_record_run_blocks_result(") == 2
+ assert source.count("recorded_outcome = await _verify_and_record_run_blocks_result(") == 2
+ assert source.count("recorded_outcome=recorded_outcome") == 2
assert "_record_run_blocks_result(copilot_ctx, result, completion_verification" not in source
assert "_record_run_blocks_result(copilot_ctx, run_result, completion_verification" not in source
assert "await _maybe_run_completion_verification(copilot_ctx" not in source
+ "result_name",
+ ["result", "run_result"],
+ ids=["run_blocks_tool", "run_updated_workflow_blocks"],
+)
+def test_each_current_run_consumer_passes_the_recorded_outcome_to_finalization(
+ result_name: str,
+) -> None:
+ source = inspect.getsource(copilot_tools)
+ producer = (
+ f"recorded_outcome = await _verify_and_record_run_blocks_result(copilot_ctx, {result_name}, handler_start)"
+ )
+ start = source.index(producer)
+ consumer = source[start : start + 700]
+ assert f"result={result_name}" in consumer
+ assert "recorded_outcome=recorded_outcome" in consumer
+
+
+async def test_same_run_recorded_operation_remains_packet_authority_after_raw_result_mutation() -> None:
+ result = _run_result(
+ [
+ {
+ "label": "collect_failure_rate",
+ "block_type": "CODE",
+ "status": "failed",
+ "workflow_run_block_id": "wrb_recorded",
+ "error_codes": ["browser_operation_failed"],
+ "failure_reason": "browser operation failed",
+ }
+ ],
+ ok=False,
+ )
+ result["data"]["requested_block_labels"] = ["collect_failure_rate"]
+ result["data"]["executed_block_labels"] = ["collect_failure_rate"]
+ result["data"]["failing_code_line"] = 1
+ ctx = _ctx(result["data"]["blocks"])
+ ctx.workflow_yaml = """workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: collect_failure_rate
+ code: |
+ return await page.locator("canvas.failure-rate").inner_text()
+"""
+ ctx.persisted_workflow_yaml = ctx.workflow_yaml
+
+ recorded_outcome = await _verify_and_record_run_blocks_result(ctx, result, time.monotonic())
+ assert recorded_outcome is not None
+ assert recorded_outcome.failed_operation is not None
+ assert recorded_outcome.failed_operation.workflow_run_block_id == "wrb_recorded"
+
+ result["data"]["blocks"][0]["workflow_run_block_id"] = "wrb_mutated"
+ run_execution.finalize_build_test_result(
+ ctx,
+ source_tool="run_blocks_and_collect_debug",
+ result=result,
+ recorded_outcome=recorded_outcome,
+ )
+
+ packet = result["data"]["build_test_packet"]
+ assert packet["failure"]["failed_operation"]["workflow_run_block_id"] == "wrb_recorded"
+
+
def test_display_reason_collapses_whitespace_and_caps_length() -> None:
assert run_outcome_display_reason(" a\n b ") == "a b"
long_text = "x" * 500
diff --git a/tests/unit/test_copilot_terminal_envelope.py b/tests/unit/test_copilot_terminal_envelope.py
index d463f6343..ec91ef968 100644
--- a/tests/unit/test_copilot_terminal_envelope.py
+++ b/tests/unit/test_copilot_terminal_envelope.py
@@ -11,8 +11,10 @@ from skyvern.forge.sdk.copilot import agent as agent_module
from skyvern.forge.sdk.copilot.blocker_signal import (
CopilotToolBlockerSignal,
)
+from skyvern.forge.sdk.copilot.build_test_outcome import BuildTestFailedOperation
from skyvern.forge.sdk.copilot.config import CopilotConfig
from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome
+from skyvern.forge.sdk.copilot.secret_scrub import clear_session_scrub_values, register_secret_scrub_value
from skyvern.forge.sdk.copilot.terminal_envelope import (
MINIMAL_HONEST_STOP,
TerminalOutcomeEnvelope,
@@ -94,6 +96,177 @@ def test_unknown_halt_kind_degrades_to_stopped_never_question() -> None:
assert finalized.next_state == "stopped"
+def test_browser_operation_failure_is_a_typed_unverified_terminal() -> None:
+ failed_operation = BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ workflow_run_id="wr_browser_operation",
+ workflow_run_block_id="wrb_capture_failure",
+ block_label="collect_failure_rate",
+ failing_line=11,
+ )
+
+ envelope = _assemble(
+ verified=True,
+ workflow_applied=True,
+ proposal_disposition="review_untested",
+ failed_operation=failed_operation,
+ proposal_present=True,
+ )
+ message, replaced = render_terminal_message(
+ envelope,
+ "Destination write completed successfully.",
+ cancelled=False,
+ )
+
+ assert envelope.next_state == "stopped"
+ assert envelope.response_kind == "stopped"
+ assert envelope.verified is False
+ assert envelope.workflow_applied is False
+ assert envelope.terminal_cause == "browser_operation_failed"
+ assert envelope.failed_operation == failed_operation
+ finalized = finalize_applied_state(envelope, applied=True, proposal_present=True)
+ assert finalized.workflow_applied is False
+ assert finalized.next_state == "stopped"
+ assert replaced is True
+ assert "browser operation failed" in message.lower()
+ assert "draft" in message.lower()
+ assert "write completed" not in message.lower()
+
+
+def test_browser_operation_failure_without_proposal_does_not_claim_draft_available() -> None:
+ envelope = _assemble(
+ proposal_disposition="no_proposal",
+ failed_operation=BuildTestFailedOperation(kind="browser_operation_failed"),
+ proposal_present=False,
+ )
+
+ message, replaced = render_terminal_message(envelope, "Destination write completed.", cancelled=False)
+
+ assert replaced is True
+ assert "browser operation failed" in message.lower()
+ assert "draft" not in message.lower()
+ assert "requested work was not confirmed" in message.lower()
+
+
+def test_browser_operation_failure_preserves_required_question_precedence() -> None:
+ failed_operation = BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ workflow_run_id="wr_browser_operation",
+ workflow_run_block_id="wrb_capture_failure",
+ )
+
+ envelope = _assemble(
+ response_type="ASK_QUESTION",
+ verified=True,
+ workflow_applied=True,
+ proposal_disposition="auto_applicable",
+ failed_operation=failed_operation,
+ )
+ model_message = "The destination write completed. Which account should I use?"
+ message, replaced = render_terminal_message(envelope, model_message, cancelled=False)
+ finalized = finalize_applied_state(envelope, applied=False)
+
+ assert envelope.user_action_required is True
+ assert envelope.next_state == "awaiting_user_input"
+ assert envelope.response_kind == "question"
+ assert envelope.verified is False
+ assert envelope.workflow_applied is False
+ assert finalized.next_state == "awaiting_user_input"
+ assert finalized.response_kind == "question"
+ assert "browser operation failed" in message.lower()
+ assert "requested work was not confirmed" in message.lower()
+ assert model_message in message
+ assert replaced is True
+
+ rerendered, rerendered_replaced = render_terminal_message(envelope, message, cancelled=False)
+
+ assert rerendered == message
+ assert rerendered_replaced is False
+
+
+def test_hydrated_question_with_failed_operation_normalizes_privileged_flags() -> None:
+ envelope = TerminalOutcomeEnvelope.model_validate(
+ {
+ "next_state": "completed",
+ "verified": True,
+ "workflow_applied": True,
+ "user_action_required": True,
+ "response_kind": "question",
+ "failed_operation": {
+ "kind": "browser_operation_failed",
+ "workflow_run_id": "wr_browser_operation",
+ },
+ }
+ )
+ finalized = finalize_applied_state(envelope, applied=True, proposal_present=True)
+
+ assert envelope.verified is False
+ assert envelope.workflow_applied is False
+ assert finalized.verified is False
+ assert finalized.workflow_applied is False
+ assert finalized.next_state == "awaiting_user_input"
+ assert finalized.response_kind == "question"
+
+
+def test_terminal_operation_serialization_and_logging_redact_registered_block_label_secret() -> None:
+ session_id = "pbs_terminal_operation_redaction"
+ secret = "terminal-label-secret-value"
+ ctx = SimpleNamespace(browser_session_id=session_id, secret_scrub_values=[])
+ register_secret_scrub_value(ctx, secret)
+ try:
+ with structlog.testing.capture_logs() as logs:
+ payload = agent_module._assemble_terminal_envelope_safe(
+ response_type="REPLY",
+ verified=False,
+ workflow_applied=False,
+ proposal_disposition="review_untested",
+ run_outcomes=[],
+ blocker_reason=None,
+ halt_kind=None,
+ attempted=None,
+ workflow_mutated=True,
+ workflow_attempted=True,
+ final_message="I stopped.",
+ failed_operation=BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ block_label=f"collect_{secret}_rate",
+ ),
+ )
+ finally:
+ clear_session_scrub_values(session_id)
+
+ assert payload is not None
+ terminal_log = next(log for log in logs if log["event"] == "copilot_terminal_envelope")
+ assert secret not in str(payload)
+ assert secret not in str(terminal_log)
+ assert payload["failed_operation"]["block_label"] == "collect_[REDACTED_SECRET]_rate"
+
+
+def test_terminal_operation_hydration_redacts_registered_block_label_secret() -> None:
+ session_id = "pbs_terminal_operation_hydration_redaction"
+ secret = "hydrated-label-secret-value"
+ ctx = SimpleNamespace(browser_session_id=session_id, secret_scrub_values=[])
+ register_secret_scrub_value(ctx, secret)
+ try:
+ envelope = TerminalOutcomeEnvelope.model_validate(
+ {
+ "next_state": "stopped",
+ "verified": False,
+ "response_kind": "stopped",
+ "failed_operation": {
+ "kind": "browser_operation_failed",
+ "block_label": f"collect_{secret}_rate",
+ },
+ }
+ )
+ finally:
+ clear_session_scrub_values(session_id)
+
+ assert secret not in envelope.model_dump_json()
+ assert envelope.failed_operation is not None
+ assert envelope.failed_operation.block_label == "collect_[REDACTED_SECRET]_rate"
+
+
def test_anchor_uses_the_latest_final_run_fact() -> None:
envelope = _assemble(
run_outcomes=[
diff --git a/tests/unit/test_workflow_copilot_route.py b/tests/unit/test_workflow_copilot_route.py
index b0202fbd7..5fd2b02e8 100644
--- a/tests/unit/test_workflow_copilot_route.py
+++ b/tests/unit/test_workflow_copilot_route.py
@@ -16,7 +16,8 @@ real database -- all DB / LLM / agent surfaces are patched.
from __future__ import annotations
import contextlib
-from datetime import datetime, timedelta, timezone
+import json
+from datetime import UTC, datetime, timedelta, timezone
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock
@@ -39,6 +40,7 @@ from skyvern.forge.sdk.copilot.terminal_envelope import (
INTERRUPTED_TERMINAL_MESSAGE,
INTERRUPTED_TERMINAL_REASON,
InterruptedTurnFacts,
+ TerminalOutcomeEnvelope,
assemble_terminal_envelope,
)
from skyvern.forge.sdk.copilot.turn_outcome import build_minimal_turn_outcome
@@ -227,6 +229,107 @@ async def test_finalise_normal_turn_finalizes_terminal_envelope_without_auto_acc
assert persisted_payload["terminalEnvelope"]["response_kind"] == "update"
+def test_unresolved_failed_operation_rejects_auto_accept_even_with_auto_applicable_disposition() -> None:
+ agent_result = AgentResult(
+ user_response="Draft available.",
+ updated_workflow=SimpleNamespace(),
+ global_llm_context=None,
+ proposal_disposition="auto_applicable",
+ narrative_payload=_narrative_payload(),
+ terminal_envelope={
+ **_terminal_payload(verified=True, workflow_applied=True),
+ "failed_operation": {
+ "kind": "browser_operation_failed",
+ "workflow_run_id": "wr_failed",
+ },
+ },
+ )
+
+ assert workflow_copilot_route._effective_auto_accept(True, agent_result) is False
+
+
+async def test_review_untested_draft_and_failed_operation_survive_persistence_and_hydration(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ chat = SimpleNamespace(
+ organization_id="org-1",
+ workflow_copilot_chat_id="chat-1",
+ proposed_workflow=None,
+ auto_accept=False,
+ )
+ original_workflow = SimpleNamespace(workflow_id="wf-canonical")
+ updated_workflow = MagicMock()
+ updated_workflow.title = "Untested draft"
+ updated_workflow.model_dump.return_value = {"workflow_id": "wf-draft", "title": "Untested draft"}
+ failed_operation = {
+ "kind": "browser_operation_failed",
+ "workflow_run_id": "wr_browser_operation",
+ "workflow_run_block_id": "wrb_browser_operation",
+ "block_label": "collect_failure_rate",
+ "failing_line": 11,
+ }
+ agent_result = AgentResult(
+ user_response="I stopped after the test failure.",
+ updated_workflow=updated_workflow,
+ global_llm_context=None,
+ response_type="REPLY",
+ proposal_disposition="review_untested",
+ narrative_payload=_narrative_payload(),
+ terminal_envelope={
+ **_terminal_payload(verified=True, workflow_applied=True),
+ "failed_operation": failed_operation,
+ },
+ )
+ _, workflow_params = setup_new_copilot_mocks(monkeypatch, chat, original_workflow, agent_result)
+ stream = MagicMock(send=AsyncMock(return_value=True))
+
+ await workflow_copilot_route._finalise_normal_turn(
+ stream=stream,
+ chat=chat,
+ organization_id="org-1",
+ original_workflow=original_workflow,
+ chat_request=_make_chat_request(),
+ agent_result=agent_result,
+ )
+
+ proposal_write = next(
+ call.kwargs["proposed_workflow"]
+ for call in workflow_params.update_workflow_copilot_chat.await_args_list
+ if call.kwargs.get("proposed_workflow") is not None
+ )
+ hydrated_proposal = json.loads(json.dumps(proposal_write))
+ assert hydrated_proposal["workflow_id"] == "wf-draft"
+ assert hydrated_proposal["_copilot_unvalidated"] is True
+
+ persisted_payload = workflow_params.create_workflow_copilot_chat_message.await_args_list[-1].kwargs[
+ "narrative_payload"
+ ]
+ assert persisted_payload is not None
+ now = datetime.now(UTC)
+ history = convert_to_history_messages(
+ [
+ WorkflowCopilotChatMessage(
+ workflow_copilot_chat_message_id="message-1",
+ workflow_copilot_chat_id="chat-1",
+ sender=WorkflowCopilotChatSender.AI,
+ content="I stopped after the test failure.",
+ narrative_payload=json.loads(json.dumps(persisted_payload)),
+ created_at=now,
+ modified_at=now,
+ )
+ ]
+ )
+ served_payload = history[0].narrative_payload
+ assert served_payload is not None
+ hydrated_envelope = TerminalOutcomeEnvelope.model_validate(served_payload["terminalEnvelope"])
+ assert served_payload["proposalDisposition"] == "review_untested"
+ assert hydrated_envelope.failed_operation is not None
+ assert hydrated_envelope.failed_operation.model_dump(mode="json") == failed_operation
+ assert hydrated_envelope.verified is False
+ assert hydrated_envelope.workflow_applied is False
+
+
@pytest.mark.asyncio
async def test_browser_ablation_timeout_response_preserves_model_terminal_cause_and_activity(
monkeypatch: pytest.MonkeyPatch,
@@ -750,6 +853,71 @@ async def test_finalise_normal_turn_flag_on_stopped_envelope_renders_terminal_te
assert persisted_payload["terminalEnvelope"]["rendered_from_envelope"] is True
+async def test_finalise_normal_turn_failed_operation_question_persists_truthful_text(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION,
+ "should_render_copilot_terminal_from_envelope",
+ AsyncMock(return_value=True),
+ )
+ chat = SimpleNamespace(
+ organization_id="org-1",
+ workflow_copilot_chat_id="chat-1",
+ proposed_workflow=None,
+ auto_accept=False,
+ )
+ model_message = "The destination write completed. Which account should I use?"
+ agent_result = AgentResult(
+ user_response=model_message,
+ updated_workflow=None,
+ global_llm_context=None,
+ response_type="ASK_QUESTION",
+ proposal_disposition="no_proposal",
+ narrative_payload={
+ **_narrative_payload(),
+ "terminalMessage": model_message,
+ "narrativeSummary": model_message,
+ },
+ narrative_summary=model_message,
+ terminal_envelope={
+ **_terminal_payload(verified=False, workflow_applied=False),
+ "user_action_required": True,
+ "response_kind": "question",
+ "next_state": "awaiting_user_input",
+ "failed_operation": {
+ "kind": "browser_operation_failed",
+ "workflow_run_id": "wr_failed",
+ },
+ },
+ )
+ original_workflow = SimpleNamespace(workflow_id="wf-canonical")
+ _, workflow_params = setup_new_copilot_mocks(monkeypatch, chat, original_workflow, agent_result)
+ stream = MagicMock(send=AsyncMock(return_value=True))
+
+ await workflow_copilot_route._finalise_normal_turn(
+ stream=stream,
+ chat=chat,
+ organization_id="org-1",
+ original_workflow=original_workflow,
+ chat_request=_make_chat_request(),
+ agent_result=agent_result,
+ )
+
+ response_frame = stream.send.await_args.args[0]
+ assert "browser operation failed" in response_frame.message.lower()
+ assert "which account should i use?" in response_frame.message.lower()
+ assert response_frame.narrative_summary == response_frame.message
+ assert response_frame.narrative_payload is not None
+ assert response_frame.narrative_payload["terminalMessage"] == response_frame.message
+ assert response_frame.narrative_payload["narrativeSummary"] == response_frame.message
+ persisted = workflow_params.create_workflow_copilot_chat_message.await_args_list[-1].kwargs
+ assert persisted["content"] == response_frame.message
+ assert persisted["narrative_payload"]["terminalMessage"] == response_frame.message
+ assert persisted["narrative_payload"]["narrativeSummary"] == response_frame.message
+
+
@pytest.mark.asyncio
async def test_finalise_normal_turn_keeps_explicit_test_model_response_verbatim_with_envelope_flag(
monkeypatch: pytest.MonkeyPatch,