Skip to content

Automate browser based workflows with AI

Preserve Copilot drafts after build-test connection failures (SKY-15148) (#8350)

Andrew Neilsonf19c46700d7b
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.test.tsx
index 14b95d548..f0abc4fcf 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.test.tsx
@@ -189,6 +189,40 @@ describe("ReviewGateCard — untested proposals stay actionable", () => {
describe("ReviewGateCard — Test end-to-end recourse", () => {
const noop = () => {};
+ it("labels the typed connection-failure action as a fresh-session retry", () => {
+ render(
+ <ReviewGateCard
+ turn={turn({
+ proposalDisposition: "review_untested",
+ terminalEnvelope: {
+ runVerdict: null,
+ runDisplayReason: null,
+ connectFailure: {
+ state: "already_closed",
+ retryAction: "test_end_to_end",
+ workflowRunId: null,
+ workflowRunBlockId: null,
+ taskId: null,
+ browserSessionId: "pbs_1",
+ },
+ },
+ })}
+ pending
+ verdict="untested"
+ actionsEnabled
+ onAccept={noop}
+ onAlwaysAccept={noop}
+ onReject={noop}
+ onReview={noop}
+ onTestEndToEnd={noop}
+ />,
+ );
+
+ expect(
+ screen.getByRole("button", { name: "Retry in a fresh session" }),
+ ).not.toBeNull();
+ });
+
it("keeps Accept working on an untested proposal that never ran end-to-end", () => {
let accepted = 0;
render(
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx
index f8ab3ca32..3d204ab1d 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx
@@ -264,7 +264,9 @@ export function ReviewGateCard({
onClick={onTestEndToEnd}
className="rounded-md border border-border px-3 py-1.5 text-xs text-foreground hover:bg-slate-elevation4 dark:text-slate-200"
>
- Test end-to-end
+ {turn?.terminalEnvelope?.connectFailure
+ ? "Retry in a fresh session"
+ : "Test end-to-end"}
</button>
) : null}
{onTestEndToEnd ? (
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.runOutcome.test.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.runOutcome.test.ts
index 509539a0f..28dc3b7a0 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.runOutcome.test.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.runOutcome.test.ts
@@ -399,6 +399,7 @@ describe("hydrateNarrativeFromPayload — outcome", () => {
expect(withEnvelope.terminalEnvelope).toEqual({
runVerdict: "not_demonstrated",
runDisplayReason: "Checkout never reached confirmation.",
+ connectFailure: null,
});
const legacy = hydrateNarrativeFromPayload(payload([]))!;
@@ -411,7 +412,50 @@ describe("hydrateNarrativeFromPayload — outcome", () => {
expect(malformed.terminalEnvelope).toEqual({
runVerdict: null,
runDisplayReason: null,
+ connectFailure: null,
});
+
+ const typedConnect = hydrateNarrativeFromPayload({
+ ...payload([]),
+ terminalEnvelope: {
+ connect_failure: {
+ state: "already_closed",
+ retry_action: "test_end_to_end",
+ browser_session_id: "pbs_1",
+ },
+ },
+ })!;
+ expect(typedConnect.terminalEnvelope?.connectFailure).toEqual({
+ state: "already_closed",
+ retryAction: "test_end_to_end",
+ workflowRunId: null,
+ workflowRunBlockId: null,
+ taskId: null,
+ browserSessionId: "pbs_1",
+ });
+
+ const futureConnectState = hydrateNarrativeFromPayload({
+ ...payload([]),
+ terminalEnvelope: {
+ connect_failure: {
+ state: "future_manager_state",
+ retry_action: "test_end_to_end",
+ browser_session_id: "pbs_2",
+ },
+ },
+ })!;
+ expect(futureConnectState.terminalEnvelope?.connectFailure).toBeNull();
+
+ const missingRetryContract = hydrateNarrativeFromPayload({
+ ...payload([]),
+ terminalEnvelope: {
+ connect_failure: {
+ state: "already_closed",
+ browser_session_id: "pbs_3",
+ },
+ },
+ })!;
+ expect(missingRetryContract.terminalEnvelope?.connectFailure).toBeNull();
});
});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
index 73497b097..068a46019 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
@@ -150,9 +150,32 @@ export function humanizeJudgeText(text: string): string {
return stripJudgeInstruction(rewritten).replace(/ {2,}/g, " ").trim();
}
+type BuildTestConnectFailureState =
+ | "already_closed"
+ | "provisioning_unavailable"
+ | "cdp_connect_failed";
+
+function isBuildTestConnectFailureState(
+ value: unknown,
+): value is BuildTestConnectFailureState {
+ return (
+ value === "already_closed" ||
+ value === "provisioning_unavailable" ||
+ value === "cdp_connect_failed"
+ );
+}
+
export interface TerminalEnvelopeFacts {
runVerdict: BlockOutcome | null;
runDisplayReason: string | null;
+ connectFailure?: {
+ state: BuildTestConnectFailureState;
+ retryAction: "test_end_to_end";
+ workflowRunId: string | null;
+ workflowRunBlockId: string | null;
+ taskId: string | null;
+ browserSessionId: string | null;
+ } | null;
}
export type ReviewChange = "added" | "changed" | "unchanged" | "removed";
@@ -211,6 +234,29 @@ export function parseTerminalEnvelope(
if (!raw || typeof raw !== "object") return null;
const obj = raw as Record<string, unknown>;
const v = obj.run_verdict;
+ const rawConnectFailure = obj.connect_failure;
+ const connectFailure = (() => {
+ if (!rawConnectFailure || typeof rawConnectFailure !== "object")
+ return null;
+ const failure = rawConnectFailure as Record<string, unknown>;
+ const state = failure.state;
+ if (
+ !isBuildTestConnectFailureState(state) ||
+ failure.retry_action !== "test_end_to_end"
+ ) {
+ return null;
+ }
+ const text = (key: string) =>
+ typeof failure[key] === "string" ? (failure[key] as string) : null;
+ return {
+ state,
+ retryAction: "test_end_to_end" as const,
+ workflowRunId: text("workflow_run_id"),
+ workflowRunBlockId: text("workflow_run_block_id"),
+ taskId: text("task_id"),
+ browserSessionId: text("browser_session_id"),
+ };
+ })();
return {
runVerdict:
v === "demonstrated" || v === "not_demonstrated" || v === "not_evaluated"
@@ -220,6 +266,7 @@ export function parseTerminalEnvelope(
typeof obj.run_display_reason === "string"
? obj.run_display_reason
: null,
+ connectFailure,
};
}
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index d2ec4f14f..b173324d3 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -49,6 +49,7 @@ from skyvern.forge.sdk.copilot.browser_ablation import (
config_for_eval_mode,
resolve_copilot_tool_surface,
)
+from skyvern.forge.sdk.copilot.build_test_connect_failure import BuildTestConnectFailure
from skyvern.forge.sdk.copilot.build_test_outcome import (
_TEXT_MAX,
_VALUE_EXCERPT_MAX,
@@ -1505,6 +1506,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"
+ connect_failure = _terminal_connect_failure(ctx)
+ if connect_failure is not None:
+ return connect_failure.state
failed_operation = _terminal_failed_operation(ctx)
if failed_operation is not None:
return failed_operation.kind
@@ -1613,6 +1617,11 @@ def _terminal_failed_operation(
return outcome.failed_operation if isinstance(outcome, RecordedBuildTestOutcome) else None
+def _terminal_connect_failure(ctx: CopilotContext) -> BuildTestConnectFailure | None:
+ outcome = ctx.latest_recorded_build_test_outcome
+ return outcome.connect_failure if isinstance(outcome, RecordedBuildTestOutcome) else None
+
+
def _assemble_terminal_envelope_safe(
*,
response_type: str,
@@ -1629,6 +1638,7 @@ def _assemble_terminal_envelope_safe(
terminal_cause: TerminalCause | None = None,
blocks_run_this_turn: int | None = None,
failed_operation: BuildTestFailedOperation | None = None,
+ connect_failure: BuildTestConnectFailure | None = None,
proposal_present: bool = False,
) -> dict[str, Any] | None:
try:
@@ -1646,6 +1656,7 @@ def _assemble_terminal_envelope_safe(
terminal_cause=terminal_cause,
blocks_run_this_turn=blocks_run_this_turn,
failed_operation=failed_operation,
+ connect_failure=connect_failure,
proposal_present=proposal_present,
)
except Exception:
@@ -1753,7 +1764,8 @@ def _make_agent_result(
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":
+ connect_failure = _terminal_connect_failure(ctx) if ctx is not None else None
+ if (failed_operation is not None or connect_failure 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):
@@ -1873,9 +1885,12 @@ def _make_agent_result(
terminal_cause=terminal_cause,
blocks_run_this_turn=len(ctx.executed_block_labels),
failed_operation=failed_operation,
+ connect_failure=connect_failure,
proposal_present=result_carries_workflow,
)
- if terminal_envelope is not None and terminal_envelope.get("failed_operation") is not None:
+ if terminal_envelope is not None and (
+ terminal_envelope.get("failed_operation") is not None or terminal_envelope.get("connect_failure") is not None
+ ):
envelope = TerminalOutcomeEnvelope.model_validate(terminal_envelope)
terminal_message, replaced = render_terminal_message(
envelope,
diff --git a/skyvern/forge/sdk/copilot/build_test_connect_failure.py b/skyvern/forge/sdk/copilot/build_test_connect_failure.py
new file mode 100644
index 000000000..2f88282b9
--- /dev/null
+++ b/skyvern/forge/sdk/copilot/build_test_connect_failure.py
@@ -0,0 +1,20 @@
+from __future__ import annotations
+
+from typing import Literal
+
+from pydantic import BaseModel, ConfigDict
+
+BuildTestConnectFailureState = Literal["already_closed", "provisioning_unavailable", "cdp_connect_failed"]
+
+
+class BuildTestConnectFailure(BaseModel):
+ """Typed browser-acquisition stop and only the identities created before it."""
+
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ state: BuildTestConnectFailureState
+ workflow_run_id: str | None = None
+ workflow_run_block_id: str | None = None
+ task_id: str | None = None
+ browser_session_id: str | None = None
+ retry_action: Literal["test_end_to_end"] = "test_end_to_end"
diff --git a/skyvern/forge/sdk/copilot/build_test_outcome.py b/skyvern/forge/sdk/copilot/build_test_outcome.py
index 166db9170..9f477e99f 100644
--- a/skyvern/forge/sdk/copilot/build_test_outcome.py
+++ b/skyvern/forge/sdk/copilot/build_test_outcome.py
@@ -13,6 +13,7 @@ import structlog
import yaml
from pydantic import BaseModel, ConfigDict, Field, JsonValue, field_validator, model_validator
+from skyvern.forge.sdk.copilot.build_test_connect_failure import BuildTestConnectFailure
from skyvern.forge.sdk.copilot.challenge_evidence import (
carrier_backed_anti_bot_categories,
interactive_challenge_controls,
@@ -265,6 +266,7 @@ class BuildTestPacketFailure(BaseModel):
error_codes: list[str] = Field(default_factory=list)
failing_line: int | None = None
failed_operation: BuildTestFailedOperation | None = None
+ connect_failure: BuildTestConnectFailure | None = None
action_trace: list[str] = Field(default_factory=list)
page_state: BuildTestPacketPageState | None = None
locator_observations: list[BuildTestPacketLocatorObservation] = Field(default_factory=list)
@@ -384,6 +386,7 @@ class RecordedBuildTestOutcome(BaseModel):
code_safety_rejection_facts: list[CodeSafetyRejectionFact] = Field(default_factory=list)
page_path_failure: PostRunPagePathFailure | None = None
failed_operation: BuildTestFailedOperation | None = None
+ connect_failure: BuildTestConnectFailure | 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)
@@ -456,7 +459,7 @@ class _RecordedBuildTestOutcomeContext(Protocol):
def record_build_test_outcome(ctx: _RecordedBuildTestOutcomeContext, outcome: RecordedBuildTestOutcome | None) -> None:
if outcome is None:
latest = getattr(ctx, "latest_recorded_build_test_outcome", None)
- if latest is None or latest.failed_operation is None:
+ if latest is None or (latest.failed_operation is None and latest.connect_failure is None):
ctx.latest_recorded_build_test_outcome = None
return
prior = getattr(ctx, "latest_recorded_build_test_outcome", None)
@@ -520,6 +523,9 @@ def record_build_test_outcome(ctx: _RecordedBuildTestOutcomeContext, outcome: Re
"failed_operation": (
outcome.failed_operation.model_dump(mode="json") if outcome.failed_operation is not None else None
),
+ "connect_failure": (
+ outcome.connect_failure.model_dump(mode="json") if outcome.connect_failure is not None else None
+ ),
"failed_operation_call_signature": outcome.failed_operation_call_signature,
}
)
@@ -1074,6 +1080,20 @@ def recorded_outcome_from_run_blocks_result(
if isinstance(requested, list)
else []
)
+ connect_failure = connect_failure_from_run_blocks_result(result)
+ if connect_failure is not None:
+ return RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ attempted_tool="update_and_run_blocks",
+ verdict="not_authoritative",
+ reason_code="unrecoverable_tool_error",
+ workflow_run_id=connect_failure.workflow_run_id,
+ requested_block_labels=requested_block_labels,
+ structural_failure_identity=f"build_test_connect:{connect_failure.state}",
+ connect_failure=connect_failure,
+ observed_evidence_summary=f"Build-test browser acquisition stopped: {connect_failure.state}.",
+ key_provenance={"structural_failure_identity": "typed build-test browser acquisition fact"},
+ )
executed_block_labels = _clean_list(
[
redacted
@@ -1461,6 +1481,17 @@ def failed_operation_from_run_blocks_result(
)
+def connect_failure_from_run_blocks_result(result: Mapping[str, object]) -> BuildTestConnectFailure | None:
+ data = _dict(result.get("data"))
+ payload = data.get("build_test_connect_failure")
+ if not isinstance(payload, Mapping):
+ return None
+ try:
+ return BuildTestConnectFailure.model_validate(payload)
+ except ValueError:
+ return None
+
+
def _stable_hash(payload: object) -> str:
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
diff --git a/skyvern/forge/sdk/copilot/output_utils.py b/skyvern/forge/sdk/copilot/output_utils.py
index 77e1965ff..3363e3613 100644
--- a/skyvern/forge/sdk/copilot/output_utils.py
+++ b/skyvern/forge/sdk/copilot/output_utils.py
@@ -14,6 +14,7 @@ import structlog
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.build_test_connect_failure import BuildTestConnectFailure
from skyvern.forge.sdk.copilot.build_test_outcome import (
_TEXT_MAX,
BuildTestEvidencePacket,
@@ -363,6 +364,42 @@ def _bounded_failed_operation(
)
+def _bounded_connect_failure(
+ failure: BuildTestConnectFailure | None,
+ notices: list[str],
+) -> BuildTestConnectFailure | None:
+ if failure is None:
+ return None
+ return failure.model_copy(
+ update={
+ "workflow_run_id": _bounded_packet_string(
+ failure.workflow_run_id,
+ field_name="failure.connect_failure.workflow_run_id",
+ max_chars=_BUILD_TEST_IDENTIFIER_MAX_CHARS,
+ notices=notices,
+ ),
+ "workflow_run_block_id": _bounded_packet_string(
+ failure.workflow_run_block_id,
+ field_name="failure.connect_failure.workflow_run_block_id",
+ max_chars=_BUILD_TEST_IDENTIFIER_MAX_CHARS,
+ notices=notices,
+ ),
+ "task_id": _bounded_packet_string(
+ failure.task_id,
+ field_name="failure.connect_failure.task_id",
+ max_chars=_BUILD_TEST_IDENTIFIER_MAX_CHARS,
+ notices=notices,
+ ),
+ "browser_session_id": _bounded_packet_string(
+ failure.browser_session_id,
+ field_name="failure.connect_failure.browser_session_id",
+ max_chars=_BUILD_TEST_IDENTIFIER_MAX_CHARS,
+ notices=notices,
+ ),
+ }
+ )
+
+
def _bounded_obstruction_control(
control: PageObstructionControl,
*,
@@ -894,6 +931,7 @@ def project_build_test_packet_for_llm(packet: BuildTestEvidencePacket) -> BuildT
notices=notices,
),
"failed_operation": _bounded_failed_operation(failure.failed_operation, notices),
+ "connect_failure": _bounded_connect_failure(failure.connect_failure, 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 bbc1e6599..8f1a875b6 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -30,6 +30,7 @@ from skyvern.cli.core.session_manager import (
)
from skyvern.config import settings
from skyvern.forge import app
+from skyvern.forge.sdk.copilot.build_test_connect_failure import BuildTestConnectFailure
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
from skyvern.forge.sdk.copilot.screenshot_utils import PendingFrameLease, ScreenshotEntry
from skyvern.forge.sdk.copilot.tracing_setup import copilot_span
@@ -43,6 +44,7 @@ from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerification
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.schemas.credentials import Credential
from skyvern.library.skyvern_browser import SkyvernBrowser
+from skyvern.webeye.browser_errors import BrowserCdpConnectionError, BrowserTargetClosedError
from skyvern.webeye.browser_state import BrowserState
if TYPE_CHECKING:
@@ -1072,15 +1074,32 @@ async def _drop_browser_session_id_at_its_fixed_deadline(ctx: AgentContext) -> N
retire_browser_session_id(ctx, session_id)
-async def ensure_browser_session(ctx: AgentContext) -> dict[str, Any] | None:
- """Create a browser session if the context holds none. Returns None on success, error dict on failure.
+def _build_test_connect_failure_result(failure: BuildTestConnectFailure) -> dict[str, Any]:
+ return {
+ "ok": False,
+ "error": f"Build-test browser acquisition stopped: {failure.state}.",
+ "data": {
+ "overall_status": "setup_failed",
+ "failure_reason": f"Build-test browser acquisition stopped: {failure.state}.",
+ "browser_session_id": failure.browser_session_id,
+ "build_test_connect_failure": failure.model_dump(mode="json", exclude_none=True),
+ "blocks": [],
+ },
+ }
+
+
+async def _provision_browser_session(ctx: AgentContext) -> BuildTestConnectFailure | None:
+ """Create a browser session if the context holds none.
+
+ Returns an immutable acquisition fact on failure and ``None`` on success. Generic callers
+ translate that fact back to their established error shape; build-test callers retain it.
An existing id is not probed here: the attach in mcp_browser_context is the oracle, and a
session it finds gone is retired and replaced where that is discovered. The one thing the
attach cannot see is a deadline landing mid-call, which is read from the manager instead.
Exception: the self-heal path raises HealAdoptionFailed instead of returning an
- error dict, so a failed adoption aborts the turn rather than degrading to a normal
+ failure fact, so a failed adoption aborts the turn rather than degrading to a normal
tool-level error. Callers must let it propagate.
"""
if ctx.turn_origin == TurnOrigin.runtime_self_heal:
@@ -1167,7 +1186,23 @@ async def ensure_browser_session(ctx: AgentContext) -> dict[str, Any] | None:
# flows back through the tool/agent path and could end up in
# LLM-visible or user-visible output, so strip raw exception text
# that may carry internal URLs, paths, or backend identifiers.
- return {"ok": False, "error": "Failed to create browser session"}
+ failed_session_id = session.persistent_browser_session_id if session is not None else installed_session_id
+ return BuildTestConnectFailure(
+ state="provisioning_unavailable",
+ browser_session_id=failed_session_id,
+ )
+
+
+async def ensure_browser_session(ctx: AgentContext) -> dict[str, Any] | None:
+ failure = await _provision_browser_session(ctx)
+ if failure is None:
+ return None
+ return {"ok": False, "error": "Failed to create browser session"}
+
+
+async def ensure_build_test_browser_session(ctx: AgentContext) -> dict[str, Any] | None:
+ failure = await _provision_browser_session(ctx)
+ return None if failure is None else _build_test_connect_failure_result(failure)
async def verify_browser_session_by_attaching(ctx: AgentContext) -> dict[str, Any] | None:
@@ -1205,3 +1240,45 @@ async def verify_browser_session_by_attaching(ctx: AgentContext) -> dict[str, An
),
"probe_error_type": type(exc).__name__,
}
+
+
+async def verify_build_test_browser_session_by_attaching(ctx: AgentContext) -> dict[str, Any] | None:
+ """Attach once for a build test; report supported acquisition state without replacing it."""
+ await _drop_browser_session_id_at_its_fixed_deadline(ctx)
+ if not ctx.browser_session_id:
+ return await ensure_build_test_browser_session(ctx)
+ examined_session_id = ctx.browser_session_id
+ try:
+ async with mcp_browser_context(ctx):
+ return None
+ except CopilotBrowserSessionUnavailable:
+ retire_browser_session_id(ctx, examined_session_id)
+ return _build_test_connect_failure_result(
+ BuildTestConnectFailure(state="already_closed", browser_session_id=examined_session_id)
+ )
+ except BrowserTargetClosedError:
+ retire_browser_session_id(ctx, examined_session_id)
+ return _build_test_connect_failure_result(
+ BuildTestConnectFailure(state="already_closed", browser_session_id=examined_session_id)
+ )
+ except BrowserCdpConnectionError:
+ # A failed attach does not prove the remote session is dead; keep its id as
+ # evidence and let the explicit fresh-session action choose replacement.
+ return _build_test_connect_failure_result(
+ BuildTestConnectFailure(state="cdp_connect_failed", browser_session_id=examined_session_id)
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ LOG.warning(
+ "Build-test browser attach could not be classified",
+ session_id=examined_session_id,
+ organization_id=ctx.organization_id,
+ error_type=type(exc).__name__,
+ exc_info=True,
+ )
+ return {
+ "ok": False,
+ "error": "The build-test browser attach could not be classified.",
+ "probe_error_type": type(exc).__name__,
+ }
diff --git a/skyvern/forge/sdk/copilot/terminal_envelope.py b/skyvern/forge/sdk/copilot/terminal_envelope.py
index be87b4dd2..84d7e5cf7 100644
--- a/skyvern/forge/sdk/copilot/terminal_envelope.py
+++ b/skyvern/forge/sdk/copilot/terminal_envelope.py
@@ -6,13 +6,21 @@ from typing import Literal
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_connect_failure import BuildTestConnectFailure
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", "browser_operation_failed"]
+TerminalCause = Literal[
+ "deadline_expired",
+ "max_turns_exceeded",
+ "browser_operation_failed",
+ "already_closed",
+ "provisioning_unavailable",
+ "cdp_connect_failed",
+]
_FINAL_RUN_VERDICTS = frozenset({"not_demonstrated", "not_evaluated"})
_REVIEW_PROPOSAL_DISPOSITIONS = frozenset({"review_untested", "review_tested"})
_SHADOW_REASON_TRAILING_PUNCTUATION = ".,;:!?"
@@ -57,6 +65,7 @@ class TerminalOutcomeEnvelope(BaseModel):
response_kind: TerminalResponseKind
terminal_cause: TerminalCause | None = None
failed_operation: BuildTestFailedOperation | None = None
+ connect_failure: BuildTestConnectFailure | None = None
proposal_present: bool = False
interruption: InterruptedTurnFacts | None = None
rendered_from_envelope: bool = False
@@ -64,7 +73,7 @@ class TerminalOutcomeEnvelope(BaseModel):
@model_validator(mode="after")
def normalize_failed_operation_state(self) -> TerminalOutcomeEnvelope:
- if self.failed_operation is not None:
+ if self.failed_operation is not None or self.connect_failure is not None:
self.verified = False
self.workflow_applied = False
return self
@@ -85,6 +94,7 @@ def assemble_terminal_envelope(
terminal_cause: TerminalCause | None = None,
blocks_run_this_turn: int | None = None,
failed_operation: BuildTestFailedOperation | None = None,
+ connect_failure: BuildTestConnectFailure | None = None,
proposal_present: bool = False,
) -> TerminalOutcomeEnvelope | None:
run_outcome = select_run_outcome_anchor(run_outcomes)
@@ -96,7 +106,7 @@ 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:
+ if failed_operation is not None or connect_failure is not None:
verified = False
workflow_applied = False
next_state = _derive_next_state(
@@ -117,6 +127,15 @@ def assemble_terminal_envelope(
next_state = "stopped"
response_kind = "stopped"
terminal_cause = terminal_cause or failed_operation.kind
+ if connect_failure is not None:
+ if not user_action_required:
+ next_state = "stopped"
+ response_kind = "stopped"
+ # Capacity is turn-level evidence and remains authoritative. Otherwise the
+ # later acquisition failure owns the user-facing terminal over an older
+ # operation failure retained from an earlier build test in the same turn.
+ if terminal_cause not in {"deadline_expired", "max_turns_exceeded"}:
+ terminal_cause = connect_failure.state
return TerminalOutcomeEnvelope(
next_state=next_state,
verified=verified,
@@ -134,6 +153,7 @@ def assemble_terminal_envelope(
response_kind=response_kind,
terminal_cause=terminal_cause,
failed_operation=failed_operation,
+ connect_failure=connect_failure,
proposal_present=proposal_present,
)
@@ -141,7 +161,7 @@ def assemble_terminal_envelope(
def finalize_applied_state(
envelope: TerminalOutcomeEnvelope, *, applied: bool, proposal_present: bool = False
) -> TerminalOutcomeEnvelope:
- if envelope.failed_operation is not None:
+ if envelope.failed_operation is not None or envelope.connect_failure is not None:
if envelope.user_action_required:
return envelope.model_copy(
update={
@@ -213,6 +233,31 @@ 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.connect_failure is not None
+ and envelope.terminal_cause == envelope.connect_failure.state
+ and not cancelled
+ ):
+ failure = envelope.connect_failure
+ message = f"Build testing stopped with browser connection state `{failure.state}`."
+ identities = [
+ ("workflow run", failure.workflow_run_id),
+ ("child run", failure.workflow_run_block_id),
+ ("task", failure.task_id),
+ ("browser session", failure.browser_session_id),
+ ]
+ for label, identity in identities:
+ if identity:
+ message = _append_sentence(message, f"Recorded {label}: {identity}.")
+ if envelope.proposal_present:
+ message = _append_sentence(message, "The untested draft was preserved for review.")
+ message = _append_sentence(message, "Retry in a fresh browser session to test this same draft.")
+ if envelope.user_action_required:
+ pending_question_intro = "The pending question is quoted below; its premise is not confirmed"
+ 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
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:
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index b188b390e..412a5e450 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -46,6 +46,7 @@ from skyvern.forge.sdk.copilot.build_test_outcome import (
RecordedBuildTestOutcome,
authored_block_parameter_keys_from_workflow,
authored_structure_signature_from_workflow,
+ connect_failure_from_run_blocks_result,
failed_operation_from_run_blocks_result,
post_run_page_capture_from_result,
record_build_test_outcome,
@@ -122,11 +123,11 @@ from skyvern.forge.sdk.copilot.runtime import (
RegisteredArtifactEntry,
RegisteredArtifactEvidence,
browser_page_custody_lock,
- ensure_browser_session,
+ ensure_build_test_browser_session,
register_sensitive_origin_run_lease,
release_sensitive_origin_run_lease,
resolve_persistent_browser_state,
- verify_browser_session_by_attaching,
+ verify_build_test_browser_session_by_attaching,
)
from skyvern.forge.sdk.copilot.runtime_authoring_repair import (
build_test_page_state_from_evidence,
@@ -2272,6 +2273,26 @@ def _credit_composition_verified_labels(
ctx.composition_verified_labels = workflow_labels[: max(end, len(credited))]
+async def acquire_build_test_browser_session(ctx: CopilotContext, *, fresh: bool) -> dict[str, Any] | None:
+ """The single initial-acquisition seam used by every build-test run."""
+ if fresh:
+ return await ensure_build_test_browser_session(ctx)
+ return await verify_build_test_browser_session_by_attaching(ctx)
+
+
+def _with_build_test_acquisition_context(
+ result: dict[str, Any], *, requested_block_labels: Sequence[str], fresh: bool
+) -> dict[str, Any]:
+ data = result.get("data")
+ if not isinstance(data, dict):
+ data = {}
+ result["data"] = data
+ data["requested_block_labels"] = list(requested_block_labels)
+ data["executed_block_labels"] = []
+ data["used_fresh_run_session"] = fresh
+ return result
+
+
async def run_workflow_end_to_end(ctx: CopilotContext, workflow_yaml: str) -> dict[str, Any]:
"""Run every block of a candidate workflow in one browser minted for this run. Frontier
selection is bypassed and the provenance stamped so a clean result earns composition credit
@@ -2585,10 +2606,10 @@ async def _run_blocks_and_collect_debug(
# keeps it; the fresh id is threaded into the run calls explicitly.
debug_session_id = ctx.browser_session_id
ctx.browser_session_id = None
- session_err = await ensure_browser_session(ctx)
+ session_err = await acquire_build_test_browser_session(ctx, fresh=True)
if session_err is not None:
ctx.browser_session_id = debug_session_id
- return session_err
+ return _with_build_test_acquisition_context(session_err, requested_block_labels=block_labels, fresh=True)
run_session_id = ctx.browser_session_id
ctx.browser_session_id = debug_session_id
used_fresh_run_session = True
@@ -2616,9 +2637,9 @@ async def _run_blocks_and_collect_debug(
else:
# This id is dispatched into a workflow run without ever being attached here, so an
# unverified session cannot be discovered later and must fail now instead.
- session_err = await verify_browser_session_by_attaching(ctx)
+ session_err = await acquire_build_test_browser_session(ctx, fresh=False)
if session_err is not None:
- return session_err
+ return _with_build_test_acquisition_context(session_err, requested_block_labels=block_labels, fresh=False)
run_session_id = ctx.browser_session_id
seeded_runtime_workflow = await _workflow_with_runtime_frontier_starter_url_seed(
@@ -4850,6 +4871,11 @@ 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:
+ connect_failure = (
+ recorded_outcome.connect_failure
+ if recorded_outcome is not None
+ else connect_failure_from_run_blocks_result(result)
+ )
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:
@@ -4891,6 +4917,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,
+ connect_failure=connect_failure,
action_trace=action_trace,
page_state=page_state,
locator_observations=_packet_locator_observations(data, omission_notices),
diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.py
index 8b7cf24b8..7d542596b 100644
--- a/skyvern/forge/sdk/routes/workflow_copilot.py
+++ b/skyvern/forge/sdk/routes/workflow_copilot.py
@@ -440,8 +440,8 @@ def _effective_auto_accept(auto_accept: bool | None, agent_result: object | None
the review gate.
"""
terminal_envelope = getattr(agent_result, "terminal_envelope", None)
- unresolved_failed_operation = (
- isinstance(terminal_envelope, dict) and terminal_envelope.get("failed_operation") is not None
+ unresolved_failed_operation = isinstance(terminal_envelope, dict) and (
+ terminal_envelope.get("failed_operation") is not None or terminal_envelope.get("connect_failure") is not None
)
if (
getattr(agent_result, "cancelled", False) is True
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index f5d99958a..3bdedd66f 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -4317,7 +4317,7 @@ class TestRunBlocksCredentialApproval:
SimpleNamespace(get_workflow_parameters=AsyncMock(return_value=[])),
)
monkeypatch.setattr(workflow_service_module, "prepare_workflow", prepare_workflow)
- monkeypatch.setattr(run_execution_module, "ensure_browser_session", never_mint)
+ monkeypatch.setattr(run_execution_module, "acquire_build_test_browser_session", never_mint)
ctx = _ctx(browser_session_id="pbs_chat")
ctx.frontier_resume_session_id = "pbs_carried"
@@ -4362,7 +4362,7 @@ class TestRunBlocksCredentialApproval:
SimpleNamespace(get_workflow_parameters=AsyncMock(return_value=[])),
)
monkeypatch.setattr(workflow_service_module, "prepare_workflow", prepare_workflow)
- monkeypatch.setattr(run_execution_module, "ensure_browser_session", never_mint)
+ monkeypatch.setattr(run_execution_module, "acquire_build_test_browser_session", never_mint)
ctx = _ctx(browser_session_id=None)
ctx.frontier_resume_session_id = "pbs_carried"
diff --git a/tests/unit/test_copilot_build_test_outcome.py b/tests/unit/test_copilot_build_test_outcome.py
index d8ab5a575..0a5a66693 100644
--- a/tests/unit/test_copilot_build_test_outcome.py
+++ b/tests/unit/test_copilot_build_test_outcome.py
@@ -18,6 +18,7 @@ from skyvern.forge.sdk.copilot.agent import (
_recorded_build_test_outcome_prompt,
)
from skyvern.forge.sdk.copilot.build_test_outcome import (
+ BuildTestConnectFailure,
BuildTestEvidencePacket,
BuildTestFailedOperation,
BuildTestPacketDownload,
@@ -63,6 +64,7 @@ from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, Paramet
from skyvern.webeye.browser_artifacts import BrowserArtifacts
from tests.unit.copilot_test_helpers import (
failed_second_factor_run,
+ make_copilot_ctx,
make_stub_html_artifact,
passing_run,
straight_line_login_yaml,
@@ -117,6 +119,65 @@ def test_run_blocks_outcome_records_requested_labels_and_shape_hashes() -> None:
assert outcome.block_shape_hashes == {"open": "h1", "search": "h2", "extract": "h3"}
+def test_connect_failure_projects_through_recorded_outcome_and_packet() -> None:
+ ctx = make_copilot_ctx()
+ ctx.workflow_yaml = "title: preserved draft"
+ ctx.staged_workflow_yaml = "title: preserved draft"
+ ctx.last_workflow_yaml = "title: preserved draft"
+ failure = BuildTestConnectFailure(
+ state="cdp_connect_failed",
+ workflow_run_id="wr_1",
+ workflow_run_block_id="wrb_1",
+ task_id="tsk_1",
+ browser_session_id="pbs_1",
+ )
+ result = {
+ "ok": False,
+ "error": "Build-test browser acquisition stopped: cdp_connect_failed.",
+ "data": {
+ "workflow_run_id": "wr_1",
+ "overall_status": "setup_failed",
+ "browser_session_id": "pbs_1",
+ "requested_block_labels": ["open"],
+ "executed_block_labels": [],
+ "blocks": [],
+ "build_test_connect_failure": failure.model_dump(mode="json"),
+ },
+ }
+
+ outcome = recorded_outcome_from_run_blocks_result(result)
+ assert outcome is not None
+ assert outcome.connect_failure == failure
+ packet = build_test_evidence_packet(ctx, result, recorded_outcome=outcome)
+ assert packet.failure is not None
+ assert packet.failure.connect_failure == failure
+ assert packet.canonical_workflow_yaml == "title: preserved draft"
+
+
+def test_connect_failure_clears_when_a_later_real_run_records_recovery() -> None:
+ ctx = _run_history_ctx(two_page_login_yaml())
+ connect_failure = RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ attempted_tool="update_and_run_blocks",
+ verdict="not_authoritative",
+ reason_code="unrecoverable_tool_error",
+ workflow_run_id="wr_failed_connect",
+ structural_failure_identity="build_test_connect:cdp_connect_failed",
+ connect_failure=BuildTestConnectFailure(
+ state="cdp_connect_failed",
+ browser_session_id="pbs_failed_connect",
+ ),
+ )
+
+ record_build_test_outcome(ctx, connect_failure)
+ record_build_test_outcome(ctx, passing_run("wr_recovered", ["sign_in_and_read"]))
+
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.workflow_run_id == "wr_recovered"
+ assert ctx.latest_recorded_build_test_outcome.connect_failure is None
+ assert ctx.recorded_build_test_outcome_history[-1]["connect_failure"] is None
+
+
def _failed_run_result_with_categories(categories: list[dict]) -> dict:
return {
"ok": False,
@@ -3466,6 +3527,39 @@ def test_browser_operation_identity_is_bounded_by_the_shared_packet_projection()
assert any("failure.failed_operation.block_label shortened" in notice for notice in projected.omission_notices)
+def test_connect_failure_identity_is_bounded_by_the_shared_packet_projection() -> None:
+ long_identity = "x" * 200
+ result = {
+ "ok": False,
+ "data": {
+ "overall_status": "setup_failed",
+ "blocks": [],
+ "build_test_connect_failure": BuildTestConnectFailure(
+ state="cdp_connect_failed",
+ workflow_run_id=long_identity,
+ workflow_run_block_id=long_identity,
+ task_id=long_identity,
+ browser_session_id=long_identity,
+ ).model_dump(mode="json"),
+ },
+ }
+
+ projected = project_build_test_packet_for_llm(build_test_evidence_packet(_locator_packet_ctx(), result))
+
+ assert projected.failure is not None
+ assert projected.failure.connect_failure is not None
+ failure = projected.failure.connect_failure
+ identities = (
+ failure.workflow_run_id,
+ failure.workflow_run_block_id,
+ failure.task_id,
+ failure.browser_session_id,
+ )
+ assert all(len(identity or "") == 160 for identity in identities)
+ assert all((identity or "").endswith("...") for identity in identities)
+ assert sum("failure.connect_failure" in notice for notice in projected.omission_notices) == 4
+
+
def test_browser_operation_packet_names_each_unavailable_operation_identity() -> None:
result = _failed_run_result(None)
data = result["data"]
diff --git a/tests/unit/test_copilot_make_agent_result_backfill.py b/tests/unit/test_copilot_make_agent_result_backfill.py
index 79184a9ab..16f1fc41f 100644
--- a/tests/unit/test_copilot_make_agent_result_backfill.py
+++ b/tests/unit/test_copilot_make_agent_result_backfill.py
@@ -13,6 +13,7 @@ from skyvern.forge.sdk.copilot.agent import (
_terminal_failed_operation,
)
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal, contains_internal_machinery_leak
+from skyvern.forge.sdk.copilot.build_test_connect_failure import BuildTestConnectFailure
from skyvern.forge.sdk.copilot.build_test_outcome import (
BuildTestFailedOperation,
RecordedBuildTestOutcome,
@@ -214,6 +215,52 @@ def test_recorded_browser_operation_failure_overrides_success_prose_but_keeps_dr
assert result.narrative_payload["turnFacts"]["ranCleanOnCurrentSource"] is False
+def test_later_connect_failure_owns_terminal_copy_over_failed_operation() -> None:
+ ctx = _ctx()
+ failed_operation = BuildTestFailedOperation(
+ kind="browser_operation_failed",
+ workflow_run_id="wr_failed_operation",
+ workflow_run_block_id="wrb_failed_operation",
+ block_label="collect_failure_rate",
+ failing_line=11,
+ )
+ connect_failure = BuildTestConnectFailure(
+ state="cdp_connect_failed",
+ browser_session_id="pbs_connect_failure",
+ )
+ 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_failed_operation",
+ structural_failure_identity="browser-operation",
+ failed_operation=failed_operation,
+ connect_failure=connect_failure,
+ ),
+ )
+
+ result = _result(
+ ctx,
+ user_response="The code run failed.",
+ updated_workflow=SimpleNamespace(name="untested draft"),
+ workflow_yaml=two_page_login_yaml(),
+ proposal_disposition="review_untested",
+ turn_outcome=_outcome(ResponseKind.BUILD),
+ narrative_payload=_payload(),
+ )
+
+ assert result.terminal_envelope is not None
+ assert result.terminal_envelope["terminal_cause"] == "cdp_connect_failed"
+ assert "cdp_connect_failed" in result.user_response
+ assert "fresh browser session" in result.user_response
+ assert result.narrative_payload is not None
+ assert result.narrative_payload["turnFacts"]["terminalCause"] == "cdp_connect_failed"
+
+
def test_recorded_browser_operation_failure_survives_later_non_clearing_outcome() -> None:
ctx = _ctx()
failed_operation = BuildTestFailedOperation(
diff --git a/tests/unit/test_copilot_runtime.py b/tests/unit/test_copilot_runtime.py
index 09c45eb8b..eb472dbd4 100644
--- a/tests/unit/test_copilot_runtime.py
+++ b/tests/unit/test_copilot_runtime.py
@@ -19,6 +19,8 @@ from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
+from playwright.async_api import Error as PlaywrightError
+from playwright.async_api import TimeoutError as PlaywrightTimeoutError
from sqlalchemy.exc import TimeoutError as SQLATimeoutError
from structlog.testing import capture_logs
@@ -27,6 +29,7 @@ from skyvern.forge.sdk.copilot import mcp_adapter, runtime
from skyvern.forge.sdk.copilot.mcp_adapter import SchemaOverlay
from skyvern.forge.sdk.copilot.runtime import AgentContext, ensure_browser_session, mcp_browser_context, mcp_to_copilot
from skyvern.forge.sdk.copilot.unrecoverable_tool_error import _is_unrecoverable_browser_session_error
+from skyvern.webeye.browser_errors import BrowserCdpConnectionError, BrowserTargetClosedError
from tests.unit.test_copilot_secret_scrub import _make_server
@@ -891,3 +894,108 @@ async def test_the_verified_caller_attaches_once_and_reports_what_the_attach_sai
assert result is not None and result["ok"] is False
assert result["probe_error_type"] == expected_error_type
assert "not evidence the browser is dead" in result["error"]
+
+
+ ("attach_effect", "expected_state"),
+ [
+ pytest.param(runtime.CopilotBrowserSessionUnavailable("bs_live"), "already_closed", id="closed"),
+ pytest.param(BrowserTargetClosedError("browser closed"), "already_closed", id="target-closed"),
+ pytest.param(BrowserCdpConnectionError("connect failed"), "cdp_connect_failed", id="cdp"),
+ ],
+)
+async def test_build_test_attach_records_typed_failure_without_replacement(
+ monkeypatch: pytest.MonkeyPatch,
+ attach_effect: BaseException,
+ expected_state: str,
+) -> None:
+ manager = MagicMock()
+ manager.create_session = AsyncMock(side_effect=AssertionError("must not replace automatically"))
+ mock_app = MagicMock()
+ mock_app.PERSISTENT_SESSIONS_MANAGER = manager
+ monkeypatch.setattr(runtime, "app", mock_app)
+
+ @asynccontextmanager
+ async def _attach(ctx: AgentContext) -> AsyncIterator[None]:
+ if isinstance(attach_effect, runtime.CopilotBrowserSessionUnavailable):
+ runtime.retire_browser_session_id(ctx, ctx.browser_session_id)
+ raise attach_effect
+ yield
+
+ monkeypatch.setattr(runtime, "mcp_browser_context", _attach)
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_live"
+
+ result = await runtime.verify_build_test_browser_session_by_attaching(ctx)
+
+ assert result is not None
+ assert result["data"]["build_test_connect_failure"] == {
+ "state": expected_state,
+ "browser_session_id": "bs_live",
+ "retry_action": "test_end_to_end",
+ }
+ manager.create_session.assert_not_awaited()
+
+
+ "attach_effect",
+ [
+ pytest.param(ConnectionError("manager returned an untyped failure"), id="connection-error"),
+ pytest.param(ConnectionResetError("transport reset outside a normalized CDP boundary"), id="connection-reset"),
+ pytest.param(PlaywrightError("browser closed"), id="native-playwright-base"),
+ pytest.param(PlaywrightTimeoutError("attach timed out"), id="native-timeout"),
+ ],
+)
+async def test_build_test_attach_does_not_invent_a_typed_state_for_unknown_failure(
+ monkeypatch: pytest.MonkeyPatch,
+ attach_effect: Exception,
+) -> None:
+ manager = MagicMock()
+ manager.create_session = AsyncMock(side_effect=AssertionError("must not replace automatically"))
+ mock_app = MagicMock()
+ mock_app.PERSISTENT_SESSIONS_MANAGER = manager
+ monkeypatch.setattr(runtime, "app", mock_app)
+
+ @asynccontextmanager
+ async def _attach(_ctx: AgentContext) -> AsyncIterator[None]:
+ raise attach_effect
+ yield
+
+ monkeypatch.setattr(runtime, "mcp_browser_context", _attach)
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_live"
+
+ result = await runtime.verify_build_test_browser_session_by_attaching(ctx)
+
+ assert result is not None
+ assert result["ok"] is False
+ assert result["probe_error_type"] == type(attach_effect).__name__
+ assert "data" not in result
+ assert ctx.browser_session_id == "bs_live"
+ manager.create_session.assert_not_awaited()
+
+
+async def test_build_test_provisioning_failure_retains_created_session_identity(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ session = SimpleNamespace(persistent_browser_session_id="bs_created")
+ manager = MagicMock()
+ manager.create_session = AsyncMock(return_value=session)
+ manager.get_browser_state = AsyncMock(side_effect=RuntimeError("boot unavailable"))
+ manager.close_session = AsyncMock()
+ mock_app = MagicMock()
+ mock_app.PERSISTENT_SESSIONS_MANAGER = manager
+ monkeypatch.setattr(runtime, "app", mock_app)
+
+ result = await runtime.ensure_build_test_browser_session(_make_ctx())
+
+ assert result is not None
+ assert result["data"]["build_test_connect_failure"] == {
+ "state": "provisioning_unavailable",
+ "browser_session_id": "bs_created",
+ "retry_action": "test_end_to_end",
+ }
+ manager.create_session.assert_awaited_once()
diff --git a/tests/unit/test_copilot_terminal_envelope.py b/tests/unit/test_copilot_terminal_envelope.py
index ec91ef968..b92f88eab 100644
--- a/tests/unit/test_copilot_terminal_envelope.py
+++ b/tests/unit/test_copilot_terminal_envelope.py
@@ -11,7 +11,7 @@ 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.build_test_outcome import BuildTestConnectFailure, 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
@@ -63,6 +63,84 @@ def test_run_anchor_reports_the_actual_latest_run() -> None:
assert envelope.run_display_reason == "A later scout run completed."
[email protected]("state", ["already_closed", "provisioning_unavailable", "cdp_connect_failed"])
+def test_connect_failure_terminal_is_typed_preserves_identity_and_offers_fresh_retry(state: str) -> None:
+ failure = BuildTestConnectFailure(
+ state=state,
+ workflow_run_id="wr_1",
+ workflow_run_block_id="wrb_1",
+ task_id="tsk_1",
+ browser_session_id="pbs_1",
+ )
+ envelope = _assemble(
+ proposal_disposition="review_untested",
+ connect_failure=failure,
+ proposal_present=True,
+ )
+
+ message, replaced = render_terminal_message(envelope, "unsupported model copy", cancelled=False)
+
+ assert envelope.terminal_cause == state
+ assert envelope.connect_failure == failure
+ assert envelope.next_state == "stopped"
+ assert replaced is True
+ assert state in message
+ assert all(identity in message for identity in ("wr_1", "wrb_1", "tsk_1", "pbs_1"))
+ assert "untested draft was preserved" in message
+ assert "fresh browser session" in message
+ assert "high demand" not in message.lower()
+
+
+def test_connect_failure_terminal_preserves_pending_question() -> None:
+ failure = BuildTestConnectFailure(state="cdp_connect_failed", browser_session_id="pbs_1")
+ envelope = _assemble(
+ response_type="ASK_QUESTION",
+ proposal_disposition="review_untested",
+ connect_failure=failure,
+ proposal_present=True,
+ )
+
+ message, replaced = render_terminal_message(envelope, "Which credential should I use?", cancelled=False)
+
+ assert envelope.next_state == "awaiting_user_input"
+ assert envelope.response_kind == "question"
+ assert "Which credential should I use?" in message
+ assert "premise is not confirmed" in message
+ assert replaced is True
+
+
+def test_connect_failure_owns_terminal_over_earlier_failed_operation() -> None:
+ failed_operation = BuildTestFailedOperation(kind="browser_operation_failed")
+ connect_failure = BuildTestConnectFailure(state="cdp_connect_failed", browser_session_id="pbs_1")
+
+ envelope = _assemble(
+ proposal_disposition="review_untested",
+ failed_operation=failed_operation,
+ connect_failure=connect_failure,
+ proposal_present=True,
+ )
+ message, replaced = render_terminal_message(envelope, "The code run failed.", cancelled=False)
+
+ assert envelope.terminal_cause == "cdp_connect_failed"
+ assert replaced is True
+ assert "cdp_connect_failed" in message
+ assert "fresh browser session" in message
+
+
[email protected]("capacity_cause", ["deadline_expired", "max_turns_exceeded"])
+def test_connect_failure_does_not_overwrite_capacity_terminal_cause(capacity_cause: str) -> None:
+ failure = BuildTestConnectFailure(state="cdp_connect_failed", browser_session_id="pbs_1")
+
+ envelope = _assemble(
+ proposal_disposition="review_untested",
+ terminal_cause=capacity_cause,
+ connect_failure=failure,
+ proposal_present=True,
+ )
+
+ assert envelope.terminal_cause == capacity_cause
+
+
def test_run_anchor_falls_back_to_latest_final_verdict_when_no_not_demonstrated() -> None:
envelope = _assemble(
run_outcomes=[
diff --git a/tests/unit/test_workflow_copilot_route.py b/tests/unit/test_workflow_copilot_route.py
index 5fd2b02e8..7b8ef1b00 100644
--- a/tests/unit/test_workflow_copilot_route.py
+++ b/tests/unit/test_workflow_copilot_route.py
@@ -248,9 +248,54 @@ def test_unresolved_failed_operation_rejects_auto_accept_even_with_auto_applicab
assert workflow_copilot_route._effective_auto_accept(True, agent_result) is False
+def test_unresolved_connect_failure_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),
+ "connect_failure": {
+ "state": "already_closed",
+ "browser_session_id": "pbs_failed",
+ "retry_action": "test_end_to_end",
+ },
+ },
+ )
+
+ assert workflow_copilot_route._effective_auto_accept(True, agent_result) is False
+
+
@pytest.mark.asyncio
-async def test_review_untested_draft_and_failed_operation_survive_persistence_and_hydration(
+ ("terminal_key", "terminal_fact"),
+ [
+ (
+ "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,
+ },
+ ),
+ (
+ "connect_failure",
+ {
+ "state": "already_closed",
+ "browser_session_id": "pbs_failed",
+ "retry_action": "test_end_to_end",
+ },
+ ),
+ ],
+)
+async def test_review_untested_draft_and_terminal_fact_survive_persistence_and_hydration(
monkeypatch: pytest.MonkeyPatch,
+ terminal_key: str,
+ terminal_fact: dict[str, object],
) -> None:
chat = SimpleNamespace(
organization_id="org-1",
@@ -262,13 +307,6 @@ async def test_review_untested_draft_and_failed_operation_survive_persistence_an
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,
@@ -278,7 +316,7 @@ async def test_review_untested_draft_and_failed_operation_survive_persistence_an
narrative_payload=_narrative_payload(),
terminal_envelope={
**_terminal_payload(verified=True, workflow_applied=True),
- "failed_operation": failed_operation,
+ terminal_key: terminal_fact,
},
)
_, workflow_params = setup_new_copilot_mocks(monkeypatch, chat, original_workflow, agent_result)
@@ -324,8 +362,9 @@ async def test_review_untested_draft_and_failed_operation_survive_persistence_an
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
+ hydrated_fact = getattr(hydrated_envelope, terminal_key)
+ assert hydrated_fact is not None
+ assert hydrated_fact.model_dump(mode="json", exclude_none=True) == terminal_fact
assert hydrated_envelope.verified is False
assert hydrated_envelope.workflow_applied is False