Skip to content

Automate browser based workflows with AI

fix(SKY-10605): interrupt active runs on terminal evidence (#6390)

Andrew Neilsone7361f26c98d
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.collapse.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.collapse.test.tsx
index a34196a94..09807d5f9 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.collapse.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.collapse.test.tsx
@@ -45,6 +45,8 @@ const inFlightTurn = (): TurnNarrativeState => ({
});
const HEADLINE = "Built and tested the workflow";
+const REVIEW_HEADLINE = "Draft needs review";
+const REVIEW_TESTED_HEADLINE = "Workflow ready for review";
afterEach(() => {
cleanup();
@@ -62,6 +64,43 @@ describe("NarrativeView collapse default", () => {
).toBe("false");
});
+ it("does not present an unverified review proposal as built and tested", () => {
+ render(
+ <NarrativeView
+ turn={{
+ ...terminalBuildTurn(),
+ proposalDisposition: "review_untested",
+ terminalMessage:
+ "I reached the requested browser state, but the reusable workflow still needs a clean verification run before it is ready.",
+ narrativeSummary:
+ "I reached the requested browser state, but the reusable workflow still needs a clean verification run before it is ready.",
+ }}
+ />,
+ );
+
+ expect(screen.getByText(REVIEW_HEADLINE)).toBeTruthy();
+ expect(screen.queryByText(HEADLINE)).toBeNull();
+ });
+
+ it("does not present a tested review proposal with a success badge", () => {
+ render(
+ <NarrativeView
+ turn={{
+ ...terminalBuildTurn(),
+ proposalDisposition: "review_tested",
+ narrativeSummary: "Workflow ready for review.",
+ }}
+ />,
+ );
+
+ const summaryButton = screen.getByRole("button", {
+ name: new RegExp(REVIEW_TESTED_HEADLINE),
+ });
+ expect(summaryButton.textContent).toContain("!");
+ expect(summaryButton.textContent).not.toContain("✓");
+ expect(screen.queryByText(HEADLINE)).toBeNull();
+ });
+
it("keeps the in-flight turn expanded in the detail view", () => {
render(<NarrativeView turn={inFlightTurn()} />);
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
index 1ef76be4e..801f09acd 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
@@ -372,6 +372,14 @@ describe("applyNarrativeEvent — terminal", () => {
expect(s.narrativeSummary).toBe("full text");
});
+ it("captures proposal disposition from response events", () => {
+ const s = applyNarrativeEvent(
+ EMPTY_NARRATIVE,
+ response({ proposal_disposition: "review_untested" }),
+ );
+ expect(s.proposalDisposition).toBe("review_untested");
+ });
+
it("response uses backend error narrative payload when present", () => {
const s = applyNarrativeEvent(
EMPTY_NARRATIVE,
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
index 4f0c72f63..2eadbd767 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
@@ -452,6 +452,10 @@ function computeTurnSummary(turn: TurnNarrativeState): TurnSummary {
mode === "clarify" ||
mode === "refuse";
const hasDrafts = (turn.draft?.blockCount ?? 0) > 0;
+ const needsUntestedProposalReview =
+ hasDrafts && turn.proposalDisposition === "review_untested";
+ const needsTestedProposalReview =
+ hasDrafts && turn.proposalDisposition === "review_tested";
const hasEdited = (turn.priorBlockCount ?? 0) > 0 && hasDrafts;
const hasReviewableDraft =
hasDrafts &&
@@ -466,17 +470,21 @@ function computeTurnSummary(turn: TurnNarrativeState): TurnSummary {
? "Run halted"
: needsInput
? "Question"
- : isQA
- ? mode === "refuse"
- ? "Declined"
- : mode === "clarify"
- ? "Question"
- : "Answered"
- : hasEdited
- ? "Applied edits and re-tested"
- : hasDrafts
- ? "Built and tested the workflow"
- : "Completed the run";
+ : needsUntestedProposalReview
+ ? "Draft needs review"
+ : needsTestedProposalReview
+ ? "Workflow ready for review"
+ : isQA
+ ? mode === "refuse"
+ ? "Declined"
+ : mode === "clarify"
+ ? "Question"
+ : "Answered"
+ : hasEdited
+ ? "Applied edits and re-tested"
+ : hasDrafts
+ ? "Built and tested the workflow"
+ : "Completed the run";
const stats: string[] = [];
const turnElapsed = formatElapsed(turn.startedAt, turn.endedAt);
@@ -494,14 +502,23 @@ function computeTurnSummary(turn: TurnNarrativeState): TurnSummary {
? "qa"
: isFail
? "fail"
- : isQA
+ : needsUntestedProposalReview || needsTestedProposalReview || isQA
? "qa"
: "ok";
return {
headline,
stats,
accent,
- glyph: isStoppedWithDraft ? "!" : isFail ? "✕" : isQA ? "✦" : "✓",
+ glyph:
+ isStoppedWithDraft ||
+ needsUntestedProposalReview ||
+ needsTestedProposalReview
+ ? "!"
+ : isFail
+ ? "✕"
+ : isQA
+ ? "✦"
+ : "✓",
isFail,
isQA,
isStoppedWithDraft,
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
index 4a102bef7..acbe12c2c 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
@@ -81,6 +81,7 @@ export interface TurnNarrativeState {
turnIndex: number | null;
mode: string;
responseType: CopilotResponseType | null;
+ proposalDisposition: ProposalDisposition | null;
designStarted: boolean;
designEnded: boolean;
draft: {
@@ -93,7 +94,6 @@ export interface TurnNarrativeState {
terminalMessage: string | null;
narrativeSummary: string | null;
cancelled: boolean;
- proposalDisposition: ProposalDisposition | null;
// Block count of the canonical workflow at turn entry. Drives the edit-
// vs-build chip derivation; the snap-back source is captured client-side
// at submit so unsaved local canvas edits survive.
@@ -112,6 +112,7 @@ export const EMPTY_NARRATIVE: TurnNarrativeState = Object.freeze({
turnIndex: null,
mode: "unknown",
responseType: null,
+ proposalDisposition: null,
designStarted: false,
designEnded: false,
draft: null,
@@ -120,7 +121,6 @@ export const EMPTY_NARRATIVE: TurnNarrativeState = Object.freeze({
terminalMessage: null,
narrativeSummary: null,
cancelled: false,
- proposalDisposition: null,
priorBlockCount: null,
startedAt: null,
endedAt: null,
@@ -443,8 +443,9 @@ export function applyNarrativeEvent(
return {
...prev,
responseType: event.response_type ?? prev.responseType,
- cancelled: event.cancelled ?? false,
- proposalDisposition: event.proposal_disposition,
+ cancelled: event.cancelled ?? prev.cancelled,
+ proposalDisposition:
+ event.proposal_disposition ?? prev.proposalDisposition,
designEnded: true,
terminal: "response",
terminalMessage: event.message,
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index 8de94795a..d67021b4f 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -816,8 +816,15 @@ def _make_agent_result(
)
narrative_payload = kwargs.get("narrative_payload")
response_type = kwargs.get("response_type", "REPLY")
- if isinstance(narrative_payload, dict) and "responseType" not in narrative_payload:
- kwargs["narrative_payload"] = {**narrative_payload, "responseType": response_type}
+ proposal_disposition = kwargs.get("proposal_disposition")
+ if isinstance(narrative_payload, dict):
+ payload_updates: dict[str, Any] = {}
+ if "responseType" not in narrative_payload:
+ payload_updates["responseType"] = response_type
+ if proposal_disposition is not None and "proposalDisposition" not in narrative_payload:
+ payload_updates["proposalDisposition"] = proposal_disposition
+ if payload_updates:
+ kwargs["narrative_payload"] = {**narrative_payload, **payload_updates}
return AgentResult(global_llm_context=final_context, turn_outcome=turn_outcome, **kwargs)
@@ -1192,8 +1199,14 @@ def _finalize_result_with_blocker_override(
else CopilotOutputKind.INFORMATIONAL_ANSWER
)
preserve_draft = local_signal.preserves_workflow_draft
- preserved_workflow_yaml = result.workflow_yaml if preserve_draft else None
- if preserve_draft and result.updated_workflow is not None:
+ preserved_workflow = None
+ preserved_workflow_yaml = None
+ if preserve_draft:
+ preserved_workflow = result.updated_workflow or result.staged_workflow or ctx.staged_workflow
+ if preserved_workflow is not None:
+ preserved_workflow_yaml = result.workflow_yaml or result.staged_workflow_yaml or ctx.staged_workflow_yaml
+ preserved_proposal = preserve_draft and preserved_workflow is not None
+ if preserved_proposal:
rendered_reply = _ensure_unvalidated_proposal_affordance(rendered_reply)
rendered_verdict = evaluate_output_policy(
request_policy=ctx.request_policy,
@@ -1201,10 +1214,10 @@ def _finalize_result_with_blocker_override(
user_response=rendered_reply,
global_llm_context=None,
workflow_yaml=preserved_workflow_yaml,
- has_workflow_proposal=preserve_draft and result.updated_workflow is not None,
+ has_workflow_proposal=preserved_proposal,
workflow_was_persisted=False,
workflow_attempted=False,
- unvalidated=preserve_draft,
+ unvalidated=preserved_proposal,
output_kind=rendered_kind,
)
raw_verdict = _copy_output_policy_verdict(rendered_verdict)
@@ -1237,6 +1250,9 @@ def _finalize_result_with_blocker_override(
**blocker_signal_to_trace_data(local_signal),
)
preserve_draft = False
+ preserved_workflow = None
+ preserved_workflow_yaml = None
+ preserved_proposal = False
# ResponseKind has no "REPLY" member; CLARIFY matches the convention other
# turn-end exits (timeout, max-turns, cancel, non-retriable-nav) use.
@@ -1260,14 +1276,13 @@ def _finalize_result_with_blocker_override(
soft_rewrite_reason_codes=[],
)
# A blocker turn is never auto-applicable; even a preserved draft is surfaced as review_untested.
- preserved_proposal = preserve_draft and result.updated_workflow is not None
return _make_agent_result(
ctx,
user_response=final_text,
- updated_workflow=result.updated_workflow if preserve_draft else None,
+ updated_workflow=preserved_workflow if preserve_draft else None,
global_llm_context=result.global_llm_context,
response_type=rendered_resp_type,
- workflow_yaml=result.workflow_yaml if preserve_draft else None,
+ workflow_yaml=preserved_workflow_yaml if preserve_draft else None,
workflow_was_persisted=result.workflow_was_persisted,
clear_proposed_workflow=not preserve_draft,
total_tokens=result.total_tokens,
diff --git a/skyvern/forge/sdk/copilot/blocker_signal.py b/skyvern/forge/sdk/copilot/blocker_signal.py
index 16259082f..6c88fc2d0 100644
--- a/skyvern/forge/sdk/copilot/blocker_signal.py
+++ b/skyvern/forge/sdk/copilot/blocker_signal.py
@@ -9,6 +9,8 @@ from typing import Any, Literal, Protocol
import structlog
from pydantic import BaseModel, ConfigDict, Field, field_serializer, model_validator
+from skyvern.forge.sdk.copilot.failure_tracking import ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE
+
BlockerKind = Literal[
"authority_denied",
"loop_detected",
@@ -141,6 +143,21 @@ _LOOP_PROGRESS_TOOLS = frozenset(
"update_workflow",
}
)
+_ACTIVE_TERMINAL_REPLACEABLE_REASON_CODES = frozenset({"tool_error_per_tool_budget_rerun"})
+
+
+def _should_stash_over_existing(
+ existing: CopilotToolBlockerSignal | None,
+ incoming: CopilotToolBlockerSignal,
+) -> bool:
+ if not isinstance(existing, CopilotToolBlockerSignal):
+ return True
+ if (
+ incoming.internal_reason_code == ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE
+ and existing.internal_reason_code in _ACTIVE_TERMINAL_REPLACEABLE_REASON_CODES
+ ):
+ return True
+ return False
def _tool_success_clears_signal(signal: CopilotToolBlockerSignal, succeeded_tool_name: str) -> bool:
@@ -166,7 +183,7 @@ def clear_blocker_signal_for_reason_codes(ctx: _BlockerSignalCtx, internal_reaso
def stash_blocker_signal(ctx: _BlockerSignalCtx, signal: CopilotToolBlockerSignal) -> str:
- """First-wins stash + observability log; returns the LLM-visible payload."""
+ """Mostly first-wins stash + observability log; returns the LLM-visible payload."""
ctx.latest_tool_blocker_signal = signal
# Keep the defensive guard for tests and partial context shims even though
# real Copilot contexts type this field as a list.
@@ -178,13 +195,16 @@ def stash_blocker_signal(ctx: _BlockerSignalCtx, signal: CopilotToolBlockerSigna
if len(history) > 20:
del history[:-20]
existing = getattr(ctx, "blocker_signal", None)
- stashed = not isinstance(existing, CopilotToolBlockerSignal)
+ stashed = _should_stash_over_existing(existing, signal)
if stashed:
ctx.blocker_signal = signal
extra: dict[str, Any] = {"stashed": stashed}
if not stashed and isinstance(existing, CopilotToolBlockerSignal):
extra["existing_reason_code"] = existing.internal_reason_code
extra["existing_blocker_kind"] = existing.blocker_kind
+ elif stashed and isinstance(existing, CopilotToolBlockerSignal):
+ extra["replaced_reason_code"] = existing.internal_reason_code
+ extra["replaced_blocker_kind"] = existing.blocker_kind
LOG.info("copilot tool blocker signal", **extra, **to_trace_data(signal))
return build_llm_tool_error_payload(signal)
diff --git a/skyvern/forge/sdk/copilot/completion_verification.py b/skyvern/forge/sdk/copilot/completion_verification.py
index bc31dd915..6b0574d71 100644
--- a/skyvern/forge/sdk/copilot/completion_verification.py
+++ b/skyvern/forge/sdk/copilot/completion_verification.py
@@ -29,6 +29,23 @@ PROMPT_TEMPLATE_NAME = "workflow-copilot-completion-verification"
_EVIDENCE_VALUE_MAX_CHARS = 2000
_MAX_BLOCK_OUTPUTS = 20
_REASON_CODES = frozenset({"evidence_confirms", "no_evidence", "evidence_contradicts", "unknown"})
+_PAGE_EVIDENCE_KEYS = (
+ "current_url",
+ "page_title",
+ "visual_evidence_summary",
+ "screenshot_used",
+ "evidence_sources",
+ "visible_text_excerpt",
+ "forms",
+ "navigation_targets",
+ "result_containers",
+ "anti_bot_indicators",
+ "challenge_state",
+ "visual_evidence_omissions",
+ "inspection_warnings",
+ "observed_empty_page",
+ "evidence_confidence",
+)
VerificationStatus = Literal["evaluated", "unavailable"]
@@ -71,9 +88,10 @@ class RunEvidenceSnapshot:
page_title: str | None = None
executed_block_labels: list[str] = field(default_factory=list)
verified_context_block_labels: list[str] = field(default_factory=list)
+ page_evidence: dict[str, Any] = field(default_factory=dict)
def has_evidence(self) -> bool:
- return bool(self.block_outputs or self.current_url or self.page_title)
+ return bool(self.block_outputs or self.current_url or self.page_title or self.page_evidence)
def render_prompt_block(self) -> str:
lines: list[str] = []
@@ -95,6 +113,15 @@ class RunEvidenceSnapshot:
serialized = payload if isinstance(payload, str) else json.dumps(payload, default=str)
serialized = " ".join(serialized.split())[:_EVIDENCE_VALUE_MAX_CHARS]
lines.append(f" - {label}: {serialized}")
+ page_evidence = {
+ key: self.page_evidence[key]
+ for key in _PAGE_EVIDENCE_KEYS
+ if key in self.page_evidence and self.page_evidence[key] not in (None, "", [], {})
+ }
+ if page_evidence:
+ serialized = json.dumps(page_evidence, default=str)
+ serialized = " ".join(serialized.split())[:_EVIDENCE_VALUE_MAX_CHARS]
+ lines.append(f"page_evidence: {serialized}")
return redact_raw_secrets_for_prompt("\n".join(lines))
diff --git a/skyvern/forge/sdk/copilot/composition_evidence.py b/skyvern/forge/sdk/copilot/composition_evidence.py
index 3200cb8cf..a03f841d5 100644
--- a/skyvern/forge/sdk/copilot/composition_evidence.py
+++ b/skyvern/forge/sdk/copilot/composition_evidence.py
@@ -61,6 +61,7 @@ _MODAL_DISMISS_HINTS: frozenset[str] = frozenset(
}
)
_MODAL_DISMISS_SYMBOLS: frozenset[str] = frozenset({"x", "\u00d7"})
+_MAX_VISIBLE_TEXT_EXCERPT_CHARS = 3000
DOM_EVIDENCE_SOURCE = "dom_html"
DOM_STYLE_EVIDENCE_SOURCE = "dom_style"
SCREENSHOT_EVIDENCE_SOURCE = "screenshot"
@@ -1005,6 +1006,7 @@ def _empty_evidence(inspected_url: str, current_url: str) -> dict[str, Any]:
"forms": [],
"navigation_targets": [],
"result_containers": [],
+ "visible_text_excerpt": "",
"anti_bot_indicators": [],
"challenge_controls": [],
"modal_overlays": [],
@@ -1489,6 +1491,7 @@ def parse_composition_html(html: str, *, inspected_url: str, current_url: str) -
for node in soup.find_all(["script", "style", "noscript"]):
node.decompose()
+ visible_text = _node_text(soup.body if getattr(soup, "body", None) is not None else soup)
all_nodes = soup.find_all(True)
modal_overlays = _modal_overlays(all_nodes)
page_obstructions = _page_obstructions_from_modal_overlays(modal_overlays)
@@ -1600,6 +1603,7 @@ def parse_composition_html(html: str, *, inspected_url: str, current_url: str) -
"forms": forms,
"navigation_targets": navigation_targets,
"result_containers": result_containers,
+ "visible_text_excerpt": _schema_text(visible_text, _MAX_VISIBLE_TEXT_EXCERPT_CHARS),
"anti_bot_indicators": anti_bot_indicators,
"challenge_controls": challenge_controls,
"modal_overlays": modal_overlays,
diff --git a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py
index 8879010c9..2235e7836 100644
--- a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py
+++ b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Any
from pydantic import BaseModel, ConfigDict, Field
+from skyvern.forge.sdk.copilot.failure_tracking import ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY
from skyvern.forge.sdk.copilot.output_policy import url_origin
from skyvern.forge.sdk.copilot.request_policy import redact_raw_secrets_for_prompt
from skyvern.forge.sdk.copilot.workflow_credential_utils import URL_CANDIDATE_RE
@@ -29,6 +30,7 @@ class DiagnosisFailureType(StrEnum):
SUSPICIOUS_SUCCESS = "suspicious_success"
MISSING_CREDENTIAL_OR_INIT = "missing_credential_or_init"
REPAIRABLE_BLOCK_FAILURE = "repairable_block_failure"
+ ACTIVE_RUN_TERMINAL_EVIDENCE = "active_run_terminal_evidence"
UNRECOVERABLE_TOOL_ERROR = "unrecoverable_tool_error"
UNKNOWN = "unknown"
@@ -126,7 +128,7 @@ def build_diagnosis_repair_contract(
frontier = _safe_str(data.get("frontier_start_label"))
target_blocks = failed_blocks or ([frontier] if frontier else []) if next_action == RepairNextAction.REPAIR else []
user_goal_satisfied, completion_contract_satisfied = _verification_satisfaction(
- run_ok, suspicious, run_status, getattr(ctx, "completion_verification_result", None)
+ run_ok, suspicious, run_status, getattr(ctx, "completion_verification_result", None), data
)
confidence = (
0.9
@@ -149,6 +151,11 @@ def build_diagnosis_repair_contract(
}.get(next_action, _safe_text(f"Repair the workflow based on: {summary}", _SUMMARY_MAX))
if next_action == RepairNextAction.REPAIR and failure_type == DiagnosisFailureType.SUSPICIOUS_SUCCESS:
decision_summary = "Repair the data-producing block so completion is proven by meaningful output."
+ elif failure_type == DiagnosisFailureType.ACTIVE_RUN_TERMINAL_EVIDENCE:
+ decision_summary = (
+ "Stop the current retry loop: the active run reached the requested browser state, "
+ "but the reusable workflow is not verified end-to-end."
+ )
completion_check = {
RepairNextAction.NO_CHANGE: "Current run already satisfies the goal.",
RepairNextAction.ASK: "Resume diagnosis after the user supplies the missing context.",
@@ -312,6 +319,11 @@ def _failure_type(
or ("404" in error_text and "browser session" in error_text)
):
return DiagnosisFailureType.UNRECOVERABLE_TOOL_ERROR
+ if (
+ ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY in categories
+ or data.get("active_run_terminal_evidence_detected") is True
+ ):
+ return DiagnosisFailureType.ACTIVE_RUN_TERMINAL_EVIDENCE
if (
data.get("skip_reason") == "workflow_credential_inputs_unbound"
or "credential" in error_text
@@ -336,6 +348,8 @@ def _next_action(failure_type: DiagnosisFailureType, ctx: CopilotContext, data:
return RepairNextAction.ASK
if failure_type == DiagnosisFailureType.UNRECOVERABLE_TOOL_ERROR:
return RepairNextAction.STOP
+ if failure_type == DiagnosisFailureType.ACTIVE_RUN_TERMINAL_EVIDENCE:
+ return RepairNextAction.STOP
if ctx.last_test_non_retriable_nav_error:
return RepairNextAction.STOP
if getattr(ctx, "last_test_anti_bot", None) and failure_type in {
@@ -361,7 +375,12 @@ def _verification_satisfaction(
suspicious: bool,
run_status: str | None,
completion_verification: CompletionVerificationResult | None = None,
+ data: dict[str, Any] | None = None,
) -> tuple[bool | None, bool | None]:
+ if isinstance(data, dict) and data.get("active_run_terminal_evidence_detected") is True:
+ trace = data.get("active_run_terminal_completion_verification")
+ fully_satisfied = isinstance(trace, dict) and trace.get("fully_satisfied") is True
+ return fully_satisfied, fully_satisfied
user_goal_satisfied = (not suspicious) if run_ok else None if run_status is None else False
# When the verification judge was required (a non-null result), its verdict
# is authoritative: an unmet or unavailable verdict cannot claim the outcome.
diff --git a/skyvern/forge/sdk/copilot/failure_tracking.py b/skyvern/forge/sdk/copilot/failure_tracking.py
index 6552b53ab..d136ba165 100644
--- a/skyvern/forge/sdk/copilot/failure_tracking.py
+++ b/skyvern/forge/sdk/copilot/failure_tracking.py
@@ -35,6 +35,12 @@ _FAILURE_REASON_MAX_CHARS = 200
# and signature normalization as a single source of truth.
PER_TOOL_BUDGET_FAILURE_CATEGORY = "PER_TOOL_BUDGET"
+# Stable active-run terminal evidence identifiers. The category is stored in
+# tool result ``failure_categories``; the reason code is stored on blocker
+# signals that convert that tool result into product-safe final copy.
+ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY = "ACTIVE_RUN_TERMINAL_EVIDENCE"
+ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE = "tool_error_active_run_terminal_evidence"
+
def normalize_failure_reason(raw: str | None) -> str:
if not raw:
diff --git a/skyvern/forge/sdk/copilot/output_utils.py b/skyvern/forge/sdk/copilot/output_utils.py
index fafa166b8..d5d16c6a1 100644
--- a/skyvern/forge/sdk/copilot/output_utils.py
+++ b/skyvern/forge/sdk/copilot/output_utils.py
@@ -12,6 +12,11 @@ from typing import TYPE_CHECKING, Any
from skyvern.forge.sdk.agents.context import sanitize_agent_tool_result_for_llm as sanitize_generic_tool_result_for_llm
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal, assert_clean_user_facing_text
from skyvern.forge.sdk.copilot.context import COPILOT_RESPONSE_TYPES
+from skyvern.forge.sdk.copilot.failure_tracking import (
+ ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY,
+ ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE,
+ PER_TOOL_BUDGET_FAILURE_CATEGORY,
+)
from skyvern.forge.sdk.copilot.loop_detection import LOOP_DETECTED_MARKER
from skyvern.schemas.workflows import BlockType
@@ -307,7 +312,6 @@ def iter_failure_reasons(result: dict[str, Any]) -> Iterator[str]:
_UNKNOWN_ERROR_SENTINEL = "Unknown error"
-_PER_TOOL_BUDGET_FAILURE_CATEGORY = "PER_TOOL_BUDGET"
_USER_FACING_SUMMARY_KEYS: tuple[str, ...] = ("user_facing_summary", "user_facing_reason")
_STRUCTURED_UNSAFE_FALLBACK = "Couldn't complete that step."
@@ -345,7 +349,11 @@ def _blocker_signal_matches_result(signal: CopilotToolBlockerSignal, result: dic
if not isinstance(error, str) or not error:
return False
steering = signal.agent_steering_text
- return error == steering or steering in error
+ if error == steering or steering in error:
+ return True
+ return signal.internal_reason_code == ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE and _has_failure_category(
+ result, ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY
+ )
def _failure_categories(result: dict[str, Any]) -> list[Any]:
@@ -406,7 +414,7 @@ def _structured_failure_summary_for_user(
if saw_structured_summary:
return _STRUCTURED_UNSAFE_FALLBACK
- if _has_failure_category(result, _PER_TOOL_BUDGET_FAILURE_CATEGORY):
+ if _has_failure_category(result, PER_TOOL_BUDGET_FAILURE_CATEGORY):
# An explicit but empty failure_reason still means the structured
# watchdog path fired; use the generic safe copy rather than raw error
# fallback.
diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.py
index 47a208a99..86b6dc4c4 100644
--- a/skyvern/forge/sdk/copilot/tools.py
+++ b/skyvern/forge/sdk/copilot/tools.py
@@ -85,6 +85,8 @@ from skyvern.forge.sdk.copilot.enforcement import (
_goal_likely_needs_more_blocks,
)
from skyvern.forge.sdk.copilot.failure_tracking import (
+ ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY,
+ ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE,
PER_TOOL_BUDGET_FAILURE_CATEGORY,
_canonical_block_config,
compute_action_sequence_fingerprint,
@@ -193,6 +195,9 @@ RUN_BLOCKS_SAFETY_CEILING_SECONDS = 1200 # 20 min
# copilot a chance to issue a smaller chain. Quiet-block runs keep the longer
# ``RUN_BLOCKS_SAFETY_CEILING_SECONDS`` above.
PER_TOOL_CALL_BUDGET_SECONDS = 240
+_ACTIVE_RUN_TERMINAL_MONITOR_INITIAL_DELAY_SECONDS = 30.0
+_ACTIVE_RUN_TERMINAL_MONITOR_INTERVAL_SECONDS = 30.0
+_ACTIVE_RUN_TERMINAL_MONITOR_MAX_SAMPLES = 8
# Primary exit condition: seconds of no observed progress across the combined
# run / block / step heartbeat. Sized to accommodate the slowest single LLM
@@ -217,6 +222,15 @@ _EVALUATE_EVIDENCE_CONFIDENCE_WITH_SCHEMA = 0.75
_EVALUATE_EVIDENCE_CONFIDENCE_ANTIBOT_ONLY = 0.4
+@dataclass(frozen=True)
+class ActiveRunTerminalEvidenceSample:
+ current_url: str | None
+ page_title: str | None
+ page_evidence: dict[str, Any]
+ completion_verification: CompletionVerificationResult
+ sample_index: int
+
+
async def _cancel_run_task_if_not_final(
run_task: asyncio.Task,
workflow_run_id: str,
@@ -618,6 +632,54 @@ def _trusted_post_drain_status(run: WorkflowRun | None) -> str | None:
return None
+def _active_run_terminal_evidence_detected(result: Mapping[str, object]) -> bool:
+ data_value = result.get("data")
+ data = data_value if isinstance(data_value, Mapping) else {}
+ return data.get("active_run_terminal_evidence_detected") is True
+
+
+def _active_run_terminal_evidence_signal(ctx: AgentContext, tool_name: str) -> CopilotToolBlockerSignal | None:
+ evidence = getattr(ctx, "workflow_verification_evidence", None)
+ has_active_terminal_evidence = getattr(
+ ctx, "last_failure_category_top", None
+ ) == ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY or bool(
+ getattr(evidence, "active_run_terminal_evidence_detected", False)
+ )
+ if not has_active_terminal_evidence:
+ return None
+
+ run_id = getattr(evidence, "active_run_terminal_evidence_workflow_run_id", None) or getattr(
+ ctx, "last_run_blocks_workflow_run_id", None
+ )
+ location = (
+ getattr(evidence, "page_title", None) or getattr(evidence, "current_url", None) or "the current browser page"
+ )
+ run_detail = f" Workflow run: {run_id}." if isinstance(run_id, str) and run_id else ""
+ agent_steering = (
+ "The prior active workflow run emitted typed ACTIVE_RUN_TERMINAL_EVIDENCE while the browser task "
+ f"was still running.{run_detail} The current page evidence already matched the user's terminal "
+ "browser-state criteria, but the reusable workflow is not verified end-to-end. "
+ f"Do not call {tool_name} again in this turn; reply with a partial-verification/blocker state that "
+ "says the requested browser state was observed, the active run was interrupted before overshoot, "
+ "and the workflow still needs a clean corrected run before it can be offered as tested."
+ )
+ user_facing = (
+ f"I reached the requested browser state on {location} and stopped before continuing, "
+ "but the reusable workflow still needs a clean verification run before it is ready."
+ )
+ return CopilotToolBlockerSignal(
+ blocker_kind="tool_error",
+ agent_steering_text=agent_steering,
+ user_facing_reason=user_facing,
+ recovery_hint="report_blocker_to_user",
+ cleared_by_tools=frozenset(),
+ preserves_workflow_draft=True,
+ renders_final_reply=True,
+ internal_reason_code=ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE,
+ blocked_tool=tool_name,
+ )
+
+
def _maybe_clear_reconciliation_flag(copilot_ctx: Any, result: Any) -> None:
"""Clear ``pending_reconciliation_run_id`` iff the matching resolved run
landed in a status the caller can move past: any ``is_final_excluding_canceled``
@@ -642,8 +704,11 @@ def _maybe_clear_reconciliation_flag(copilot_ctx: Any, result: Any) -> None:
# ``last_failure_category_top`` reflects the prior block-running tool's outcome —
# only ``_record_run_blocks_result`` writes it, and the reconciliation guard
# prevents another block-running call from clobbering it before this read.
- was_per_tool_budget = getattr(copilot_ctx, "last_failure_category_top", None) == PER_TOOL_BUDGET_FAILURE_CATEGORY
- if is_trusted_final or was_per_tool_budget:
+ internal_watchdog_cancel_category = getattr(copilot_ctx, "last_failure_category_top", None) in {
+ PER_TOOL_BUDGET_FAILURE_CATEGORY,
+ ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY,
+ }
+ if is_trusted_final or internal_watchdog_cancel_category:
copilot_ctx.pending_reconciliation_run_id = None
copilot_ctx.pending_reconciliation_requires_user_input = False
clear_blocker_signal_for_reason_codes(
@@ -1593,6 +1658,11 @@ def _tool_loop_error(ctx: AgentContext, tool_name: str, arguments: dict[str, Any
if detected is not None:
return _emit_tool_blocker_signal(ctx, _build_loop_blocker_signal(detected, tool_name=tool_name))
+ if tool_name == "update_workflow" or tool_name in BLOCK_RUNNING_TOOLS:
+ active_terminal_signal = _active_run_terminal_evidence_signal(ctx, tool_name)
+ if active_terminal_signal is not None:
+ return _emit_tool_blocker_signal(ctx, active_terminal_signal)
+
# Hard-abort when the agent has re-fired the same action sequence against
# the page N times without intervening success. This is the signal that
# the form is blocked (captcha / anti-bot / error banner the agent isn't
@@ -3200,7 +3270,18 @@ def _frontier_run_size_error(
# last-resort budget-exhausted branch, and ``task_exit_unfinalized`` is the
# rare race where ``execute_workflow`` naturally exits before writing a
# terminal row.
-WatchdogExitReason = Literal["success", "stagnation", "ceiling", "per_tool_budget", "task_exit_unfinalized"]
+WatchdogExitReason = Literal[
+ "success",
+ "stagnation",
+ "ceiling",
+ "per_tool_budget",
+ "task_exit_unfinalized",
+ "active_run_terminal_evidence",
+]
+
+
+def _watchdog_exit_allows_terminal_promotion(exit_reason: WatchdogExitReason | None) -> bool:
+ return exit_reason != "active_run_terminal_evidence"
# Block types that legitimately execute long silent periods: one DB write on
@@ -3343,6 +3424,21 @@ async def _watchdog_error_message(
if current_url:
message += f" Browser was on: {current_url}"
return message
+ elif exit_reason == "active_run_terminal_evidence":
+ message = (
+ "The active run was interrupted because bounded current-page evidence matched the requested "
+ "browser terminal state while the workflow run was still in progress.\n"
+ f"Run ID: {workflow_run_id}.\n"
+ "This is NOT full workflow verification: the requested browser state was observed, but the durable "
+ "workflow chain still needs diagnosis/repair and a clean verification run. Next step: call "
+ "get_run_results with this workflow_run_id to inspect the active run boundary, preserve the observed "
+ "current-page evidence, and update only the block(s) that overshot or kept running after the state "
+ "was reached. Do NOT report end-to-end success unless a corrected workflow run verifies cleanly."
+ )
+ current_url, _ = await _fallback_page_info(ctx)
+ if current_url:
+ message += f" Browser was on: {current_url}"
+ return message
elif exit_reason == "ceiling":
body = (
f"The run exceeded the {budget_seconds}s absolute ceiling "
@@ -3377,6 +3473,11 @@ def _watchdog_user_failure_reason(
body = f"The run stopped after no observable progress for {RUN_BLOCKS_STAGNATION_WINDOW_SECONDS}s."
elif exit_reason == "per_tool_budget":
body = f"The run exceeded the {budget_seconds}s per-tool-call budget while still making progress."
+ elif exit_reason == "active_run_terminal_evidence":
+ body = (
+ "The active run reached the requested browser state before the workflow finished, "
+ "so it was interrupted for diagnosis/repair. Full workflow verification is still required."
+ )
elif exit_reason == "ceiling":
body = f"The run exceeded the {budget_seconds}s absolute ceiling while still showing progress."
else:
@@ -3837,6 +3938,7 @@ async def _run_blocks_and_collect_debug(
run: Any = initial_run
exit_reason: WatchdogExitReason | None = None
run_cancelled_by_watchdog = False
+ active_run_terminal_evidence: ActiveRunTerminalEvidenceSample | None = None
# Quiet blocks (WAIT/TEXT_PROMPT/HUMAN_INTERACTION) legitimately have
# DB-silent periods; disable stagnation for any invocation that includes
# one. Safety ceiling still applies.
@@ -3861,6 +3963,13 @@ async def _run_blocks_and_collect_debug(
seen_block_states: dict[str, str] = {}
prior_block_ts: datetime | None = initial_block_ts
last_block_fetch_monotonic = 0.0
+ active_terminal_monitor_enabled = await _active_run_terminal_monitor_enabled(ctx)
+ next_active_terminal_monitor_monotonic = (
+ started_monotonic + _ACTIVE_RUN_TERMINAL_MONITOR_INITIAL_DELAY_SECONDS
+ if active_terminal_monitor_enabled
+ else float("inf")
+ )
+ active_terminal_monitor_samples = 0
try:
while True:
@@ -3906,6 +4015,32 @@ async def _run_blocks_and_collect_debug(
is_paused = run is not None and run.status == WorkflowRunStatus.paused.value
stagnation_active = stagnation_enabled and not is_paused
+ if (
+ active_terminal_monitor_enabled
+ and not is_paused
+ and active_terminal_monitor_samples < _ACTIVE_RUN_TERMINAL_MONITOR_MAX_SAMPLES
+ and now >= next_active_terminal_monitor_monotonic
+ ):
+ active_terminal_monitor_samples += 1
+ next_active_terminal_monitor_monotonic += _ACTIVE_RUN_TERMINAL_MONITOR_INTERVAL_SECONDS
+ sample = await _active_run_terminal_evidence_sample(
+ ctx,
+ workflow_run_id=workflow_run.workflow_run_id,
+ labels_to_execute=labels_to_execute,
+ sample_index=active_terminal_monitor_samples,
+ )
+ if sample is not None:
+ post_sample_run = await _safe_read_workflow_run(
+ workflow_run.workflow_run_id,
+ ctx.organization_id,
+ context="active-terminal-post-sample",
+ )
+ if post_sample_run is not None:
+ run = post_sample_run
+ active_run_terminal_evidence = sample
+ exit_reason = "active_run_terminal_evidence"
+ break
+
if new_marker != progress_marker:
progress_marker = new_marker
last_progress_monotonic = now
@@ -3928,20 +4063,28 @@ async def _run_blocks_and_collect_debug(
pre_cancel_run = await _safe_read_workflow_run(
workflow_run.workflow_run_id, ctx.organization_id, context="pre-cancel"
)
- if pre_cancel_run is not None and WorkflowRunStatus(pre_cancel_run.status).is_final():
+ if (
+ _watchdog_exit_allows_terminal_promotion(exit_reason)
+ and pre_cancel_run is not None
+ and WorkflowRunStatus(pre_cancel_run.status).is_final()
+ ):
final_status = pre_cancel_run.status
run = pre_cancel_run
exit_reason = "success"
else:
- await _cancel_run_task_if_not_final(run_task, workflow_run.workflow_run_id)
- run_cancelled_by_watchdog = True
- run = await _safe_read_workflow_run(
- workflow_run.workflow_run_id, ctx.organization_id, context="post-drain"
- )
- trusted = _trusted_post_drain_status(run)
- if trusted is not None:
- final_status = trusted
- exit_reason = "success"
+ if pre_cancel_run is not None:
+ run = pre_cancel_run
+ if run is None or not WorkflowRunStatus(run.status).is_final():
+ await _cancel_run_task_if_not_final(run_task, workflow_run.workflow_run_id)
+ run_cancelled_by_watchdog = True
+ run = await _safe_read_workflow_run(
+ workflow_run.workflow_run_id, ctx.organization_id, context="post-drain"
+ )
+ if _watchdog_exit_allows_terminal_promotion(exit_reason):
+ trusted = _trusted_post_drain_status(run)
+ if trusted is not None:
+ final_status = trusted
+ exit_reason = "success"
if exit_reason != "success":
assert exit_reason is not None # narrows for mypy; outer check excludes "success" but not None
@@ -3954,22 +4097,35 @@ async def _run_blocks_and_collect_debug(
)
user_facing_summary = _watchdog_user_facing_summary(exit_reason, budget_seconds, run)
current_url, page_title = await _fallback_page_info(ctx)
- result: dict[str, Any] = {
- "ok": False,
- "error": error_msg,
- "data": {
- "workflow_run_id": workflow_run.workflow_run_id,
- "overall_status": run.status if run is not None else None,
- "failure_reason": user_failure_reason,
- "current_url": current_url,
- "page_title": page_title,
- "control_signal": {
- "kind": f"watchdog_{exit_reason}",
- "user_facing_summary": user_facing_summary,
+ if exit_reason == "active_run_terminal_evidence" and active_run_terminal_evidence is not None:
+ result: dict[str, Any] = _active_run_terminal_evidence_result(
+ workflow_run_id=workflow_run.workflow_run_id,
+ run_status=run.status if run is not None else None,
+ sample=active_run_terminal_evidence,
+ requested_block_labels=list(block_labels),
+ executed_block_labels=list(labels_to_execute),
+ current_url=current_url,
+ page_title=page_title,
+ )
+ result["error"] = error_msg
+ result["data"]["failure_reason"] = user_failure_reason
+ else:
+ result = {
+ "ok": False,
+ "error": error_msg,
+ "data": {
+ "workflow_run_id": workflow_run.workflow_run_id,
+ "overall_status": run.status if run is not None else None,
+ "failure_reason": user_failure_reason,
+ "current_url": current_url,
+ "page_title": page_title,
},
- "user_facing_summary": user_facing_summary,
- },
+ }
+ result["data"]["control_signal"] = {
+ "kind": f"watchdog_{exit_reason}",
+ "user_facing_summary": user_facing_summary,
}
+ result["data"]["user_facing_summary"] = user_facing_summary
if exit_reason == "per_tool_budget":
# Stable failure_categories entry so consecutive budget trips
# hash to the same streak signature; without it the run_id in
@@ -5638,6 +5794,17 @@ def _update_verification_evidence_from_run_result(copilot_ctx: AgentContext, res
run_id = data.get("workflow_run_id")
if isinstance(run_id, str) and run_id.strip():
evidence.workflow_run_id = run_id.strip()
+ if _active_run_terminal_evidence_detected(result):
+ evidence.active_run_terminal_evidence_detected = True
+ evidence.live_page_state_verified = True
+ evidence.verified_from_current_browser_state = True
+ evidence.full_workflow_verified = False
+ evidence.test_attempted_but_incomplete = True
+ if isinstance(run_id, str) and run_id.strip():
+ evidence.active_run_terminal_evidence_workflow_run_id = run_id.strip()
+ sample_index = data.get("active_run_terminal_evidence_sample_index")
+ if isinstance(sample_index, int):
+ evidence.active_run_terminal_evidence_sample_index = sample_index
current_url = _valid_runtime_anchor_url(data.get("current_url"))
if current_url is not None:
evidence.current_url = current_url
@@ -5686,6 +5853,146 @@ async def _completion_verification_handler(copilot_ctx: Any) -> Any | None:
)
+async def _active_run_terminal_monitor_enabled(copilot_ctx: Any) -> bool:
+ if not settings.COPILOT_OUTCOME_VERIFICATION_ENABLED:
+ return False
+ if not getattr(copilot_ctx, "browser_session_id", None):
+ return False
+ if not getattr(copilot_ctx, "discovery_mcp_server", None):
+ return False
+ if not _completion_verification_criteria(copilot_ctx):
+ return False
+ return await _completion_verification_handler(copilot_ctx) is not None
+
+
+def _active_run_terminal_evidence_needs_visual_fallback(evidence: dict[str, Any]) -> bool:
+ if page_evidence_needs_visual_fallback(evidence):
+ return True
+ return evidence.get("screenshot_used") is not True
+
+
+async def _active_run_terminal_evidence_sample(
+ copilot_ctx: Any,
+ *,
+ workflow_run_id: str,
+ labels_to_execute: list[str],
+ sample_index: int,
+) -> ActiveRunTerminalEvidenceSample | None:
+ criteria = _completion_verification_criteria(copilot_ctx)
+ if not criteria:
+ return None
+ handler = await _completion_verification_handler(copilot_ctx)
+ if handler is None:
+ return None
+
+ current_url_raw, page_title_raw = await _fallback_page_info(copilot_ctx)
+ current_url = _valid_runtime_anchor_url(current_url_raw)
+ if current_url is None:
+ return None
+
+ evidence, html_error = await _capture_composition_evidence(
+ copilot_ctx,
+ inspected_url=current_url,
+ current_url=current_url,
+ active_run_terminal_sample=True,
+ )
+ if html_error is not None or evidence is None:
+ LOG.info(
+ "copilot active-run terminal evidence sample skipped",
+ workflow_run_id=workflow_run_id,
+ sample_index=sample_index,
+ html_error=html_error,
+ )
+ return None
+
+ page_title = evidence.get("page_title")
+ if not isinstance(page_title, str) or not page_title.strip():
+ page_title = page_title_raw if isinstance(page_title_raw, str) and page_title_raw.strip() else None
+ evidence = {
+ **evidence,
+ "workflow_run_id": workflow_run_id,
+ "observed_during_active_workflow_run": True,
+ }
+ snapshot = RunEvidenceSnapshot(
+ workflow_run_id=workflow_run_id,
+ current_url=current_url,
+ page_title=page_title,
+ executed_block_labels=list(labels_to_execute),
+ page_evidence=evidence,
+ )
+ if not snapshot.has_evidence():
+ return None
+
+ result = await evaluate_completion_criteria(criteria, snapshot, handler)
+ LOG.info(
+ "copilot active-run terminal evidence sample",
+ workflow_run_id=workflow_run_id,
+ sample_index=sample_index,
+ completion_verification_status=result.status,
+ completion_verification_fully_satisfied=result.is_fully_satisfied(),
+ )
+ if result.status != "evaluated" or not result.is_fully_satisfied():
+ return None
+ copilot_ctx.composition_page_evidence = evidence
+ return ActiveRunTerminalEvidenceSample(
+ current_url=current_url,
+ page_title=page_title,
+ page_evidence=evidence,
+ completion_verification=result,
+ sample_index=sample_index,
+ )
+
+
+def _active_run_terminal_evidence_result(
+ *,
+ workflow_run_id: str,
+ run_status: str | None,
+ sample: Any,
+ requested_block_labels: list[str],
+ executed_block_labels: list[str],
+ current_url: str | None = None,
+ page_title: str | None = None,
+) -> dict[str, Any]:
+ observed_url = current_url or getattr(sample, "current_url", None)
+ observed_title = page_title or getattr(sample, "page_title", None)
+ completion = getattr(sample, "completion_verification", None)
+ completion_trace = completion.to_trace_data() if isinstance(completion, CompletionVerificationResult) else {}
+ reason = (
+ "The active run reached the requested browser state while the workflow was still running, "
+ "so Copilot interrupted it before further browser actions could overshoot that state. "
+ "The current page evidence is not a durable full-workflow verification; inspect the run boundary, "
+ "repair the workflow if needed, and verify the corrected workflow run."
+ )
+ return {
+ "ok": False,
+ "error": reason,
+ "data": {
+ "workflow_run_id": workflow_run_id,
+ "overall_status": run_status,
+ "failure_reason": reason,
+ "requested_block_labels": list(requested_block_labels),
+ "executed_block_labels": list(executed_block_labels),
+ "current_url": observed_url,
+ "page_title": observed_title,
+ "active_run_terminal_evidence_detected": True,
+ "active_run_terminal_evidence_sample_index": getattr(sample, "sample_index", None),
+ "full_workflow_verified": False,
+ "current_page_evidence": getattr(sample, "page_evidence", None),
+ "active_run_terminal_completion_verification": completion_trace,
+ "failure_categories": [
+ {
+ "category": ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY,
+ "confidence_float": 1.0,
+ "reasoning": (
+ "Bounded current-page evidence matched the request-policy completion criteria "
+ "while the workflow run was still active; the run was interrupted for diagnosis/repair."
+ ),
+ }
+ ],
+ },
+ }
+
+
def _is_outcome_evidence_candidate(copilot_ctx: Any, result: dict[str, Any]) -> bool:
"""A clean ok=True run worth judging on its whole-workflow outcome.
@@ -5712,6 +6019,8 @@ def _is_unfinished_run_verification_candidate(copilot_ctx: Any, result: dict[str
"""
if bool(result.get("ok", False)):
return False
+ if _active_run_terminal_evidence_detected(result):
+ return False
if _run_blocks_structured_blocker_message(result):
return False
data = result.get("data")
@@ -5960,6 +6269,12 @@ def _record_run_blocks_result(
if isinstance(data, dict):
data["failure_categories"] = failure_categories
+ if _active_run_terminal_evidence_detected(result):
+ _update_verification_evidence_from_run_result(copilot_ctx, result)
+ signal = _active_run_terminal_evidence_signal(copilot_ctx, "update_and_run_blocks")
+ if signal is not None:
+ stash_blocker_signal(copilot_ctx, signal)
+
if run_ok:
_mark_page_inspected(copilot_ctx)
if structured_blocker:
@@ -7086,17 +7401,20 @@ def _composition_visual_prompt(evidence: dict[str, Any]) -> str:
"Return JSON only with keys: summary, challenge_detected, challenge_kind, "
"challenge_location, submit_blocked, blocked_submit_controls, empty_page_visible, "
"loading_state_visible, page_obstruction_detected, obstruction_kind, "
- "obstruction_location, underlying_page_blocked, visible_dismiss_controls, omissions. Focus on "
- "visible anti-bot or human-verification state, whether it appears to gate a submit/search "
- "control, whether any visible artificial barrier mechanically blocks the underlying page, "
- "and where it appears relative to the page controls. Do not include raw DOM, "
- "code, selectors, personal data, or workflow instructions. If no challenge is visible, "
- "set challenge_detected to false and submit_blocked to false. If no page obstruction is visible, "
- "set page_obstruction_detected to false. If DOM context shows a "
- "schema-empty page, set empty_page_visible to true only when the screenshot shows a "
- "settled page with no visible forms, controls, result data, challenge, or loading/progress "
- "state; set loading_state_visible to true when the page appears to be waiting, loading, "
- "redirecting, or still rendering.\n\n"
+ "obstruction_location, underlying_page_blocked, visible_dismiss_controls, omissions. "
+ "In summary, include the visible page state that would help verify an end-state outcome, "
+ "such as cart items, "
+ "record rows, visible identifiers, quantities, statuses, prices, confirmations, search results, "
+ "or selected values when legible. Also note visible anti-bot or human-verification state, "
+ "whether it appears to gate a submit/search control, whether any visible artificial barrier "
+ "mechanically blocks the underlying page, and where it appears relative to the page controls. "
+ "Do not include raw DOM, code, selectors, personal data, or workflow instructions. "
+ "If no challenge is visible, set challenge_detected to false and submit_blocked to false. "
+ "If no page obstruction is visible, set page_obstruction_detected to false. "
+ "If DOM context shows a schema-empty page, set empty_page_visible to true only when the "
+ "screenshot shows a settled page with no visible forms, controls, result data, challenge, "
+ "or loading/progress state; set loading_state_visible to true when the page appears to be "
+ "waiting, loading, redirecting, or still rendering.\n\n"
f"DOM evidence context:\n{json.dumps(context, sort_keys=True)}"
)
@@ -7498,6 +7816,7 @@ async def _capture_composition_evidence(
*,
inspected_url: str,
current_url: str,
+ active_run_terminal_sample: bool = False,
) -> tuple[dict[str, Any] | None, str | None]:
"""Read page HTML and parse composition evidence, recapturing on a hollow read.
@@ -7526,6 +7845,7 @@ async def _capture_composition_evidence(
evidence = await _augment_composition_evidence_with_computed_obstruction_candidates(copilot_ctx, evidence)
if evidence is not None and (
page_evidence_needs_visual_fallback(evidence)
+ or (active_run_terminal_sample and _active_run_terminal_evidence_needs_visual_fallback(evidence))
or (evidence.get("schema_empty_page") is True and not has_bounded_page_schema(evidence))
):
evidence = await _augment_composition_evidence_with_visual_fallback(copilot_ctx, evidence)
diff --git a/skyvern/forge/sdk/copilot/verification_evidence.py b/skyvern/forge/sdk/copilot/verification_evidence.py
index 853ed2641..a5d0b4570 100644
--- a/skyvern/forge/sdk/copilot/verification_evidence.py
+++ b/skyvern/forge/sdk/copilot/verification_evidence.py
@@ -12,6 +12,7 @@ class WorkflowVerificationEvidence:
full_workflow_verified: bool = False
block_verified: list[str] = field(default_factory=list)
live_page_state_verified: bool = False
+ active_run_terminal_evidence_detected: bool = False
test_attempted_but_incomplete: bool = False
per_tool_budget_on_block: list[str] = field(default_factory=list)
verified_from_current_browser_state: bool = False
@@ -20,6 +21,8 @@ class WorkflowVerificationEvidence:
current_url: str | None = None
page_title: str | None = None
workflow_run_id: str | None = None
+ active_run_terminal_evidence_workflow_run_id: str | None = None
+ active_run_terminal_evidence_sample_index: int | None = None
unverified_block_labels: list[str] = field(default_factory=list)
failed_block_labels: list[str] = field(default_factory=list)
failure_reason: str | None = None
@@ -35,6 +38,7 @@ class WorkflowVerificationEvidence:
self.full_workflow_verified
or self.block_verified
or self.live_page_state_verified
+ or self.active_run_terminal_evidence_detected
or self.test_attempted_but_incomplete
or self.per_tool_budget_on_block
or self.verified_from_current_browser_state
@@ -42,6 +46,8 @@ class WorkflowVerificationEvidence:
or self.current_url_may_encode_runtime_state
or self.current_url
or self.workflow_run_id
+ or self.active_run_terminal_evidence_workflow_run_id
+ or self.active_run_terminal_evidence_sample_index is not None
or self.unverified_block_labels
or self.failed_block_labels
or self.failure_reason
@@ -52,6 +58,7 @@ class WorkflowVerificationEvidence:
"full_workflow_verified": self.full_workflow_verified,
"block_verified_count": len(self.block_verified),
"live_page_state_verified": self.live_page_state_verified,
+ "active_run_terminal_evidence_detected": self.active_run_terminal_evidence_detected,
"test_attempted_but_incomplete": self.test_attempted_but_incomplete,
"per_tool_budget_on_block_count": len(self.per_tool_budget_on_block),
"verified_from_current_browser_state": self.verified_from_current_browser_state,
@@ -59,6 +66,7 @@ class WorkflowVerificationEvidence:
"current_url_may_encode_runtime_state": self.current_url_may_encode_runtime_state,
"has_current_url": bool(self.current_url),
"has_workflow_run_id": bool(self.workflow_run_id),
+ "has_active_run_terminal_evidence_workflow_run_id": bool(self.active_run_terminal_evidence_workflow_run_id),
"unverified_block_count": len(self.unverified_block_labels),
"failed_block_count": len(self.failed_block_labels),
"has_failure_reason": bool(self.failure_reason),
@@ -71,6 +79,7 @@ class WorkflowVerificationEvidence:
lines = [
f"full_workflow_verified: {str(self.full_workflow_verified).lower()}",
f"live_page_state_verified: {str(self.live_page_state_verified).lower()}",
+ f"active_run_terminal_evidence_detected: {str(self.active_run_terminal_evidence_detected).lower()}",
f"test_attempted_but_incomplete: {str(self.test_attempted_but_incomplete).lower()}",
f"verified_from_current_browser_state: {str(self.verified_from_current_browser_state).lower()}",
]
@@ -93,6 +102,12 @@ class WorkflowVerificationEvidence:
lines.append(f"page_title: {self.page_title}")
if self.workflow_run_id:
lines.append(f"workflow_run_id: {self.workflow_run_id}")
+ if self.active_run_terminal_evidence_workflow_run_id:
+ lines.append(
+ f"active_run_terminal_evidence_workflow_run_id: {self.active_run_terminal_evidence_workflow_run_id}"
+ )
+ if self.active_run_terminal_evidence_sample_index is not None:
+ lines.append(f"active_run_terminal_evidence_sample_index: {self.active_run_terminal_evidence_sample_index}")
if self.failure_reason:
lines.append(f"failure_reason: {self.failure_reason}")
return "\n".join(lines)
diff --git a/tests/unit/test_copilot_agent_blocker_renderer.py b/tests/unit/test_copilot_agent_blocker_renderer.py
index 1064774ca..65219931f 100644
--- a/tests/unit/test_copilot_agent_blocker_renderer.py
+++ b/tests/unit/test_copilot_agent_blocker_renderer.py
@@ -240,6 +240,46 @@ def test_shim_preserves_workflow_draft_when_signal_opts_in() -> None:
assert overridden.user_response != ctx.blocker_signal.user_facing_reason
+def test_shim_preserves_staged_workflow_draft_when_verified_result_is_empty() -> None:
+ """Active-run terminal evidence can leave the verified workflow empty while
+ the keepable draft remains staged. That draft must still surface for
+ explicit user review instead of clearing the proposal controls."""
+ ctx = _ctx()
+ fake_workflow: Any = object()
+ ctx.staged_workflow = fake_workflow
+ ctx.staged_workflow_yaml = "title: Staged\n"
+ ctx.has_staged_proposal = True
+ ctx.blocker_signal = CopilotToolBlockerSignal(
+ blocker_kind="tool_error",
+ agent_steering_text="Stop and reply with the staged draft.",
+ user_facing_reason=(
+ "I reached the requested browser state, but the reusable workflow "
+ "still needs a clean verification run before it is ready."
+ ),
+ recovery_hint="stop",
+ preserves_workflow_draft=True,
+ internal_reason_code="tool_error_active_run_terminal_evidence",
+ blocked_tool="update_and_run_blocks",
+ )
+ result = AgentResult(
+ user_response="agent reply",
+ updated_workflow=None,
+ global_llm_context=None,
+ workflow_yaml=None,
+ staged_workflow_yaml=ctx.staged_workflow_yaml,
+ staged_workflow=fake_workflow,
+ has_staged_proposal=True,
+ )
+ overridden = _finalize_result_with_blocker_override(ctx, result)
+ assert overridden.updated_workflow is fake_workflow
+ assert overridden.workflow_yaml == ctx.staged_workflow_yaml
+ assert overridden.clear_proposed_workflow is False
+ assert overridden.proposal_disposition == "review_untested"
+ assert overridden.narrative_payload is not None
+ assert overridden.narrative_payload["proposalDisposition"] == "review_untested"
+ assert "Accept to save" in overridden.user_response
+
+
def test_shim_keeps_model_reply_when_signal_opts_out_of_final_rendering() -> None:
"""Some tool guards are steering-only: they block a tool call but still let
the model answer from evidence already gathered in the turn."""
diff --git a/tests/unit/test_copilot_blocker_signal.py b/tests/unit/test_copilot_blocker_signal.py
index a36ca1f67..fcf278f41 100644
--- a/tests/unit/test_copilot_blocker_signal.py
+++ b/tests/unit/test_copilot_blocker_signal.py
@@ -253,6 +253,20 @@ def test_stash_blocker_signal_first_wins_returns_llm_payload() -> None:
assert ctx.tool_blocker_signals == [first, second]
+def test_stash_blocker_signal_active_terminal_replaces_per_tool_budget() -> None:
+ ctx = _Ctx()
+ budget = _make(internal_reason_code="tool_error_per_tool_budget_rerun")
+ active_terminal = _make(internal_reason_code="tool_error_active_run_terminal_evidence")
+
+ stash_blocker_signal(ctx, budget)
+ payload = stash_blocker_signal(ctx, active_terminal)
+
+ assert payload == active_terminal.agent_steering_text
+ assert ctx.blocker_signal is active_terminal
+ assert ctx.latest_tool_blocker_signal is active_terminal
+ assert ctx.tool_blocker_signals == [budget, active_terminal]
+
+
def test_agent_context_and_copilot_context_blocker_signal_defaults_match() -> None:
"""The field is declared on both AgentContext (parent) and CopilotContext
(child) per the field-shadowing convention. Default values must stay in
diff --git a/tests/unit/test_copilot_completion_verification.py b/tests/unit/test_copilot_completion_verification.py
index 1239f6eaf..bbb3ccfd3 100644
--- a/tests/unit/test_copilot_completion_verification.py
+++ b/tests/unit/test_copilot_completion_verification.py
@@ -38,7 +38,12 @@ from skyvern.forge.sdk.copilot.enforcement import (
from skyvern.forge.sdk.copilot.hooks import _tool_completion_satisfies_turn
from skyvern.forge.sdk.copilot.request_policy import CompletionCriterion, RequestPolicy, _parse_completion_criteria
from skyvern.forge.sdk.copilot.tools import (
+ ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY,
+ _active_run_terminal_evidence_needs_visual_fallback,
+ _active_run_terminal_evidence_result,
+ _active_run_terminal_evidence_sample,
_build_run_evidence_snapshot,
+ _composition_visual_prompt,
_current_workflow_has_evidence_block,
_is_outcome_evidence_candidate,
_is_unfinished_run_verification_candidate,
@@ -48,7 +53,9 @@ from skyvern.forge.sdk.copilot.tools import (
_outcome_unverified_reason,
_record_composition_page_observation,
_record_run_blocks_result,
+ _tool_loop_error,
_tool_visible_result_after_completion_verification,
+ _watchdog_exit_allows_terminal_promotion,
)
@@ -152,6 +159,106 @@ def test_snapshot_has_evidence() -> None:
assert RunEvidenceSnapshot().has_evidence() is False
assert RunEvidenceSnapshot(current_url="https://example.com").has_evidence() is True
assert RunEvidenceSnapshot(block_outputs={"a": 1}).has_evidence() is True
+ assert RunEvidenceSnapshot(page_evidence={"visible_text_excerpt": "cart item PART-001-TEST"}).has_evidence() is True
+
+
+def test_snapshot_renders_bounded_page_evidence() -> None:
+ long_visible_text = "Footer recommendation " * 200
+ snapshot = RunEvidenceSnapshot(
+ workflow_run_id="wr_active",
+ current_url="https://example.com/cart",
+ page_title="Cart",
+ page_evidence={
+ "visible_text_excerpt": long_visible_text,
+ "visual_evidence_summary": "Screenshot shows the cart with TESTBRAND PART-001-TEST quantity 1.",
+ "screenshot_used": True,
+ "evidence_sources": ["dom_html", "screenshot", "vision_summary"],
+ "forms": [{"id": "checkout", "submit_controls": [{"text": "Checkout"}]}],
+ "result_containers": [{"selector": "#cart"}],
+ "anti_bot_indicators": [],
+ "raw_html": "<div>must not render</div>",
+ },
+ )
+
+ rendered = snapshot.render_prompt_block()
+
+ assert "page_evidence:" in rendered
+ assert "visible_text_excerpt" in rendered
+ assert "visual_evidence_summary" in rendered
+ assert "screenshot" in rendered
+ assert "PART-001-TEST" in rendered
+ assert rendered.index("visual_evidence_summary") < rendered.index("visible_text_excerpt")
+ assert "raw_html" not in rendered
+
+
+def test_active_run_terminal_visual_fallback_uses_screenshot_when_missing() -> None:
+ assert (
+ _active_run_terminal_evidence_needs_visual_fallback(
+ {
+ "visible_text_excerpt": "",
+ "forms": [],
+ "navigation_targets": [],
+ "result_containers": [],
+ "evidence_confidence": 0.1,
+ }
+ )
+ is True
+ )
+ assert (
+ _active_run_terminal_evidence_needs_visual_fallback(
+ {
+ "visible_text_excerpt": "Cart TESTBRAND PART-001-TEST quantity 1",
+ "forms": [],
+ "navigation_targets": [],
+ "result_containers": [],
+ "evidence_confidence": 0.1,
+ }
+ )
+ is True
+ )
+ assert (
+ _active_run_terminal_evidence_needs_visual_fallback(
+ {
+ "visible_text_excerpt": "Cart contains item PART-001-TEST with quantity 1. " * 4,
+ "forms": [],
+ "navigation_targets": [],
+ "result_containers": [],
+ "evidence_confidence": 0.1,
+ }
+ )
+ is True
+ )
+ assert (
+ _active_run_terminal_evidence_needs_visual_fallback(
+ {
+ "visible_text_excerpt": "",
+ "forms": [],
+ "navigation_targets": [],
+ "result_containers": [{"selector": "#cart"}],
+ "evidence_confidence": 0.3,
+ }
+ )
+ is True
+ )
+ assert (
+ _active_run_terminal_evidence_needs_visual_fallback(
+ {
+ "visible_text_excerpt": "Cart TESTBRAND PART-001-TEST quantity 1",
+ "result_containers": [{"selector": "#cart"}],
+ "screenshot_used": True,
+ }
+ )
+ is False
+ )
+
+
+def test_visual_prompt_requests_outcome_relevant_page_state() -> None:
+ prompt = _composition_visual_prompt({"current_url": "https://example.com/cart", "page_title": "Cart"})
+
+ assert "cart items" in prompt
+ assert "visible identifiers" in prompt
+ assert "quantities" in prompt
+ assert "human-verification" in prompt
def test_summarize_unsatisfied_lists_unmet_outcomes() -> None:
@@ -387,6 +494,12 @@ def test_current_workflow_has_evidence_block() -> None:
assert _current_workflow_has_evidence_block(_run_ctx()) is False
+def test_active_terminal_watchdog_exit_cannot_promote_to_terminal_success() -> None:
+ assert _watchdog_exit_allows_terminal_promotion("active_run_terminal_evidence") is False
+ assert _watchdog_exit_allows_terminal_promotion("per_tool_budget") is True
+ assert _watchdog_exit_allows_terminal_promotion("task_exit_unfinalized") is True
+
+
def test_outcome_failure_warrants_repair() -> None:
has_block = _ctx_with_blocks("extraction")
nav_only = _ctx_with_blocks("goto_url", "navigation")
@@ -460,6 +573,191 @@ async def test_maybe_run_completion_verification_runs_on_canceled_run(monkeypatc
assert result.is_fully_satisfied() is True
+async def test_maybe_run_completion_verification_skips_active_terminal_evidence(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def handler(**_: object) -> dict:
+ raise AssertionError("active-run terminal evidence must not be promoted to final success")
+
+ async def fake_completion_verification_handler(_ctx: object) -> object:
+ return handler
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools._completion_verification_handler",
+ fake_completion_verification_handler,
+ )
+ ctx = _run_ctx()
+ result = _canceled_budget_result()
+ result["data"]["active_run_terminal_evidence_detected"] = True
+
+ assert await _maybe_run_completion_verification(ctx, result, time.monotonic()) is None
+
+
+async def test_active_run_terminal_evidence_sample_matches_current_page(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ captured: dict[str, object] = {}
+
+ async def handler(**kwargs: object) -> dict:
+ captured.update(kwargs)
+ return {"verdicts": [{"criterion_id": "c0", "satisfied": True, "reason_code": "evidence_confirms"}]}
+
+ async def fake_fallback_page_info(_ctx: object) -> tuple[str, str]:
+ return "https://example.com/cart", "Cart"
+
+ async def fake_capture_composition_evidence(
+ _ctx: object,
+ *,
+ inspected_url: str,
+ current_url: str,
+ active_run_terminal_sample: bool = False,
+ ) -> tuple[dict, None]:
+ captured["active_run_terminal_sample"] = active_run_terminal_sample
+ return (
+ {
+ "inspected_url": inspected_url,
+ "current_url": current_url,
+ "page_title": "Cart",
+ "visible_text_excerpt": "Cart TESTBRAND PART-001-TEST quantity 1",
+ "forms": [],
+ "result_containers": [{"selector": "#cart"}],
+ "anti_bot_indicators": [],
+ },
+ None,
+ )
+
+ async def fake_completion_verification_handler(_ctx: object) -> object:
+ return handler
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools._completion_verification_handler",
+ fake_completion_verification_handler,
+ )
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._fallback_page_info", fake_fallback_page_info)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.tools._capture_composition_evidence",
+ fake_capture_composition_evidence,
+ )
+ ctx = _run_ctx()
+
+ sample = await _active_run_terminal_evidence_sample(
+ ctx,
+ workflow_run_id="wr_active",
+ labels_to_execute=["search_and_add"],
+ sample_index=1,
+ )
+
+ assert sample is not None
+ assert sample.completion_verification.is_fully_satisfied() is True
+ assert sample.current_url == "https://example.com/cart"
+ assert sample.page_evidence["observed_during_active_workflow_run"] is True
+ assert captured["active_run_terminal_sample"] is True
+ assert "PART-001-TEST" in str(captured["prompt"])
+
+
+async def test_active_run_terminal_evidence_sample_skips_method_only_criteria(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def handler(**_: object) -> dict:
+ raise AssertionError("method-mandated criteria cannot be verified from page state")
+
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._completion_verification_handler", lambda: handler)
+ ctx = _run_ctx()
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[_criterion("c0", "must use website search", method_mandated=True)]
+ )
+
+ assert (
+ await _active_run_terminal_evidence_sample(
+ ctx,
+ workflow_run_id="wr_active",
+ labels_to_execute=["search_and_add"],
+ sample_index=1,
+ )
+ is None
+ )
+
+
+def test_active_run_terminal_evidence_result_shape_is_not_final_success() -> None:
+ sample = SimpleNamespace(
+ current_url="https://example.com/cart",
+ page_title="Cart",
+ sample_index=2,
+ completion_verification=_evaluated(("c0", True)),
+ page_evidence={
+ "current_url": "https://example.com/cart",
+ "page_title": "Cart",
+ "visible_text_excerpt": "Cart TESTBRAND PART-001-TEST quantity 1",
+ },
+ )
+
+ result = _active_run_terminal_evidence_result(
+ workflow_run_id="wr_active",
+ run_status="running",
+ sample=sample,
+ requested_block_labels=["search_and_add"],
+ executed_block_labels=["search_and_add"],
+ )
+
+ assert result["ok"] is False
+ assert result["data"]["active_run_terminal_evidence_detected"] is True
+ assert result["data"]["full_workflow_verified"] is False
+ assert result["data"]["failure_categories"][0]["category"] == ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY
+
+
+def test_record_active_run_terminal_evidence_keeps_workflow_unverified() -> None:
+ sample = SimpleNamespace(
+ current_url="https://example.com/cart",
+ page_title="Cart",
+ sample_index=2,
+ completion_verification=_evaluated(("c0", True)),
+ page_evidence={
+ "current_url": "https://example.com/cart",
+ "page_title": "Cart",
+ "visible_text_excerpt": "Cart TESTBRAND PART-001-TEST quantity 1",
+ },
+ )
+ result = _active_run_terminal_evidence_result(
+ workflow_run_id="wr_active",
+ run_status="canceled",
+ sample=sample,
+ requested_block_labels=["search_and_add"],
+ executed_block_labels=["search_and_add"],
+ )
+ ctx = _run_ctx()
+
+ _record_run_blocks_result(ctx, result)
+
+ assert ctx.last_test_ok is False
+ assert ctx.last_full_workflow_test_ok is False
+ assert ctx.last_failure_category_top == ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY
+ assert ctx.workflow_verification_evidence.full_workflow_verified is False
+ assert ctx.workflow_verification_evidence.live_page_state_verified is True
+ assert ctx.workflow_verification_evidence.active_run_terminal_evidence_detected is True
+ assert ctx.workflow_verification_evidence.active_run_terminal_evidence_workflow_run_id == "wr_active"
+ assert ctx.workflow_verification_evidence.active_run_terminal_evidence_sample_index == 2
+ assert ctx.blocker_signal is not None
+ assert ctx.blocker_signal.internal_reason_code == "tool_error_active_run_terminal_evidence"
+
+
+def test_active_run_terminal_evidence_blocks_same_turn_mutation_tools() -> None:
+ ctx = _run_ctx()
+ ctx.last_failure_category_top = ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY
+ ctx.workflow_verification_evidence.active_run_terminal_evidence_detected = True
+ ctx.workflow_verification_evidence.current_url = "https://example.com/cart"
+ ctx.workflow_verification_evidence.workflow_run_id = "wr_active"
+
+ result = _tool_loop_error(ctx, "update_and_run_blocks", {"block_labels": ["search_and_add"]})
+
+ assert result is not None
+ assert "ACTIVE_RUN_TERMINAL_EVIDENCE" in result
+ assert ctx.blocker_signal is not None
+ assert ctx.blocker_signal.internal_reason_code == "tool_error_active_run_terminal_evidence"
+
+
def test_outcome_fully_verified_predicate(monkeypatch: pytest.MonkeyPatch) -> None:
ctx = _gate_ctx()
ctx.completion_verification_result = _evaluated(("c0", True))
diff --git a/tests/unit/test_copilot_diagnosis_repair_contract.py b/tests/unit/test_copilot_diagnosis_repair_contract.py
index db18714d3..d9e5c63b1 100644
--- a/tests/unit/test_copilot_diagnosis_repair_contract.py
+++ b/tests/unit/test_copilot_diagnosis_repair_contract.py
@@ -116,6 +116,37 @@ def test_repairable_block_failure_contract_is_queryable_and_safe() -> None:
assert "hunter2" not in contract.model_dump_json()
+def test_active_run_terminal_evidence_contract_stops_without_marking_workflow_success() -> None:
+ contract = build_diagnosis_repair_contract(
+ source_tool="update_and_run_blocks",
+ result={
+ "ok": False,
+ "error": "Active run terminal evidence was observed.",
+ "data": {
+ "workflow_run_id": "wr_active",
+ "overall_status": "canceled",
+ "active_run_terminal_evidence_detected": True,
+ "active_run_terminal_completion_verification": {
+ "status": "evaluated",
+ "criterion_count": 1,
+ "satisfied_count": 1,
+ "fully_satisfied": True,
+ "reason_codes": ["evidence_confirms"],
+ },
+ "failure_categories": [{"category": "ACTIVE_RUN_TERMINAL_EVIDENCE"}],
+ },
+ },
+ ctx=_ctx(),
+ workflow_updated=True,
+ )
+
+ assert contract.diagnosis_result.suspected_failure_type == DiagnosisFailureType.ACTIVE_RUN_TERMINAL_EVIDENCE
+ assert contract.repair_decision.next_action == RepairNextAction.STOP
+ assert contract.verification_result.user_goal_satisfied is True
+ assert contract.verification_result.completion_contract_satisfied is True
+ assert "not verified end-to-end" in contract.repair_decision.proposed_change_summary
+
+
def test_anti_bot_suspicious_success_contract_stops_instead_of_repairing() -> None:
ctx = _ctx()
ctx.last_test_suspicious_success = True
diff --git a/tests/unit/test_copilot_output_utils.py b/tests/unit/test_copilot_output_utils.py
index bd0574d6a..35d33f648 100644
--- a/tests/unit/test_copilot_output_utils.py
+++ b/tests/unit/test_copilot_output_utils.py
@@ -464,6 +464,55 @@ class TestFormatToolResultForUser:
agent_summary = summarize_tool_result("update_and_run_blocks", result)
assert "Do NOT start another block-running tool call" in agent_summary
+ def test_blocker_signal_does_not_reverse_match_unrelated_short_error(self) -> None:
+ from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal
+
+ signal = CopilotToolBlockerSignal(
+ blocker_kind="tool_error",
+ agent_steering_text="A long, specific blocker for an unrelated timeout.",
+ user_facing_reason="A specific timeout summary.",
+ recovery_hint="stop",
+ internal_reason_code="tool_error_specific_timeout",
+ blocked_tool="update_and_run_blocks",
+ )
+ result = {"ok": False, "error": "timeout"}
+
+ summary = format_tool_result_for_user("update_and_run_blocks", result, blocker_signal=signal)
+
+ assert summary != signal.user_facing_reason
+ assert summary == "Failed: timeout"
+
+ def test_active_terminal_blocker_matches_structured_failure_category(self) -> None:
+ from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal
+ from skyvern.forge.sdk.copilot.failure_tracking import (
+ ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY,
+ ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE,
+ )
+
+ signal = CopilotToolBlockerSignal(
+ blocker_kind="tool_error",
+ agent_steering_text="The prior active workflow run emitted typed terminal evidence.",
+ user_facing_reason="I reached the requested browser state, but the workflow still needs review.",
+ recovery_hint="report_blocker_to_user",
+ internal_reason_code=ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE,
+ blocked_tool="update_and_run_blocks",
+ )
+ result = {
+ "ok": False,
+ "error": "The active run reached the requested browser state.",
+ "data": {
+ "failure_categories": [
+ {"category": ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY, "confidence_float": 1.0}
+ ]
+ },
+ }
+
+ summary = format_tool_result_for_user("update_and_run_blocks", result, blocker_signal=signal)
+ detail = summarize_tool_result_detail(result, blocker_signal=signal)
+
+ assert summary == signal.user_facing_reason
+ assert detail == signal.user_facing_reason
+
def test_watchdog_control_signal_summary_overrides_raw_detail(self) -> None:
result = {
"ok": False,
diff --git a/tests/unit/test_copilot_per_tool_budget.py b/tests/unit/test_copilot_per_tool_budget.py
index c4cf8273c..8e596a7fe 100644
--- a/tests/unit/test_copilot_per_tool_budget.py
+++ b/tests/unit/test_copilot_per_tool_budget.py
@@ -36,6 +36,7 @@ from skyvern.forge.sdk.copilot.failure_tracking import (
compute_failure_signature,
)
from skyvern.forge.sdk.copilot.tools import (
+ ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY,
WatchdogExitReason,
_composition_anti_bot_reason,
_last_run_has_terminal_anti_bot_blocker,
@@ -200,6 +201,15 @@ def test_watchdog_user_failure_reason_excludes_next_tool_instruction() -> None:
assert "update_and_run_blocks" not in reason
+def test_watchdog_user_failure_reason_for_active_terminal_evidence_is_not_success() -> None:
+ exit_reason: WatchdogExitReason = "active_run_terminal_evidence"
+ reason = _watchdog_user_failure_reason(exit_reason, "wr_active", 240, None)
+
+ assert "requested browser state" in reason
+ assert "Full workflow verification is still required" in reason
+ assert "Run ID: wr_active" in reason
+
+
def test_record_clears_top_category_on_run_with_different_category() -> None:
ctx = _fresh_context()
ctx.last_failure_category_top = PER_TOOL_BUDGET_FAILURE_CATEGORY
@@ -438,6 +448,16 @@ def test_reconciliation_clears_for_per_tool_budget_even_on_canceled_status() ->
assert ctx.pending_reconciliation_run_id is None
+def test_reconciliation_clears_for_active_terminal_evidence_cancel() -> None:
+ ctx = _fresh_context()
+ ctx.pending_reconciliation_run_id = "wr_active"
+ ctx.last_failure_category_top = ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY
+
+ _maybe_clear_reconciliation_flag(ctx, _get_run_results_response("wr_active", "canceled"))
+
+ assert ctx.pending_reconciliation_run_id is None
+
+
def test_reconciliation_does_not_clear_for_non_budget_canceled() -> None:
"""Non-budget watchdog cancels keep the existing strict semantics:
``canceled`` is ambiguous and must not silently clear the guard."""