Skip to content

Automate browser based workflows with AI

Add growth-analytics skill with canonical metric definitions and Redshift query patterns (#8232)

Marc Kelechavaf0cd9109493b
diff --git a/alembic/versions/2026_08_19_1844-2c948904bb50_persistent_browser_sessions_download_run_id.py b/alembic/versions/2026_08_19_1844-2c948904bb50_persistent_browser_sessions_download_run_id.py
new file mode 100644
index 000000000..9e960e832
--- /dev/null
+++ b/alembic/versions/2026_08_19_1844-2c948904bb50_persistent_browser_sessions_download_run_id.py
@@ -0,0 +1,29 @@
+"""persistent_browser_sessions.download_run_id
+
+Revision ID: 2c948904bb50
+Revises: 49bb8a1289de
+Create Date: 2026-08-19T18:44:56.704271+00:00
+
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "2c948904bb50"
+down_revision: Union[str, None] = "49bb8a1289de"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.add_column("persistent_browser_sessions", sa.Column("download_run_id", sa.String(), nullable=True))
+
+
+def downgrade() -> None:
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.drop_column("persistent_browser_sessions", "download_run_id")
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.test.ts b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.test.ts
new file mode 100644
index 000000000..26a13ae68
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, test } from "vitest";
+
+import { Status } from "@/api/types";
+
+import {
+ getRunStatusRefetchInterval,
+ RUN_STATUS_POLL_INTERVAL_MS,
+} from "./useWorkflowRunQuery";
+
+describe("getRunStatusRefetchInterval", () => {
+ test("stops polling once the query is in an error state, even with stale non-finalized data", () => {
+ expect(
+ getRunStatusRefetchInterval({
+ status: "error",
+ data: { status: Status.Running },
+ }),
+ ).toBe(false);
+ });
+
+ test("does not poll before the first successful fetch", () => {
+ expect(
+ getRunStatusRefetchInterval({ status: "pending", data: undefined }),
+ ).toBe(false);
+ });
+
+ test("polls while the run is not finalized", () => {
+ expect(
+ getRunStatusRefetchInterval({
+ status: "success",
+ data: { status: Status.Running },
+ }),
+ ).toBe(RUN_STATUS_POLL_INTERVAL_MS);
+ });
+
+ test("stops polling once the run is finalized", () => {
+ expect(
+ getRunStatusRefetchInterval({
+ status: "success",
+ data: { status: Status.Completed },
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.ts
index fa8fe49e4..3d1c40c50 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.ts
@@ -1,5 +1,5 @@
import { getClient } from "@/api/AxiosClient";
-import { WorkflowRunStatusApiResponse } from "@/api/types";
+import { Status, WorkflowRunStatusApiResponse } from "@/api/types";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { useFirstParam } from "@/hooks/useFirstParam";
import {
@@ -15,6 +15,27 @@ import {
useActiveOrgId,
} from "@/store/ActiveOrgContext";
+const RUN_STATUS_POLL_INTERVAL_MS = 5000;
+
+// Data from before a failed refetch is retained, so a run whose workflow stops
+// resolving mid-run would keep a non-finalized stale payload and poll its error
+// every 5s forever; the error state has to stop the poll first.
+function getRunStatusRefetchInterval(state: {
+ status: "pending" | "error" | "success";
+ data?: { status: Status };
+}): number | false {
+ if (state.status === "error") {
+ return false;
+ }
+ if (!state.data) {
+ return false;
+ }
+ if (statusIsNotFinalized(state.data)) {
+ return RUN_STATUS_POLL_INTERVAL_MS;
+ }
+ return false;
+}
+
function useWorkflowRunQuery(options?: {
workflowRunId?: string;
enabled?: boolean;
@@ -48,15 +69,7 @@ function useWorkflowRunQuery(options?: {
})
.then((response) => response.data);
},
- refetchInterval: (query) => {
- if (!query.state.data) {
- return false;
- }
- if (statusIsNotFinalized(query.state.data)) {
- return 5000;
- }
- return false;
- },
+ refetchInterval: (query) => getRunStatusRefetchInterval(query.state),
// required for OS-level notifications to work (workflow run completion)
refetchIntervalInBackground: true,
placeholderData: keepPreviousData,
@@ -80,4 +93,8 @@ function useWorkflowRunQuery(options?: {
});
}
-export { useWorkflowRunQuery };
+export {
+ getRunStatusRefetchInterval,
+ RUN_STATUS_POLL_INTERVAL_MS,
+ useWorkflowRunQuery,
+};
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunTimelineQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunTimelineQuery.ts
index ff70d3285..0efc28cdc 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunTimelineQuery.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunTimelineQuery.ts
@@ -55,10 +55,16 @@ function useWorkflowRunTimelineQuery(options?: { workflowRunId?: string }) {
// The header counted off this data used to refetch only when the 5s run query landed,
// so it trailed the copilot chat's own 2.5s timeline poll and could report no actions
// while rows were visibly executing. Polling directly replaces that chained refetch.
- refetchInterval:
- workflowRun && statusIsNotFinalized(workflowRun)
+ // The gate reads the run query's cached data, which is retained after failed
+ // refetches, so this query's own error state has to stop the poll.
+ refetchInterval: (query) => {
+ if (query.state.status === "error") {
+ return false;
+ }
+ return workflowRun && statusIsNotFinalized(workflowRun)
? RUNNING_TIMELINE_REFETCH_INTERVAL_MS
- : false,
+ : false;
+ },
placeholderData: keepPreviousData,
refetchOnMount:
workflowRun && statusIsNotFinalized(workflowRun) ? "always" : false,
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunWithWorkflowQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunWithWorkflowQuery.ts
index b74365dd9..6e781b306 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunWithWorkflowQuery.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunWithWorkflowQuery.ts
@@ -1,12 +1,10 @@
import { getClient } from "@/api/AxiosClient";
import { WorkflowRunStatusApiResponseWithWorkflow } from "@/api/types";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
-import {
- statusIsNotFinalized,
- statusIsRunningOrQueued,
-} from "@/routes/tasks/types";
+import { statusIsRunningOrQueued } from "@/routes/tasks/types";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { useFirstParam } from "@/hooks/useFirstParam";
+import { getRunStatusRefetchInterval } from "./useWorkflowRunQuery";
import {
getActiveOrgQueryKeyScope,
getOrgScopedQueryKey,
@@ -34,15 +32,7 @@ function useWorkflowRunWithWorkflowQuery(options?: {
.get(`/workflows/runs/${workflowRunId}`, { signal })
.then((response) => response.data);
},
- refetchInterval: (query) => {
- if (!query.state.data) {
- return false;
- }
- if (statusIsNotFinalized(query.state.data)) {
- return 5000;
- }
- return false;
- },
+ refetchInterval: (query) => getRunStatusRefetchInterval(query.state),
// required for OS-level notifications to work (workflow run completion)
refetchIntervalInBackground: true,
placeholderData: keepPreviousData,
diff --git a/skyvern/cli/mcp_tools/blocks.py b/skyvern/cli/mcp_tools/blocks.py
index 20aa0a736..ea8dd3a4e 100644
--- a/skyvern/cli/mcp_tools/blocks.py
+++ b/skyvern/cli/mcp_tools/blocks.py
@@ -281,6 +281,17 @@ BLOCK_EXAMPLES: dict[str, dict[str, Any]] = {
"prompt": "Split this combined PDF into one file per document; name each by document type.",
"parameter_keys": ["source_pdf_output"],
},
+ "human_interaction": {
+ "block_type": "human_interaction",
+ "label": "approve_order",
+ "timeout_seconds": 3600,
+ "recipients": ["[email protected]"],
+ "subject": "Approval needed before the order is submitted",
+ "body": "A workflow run is paused and needs someone to approve the order before it is submitted.",
+ "instructions": "Review the order total and line items, then approve to submit or reject to cancel the run.",
+ "positive_descriptor": "Approve order",
+ "negative_descriptor": "Cancel",
+ },
"google_sheets_read": {
"block_type": "google_sheets_read",
"label": "read_sheet_data",
diff --git a/skyvern/core/script_generations/real_skyvern_page_ai.py b/skyvern/core/script_generations/real_skyvern_page_ai.py
index 9b52a2a68..f692787b2 100644
--- a/skyvern/core/script_generations/real_skyvern_page_ai.py
+++ b/skyvern/core/script_generations/real_skyvern_page_ai.py
@@ -359,7 +359,8 @@ class RealSkyvernPageAi(SkyvernPageAi):
if selector is None:
raise
LOG.warning(
- f"Failed to do ai click. Falling back to original selector={selector}, intention={intention}, data={data}",
+ "AI click failed unexpectedly; falling back to original selector",
+ selector=selector,
exc_info=True,
)
@@ -720,13 +721,17 @@ class RealSkyvernPageAi(SkyvernPageAi):
if not action.option:
raise ValueError("SelectOptionAction requires an 'option' field")
option_value = action.option.value or action.option.label or ""
- await handle_select_option_action(
+ result = await handle_select_option_action(
action=action,
page=self.page,
scraped_page=self.scraped_page,
task=task,
step=step,
)
+ if result and result[-1].success is False:
+ raise SkyvernActionFailed(
+ result[-1].exception_message or "Select option action returned success=False"
+ )
return option_value
except Exception:
# Nothing has been selected at this point, so returning option_value here would
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index d05d7daa9..d31eb177a 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -131,6 +131,7 @@ from skyvern.forge.sdk.experimentation.transient_ui_capture import (
resolve_transient_ui_capture_arm,
transient_ui_capture_arm,
)
+from skyvern.forge.sdk.experimentation.workflow_block_engine import task_v3_disabled
from skyvern.forge.sdk.fail_fast.shadow import record_fail_fast_shadow
from skyvern.forge.sdk.log_artifacts import save_step_logs, save_task_logs
from skyvern.forge.sdk.models import SpeculativeLLMMetadata, Step, StepStatus
@@ -147,6 +148,7 @@ from skyvern.forge.sdk.workflow.models.block import (
CodeBlock,
FileDownloadBlock,
ValidationBlock,
+ _task_block_supports_v3,
)
from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowRun, WorkflowRunStatus
from skyvern.forge.validation_evidence_router import (
@@ -156,7 +158,6 @@ from skyvern.forge.validation_evidence_router import (
)
from skyvern.schemas.runs import CUA_ENGINES, RunEngine
from skyvern.schemas.steps import AgentStepOutput
-from skyvern.schemas.workflows import BlockType
from skyvern.services import run_service, service_utils
from skyvern.services.action_service import get_action_history
from skyvern.services.error_detection_service import detect_user_defined_errors_for_task
@@ -597,31 +598,6 @@ async def _resolve_task_v3_llm_key(task: Task) -> str:
return override or settings.TASK_V3_LLM_KEY or settings.LLM_KEY
-_TASK_V3_SUPPORTED_BLOCK_TYPES = frozenset(
- {
- BlockType.TASK,
- BlockType.NAVIGATION,
- BlockType.LOGIN,
- BlockType.ACTION,
- BlockType.VALIDATION,
- BlockType.EXTRACTION,
- }
-)
-
-
-def _task_block_supports_v3(task_block: BaseTaskBlock) -> bool:
- """Whether a workflow task block is eligible to dispatch to the Task V3 native engine.
-
- v3 doesn't implement download-completion semantics yet, so a block relying on them
- (complete_on_download / download_suffix / download_timeout) stays on the step engine.
- """
- if task_block.block_type not in _TASK_V3_SUPPORTED_BLOCK_TYPES:
- return False
- if task_block.complete_on_download or task_block.download_suffix or task_block.download_timeout is not None:
- return False
- return True
-
-
def _redact_extracted_information(value: Any, secret_values: set[str]) -> Any:
"""Scrub registered secrets from a (possibly deeply nested) extraction result.
@@ -1724,11 +1700,7 @@ class ForgeAgent:
# v3 now resolves TOTP via get_verification_code; only a totp_verification_url task
# (needs step-engine webhook delivery) stays excluded on that axis.
and not task.totp_verification_url
- and not await app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached(
- "DISABLE_TASK_V3",
- task.workflow_run_id or task.task_id,
- properties={"organization_id": task.organization_id},
- )
+ and not await task_v3_disabled(task.workflow_run_id or task.task_id, task.organization_id)
):
try:
step, task = await self._execute_task_v3(
@@ -5802,10 +5774,8 @@ class ForgeAgent:
)
artifact_outcome = "partial"
artifact_error = "storage_partial"
- # Tag any session-scoped DOWNLOAD artifacts created during
- # this run with run_id, so GET /v1/runs/{id} surfaces them
- # (the watcher in browser_controller can't know the active
- # run at upload time — see
+ # Reconcile session-scoped DOWNLOAD rows the watcher left unbound, so
+ # GET /v1/runs/{id} surfaces them (see
# cloud_docs/BROWSER_SESSION_DOWNLOAD_ARTIFACTS.md).
browser_session_id = context.browser_session_id if context else None
if browser_session_id and task.organization_id and finalization_run_id:
@@ -5971,7 +5941,6 @@ class ForgeAgent:
"Sending task response to webhook callback url",
task_id=task.task_id,
webhook_callback_url=task.webhook_callback_url,
- payload=signed_data.payload_for_log,
headers=signed_data.headers,
)
@@ -6023,7 +5992,6 @@ class ForgeAgent:
LOG.info(
"Webhook failed",
task_id=task.task_id,
- resp=resp,
resp_code=resp.status_code,
resp_text=resp.text,
)
diff --git a/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt b/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt
index 7398bc361..e809275b9 100644
--- a/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt
+++ b/skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt
@@ -701,10 +701,10 @@ Purpose: Send email notifications. This is the "Send Email Block" in the UI.
Structure:
block_type: send_email
label: <unique_label>
-smtp_host_secret_parameter_key: <param_key> # Secret parameter key for SMTP host (required unless custom_smtp_host is set)
-smtp_port_secret_parameter_key: <param_key> # Secret parameter key for SMTP port (required unless custom_smtp_host is set)
-smtp_username_secret_parameter_key: <param_key> # Secret parameter key for SMTP username (required unless custom_smtp_host is set)
-smtp_password_secret_parameter_key: <param_key> # Secret parameter key for SMTP password (required unless custom_smtp_host is set)
+smtp_host_secret_parameter_key: <param_key> # Optional: Only to point at your own declared secret parameter; the platform provisions its own SMTP credentials when these are omitted
+smtp_port_secret_parameter_key: <param_key> # Optional: See smtp_host_secret_parameter_key
+smtp_username_secret_parameter_key: <param_key> # Optional: See smtp_host_secret_parameter_key
+smtp_password_secret_parameter_key: <param_key> # Optional: See smtp_host_secret_parameter_key
sender: <email_address> # Required: Sender email address
recipients: [<email_address>] # Required: Recipient list
subject: <subject_line> # Required: Email subject
@@ -726,16 +726,46 @@ blocks:
- block_type: send_email
label: notify_ops
next_block_label: null
- smtp_host_secret_parameter_key: smtp_host
- smtp_port_secret_parameter_key: smtp_port
- smtp_username_secret_parameter_key: smtp_user
- smtp_password_secret_parameter_key: smtp_pass
recipients: ["[email protected]"]
subject: "Daily report ready"
body: "The latest report is ready for review."
file_attachments: ["/tmp/latest_report.pdf"]
+** HUMAN INTERACTION BLOCK (human_interaction) **
+
+Purpose: Pause the workflow and wait for a person. This is the "Human Interaction Block" in the UI. The run moves to the paused state, the recipients are emailed a link to the run (plus a link to the browser session when the run has one), and the workflow waits. The person opens the run in Skyvern, optionally takes control of the browser to do the step by hand, then approves - which resumes the workflow - or rejects, which cancels the run. If nobody responds within timeout_seconds the block times out and the workflow stops. Choose this block whenever a person must approve before the workflow continues, or must do something the agent cannot do itself. Prefer an automated path first: a credentialed login block signs in on its own and handles 2FA, so use it for sign-in rather than this block. Every human_interaction block turns a reusable automation into a manual step on every future run, so it is the right answer for approval gates and for steps automation genuinely cannot perform - not a shortcut past a hard login.
+
+Use Cases:
+- A person approves before the workflow continues (high-value action, compliance review, a check of extracted data)
+- A person does a step by hand in the browser that has no automated path: solving a CAPTCHA, biometric or voice verification, or a sign-in that credentialed login cannot complete
+- Escalation for a case the agent is not allowed to decide on its own
+
+Structure:
+block_type: human_interaction
+label: <unique_label>
+recipients: [<email_address>] # Required: Who gets notified; ask the user for an address if you do not have one
+timeout_seconds: <number> # Optional: How long to wait for the person before the block times out (default: 7200). A paused run is reaped after about 4.5 hours, so values beyond that do not extend the wait
+sender: <email_address> # Optional: A copy is BCC'd here as the record of the send (default: "[email protected]")
+subject: <subject_line> # Optional: Notification subject (default: "Human interaction required for workflow run")
+body: <email_body> # Optional: Notification body (default: "Your interaction is required for a workflow run!")
+instructions: <text> # Optional: What the person should do, shown beside the approve/reject controls (default: "Please review and approve or reject to continue the workflow.")
+positive_descriptor: <text> # Optional: Label on the approve control (default: "Approve")
+negative_descriptor: <text> # Optional: Label on the reject control (default: "Reject")
+
+Example:
+blocks:
+ - block_type: human_interaction
+ label: approve_order
+ next_block_label: submit_order
+ timeout_seconds: 3600
+ recipients: ["[email protected]"]
+ subject: "Approval needed before the order is submitted"
+ body: "A workflow run is paused and needs someone to approve the order before it is submitted."
+ instructions: "Review the order total and line items, then approve to submit or reject to cancel the run."
+ positive_descriptor: "Approve order"
+ negative_descriptor: "Cancel"
+
** TEXT PROMPT BLOCK (text_prompt) **
Purpose: Process text with LLM. This is the "Text Prompt Block" in the UI.
diff --git a/skyvern/forge/sdk/artifact/manager.py b/skyvern/forge/sdk/artifact/manager.py
index 21e95521d..501f4914c 100644
--- a/skyvern/forge/sdk/artifact/manager.py
+++ b/skyvern/forge/sdk/artifact/manager.py
@@ -515,22 +515,13 @@ class ArtifactManager:
filename: str,
checksum: str | None = None,
file_size: int | None = None,
+ run_id: str | None = None,
) -> str:
- """Register a session-scoped downloaded file as an Artifact row.
-
- Used by the browser_controller's watcher write site
- (``S3Storage.sync_browser_session_file(artifact_type="downloads")``).
- Idempotent on ``(organization_id, browser_session_id, uri)`` — the
- watcher fires repeatedly as a downloaded file grows, so we look up
- the existing row before inserting.
-
- ``run_id`` is intentionally NOT set here. The watcher runs in a
- separate process from the agent and does not know which run is
- currently using the session. Run finalization runs the
- ``claim_session_download_artifacts_for_run`` UPDATE to tag rows
- whose ``created_at`` falls inside the run's window; a code block
- runs the same UPDATE mid-run over its own block row's window.
- """
+ """Register a session-scoped downloaded file as an Artifact row, idempotent on
+ ``(organization_id, browser_session_id, uri)`` because the watcher fires repeatedly as the
+ file grows. ``run_id`` is the run occupying the session when the download was observed and
+ must be resolved at that observation, not here, where a late write would name whichever run
+ holds the session now."""
return await self._create_browser_session_artifact(
organization_id=organization_id,
browser_session_id=browser_session_id,
@@ -539,6 +530,7 @@ class ArtifactManager:
artifact_type=ArtifactType.DOWNLOAD,
checksum=checksum,
file_size=file_size,
+ run_id=run_id,
)
async def create_browser_session_recording_artifact(
@@ -684,6 +676,7 @@ class ArtifactManager:
artifact_type: ArtifactType,
checksum: str | None = None,
file_size: int | None = None,
+ run_id: str | None = None,
) -> str:
"""Insert a browser-session artifact, deduplicating every type except action logs."""
if artifact_type != ArtifactType.BROWSER_SESSION_ACTION_LOG:
@@ -694,6 +687,12 @@ class ArtifactManager:
artifact_type=artifact_type,
)
if existing is not None:
+ if run_id is not None and existing.run_id is None:
+ await app.DATABASE.artifacts.bind_session_download_artifact_producer(
+ artifact_id=existing.artifact_id,
+ organization_id=organization_id,
+ run_id=run_id,
+ )
return existing.artifact_id
artifact_id = generate_artifact_id()
@@ -703,6 +702,7 @@ class ArtifactManager:
uri=uri,
organization_id=organization_id,
browser_session_id=browser_session_id,
+ run_id=run_id,
checksum=checksum,
file_size=file_size,
)
diff --git a/skyvern/forge/sdk/artifact/storage/azure.py b/skyvern/forge/sdk/artifact/storage/azure.py
index 49682f0ca..85ebb5d8e 100644
--- a/skyvern/forge/sdk/artifact/storage/azure.py
+++ b/skyvern/forge/sdk/artifact/storage/azure.py
@@ -762,6 +762,7 @@ class AzureStorage(BaseStorage):
remote_path: str,
date: str | None = None,
recording_finalized_at: datetime | None = None,
+ producer_run_id: str | None = None,
) -> str:
"""Sync a file from local browser session to Azure."""
uri = self._build_browser_session_uri(organization_id, browser_session_id, artifact_type, remote_path, date)
@@ -832,6 +833,7 @@ class AzureStorage(BaseStorage):
filename=os.path.basename(remote_path),
checksum=download_checksum,
file_size=download_file_size,
+ run_id=None if is_partial else producer_run_id,
)
return uri
diff --git a/skyvern/forge/sdk/artifact/storage/base.py b/skyvern/forge/sdk/artifact/storage/base.py
index 66ce70f22..cf4ee4794 100644
--- a/skyvern/forge/sdk/artifact/storage/base.py
+++ b/skyvern/forge/sdk/artifact/storage/base.py
@@ -330,6 +330,7 @@ class BaseStorage(ABC):
remote_path: str,
date: str | None = None,
recording_finalized_at: datetime | None = None,
+ producer_run_id: str | None = None,
) -> str:
pass
diff --git a/skyvern/forge/sdk/artifact/storage/gcs.py b/skyvern/forge/sdk/artifact/storage/gcs.py
index 323be0fd9..82b75ac45 100644
--- a/skyvern/forge/sdk/artifact/storage/gcs.py
+++ b/skyvern/forge/sdk/artifact/storage/gcs.py
@@ -780,6 +780,7 @@ class GcsStorage(BaseStorage):
remote_path: str,
date: str | None = None,
recording_finalized_at: datetime | None = None,
+ producer_run_id: str | None = None,
) -> str:
"""Sync a file from local browser session to GCS."""
uri = self._build_browser_session_uri(organization_id, browser_session_id, artifact_type, remote_path, date)
@@ -855,6 +856,7 @@ class GcsStorage(BaseStorage):
filename=os.path.basename(remote_path),
checksum=download_checksum,
file_size=download_file_size,
+ run_id=None if is_partial else producer_run_id,
)
return uri
diff --git a/skyvern/forge/sdk/artifact/storage/local.py b/skyvern/forge/sdk/artifact/storage/local.py
index 034420e5e..498a447c6 100644
--- a/skyvern/forge/sdk/artifact/storage/local.py
+++ b/skyvern/forge/sdk/artifact/storage/local.py
@@ -543,6 +543,7 @@ class LocalStorage(BaseStorage):
remote_path: str,
date: str | None = None,
recording_finalized_at: datetime | None = None,
+ producer_run_id: str | None = None,
) -> str:
"""Sync a file from local browser session to local storage."""
target_path = self._build_browser_session_path(
diff --git a/skyvern/forge/sdk/artifact/storage/s3.py b/skyvern/forge/sdk/artifact/storage/s3.py
index 3f01b55ea..39588b73e 100644
--- a/skyvern/forge/sdk/artifact/storage/s3.py
+++ b/skyvern/forge/sdk/artifact/storage/s3.py
@@ -982,6 +982,7 @@ class S3Storage(BaseStorage):
remote_path: str,
date: str | None = None,
recording_finalized_at: datetime | None = None,
+ producer_run_id: str | None = None,
) -> str:
"""Sync a file from local browser session to S3."""
uri = self._build_browser_session_uri(organization_id, browser_session_id, artifact_type, remote_path, date)
@@ -1064,6 +1065,7 @@ class S3Storage(BaseStorage):
filename=os.path.basename(remote_path),
checksum=download_checksum,
file_size=download_file_size,
+ run_id=None if is_partial else producer_run_id,
)
return uri
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index 652738863..431dedc72 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -1912,23 +1912,29 @@ def _build_turn_halt_exit_result(
)
-_TIMEOUT_REPLY_DEFAULT = "I ran out of time processing your request. Here's what I have so far."
+_TIMEOUT_REPLY_DEFAULT = (
+ "I ran out of time processing your request, and I don't have a draft workflow to hand over. "
+ "Tell me what to focus on and I'll try again."
+)
_TIMEOUT_REPLY_UNVALIDATED = (
- "I ran out of time before I could finish testing. I have a draft workflow you can keep — "
+ "I ran out of time. I have a draft workflow you can keep — "
"accept it to save (note: it hasn't been verified end-to-end), or discard."
)
_TIMEOUT_REPLY_TESTED = "I ran out of time, but I have a tested draft for you. Accept it to save, or discard."
-_MAX_TURNS_REPLY_DEFAULT = "I've reached the maximum number of steps. Here's what I have so far."
+_MAX_TURNS_REPLY_DEFAULT = (
+ "I've reached the maximum number of steps, and I don't have a draft workflow to hand over. "
+ "Tell me what to focus on and I'll try again."
+)
_MAX_TURNS_REPLY_UNVALIDATED = (
- "I've reached the maximum number of steps before I could finish testing. I have a draft "
+ "I've reached the maximum number of steps. I have a draft "
"workflow you can keep — accept it to save (note: it hasn't been verified end-to-end), or discard."
)
_MAX_TURNS_REPLY_TESTED = (
"I've reached the maximum number of steps, but I have a tested draft for you. Accept it to save, or discard."
)
_UNEXPECTED_ERROR_REPLY_UNVALIDATED = (
- "I hit an unexpected issue before I could finish testing. I have a draft workflow you can keep — "
+ "I hit an unexpected issue. I have a draft workflow you can keep — "
"accept it to save (note: it hasn't been verified end-to-end), or discard."
)
_UNEXPECTED_ERROR_REPLY_TESTED = (
@@ -2465,7 +2471,7 @@ def _build_wip_exit_result(
cancelled: bool = False,
terminal_reason: str | None = None,
) -> AgentResult:
- """Selected non-success exits surface the most recent successfully parsed workflow."""
+ """Non-success exits surface the most recent successfully parsed workflow."""
internal_tool_instruction_failure = _recorded_failure_is_internal_tool_instruction(ctx)
halted_mid_progress = _halted_mid_progress(ctx, internal_tool_instruction_failure)
recorded_failure_reply = _recorded_failure_reply(
@@ -2572,13 +2578,10 @@ def _build_wip_exit_result(
),
exit_site="wip_last_good_workflow",
)
- if (
- ctx.last_workflow is not None
- and ctx.last_workflow_yaml
- and (ctx.last_test_ok is not False or halted_mid_progress)
- and not ctx.last_test_suspicious_success
- ):
- full_test_ok = ctx.last_test_ok is True and ctx.last_full_workflow_test_ok is True
+ if ctx.last_workflow is not None and ctx.last_workflow_yaml:
+ full_test_ok = (
+ ctx.last_test_ok is True and ctx.last_full_workflow_test_ok is True and not ctx.last_test_suspicious_success
+ )
unvalidated = not full_test_ok
if unvalidated and recorded_failure_reply:
reply = _deadline_owned_or(unvalidated_reply, recorded_failure_reply) or unvalidated_reply
@@ -2616,13 +2619,16 @@ def _build_wip_exit_result(
),
exit_site="wip_last_workflow",
)
+ # This branch carries no draft and its reply says so, so it must not report a
+ # disposition auto-accept can act on -- that would commit a staged workflow to
+ # canonical on the same turn the user is told there is nothing to hand over.
return _build_exit_result(
ctx,
_deadline_owned_or(default_reply, recorded_failure_reply) or default_reply,
global_llm_context,
cancelled=cancelled,
terminal_reason=effective_terminal,
- proposal_disposition="auto_applicable",
+ proposal_disposition="no_proposal",
)
diff --git a/skyvern/forge/sdk/copilot/challenge_evidence.py b/skyvern/forge/sdk/copilot/challenge_evidence.py
index 870bef1a5..18543b5b9 100644
--- a/skyvern/forge/sdk/copilot/challenge_evidence.py
+++ b/skyvern/forge/sdk/copilot/challenge_evidence.py
@@ -215,7 +215,7 @@ def composition_challenge_carrier(evidence: Mapping[str, Any] | None) -> Challen
if stamped in CARRIER_CHALLENGE_EVIDENCE_SOURCES:
return stamped
# gates_submit_controls is only ever derived from rendered controls or a
- # vision confirmation, so it carries the same weight as either.
+ # structurally corroborated vision confirmation, so it carries the same weight as either.
if (
challenge_state.get("requires_human_verification") is True
or challenge_state.get("gates_submit_controls") is True
diff --git a/skyvern/forge/sdk/copilot/composition_browser_expressions.py b/skyvern/forge/sdk/copilot/composition_browser_expressions.py
index 4b128c010..7f326431d 100644
--- a/skyvern/forge/sdk/copilot/composition_browser_expressions.py
+++ b/skyvern/forge/sdk/copilot/composition_browser_expressions.py
@@ -732,6 +732,7 @@ const selectOptions = (el) => {
return out;
};
const controlDisabled = (el) => !!(el.hasAttribute('disabled') || lower(attr(el, 'aria-disabled')) === 'true' || lower(attr(el, 'data-disabled')) === 'true');
+const controlReadonly = (el) => !!(el.readOnly === true || el.hasAttribute('readonly') || lower(attr(el, 'aria-readonly')) === 'true');
const modalIdentity = (el) => [
(el.tagName || '').toLowerCase(), attr(el, 'id'), classesFor(el).join(' '), attr(el, 'role'),
attr(el, 'aria-label'), attr(el, 'title'), attr(el, 'data-testid'), attr(el, 'data-test'), attr(el, 'data-dismiss'),
@@ -797,7 +798,7 @@ for (const form of document.querySelectorAll('form')) {
continue;
}
if (fields.length >= MAX_FIELDS_PER_FORM) continue;
- fields.push({ name: attr(node, 'name'), id: attr(node, 'id'), label: fieldLabel(node), type: fieldType, value: attr(node, 'value'), filled: isFilled(node), class: classesFor(node), placeholder: attr(node, 'placeholder'), required: !!(node.hasAttribute('required') || lower(attr(node, 'aria-required')) === 'true'), disabled: controlDisabled(node), visible: controlVisible(node), checked: node.hasAttribute('checked'), options: tag === 'select' ? selectOptions(node) : [], selector: selectorFor(node), selector_candidates: selectorCandidatesFor(node), identity: identityFor(node) });
+ fields.push({ name: attr(node, 'name'), id: attr(node, 'id'), label: fieldLabel(node), type: fieldType, value: attr(node, 'value'), filled: isFilled(node), class: classesFor(node), placeholder: attr(node, 'placeholder'), required: !!(node.hasAttribute('required') || lower(attr(node, 'aria-required')) === 'true'), disabled: controlDisabled(node), readonly: controlReadonly(node), visible: controlVisible(node), checked: node.hasAttribute('checked'), options: tag === 'select' ? selectOptions(node) : [], selector: selectorFor(node), selector_candidates: selectorCandidatesFor(node), identity: identityFor(node) });
}
forms.push({ id: attr(form, 'id'), name: attr(form, 'name'), action: attr(form, 'action'), method: attr(form, 'method'), fields: fields, submit_controls: submitControls });
}
diff --git a/skyvern/forge/sdk/copilot/composition_evidence.py b/skyvern/forge/sdk/copilot/composition_evidence.py
index 5b86873c5..48f85c233 100644
--- a/skyvern/forge/sdk/copilot/composition_evidence.py
+++ b/skyvern/forge/sdk/copilot/composition_evidence.py
@@ -98,6 +98,9 @@ _EMPTY_RESULT_TEXT_PATTERNS: frozenset[str] = frozenset(
_MAX_VISUAL_SUMMARY_CHARS = 500
_MAX_VISUAL_OMISSIONS = 5
_ANTI_BOT_SCAN_BYTES = 250_000
+_NON_ENTRY_FIELD_TYPES: frozenset[str] = frozenset(
+ {"hidden", "submit", "button", "reset", "checkbox", "radio", "file", "image"}
+)
class _PostRunCompositionContext(Protocol):
@@ -164,6 +167,12 @@ def _control_disabled(node: Any) -> bool:
)
+def _control_readonly(node: Any) -> bool:
+ if not hasattr(node, "has_attr"):
+ return False
+ return bool(node.has_attr("readonly") or str(node.get("aria-readonly") or "").strip().lower() == "true")
+
+
def _gated_submit_controls(forms: list[dict[str, Any]]) -> list[dict[str, Any]]:
controls: list[dict[str, Any]] = []
for form in forms:
@@ -250,13 +259,71 @@ def page_evidence_needs_visual_fallback(evidence: dict[str, Any]) -> bool:
return bool(evidence.get("anti_bot_indicators") or evidence.get("challenge_controls"))
+def _usable_control(control: Any) -> bool:
+ # Static HTML cannot see a stylesheet, so the fallback parser reports no `visible` flag at all
+ # and absent has to read as usable here; a control it never showed can still count.
+ return (
+ isinstance(control, dict)
+ and control.get("disabled") is not True
+ and control.get("readonly") is not True
+ and control.get("visible") is not False
+ )
+
+
+def _satisfiable_form_path(forms: Any) -> bool:
+ """True when the page offers an entry field plus an enabled submit control, so the turn can
+ complete it without a person.
+
+ The claim under refutation is that the submit control is gated. The page is authoritative about
+ disabled state, so a form whose own submit control it reports disabled corroborates the claim and
+ cannot refute it; matching the claim's prose to a control would be the harness interpreting prose.
+ A disabled control in some unrelated form says nothing about the form under consideration.
+ """
+ if not isinstance(forms, list):
+ return False
+ for form in forms:
+ if not isinstance(form, dict):
+ continue
+ submit_controls = [control for control in form.get("submit_controls") or [] if isinstance(control, dict)]
+ if any(control.get("disabled") is True for control in submit_controls):
+ continue
+ has_entry_field = any(
+ _usable_control(field) and str(field.get("type") or "").strip() not in _NON_ENTRY_FIELD_TYPES
+ for field in form.get("fields") or []
+ )
+ if not has_entry_field:
+ continue
+ # A bare <button> in a form already captures as "submit"; an explicit type="button" is
+ # JS-driven and indistinguishable from Cancel without reading its label, so it does not
+ # count and the claim stands.
+ if any(
+ _usable_control(control) and str(control.get("type") or "").strip() == "submit"
+ for control in submit_controls
+ ):
+ return True
+ return False
+
+
def _confirmed_visual_challenge(evidence: dict[str, Any], visual_summary: dict[str, Any]) -> bool:
if visual_summary.get("challenge_detected") is not True:
return False
if interactive_challenge_controls(evidence.get("challenge_controls")):
return True
obstruction_kind = str(visual_summary.get("obstruction_kind") or "").strip().lower()
- return obstruction_kind != CONSENT_OBSTRUCTION_KIND
+ if obstruction_kind == CONSENT_OBSTRUCTION_KIND:
+ return False
+ if evidence.get("visual_obstruction_candidates") or evidence.get("modal_overlays"):
+ return True
+ # Form shape may only refute the one commensurable vision claim, that the submit control
+ # is gated; occlusion is answered by the obstruction evidence above, never by shape.
+ blocked_claims = [
+ item for item in visual_summary.get("blocked_submit_controls") or [] if isinstance(item, str) and item.strip()
+ ]
+ # submit_blocked normalizes to None whenever the model omits it, so a named blocked control
+ # carries the same gating claim; keying on the boolean alone would silently disable this.
+ if visual_summary.get("submit_blocked") is not True and not blocked_claims:
+ return True
+ return not _satisfiable_form_path(evidence.get("forms"))
def merge_visual_composition_evidence(
@@ -298,7 +365,7 @@ def merge_visual_composition_evidence(
omissions.append(bounded)
challenge_state = dict(merged.get("challenge_state") or {})
challenge_confirmed = _confirmed_visual_challenge(evidence, visual_summary)
- if vision_challenge_carrier(visual_summary):
+ if challenge_confirmed and vision_challenge_carrier(visual_summary):
challenge_state.setdefault(CHALLENGE_EVIDENCE_SOURCE_KEY, ChallengeEvidenceSource.VISION.value)
if challenge_confirmed:
challenge_state["detected"] = True
@@ -2478,6 +2545,7 @@ def parse_composition_html(
node.has_attr("required") or str(node.get("aria-required") or "").lower() == "true"
),
"disabled": _control_disabled(node),
+ "readonly": _control_readonly(node),
"checked": bool(node.has_attr("checked")),
"options": _select_options(node) if tag_name == "select" else [],
"selector": _bounded_selector(_selector_for(node)),
@@ -2685,6 +2753,7 @@ def _structured_form(form: Any) -> dict[str, Any] | None:
"placeholder": _schema_text(_structured_str(node.get("placeholder")), 240),
"required": node.get("required") is True,
"disabled": node.get("disabled") is True,
+ "readonly": node.get("readonly") is True,
"checked": node.get("checked") is True,
"options": _structured_select_options(node.get("options")),
"selector": _bounded_selector(_structured_str(node.get("selector"))),
diff --git a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py
index 2f9bac91f..0b631404b 100644
--- a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py
+++ b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py
@@ -425,6 +425,10 @@ def _failure_type(
data: dict[str, Any],
repair_context: CodeAuthoringRepairContext | None,
) -> DiagnosisFailureType:
+ # A paused run is waiting on a person, not failing: classifying it as a failure would tell the
+ # model to repair a workflow whose only problem is that nobody has approved it yet.
+ if (data.get("control_signal") or {}).get("kind") == "watchdog_paused":
+ return DiagnosisFailureType.NO_FAILURE
skip_reason = _safe_str(data.get("skip_reason"))
if skip_reason in _CREDENTIAL_INPUT_MISSING_SKIP_REASONS:
return DiagnosisFailureType.MISSING_CREDENTIAL_OR_INIT
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index 4ec913289..2b95f5c41 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -661,23 +661,26 @@ def _same_page(left: str | None, right: str | None) -> bool:
return left_path == right_path
-def _consume_pending_screenshots(ctx: Any) -> dict[str, Any] | None:
- """Drain pending_screenshots into a synthetic user message with images.
+def pending_screenshot_message(ctx: Any) -> dict[str, Any] | None:
+ """Build the synthetic user message for the staged frame without draining it.
Tool results stay text-only because OpenAI rejects images in tool
messages, so screenshots are delivered as a follow-up user message.
"""
+ # Re-checked here rather than only at enqueue: a retriable failure can swap in a
+ # non-vision fallback model after the frame was staged, so every delivery path needs it.
+ if not getattr(ctx, "supports_vision", False):
+ return None
pending = getattr(ctx, "pending_screenshots", None)
if not isinstance(pending, list) or not pending:
return None
screenshots: list[ScreenshotEntry] = list(pending)
- pending.clear()
content: list[dict[str, Any]] = [
{
"type": "input_text",
"text": (
- SCREENSHOT_SENTINEL + "Here is the screenshot from the tool result. "
- "Analyze it to understand the current browser state."
+ SCREENSHOT_SENTINEL + "Here is the most recent screenshot captured this turn. "
+ "It shows the page as of that capture and may predate later actions."
),
},
]
@@ -692,6 +695,15 @@ def _consume_pending_screenshots(ctx: Any) -> dict[str, Any] | None:
return {"role": "user", "content": content}
+def _consume_pending_screenshots(ctx: Any) -> dict[str, Any] | None:
+ """Build the screenshot message and clear the queue — the end-of-turn drain."""
+ message = pending_screenshot_message(ctx)
+ pending = getattr(ctx, "pending_screenshots", None)
+ if isinstance(pending, list):
+ pending.clear()
+ return message
+
+
def _parse_normalized_final_response(result: RunResultStreaming | None) -> dict[str, Any] | None:
if result is None:
return None
@@ -1786,7 +1798,10 @@ async def run_with_enforcement(
except asyncio.CancelledError:
_mark_copilot_total_timeout_if_elapsed(ctx, start_time, iteration)
raise
- if images_stripped:
+ # Unconditional: the staged frame never reaches current_input, so images_stripped
+ # cannot see it, and the filter would re-append it to the retry we just shrank.
+ frame_dropped = _consume_pending_screenshots(ctx) is not None
+ if images_stripped or frame_dropped:
# The agent could otherwise reason about the page from
# memory on the next turn; warn it explicitly.
pending_recovery_nudge = _nudge(copilot_config, "screenshot_dropped")
diff --git a/skyvern/forge/sdk/copilot/mcp_adapter.py b/skyvern/forge/sdk/copilot/mcp_adapter.py
index 773c214bb..b5d70ff5c 100644
--- a/skyvern/forge/sdk/copilot/mcp_adapter.py
+++ b/skyvern/forge/sdk/copilot/mcp_adapter.py
@@ -4,11 +4,12 @@ from __future__ import annotations
import asyncio
import json
+import time
from collections.abc import AsyncIterator, Awaitable, Callable
from contextlib import AsyncExitStack, asynccontextmanager
from copy import deepcopy
from dataclasses import dataclass, field
-from typing import Any
+from typing import TYPE_CHECKING, Any, Literal
from urllib.parse import urlparse
import structlog
@@ -29,6 +30,7 @@ from skyvern.cli.core.session_manager import request_session_scope
from skyvern.forge import app
from skyvern.forge.agent_functions import CopilotCandidateNetworkHop
from skyvern.forge.sdk.copilot.enforcement import requested_output_paths_for_derivation
+from skyvern.forge.sdk.copilot.hooks import _copilot_log_fields
from skyvern.forge.sdk.copilot.loop_detection import record_tool_step_result_for_ctx
from skyvern.forge.sdk.copilot.output_utils import mark_mcp_result_untrusted_for_llm, sanitize_tool_result_for_llm
from skyvern.forge.sdk.copilot.request_policy import RequestPolicy
@@ -43,6 +45,9 @@ from skyvern.forge.sdk.copilot.screenshot_utils import enqueue_screenshot_from_r
from skyvern.forge.sdk.copilot.secret_scrub import scrub_secrets_from_structure
from skyvern.webeye.browser_state import BrowserState
+if TYPE_CHECKING:
+ from skyvern.forge.sdk.copilot.context import CopilotContext
+
PreHook = Callable[[dict[str, Any], AgentContext], Awaitable[dict[str, Any] | None]]
PostHook = Callable[[dict[str, Any], dict[str, Any], AgentContext], Awaitable[dict[str, Any]]]
@@ -156,6 +161,34 @@ def _scrub_tool_exception(ctx: AgentContext, tool_name: str, exception: BaseExce
return _scrub_tool_result(ctx, {"ok": False, "error": error})
+def _elapsed_ms(started: float) -> int:
+ return int((time.monotonic() - started) * 1000)
+
+
+def _log_mcp_timing(
+ ctx: CopilotContext,
+ tool_name: str,
+ mcp_tool_name: str,
+ wall_clock_ms: int,
+ raw_mcp: dict[str, Any],
+ call_path: Literal["model", "internal"],
+ call_status: Literal["ok", "timeout", "error", "session_error", "cancelled", "not_connected"] = "ok",
+) -> None:
+ timing = raw_mcp.get("timing_ms")
+ total = timing.get("total") if isinstance(timing, dict) else None
+ reported = total if isinstance(total, int) and not isinstance(total, bool) else None
+ LOG.info(
+ "MCP tool timing",
+ tool_name=tool_name,
+ mcp_tool_name=mcp_tool_name,
+ wall_clock_ms=wall_clock_ms,
+ server_timing_ms=reported,
+ call_path=call_path,
+ call_status=call_status,
+ **_copilot_log_fields(ctx),
+ )
+
+
def _requested_output_path_choices(schema: dict[str, Any], paths: list[str]) -> dict[str, Any]:
"""Present the outputs this turn owes as the choices for the path a read claims.
@@ -504,12 +537,21 @@ class SkyvernOverlayMCPServer(MCPServer):
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, hook_result)
return _copilot_to_call_tool_result(hook_result)
+ started = time.monotonic()
mcp_name = self._alias_map.get(tool_name, tool_name)
mcp_args = _transform_args(arguments, overlay)
if overlay.requires_browser:
- err = await ensure_browser_session(copilot_ctx)
+ try:
+ err = await ensure_browser_session(copilot_ctx)
+ except asyncio.CancelledError:
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, _elapsed_ms(started), {}, "model", "cancelled")
+ raise
+ except Exception:
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, _elapsed_ms(started), {}, "model", "session_error")
+ raise
if err:
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, _elapsed_ms(started), {}, "model", "session_error")
err = _scrub_tool_result(copilot_ctx, err)
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, err)
return _copilot_to_call_tool_result(err)
@@ -532,6 +574,7 @@ class SkyvernOverlayMCPServer(MCPServer):
)
except TimeoutError:
LOG.warning("MCP tool call timed out", tool=tool_name, ceiling_seconds=overlay.timeout)
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, _elapsed_ms(started), {}, "model", "timeout")
# The call is cancelled where it stands, so a tool that changes the page may already have
# changed it. Reporting a plain failure invites a retry that acts on the page twice.
err = {
@@ -544,11 +587,16 @@ class SkyvernOverlayMCPServer(MCPServer):
err = _scrub_tool_result(copilot_ctx, err)
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, err)
return _copilot_to_call_tool_result(err)
+ except asyncio.CancelledError:
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, _elapsed_ms(started), {}, "model", "cancelled")
+ raise
except Exception as exc:
LOG.warning("MCP tool call failed", tool=tool_name)
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, _elapsed_ms(started), {}, "model", "error")
err = _scrub_tool_exception(copilot_ctx, tool_name, exc)
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, err)
return _copilot_to_call_tool_result(err)
+ wall_clock_ms = _elapsed_ms(started)
# Copy fastmcp's structured_content so mutations below stay local to
# this call — the client may reuse or cache the response object.
@@ -560,6 +608,8 @@ class SkyvernOverlayMCPServer(MCPServer):
raw_mcp["error"] = " ".join(text_parts) if text_parts else "Unknown MCP error"
else:
raw_mcp["error"] = raw_mcp.get("error") or "Unknown MCP error"
+ failed = raw_result.is_error or raw_mcp.get("ok", True) is not True
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, wall_clock_ms, raw_mcp, "model", "error" if failed else "ok")
# Scrub before the post hook so evidence the hooks record from raw_mcp
# (flow evidence, scout observations) is scrubbed too.
raw_mcp = _scrub_tool_result(copilot_ctx, raw_mcp)
@@ -612,21 +662,37 @@ class SkyvernOverlayMCPServer(MCPServer):
extracted error string rather than silently defaulting to
``ok=True``.
"""
+ started = time.monotonic()
+ copilot_name = self._reverse_alias.get(mcp_tool_name, mcp_tool_name)
ctx = self._context_provider()
if not self._client:
+ _log_mcp_timing(ctx, copilot_name, mcp_tool_name, _elapsed_ms(started), {}, "internal", "not_connected")
return _scrub_tool_result(ctx, {"ok": False, "error": "MCP client not connected"})
- err = await ensure_browser_session(ctx)
+ try:
+ err = await ensure_browser_session(ctx)
+ except asyncio.CancelledError:
+ _log_mcp_timing(ctx, copilot_name, mcp_tool_name, _elapsed_ms(started), {}, "internal", "cancelled")
+ raise
+ except Exception:
+ _log_mcp_timing(ctx, copilot_name, mcp_tool_name, _elapsed_ms(started), {}, "internal", "session_error")
+ raise
if err:
+ _log_mcp_timing(ctx, copilot_name, mcp_tool_name, _elapsed_ms(started), {}, "internal", "session_error")
return _scrub_tool_result(ctx, err)
merged_args = {**mcp_args, "session_id": ctx.browser_session_id}
try:
async with mcp_browser_context(ctx):
raw = await self._client.call_tool(mcp_tool_name, merged_args, raise_on_error=False)
+ wall_clock_ms = _elapsed_ms(started)
if self._evidence_candidate_origin is not None:
await asyncio.sleep(0)
await self._drain_evidence_candidate_response_tasks()
+ except asyncio.CancelledError:
+ _log_mcp_timing(ctx, copilot_name, mcp_tool_name, _elapsed_ms(started), {}, "internal", "cancelled")
+ raise
except Exception as exc:
LOG.warning("Internal MCP tool call failed", tool=mcp_tool_name)
+ _log_mcp_timing(ctx, copilot_name, mcp_tool_name, _elapsed_ms(started), {}, "internal", "error")
return _scrub_tool_exception(ctx, mcp_tool_name, exc)
raw_mcp = dict(raw.structured_content or {})
if raw.is_error:
@@ -636,6 +702,10 @@ class SkyvernOverlayMCPServer(MCPServer):
raw_mcp["error"] = " ".join(text_parts) if text_parts else "Unknown MCP error"
else:
raw_mcp["error"] = raw_mcp.get("error") or "Unknown MCP error"
+ failed = raw.is_error or raw_mcp.get("ok", True) is not True
+ _log_mcp_timing(
+ ctx, copilot_name, mcp_tool_name, wall_clock_ms, raw_mcp, "internal", "error" if failed else "ok"
+ )
scrubbed = _scrub_tool_result(ctx, raw_mcp)
return mcp_to_copilot(scrubbed) if scrubbed else {}
diff --git a/skyvern/forge/sdk/copilot/output_utils.py b/skyvern/forge/sdk/copilot/output_utils.py
index 6523d18c5..b001bba40 100644
--- a/skyvern/forge/sdk/copilot/output_utils.py
+++ b/skyvern/forge/sdk/copilot/output_utils.py
@@ -457,6 +457,11 @@ def user_facing_success(
by a precondition/authority blocker signal — the agent was redirected, not broken."""
if result.get("ok", True):
return True
+ # A run waiting on a human approval is the designed outcome of a human_interaction block, not a
+ # break, so it must not stream with failure affect.
+ data = result.get("data")
+ if isinstance(data, dict) and (data.get("control_signal") or {}).get("kind") == "watchdog_paused":
+ return True
return any(
signal.blocker_kind in _NEUTRAL_REDIRECT_BLOCKER_KINDS and _blocker_signal_matches_result(signal, result)
for signal in _iter_blocker_signals(blocker_signal)
diff --git a/skyvern/forge/sdk/copilot/session_factory.py b/skyvern/forge/sdk/copilot/session_factory.py
index 8d7643216..34c50cfee 100644
--- a/skyvern/forge/sdk/copilot/session_factory.py
+++ b/skyvern/forge/sdk/copilot/session_factory.py
@@ -36,6 +36,7 @@ from skyvern.forge.sdk.copilot.enforcement import (
is_screenshot_message,
is_synthetic_user_message,
log_recent_tool_output_truncation,
+ pending_screenshot_message,
)
LOG = structlog.get_logger()
@@ -150,8 +151,25 @@ def _log_tool_pair_repair(moved: int, size_delta: int) -> None:
LOG.info("copilot_tool_pair_repaired", moved=moved, size_delta=size_delta)
+def _run_context(data: CallModelData[Any]) -> Any:
+ """CallModelData carries the run context itself; only some entry points hand over a wrapper."""
+ return data.context.context if isinstance(data.context, RunContextWrapper) else data.context
+
+
def _copilot_call_model_input_filter(data: CallModelData[Any], *, token_budget: int) -> ModelInputData:
- budgeted = _filter_to_budget(data, token_budget=token_budget)
+ items = list(data.model_data.input)
+ # Read-only peek: the end-of-turn drain in enforcement stays the only clear, so a provider
+ # retry or model fallback re-running this filter still carries the frame.
+ screenshot_msg = pending_screenshot_message(_run_context(data))
+ if screenshot_msg is not None:
+ LOG.info(
+ "Injecting screenshot user message",
+ count=len(screenshot_msg["content"]) - 1,
+ path="model_input_filter",
+ )
+ items.append(screenshot_msg)
+
+ budgeted = _filter_to_budget(items, data.model_data.instructions, token_budget=token_budget)
# Last thing before the request leaves: every budget rung above reorders nothing, but
# history assembly upstream can seat a result after a later assistant turn, which the
# provider rejects outright. Repair here so no path can emit an invalid pairing.
@@ -186,8 +204,7 @@ def _maybe_dump_model_input(data: CallModelData[Any], model_data: ModelInputData
try:
from skyvern.forge.sdk.copilot.enforcement import requested_output_paths_for_derivation
- # CallModelData carries the run context itself; only some entry points hand over a wrapper.
- ctx = data.context.context if isinstance(data.context, RunContextWrapper) else data.context
+ ctx = _run_context(data)
try:
requested_output_paths = sorted(requested_output_paths_for_derivation(ctx)) if ctx else []
except Exception:
@@ -213,7 +230,7 @@ def _maybe_dump_model_input(data: CallModelData[Any], model_data: ModelInputData
LOG.warning("Failed to dump copilot model input")
-def _filter_to_budget(data: CallModelData[Any], *, token_budget: int) -> ModelInputData:
+def _filter_to_budget(items: list[Any], instructions: str | None, *, token_budget: int) -> ModelInputData:
"""Token-budget enforcement applied just before each model call.
Graduated pruning:
@@ -224,11 +241,8 @@ def _filter_to_budget(data: CallModelData[Any], *, token_budget: int) -> ModelIn
then to 300 only if the softer pass was not enough.
4. If still over budget: aggressive prune as last resort.
"""
- model_data = data.model_data
- items = list(model_data.input)
-
if not items:
- return ModelInputData(input=items, instructions=model_data.instructions)
+ return ModelInputData(input=items, instructions=instructions)
est = estimate_tokens(items)
LOG.info("Token estimate before filtering", tokens=est)
@@ -243,7 +257,7 @@ def _filter_to_budget(data: CallModelData[Any], *, token_budget: int) -> ModelIn
est = estimate_tokens(items)
if est <= token_budget:
LOG.info("Within budget after tool trim", tokens=est)
- return ModelInputData(input=items, instructions=model_data.instructions)
+ return ModelInputData(input=items, instructions=instructions)
# Layer 2: Drop all screenshots except the most recent
screenshot_indices = [i for i, item in enumerate(items) if is_screenshot_message(item)]
@@ -257,7 +271,7 @@ def _filter_to_budget(data: CallModelData[Any], *, token_budget: int) -> ModelIn
est = estimate_tokens(items)
if est <= token_budget:
LOG.info("Within budget after screenshot drop", tokens=est)
- return ModelInputData(input=items, instructions=model_data.instructions)
+ return ModelInputData(input=items, instructions=instructions)
# Layer 3a: bring every tool output down to the pre-raise bound before resorting
# to the harsher pass, so a code-bearing recent output degrades gracefully.
@@ -266,7 +280,7 @@ def _filter_to_budget(data: CallModelData[Any], *, token_budget: int) -> ModelIn
est = estimate_tokens(items)
if est <= token_budget:
LOG.info("Within budget after soft emergency truncation", tokens=est)
- return ModelInputData(input=items, instructions=model_data.instructions)
+ return ModelInputData(input=items, instructions=instructions)
# Layer 3b: Truncate ALL tool outputs to 300 chars
items = _emergency_truncate_all(items, TOOL_OUTPUT_TRUNCATE_EMERGENCY)
@@ -274,7 +288,7 @@ def _filter_to_budget(data: CallModelData[Any], *, token_budget: int) -> ModelIn
est = estimate_tokens(items)
if est <= token_budget:
LOG.info("Within budget after emergency truncation", tokens=est)
- return ModelInputData(input=items, instructions=model_data.instructions)
+ return ModelInputData(input=items, instructions=instructions)
# Layer 4: Aggressive prune as last resort
LOG.warning("Aggressive prune needed", tokens=est, budget=token_budget)
@@ -282,7 +296,7 @@ def _filter_to_budget(data: CallModelData[Any], *, token_budget: int) -> ModelIn
est = estimate_tokens(items)
LOG.info("Final token estimate after aggressive prune", tokens=est)
- return ModelInputData(input=items, instructions=model_data.instructions)
+ return ModelInputData(input=items, instructions=instructions)
def _truncate_tool_output(item: Any, max_chars: int) -> Any:
diff --git a/skyvern/forge/sdk/copilot/tools/banned_blocks.py b/skyvern/forge/sdk/copilot/tools/banned_blocks.py
index 8be36009a..e6da1fb71 100644
--- a/skyvern/forge/sdk/copilot/tools/banned_blocks.py
+++ b/skyvern/forge/sdk/copilot/tools/banned_blocks.py
@@ -292,7 +292,8 @@ ACTIVE BLOCK AUTHORING POLICY: CODE-ONLY BROWSER MODE
Rules:
- Browser/page/session durable steps must be focused `code` blocks.
- Allowed non-browser helper blocks remain available: `conditional`, `for_loop`,
- `while_loop`, `send_email`, S3/Google Sheets helpers, file parsers, and triggers.
+ `while_loop`, `send_email`, `human_interaction`, S3/Google Sheets helpers, file
+ parsers, and triggers.
- {_code_only_browser_validation_guidance()}
{pending}
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index cfbc12fef..28ee3d0ff 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -605,18 +605,20 @@ def _summarize_action_trace(action_trace: list[dict[str, Any]] | None) -> list[s
# Watchdog exit reasons. ``success`` means the run reached a trustworthy
# terminal status inside the poll loop OR after the post-drain reconcile.
-# The three non-success reasons share the reconcile path but produce distinct
+# The run-ending reasons share the reconcile path but produce distinct
# error messages: ``stagnation`` is the primary trip (no progress signals
# for ``RUN_BLOCKS_STAGNATION_WINDOW_SECONDS`` seconds), ``ceiling`` is the
# last-resort budget-exhausted branch, and ``task_exit_unfinalized`` is the
# rare race where ``execute_workflow`` naturally exits before writing a
-# terminal row.
+# terminal row. ``paused`` is the exception: the run is alive and waiting on a
+# person, so it is neither cancelled nor reconciled.
WatchdogExitReason = Literal[
"success",
"stagnation",
"ceiling",
"per_tool_budget",
"task_exit_unfinalized",
+ "paused",
]
@@ -741,6 +743,16 @@ async def _watchdog_error_message(
f"hidden validation error, or an infinite-retry loop on an action the agent "
f"cannot detect is failing."
)
+ elif exit_reason == "paused":
+ # A pause is a healthy waiting state rather than an uncertain outcome, so it returns here
+ # instead of picking up the shared "outcome is uncertain, do not re-invoke" tail below. This
+ # is the one arm that directs the model to relay its own text, so it carries no run id.
+ return (
+ "The run is paused at a human_interaction block, waiting for a person to approve or "
+ "reject it. It stays paused until someone acts on it in Skyvern or the block's timeout "
+ "elapses; nothing was cancelled. Tell the user the run is paused and what it is waiting "
+ "for, and do not re-run these blocks."
+ )
elif exit_reason == "per_tool_budget":
message = (
f"The run exceeded the {budget_seconds}s per-tool-call budget while still "
@@ -796,6 +808,8 @@ def _watchdog_user_failure_reason(
budget_seconds: int,
run: WorkflowRun | None,
) -> str:
+ if exit_reason == "paused":
+ return "The run is paused, waiting for a person to approve or reject it."
if exit_reason == "stagnation":
body = f"The run stopped after no observable progress for {RUN_BLOCKS_STAGNATION_WINDOW_SECONDS}s."
elif exit_reason == "per_tool_budget":
@@ -815,6 +829,8 @@ def _watchdog_user_facing_summary(
) -> str:
if exit_reason == "stagnation":
return f"The run stopped after no observable progress for {RUN_BLOCKS_STAGNATION_WINDOW_SECONDS}s."
+ if exit_reason == "paused":
+ return "The run is paused, waiting for a person to approve or reject it."
if exit_reason == "per_tool_budget":
return f"The run exceeded the {budget_seconds}s per-tool-call budget while still making progress."
if exit_reason == "ceiling":
@@ -2084,6 +2100,7 @@ async def _run_blocks_and_collect_debug(
raise
active_run_association: ActiveRunSessionAssociation | None = None
+ run_paused = False
if run_detached_from_chat and debug_session_id and run_session_id:
try:
active_run_association = await publish_active_run_session(
@@ -2201,11 +2218,18 @@ async def _run_blocks_and_collect_debug(
exit_reason = "stagnation"
break
+ if is_paused:
+ exit_reason = "paused"
+ run_paused = True
+ break
+
if now - started_monotonic >= budget_seconds:
exit_reason = budget_exit_reason
break
- if exit_reason is not None and exit_reason != "success":
+ if exit_reason is not None and exit_reason not in ("success", "paused"):
+ # A paused run is waiting for a person, so it is deliberately excluded here:
+ # cancelling it would destroy the very state the person was asked to act on.
# Pre-cancel read first: a legitimate self-finalize (user/block
# cancel, or any terminal the run wrote itself) can land between
# the last poll and here, and trusting it avoids the
@@ -2300,6 +2324,12 @@ async def _run_blocks_and_collect_debug(
result[_INTERNAL_RUN_CANCELLED_BY_WATCHDOG_KEY] = True
return result
except asyncio.CancelledError:
+ # A pause is detected several awaits before the result is returned, so a tool timeout
+ # landing in that window reaches here with the run alive and waiting on a person.
+ # Cancelling it would destroy the state the person was asked to act on, so leave the
+ # run to the ``finally`` below, which adopts the executor instead.
+ if run_paused:
+ raise
# The SDK's @function_tool(timeout=...) cancelled us mid-poll. Shield
# the cleanup so the parent cancellation can't interrupt it mid-await.
# If the shield itself is cancelled, fall back to a detached task
@@ -2328,7 +2358,14 @@ async def _run_blocks_and_collect_debug(
# poll loop — signal the run_task so we don't leak it. Dispatched runs have no in-process
# task, so there is nothing to signal.
if run_task is not None and not run_task.done():
- run_task.cancel()
+ if run_paused:
+ # The inline executor coroutine is what observes the approval and resumes the
+ # run, so it has to outlive this tool call instead of being cancelled.
+ _DETACHED_CLEANUP_TASKS.add(run_task)
+ run_task.add_done_callback(_DETACHED_CLEANUP_TASKS.discard)
+ run_task.add_done_callback(_log_detached_cleanup_failure)
+ else:
+ run_task.cancel()
# Soft-delete the pinned draft so it never lingers as the latest version. Gated on a final
# run state: on the normal path the poll loop only exits once the run is terminal, but an
# unexpected exception can reach here before the worker has loaded the draft, and deleting
@@ -2539,7 +2576,9 @@ async def _run_blocks_and_collect_debug(
return build_run_blocks_response(run_ok, result_data)
finally:
- if active_run_association is not None:
+ # A paused run keeps its association so the pane still follows the run the person was
+ # asked to act on; the next run's generation replaces it.
+ if active_run_association is not None and not run_paused:
try:
await clear_active_run_session(
organization_id=active_run_association.organization_id,
@@ -2979,7 +3018,11 @@ def _record_run_blocks_result(
# timeout softens to ``None`` to keep the unvalidated WIP rescue open.
cancelled_by_watchdog = result.get(_INTERNAL_RUN_CANCELLED_BY_WATCHDOG_KEY) is True
timeout_latched = bool(copilot_ctx.copilot_total_timeout_exceeded)
- copilot_ctx.last_test_ok = None if (cancelled_by_watchdog and timeout_latched) else run_ok
+ # A pause softens the same way: left at False the generic failed-test nudge rewrites the reply
+ # into "the test failed" about a run that is alive and waiting, and ``None`` still bars a
+ # verified proposal because that gate requires ``is True``.
+ run_paused = isinstance(data, dict) and (data.get("control_signal") or {}).get("kind") == "watchdog_paused"
+ copilot_ctx.last_test_ok = None if run_paused or (cancelled_by_watchdog and timeout_latched) else run_ok
copilot_ctx.last_full_workflow_test_ok = False
# Re-affirmed per run below only when this run satisfies completion; never let a
# prior run's terminal-ready latch leak into a run that did not verify.
diff --git a/skyvern/forge/sdk/core/security.py b/skyvern/forge/sdk/core/security.py
index 80e5fe454..293b611ef 100644
--- a/skyvern/forge/sdk/core/security.py
+++ b/skyvern/forge/sdk/core/security.py
@@ -1,11 +1,9 @@
import hashlib
import hmac
import json
-import re
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Any, Union
-from urllib.parse import parse_qsl, urlsplit, urlunsplit
import jwt
@@ -64,67 +62,18 @@ def generate_skyvern_signature(
return hash_obj.hexdigest()
-MAX_WEBHOOK_PAYLOAD_LOG_SIZE = 8000 # ~8KB – keeps Datadog log entries manageable
-
-# Any absolute http(s) URL token, up to the next whitespace/quote/angle bracket
-# (a JSON string can't contain a raw " or \), so an embedded URL is matched too,
-# not only a whole-value URL. Case-insensitive to catch uppercase schemes.
-_URL_TOKEN_RE = re.compile(r"https?://[^\s\"\\<>]+", re.IGNORECASE)
-# Query-param names whose presence marks a URL as credentialed: Skyvern HMAC
-# signing (sig), and storage presigns (S3 X-Amz-Signature/Credential/Security-Token,
-# GCS X-Goog-Signature, Azure SAS sig). Any match strips the whole query.
-_URL_SIGNATURE_PARAMS = frozenset(
- {"sig", "x-amz-signature", "x-amz-credential", "x-amz-security-token", "x-goog-signature"}
-)
-
-
-def _strip_credentialed_url_query(match: "re.Match[str]") -> str:
- url = match.group(0)
- try:
- parsed = urlsplit(url)
- except ValueError:
- # Fail closed: an unparseable URL keeps only its pre-query/fragment prefix.
- return re.split(r"[?#]", url, maxsplit=1)[0]
- query_keys = {key.lower() for key, _ in parse_qsl(parsed.query, keep_blank_values=True)}
- if not query_keys & _URL_SIGNATURE_PARAMS:
- return url
- netloc = parsed.netloc.rsplit("@", 1)[-1] # drop any basic-auth userinfo
- return urlunsplit((parsed.scheme, netloc, parsed.path, "", ""))
-
-
-def redact_credentialed_urls(text: str) -> str:
- """Strip signing/presign query params from any credentialed URL in a string.
-
- Covers Skyvern signed content URLs and S3/Azure/GCS presigns, including URLs embedded in a
- larger value; non-credentialed URLs and surrounding text are untouched. For log-only copies.
- """
- return _URL_TOKEN_RE.sub(_strip_credentialed_url_query, text)
-
-
@dataclass
class WebhookSignature:
timestamp: str
signature: str
signed_payload: str
headers: dict[str, str]
- # URL-credential-redacted, truncated copy of the payload — safe for logging.
- payload_for_log: str
def generate_skyvern_webhook_signature(payload: dict, api_key: str) -> WebhookSignature:
payload_str = _normalize_json_dumps(payload)
signature = generate_skyvern_signature(payload=payload_str, api_key=api_key)
timestamp = str(int(datetime.utcnow().timestamp()))
- # Redact signed/presigned URL params before truncating so the log copy never
- # carries replayable credentials. signed_payload stays raw so delivery and the
- # HMAC signature above are unaffected.
- log_payload = redact_credentialed_urls(payload_str)
- if len(log_payload) > MAX_WEBHOOK_PAYLOAD_LOG_SIZE:
- payload_for_log = (
- log_payload[:MAX_WEBHOOK_PAYLOAD_LOG_SIZE] + f"... (truncated, original size: {len(payload_str)})"
- )
- else:
- payload_for_log = log_payload
return WebhookSignature(
timestamp=timestamp,
signature=signature,
@@ -134,5 +83,4 @@ def generate_skyvern_webhook_signature(payload: dict, api_key: str) -> WebhookSi
"x-skyvern-signature": signature,
"Content-Type": "application/json",
},
- payload_for_log=payload_for_log,
)
diff --git a/skyvern/forge/sdk/core/skyvern_context.py b/skyvern/forge/sdk/core/skyvern_context.py
index 4a37b8cf1..6742ecaa8 100644
--- a/skyvern/forge/sdk/core/skyvern_context.py
+++ b/skyvern/forge/sdk/core/skyvern_context.py
@@ -12,6 +12,7 @@ from zoneinfo import ZoneInfo
import structlog
from skyvern.config import settings
+from skyvern.schemas.run_enums import RunEngine
from skyvern.webeye.browser_health import BrowserHealth, BrowserOperation
if TYPE_CHECKING:
@@ -180,6 +181,15 @@ class SkyvernContext:
# Both sites for a run run sequentially, so the read-modify-write needs no lock; verification /
# extraction / error-detection scrapes never touch it.
transient_ui_consecutive_suppressions: int = 0
+ # WORKFLOW_TASK_V3_AB arm, resolved once per workflow run: the engine every default-engine
+ # task block of that run dispatches to, or None for control.
+ workflow_block_engine_override: RunEngine | None = None
+ # The workflow run the override above was resolved for. A nested execution sharing this context
+ # (an inline child workflow run) has its own id and its own definition, so it must re-resolve
+ # rather than inherit an arm that was never checked against its blocks.
+ workflow_block_engine_resolved_run_id: str | None = None
+ # Single-flight the first-use provider resolution when parallel branches share one context.
+ workflow_block_engine_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
enrich_tree_mode: EnrichTreeMode = EnrichTreeMode.CONTROL
step_retry_index: int = 0
diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.py
index e0ed6b244..6391c1c03 100644
--- a/skyvern/forge/sdk/db/models.py
+++ b/skyvern/forge/sdk/db/models.py
@@ -1370,6 +1370,9 @@ class PersistentBrowserSessionModel(Base):
runnable_type = Column(String, nullable=True)
runnable_id = Column(String, nullable=True, index=True)
runnable_generation_id = Column(String, nullable=True)
+ # Canonical download-dir key of the occupying run (``resolve_run_download_id``). Distinct from
+ # ``runnable_id``, the lease id, which diverges on nested/inherited runs.
+ download_run_id = Column(String, nullable=True)
browser_id = Column(String, nullable=True)
browser_address = Column(String, nullable=True, unique=True)
status = Column(String, nullable=True, default="created")
diff --git a/skyvern/forge/sdk/db/repositories/artifacts.py b/skyvern/forge/sdk/db/repositories/artifacts.py
index e72147d4e..67bc752cc 100644
--- a/skyvern/forge/sdk/db/repositories/artifacts.py
+++ b/skyvern/forge/sdk/db/repositories/artifacts.py
@@ -4,8 +4,9 @@ import datetime
from typing import TYPE_CHECKING, Any, Callable
import structlog
-from sqlalchemy import and_, delete, func, or_, select, update
+from sqlalchemy import and_, delete, or_, select, update
from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.sql.elements import ColumnElement
from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType
from skyvern.forge.sdk.db._error_handling import db_operation
@@ -21,6 +22,37 @@ if TYPE_CHECKING:
LOG = structlog.get_logger()
+def _session_download_scope_filters(
+ browser_session_id: str,
+ organization_id: str,
+ run_started_at: datetime.datetime,
+) -> list[ColumnElement[bool]]:
+ """Session-scoped DOWNLOAD rows written inside the run's window. The lower bound applies to
+ stamped rows too: a canonical download key can name a parent workflow, whose pre-start downloads
+ are not this run's."""
+ return [
+ ArtifactModel.browser_session_id == browser_session_id,
+ ArtifactModel.organization_id == organization_id,
+ ArtifactModel.artifact_type == ArtifactType.DOWNLOAD,
+ ArtifactModel.created_at >= run_started_at,
+ ]
+
+
+def _session_download_filters(
+ run_id: str,
+ browser_session_id: str,
+ organization_id: str,
+ run_started_at: datetime.datetime,
+) -> list[ColumnElement[bool]]:
+ """In-window rows attributable to ``run_id``: the watcher stamped this run as producer, or the
+ row is still unbound. The unbound arm is the legacy shape, kept for rows written before
+ stamping."""
+ return [
+ *_session_download_scope_filters(browser_session_id, organization_id, run_started_at),
+ or_(ArtifactModel.run_id == run_id, ArtifactModel.run_id.is_(None)),
+ ]
+
+
class ArtifactsRepository(BaseRepository):
"""Database operations for artifact management."""
@@ -575,52 +607,58 @@ class ArtifactsRepository(BaseRepository):
organization_id: str,
run_started_at: datetime.datetime,
) -> int:
- """Tag session-scoped DOWNLOAD artifacts that landed during this run with ``run_id``.
-
- Called at run finalization with the run's own window, and mid-run by a
- code block registering its downloads, which passes its block row's
- ``created_at`` so a co-tenant run's earlier rows stay unclaimed.
-
- Returns the number of rows updated. Idempotent: re-running picks up
- only ``run_id IS NULL`` rows, so a retry after success is a no-op.
- """
+ """Reconcile in-window session-scoped DOWNLOAD rows the watcher left unbound onto ``run_id``,
+ returning the number updated. Idempotent: an already-stamped row is never re-stamped, so a
+ retry after success is a no-op."""
async with self.Session() as session:
result = await session.execute(
update(ArtifactModel)
- .where(ArtifactModel.browser_session_id == browser_session_id)
- .where(ArtifactModel.organization_id == organization_id)
- .where(ArtifactModel.artifact_type == ArtifactType.DOWNLOAD)
+ .where(*_session_download_scope_filters(browser_session_id, organization_id, run_started_at))
.where(ArtifactModel.run_id.is_(None))
- .where(ArtifactModel.created_at >= run_started_at)
.values(run_id=run_id)
)
await session.commit()
return result.rowcount or 0
- @db_operation("count_unclaimed_session_download_artifacts")
- async def count_unclaimed_session_download_artifacts(
+ @db_operation("bind_session_download_artifact_producer")
+ async def bind_session_download_artifact_producer(
self,
- browser_session_id: str,
+ artifact_id: str,
organization_id: str,
- run_started_at: datetime.datetime,
- ) -> int:
- """Session-scoped DOWNLOAD artifacts this run produced but finalization has not claimed yet.
-
- Read-only counterpart of :meth:`claim_session_download_artifacts_for_run`, matched on the
- same filter so a grader reading before the claim sees this run's files and not a reused
- session's earlier ones. A code block can claim mid-run when artifact content signing is
- configured, so on those deployments this counts only what no block has claimed yet."""
+ run_id: str,
+ ) -> bool:
+ """Fill an unbound row's producing run. Never re-stamps: the watcher re-uploads a download as
+ it grows, and a later observation can fall after the session changed hands."""
async with self.Session() as session:
result = await session.execute(
- select(func.count())
- .select_from(ArtifactModel)
- .where(ArtifactModel.browser_session_id == browser_session_id)
+ update(ArtifactModel)
+ .where(ArtifactModel.artifact_id == artifact_id)
.where(ArtifactModel.organization_id == organization_id)
.where(ArtifactModel.artifact_type == ArtifactType.DOWNLOAD)
.where(ArtifactModel.run_id.is_(None))
- .where(ArtifactModel.created_at >= run_started_at)
+ .values(run_id=run_id)
+ )
+ await session.commit()
+ return bool(result.rowcount)
+
+ @db_operation("list_session_download_artifact_ids_for_run")
+ async def list_session_download_artifact_ids_for_run(
+ self,
+ run_id: str,
+ browser_session_id: str,
+ organization_id: str,
+ run_started_at: datetime.datetime,
+ ) -> set[str]:
+ """Ids of the session-scoped DOWNLOAD artifacts attributable to this run, both stamped and
+ still-unbound in-window rows, so a grader reading before the claim is not short. Ids rather
+ than a count because a caller combining this with a run-scoped read would double-count."""
+ async with self.Session() as session:
+ result = await session.scalars(
+ select(ArtifactModel.artifact_id).where(
+ *_session_download_filters(run_id, browser_session_id, organization_id, run_started_at)
+ )
)
- return int(result.scalar() or 0)
+ return set(result.all())
@db_operation("delete_artifact_for_browser_session")
async def delete_artifact_for_browser_session(
diff --git a/skyvern/forge/sdk/db/repositories/browser_sessions.py b/skyvern/forge/sdk/db/repositories/browser_sessions.py
index fd80c0f03..8e1b80f6a 100644
--- a/skyvern/forge/sdk/db/repositories/browser_sessions.py
+++ b/skyvern/forge/sdk/db/repositories/browser_sessions.py
@@ -661,6 +661,7 @@ class BrowserSessionsRepository(BaseRepository):
values: dict[str, str | None] = {
"bound_workflow_permanent_id": None,
"bound_key": None,
+ "download_run_id": None,
}
if expected_runnable_id is None:
statement = statement.where(PersistentBrowserSessionModel.runnable_id.is_(None))
@@ -877,6 +878,7 @@ class BrowserSessionsRepository(BaseRepository):
provisioning_deadline_at: datetime | None = None,
bound_workflow_permanent_id: str | None = None,
bound_key: str | None = None,
+ download_run_id: str | None = None,
) -> PersistentBrowserSession:
"""Create a new persistent browser session."""
extensions_str: list[str] | None = (
@@ -908,6 +910,7 @@ class BrowserSessionsRepository(BaseRepository):
organization_id=organization_id,
runnable_type=runnable_type,
runnable_id=runnable_id,
+ download_run_id=download_run_id or runnable_id,
timeout_minutes=timeout_minutes,
proxy_location=serialized_proxy_location,
proxy_session_id=proxy_session_id,
@@ -959,10 +962,15 @@ class BrowserSessionsRepository(BaseRepository):
if status:
persistent_browser_session.status = status
+ if status in FINAL_STATUSES:
+ # A session that has reached a final status is no longer producing downloads, so the
+ # producer key must not survive it even when the caller omits completed_at.
+ persistent_browser_session.download_run_id = None
if timeout_minutes:
persistent_browser_session.timeout_minutes = timeout_minutes
if completed_at:
persistent_browser_session.completed_at = to_naive_utc(completed_at)
+ persistent_browser_session.download_run_id = None
if started_at:
persistent_browser_session.started_at = to_naive_utc(started_at)
if generate_browser_profile is not None:
@@ -1089,6 +1097,7 @@ class BrowserSessionsRepository(BaseRepository):
organization_id: str,
*,
runnable_generation_id: str | None = None,
+ download_run_id: str | None = None,
) -> None:
"""Occupy a specific persistent browser session."""
async with self.Session() as session:
@@ -1112,6 +1121,7 @@ class BrowserSessionsRepository(BaseRepository):
runnable_type=runnable_type,
runnable_id=runnable_id,
runnable_generation_id=runnable_generation_id,
+ download_run_id=download_run_id or runnable_id,
)
.returning(PersistentBrowserSessionModel)
)
@@ -1169,9 +1179,9 @@ class BrowserSessionsRepository(BaseRepository):
)
)
result = await session.scalars(
- statement.values(runnable_type=None, runnable_id=None, runnable_generation_id=None).returning(
- PersistentBrowserSessionModel
- )
+ statement.values(
+ runnable_type=None, runnable_id=None, runnable_generation_id=None, download_run_id=None
+ ).returning(PersistentBrowserSessionModel)
)
persistent_browser_session = result.first()
if persistent_browser_session is None:
@@ -1200,6 +1210,7 @@ class BrowserSessionsRepository(BaseRepository):
persistent_browser_session.runnable_type = None
persistent_browser_session.runnable_id = None
persistent_browser_session.runnable_generation_id = None
+ persistent_browser_session.download_run_id = None
await session.commit()
await session.refresh(persistent_browser_session)
return PersistentBrowserSession.model_validate(persistent_browser_session)
@@ -1221,6 +1232,7 @@ class BrowserSessionsRepository(BaseRepository):
return PersistentBrowserSession.model_validate(persistent_browser_session)
persistent_browser_session.completed_at = naive_utc_now()
persistent_browser_session.status = "completed"
+ persistent_browser_session.download_run_id = None
await session.commit()
await session.refresh(persistent_browser_session)
return PersistentBrowserSession.model_validate(persistent_browser_session)
diff --git a/skyvern/forge/sdk/encrypt/bootstrap.py b/skyvern/forge/sdk/encrypt/bootstrap.py
index 6450c675d..26e606c6f 100644
--- a/skyvern/forge/sdk/encrypt/bootstrap.py
+++ b/skyvern/forge/sdk/encrypt/bootstrap.py
@@ -46,9 +46,9 @@ def create_aes_encryptor(
"secret; empty values and the default placeholder 'fillmein' both fail closed."
)
fallback_parameters = list(fallback_decrypt_keys or ())
- # Legacy ciphertext has no version marker. Always retry the pre-SHA-normalization
- # parameters on decrypt, including explicit deployment salt/IV settings.
- fallback_parameters.insert(0, (salt, iv))
+ if not (salt and iv):
+ # Legacy ciphertext has no version marker, so retry the pre-derivation parameters on decrypt.
+ fallback_parameters.insert(0, (salt, iv))
return AES(
secret_key=secret_key,
salt=salt or _derive_from_secret_key(secret_key, _SALT_DERIVATION_LABEL),
diff --git a/skyvern/forge/sdk/experimentation/workflow_block_engine.py b/skyvern/forge/sdk/experimentation/workflow_block_engine.py
new file mode 100644
index 000000000..c6cf29fe4
--- /dev/null
+++ b/skyvern/forge/sdk/experimentation/workflow_block_engine.py
@@ -0,0 +1,101 @@
+from __future__ import annotations
+
+import structlog
+
+from skyvern.forge import app
+from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.experimentation.providers import NoOpExperimentationProvider
+from skyvern.schemas.run_enums import RunEngine
+
+LOG = structlog.get_logger()
+
+WORKFLOW_TASK_V3_AB_FLAG = "WORKFLOW_TASK_V3_AB"
+DISABLE_TASK_V3_FLAG = "DISABLE_TASK_V3"
+
+
+async def task_v3_disabled(distinct_id: str, organization_id: str | None) -> bool:
+ """The Task V3 kill switch, evaluated identically for the dispatch gate and the A/B resolver.
+
+ The provider caches on (flag, distinct_id, properties), so both callers must build the same
+ key or the kill switch can answer differently for the same run.
+ """
+ return await app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached(
+ DISABLE_TASK_V3_FLAG, distinct_id, properties={"organization_id": organization_id}
+ )
+
+
+async def resolve_workflow_block_engine_arm(
+ context: skyvern_context.SkyvernContext,
+ *,
+ workflow_run_id: str,
+ organization_id: str | None,
+ workflow_permanent_id: str | None,
+ run_is_eligible: bool,
+) -> None:
+ """Resolve the workflow-block engine A/B once at execution start and pin the arm on the context.
+
+ Bucketed per workflow run so every block of one run shares an arm. Idempotent per run: once
+ resolved, a TTL expiry or a mid-run flag ramp cannot flip it. The pin records the run it was
+ resolved for, so a nested execution sharing this context -- an inline child workflow run has its
+ own workflow_run_id and its own definition -- re-resolves instead of inheriting an arm that was
+ never checked against its blocks. Control (no override) is the safe default and the outcome of
+ every failure.
+ """
+ if context.workflow_block_engine_resolved_run_id == workflow_run_id:
+ return
+ provider = app.EXPERIMENTATION_PROVIDER
+ if isinstance(provider, NoOpExperimentationProvider):
+ # No experimentation configured (OSS default) -> control, and never query the provider.
+ context.workflow_block_engine_override = None
+ context.workflow_block_engine_resolved_run_id = workflow_run_id
+ return
+ async with context.workflow_block_engine_lock:
+ if context.workflow_block_engine_resolved_run_id == workflow_run_id:
+ return
+ override: RunEngine | None = None
+ try:
+ if run_is_eligible:
+ # The kill switch, shared with the dispatch gate via task_v3_disabled so both
+ # evaluations use the same cache key, wins over the experiment. A kill flipped
+ # mid-run still takes effect at dispatch while these rows already read v3:
+ # stopping the run wins over its attribution.
+ disabled = await task_v3_disabled(workflow_run_id, organization_id)
+ if not disabled and await provider.is_feature_enabled_cached(
+ WORKFLOW_TASK_V3_AB_FLAG,
+ workflow_run_id,
+ properties={
+ "organization_id": organization_id,
+ "workflow_permanent_id": workflow_permanent_id or "not_workflow",
+ },
+ ):
+ override = RunEngine.skyvern_v3
+ except Exception:
+ LOG.warning(
+ "Failed to resolve the workflow-block engine arm; using control",
+ workflow_run_id=workflow_run_id,
+ exc_info=True,
+ )
+ override = None
+ context.workflow_block_engine_override = override
+ context.workflow_block_engine_resolved_run_id = workflow_run_id
+ LOG.info(
+ "Resolved workflow-block engine arm",
+ workflow_run_id=workflow_run_id,
+ workflow_permanent_id=workflow_permanent_id,
+ arm="treatment" if override else "control",
+ run_is_eligible=run_is_eligible,
+ )
+
+
+def workflow_block_engine_override(workflow_run_id: str | None) -> RunEngine | None:
+ """The engine the A/B pinned for this run, or None when the run is control or unresolved.
+
+ Returns None unless the pin was resolved for this exact run, so an execution path that never
+ reaches the resolver (task_v2, the cached-script block helpers) keeps its declared engine.
+ """
+ if not workflow_run_id:
+ return None
+ context = skyvern_context.current()
+ if context is None or context.workflow_block_engine_resolved_run_id != workflow_run_id:
+ return None
+ return context.workflow_block_engine_override
diff --git a/skyvern/forge/sdk/schemas/persistent_browser_sessions.py b/skyvern/forge/sdk/schemas/persistent_browser_sessions.py
index a112d36d5..a3b710e1d 100644
--- a/skyvern/forge/sdk/schemas/persistent_browser_sessions.py
+++ b/skyvern/forge/sdk/schemas/persistent_browser_sessions.py
@@ -72,6 +72,7 @@ class PersistentBrowserSession(BaseModel):
runnable_type: str | None = None
runnable_id: str | None = None
runnable_generation_id: str | None = None
+ download_run_id: str | None = None
browser_address: str | None = None
ip_address: str | None = None
# Server-side only: the upstream CDP endpoint and the adapter that dials it. browser_address
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index f38fe0b65..947b02025 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -140,6 +140,7 @@ from skyvern.forge.sdk.db.enums import TaskType
from skyvern.forge.sdk.db.exceptions import NotFoundError
from skyvern.forge.sdk.db.id import generate_action_id
from skyvern.forge.sdk.experimentation.llm_prompt_config import get_llm_handler_for_prompt_type
+from skyvern.forge.sdk.experimentation.workflow_block_engine import workflow_block_engine_override
from skyvern.forge.sdk.models import Step, StepStatus
from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.schemas.task_v2 import TaskV2Status
@@ -1148,7 +1149,7 @@ class Block(BaseModel, abc.ABC):
engine: RunEngine | None = None
try:
if isinstance(self, BaseTaskBlock):
- engine = self.engine
+ engine = self.resolve_engine(workflow_run_id)
workflow_run_block = await app.DATABASE.observer.create_workflow_run_block(
workflow_run_id=workflow_run_id,
@@ -1303,6 +1304,31 @@ class BaseTaskBlock(Block):
include_action_history_in_verification: bool = False
download_timeout: float | None = None # minutes
include_extracted_text: bool = True
+ # Blocks built at runtime for internal machinery (loop-value and branch-condition extraction)
+ # are not part of the workflow definition, so the run-level engine A/B never saw them and must
+ # not reroute them. Private so an internal experiment toggle stays out of the published block
+ # schemas and out of stored workflow definitions.
+ _exclude_from_engine_ab: bool = PrivateAttr(default=False)
+
+ def resolve_engine(self, workflow_run_id: str | None) -> RunEngine:
+ """The engine this block dispatches to, after the per-run A/B.
+
+ Both the persisted workflow_run_blocks.engine and the execute_step dispatch read this, so
+ the recorded engine cannot disagree with the one that ran. A block pinned to a non-default
+ engine is honored as-authored, and a block the eligibility check never saw is left alone;
+ neither is ever rerouted.
+ """
+ if (
+ self.engine != RunEngine.skyvern_v1
+ or self._exclude_from_engine_ab
+ # Mirrors run_is_eligible_for_v3_ab: a block eligibility skipped as engine-inert must
+ # not be labeled v3 here either, or its row claims an engine that never ran. It does not
+ # re-check _task_block_supports_v3 because run-level eligibility already rejected the
+ # whole run if any block failed it; loosening that predicate means revisiting this.
+ or self.block_type in _ENGINE_INERT_BLOCK_TYPES
+ ):
+ return self.engine
+ return workflow_block_engine_override(workflow_run_id) or self.engine
def get_all_parameters(
self,
@@ -1786,7 +1812,7 @@ class BaseTaskBlock(Block):
browser_session_id=browser_session_id,
close_browser_on_completion=close_browser_on_completion,
complete_verification=self.complete_verification,
- engine=self.engine,
+ engine=self.resolve_engine(workflow_run.workflow_run_id),
)
except Exception as e:
# Make sure the task is marked as failed in the database before raising the exception
@@ -2563,12 +2589,14 @@ class ForLoopBlock(Block):
description="Natural language extraction result",
)
- return ExtractionBlock(
+ extraction_block = ExtractionBlock(
label=f"natural_lang_extraction_{generate_random_string()}",
data_extraction_goal=extraction_goal,
data_schema=data_schema,
output_parameter=output_param,
)
+ extraction_block._exclude_from_engine_ab = True
+ return extraction_block
def _build_loop_graph(
self,
@@ -4624,13 +4652,14 @@ async def _code_block_click_and_claim_download_builtin(
except CodeBlockDownloadClaimError:
raise
except Exception as exc:
+ # Whether a monitor owned the binding is the first question asked of a claim that saw no
+ # event, and it is unanswerable after the fact.
+ claim_monitor_owns_binding = _download_monitor_owns_binding(page)
LOG.info(
"codeblock.download_claim_decision",
engaged=False,
binding=download_binding.value,
- # Recorded on the failure path too: whether a monitor owned the binding is the first
- # question asked of a claim that saw no event, and it is unanswerable after the fact.
- monitor_owns_binding=_download_monitor_owns_binding(page),
+ monitor_owns_binding=claim_monitor_owns_binding,
clicked=click_error is None,
workflow_run_id=workflow_run_id,
organization_id=organization_id,
@@ -4639,11 +4668,12 @@ async def _code_block_click_and_claim_download_builtin(
# A selector that no longer matches is a page failure, not a download that failed to
# fire. Re-raise Playwright's own error so the healing path still recognises its type.
raise click_error
- if download_binding is DownloadBinding.SESSION_DIR:
- # The click landed and this binding's delivery is the session watcher's and the
- # finalization claim's to prove, not this page's to witness. Failing here would fail a
- # download that succeeded; the execution layer still reports an unregistered intent when
- # nothing arrives.
+ if download_binding is DownloadBinding.SESSION_DIR or claim_monitor_owns_binding:
+ # The click landed, and this binding's delivery belongs to the session watcher or to the
+ # monitor -- which denies browser-native downloads and fetches the bytes itself, so no
+ # Download event need ever reach this page. Failing here would fail a download that
+ # succeeded; the execution layer still reports an unregistered intent when nothing
+ # arrives.
return _DOWNLOAD_CLAIM_FALLBACK_STEM
raise CodeBlockDownloadClaimError("Clicking the affordance did not fire a browser download.") from exc
@@ -5075,9 +5105,10 @@ async def wrapper({default_args}):
run_id: str,
session_bound: bool,
) -> None:
- """Tag this run's session-keyed DOWNLOAD artifacts so a run-scoped read can see them.
- The watcher writes them with ``run_id`` NULL because it cannot know which run is active, and
- the window is this block's own row so a co-tenant run's earlier downloads stay unclaimed."""
+ """Reconcile this run's session-keyed DOWNLOAD artifacts so a run-scoped read can see them.
+ The watcher binds the producing run when it observes a download; this picks up rows an older
+ watcher left unbound, windowed on this block's own row so a co-tenant run's earlier downloads
+ stay unclaimed."""
context = skyvern_context.current()
browser_session_id = context.browser_session_id if context else None
if not session_bound:
@@ -14106,6 +14137,7 @@ async def _evaluate_prompt_branch_conditions_batch(
data_schema=data_schema,
output_parameter=output_param,
)
+ extraction_block._exclude_from_engine_ab = True
LOG.info(
"Conditional branch ExtractionBlock created (batched)",
@@ -15038,6 +15070,78 @@ class WorkflowTriggerBlock(Block):
)
+_TASK_V3_SUPPORTED_BLOCK_TYPES = frozenset(
+ {
+ BlockType.TASK,
+ BlockType.NAVIGATION,
+ BlockType.LOGIN,
+ BlockType.ACTION,
+ BlockType.VALIDATION,
+ BlockType.EXTRACTION,
+ }
+)
+
+
+# Task blocks whose engine field never reaches a dispatch decision: a GOTO_URL block's task has no
+# goal or criterion, so execute_step completes it before the v3 gate, and HumanInteractionBlock
+# overrides execute and never calls execute_step at all. They neither qualify nor disqualify a run.
+_ENGINE_INERT_BLOCK_TYPES = frozenset({BlockType.GOTO_URL, BlockType.HUMAN_INTERACTION})
+
+
+def _task_block_supports_v3(task_block: BaseTaskBlock) -> bool:
+ """Whether a workflow task block is eligible to dispatch to the Task V3 native engine.
+
+ v3 doesn't implement download-completion semantics yet, so a block relying on them
+ (complete_on_download / download_suffix / download_timeout) stays on the step engine.
+ """
+ if task_block.block_type not in _TASK_V3_SUPPORTED_BLOCK_TYPES:
+ return False
+ if task_block.complete_on_download or task_block.download_suffix or task_block.download_timeout is not None:
+ return False
+ return True
+
+
+def run_is_eligible_for_v3_ab(blocks: list[BlockTypeVar], *, is_script_run: bool) -> bool:
+ """Whether a whole workflow run may be rerouted onto v3 by the A/B.
+
+ Eligibility is a property of the RUN, not of a block: a run whose blocks disagreed about the
+ engine would drive one browser session with two engines, so no per-run outcome would be
+ attributable to either arm. One participating block v3 cannot execute therefore disqualifies
+ the run, and so does one block pinned to a non-default engine -- that block is honored
+ as-authored in both arms, but it would leave the control arm mixed.
+
+ ``blocks`` must be the flattened definition (``get_all_blocks``), i.e. the superset of task
+ blocks the run could reach. A ``block_labels`` re-run executes only a whitelisted subset of
+ that definition but is still judged against all of it, so one ineligible block elsewhere in the
+ workflow keeps the re-run on control. That is deliberate: scoping eligibility to the subset
+ would have to reproduce exactly which blocks the whitelist reaches, and getting it wrong is the
+ mixed-arm run this predicate exists to prevent -- and a partial re-run is not comparable to a
+ full run in the cohort anyway.
+
+ Script runs are excluded: their blocks execute as cached code and never reach engine dispatch,
+ so treatment would land only on the ai_fallback subset -- the blocks that already failed cached
+ execution.
+ """
+ if is_script_run:
+ return False
+ reroutable_blocks = 0
+ for block in blocks:
+ if not isinstance(block, BaseTaskBlock):
+ continue
+ if block.block_type in _ENGINE_INERT_BLOCK_TYPES:
+ continue
+ if block.engine != RunEngine.skyvern_v1:
+ return False
+ if not _task_block_supports_v3(block):
+ return False
+ if block.totp_verification_url:
+ return False
+ reroutable_blocks += 1
+ # A run with nothing to reroute would be bucketed and recorded as an exposure while both arms
+ # execute identically, diluting the experiment.
+ return reroutable_blocks > 0
+
+
def get_all_blocks(blocks: list[BlockTypeVar]) -> list[BlockTypeVar]:
"""
Recursively get "all blocks" in a workflow definition.
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 7af2f097a..c3f8ef6e2 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -90,6 +90,7 @@ from skyvern.forge.sdk.db.id import generate_output_parameter_id, generate_workf
from skyvern.forge.sdk.enterprise_features import collect_enterprise_gated_run_features
from skyvern.forge.sdk.experimentation.enrich_tree import resolve_enrich_tree_for_context
from skyvern.forge.sdk.experimentation.transient_ui_capture import resolve_transient_ui_capture_arm
+from skyvern.forge.sdk.experimentation.workflow_block_engine import resolve_workflow_block_engine_arm
from skyvern.forge.sdk.forge_log import exception_log_fields
from skyvern.forge.sdk.models import Step, StepStatus
from skyvern.forge.sdk.schemas.browser_profiles import BrowserProfile
@@ -151,6 +152,7 @@ from skyvern.forge.sdk.workflow.models.block import (
compute_conditional_scopes,
get_all_blocks,
resolve_conditional_merge_edges,
+ run_is_eligible_for_v3_ab,
)
from skyvern.forge.sdk.workflow.models.parameter import (
AWSSecretParameter,
@@ -5650,6 +5652,24 @@ class WorkflowService:
is_script_run = await self.should_run_script(workflow, workflow_run)
+ # Resolve the workflow-block engine A/B once, before any block runs: eligibility is a
+ # property of the whole run (see run_is_eligible_for_v3_ab), and every block of a run must
+ # share an arm. Covers the DAG executor too, which this method delegates to.
+ current_context = skyvern_context.current()
+ if current_context:
+ await resolve_workflow_block_engine_arm(
+ current_context,
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ workflow_permanent_id=workflow_run.workflow_permanent_id,
+ run_is_eligible=run_is_eligible_for_v3_ab(all_blocks, is_script_run=is_script_run),
+ )
+ else:
+ LOG.warning(
+ "No context to pin the workflow-block engine arm on; the run stays on control",
+ workflow_run_id=workflow_run_id,
+ )
+
# A cached script can be superseded (e.g. a stale pin replaced by a platform static
# script) — drop it here so the ensure_static_script path below re-creates the pin.
if script and is_script_run:
@@ -9552,30 +9572,31 @@ class WorkflowService:
return workflow_run
- async def _session_download_count(self, workflow_run: WorkflowRun, context: object) -> int:
- """This run's downloads still scoped to the browser session, which cleanup tags with the run
- id after this grade runs — except on deployments with artifact content signing, where a code
- block already claimed them and ``get_downloaded_files`` counts them instead. Failure-tolerant:
- an unavailable count must not manufacture a shortfall."""
- browser_session_id = getattr(context, "browser_session_id", None)
- if not browser_session_id:
- return 0
+ async def _session_download_artifact_ids(
+ self, workflow_run: WorkflowRun, context: SkyvernContext | None, download_run_id: str | None
+ ) -> set[str]:
+ """This run's downloads still scoped to the browser session, whether the watcher already
+ bound them to it or cleanup has yet to. Failure-tolerant: an unavailable read must not
+ manufacture a shortfall."""
+ browser_session_id = context.browser_session_id if context else None
+ if not browser_session_id or not download_run_id:
+ return set()
try:
- # Scoped to this run's window and to rows finalization has not claimed: a reused session
- # carries earlier runs' downloads, which would otherwise satisfy the contract for a run
- # that produced nothing.
- return await app.DATABASE.artifacts.count_unclaimed_session_download_artifacts(
+ # This run as producer plus still-unbound rows in its window: a reused session's
+ # earlier downloads would otherwise satisfy a run that produced nothing.
+ return await app.DATABASE.artifacts.list_session_download_artifact_ids_for_run(
+ run_id=download_run_id,
browser_session_id=browser_session_id,
organization_id=workflow_run.organization_id,
run_started_at=workflow_run.created_at,
)
except Exception:
LOG.warning(
- "Session download count failed while grading; counting zero from this source",
+ "Session download read failed while grading; counting zero from this source",
workflow_run_id=workflow_run.workflow_run_id,
exc_info=True,
)
- return 0
+ return set()
async def _grade_completion_contract(
self,
@@ -9610,22 +9631,30 @@ class WorkflowService:
context = skyvern_context.current()
# Producer and consumer must resolve the same download key: a sub-workflow registers
# files under the parent's run id, so the raw workflow_run_id would read an empty dir.
+ download_run_id = resolve_run_download_id(context, fallback_run_id=workflow_run.workflow_run_id)
files = await app.STORAGE.get_downloaded_files(
organization_id=workflow_run.organization_id,
- run_id=resolve_run_download_id(context, fallback_run_id=workflow_run.workflow_run_id),
- )
- # Session-scoped downloads are only tagged with the run id during cleanup, which runs
- # after this grade. Counting them here keeps a real download from reading as zero;
- # double-counting one file is harmless because the grader only ever needs a floor.
- session_files = await self._session_download_count(workflow_run, context)
- verdict = grade_completion_contract(criteria, registered_download_count=len(files or []) + session_files)
+ run_id=download_run_id,
+ )
+ # Session-scoped downloads may not be registered under the run dir; including them
+ # keeps a real download from reading as zero.
+ session_download_ids = await self._session_download_artifact_ids(workflow_run, context, download_run_id)
+ registered = files or []
+ # The sources overlap on the same resolved run key once rows carry ids, so subtracting
+ # the ids already present in `registered` counts a stamped file once. Without ids the
+ # two reads address different storage prefixes (run dir vs browser_sessions/<id>/
+ # downloads), so they are separate files and both count.
+ registered_ids = {file.artifact_id for file in registered if file.artifact_id}
+ download_count = len(registered) + len(session_download_ids - registered_ids)
+ verdict = grade_completion_contract(criteria, registered_download_count=download_count)
LOG.info(
"workflow_completion_contract_graded",
workflow_run_id=workflow_run.workflow_run_id,
satisfied=verdict.satisfied,
unmet_criterion_ids=list(verdict.unmet_criterion_ids),
- registered_download_count=len(files or []),
- session_download_count=session_files,
+ registered_download_count=len(registered),
+ session_download_count=len(session_download_ids),
+ graded_download_count=download_count,
)
return verdict
except Exception:
@@ -11117,7 +11146,7 @@ class WorkflowService:
try:
async with asyncio.timeout(SAVE_DOWNLOADED_FILES_TIMEOUT):
context = skyvern_context.current()
- finalization_run_id = context.run_id if context and context.run_id else workflow_run.workflow_run_id
+ finalization_run_id = resolve_run_download_id(context, fallback_run_id=workflow_run.workflow_run_id)
try:
await app.STORAGE.save_downloaded_files(
organization_id=workflow_run.organization_id,
@@ -11130,8 +11159,7 @@ class WorkflowService:
workflow_run_id=workflow_run.workflow_run_id,
skipped_file_count=len(exc.skipped_files),
)
- # Tag any session-scoped DOWNLOAD artifacts created during this
- # workflow run with run_id (see
+ # Reconcile session-scoped DOWNLOAD rows the watcher left unbound (see
# cloud_docs/BROWSER_SESSION_DOWNLOAD_ARTIFACTS.md).
browser_session_id = context.browser_session_id if context else None
if browser_session_id and finalization_run_id:
@@ -11325,7 +11353,6 @@ class WorkflowService:
workflow_id=workflow_id,
workflow_run_id=workflow_run.workflow_run_id,
webhook_callback_url=workflow_run.webhook_callback_url,
- payload=signed_data.payload_for_log,
headers=signed_data.headers,
)
return PreparedWorkflowWebhook(
@@ -11335,7 +11362,6 @@ class WorkflowService:
webhook_callback_url=workflow_run.webhook_callback_url,
signed_payload=signed_data.signed_payload,
headers=signed_data.headers,
- payload_for_log=signed_data.payload_for_log,
)
async def deliver_prepared_workflow_webhook(self, webhook: PreparedWorkflowWebhook) -> None:
@@ -11345,7 +11371,6 @@ class WorkflowService:
workflow_id=webhook.workflow_id,
workflow_run_id=webhook.workflow_run_id,
webhook_callback_url=webhook.webhook_callback_url,
- payload=webhook.payload_for_log,
headers=webhook.headers,
)
try:
@@ -11406,8 +11431,6 @@ class WorkflowService:
"Webhook failed",
workflow_id=webhook.workflow_id,
workflow_run_id=webhook.workflow_run_id,
- webhook_data=webhook.payload_for_log,
- resp=resp,
resp_code=resp.status_code,
resp_text=resp.text,
)
diff --git a/skyvern/services/task_v2_service.py b/skyvern/services/task_v2_service.py
index aa56878c6..264144dc2 100644
--- a/skyvern/services/task_v2_service.py
+++ b/skyvern/services/task_v2_service.py
@@ -2840,7 +2840,6 @@ async def send_task_v2_webhook(task_v2: TaskV2, *, success_marker: str = "") ->
LOG.info(
"Task v2 webhook failed",
task_v2_id=task_v2.observer_cruise_id,
- resp=resp,
resp_code=resp.status_code,
resp_text=resp.text,
)
diff --git a/skyvern/services/webhook_delivery.py b/skyvern/services/webhook_delivery.py
index fc89461c6..19427ea78 100644
--- a/skyvern/services/webhook_delivery.py
+++ b/skyvern/services/webhook_delivery.py
@@ -45,7 +45,6 @@ class PreparedWorkflowWebhook:
webhook_callback_url: str
signed_payload: str
headers: dict[str, str]
- payload_for_log: str
def is_retryable_status(status_code: int) -> bool:
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index 05211fd19..ebf18a1f6 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -163,7 +163,7 @@ from skyvern.webeye.actions.actions import (
from skyvern.webeye.actions.responses import ActionAbort, ActionFailure, ActionResult, ActionSuccess
from skyvern.webeye.browser_artifacts import DownloadBinding
from skyvern.webeye.browser_engine import UNSET_SELECTION, BrowserEngineSelection, resolve_engine_selection_for_task
-from skyvern.webeye.browser_factory import initialize_download_dir, resolve_artifact_path
+from skyvern.webeye.browser_factory import initialize_download_dir, read_download_failure, resolve_artifact_path
from skyvern.webeye.browser_state import BLANK_PAGE_URLS, BrowserState
from skyvern.webeye.cdp_download_interceptor import (
DOWNLOAD_MIME_TYPES,
@@ -228,6 +228,10 @@ DOWNLOAD_NOT_TRIGGERED_FOLLOWUP_MESSAGE = (
"No file download was observed or credited after this action. "
"If the goal still requires this file, keep trying to download it rather than reporting the goal complete."
)
+DOWNLOAD_ABORTED_FAILURE_MESSAGE = (
+ "The browser started this download but aborted it before any file was saved. "
+ "The download link may have expired; regenerate it before trying the download again."
+)
SENSITIVE_CLIPBOARD_CLEAR_FAILED_FOLLOWUP_MESSAGE = (
"The sensitive paste completed, but the clipboard could not be cleared. "
"Do not repeat the paste; stop and report the clipboard safety failure."
@@ -4266,6 +4270,24 @@ class ActionHandler:
)
if downloaded_file_names:
results[-1].downloaded_files = action.downloaded_files = downloaded_file_names
+ elif (
+ captured_download is not None
+ and (aborted_reason := await read_download_failure(captured_download)) is not None
+ ):
+ # The partial file appearing is what credited download_triggered, and the browser
+ # deletes it on abort, so the settle above reads an aborted transfer as a completed
+ # one. Without this the action reports success with no file and the agent retries
+ # the already-consumed link instead of regenerating it.
+ LOG.warning(
+ "Browser aborted the download after it was credited; no file was saved",
+ workflow_run_id=task.workflow_run_id,
+ download_dir=download_dir,
+ failure=aborted_reason,
+ )
+ results[-1] = ActionFailure(
+ Exception(f"{DOWNLOAD_ABORTED_FAILURE_MESSAGE} (browser reported: {aborted_reason})"),
+ download_triggered=True,
+ )
if xhr_fallback_moved_paths:
post_settle_extra_paths = new_file_paths - xhr_fallback_moved_paths
if post_settle_extra_paths:
@@ -8463,6 +8485,11 @@ async def chain_click(
# File choosers are impossible to close if you don't expect one. Instead of dealing with it, close it!
dom = DomUtil(scraped_page=scraped_page, page=page)
+ composite_source = skyvern_element
+ composite_target_id = composite_source.get_id()
+ skyvern_element = await dom.resolve_effective_click_target(composite_source)
+ if skyvern_element.get_id() != composite_target_id and await skyvern_element.is_disabled(dynamic=True):
+ return [ActionFailure(InteractWithDisabledElement(skyvern_element.get_id()))]
locator = skyvern_element.locator
click_count = _get_click_count(action)
# TODO (suchintan): This should likely result in an ActionFailure -- we can figure out how to do this later!
@@ -8729,6 +8756,7 @@ async def chain_click(
coordinate_error: Exception | None = None
if not skip_coordinate_click:
try:
+ skyvern_element = await dom.resolve_effective_click_target(composite_source)
await skyvern_element.coordinate_click(page=page, click_count=click_count)
except Exception as e:
coordinate_error = e
@@ -8778,6 +8806,7 @@ async def chain_click(
locator=locator,
)
try:
+ skyvern_element = await dom.resolve_effective_click_target(composite_source)
await skyvern_element.click_in_javascript()
except Exception as e:
action_results.append(ActionFailure(FailToClick(action.element_id, anchor="self_js", msg=str(e))))
@@ -9276,7 +9305,18 @@ async def choose_auto_completion_dropdown(
finally:
await incremental_scraped.stop_listen_dom_increment()
if clear_input and await skyvern_element.is_visible():
- await skyvern_element.input_clear()
+ try:
+ await skyvern_element.input_clear()
+ except Exception:
+ # Best-effort cleanup of the probe text typed above; an exception raised here
+ # (e.g. InvalidElementForTextInput when the live node no longer matches the
+ # scraped tag) would otherwise escape this finally block and clobber whatever
+ # `result`/exception the try/except above already produced, denying the
+ # caller's designed fallback chain (retry -> full-dropdown discovery -> plain fill).
+ LOG.info(
+ "Failed to clear the auto-completion probe text, but continue",
+ element_id=skyvern_element.get_id(),
+ )
def remove_duplicated_HTML_element(elements: list[dict]) -> list[dict]:
@@ -10362,7 +10402,63 @@ async def _verify_custom_select_option(
# input_text_converted is excluded: its anchor is frequently not an <input>, so the reset path that
# contains an unverified click does not exist for it.
_EXECUTABLE_CUSTOM_SELECT_ENTRIES = ("select_option", "input_text")
-_CUSTOM_SELECT_VERIFY_SETTLE_RETRY_DELAYS_SECONDS = (0.15, 0.15)
+# The timer is only a liveness cap for frame-starved/background pages and vendor CDP engines. Double-rAF
+# remains the normal render-driven path; the timer does not claim that rendering has become stable.
+_CUSTOM_SELECT_RENDER_SETTLE_JS = (
+ "() => Promise.race(["
+ "new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve('raf')))),"
+ "new Promise((resolve) => setTimeout(() => resolve('liveness_fallback'), 250))"
+ "])"
+)
+
+
+class _CustomSelectRenderSettle(NamedTuple):
+ source: str
+ elapsed_ms: int
+
+
+async def _wait_custom_select_render_settle(element: SkyvernElement) -> _CustomSelectRenderSettle:
+ started_at = time.monotonic()
+ source = await _evaluate_element_scoped(element, _CUSTOM_SELECT_RENDER_SETTLE_JS)
+ return _CustomSelectRenderSettle(
+ source=source if source in {"raf", "liveness_fallback"} else "unknown",
+ elapsed_ms=int((time.monotonic() - started_at) * 1000),
+ )
+
+
+def _custom_select_settle_summary(settles: list[_CustomSelectRenderSettle]) -> tuple[str, int]:
+ source = "liveness_fallback" if any(settle.source == "liveness_fallback" for settle in settles) else "raf"
+ if not settles:
+ source = "not_run"
+ elif any(settle.source == "unknown" for settle in settles):
+ source = "unknown"
+ return source, sum(settle.elapsed_ms for settle in settles)
+
+
+def _log_custom_select_verification_outcome(
+ event: str,
+ *,
+ phase: str,
+ settles: list[_CustomSelectRenderSettle],
+ committed: bool,
+ verification_branch: str,
+ verification_reason: str,
+ recovery_attempted: bool,
+ recovery_succeeded: bool,
+) -> None:
+ render_settle_source, render_settle_elapsed_ms = _custom_select_settle_summary(settles)
+ LOG.info(
+ event,
+ phase=phase,
+ render_settle_source=render_settle_source,
+ render_settle_count=len(settles),
+ render_settle_elapsed_ms=render_settle_elapsed_ms,
+ committed=committed,
+ verification_branch=verification_branch,
+ verification_reason=verification_reason,
+ recovery_attempted=recovery_attempted,
+ recovery_succeeded=recovery_succeeded,
+ )
async def _verify_custom_select_option_with_settle(
@@ -10373,16 +10469,14 @@ async def _verify_custom_select_option_with_settle(
matched_element_id: str,
matched_label: str | None,
use_strict_verification: bool,
+ settle_outcomes: list[_CustomSelectRenderSettle] | None = None,
) -> tuple[bool, str]:
- """Retry the read-back a couple of times before giving up.
-
- Some frameworks commit ``aria-selected``/trigger-text reflection on the next render tick
- rather than synchronously on click, so an immediate read-back can read stale state. Retries
- only fire on the failure path; a confirmed read-back returns immediately with no added delay.
- """
- for delay_seconds in (0.0, *_CUSTOM_SELECT_VERIFY_SETTLE_RETRY_DELAYS_SECONDS):
- if delay_seconds:
- await asyncio.sleep(delay_seconds)
+ """Read back after bounded render turns so framework reconciliation is causally observable."""
+ settle_element = readback_scope_element or matched_element
+ for _ in range(2):
+ settle = await _wait_custom_select_render_settle(settle_element)
+ if settle_outcomes is not None and isinstance(settle, _CustomSelectRenderSettle):
+ settle_outcomes.append(settle)
verified, branch = await _verify_custom_select_option(
matched_element=matched_element,
readback_scope_element=readback_scope_element,
@@ -10474,6 +10568,8 @@ async def _select_deterministic_custom_option(
select_depth: int = 0,
on_click_attempted: Callable[[], None] | None = None,
on_reset_fallback: Callable[[Callable[[CustomSelectFamilyOutcome], None]], None] | None = None,
+ settle_outcomes: list[_CustomSelectRenderSettle] | None = None,
+ post_failed_click_commit_recovery: bool = False,
engine_selection: BrowserEngineSelection | None = UNSET_SELECTION,
) -> tuple[ActionResult, str | None] | None:
if engine_selection is UNSET_SELECTION:
@@ -10540,7 +10636,7 @@ async def _select_deterministic_custom_option(
COLLAPSE_CUSTOM_SELECT_FANOUT_FLAG,
"collapse-custom-select-fanout",
)
- if gate.gate_error:
+ if gate.gate_error and not post_failed_click_commit_recovery:
emit(CustomSelectFamilyOutcome.llm_fallback_gate_error)
return None
@@ -10565,10 +10661,10 @@ async def _select_deterministic_custom_option(
option_count = len(option_candidates)
eligible = not resolution.fallback_to_llm and resolution.matched_index is not None
match_tier = resolution.matched_tier
- if not gate.family_enabled:
+ if not gate.family_enabled and not post_failed_click_commit_recovery:
emit(CustomSelectFamilyOutcome.llm_fallback_family_off)
return None
- if gate.assigned is False:
+ if gate.assigned is False and not post_failed_click_commit_recovery:
emit(CustomSelectFamilyOutcome.llm_fallback_control)
return None
if resolution.fallback_to_llm or resolution.matched_index is None:
@@ -10674,6 +10770,7 @@ async def _select_deterministic_custom_option(
matched_element_id=element_id,
matched_label=matched_label,
use_strict_verification=anchor_is_combobox_input and allow_single_value_scope,
+ settle_outcomes=settle_outcomes,
)
if verified:
emit(CustomSelectFamilyOutcome.success_verified)
@@ -10824,6 +10921,66 @@ def _collect_new_roots(element: dict, new_ids: set[str], out: list[dict]) -> Non
_collect_new_roots(child, new_ids, out)
+def _custom_select_anchor_ownership(element: dict | None) -> tuple[str, frozenset[str]] | None:
+ if not element:
+ return None
+ attributes = element.get("attributes") or {}
+ role = str(attributes.get("role") or "").lower()
+ owned_ids = frozenset(
+ token
+ for attribute in ("aria-controls", "aria-owns")
+ for token in str(attributes.get(attribute) or "").split()
+ if token
+ )
+ if role != "combobox" or not owned_ids:
+ return None
+ return role, owned_ids
+
+
+def _resolve_owned_custom_select_recovery(
+ *,
+ original_anchor: dict | None,
+ refreshed_page: ScrapedPage,
+) -> tuple[str, list[dict]] | None:
+ ownership = _custom_select_anchor_ownership(original_anchor)
+ if ownership is None:
+ return None
+
+ matching_anchor_ids = _matching_custom_select_anchor_ids(ownership, refreshed_page)
+ if len(matching_anchor_ids) != 1:
+ return None
+
+ owned_ids = ownership[1]
+ matching_roots = [
+ element
+ for element in refreshed_page.elements
+ if str((element.get("attributes") or {}).get("id") or "") in owned_ids
+ and str((element.get("attributes") or {}).get("role") or "").lower() == "listbox"
+ and element.get("id")
+ ]
+ if len(matching_roots) != 1:
+ return None
+
+ owned_subtrees = _extract_new_subtrees(
+ refreshed_page.element_tree_trimmed,
+ {str(matching_roots[0]["id"])},
+ )
+ if len(owned_subtrees) != 1:
+ return None
+ return matching_anchor_ids[0], owned_subtrees
+
+
+def _matching_custom_select_anchor_ids(
+ ownership: tuple[str, frozenset[str]],
+ refreshed_page: ScrapedPage,
+) -> list[str]:
+ return [
+ str(element["id"])
+ for element in refreshed_page.elements
+ if _custom_select_anchor_ownership(element) == ownership and element.get("id")
+ ]
+
+
@traced(name="skyvern.agent.dropdown.select_emerging")
async def select_from_emerging_elements(
current_element_id: str,
@@ -10959,6 +11116,17 @@ async def select_from_emerging_elements(
# string raises ValueError and would mask the OPTION_NOT_AVAILABLE signal.
raw_action_type: str = (json_response.get("action_type") or "").lower()
element_id: str | None = json_response.get("id", None)
+ requested_value = options.target_value if _normalize_select_shadow_text(options.target_value) else None
+ if requested_value is None and _normalize_select_shadow_text(value):
+ requested_value = value
+ if requested_value is None and raw_action_type == ActionType.CLICK.value and element_id:
+ clicked_candidates = [
+ candidate
+ for candidate in _custom_select_candidates_from_elements(shadow_candidate_elements)
+ if candidate["element_id"] == element_id and _normalize_select_shadow_text(candidate["label"])
+ ]
+ if len(clicked_candidates) == 1:
+ requested_value = clicked_candidates[0]["label"]
_log_select_shadow_match(
prompt_name="custom-select/emerging",
target_value=options.target_value,
@@ -11028,9 +11196,166 @@ async def select_from_emerging_elements(
if await selected_element.get_attr("role") == "listbox":
return ActionFailure(exception=InteractWithDropdownContainer(element_id=element_id))
+ original_anchor = scraped_page_after_open.id_to_element_dict.get(current_element_id)
await selected_element.scroll_into_view()
await selected_element.click(page=page, engine_selection=engine_selection)
- return ActionSuccess()
+ readback_scope_element = await _resolve_custom_select_readback_scope_element(
+ get_readback_scope_element=get_readback_scope_element,
+ target_value=options.target_value or "",
+ matched_element_id=element_id,
+ matched_label=requested_value,
+ )
+ anchor_is_combobox_input = await _anchor_is_combobox_input(readback_scope_element)
+ initial_settles: list[_CustomSelectRenderSettle] = []
+ verification_branch = "none"
+ try:
+ verified, verification_branch = await _verify_custom_select_option_with_settle(
+ matched_element=selected_element,
+ readback_scope_element=readback_scope_element,
+ anchor_is_combobox_input=anchor_is_combobox_input,
+ matched_element_id=element_id,
+ matched_label=requested_value,
+ use_strict_verification=True,
+ settle_outcomes=initial_settles,
+ )
+ if verified:
+ final_settle = await _wait_custom_select_render_settle(readback_scope_element or selected_element)
+ if isinstance(final_settle, _CustomSelectRenderSettle):
+ initial_settles.append(final_settle)
+ verified, verification_branch = await _verify_custom_select_option(
+ matched_element=selected_element,
+ readback_scope_element=readback_scope_element,
+ anchor_is_combobox_input=anchor_is_combobox_input,
+ matched_element_id=element_id,
+ matched_label=requested_value,
+ use_strict_verification=True,
+ )
+ except Exception:
+ LOG.info(
+ "Custom-select primary commit verification exception",
+ phase="initial_click",
+ exc_info=True,
+ )
+ _log_custom_select_verification_outcome(
+ "Custom-select commit verification outcome",
+ phase="initial_click",
+ settles=initial_settles,
+ committed=False,
+ verification_branch="none",
+ verification_reason="verification_error",
+ recovery_attempted=False,
+ recovery_succeeded=False,
+ )
+ return _terminal_custom_select_failure(
+ target_value=options.target_value or requested_value or "",
+ matched_label=requested_value,
+ )[0]
+ _log_custom_select_verification_outcome(
+ "Custom-select commit verification outcome",
+ phase="initial_click",
+ settles=initial_settles,
+ committed=verified,
+ verification_branch=verification_branch,
+ verification_reason="verified" if verified else "not_committed",
+ recovery_attempted=not verified,
+ recovery_succeeded=False,
+ )
+ if verified:
+ return ActionSuccess()
+
+ recovery_settles: list[_CustomSelectRenderSettle] = []
+ recovery_reason = "not_committed"
+ try:
+ refreshed_page = await scraped_page_after_open.generate_scraped_page_without_screenshots()
+ refreshed_dom = DomUtil(scraped_page=refreshed_page, page=page, engine_selection=engine_selection)
+ ownership = _custom_select_anchor_ownership(original_anchor)
+ if ownership is None:
+ raise ValueError("Custom-select recovery ownership is missing")
+ matching_anchor_ids = _matching_custom_select_anchor_ids(ownership, refreshed_page)
+ if len(matching_anchor_ids) != 1:
+ raise ValueError("Custom-select recovery anchor is missing or ambiguous")
+ recovered_anchor_id = matching_anchor_ids[0]
+ recovered_anchor = await refreshed_dom.get_skyvern_element_by_id(recovered_anchor_id)
+ if await recovered_anchor.get_locator().get_attribute("aria-expanded") != "true":
+ await recovered_anchor.click(page=page, engine_selection=engine_selection)
+ refreshed_page = await scraped_page_after_open.generate_scraped_page_without_screenshots()
+ refreshed_dom = DomUtil(scraped_page=refreshed_page, page=page, engine_selection=engine_selection)
+ owned_recovery = _resolve_owned_custom_select_recovery(
+ original_anchor=original_anchor,
+ refreshed_page=refreshed_page,
+ )
+ if owned_recovery is None:
+ raise ValueError("Custom-select recovery ownership is missing or ambiguous")
+ recovered_anchor_id, refreshed_option_elements = owned_recovery
+ recovery_result = await _select_deterministic_custom_option(
+ execute=True,
+ target_value=requested_value,
+ get_option_candidates=lambda: _custom_select_candidates_from_elements(refreshed_option_elements),
+ field_context=options.model_dump(),
+ page=page,
+ get_skyvern_element=refreshed_dom.get_skyvern_element_by_id,
+ get_readback_scope_element=lambda: refreshed_dom.get_skyvern_element_by_id(recovered_anchor_id),
+ task=task,
+ step=step,
+ entry_action_type=entry_action_type,
+ selection_group_id=selection_group_id,
+ select_depth=1,
+ settle_outcomes=recovery_settles,
+ post_failed_click_commit_recovery=True,
+ engine_selection=engine_selection,
+ )
+ except Exception:
+ LOG.info(
+ "Custom-select deterministic recovery exception",
+ phase="recovery",
+ exc_info=True,
+ )
+ recovery_reason = "recovery_error"
+ recovery_result = None
+
+ recovery_committed = False
+ recovery_branch = "none"
+ if recovery_result is not None and isinstance(recovery_result[0], ActionSuccess):
+ try:
+ recovered_label = requested_value if requested_value is not None else recovery_result[1]
+ expected_label = _normalize_select_shadow_text(recovered_label)
+ recovered_scope = await refreshed_dom.get_skyvern_element_by_id(recovered_anchor_id)
+ recovery_settle = await _wait_custom_select_render_settle(recovered_scope)
+ if isinstance(recovery_settle, _CustomSelectRenderSettle):
+ recovery_settles.append(recovery_settle)
+ recovery_committed, recovery_branch = await _custom_select_scope_confirms_committed(
+ readback_scope_element=recovered_scope,
+ anchor_is_combobox_input=await _anchor_is_combobox_input(recovered_scope),
+ matched_element_id=element_id,
+ matched_label=recovered_label,
+ expected_label=expected_label,
+ allow_aria_selected_option_tokens=False,
+ allow_single_value_scope=True,
+ )
+ except Exception:
+ LOG.info(
+ "Custom-select recovery commit verification exception",
+ phase="recovery",
+ exc_info=True,
+ )
+ recovery_reason = "verification_error"
+ recovery_committed = False
+ _log_custom_select_verification_outcome(
+ "Custom-select recovery outcome",
+ phase="recovery",
+ settles=recovery_settles,
+ committed=recovery_committed,
+ verification_branch=recovery_branch,
+ verification_reason="verified" if recovery_committed else recovery_reason,
+ recovery_attempted=True,
+ recovery_succeeded=recovery_committed,
+ )
+ if recovery_committed and recovery_result is not None:
+ return recovery_result[0]
+ return _terminal_custom_select_failure(
+ target_value=requested_value or "",
+ matched_label=requested_value,
+ )[0]
@traced(name="skyvern.agent.dropdown.select")
diff --git a/skyvern/webeye/actions/parse_actions.py b/skyvern/webeye/actions/parse_actions.py
index cad99a8bf..1712e5598 100644
--- a/skyvern/webeye/actions/parse_actions.py
+++ b/skyvern/webeye/actions/parse_actions.py
@@ -155,7 +155,7 @@ def parse_action(
input_or_select_context = InputOrSelectContext.model_validate(context_dict)
return InputTextAction(
**base_action_dict,
- text=action["text"],
+ text=action.get("text"),
input_or_select_context=input_or_select_context,
totp_code_required=totp_code_required,
)
@@ -163,22 +163,22 @@ def parse_action(
if action_type == ActionType.PASTE_TEXT:
return PasteTextAction(
**base_action_dict,
- text=action["text"],
+ text=action.get("text"),
)
if action_type == ActionType.UPLOAD_FILE:
# TODO: see if the element is a file input element. if it's not, convert this action into a click action
return UploadFileAction(
**base_action_dict,
- file_url=action["file_url"],
+ file_url=action.get("file_url"),
)
# This action is not used in the current implementation. Click actions are used instead.
if action_type == ActionType.DOWNLOAD_FILE:
- return DownloadFileAction(**base_action_dict, file_name=action["file_name"])
+ return DownloadFileAction(**base_action_dict, file_name=action.get("file_name"))
if action_type == ActionType.SELECT_OPTION:
- option = action["option"]
+ option = action.get("option")
if option is None:
raise ValueError("SelectOptionAction requires an 'option' field")
@@ -206,7 +206,7 @@ def parse_action(
if action_type == ActionType.CHECKBOX:
return CheckboxAction(
**base_action_dict,
- is_checked=action["is_checked"],
+ is_checked=action.get("is_checked"),
)
if action_type == ActionType.WAIT:
@@ -354,7 +354,7 @@ def parse_action(
@traced(name="skyvern.agent.parse_actions")
def parse_actions(
- task: Task, step_id: str, step_order: int, scraped_page: ScrapedPage, json_response: list[Dict[str, Any]]
+ task: Task, step_id: str, step_order: int, scraped_page: ScrapedPage, json_response: list[Any]
) -> list[Action]:
actions: list[Action] = []
_span = otel_trace.get_current_span()
@@ -362,7 +362,14 @@ def parse_actions(
context = skyvern_context.ensure_context()
totp_code = context.totp_codes.get(task.task_id)
totp_code_required = bool(totp_code)
+ non_object_entries: list[Any] = []
for idx, action in enumerate(json_response):
+ # A planner refusal repaired into the actions array arrives as prose, and one bad
+ # response can carry dozens of such fragments. Collect them for a single log rather
+ # than letting each one fail inside parse_action.
+ if not isinstance(action, dict):
+ non_object_entries.append(action)
+ continue
try:
action_instance = parse_action(
action=action,
@@ -409,6 +416,16 @@ def parse_actions(
exc_info=True,
)
+ if non_object_entries:
+ LOG.warning(
+ "Skipped non-object entries in the actions array",
+ task_id=task.task_id,
+ skipped_count=len(non_object_entries),
+ raw_action_count=len(json_response),
+ parsed_action_count=len(actions),
+ sample_entries=[str(entry)[:200] for entry in non_object_entries[:3]],
+ )
+
############################ This part of code might not be needed ############################
# Reason #1. validation can be done in action handler but not in parser
# Reason #2. no need to validate whether the element_id has a hash.
diff --git a/skyvern/webeye/browser_factory.py b/skyvern/webeye/browser_factory.py
index 4c14f6825..75e558069 100644
--- a/skyvern/webeye/browser_factory.py
+++ b/skyvern/webeye/browser_factory.py
@@ -322,6 +322,23 @@ def _consume_abandoned_task_result(task: asyncio.Task) -> None:
task.exception()
+DOWNLOAD_FAILURE_READ_TIMEOUT_SECONDS = 5.0
+
+
+async def read_download_failure(download: Download) -> str | None:
+ """Return the browser's failure string for a download, or None if it finished or is unreadable.
+
+ Chromium deletes the partial file when it aborts a transfer, so an aborted download and a
+ completed one look identical from a directory listing; this is the only authoritative signal.
+ Never raises — callers use it to report an outcome, not to control the download.
+ """
+ try:
+ async with asyncio.timeout(DOWNLOAD_FAILURE_READ_TIMEOUT_SECONDS):
+ return await download.failure()
+ except Exception:
+ return None
+
+
def set_popup_video_listener(browser_context: BrowserContext, browser_artifacts: BrowserArtifacts) -> None:
tracked_paths: set[str] = set()
@@ -452,6 +469,18 @@ def set_download_file_listener(
# TODO: maybe should try to parse it from URL response
except Exception:
+ # An aborted transfer surfaces here as a path() error; reporting it as a rename failure
+ # sends triage to the wrong subsystem and hides that no file was ever saved.
+ failure = await read_download_failure(download)
+ if failure is not None:
+ LOG.warning(
+ "Browser aborted the download before any file was saved",
+ workflow_run_id=workflow_run_id,
+ task_id=task_id,
+ failure=failure,
+ url=_redact_url_query(download.url),
+ )
+ return
LOG.exception(
"Failed to add file extension name to downloaded file",
workflow_run_id=workflow_run_id,
diff --git a/skyvern/webeye/default_persistent_sessions_manager.py b/skyvern/webeye/default_persistent_sessions_manager.py
index 14fe62419..d45825603 100644
--- a/skyvern/webeye/default_persistent_sessions_manager.py
+++ b/skyvern/webeye/default_persistent_sessions_manager.py
@@ -15,6 +15,8 @@ from skyvern.cli.core.session_manager import active_copilot_session_ids
from skyvern.config import settings
from skyvern.exceptions import BrowserSessionClosed, BrowserSessionNotRenewable, MissingBrowserAddressError
from skyvern.forge import app
+from skyvern.forge.sdk.api.files import resolve_run_download_id
+from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.db.agent_db import AgentDB
from skyvern.forge.sdk.db.polls import wait_on_persistent_browser_address
from skyvern.forge.sdk.schemas.persistent_browser_sessions import (
@@ -257,6 +259,7 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):
runnable_id=runnable_id,
organization_id=organization_id,
runnable_generation_id=runnable_generation_id,
+ download_run_id=resolve_run_download_id(skyvern_context.current(), fallback_run_id=runnable_id),
)
LOG.info("Browser session begin", browser_session_id=browser_session_id)
@@ -420,6 +423,7 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):
inherit_profile_proxy=inherit_profile_proxy,
bound_workflow_permanent_id=bound_workflow_permanent_id,
bound_key=bound_key,
+ download_run_id=resolve_run_download_id(skyvern_context.current(), fallback_run_id=runnable_id),
)
# Launch the browser immediately for standalone sessions so the
@@ -523,6 +527,7 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):
organization_id: str,
*,
runnable_generation_id: str | None = None,
+ download_run_id: str | None = None,
) -> None:
"""Occupy a specific browser session."""
await self.database.browser_sessions.occupy_persistent_browser_session(
@@ -531,6 +536,7 @@ class DefaultPersistentSessionsManager(PersistentSessionsManager):
runnable_id=runnable_id,
organization_id=organization_id,
runnable_generation_id=runnable_generation_id,
+ download_run_id=download_run_id,
)
async def renew_or_close_session(self, session_id: str, organization_id: str) -> PersistentBrowserSession:
diff --git a/skyvern/webeye/persistent_sessions_manager.py b/skyvern/webeye/persistent_sessions_manager.py
index cf5735720..b7002db44 100644
--- a/skyvern/webeye/persistent_sessions_manager.py
+++ b/skyvern/webeye/persistent_sessions_manager.py
@@ -164,6 +164,7 @@ class PersistentSessionsManager(Protocol):
organization_id: str,
*,
runnable_generation_id: str | None = None,
+ download_run_id: str | None = None,
) -> None:
"""Occupy a browser session for use."""
...
diff --git a/skyvern/webeye/utils/dom.py b/skyvern/webeye/utils/dom.py
index cfad091d4..e6671edd7 100644
--- a/skyvern/webeye/utils/dom.py
+++ b/skyvern/webeye/utils/dom.py
@@ -1624,3 +1624,68 @@ class DomUtil:
except Exception:
LOG.warning("Failed to get skyvern element by id", element_id=element_id, exc_info=True)
return None
+
+ def _ancestor_path(self, element_id: str) -> list[dict]:
+ def _find(nodes: list[dict], ancestors: list[dict]) -> list[dict] | None:
+ for node in nodes:
+ if not isinstance(node, dict):
+ continue
+ if node.get("id") == element_id:
+ return ancestors
+ children = node.get("children")
+ if isinstance(children, list):
+ result = _find(children, [*ancestors, node])
+ if result is not None:
+ return result
+ return None
+
+ tree = self.scraped_page.element_tree
+ if not isinstance(tree, list):
+ return []
+ return _find(tree, []) or []
+
+ async def resolve_effective_click_target(self, element: SkyvernElement) -> SkyvernElement:
+ static = element.get_element_dict()
+ tag_name = element.get_tag_name().lower()
+ if tag_name in {InteractiveElement.A, InteractiveElement.INPUT, InteractiveElement.SELECT}:
+ return element
+ if tag_name == InteractiveElement.BUTTON and not static.get("hoverOnly", False):
+ return element
+ if static.get("interactable", False) and not static.get("hoverOnly", False):
+ return element
+
+ for ancestor in reversed(self._ancestor_path(element.get_id())):
+ ancestor_id = ancestor.get("id")
+ if not isinstance(ancestor_id, str) or not ancestor_id:
+ continue
+ if not ancestor.get("interactable", False) or ancestor.get("hoverOnly", False):
+ continue
+ attrs = ancestor.get("attributes")
+ if not isinstance(attrs, dict):
+ continue
+ role = str(attrs.get("role") or "").strip().lower()
+ haspopup = str(attrs.get("aria-haspopup") or "").strip().lower()
+ if role != "combobox" and haspopup not in {"true", "listbox", "menu", "tree", "grid"}:
+ continue
+ css = self.scraped_page.id_to_css_dict.get(ancestor_id)
+ if not isinstance(css, str) or not css:
+ continue
+ locator = element.get_frame().locator(css)
+ if await locator.count() != 1:
+ continue
+ owner = SkyvernElement(
+ locator,
+ element.get_frame(),
+ ancestor,
+ self.scraped_page.id_to_element_hash.get(ancestor_id, ""),
+ engine_selection=self.engine_selection,
+ )
+ if not await owner.is_visible():
+ continue
+ LOG.info(
+ "Resolved decorative click target to stable composite owner",
+ element_id=element.get_id(),
+ owner_id=owner.get_id(),
+ )
+ return owner
+ return element
diff --git a/tests/unit/test_actions.py b/tests/unit/test_actions.py
index 4919dfc26..1a5a36c37 100644
--- a/tests/unit/test_actions.py
+++ b/tests/unit/test_actions.py
@@ -4,14 +4,18 @@ from unittest.mock import MagicMock
import pytest
from pydantic import TypeAdapter, ValidationError
+from structlog.testing import capture_logs
from skyvern.config import settings
+from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.db.models import ActionModel
from skyvern.forge.sdk.db.repositories.workflow_parameters import WorkflowParametersRepository
from skyvern.forge.sdk.db.utils import hydrate_action
from skyvern.forge.sdk.schemas import sdk_actions
from skyvern.forge.sdk.schemas.sdk_actions import InputTextAction as SdkInputTextAction
from skyvern.forge.sdk.schemas.sdk_actions import SdkActionType
+from skyvern.forge.sdk.schemas.tasks import Task, TaskStatus
from skyvern.schemas.steps import AgentStepOutput
from skyvern.utils.action_redaction import (
REDACTED_OTP_IDENTIFIER,
@@ -41,7 +45,7 @@ from skyvern.webeye.actions.actions import (
WebAction,
)
from skyvern.webeye.actions.models import DetailedAgentStepOutput
-from skyvern.webeye.actions.parse_actions import parse_action
+from skyvern.webeye.actions.parse_actions import parse_action, parse_actions
def _mock_scraped_page() -> MagicMock:
@@ -616,6 +620,48 @@ def test_parse_select_option_download_missing() -> None:
assert action.download is False
+ "raw_action",
+ [
+ {"action_type": "INPUT_TEXT", "id": "1"},
+ {"action_type": "PASTE_TEXT", "id": "1"},
+ {"action_type": "UPLOAD_FILE", "id": "1"},
+ {"action_type": "DOWNLOAD_FILE"},
+ {"action_type": "SELECT_OPTION", "id": "1"},
+ {"action_type": "CHECKBOX", "id": "1"},
+ ],
+)
+def test_parse_actions_treats_missing_required_fields_as_invalid(
+ monkeypatch: pytest.MonkeyPatch,
+ raw_action: dict[str, object],
+) -> None:
+ context = MagicMock()
+ context.totp_codes = {}
+ monkeypatch.setattr(
+ "skyvern.webeye.actions.parse_actions.skyvern_context.ensure_context",
+ lambda: context,
+ )
+ task = MagicMock()
+ task.task_id = "tsk_test"
+ task.organization_id = "org_test"
+ task.workflow_run_id = "wr_test"
+ task.data_extraction_goal = None
+ task.extracted_information_schema = None
+
+ with capture_logs() as logs:
+ actions = parse_actions(
+ task=task,
+ step_id="stp_test",
+ step_order=1,
+ scraped_page=_mock_scraped_page(),
+ json_response=[raw_action],
+ )
+
+ assert actions == []
+ assert [log["event"] for log in logs] == ["Invalid action"]
+ assert logs[0]["log_level"] == "warning"
+
+
@pytest.mark.parametrize("download_value", [None, False, True])
def test_parse_click_download_field(download_value: bool | None) -> None:
"""CLICK must parse successfully even when LLM returns download: null (SKY-10453)."""
@@ -829,6 +875,32 @@ def test_parse_switch_tab_action_non_integer_index_returns_null() -> None:
assert isinstance(action, NullAction)
+def test_parse_actions_skips_non_object_entries_and_keeps_real_actions() -> None:
+ # A planner refusal repaired into the actions array arrives as prose fragments. They must
+ # be dropped without crashing, and the real action dicts alongside them must still parse.
+ now = datetime.now()
+ task = Task(
+ task_id="tsk_parse",
+ organization_id="o_test",
+ status=TaskStatus.running,
+ created_at=now,
+ modified_at=now,
+ url="https://example.com",
+ )
+ payload = [
+ "I cannot provide an action. The `actions` array will be empty.",
+ {"action_type": "CLICK", "id": "e1", "reasoning": "click the button"},
+ ["nested", "junk"],
+ None,
+ ]
+
+ with skyvern_context.scoped(SkyvernContext()):
+ actions = parse_actions(task, "stp_parse", 0, _mock_scraped_page(), payload)
+
+ assert [type(action) for action in actions] == [ClickAction]
+ assert actions[0].element_id == "e1"
+
+
def test_tab_actions_registered_for_db_hydration() -> None:
from skyvern.forge.sdk.db.utils import ACTION_TYPE_TO_CLASS
from skyvern.webeye.actions.action_types import ActionType
diff --git a/tests/unit/test_aes_fallback_decrypt.py b/tests/unit/test_aes_fallback_decrypt.py
index 5c8d29cf8..27a0eafd2 100644
--- a/tests/unit/test_aes_fallback_decrypt.py
+++ b/tests/unit/test_aes_fallback_decrypt.py
@@ -7,18 +7,6 @@ PRIMARY_SALT = "primary_salt_value_xxxxxxxxxxxxxxx"
PRIMARY_IV = "primary_iv_xxxxxxxxx"
PRIOR_SALT = "prior_salt_value_xxxxxxxxxxxxxxxxx"
PRIOR_IV = "prior_iv_value_xxxxx"
-LEGACY_PRIMARY_CIPHERTEXT = "rvmea7ou1gzyata3OwKEQg=="
-
-
-async def test_decrypts_ciphertext_created_with_legacy_primary_normalization() -> None:
- aes = AES(
- secret_key=SECRET,
- salt=PRIMARY_SALT,
- iv=PRIMARY_IV,
- fallback_decrypt_keys=[(PRIMARY_SALT, PRIMARY_IV)],
- )
- assert await aes.decrypt(LEGACY_PRIMARY_CIPHERTEXT) == "legacy primary"
@pytest.mark.asyncio
diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.py
index 8406d3d4b..cc20e298f 100644
--- a/tests/unit/test_agent_task_v3.py
+++ b/tests/unit/test_agent_task_v3.py
@@ -24,6 +24,7 @@ from skyvern.forge.sdk.artifact.manager import ArtifactManager
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.db.enums import TaskType
+from skyvern.forge.sdk.experimentation.providers import BaseExperimentationProvider
from skyvern.forge.sdk.models import Step, StepStatus
from skyvern.forge.sdk.schemas.tasks import TaskStatus
from skyvern.forge.sdk.workflow.models.block import (
@@ -739,11 +740,13 @@ async def test_execute_step_v3_standalone_flushes_llm_artifacts(cancelled: bool)
with (
patch("skyvern.forge.agent.app") as mock_app,
patch("skyvern.forge.sdk.artifact.manager.app", mock_app),
+ patch("skyvern.forge.sdk.experimentation.workflow_block_engine.app") as mock_wbe_app,
):
mock_app.DATABASE.tasks.get_task = AsyncMock(return_value=None)
mock_app.DATABASE.tasks.update_task = AsyncMock(return_value=task)
mock_app.AGENT_FUNCTION.validate_step_execution = AsyncMock()
mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)
+ mock_wbe_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)
mock_app.ARTIFACT_MANAGER = manager
mock_app.STORAGE = storage
mock_app.DATABASE.artifacts = database.artifacts
@@ -862,6 +865,7 @@ async def _run_execute_step_gate(
*,
engine: agent_module.RunEngine,
task_block: BaseTaskBlock | None,
+ experimentation_provider: BaseExperimentationProvider | None = None,
**task_overrides: Any,
) -> tuple[AsyncMock, AsyncMock]:
"""Drive ForgeAgent.execute_step through the v3 dispatch gate.
@@ -886,11 +890,20 @@ async def _run_execute_step_gate(
context = SkyvernContext(task_id=task.task_id, step_id=step.step_id, organization_id=task.organization_id)
skyvern_context.set(context)
try:
- with patch("skyvern.forge.agent.app") as mock_app:
+ with (
+ patch("skyvern.forge.agent.app") as mock_app,
+ patch("skyvern.forge.sdk.experimentation.workflow_block_engine.app") as mock_wbe_app,
+ ):
mock_app.DATABASE.tasks.get_task = AsyncMock(return_value=None)
mock_app.DATABASE.tasks.update_task = AsyncMock()
+ mock_app.DATABASE.workflow_runs.get_workflow_run = AsyncMock(return_value=None)
mock_app.AGENT_FUNCTION.validate_step_execution = AsyncMock()
- mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)
+ if experimentation_provider is not None:
+ mock_app.EXPERIMENTATION_PROVIDER = experimentation_provider
+ mock_wbe_app.EXPERIMENTATION_PROVIDER = experimentation_provider
+ else:
+ mock_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)
+ mock_wbe_app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached = AsyncMock(return_value=False)
mock_app.ARTIFACT_MANAGER.flush_step_archive = AsyncMock()
try:
await agent.execute_step(
diff --git a/tests/unit/test_ai_click_empty_actions.py b/tests/unit/test_ai_click_empty_actions.py
index 417dbc9f3..2397b3a24 100644
--- a/tests/unit/test_ai_click_empty_actions.py
+++ b/tests/unit/test_ai_click_empty_actions.py
@@ -12,9 +12,12 @@ from contextlib import contextmanager
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from structlog.testing import capture_logs
+from skyvern.config import settings
from skyvern.core.script_generations.real_skyvern_page_ai import RealSkyvernPageAi
from skyvern.exceptions import SkyvernActionFailed
+from skyvern.webeye.actions.responses import ActionFailure
@pytest.fixture
@@ -132,6 +135,55 @@ class TestAiClickEmptyActions:
assert "LLM provider down" in str(exc_info.value)
assert not isinstance(exc_info.value, SkyvernActionFailed)
+ @pytest.mark.asyncio
+ async def test_ai_click_warns_when_unknown_exception_falls_back_to_selector(
+ self,
+ mock_page,
+ mock_scraped_page,
+ mock_context,
+ mock_app,
+ ):
+ real_page_ai = RealSkyvernPageAi(mock_scraped_page, mock_page)
+ llm_handler = AsyncMock(side_effect=RuntimeError("synthetic provider failure"))
+ selector = "#fallback-target"
+ sensitive_test_value = "SENSITIVE_TEST_VALUE"
+
+ with (
+ patch.object(real_page_ai, "_refresh_scraped_page", new_callable=AsyncMock),
+ patch(
+ "skyvern.core.script_generations.real_skyvern_page_ai.skyvern_context.ensure_context",
+ return_value=mock_context,
+ ),
+ patch("skyvern.core.script_generations.real_skyvern_page_ai.app", mock_app),
+ patch(
+ "skyvern.core.script_generations.real_skyvern_page_ai.prompt_engine.load_prompt",
+ return_value="synthetic prompt",
+ ),
+ patch(
+ "skyvern.core.script_generations.real_skyvern_page_ai._resolve_assist_llm_handler",
+ new=AsyncMock(return_value=llm_handler),
+ ),
+ capture_logs() as logs,
+ ):
+ result = await real_page_ai.ai_click(
+ selector=selector,
+ intention="synthetic intention",
+ data={"value": sensitive_test_value},
+ )
+
+ assert result == selector
+ mock_page.locator.assert_called_once_with(selector)
+ mock_page.locator.return_value.click.assert_awaited_once_with(timeout=settings.BROWSER_ACTION_TIMEOUT_MS)
+ fallback_logs = [
+ log for log in logs if log["event"] == "AI click failed unexpectedly; falling back to original selector"
+ ]
+ assert len(fallback_logs) == 1
+ assert fallback_logs[0]["log_level"] == "warning"
+ assert fallback_logs[0]["selector"] == selector
+ assert sensitive_test_value not in str(logs)
+ assert "synthetic intention" not in str(logs)
+ assert not [log for log in logs if log["log_level"] == "error"]
+
@pytest.mark.asyncio
async def test_ai_click_falls_back_to_selector_when_llm_returns_empty(
self, mock_page, mock_scraped_page, mock_context, mock_app
@@ -287,3 +339,44 @@ class TestAiSelectOptionEmptyActions:
handle_select.assert_awaited_once()
mock_page.locator.return_value.select_option.assert_not_awaited()
assert result == "CA"
+
+
+class TestAiSelectOptionHandlerFailures:
+ @pytest.mark.asyncio
+ async def test_handler_failure_falls_back_to_raw_select(self, mock_page, mock_scraped_page, mock_context, mock_app):
+ page_ai = RealSkyvernPageAi(mock_scraped_page, mock_page)
+ action = MagicMock()
+ action.option = MagicMock(value="adapted", label=None)
+
+ with select_option_patches(page_ai, mock_context, mock_app, [action]) as handle_select:
+ handle_select.return_value = [ActionFailure(RuntimeError("selection was not committed"))]
+ result = await page_ai.ai_select_option(
+ selector="#country",
+ value="original",
+ intention="select the synthetic option",
+ )
+
+ handle_select.assert_awaited_once()
+ mock_page.locator.assert_called_once_with("#country")
+ mock_page.locator.return_value.select_option.assert_awaited_once_with(
+ "adapted", timeout=settings.BROWSER_ACTION_TIMEOUT_MS
+ )
+ assert result == "adapted"
+
+ @pytest.mark.asyncio
+ async def test_handler_failure_raises_without_selector(self, mock_page, mock_scraped_page, mock_context, mock_app):
+ page_ai = RealSkyvernPageAi(mock_scraped_page, mock_page)
+ action = MagicMock()
+ action.option = MagicMock(value="adapted", label=None)
+
+ with select_option_patches(page_ai, mock_context, mock_app, [action]) as handle_select:
+ handle_select.return_value = [ActionFailure(RuntimeError("selection was not committed"))]
+ with pytest.raises(SkyvernActionFailed, match="selection was not committed"):
+ await page_ai.ai_select_option(
+ selector=None,
+ value="original",
+ intention="select the synthetic option",
+ )
+
+ handle_select.assert_awaited_once()
+ mock_page.locator.assert_not_called()
diff --git a/tests/unit/test_api_handler_factory.py b/tests/unit/test_api_handler_factory.py
index fa132439c..1bde91e6c 100644
--- a/tests/unit/test_api_handler_factory.py
+++ b/tests/unit/test_api_handler_factory.py
@@ -2414,34 +2414,40 @@ def test_llmcaller_router_is_cached_across_instances(monkeypatch: pytest.MonkeyP
assert len(build_calls) == 1
-def _luna_xhigh_flex_fallback_router(*, fallback_deployment_model: str = "gpt-5.6-luna") -> LLMRouterConfig:
+# Deployments have to be models litellm's *bundled* cost map knows: CI forces
+# LITELLM_LOCAL_MODEL_COST_MAP to match production, and a model that only the fetched map
+# carries would make the probe answer differently depending on which suite ran first.
+_TOOL_CHOICE_CAPABLE_MODEL = "gpt-4o"
+
+
+def _flex_fallback_router(*, fallback_deployment_model: str = _TOOL_CHOICE_CAPABLE_MODEL) -> LLMRouterConfig:
return LLMRouterConfig(
- model_name="openai-gpt-5-6-luna-xhigh-flex-fallback-router",
+ model_name="openai-flex-fallback-router",
required_env_vars=[],
supports_vision=True,
add_assistant_prefix=False,
model_list=[
LLMRouterModelConfig(
- model_name="openai-gpt-5-6-luna-xhigh-flex",
- litellm_params={"model": "gpt-5.6-luna"},
+ model_name="openai-flex",
+ litellm_params={"model": _TOOL_CHOICE_CAPABLE_MODEL},
),
LLMRouterModelConfig(
- model_name="openai-gpt-5-6-luna-xhigh-fallback",
+ model_name="openai-flex-fallback",
litellm_params={"model": fallback_deployment_model},
),
],
- main_model_group="openai-gpt-5-6-luna-xhigh-flex",
- fallback_model_group="openai-gpt-5-6-luna-xhigh-fallback",
+ main_model_group="openai-flex",
+ fallback_model_group="openai-flex-fallback",
)
def test_supports_tool_choice_resolves_router_through_its_deployments(monkeypatch: pytest.MonkeyPatch) -> None:
"""The probe must resolve a router's tool_choice support through its deployments' underlying
litellm models, not the router's own group name -- litellm knows nothing about the latter."""
- router_config = _luna_xhigh_flex_fallback_router()
+ router_config = _flex_fallback_router()
monkeypatch.setattr(api_handler_factory.LLMConfigRegistry, "get_config", lambda _: router_config)
- caller = LLMCaller("LUNA_XHIGH_FLEX_FALLBACK_ROUTER")
+ caller = LLMCaller("FLEX_FALLBACK_ROUTER")
assert caller.supports_tool_choice() is True
# Pins why the probe must go through model_list: asking litellm about the router's own group
@@ -2455,10 +2461,10 @@ def test_supports_tool_choice_denies_router_when_any_deployment_is_unsupported(
# litellm.Router validates every deployment's model string at construction time, so the
# "unsupported" deployment must be a real, recognized model (just one litellm knows doesn't
# take tool_choice) rather than a made-up string, which would blow up LLMCaller.__init__.
- router_config = _luna_xhigh_flex_fallback_router(fallback_deployment_model="openai/gpt-3.5-turbo-instruct")
+ router_config = _flex_fallback_router(fallback_deployment_model="openai/gpt-3.5-turbo-instruct")
monkeypatch.setattr(api_handler_factory.LLMConfigRegistry, "get_config", lambda _: router_config)
- caller = LLMCaller("LUNA_XHIGH_FLEX_FALLBACK_ROUTER_PARTIAL")
+ caller = LLMCaller("FLEX_FALLBACK_ROUTER_PARTIAL")
assert caller.supports_tool_choice() is False
@@ -2466,7 +2472,7 @@ def test_supports_tool_choice_denies_router_when_any_deployment_is_unsupported(
def test_supports_tool_choice_follows_dispatch_order_for_anthropic_keys(monkeypatch: pytest.MonkeyPatch) -> None:
# A router-backed key dispatches through litellm.Router, which forwards tool_choice, even when
# its name contains ANTHROPIC. Denying on the substring alone would silently disable the lever.
- router_config = _luna_xhigh_flex_fallback_router()
+ router_config = _flex_fallback_router()
monkeypatch.setattr(api_handler_factory.LLMConfigRegistry, "get_config", lambda _: router_config)
monkeypatch.setattr(api_handler_factory, "_LLMCALLER_ROUTER_CACHE", {})
monkeypatch.setattr(api_handler_factory, "_build_litellm_router", lambda cfg: MagicMock())
diff --git a/tests/unit/test_auto_completion_location.py b/tests/unit/test_auto_completion_location.py
index cd778592d..487beb26a 100644
--- a/tests/unit/test_auto_completion_location.py
+++ b/tests/unit/test_auto_completion_location.py
@@ -13,7 +13,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from skyvern.constants import SKYVERN_ID_ATTR
-from skyvern.exceptions import NoIncrementalElementFoundForAutoCompletion
+from skyvern.exceptions import InvalidElementForTextInput, NoIncrementalElementFoundForAutoCompletion
from skyvern.forge.sdk.models import StepStatus
from skyvern.webeye.actions.actions import InputOrSelectContext
from skyvern.webeye.actions.handler import (
@@ -22,7 +22,7 @@ from skyvern.webeye.actions.handler import (
choose_auto_completion_dropdown,
input_or_auto_complete_input,
)
-from skyvern.webeye.actions.responses import ActionSuccess
+from skyvern.webeye.actions.responses import ActionFailure, ActionSuccess
from tests.unit.helpers import make_organization, make_step, make_task
# ---------------------------------------------------------------------------
@@ -364,6 +364,45 @@ async def test_location_fast_path_element_not_in_dom_falls_through() -> None:
mock_app.AUTO_COMPLETION_LLM_API_HANDLER.assert_awaited_once()
+async def test_dropdown_cleanup_clear_failure_does_not_clobber_result() -> None:
+ """SKY-14330: the finally block's best-effort clear of the probe text must not let its
+ own failure (e.g. InvalidElementForTextInput, a real Playwright guard when the live node
+ no longer matches the scraped tag) replace the ActionFailure the try/except already
+ produced -- every other input_clear() call site in this file already guards this way."""
+ frame = _mock_frame(locator_count=1)
+ skyvern_el = _mock_skyvern_element(frame)
+ skyvern_el.press_fill = AsyncMock(side_effect=RuntimeError("press_fill boom"))
+ skyvern_el.input_clear = AsyncMock(side_effect=InvalidElementForTextInput(element_id="elem-1", tag_name="button"))
+ inc_scrape = _mock_incremental_scrape([])
+
+ with (
+ patch(
+ "skyvern.webeye.actions.handler.SkyvernFrame.create_instance",
+ new=AsyncMock(return_value=MagicMock(safe_wait_for_animation_end=AsyncMock())),
+ ),
+ patch(
+ "skyvern.webeye.actions.handler.IncrementalScrapePage",
+ return_value=inc_scrape,
+ ),
+ ):
+ result = await choose_auto_completion_dropdown(
+ context=_make_non_location_context(),
+ page=MagicMock(),
+ scraped_page=MagicMock(),
+ dom=MagicMock(),
+ text="foo",
+ skyvern_element=skyvern_el,
+ step=_STEP,
+ task=_TASK,
+ )
+
+ skyvern_el.input_clear.assert_awaited_once()
+ assert isinstance(result.action_result, ActionFailure)
+ assert result.action_result.exception_type == "RuntimeError"
+ assert "press_fill boom" in (result.action_result.exception_message or "")
+
+
# ---------------------------------------------------------------------------
# Tests for input_or_auto_complete_input flag propagation
# ---------------------------------------------------------------------------
diff --git a/tests/unit/test_browser_effect_sink_enumeration.py b/tests/unit/test_browser_effect_sink_enumeration.py
index fb800fe94..1f44d3259 100644
--- a/tests/unit/test_browser_effect_sink_enumeration.py
+++ b/tests/unit/test_browser_effect_sink_enumeration.py
@@ -21,7 +21,7 @@ _DISCOVERED_BROWSER_API_CALLS = {
{
"bring_to_front": 2,
"check": 2,
- "click": 23,
+ "click": 24,
"clear": 4,
"close": 5,
"dblclick": 2,
@@ -209,14 +209,14 @@ def test_discovered_browser_api_lower_bound_is_stable() -> None:
}
assert observed == _DISCOVERED_BROWSER_API_CALLS
- assert sum(sum(methods.values()) for methods in observed.values()) == 153
+ assert sum(sum(methods.values()) for methods in observed.values()) == 154
handler_candidates = _candidate_signatures("skyvern/webeye/actions/handler.py", _CANDIDATE_METHODS)
classified_non_browser = Counter(
{signature: count for signature, count in handler_candidates.items() if signature in _NON_BROWSER_CANDIDATES}
)
assert classified_non_browser == _NON_BROWSER_CANDIDATES
assert sum(_NON_BROWSER_CANDIDATES.values()) == 5
- assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 148
+ assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 149
def test_every_raw_evaluate_call_is_classified() -> None:
diff --git a/tests/unit/test_browser_session_download_artifacts.py b/tests/unit/test_browser_session_download_artifacts.py
index 809fc1e19..4e6a0f2c8 100644
--- a/tests/unit/test_browser_session_download_artifacts.py
+++ b/tests/unit/test_browser_session_download_artifacts.py
@@ -112,7 +112,7 @@ async def test_create_browser_session_download_artifact_inserts_when_no_existing
assert kwargs["organization_id"] == "o_1"
assert kwargs["checksum"] == "sha-xyz"
assert kwargs["file_size"] == 1234
- # No run_id at write time — claim happens at run finalization.
+ # An unresolved producer still writes the row; the claim reconciles it later.
assert kwargs.get("run_id") is None
@@ -150,6 +150,63 @@ async def test_create_browser_session_download_artifact_is_idempotent_per_sessio
mock_db_create.assert_not_awaited()
+async def test_create_browser_session_download_artifact_fills_an_unbound_existing_row():
+ manager = ArtifactManager()
+ existing = _make_artifact("a_existing", "s3://bucket/pbs_1/downloads/file.pdf")
+ mock_bind = AsyncMock(return_value=True)
+
+ with (
+ patch(
+ "skyvern.forge.sdk.artifact.manager.app.DATABASE.artifacts.find_artifact_for_browser_session",
+ AsyncMock(return_value=existing),
+ ),
+ patch(
+ "skyvern.forge.sdk.artifact.manager.app.DATABASE.artifacts.bind_session_download_artifact_producer",
+ mock_bind,
+ ),
+ ):
+ await manager.create_browser_session_download_artifact(
+ organization_id="o_1",
+ browser_session_id="pbs_1",
+ uri=existing.uri,
+ filename="file.pdf",
+ run_id="wr_a",
+ )
+
+ mock_bind.assert_awaited_once()
+ assert mock_bind.call_args.kwargs["run_id"] == "wr_a"
+
+
+async def test_create_browser_session_download_artifact_never_restamps_a_bound_row():
+ """A download re-uploaded as it grows can be observed after the session changed hands; the
+ producer recorded on the first write must win."""
+ manager = ArtifactManager()
+ existing = _make_artifact("a_existing", "s3://bucket/pbs_1/downloads/file.pdf", run_id="wr_a")
+ mock_bind = AsyncMock()
+
+ with (
+ patch(
+ "skyvern.forge.sdk.artifact.manager.app.DATABASE.artifacts.find_artifact_for_browser_session",
+ AsyncMock(return_value=existing),
+ ),
+ patch(
+ "skyvern.forge.sdk.artifact.manager.app.DATABASE.artifacts.bind_session_download_artifact_producer",
+ mock_bind,
+ ),
+ ):
+ await manager.create_browser_session_download_artifact(
+ organization_id="o_1",
+ browser_session_id="pbs_1",
+ uri=existing.uri,
+ filename="file.pdf",
+ run_id="wr_b",
+ )
+
+ mock_bind.assert_not_awaited()
+
+
# ---------------------------------------------------------------------------
# Storage write site — sync_browser_session_file
# ---------------------------------------------------------------------------
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 89e819cad..2cfbe7598 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -143,6 +143,18 @@ def _unverified_no_repair_contract() -> DiagnosisRepairContract:
class TestFailedTestResponseNormalization:
+ def test_paused_run_reply_is_not_rewritten_into_a_failed_test(self) -> None:
+ from skyvern.forge.sdk.copilot.agent import _rewrite_failed_test_response
+
+ ctx = _ctx(
+ last_update_block_count=2,
+ last_test_ok=None,
+ last_test_failure_reason="The run is paused, waiting for a person to approve or reject it.",
+ )
+ pause_reply = "The run is paused at the approval step, waiting for someone to approve or reject it."
+
+ assert _rewrite_failed_test_response(pause_reply, ctx) == pause_reply
+
def test_rewrite_failed_test_response_avoids_success_language(self) -> None:
from skyvern.forge.sdk.copilot.agent import _rewrite_failed_test_response
diff --git a/tests/unit/test_copilot_banned_block_policy.py b/tests/unit/test_copilot_banned_block_policy.py
index 81979f747..2c4116f16 100644
--- a/tests/unit/test_copilot_banned_block_policy.py
+++ b/tests/unit/test_copilot_banned_block_policy.py
@@ -995,3 +995,18 @@ def test_authoring_prompt_exposes_credential_capabilities_without_a_login_proced
def test_settled_login_does_not_change_new_workflow_rendering() -> None:
assert _code_only_browser_authoring_prompt(frozenset()) == _code_only_browser_authoring_prompt(None)
+
+
+async def test_recipient_less_human_interaction_is_not_refused_at_author_time(
+ ctx: MagicMock, code_only_ctx: MagicMock
+) -> None:
+ """Author-time refusal is a closed set of three hard blocks (workflow-copilot decision 0022);
+ ``human_interaction`` is not in it under either authoring policy, even with no recipient."""
+ block_json = json.dumps({"block_type": "human_interaction", "label": "approve_step", "recipients": []})
+
+ for policy_ctx in (ctx, code_only_ctx):
+ assert await _validate_block_pre_hook({"block_json": block_json}, policy_ctx) is None
+
+ assert "human_interaction" not in _COPILOT_BANNED_BLOCK_TYPES
+ assert "human_interaction" not in _COPILOT_CODE_ONLY_BROWSER_BANNED_BLOCK_TYPES
diff --git a/tests/unit/test_copilot_composition_evidence.py b/tests/unit/test_copilot_composition_evidence.py
index 57c857b0a..e4aba08a8 100644
--- a/tests/unit/test_copilot_composition_evidence.py
+++ b/tests/unit/test_copilot_composition_evidence.py
@@ -16,6 +16,7 @@ import yaml
from skyvern.config import settings
from skyvern.forge.sdk.copilot import tools as tools_module
from skyvern.forge.sdk.copilot.challenge_evidence import (
+ CHALLENGE_EVIDENCE_SOURCE_KEY,
CHALLENGE_KIND_KEY,
ChallengeEvidenceSource,
ChallengeKind,
@@ -4517,3 +4518,242 @@ def test_selector_candidate_source_vocabulary_matches_the_page_side_ladder() ->
# Drift detection, not enforcement: an emitted rung the parser cannot rank still reaches the model,
# but the two lists diverging means someone added a rung and left it unrankable.
assert emitted == set(_SELECTOR_CANDIDATE_SOURCES) - {_UNKNOWN_SELECTOR_SOURCE}
+
+
+_VISION_CHALLENGE_SUMMARY = {
+ "summary": "A centered Two-Factor Authentication card requests an authenticator token; a Login button is shown.",
+ "challenge_detected": True,
+ "challenge_kind": "other",
+ "challenge_location": "Centered page card",
+ "submit_blocked": True,
+ "blocked_submit_controls": ["Login button requires successful two-factor authentication"],
+}
+
+_SATISFIABLE_TOTP_HTML = (
+ "<html><head><title>Two-Factor Authentication</title></head><body>"
+ "<p>Complete the challenge to continue.</p>"
+ "<form><label for='token'>Authenticator token</label>"
+ "<input id='token' name='token' type='text' placeholder='123456' />"
+ "<button type='submit' class='btn--login'>Login</button></form></body></html>"
+)
+_CAPTCHA_HTML = (
+ "<html><head><title>Security Verification</title></head><body>"
+ "<form><input id='lastName' name='lastName' type='text' />"
+ "<div class='captcha-box'><p id='captchaInstruction'>Enter all the digits from 'c7MDRxt'</p>"
+ "<input id='captchaAnswer' name='captchaAnswer' type='text' /></div>"
+ "<button type='submit'>Search</button></form></body></html>"
+)
+_ACCESS_DENIED_HTML = (
+ "<html><head><title>Access Denied</title></head><body>"
+ "<h1>Access denied</h1><p>You do not have permission to view this page.</p></body></html>"
+)
+_DEVICE_APPROVAL_HTML = (
+ "<html><head><title>Approve this sign-in</title></head><body>"
+ "<p>Open your authenticator app and approve this sign-in to complete verification.</p>"
+ "<form><button type='submit'>Resend request</button></form></body></html>"
+)
+_CANCEL_ONLY_HTML = (
+ "<html><head><title>Verification required</title></head><body>"
+ "<p>Complete the challenge to continue.</p>"
+ "<form><input id='token' name='token' type='text' />"
+ "<button type='button'>Cancel</button><button type='reset'>Clear</button></form></body></html>"
+)
+
+_STRUCTURED_TOTP_EVIDENCE: dict[str, Any] = {
+ "current_url": "https://example.test/login",
+ "page_title": "Two-Factor Authentication",
+ "anti_bot_indicators": ["captcha", "challenge"],
+ "challenge_controls": [],
+ "visual_obstruction_candidates": [],
+ "modal_overlays": [],
+ "page_obstructions": [],
+ "navigation_targets": [],
+ "result_containers": [],
+ "forms": [
+ {
+ "id": "",
+ "fields": [
+ {
+ "name": "token",
+ "id": "token",
+ "label": "Authenticator token",
+ "type": "text",
+ "disabled": False,
+ "visible": True,
+ "selector": "#token",
+ }
+ ],
+ "submit_controls": [
+ {
+ "text": "Login",
+ "type": "submit",
+ "disabled": False,
+ "visible": True,
+ "selector": "button.btn--login",
+ }
+ ],
+ }
+ ],
+ "challenge_state": {
+ "detected": True,
+ "kind": "captcha",
+ "source": "dom_html",
+ "indicators": ["captcha", "challenge"],
+ "requires_human_verification": False,
+ "visual_location": "",
+ "gates_submit_controls": False,
+ "gated_submit_controls": [],
+ },
+}
+
+
+def _merged_from_html(html: str, **evidence_overrides: Any) -> dict[str, Any]:
+ parsed = parse_composition_html(
+ html,
+ inspected_url="https://example.test/login",
+ current_url="https://example.test/login",
+ )
+ parsed.update(evidence_overrides)
+ return merge_visual_composition_evidence(parsed, visual_summary=dict(_VISION_CHALLENGE_SUMMARY))
+
+
+ ("case", "merged", "expected_promotion"),
+ [
+ ("satisfiable_totp_form", _merged_from_html(_SATISFIABLE_TOTP_HTML), False),
+ (
+ "satisfiable_totp_form_structured_capture",
+ merge_visual_composition_evidence(
+ dict(_STRUCTURED_TOTP_EVIDENCE), visual_summary=dict(_VISION_CHALLENGE_SUMMARY)
+ ),
+ False,
+ ),
+ ("captcha_with_rendered_control", _merged_from_html(_CAPTCHA_HTML), True),
+ ("access_denied_no_form", _merged_from_html(_ACCESS_DENIED_HTML), True),
+ ("device_approval_no_entry_field", _merged_from_html(_DEVICE_APPROVAL_HTML), True),
+ ("cancel_and_reset_controls_only", _merged_from_html(_CANCEL_ONLY_HTML), True),
+ (
+ "visual_obstruction_over_enabled_form",
+ _merged_from_html(
+ _SATISFIABLE_TOTP_HTML,
+ visual_obstruction_candidates=[{"tag": "canvas", "selector": "canvas#widget"}],
+ ),
+ True,
+ ),
+ ],
+)
+def test_vision_challenge_promotion_requires_structural_corroboration(
+ case: str, merged: dict[str, Any], expected_promotion: bool
+) -> None:
+ del case
+ challenge_state = merged["challenge_state"]
+
+ assert challenge_state["requires_human_verification"] is expected_promotion
+ assert challenge_state["gates_submit_controls"] is expected_promotion
+ assert bool(challenge_state["gated_submit_controls"]) is expected_promotion
+ assert (composition_challenge_carrier(merged) is not None) is expected_promotion
+
+
+def test_vision_challenge_without_a_submit_claim_is_not_refuted_by_form_shape() -> None:
+ occlusion_only = {
+ key: value
+ for key, value in _VISION_CHALLENGE_SUMMARY.items()
+ if key not in {"submit_blocked", "blocked_submit_controls"}
+ }
+ merged = merge_visual_composition_evidence(
+ parse_composition_html(
+ _SATISFIABLE_TOTP_HTML,
+ inspected_url="https://example.test/login",
+ current_url="https://example.test/login",
+ ),
+ visual_summary=occlusion_only,
+ )
+
+ assert merged["challenge_state"]["requires_human_verification"] is True
+ assert composition_challenge_carrier(merged) is ChallengeEvidenceSource.VISION
+
+
+def test_named_blocked_control_carries_the_gating_claim_without_the_boolean() -> None:
+ named_only = {key: value for key, value in _VISION_CHALLENGE_SUMMARY.items() if key != "submit_blocked"}
+ merged = merge_visual_composition_evidence(
+ parse_composition_html(
+ _SATISFIABLE_TOTP_HTML,
+ inspected_url="https://example.test/login",
+ current_url="https://example.test/login",
+ ),
+ visual_summary=named_only,
+ )
+
+ assert merged["challenge_state"].get("requires_human_verification") is not True
+ assert composition_challenge_carrier(merged) is None
+
+
+def test_a_disabled_submit_in_the_same_form_corroborates_the_gating_claim() -> None:
+ page_with_disabled_submit = _SATISFIABLE_TOTP_HTML.replace(
+ "</form>",
+ "<button type='submit' disabled>Verify</button></form>",
+ )
+ merged = merge_visual_composition_evidence(
+ parse_composition_html(
+ page_with_disabled_submit,
+ inspected_url="https://example.test/login",
+ current_url="https://example.test/login",
+ ),
+ visual_summary=dict(_VISION_CHALLENGE_SUMMARY),
+ )
+
+ assert merged["challenge_state"]["requires_human_verification"] is True
+ assert composition_challenge_carrier(merged) is ChallengeEvidenceSource.VISION
+
+
+def test_a_disabled_control_in_an_unrelated_form_does_not_corroborate_the_claim() -> None:
+ page_with_disabled_footer_form = _SATISFIABLE_TOTP_HTML.replace(
+ "</body>",
+ "<form><input type='email' name='news'><button type='submit' disabled>Subscribe</button></form></body>",
+ )
+ merged = merge_visual_composition_evidence(
+ parse_composition_html(
+ page_with_disabled_footer_form,
+ inspected_url="https://example.test/login",
+ current_url="https://example.test/login",
+ ),
+ visual_summary=dict(_VISION_CHALLENGE_SUMMARY),
+ )
+
+ assert merged["challenge_state"].get("requires_human_verification") is not True
+ assert composition_challenge_carrier(merged) is None
+
+
+def test_readonly_entry_field_is_not_a_satisfiable_path() -> None:
+ readonly_token = _SATISFIABLE_TOTP_HTML.replace("id='token'", "id='token' readonly")
+ merged = merge_visual_composition_evidence(
+ parse_composition_html(
+ readonly_token,
+ inspected_url="https://example.test/login",
+ current_url="https://example.test/login",
+ ),
+ visual_summary=dict(_VISION_CHALLENGE_SUMMARY),
+ )
+
+ assert merged["challenge_state"]["requires_human_verification"] is True
+ assert composition_challenge_carrier(merged) is ChallengeEvidenceSource.VISION
+
+
+def test_withheld_vision_challenge_keeps_the_observation_the_model_reads() -> None:
+ merged = _merged_from_html(_SATISFIABLE_TOTP_HTML)
+
+ assert merged["challenge_state"]["detected"] is True
+ assert merged["visual_evidence_summary"] == _VISION_CHALLENGE_SUMMARY["summary"]
+ assert merged["evidence_sources"] == ["dom_html", "screenshot", "vision_summary"]
+ assert CHALLENGE_EVIDENCE_SOURCE_KEY not in merged["challenge_state"]
+
+
+def test_html_fallback_capture_carries_no_visibility_flags() -> None:
+ parsed = parse_composition_html(
+ _SATISFIABLE_TOTP_HTML,
+ inspected_url="https://example.test/login",
+ current_url="https://example.test/login",
+ )
+ form = parsed["forms"][0]
+
+ assert [control for control in form["fields"] + form["submit_controls"] if "visible" in control] == []
diff --git a/tests/unit/test_copilot_diagnosis_repair_contract.py b/tests/unit/test_copilot_diagnosis_repair_contract.py
index a7e751653..de6088b2c 100644
--- a/tests/unit/test_copilot_diagnosis_repair_contract.py
+++ b/tests/unit/test_copilot_diagnosis_repair_contract.py
@@ -4,6 +4,7 @@ import hashlib
import json
from collections.abc import Callable
from types import SimpleNamespace
+from typing import Any
from unittest.mock import MagicMock
import pytest
@@ -11,8 +12,17 @@ from structlog.testing import capture_logs
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal
from skyvern.forge.sdk.copilot.build_test_outcome import recorded_outcome_from_run_blocks_result
-from skyvern.forge.sdk.copilot.challenge_evidence import CHALLENGE_KIND_KEY, ChallengeKind
+from skyvern.forge.sdk.copilot.challenge_evidence import (
+ CHALLENGE_KIND_KEY,
+ ChallengeEvidenceSource,
+ ChallengeKind,
+ composition_challenge_carrier,
+)
from skyvern.forge.sdk.copilot.completion_verification import CompletionVerificationResult, CriterionVerdict
+from skyvern.forge.sdk.copilot.composition_evidence import (
+ merge_visual_composition_evidence,
+ parse_composition_html,
+)
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
from skyvern.forge.sdk.copilot.context import CodeAuthoringRepairContext, CopilotContext
from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (
@@ -225,6 +235,77 @@ def test_contract_shapes_for_failed_suspicious_and_missing_credential_cases() ->
) == (DiagnosisFailureType.MISSING_CREDENTIAL_OR_INIT, RepairNextAction.ASK, [])
+def test_paused_run_is_not_a_failure_and_is_not_claimed_as_success() -> None:
+ paused = build_diagnosis_repair_contract(
+ source_tool="run_blocks_and_collect_debug",
+ result={
+ "ok": False,
+ "error": "The run is paused at a human_interaction block, waiting for a person.",
+ "data": {
+ "workflow_run_id": "wr_paused",
+ "overall_status": "paused",
+ "failure_reason": "The run is paused, waiting for a person to approve or reject it.",
+ "control_signal": {"kind": "watchdog_paused"},
+ },
+ },
+ ctx=_ctx(),
+ )
+
+ assert (
+ paused.diagnosis_result.suspected_failure_type,
+ paused.repair_decision.next_action,
+ paused.verification_result.user_goal_satisfied,
+ ) == (DiagnosisFailureType.NO_FAILURE, RepairNextAction.NO_CHANGE, False)
+
+
+def test_pause_outranks_trusted_challenge_evidence() -> None:
+ """A pause on a challenge-flagged page stays NO_FAILURE. Classifying it as a challenge blocker
+ maps to STOP, which would have the copilot call the site unfixable about a run that has emailed
+ a person to solve that exact challenge. ``_next_action`` already excludes NO_FAILURE from its
+ anti-bot latch; this keeps ``_failure_type`` agreeing with it."""
+ paused_on_challenge = build_diagnosis_repair_contract(
+ source_tool="run_blocks_and_collect_debug",
+ result={
+ "ok": False,
+ "error": "The run is paused at a human_interaction block, waiting for a person.",
+ "data": {
+ "workflow_run_id": "wr_paused_challenge",
+ "overall_status": "paused",
+ "control_signal": {"kind": "watchdog_paused"},
+ "failure_categories": [
+ {"category": "ANTI_BOT_DETECTION", "evidence_source": "challenge_state", "confidence_float": 1.0}
+ ],
+ },
+ },
+ ctx=_ctx(),
+ )
+
+ assert (
+ paused_on_challenge.diagnosis_result.suspected_failure_type,
+ paused_on_challenge.repair_decision.next_action,
+ ) == (DiagnosisFailureType.NO_FAILURE, RepairNextAction.NO_CHANGE)
+
+
+def test_non_paused_watchdog_exit_still_classifies_as_a_failed_run() -> None:
+ ceiling = build_diagnosis_repair_contract(
+ source_tool="run_blocks_and_collect_debug",
+ result={
+ "ok": False,
+ "error": "The run exceeded the 600s absolute ceiling while still showing progress.",
+ "data": {
+ "workflow_run_id": "wr_ceiling",
+ "overall_status": "running",
+ "failure_reason": "ceiling",
+ "control_signal": {"kind": "watchdog_ceiling"},
+ },
+ },
+ ctx=_ctx(),
+ )
+
+ assert ceiling.diagnosis_result.suspected_failure_type == DiagnosisFailureType.FAILED_RUN
+ assert ceiling.repair_decision.next_action == RepairNextAction.REPAIR
+
+
def test_authoring_repair_contexts_have_distinct_structural_root_cause_signatures() -> None:
ambiguous = CodeAuthoringRepairContext(
block_label="retrieve_document_link",
@@ -3119,3 +3200,115 @@ def test_enforcement_signal_will_not_name_a_device_wall_from_another_run() -> No
assert signal is not None
assert signal.internal_reason_code == TERMINAL_CHALLENGE_BLOCKER_REASON_CODE
assert signal.user_facing_reason == TERMINAL_CHALLENGE_USER_FACING_REASON
+
+
+_SATISFIABLE_TOTP_PAGE_HTML = (
+ "<html><head><title>Two-Factor Authentication</title></head><body>"
+ "<p>Complete the challenge to continue.</p>"
+ "<form><label for='token'>Authenticator token</label>"
+ "<input id='token' name='token' type='text' placeholder='123456' />"
+ "<button type='submit' class='btn--login'>Login</button></form></body></html>"
+)
+_TOTP_VISION_CHALLENGE_SUMMARY = {
+ "summary": "A centered Two-Factor Authentication card requests an authenticator token; a Login button is shown.",
+ "challenge_detected": True,
+ "challenge_kind": "other",
+ "challenge_location": "Centered page card",
+ "submit_blocked": True,
+ "blocked_submit_controls": ["Login button requires successful two-factor authentication"],
+}
+
+
+_TOTP_VISION_OCCLUSION_ONLY_SUMMARY = {
+ "summary": "A centered Two-Factor Authentication card is covered by a site verification interstitial.",
+ "challenge_detected": True,
+ "challenge_kind": "other",
+ "challenge_location": "Full-page interstitial",
+}
+_FAILED_BLOCK_ACTION_TRACE = [
+ {
+ "action": "null_action",
+ "status": "failed",
+ "reasoning": None,
+ "element": None,
+ "description": "page.wait_for_selector(\"button[name='Continue']\", timeout=15000)",
+ "code_line": 27,
+ },
+ {
+ "action": "null_action",
+ "status": "completed",
+ "reasoning": None,
+ "element": None,
+ "description": "token = credential.otp()",
+ },
+]
+
+
+def _failed_run_blocks_result() -> dict[str, Any]:
+ return {
+ "ok": False,
+ "data": {
+ "workflow_run_id": "wr_failed",
+ "overall_status": "failed",
+ "blocks": [
+ {
+ "label": "login_and_read_visitors",
+ "status": "failed",
+ "failure_reason": "Timed out waiting for button[name='Continue']",
+ }
+ ],
+ "action_trace_summary": run_execution_module._summarize_action_trace(_FAILED_BLOCK_ACTION_TRACE),
+ },
+ }
+
+
+def _post_run_totp_page_evidence(visual_summary: dict[str, Any]) -> dict[str, Any]:
+ merged = merge_visual_composition_evidence(
+ parse_composition_html(
+ _SATISFIABLE_TOTP_PAGE_HTML,
+ inspected_url="https://example.test/login",
+ current_url="https://example.test/login",
+ ),
+ visual_summary=dict(visual_summary),
+ )
+ return {
+ **merged,
+ "workflow_run_id": "wr_failed",
+ "observed_after_workflow_run": True,
+ "source_tool": "inspect_page_for_composition",
+ }
+
+
+def test_runtime_authoring_repair_survives_a_vision_only_challenge_over_a_satisfiable_form() -> None:
+ ctx = _ctx()
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.composition_page_evidence = _post_run_totp_page_evidence(_TOTP_VISION_CHALLENGE_SUMMARY)
+ result = _failed_run_blocks_result()
+
+ run_execution_module._record_run_blocks_result(ctx, result)
+ repair_context = finalize_runtime_authoring_repair_context_from_page_observation(ctx)
+
+ assert composition_challenge_carrier(ctx.composition_page_evidence) is None
+ assert terminal_challenge_blocker_signal_from_page_evidence(ctx, blocked_tool="update_and_run_blocks") is None
+ assert repair_context is not None
+ assert repair_context.block_label == "login_and_read_visitors"
+ assert ctx.last_code_authoring_repair_context is not None
+ assert any("Authenticator token" in summary for summary in repair_context.page_form_summaries)
+ statement_lines = result["data"]["action_trace_summary"]
+ assert any("code_line=27" in line and "wait_for_selector" in line for line in statement_lines)
+ assert any("credential.otp()" in line for line in statement_lines)
+
+
+def test_vision_challenge_without_a_blocked_submit_claim_still_terminalizes_over_a_form() -> None:
+ ctx = _ctx()
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.composition_page_evidence = _post_run_totp_page_evidence(_TOTP_VISION_OCCLUSION_ONLY_SUMMARY)
+
+ run_execution_module._record_run_blocks_result(ctx, _failed_run_blocks_result())
+
+ carrier = composition_challenge_carrier(ctx.composition_page_evidence)
+ signal = terminal_challenge_blocker_signal_from_page_evidence(ctx, blocked_tool="update_and_run_blocks")
+
+ assert carrier is ChallengeEvidenceSource.VISION
+ assert signal is not None
+ assert signal.internal_reason_code == TERMINAL_CHALLENGE_BLOCKER_REASON_CODE
diff --git a/tests/unit/test_copilot_mcp_adapter.py b/tests/unit/test_copilot_mcp_adapter.py
index bf8eed548..2ce3fe93d 100644
--- a/tests/unit/test_copilot_mcp_adapter.py
+++ b/tests/unit/test_copilot_mcp_adapter.py
@@ -1,4 +1,24 @@
-from skyvern.forge.sdk.copilot.mcp_adapter import _requested_output_path_choices
+import asyncio
+from collections.abc import AsyncIterator, Iterator
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from mcp.types import CallToolResult
+from structlog.testing import capture_logs
+
+from skyvern.forge.sdk.copilot import mcp_adapter
+from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
+from skyvern.forge.sdk.copilot.mcp_adapter import (
+ SchemaOverlay,
+ SkyvernOverlayMCPServer,
+ _requested_output_path_choices,
+)
+from skyvern.forge.sdk.copilot.runtime import AgentContext, mcp_to_copilot
+from skyvern.forge.sdk.copilot.tools.mcp_hooks import _build_skyvern_mcp_overlays, get_skyvern_mcp_alias_map
+from tests.unit.copilot_test_helpers import make_copilot_ctx
+from tests.unit.test_copilot_secret_scrub import _make_server
def _schema() -> dict:
@@ -36,11 +56,299 @@ class TestRequestedOutputPathChoices:
def test_the_declared_path_says_the_expression_is_that_value() -> None:
- from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
- from skyvern.forge.sdk.copilot.tools.mcp_hooks import _build_skyvern_mcp_overlays
-
overlays = _build_skyvern_mcp_overlays(BlockAuthoringPolicy.CODE_ONLY_BROWSER)
description = overlays["evaluate"].copilot_params["output_path"]["description"]
assert "evaluates to that one value" in description
assert "exploration" in description
+
+
+_TIMING_EVENT = "MCP tool timing"
+_PAYLOAD_KEYS_THAT_WOULD_LEAK = {"args", "merged_args", "arguments", "mcp_args", "data", "raw_mcp", "result"}
+_BROWSER_BOOT_SECONDS = 2.0
+_MCP_CALL_SECONDS = 3.0
+_AFTER_CALL_SECONDS = 5.0
+_WALL_MS = 5000
+_SESSION_ONLY_MS = 2000
+
+
+def _fake_clock(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[float]]:
+ now = [100.0]
+ monkeypatch.setattr(mcp_adapter, "time", SimpleNamespace(monotonic=lambda: now[0]))
+ yield now
+
+
+def _stub_browser_session(monkeypatch: pytest.MonkeyPatch, _fake_clock: list[float]) -> Iterator[None]:
+ async def _no_error(_ctx: AgentContext) -> None:
+ _fake_clock[0] += _BROWSER_BOOT_SECONDS
+ return None
+
+ @asynccontextmanager
+ async def _no_session_scope(_ctx: AgentContext) -> AsyncIterator[None]:
+ yield
+
+ monkeypatch.setattr(mcp_adapter, "ensure_browser_session", _no_error)
+ monkeypatch.setattr(mcp_adapter, "mcp_browser_context", _no_session_scope)
+ yield
+
+
+def _timing_records(captured: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ return [record for record in captured if record.get("event") == _TIMING_EVENT]
+
+
+async def _call(server: SkyvernOverlayMCPServer, call_path: str) -> CallToolResult | dict[str, Any]:
+ if call_path == "model":
+ return await server.call_tool("evaluate", {"expression": "scan()"})
+ return await server.call_internal_tool("skyvern_evaluate", {"expression": "scan()"})
+
+
+def _surfaced_error(result: CallToolResult | dict[str, Any], call_path: str) -> str:
+ if call_path == "model":
+ assert isinstance(result, CallToolResult)
+ return result.content[0].text
+ assert isinstance(result, dict)
+ return str(result.get("error"))
+
+
+def _server_whose_call_takes_time(
+ payload: dict[str, Any] | Exception,
+ overlay: SchemaOverlay,
+ clock: list[float],
+ alias_map: dict[str, str] | None = None,
+ is_error: bool = False,
+) -> SkyvernOverlayMCPServer:
+ def _advance() -> None:
+ clock[0] += _MCP_CALL_SECONDS
+
+ return _make_server(
+ make_copilot_ctx(browser_session_id="pbs_1"),
+ payload,
+ overlay,
+ alias_map=alias_map,
+ on_call=_advance,
+ is_error=is_error,
+ )
+
+
[email protected]("_stub_browser_session")
+class TestMCPToolTiming:
+ @pytest.mark.asyncio
+ async def test_internal_call_logs_the_server_total_without_changing_the_result(
+ self, monkeypatch: pytest.MonkeyPatch, _fake_clock: list[float]
+ ) -> None:
+ payload = {"ok": True, "data": {"x": 1}, "timing_ms": {"sdk": 812, "total": 815}}
+ server = _server_whose_call_takes_time(payload, SchemaOverlay(), _fake_clock)
+ server._evidence_candidate_origin = "https://public.test"
+
+ async def _slow_drain() -> None:
+ _fake_clock[0] += _AFTER_CALL_SECONDS
+
+ monkeypatch.setattr(server, "_drain_evidence_candidate_response_tasks", _slow_drain)
+
+ with capture_logs() as captured:
+ result = await server.call_internal_tool("skyvern_evaluate", {"expression": "scan()"})
+
+ records = _timing_records(captured)
+ assert len(records) == 1
+ record = records[0]
+ assert record["tool_name"] == "skyvern_evaluate"
+ assert record["mcp_tool_name"] == "skyvern_evaluate"
+ assert record["call_path"] == "internal"
+ assert record["server_timing_ms"] == 815
+ assert record["wall_clock_ms"] == _WALL_MS
+ assert set(record) & _PAYLOAD_KEYS_THAT_WOULD_LEAK == set()
+ assert record["workflow_permanent_id"] == "wfp-1"
+ assert "turn_id" in record
+ assert "workflow_copilot_chat_id" in record
+
+ assert result == mcp_to_copilot(payload)
+ assert "timing_ms" not in result
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("timing_ms", [None, {}, "815ms", {"total": "815"}, {"total": True}])
+ async def test_a_result_without_a_server_timing_dict_still_logs(
+ self, timing_ms: str | dict[str, str | bool] | None, _fake_clock: list[float]
+ ) -> None:
+ payload: dict[str, Any] = {"ok": True, "data": {"x": 1}}
+ if timing_ms is not None:
+ payload["timing_ms"] = timing_ms
+ server = _server_whose_call_takes_time(payload, SchemaOverlay(), _fake_clock)
+
+ with capture_logs() as captured:
+ await server.call_internal_tool("skyvern_evaluate", {"expression": "scan()"})
+
+ records = _timing_records(captured)
+ assert len(records) == 1
+ assert records[0]["server_timing_ms"] is None
+ assert records[0]["tool_name"] == "skyvern_evaluate"
+ assert records[0]["mcp_tool_name"] == "skyvern_evaluate"
+ assert records[0]["call_path"] == "internal"
+ assert records[0]["wall_clock_ms"] == _WALL_MS
+
+ @pytest.mark.asyncio
+ async def test_model_facing_call_logs_both_names_and_excludes_the_post_hook(self, _fake_clock: list[float]) -> None:
+ payload = {"ok": True, "data": {"result": 1}, "timing_ms": {"sdk": 812, "total": 815}}
+
+ async def _slow_post_hook(
+ copilot_result: dict[str, Any], raw_mcp: dict[str, Any], ctx: AgentContext
+ ) -> dict[str, Any]:
+ _fake_clock[0] += _AFTER_CALL_SECONDS
+ return copilot_result
+
+ overlay = SchemaOverlay(requires_browser=True, post_hook=_slow_post_hook)
+ server = _server_whose_call_takes_time(payload, overlay, _fake_clock, alias_map=get_skyvern_mcp_alias_map())
+
+ with capture_logs() as captured:
+ result = await server.call_tool("evaluate", {"expression": "scan()"})
+
+ records = _timing_records(captured)
+ assert len(records) == 1
+ assert records[0]["tool_name"] == "evaluate"
+ assert records[0]["mcp_tool_name"] == "skyvern_evaluate"
+ assert records[0]["call_path"] == "model"
+ assert records[0]["server_timing_ms"] == 815
+ assert records[0]["wall_clock_ms"] == _WALL_MS
+ assert records[0]["call_status"] == "ok"
+ assert "timing_ms" not in result.content[0].text
+
+ @pytest.mark.asyncio
+ async def test_a_call_that_exceeds_its_ceiling_reports_its_wall_time(self, _fake_clock: list[float]) -> None:
+ overlay = SchemaOverlay(requires_browser=True, timeout=30)
+ server = _server_whose_call_takes_time(TimeoutError(), overlay, _fake_clock)
+
+ with capture_logs() as captured:
+ await server.call_tool("evaluate", {"expression": "scan()"})
+
+ records = _timing_records(captured)
+ assert len(records) == 1
+ assert records[0]["call_status"] == "timeout"
+ assert records[0]["server_timing_ms"] is None
+ assert records[0]["wall_clock_ms"] == _WALL_MS
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "payload",
+ [
+ {"ok": True, "data": {"x": 1}, "timing_ms": {"sdk": 812, "total": 815}},
+ RuntimeError("mcp exploded"),
+ ],
+ ids=["ok", "error"],
+ )
+ async def test_an_internal_call_reports_the_model_facing_name_so_one_tool_is_one_facet(
+ self, payload: dict[str, Any] | Exception, _fake_clock: list[float]
+ ) -> None:
+ server = _server_whose_call_takes_time(
+ payload, SchemaOverlay(), _fake_clock, alias_map={"evaluate": "skyvern_evaluate"}
+ )
+
+ with capture_logs() as captured:
+ await server.call_internal_tool("skyvern_evaluate", {"expression": "scan()"})
+
+ records = _timing_records(captured)
+ assert len(records) == 1
+ assert records[0]["tool_name"] == "evaluate"
+ assert records[0]["mcp_tool_name"] == "skyvern_evaluate"
+ assert records[0]["call_path"] == "internal"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("call_path", ["model", "internal"])
+ async def test_a_call_cancelled_while_resolving_its_session_still_reports_the_budget_it_spent(
+ self, call_path: str, monkeypatch: pytest.MonkeyPatch, _fake_clock: list[float]
+ ) -> None:
+ async def _cancelled(_ctx: AgentContext) -> None:
+ _fake_clock[0] += _BROWSER_BOOT_SECONDS
+ raise asyncio.CancelledError
+
+ monkeypatch.setattr(mcp_adapter, "ensure_browser_session", _cancelled)
+ server = _server_whose_call_takes_time({"ok": True}, SchemaOverlay(requires_browser=True), _fake_clock)
+
+ with capture_logs() as captured:
+ with pytest.raises(asyncio.CancelledError):
+ await _call(server, call_path)
+
+ records = _timing_records(captured)
+ assert len(records) == 1
+ assert records[0]["call_status"] == "cancelled"
+ assert records[0]["call_path"] == call_path
+ assert records[0]["wall_clock_ms"] == _SESSION_ONLY_MS
+ assert records[0]["server_timing_ms"] is None
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("call_path", ["model", "internal"])
+ async def test_a_session_that_fails_to_resolve_still_reports_the_budget_it_spent(
+ self, call_path: str, monkeypatch: pytest.MonkeyPatch, _fake_clock: list[float]
+ ) -> None:
+ async def _session_error(_ctx: AgentContext) -> dict[str, Any]:
+ _fake_clock[0] += _BROWSER_BOOT_SECONDS
+ return {"ok": False, "error": "no browser session"}
+
+ monkeypatch.setattr(mcp_adapter, "ensure_browser_session", _session_error)
+ server = _server_whose_call_takes_time({"ok": True}, SchemaOverlay(requires_browser=True), _fake_clock)
+
+ with capture_logs() as captured:
+ result = await _call(server, call_path)
+
+ records = _timing_records(captured)
+ assert len(records) == 1
+ assert records[0]["call_status"] == "session_error"
+ assert records[0]["call_path"] == call_path
+ assert records[0]["wall_clock_ms"] == _SESSION_ONLY_MS
+ assert records[0]["server_timing_ms"] is None
+ assert "no browser session" in _surfaced_error(result, call_path)
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("call_path", ["model", "internal"])
+ async def test_a_session_that_raises_instead_of_returning_an_error_still_reports_its_budget(
+ self, call_path: str, monkeypatch: pytest.MonkeyPatch, _fake_clock: list[float]
+ ) -> None:
+ async def _session_raises(_ctx: AgentContext) -> None:
+ _fake_clock[0] += _BROWSER_BOOT_SECONDS
+ raise RuntimeError("adoption failed")
+
+ monkeypatch.setattr(mcp_adapter, "ensure_browser_session", _session_raises)
+ server = _server_whose_call_takes_time({"ok": True}, SchemaOverlay(requires_browser=True), _fake_clock)
+
+ with capture_logs() as captured:
+ await _call(server, call_path)
+
+ records = _timing_records(captured)
+ assert len(records) == 1
+ assert records[0]["call_status"] == "session_error"
+ assert records[0]["call_path"] == call_path
+ assert records[0]["wall_clock_ms"] == _SESSION_ONLY_MS
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("call_path", ["model", "internal"])
+ async def test_a_tool_that_reports_failure_without_raising_is_not_recorded_as_ok(
+ self, call_path: str, _fake_clock: list[float]
+ ) -> None:
+ payload = {"ok": False, "error": "selector not found", "timing_ms": {"total": 815}}
+ server = _server_whose_call_takes_time(
+ payload, SchemaOverlay(requires_browser=True), _fake_clock, alias_map=get_skyvern_mcp_alias_map()
+ )
+
+ with capture_logs() as captured:
+ await _call(server, call_path)
+
+ records = _timing_records(captured)
+ assert len(records) == 1
+ assert records[0]["call_status"] == "error"
+ assert records[0]["server_timing_ms"] == 815
+
+ @pytest.mark.asyncio
+ async def test_an_internal_call_without_a_connected_client_still_leaves_a_record(
+ self, _fake_clock: list[float]
+ ) -> None:
+ server = _server_whose_call_takes_time({"ok": True}, SchemaOverlay(), _fake_clock)
+ server._client = None
+
+ with capture_logs() as captured:
+ await server.call_internal_tool("skyvern_evaluate", {"expression": "scan()"})
+
+ records = _timing_records(captured)
+ assert len(records) == 1
+ assert records[0]["call_status"] == "not_connected"
+ assert records[0]["call_path"] == "internal"
+ assert records[0]["server_timing_ms"] is None
diff --git a/tests/unit/test_copilot_output_utils.py b/tests/unit/test_copilot_output_utils.py
index 5b288b062..5ff978cac 100644
--- a/tests/unit/test_copilot_output_utils.py
+++ b/tests/unit/test_copilot_output_utils.py
@@ -916,6 +916,14 @@ class TestUserFacingSuccess:
result = {"ok": False, "error": signal.agent_steering_text}
assert user_facing_success(result, blocker_signal=signal) is True
+ def test_true_for_paused_run(self) -> None:
+ result = {"ok": False, "data": {"control_signal": {"kind": "watchdog_paused"}}}
+ assert user_facing_success(result) is True
+
+ def test_false_for_other_watchdog_exits(self) -> None:
+ result = {"ok": False, "data": {"control_signal": {"kind": "watchdog_ceiling"}}}
+ assert user_facing_success(result) is False
+
def test_false_for_genuine_tool_error(self) -> None:
"""Regression guard: real tool errors keep failure affect."""
blocker_kind = "tool_error"
diff --git a/tests/unit/test_copilot_screenshot_handling.py b/tests/unit/test_copilot_screenshot_handling.py
index d8f9920cc..7ba162b70 100644
--- a/tests/unit/test_copilot_screenshot_handling.py
+++ b/tests/unit/test_copilot_screenshot_handling.py
@@ -3,11 +3,17 @@
from __future__ import annotations
import base64
+from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
+from skyvern.forge.sdk.copilot.enforcement import _consume_pending_screenshots
+from skyvern.forge.sdk.copilot.screenshot_utils import ScreenshotEntry
+from skyvern.forge.sdk.copilot.session_factory import copilot_call_model_input_filter
+from tests.unit.copilot_test_helpers import make_model_input_data
+
def _install_mock_database(monkeypatch: pytest.MonkeyPatch, mock_db: Any) -> None:
"""Replace `skyvern.forge.sdk.copilot.tools.run_execution.app` with a stub whose
@@ -170,6 +176,36 @@ class TestConsumePendingScreenshots:
assert _consume_pending_screenshots(ctx) is None
+class TestNudgeDrainAndFilterExclusivity:
+ def test_nudge_delivery_binds_the_frame_and_the_next_filter_pass_adds_nothing(self) -> None:
+ ctx = SimpleNamespace(
+ pending_screenshots=[ScreenshotEntry(b64="dGVzdA==", mime="image/jpeg")],
+ supports_vision=True,
+ )
+
+ nudge_msg = _consume_pending_screenshots(ctx)
+
+ assert nudge_msg is not None
+ assert [part["type"] for part in nudge_msg["content"]] == ["input_text", "input_image"]
+ assert ctx.pending_screenshots == []
+
+ items = [{"role": "user", "content": "clear the modal on this page"}]
+ result = copilot_call_model_input_filter(make_model_input_data(items, context=ctx))
+
+ assert result.input == items
+
+ def test_the_nudge_path_also_withholds_the_frame_from_a_non_vision_model(self) -> None:
+ # The vision check lives in the shared builder so every delivery path inherits it;
+ # the drain still empties the queue.
+ ctx = SimpleNamespace(
+ pending_screenshots=[ScreenshotEntry(b64="dGVzdA==", mime="image/jpeg")],
+ supports_vision=False,
+ )
+
+ assert _consume_pending_screenshots(ctx) is None
+ assert ctx.pending_screenshots == []
+
+
class TestExtractScreenshotB64:
@staticmethod
def _extract(result: dict) -> Any:
diff --git a/tests/unit/test_copilot_secret_scrub.py b/tests/unit/test_copilot_secret_scrub.py
index a893ceac7..4d938cc65 100644
--- a/tests/unit/test_copilot_secret_scrub.py
+++ b/tests/unit/test_copilot_secret_scrub.py
@@ -7,7 +7,7 @@ from __future__ import annotations
import base64
import json
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from typing import Any
from unittest.mock import MagicMock
@@ -127,13 +127,22 @@ class _FakeRawResult:
class _FakeClient:
- def __init__(self, payload: dict[str, Any] | Exception) -> None:
+ def __init__(
+ self,
+ payload: dict[str, Any] | Exception,
+ on_call: Callable[[], None] | None = None,
+ is_error: bool = False,
+ ) -> None:
self._payload = payload
+ self._on_call = on_call
+ self._is_error = is_error
async def call_tool(self, name: str, args: dict[str, Any], raise_on_error: bool = False) -> _FakeRawResult:
+ if self._on_call is not None:
+ self._on_call()
if isinstance(self._payload, Exception):
raise self._payload
- return _FakeRawResult(self._payload)
+ return _FakeRawResult(self._payload, self._is_error)
def _evaluate_readback_payload() -> dict[str, Any]:
@@ -156,16 +165,21 @@ def _evaluate_readback_payload() -> dict[str, Any]:
def _make_server(
- ctx: AgentContext, payload: dict[str, Any] | Exception, overlay: SchemaOverlay
+ ctx: AgentContext,
+ payload: dict[str, Any] | Exception,
+ overlay: SchemaOverlay,
+ alias_map: dict[str, str] | None = None,
+ on_call: Callable[[], None] | None = None,
+ is_error: bool = False,
) -> SkyvernOverlayMCPServer:
server = SkyvernOverlayMCPServer(
transport=MagicMock(),
overlays={"evaluate": overlay},
- alias_map={},
+ alias_map=alias_map or {},
allowlist=frozenset(),
context_provider=lambda: ctx,
)
- server._client = _FakeClient(payload)
+ server._client = _FakeClient(payload, on_call, is_error)
return server
diff --git a/tests/unit/test_copilot_session_factory.py b/tests/unit/test_copilot_session_factory.py
index 33d4396f7..07765cc31 100644
--- a/tests/unit/test_copilot_session_factory.py
+++ b/tests/unit/test_copilot_session_factory.py
@@ -8,10 +8,30 @@ from types import SimpleNamespace
from typing import Any
import pytest
+from structlog.testing import capture_logs
+from skyvern.forge.sdk.copilot.screenshot_utils import ScreenshotEntry
+from skyvern.forge.sdk.copilot.session_factory import (
+ copilot_call_model_input_filter,
+ make_copilot_call_model_input_filter,
+)
from tests.unit.copilot_test_helpers import make_model_input_data as _mk_input_data
+def _image_parts(item: Any) -> list[Any]:
+ content = item.get("content") if isinstance(item, dict) else None
+ if not isinstance(content, list):
+ return []
+ return [part for part in content if part.get("type") == "input_image"]
+
+
+def _ctx_with_staged_frame(*, supports_vision: bool = True) -> SimpleNamespace:
+ return SimpleNamespace(
+ pending_screenshots=[ScreenshotEntry(b64="dGVzdA==", mime="image/jpeg")],
+ supports_vision=supports_vision,
+ )
+
+
class TestFirstTurnCompaction:
"""CORR-3 regression guards: first-turn transcripts (one real user +
long tool chain) must compact older tool outputs / function-call args
@@ -261,3 +281,61 @@ def test_model_input_pipeline_has_no_generated_offer_special_case() -> None:
from skyvern.forge.sdk.copilot import enforcement
assert not hasattr(enforcement, "collapse_superseded_synthesized_offers")
+
+
+class TestStagedScreenshotBinding:
+ """A frame a tool captured mid-run must reach the acting model on the same turn."""
+
+ def test_staged_frame_rides_as_the_last_item(self) -> None:
+ ctx = _ctx_with_staged_frame()
+ items = [{"role": "user", "content": "clear the modal on this page"}]
+
+ with capture_logs() as logs:
+ result = copilot_call_model_input_filter(_mk_input_data(items, context=ctx))
+
+ assert [len(_image_parts(item)) for item in result.input] == [0, 1]
+ assert any(log["event"] == "Injecting screenshot user message" for log in logs)
+
+ def test_a_second_pass_over_the_same_context_still_carries_the_frame(self) -> None:
+ ctx = _ctx_with_staged_frame()
+ items = [{"role": "user", "content": "clear the modal on this page"}]
+
+ first = copilot_call_model_input_filter(_mk_input_data(items, context=ctx))
+ second = copilot_call_model_input_filter(_mk_input_data(items, context=ctx))
+
+ assert len(_image_parts(first.input[-1])) == 1
+ assert len(_image_parts(second.input[-1])) == 1
+ assert len(ctx.pending_screenshots) == 1
+
+ def test_a_non_vision_fallback_model_gets_no_image(self) -> None:
+ # The frame was staged while the primary was still vision-capable; a retriable failure
+ # can swap in a fallback that cannot accept images.
+ ctx = _ctx_with_staged_frame(supports_vision=False)
+ items = [{"role": "user", "content": "clear the modal on this page"}]
+
+ result = copilot_call_model_input_filter(_mk_input_data(items, context=ctx))
+
+ assert not any(_image_parts(item) for item in result.input)
+ assert len(ctx.pending_screenshots) == 1
+
+ def test_call_with_nothing_staged_carries_no_image(self) -> None:
+ ctx = SimpleNamespace(pending_screenshots=[])
+ items = [{"role": "user", "content": "clear the modal on this page"}]
+
+ with capture_logs() as logs:
+ result = copilot_call_model_input_filter(_mk_input_data(items, context=ctx))
+
+ assert result.input == items
+ assert not any(_image_parts(item) for item in result.input)
+ assert not any(log["event"] == "Injecting screenshot user message" for log in logs)
+
+ def test_aggressive_prune_drops_the_bound_frame_like_any_other_screenshot(self) -> None:
+ ctx = _ctx_with_staged_frame()
+ items: list[dict[str, Any]] = [{"role": "user", "content": "build me a workflow"}]
+ for i in range(12):
+ items.append({"type": "function_call", "call_id": f"call-{i}", "name": "observe", "arguments": "{}"})
+ items.append({"type": "function_call_output", "call_id": f"call-{i}", "output": "y" * 4000})
+
+ result = make_copilot_call_model_input_filter(1)(_mk_input_data(items, context=ctx))
+
+ assert not any(_image_parts(item) for item in result.input)
diff --git a/tests/unit/test_copilot_timeout_wip.py b/tests/unit/test_copilot_timeout_wip.py
index 92d0f4f9c..3f73b347e 100644
--- a/tests/unit/test_copilot_timeout_wip.py
+++ b/tests/unit/test_copilot_timeout_wip.py
@@ -33,6 +33,7 @@ from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (
RepairDecision,
VerificationResult,
)
+from skyvern.forge.sdk.copilot.failure_tracking import PER_TOOL_BUDGET_FAILURE_CATEGORY
from skyvern.forge.sdk.copilot.review_gate import workflow_block_fingerprints
from skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind
@@ -98,11 +99,11 @@ def _overwrite_ctx(*, last_test_ok: bool | None) -> MagicMock:
_STATE_EXPECTATIONS = {
- "no_workflow": ("auto_applicable", "default", False),
+ "no_workflow": ("no_proposal", "default", False),
"untested": ("review_untested", "unvalidated", True),
- "failed_test": ("auto_applicable", "default", False),
+ "failed_test": ("review_untested", "unvalidated", True),
"passing_test": ("review_tested", "tested", True),
- "suspicious_success": ("auto_applicable", "default", False),
+ "suspicious_success": ("review_untested", "unvalidated", True),
}
@@ -295,7 +296,7 @@ class TestBuildTimeoutExitResult:
assert result.updated_workflow is None
assert result.workflow_yaml is None
- assert result.proposal_disposition == "auto_applicable"
+ assert result.proposal_disposition == "no_proposal"
assert result.user_response == _TIMEOUT_REPLY_DEFAULT
def test_missing_yaml_drops_tested_proposal(self) -> None:
@@ -306,7 +307,7 @@ class TestBuildTimeoutExitResult:
assert result.updated_workflow is None
assert result.workflow_yaml is None
- assert result.proposal_disposition == "auto_applicable"
+ assert result.proposal_disposition == "no_proposal"
assert result.user_response == _TIMEOUT_REPLY_DEFAULT
def test_interactive_completion_verdict_cannot_preserve_tested_proposal_on_timeout(self) -> None:
@@ -326,13 +327,13 @@ class TestBuildTimeoutExitResult:
result = _build_timeout_exit_result(ctx, global_llm_context=None)
- assert result.updated_workflow is None
- assert result.workflow_yaml is None
- assert result.proposal_disposition == "auto_applicable"
- assert result.user_response == _TIMEOUT_REPLY_DEFAULT
+ assert result.updated_workflow is wf
+ assert result.workflow_yaml == "version: '1.0'"
+ assert result.proposal_disposition == "review_untested"
+ assert result.user_response == _TIMEOUT_REPLY_UNVALIDATED
assert result.clear_proposed_workflow is False
- def test_stale_latch_without_judge_verdict_does_not_preserve_proposal(self) -> None:
+ def test_stale_latch_without_judge_verdict_does_not_credit_proposal_as_tested(self) -> None:
wf = MagicMock(name="wf")
ctx = _ctx(
last_workflow=wf,
@@ -346,11 +347,12 @@ class TestBuildTimeoutExitResult:
result = _build_timeout_exit_result(ctx, global_llm_context=None)
- assert result.updated_workflow is None
- assert result.workflow_yaml is None
- assert result.user_response == _TIMEOUT_REPLY_DEFAULT
+ assert result.updated_workflow is wf
+ assert result.workflow_yaml == "version: '1.0'"
+ assert result.proposal_disposition == "review_untested"
+ assert result.user_response == _TIMEOUT_REPLY_UNVALIDATED
- def test_suspicious_current_run_drops_last_good_workflow_without_verified_terminal_state(self) -> None:
+ def test_suspicious_current_run_surfaces_current_draft_not_last_good_workflow(self) -> None:
wf = MagicMock(name="wf")
last_good = MagicMock(name="last_good")
ctx = _ctx(
@@ -364,10 +366,12 @@ class TestBuildTimeoutExitResult:
result = _build_timeout_exit_result(ctx, global_llm_context=None)
- assert result.updated_workflow is None
- assert result.workflow_yaml is None
- assert result.proposal_disposition == "auto_applicable"
- assert result.user_response == _TIMEOUT_REPLY_DEFAULT
+ # The last-good branch stays guarded on a suspicious run -- crediting that
+ # shape as tested would be the false-success this terminal must not make.
+ assert result.updated_workflow is wf
+ assert result.workflow_yaml == "version: 'broken'"
+ assert result.proposal_disposition == "review_untested"
+ assert result.user_response == _TIMEOUT_REPLY_UNVALIDATED
class TestBuildCancelledExitResult:
@@ -405,7 +409,7 @@ class TestBuildUnexpectedErrorExitResult:
assert result.updated_workflow is None
assert result.workflow_yaml is None
- assert result.proposal_disposition == "auto_applicable"
+ assert result.proposal_disposition == "no_proposal"
assert "An unexpected error occurred. Please try again." not in result.user_response
assert "Copilot hit an internal error before it could finish this turn" in result.user_response
assert "The workflow was not modified" in result.user_response
@@ -433,18 +437,16 @@ class TestBuildUnexpectedErrorExitResult:
assert result.proposal_disposition == "review_tested"
assert result.user_response == _UNEXPECTED_ERROR_REPLY_TESTED
- def test_failed_test_drops_proposal(self) -> None:
+ def test_failed_test_surfaces_proposal_as_unvalidated(self) -> None:
wf = MagicMock(name="wf")
ctx = _ctx(last_workflow=wf, last_workflow_yaml="version: '1.0'", last_test_ok=False)
result = _build_unexpected_error_exit_result(ctx, global_llm_context=None)
- assert result.updated_workflow is None
- assert result.workflow_yaml is None
- assert result.proposal_disposition == "auto_applicable"
- assert "Copilot hit an internal error before it could finish this turn" in result.user_response
- assert "The workflow was preserved" in result.user_response
- assert "reference cpe_" in result.user_response
+ assert result.updated_workflow is wf
+ assert result.workflow_yaml == "version: '1.0'"
+ assert result.proposal_disposition == "review_untested"
+ assert result.user_response == _UNEXPECTED_ERROR_REPLY_UNVALIDATED
def test_failed_test_uses_recorded_blocker_reply(self) -> None:
wf = MagicMock(name="wf")
@@ -542,7 +544,7 @@ class TestBuildUnexpectedErrorExitResult:
assert "tested it" not in result.user_response
assert "I couldn't start a test run" in result.user_response
- def test_suspicious_success_drops_proposal(self) -> None:
+ def test_suspicious_success_surfaces_proposal_without_crediting_it_as_tested(self) -> None:
wf = MagicMock(name="wf")
ctx = _ctx(
last_workflow=wf,
@@ -553,12 +555,10 @@ class TestBuildUnexpectedErrorExitResult:
result = _build_unexpected_error_exit_result(ctx, global_llm_context=None)
- assert result.updated_workflow is None
- assert result.workflow_yaml is None
- assert result.proposal_disposition == "auto_applicable"
- assert "Copilot hit an internal error before it could finish this turn" in result.user_response
- assert "The workflow was preserved" in result.user_response
- assert "reference cpe_" in result.user_response
+ assert result.updated_workflow is wf
+ assert result.workflow_yaml == "version: '1.0'"
+ assert result.proposal_disposition == "review_untested"
+ assert result.user_response == _UNEXPECTED_ERROR_REPLY_UNVALIDATED
class TestWipExitSurfacesLastGoodWithForceReviewNotUnvalidated:
@@ -690,7 +690,7 @@ class TestTimeoutExitNamesTimeAndDraftState:
result = _build_timeout_exit_result(ctx, global_llm_context=None)
- assert result.proposal_disposition == "auto_applicable"
+ assert result.proposal_disposition == "no_proposal"
assert "ran out of time" in result.user_response
def test_untested_draft_with_recorded_failure_still_names_time(self) -> None:
@@ -823,3 +823,69 @@ class TestCancelExitIsRecordedAsAStopNotAQuestion:
assert result.turn_outcome is not None
assert result.turn_outcome.terminal_reason == terminal_reason
assert result.turn_outcome.response_kind is ResponseKind.CLARIFY
+
+
+class TestDeadlineTerminalHandsOverRecordedDraft:
+ """Existence is the condition for surfacing; the test verdict is a label on what is surfaced."""
+
+ def test_failed_test_draft_survives_the_deadline(self) -> None:
+ wf = MagicMock(name="wf")
+ ctx = _ctx(last_workflow=wf, last_workflow_yaml="version: '1.0'", last_test_ok=False)
+ ctx.copilot_total_timeout_exceeded = True
+ ctx.last_failure_category_top = None
+
+ result = _build_timeout_exit_result(ctx, global_llm_context=None)
+
+ assert result.updated_workflow is wf
+ assert result.workflow_yaml == "version: '1.0'"
+ assert result.proposal_disposition == "review_untested"
+
+ def test_failed_test_reply_names_the_failure(self) -> None:
+ wf = MagicMock(name="wf")
+ ctx = _ctx(last_workflow=wf, last_workflow_yaml="version: '1.0'", last_test_ok=False)
+ ctx.copilot_total_timeout_exceeded = True
+ ctx.last_failure_category_top = None
+ ctx.last_update_block_count = 2
+ ctx.latest_diagnosis_repair_contract = _blocker_contract(
+ "The login block never reached the dashboard.",
+ run_status="failed",
+ workflow_run_id="wr_sky14395",
+ )
+
+ result = _build_timeout_exit_result(ctx, global_llm_context=None)
+
+ assert result.updated_workflow is wf
+ assert "The last test did not verify" in result.user_response
+ assert "The login block never reached the dashboard" in result.user_response
+
+ @pytest.mark.parametrize(
+ "builder",
+ [
+ pytest.param(_build_timeout_exit_result, id="timeout"),
+ pytest.param(_build_max_turns_exit_result, id="max_turns"),
+ ],
+ )
+ def test_empty_terminal_claims_no_deliverable(self, builder) -> None:
+ ctx, _ = _state_ctx("no_workflow")
+ ctx.copilot_total_timeout_exceeded = True
+
+ result = builder(ctx, global_llm_context=None)
+
+ assert result.updated_workflow is None
+ assert result.proposal_disposition == "no_proposal"
+ assert "draft workflow" in result.user_response
+ assert "what I have so far" not in result.user_response
+ assert "I have a draft" not in result.user_response
+ assert "draft workflow you can keep" not in result.user_response
+
+ def test_budget_halted_run_is_not_told_its_test_failed(self) -> None:
+ wf = MagicMock(name="wf")
+ ctx = _ctx(last_workflow=wf, last_workflow_yaml="version: '1.0'", last_test_ok=False)
+ ctx.copilot_total_timeout_exceeded = True
+ ctx.last_failure_category_top = PER_TOOL_BUDGET_FAILURE_CATEGORY
+
+ result = _build_timeout_exit_result(ctx, global_llm_context=None)
+
+ assert result.updated_workflow is wf
+ assert "did not pass" not in result.user_response
+ assert "did not verify" not in result.user_response
diff --git a/tests/unit/test_copilot_turn_halt.py b/tests/unit/test_copilot_turn_halt.py
index 93e8c635d..6b8ee494f 100644
--- a/tests/unit/test_copilot_turn_halt.py
+++ b/tests/unit/test_copilot_turn_halt.py
@@ -5,6 +5,13 @@ from types import SimpleNamespace
import pytest
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal
+from skyvern.forge.sdk.copilot.composition_evidence import (
+ merge_visual_composition_evidence,
+ parse_composition_html,
+)
+from skyvern.forge.sdk.copilot.context import CopilotContext
+from skyvern.forge.sdk.copilot.enforcement import terminal_challenge_blocker_signal_from_page_evidence
+from skyvern.forge.sdk.copilot.request_policy import RequestPolicy
from skyvern.forge.sdk.copilot.run_outcome import (
DEVICE_APPROVAL_BLOCKER_REASON_CODE,
TERMINAL_CHALLENGE_BLOCKER_REASON_CODE,
@@ -57,3 +64,78 @@ def test_device_approval_challenge_stashes_local_halt() -> None:
assert halt.kind is TurnHaltKind.ACTIVE_TERMINAL_CHALLENGE
with pytest.raises(CopilotTurnHalt):
raise_if_turn_halt(ctx)
+
+
+_GENUINE_CHALLENGE_PAGES = {
+ "captcha": (
+ "<html><head><title>Security Verification</title></head><body>"
+ "<form><input id='lastName' name='lastName' type='text' />"
+ "<div class='captcha-box'><p id='captchaInstruction'>Enter all the digits from 'c7MDRxt'</p>"
+ "<input id='captchaAnswer' name='captchaAnswer' type='text' /></div>"
+ "<button type='submit'>Search</button></form></body></html>"
+ ),
+ "access_denied": (
+ "<html><head><title>Access Denied</title></head><body>"
+ "<h1>Access denied</h1><p>You do not have permission to view this page.</p></body></html>"
+ ),
+ "device_approval": (
+ "<html><head><title>Approve this sign-in</title></head><body>"
+ "<p>Open your authenticator app and approve this sign-in to complete verification.</p>"
+ "<form><button type='submit'>Resend request</button></form></body></html>"
+ ),
+}
+_SATISFIABLE_TOTP_PAGE = (
+ "<html><head><title>Two-Factor Authentication</title></head><body>"
+ "<p>Complete the challenge to continue.</p>"
+ "<form><label for='token'>Authenticator token</label>"
+ "<input id='token' name='token' type='text' placeholder='123456' />"
+ "<button type='submit' class='btn--login'>Login</button></form></body></html>"
+)
+_VISION_CHALLENGE_SUMMARY = {
+ "summary": "A centered verification card is shown; the primary submit control is described as blocked.",
+ "challenge_detected": True,
+ "challenge_kind": "other",
+ "challenge_location": "Centered page card",
+ "submit_blocked": True,
+ "blocked_submit_controls": ["Login button requires successful two-factor authentication"],
+}
+
+
+def _page_evidence_ctx(html: str) -> CopilotContext:
+ ctx = CopilotContext(
+ organization_id="o",
+ workflow_id="w",
+ workflow_permanent_id="wp",
+ workflow_yaml="",
+ browser_session_id=None,
+ stream=SimpleNamespace(), # type: ignore[arg-type]
+ request_policy=RequestPolicy(allow_update_workflow=True, allow_run_blocks=True),
+ )
+ ctx.last_run_blocks_workflow_run_id = "wr_failed"
+ ctx.composition_page_evidence = merge_visual_composition_evidence(
+ parse_composition_html(html, inspected_url="https://example.test/x", current_url="https://example.test/x"),
+ visual_summary=dict(_VISION_CHALLENGE_SUMMARY),
+ )
+ return ctx
+
+
[email protected]("page", sorted(_GENUINE_CHALLENGE_PAGES))
+def test_page_with_no_satisfiable_path_still_halts_the_turn(page: str) -> None:
+ ctx = _page_evidence_ctx(_GENUINE_CHALLENGE_PAGES[page])
+
+ signal = terminal_challenge_blocker_signal_from_page_evidence(ctx, blocked_tool="update_and_run_blocks")
+ halt = stash_turn_halt_from_blocker_signal(ctx, signal, source="test")
+
+ assert signal is not None
+ assert halt is not None
+ assert halt.kind is TurnHaltKind.ACTIVE_TERMINAL_CHALLENGE
+ with pytest.raises(CopilotTurnHalt):
+ raise_if_turn_halt(ctx)
+
+
+def test_editable_one_time_code_page_leaves_the_turn_running() -> None:
+ ctx = _page_evidence_ctx(_SATISFIABLE_TOTP_PAGE)
+
+ assert terminal_challenge_blocker_signal_from_page_evidence(ctx, blocked_tool="update_and_run_blocks") is None
+ assert stash_turn_halt_from_blocker_signal(ctx, None, source="test") is None
+ raise_if_turn_halt(ctx)
diff --git a/tests/unit/test_copilot_watchdog.py b/tests/unit/test_copilot_watchdog.py
index 05ba690aa..0cc64d08a 100644
--- a/tests/unit/test_copilot_watchdog.py
+++ b/tests/unit/test_copilot_watchdog.py
@@ -27,13 +27,18 @@ Those three are where the SKY-9163 correctness properties live:
from __future__ import annotations
import asyncio
-from datetime import datetime, timezone
+import time
+from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
from typing import Any
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, MagicMock
import pytest
+from skyvern.forge import app as forge_app
+from skyvern.forge.sdk.copilot.active_run_session import ActiveRunSessionAssociation
+from skyvern.forge.sdk.copilot.blocker_signal import contains_internal_machinery_leak
+from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.tools import (
PER_TOOL_CALL_BUDGET_SECONDS,
RUN_BLOCKS_SAFETY_CEILING_SECONDS,
@@ -42,9 +47,21 @@ from skyvern.forge.sdk.copilot.tools import (
_fallback_page_info,
_progress_marker,
_read_progress_sources,
+ _run_blocks_and_collect_debug,
_watchdog_error_message,
+ run_execution,
+)
+from skyvern.forge.sdk.copilot.tools.run_execution import (
+ WatchdogExitReason,
+ _watchdog_user_facing_summary,
+ _watchdog_user_failure_reason,
)
from skyvern.forge.sdk.copilot.turn_origin import TurnOrigin
+from skyvern.forge.sdk.routes.workflow_copilot import _process_workflow_yaml
+from skyvern.forge.sdk.schemas.organizations import Organization
+from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, WorkflowParameter
+from skyvern.services import workflow_service as workflow_service_module
+from tests.unit.copilot_test_helpers import make_copilot_ctx
def _fake_run(status: str = "running", modified_at: datetime | None = None) -> Any:
@@ -384,6 +401,55 @@ async def test_task_exit_unfinalized_message_tolerates_unreadable_run() -> None:
assert "get_run_results" in msg
+async def test_paused_error_message_reports_a_wait_not_an_uncertain_outcome() -> None:
+ """This arm is the only one that tells the model to relay its own text to the user, so relaying
+ it verbatim has to clear the output guard. It must also not inherit the "outcome is uncertain"
+ tail, which would push a re-run of blocks that are still live and waiting on a person."""
+ msg = await _watchdog_error_message("paused", _ErrorCtx(), "wr_test", _fake_run(status="paused"), 240)
+
+ assert "paused" in msg.lower()
+ assert "tell the user" in msg.lower()
+ assert "wr_test" not in msg
+ assert contains_internal_machinery_leak(msg) is False
+ assert "uncertain" not in msg.lower()
+ assert "nothing was cancelled" in msg.lower()
+
+
+async def test_non_paused_error_messages_keep_the_run_id_for_the_model() -> None:
+ """The other arms never direct a relay — they tell the model to look the run up — so stripping
+ the id there would take away the only handle it has."""
+ exit_reasons: tuple[WatchdogExitReason, ...] = ("stagnation", "ceiling", "per_tool_budget", "task_exit_unfinalized")
+ for exit_reason in exit_reasons:
+ msg = await _watchdog_error_message(exit_reason, _ErrorCtx(), "wr_test", _fake_run(), 240)
+
+ assert "Run ID: wr_test" in msg
+ assert "tell the user" not in msg.lower()
+
+
+def test_paused_user_relayed_text_carries_no_run_id() -> None:
+ """Both user-relayed arms of the paused exit: the person reading chat gets told what the run is
+ waiting for, never an internal ``wr_`` identifier."""
+ reason = _watchdog_user_failure_reason("paused", "wr_test", 240, _fake_run(status="paused"))
+ summary = _watchdog_user_facing_summary("paused", 240, _fake_run(status="paused"))
+
+ for text in (reason, summary):
+ assert "paused" in text.lower()
+ assert "approve or reject" in text.lower()
+ assert "wr_" not in text
+ assert "uncertain" not in text.lower()
+ assert contains_internal_machinery_leak(text) is False
+
+
+def test_per_tool_budget_user_relayed_text_still_carries_the_run_id() -> None:
+ """The run id strip is scoped to the pause: the budget arm keeps it, because that run was
+ cancelled and the id is how the follow-up finds what it completed."""
+ reason = _watchdog_user_failure_reason("per_tool_budget", "wr_test", 240, None)
+
+ assert "Run ID: wr_test" in reason
+
+
# ---------------------------------------------------------------------------
# _any_quiet_block_requested: stagnation bypass for block types that
# legitimately do long-silent work. Without this bypass, a WAIT block with
@@ -485,6 +551,258 @@ def test_any_quiet_block_requested_empty_labels_returns_false() -> None:
assert _any_quiet_block_requested(ctx, []) is False
+_HUMAN_INTERACTION_WORKFLOW_YAML = """
+title: human approval example
+workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: human_interaction
+ label: approve_login
+ timeout_seconds: 3600
+ recipients: ["[email protected]"]
+ subject: Manual sign-in needed
+ body: A workflow run is paused and needs someone to sign in.
+"""
+
+_EXTRACTION_WORKFLOW_YAML = """
+title: extraction example
+workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: extraction
+ label: extract_heading
+ url: https://example.com
+ data_extraction_goal: Extract the page heading.
+"""
+
+
+async def _install_run_harness(
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ workflow_yaml: str,
+ polled_status: str,
+) -> dict[str, Any]:
+ """Stub the collaborators an inline ``_run_blocks_and_collect_debug`` call reaches, with the
+ polled run parked on ``polled_status`` so the watchdog decides the exit."""
+ workflow = await _process_workflow_yaml(
+ settings_fallback_yaml="enable_self_healing: false",
+ workflow_id="w_source",
+ workflow_permanent_id="wfp-1",
+ organization_id="org-1",
+ workflow_yaml=workflow_yaml,
+ )
+ now = datetime.now(timezone.utc)
+ organization = Organization(
+ organization_id="org-1",
+ organization_name="Test Org",
+ created_at=now,
+ modified_at=now,
+ )
+ captured: dict[str, Any] = {"workflow": workflow, "executor_cancelled": False}
+
+ database = MagicMock()
+ database.workflows.get_workflow_by_permanent_id = AsyncMock(return_value=workflow)
+ database.organizations.get_organization = AsyncMock(return_value=organization)
+ persisted_output_params = [p for p in workflow.workflow_definition.parameters if isinstance(p, OutputParameter)]
+ persisted_workflow_params = [p for p in workflow.workflow_definition.parameters if isinstance(p, WorkflowParameter)]
+ database.workflow_params.get_workflow_output_parameters = AsyncMock(return_value=persisted_output_params)
+ database.observer.get_workflow_run_blocks = AsyncMock(return_value=[])
+ database.workflow_runs.get_workflow_run = AsyncMock(return_value=_fake_run(status=polled_status))
+ monkeypatch.setattr(forge_app, "DATABASE", database)
+
+ async def _execute_workflow(**_kwargs: Any) -> None:
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ captured["executor_cancelled"] = True
+ raise
+
+ workflow_service = MagicMock()
+ workflow_service.get_workflow_parameters = AsyncMock(return_value=persisted_workflow_params)
+ workflow_service.execute_workflow = AsyncMock(side_effect=_execute_workflow)
+ monkeypatch.setattr(forge_app, "WORKFLOW_SERVICE", workflow_service)
+ monkeypatch.setattr(
+ forge_app.AGENT_FUNCTION,
+ "should_dispatch_copilot_block_run_to_worker",
+ AsyncMock(return_value=False),
+ )
+ monkeypatch.setattr(
+ forge_app.AGENT_FUNCTION,
+ "allow_copilot_inline_code_execution",
+ MagicMock(return_value=False),
+ )
+
+ workflow_run = SimpleNamespace(
+ workflow_run_id="wr_paused",
+ workflow_id="w_source",
+ sequential_credential_id=None,
+ )
+ monkeypatch.setattr(workflow_service_module, "prepare_workflow", AsyncMock(return_value=workflow_run))
+
+ polled_run = _fake_run(status=polled_status)
+
+ async def _read_progress(_ctx: CopilotContext, _run_id: str) -> tuple[Any, Any, Any]:
+ return polled_run, now, now
+
+ monkeypatch.setattr(run_execution, "_read_progress_sources", _read_progress)
+ monkeypatch.setattr(run_execution, "RUN_BLOCKS_POLL_INTERVAL_SECONDS", 0)
+ monkeypatch.setattr(run_execution, "_fallback_page_info", AsyncMock(return_value=("", "")))
+
+ association = ActiveRunSessionAssociation(
+ organization_id="org-1",
+ workflow_permanent_id="wfp-1",
+ debug_browser_session_id="pbs_chat",
+ run_browser_session_id="pbs_run",
+ workflow_run_id="wr_paused",
+ turn_id="turn-1",
+ generation="gen-1",
+ expires_at=now + timedelta(minutes=5),
+ )
+ captured["publish"] = AsyncMock(return_value=association)
+ captured["clear"] = AsyncMock(return_value=True)
+ captured["cancel_run_task"] = AsyncMock(return_value=None)
+ captured["cooperative_cancel"] = AsyncMock(return_value=None)
+ monkeypatch.setattr(run_execution, "publish_active_run_session", captured["publish"])
+ monkeypatch.setattr(run_execution, "clear_active_run_session", captured["clear"])
+ monkeypatch.setattr(run_execution, "_cancel_run_task_if_not_final", captured["cancel_run_task"])
+ monkeypatch.setattr(run_execution, "_cooperative_cancel_dispatched_run", captured["cooperative_cancel"])
+ return captured
+
+
+def _adopted_detached_tasks(before: set[Any]) -> list[Any]:
+ return [task for task in run_execution._DETACHED_CLEANUP_TASKS if task not in before]
+
+
+async def test_paused_run_is_reported_as_a_pause_and_left_running(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A run paused at a human_interaction block with nobody responding: the watchdog must leave
+ the poll loop immediately, report the pause, and tear nothing down — the executor task, the run
+ itself and the pane's run-session association all have to outlive the tool call for an approval
+ to be able to resume the run."""
+ harness = await _install_run_harness(
+ monkeypatch,
+ workflow_yaml=_HUMAN_INTERACTION_WORKFLOW_YAML,
+ polled_status="paused",
+ )
+ ctx = make_copilot_ctx(browser_session_id="pbs_chat")
+ ctx.staged_workflow = harness["workflow"]
+ ctx.frontier_resume_session_id = "pbs_run"
+ before = set(run_execution._DETACHED_CLEANUP_TASKS)
+
+ started = time.monotonic()
+ result = await _run_blocks_and_collect_debug({"block_labels": ["approve_login"], "parameters": {}}, ctx)
+ elapsed = time.monotonic() - started
+
+ assert elapsed < RUN_BLOCKS_SAFETY_CEILING_SECONDS / 10
+ assert result["ok"] is False, result
+ assert result["data"]["control_signal"]["kind"] == "watchdog_paused", result
+ assert "paused" in result["data"]["user_facing_summary"].lower()
+ assert "uncertain" not in result["error"].lower()
+
+ harness["cancel_run_task"].assert_not_awaited()
+ harness["cooperative_cancel"].assert_not_awaited()
+ harness["clear"].assert_not_awaited()
+ harness["publish"].assert_awaited_once()
+
+ adopted = _adopted_detached_tasks(before)
+ assert len(adopted) == 1
+ await asyncio.sleep(0)
+ assert harness["executor_cancelled"] is False
+ assert not adopted[0].done()
+
+ adopted[0].cancel()
+ await asyncio.gather(*adopted, return_exceptions=True)
+
+
+async def test_tool_cancelled_while_paused_leaves_the_run_alive(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The pause is decided several awaits before the result is returned. A tool timeout landing in
+ that window must still leave the run alive, or the person's approval has nothing to resume."""
+ harness = await _install_run_harness(
+ monkeypatch,
+ workflow_yaml=_HUMAN_INTERACTION_WORKFLOW_YAML,
+ polled_status="paused",
+ )
+
+ async def _cancel_mid_flight(*_args: Any, **_kwargs: Any) -> str:
+ raise asyncio.CancelledError
+
+ monkeypatch.setattr(run_execution, "_watchdog_error_message", _cancel_mid_flight)
+
+ ctx = make_copilot_ctx(browser_session_id="pbs_chat")
+ ctx.staged_workflow = harness["workflow"]
+ ctx.frontier_resume_session_id = "pbs_run"
+ before = set(run_execution._DETACHED_CLEANUP_TASKS)
+
+ with pytest.raises(asyncio.CancelledError):
+ await _run_blocks_and_collect_debug({"block_labels": ["approve_login"], "parameters": {}}, ctx)
+
+ harness["cancel_run_task"].assert_not_awaited()
+ harness["cooperative_cancel"].assert_not_awaited()
+
+ adopted = _adopted_detached_tasks(before)
+ assert len(adopted) == 1
+ await asyncio.sleep(0)
+ assert harness["executor_cancelled"] is False
+
+ adopted[0].cancel()
+ await asyncio.gather(*adopted, return_exceptions=True)
+
+
+async def test_non_paused_watchdog_exit_still_cancels_and_clears(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The pause carve-out is scoped to the pause: a stagnating run still gets cancelled and still
+ releases the run-session association."""
+ harness = await _install_run_harness(
+ monkeypatch,
+ workflow_yaml=_EXTRACTION_WORKFLOW_YAML,
+ polled_status="running",
+ )
+ monkeypatch.setattr(run_execution, "RUN_BLOCKS_STAGNATION_WINDOW_SECONDS", 0)
+ ctx = make_copilot_ctx(browser_session_id="pbs_chat")
+ ctx.staged_workflow = harness["workflow"]
+ ctx.frontier_resume_session_id = "pbs_run"
+ before = set(run_execution._DETACHED_CLEANUP_TASKS)
+
+ result = await _run_blocks_and_collect_debug({"block_labels": ["extract_heading"], "parameters": {}}, ctx)
+
+ assert result["data"]["control_signal"]["kind"] == "watchdog_stagnation"
+ harness["cancel_run_task"].assert_awaited_once()
+ harness["clear"].assert_awaited_once()
+ assert _adopted_detached_tasks(before) == []
+
+
+def test_paused_result_records_last_test_ok_as_none() -> None:
+ """``None`` is the only honest value: at ``False`` the finalizer rewrites the reply into a
+ failed test, and ``True`` would let an unapproved draft count as verified."""
+ ctx = make_copilot_ctx(browser_session_id="pbs_chat")
+
+ run_execution._record_run_blocks_result(
+ ctx,
+ {
+ "ok": False,
+ "data": {"workflow_run_id": "wr_paused", "control_signal": {"kind": "watchdog_paused"}},
+ },
+ )
+
+ assert ctx.last_test_ok is None
+
+
+def test_non_paused_failure_still_records_last_test_ok_as_false() -> None:
+ ctx = make_copilot_ctx(browser_session_id="pbs_chat")
+
+ run_execution._record_run_blocks_result(
+ ctx,
+ {
+ "ok": False,
+ "data": {"workflow_run_id": "wr_ceiling", "control_signal": {"kind": "watchdog_ceiling"}},
+ },
+ )
+
+ assert ctx.last_test_ok is False
+
+
# ---------------------------------------------------------------------------
# Reconciliation guard message: regression guard on "timed out" phrasing.
# The guard itself is tested in test_copilot_cancel_helpers.py; this test is
diff --git a/tests/unit/test_download_file_action_handler.py b/tests/unit/test_download_file_action_handler.py
index 216649ccd..3fd85a420 100644
--- a/tests/unit/test_download_file_action_handler.py
+++ b/tests/unit/test_download_file_action_handler.py
@@ -1471,6 +1471,66 @@ async def test_handle_action_crdownload_signal_enters_completion_before_reportin
assert "report.pdf.crdownload" not in results[-1].downloaded_files
+async def test_handle_action_aborted_download_is_reported_as_failure_not_success() -> None:
+ # The browser deletes the partial file when it aborts a transfer, so the settle sees the same
+ # empty directory a completed download leaves behind. Reporting success here tells the agent the
+ # file arrived, and it retries the already-consumed link instead of regenerating it.
+ now = datetime.now(UTC)
+ organization = make_organization(now)
+ task, step, page, browser_state, scraped_page, action = _make_download_click_context(
+ now=now,
+ organization=organization,
+ page_url="https://example.com/download",
+ )
+ task.download_timeout = 0.05
+
+ with tempfile.TemporaryDirectory() as temp_dir:
+ partial_path = Path(temp_dir) / "bundle.zip.crdownload"
+ aborted_download = _download(path=partial_path, failure="canceled")
+ aborted_download.url = "https://example.com/bundle.zip"
+
+ async def mock_inner_handle_action(*args: object, **kwargs: object) -> list[ActionSuccess]:
+ partial_path.write_bytes(b"in progress")
+ capture = next(call_.args[1] for call_ in page.on.call_args_list if call_.args[0] == "download")
+ capture(aborted_download)
+ return [ActionSuccess()]
+
+ async def abort_download(**kwargs: object) -> None:
+ partial_path.unlink()
+
+ mock_app = MagicMock()
+ mock_app.BROWSER_MANAGER.get_for_task.return_value = browser_state
+ mock_app.DATABASE.workflow_params.create_action = AsyncMock(return_value=action)
+ mock_app.STORAGE = MagicMock()
+
+ with (
+ patch.object(ActionHandler, "_handle_action", side_effect=mock_inner_handle_action),
+ patch("skyvern.webeye.actions.handler.get_download_dir", return_value=temp_dir),
+ patch("skyvern.webeye.actions.handler.skyvern_context.current", return_value=None),
+ patch(
+ "skyvern.webeye.actions.handler.check_downloading_files_and_wait_for_download_to_complete",
+ new=AsyncMock(side_effect=abort_download),
+ ),
+ patch("skyvern.webeye.actions.handler.app", mock_app),
+ ):
+ results = await asyncio.wait_for(
+ ActionHandler.handle_action(
+ scraped_page=scraped_page,
+ task=task,
+ step=step,
+ page=page,
+ action=action,
+ ),
+ timeout=CI_TEST_RUNAWAY_TIMEOUT_SECONDS,
+ )
+
+ assert results[-1].success is False
+ assert results[-1].download_triggered is True
+ assert not results[-1].downloaded_files
+ assert "canceled" in (results[-1].exception_message or "")
+
+
@pytest.mark.asyncio
async def test_handle_action_remote_crdownload_signal_enters_completion_before_reporting_final_artifact() -> None:
now = datetime.now(UTC)
diff --git a/tests/unit/test_security.py b/tests/unit/test_security.py
index dce77964b..8bd285255 100644
--- a/tests/unit/test_security.py
+++ b/tests/unit/test_security.py
@@ -2,21 +2,10 @@ import pytest
from freezegun import freeze_time
from skyvern.forge.sdk.core.security import (
- MAX_WEBHOOK_PAYLOAD_LOG_SIZE,
create_access_token,
generate_skyvern_webhook_signature,
- redact_credentialed_urls,
)
-_SIGNED = "https://api.skyvern.com/v1/artifacts/art_1/content?expiry=1800000600&kid=k1&sig=SIGNED_SECRET"
-_S3 = (
- "https://bucket.s3.amazonaws.com/org/art_2.png"
- "?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIA%2F20260716&X-Amz-Expires=900&X-Amz-Signature=S3_SECRET"
-)
-_AZURE = "https://acct.blob.core.windows.net/c/art_3.webm?sv=2021-08-06&se=2026-07-16T00%3A00%3A00Z&sig=AZURE_SECRET"
-_GCS = "https://storage.googleapis.com/bucket/art_4.png?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Signature=GCS_SECRET"
-_PLAIN = "https://consumer.example.com/callback?run_id=r_1&status=done"
-
@pytest.mark.skip(reason="Skipping test_generate_skyvern_signature")
@freeze_time("2023-11-30 00:00:00")
@@ -25,89 +14,3 @@ def test_generate_skyvern_signature() -> None:
payload = {"task_id": "t_12345", "float": 1.0}
signed_data = generate_skyvern_webhook_signature(payload, api_key)
assert signed_data.signature == "1fac4204e1abc7cb0bdf1a42eb17d27f6f1feba065d5726777d5eb77581298c1"
-
-
-class TestRedactCredentialedUrls:
- def test_strips_skyvern_signed_content_url(self) -> None:
- assert redact_credentialed_urls(_SIGNED) == "https://api.skyvern.com/v1/artifacts/art_1/content"
-
- def test_strips_s3_presigned(self) -> None:
- out = redact_credentialed_urls(_S3)
- assert "S3_SECRET" not in out
- assert out == "https://bucket.s3.amazonaws.com/org/art_2.png"
-
- def test_strips_azure_sas(self) -> None:
- out = redact_credentialed_urls(_AZURE)
- assert "AZURE_SECRET" not in out
- assert out == "https://acct.blob.core.windows.net/c/art_3.webm"
-
- def test_strips_gcs_presigned(self) -> None:
- out = redact_credentialed_urls(_GCS)
- assert "GCS_SECRET" not in out
- assert out == "https://storage.googleapis.com/bucket/art_4.png"
-
- def test_preserves_non_credentialed_url(self) -> None:
- assert redact_credentialed_urls(_PLAIN) == _PLAIN
-
- def test_strips_signed_url_embedded_in_text(self) -> None:
- out = redact_credentialed_urls(f"failed to fetch {_SIGNED} after 3 retries")
- assert "SIGNED_SECRET" not in out
- assert out == "failed to fetch https://api.skyvern.com/v1/artifacts/art_1/content after 3 retries"
-
- def test_leaves_plain_text_untouched(self) -> None:
- assert redact_credentialed_urls("no urls here, just text") == "no urls here, just text"
-
- def test_strips_uppercase_scheme(self) -> None:
- url = "HTTPS://api.skyvern.com/v1/artifacts/art_5/content?expiry=1&kid=k&sig=UPPER_SECRET"
- assert "UPPER_SECRET" not in redact_credentialed_urls(url)
-
- def test_strips_presigned_url_with_apostrophe_in_path(self) -> None:
- url = "https://bucket.s3.amazonaws.com/o'brien.pdf?X-Amz-Signature=APOS_SECRET"
- out = redact_credentialed_urls(url)
- assert "APOS_SECRET" not in out
- assert out == "https://bucket.s3.amazonaws.com/o'brien.pdf"
-
- def test_strips_basic_auth_userinfo_on_credentialed_url(self) -> None:
- url = "https://user:[email protected]/v1/artifacts/art_6/content?sig=X"
- out = redact_credentialed_urls(url)
- assert "PASSWORD" not in out
- assert out == "https://api.skyvern.com/v1/artifacts/art_6/content"
-
- def test_fails_closed_on_unparseable_url(self) -> None:
- # An invalid IPv6 host makes urlsplit raise ValueError — must not leak the sig.
- url = "https://[bad_ipv6/path?sig=UNPARSEABLE_SECRET"
- out = redact_credentialed_urls(url)
- assert "UNPARSEABLE_SECRET" not in out
-
-
-class TestWebhookPayloadForLog:
- def test_payload_for_log_redacts_urls_but_signed_payload_stays_raw(self) -> None:
- api_key = "test-api-key"
- payload = {
- "task_id": "t_1",
- "screenshot_url": _SIGNED,
- "recording_url": _S3,
- "webhook_callback_url": _PLAIN,
- "notes": f"artifact at {_SIGNED}",
- }
- signed = generate_skyvern_webhook_signature(payload, api_key)
-
- # log copy is scrubbed of every signature/presign secret, incl. the embedded one
- for secret in ("SIGNED_SECRET", "S3_SECRET"):
- assert secret not in signed.payload_for_log
- # non-credentialed callback URL is preserved in the log
- assert "run_id=r_1" in signed.payload_for_log
- # delivered payload + signature are untouched (raw, still carry the secrets)
- assert "SIGNED_SECRET" in signed.signed_payload
- assert "S3_SECRET" in signed.signed_payload
- assert signed.signature == generate_skyvern_webhook_signature(payload, api_key).signature
-
- def test_oversized_payload_is_redacted_and_truncated(self) -> None:
- api_key = "test-api-key"
- filler = "x" * MAX_WEBHOOK_PAYLOAD_LOG_SIZE
- payload = {"screenshot_url": _SIGNED, "filler": filler}
- signed = generate_skyvern_webhook_signature(payload, api_key)
-
- assert "SIGNED_SECRET" not in signed.payload_for_log
- assert "truncated" in signed.payload_for_log
- assert signed.payload_for_log.endswith(")")
diff --git a/tests/unit/test_select_shadow_match.py b/tests/unit/test_select_shadow_match.py
index a64705e17..34181fd0a 100644
--- a/tests/unit/test_select_shadow_match.py
+++ b/tests/unit/test_select_shadow_match.py
@@ -500,6 +500,9 @@ async def test_emerging_select_call_path_forwards_committed_value_to_shadow_matc
monkeypatch.setattr(handler, "json_to_html", Mock(return_value="<div>Committed Value</div>"))
deterministic_select = AsyncMock(return_value=None)
monkeypatch.setattr(handler, "_select_deterministic_custom_option", deterministic_select)
+ monkeypatch.setattr(handler, "_verify_custom_select_option_with_settle", AsyncMock(return_value=(True, "scope")))
+ monkeypatch.setattr(handler, "_verify_custom_select_option", AsyncMock(return_value=(True, "scope")))
+ monkeypatch.setattr(handler, "_wait_custom_select_render_settle", AsyncMock())
monkeypatch.setattr(handler.prompt_engine, "load_prompt", Mock(return_value="prompt"))
monkeypatch.setattr(
handler.LLMAPIHandlerFactory,
@@ -512,6 +515,7 @@ async def test_emerging_select_call_path_forwards_committed_value_to_shadow_matc
scraped_page = SimpleNamespace(id_to_css_dict={})
scraped_page_after_open = SimpleNamespace(
id_to_css_dict={"matched-id": "[data-id=matched-id]"},
+ id_to_element_dict={"field-id": {"id": "field-id"}},
element_tree_trimmed=[_SHADOW_OPTION],
)
with skyvern_context.scoped(SkyvernContext(tz_info=ZoneInfo("UTC"))):
diff --git a/tests/unit/test_webhook_failure_reason.py b/tests/unit/test_webhook_failure_reason.py
index 7ce188ef0..0911f597d 100644
--- a/tests/unit/test_webhook_failure_reason.py
+++ b/tests/unit/test_webhook_failure_reason.py
@@ -37,7 +37,6 @@ def task_webhook_agent(monkeypatch: pytest.MonkeyPatch) -> tuple[ForgeAgent, Asy
agent_module,
"generate_skyvern_webhook_signature",
lambda payload, api_key: SimpleNamespace(
- payload_for_log='{"safe":true}',
headers={"x-skyvern-signature": "sig"},
signed_payload='{"signed":true}',
),
@@ -132,7 +131,6 @@ async def test_task_v2_webhook_delivery_exception_persists_failure_reason(
task_v2_service,
"generate_skyvern_webhook_signature",
lambda payload, api_key: SimpleNamespace(
- payload_for_log='{"safe":true}',
headers={"x-skyvern-signature": "sig"},
signed_payload='{"signed":true}',
),
diff --git a/tests/unit/test_workflow_block_engine.py b/tests/unit/test_workflow_block_engine.py
new file mode 100644
index 000000000..27ff2409d
--- /dev/null
+++ b/tests/unit/test_workflow_block_engine.py
@@ -0,0 +1,489 @@
+"""Tests for the WORKFLOW_TASK_V3_AB run-level engine A/B: run eligibility, arm resolution
+(idempotency, kill switch, fail-closed), and the invariant that the persisted engine on
+workflow_run_blocks and the dispatched engine come from the same resolution.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+from datetime import UTC, datetime
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from skyvern.forge import app
+from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
+from skyvern.forge.sdk.experimentation.providers import BaseExperimentationProvider, NoOpExperimentationProvider
+from skyvern.forge.sdk.experimentation.workflow_block_engine import (
+ DISABLE_TASK_V3_FLAG,
+ WORKFLOW_TASK_V3_AB_FLAG,
+ resolve_workflow_block_engine_arm,
+ workflow_block_engine_override,
+)
+from skyvern.forge.sdk.workflow.models.block import (
+ ActionBlock,
+ BaseTaskBlock,
+ Block,
+ CodeBlock,
+ FileDownloadBlock,
+ ForLoopBlock,
+ HumanInteractionBlock,
+ NavigationBlock,
+ TaskBlock,
+ UrlBlock,
+ get_all_blocks,
+ run_is_eligible_for_v3_ab,
+)
+from skyvern.forge.sdk.workflow.service import WorkflowService
+from skyvern.schemas.run_enums import RunEngine
+from tests.unit.helpers import make_organization
+from tests.unit.test_agent_task_v3 import _make_block, _make_output_parameter, _run_execute_step_gate
+from tests.unit.test_block_description_caching import _block_result, _setup_mocks
+from tests.unit.test_missing_starter_url import _mock_block_execute_deps
+
+WORKFLOW_BLOCK_ENGINE_APP_TARGET = "skyvern.forge.sdk.experimentation.workflow_block_engine.app"
+
+
+class _FakeExperimentationProvider(BaseExperimentationProvider):
+ def __init__(self, flags: dict[str, bool] | None = None, raise_error: bool = False) -> None:
+ super().__init__()
+ self.flags = dict(flags or {})
+ self.calls: list[tuple[str, str, dict | None]] = []
+ self.raise_error = raise_error
+
+ async def _is_feature_enabled(self, feature_name: str, distinct_id: str, properties: dict | None = None) -> bool:
+ self.calls.append((feature_name, distinct_id, properties))
+ if self.raise_error:
+ raise RuntimeError("provider unavailable")
+ return self.flags.get(feature_name, False)
+
+ async def _get_value(self, feature_name: str, distinct_id: str, properties: dict | None = None) -> str | None:
+ return None
+
+ async def _get_payload(self, feature_name: str, distinct_id: str, properties: dict | None = None) -> Any:
+ return None
+
+
+def scoped_context() -> Iterator[SkyvernContext]:
+ context = SkyvernContext()
+ skyvern_context.set(context)
+ try:
+ yield context
+ finally:
+ skyvern_context.reset()
+
+
+async def _resolve(
+ context: SkyvernContext,
+ provider: BaseExperimentationProvider,
+ *,
+ workflow_run_id: str,
+ run_is_eligible: bool,
+ organization_id: str | None = "org_1",
+ workflow_permanent_id: str | None = "wpid_1",
+) -> None:
+ with patch(WORKFLOW_BLOCK_ENGINE_APP_TARGET) as mock_app:
+ mock_app.EXPERIMENTATION_PROVIDER = provider
+ await resolve_workflow_block_engine_arm(
+ context,
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ run_is_eligible=run_is_eligible,
+ )
+
+
+def test_mixed_eligibility_run_download_block_disqualifies(scoped_context: SkyvernContext) -> None:
+ eligible_1 = _make_block(TaskBlock, label="t1")
+ eligible_2 = _make_block(NavigationBlock, label="t2", navigation_goal="Apply to the job")
+ download_block = _make_block(ActionBlock, label="dl", complete_on_download=True)
+ blocks: list[BaseTaskBlock] = [eligible_1, eligible_2, download_block]
+
+ assert run_is_eligible_for_v3_ab(blocks, is_script_run=False) is False
+
+
+def test_mixed_eligibility_run_file_download_block_disqualifies(scoped_context: SkyvernContext) -> None:
+ eligible_1 = _make_block(TaskBlock, label="t1")
+ eligible_2 = _make_block(NavigationBlock, label="t2", navigation_goal="Apply to the job")
+ file_download_block = _make_block(FileDownloadBlock, label="fd")
+ blocks: list[BaseTaskBlock] = [eligible_1, eligible_2, file_download_block]
+
+ assert run_is_eligible_for_v3_ab(blocks, is_script_run=False) is False
+
+
+async def test_mixed_eligibility_run_pins_whole_run_to_control(scoped_context: SkyvernContext) -> None:
+ eligible_1 = _make_block(TaskBlock, label="t1")
+ eligible_2 = _make_block(NavigationBlock, label="t2", navigation_goal="Apply to the job")
+ totp_block = _make_block(TaskBlock, label="totp", totp_verification_url="https://example.com/otp")
+ blocks: list[BaseTaskBlock] = [eligible_1, eligible_2, totp_block]
+
+ assert run_is_eligible_for_v3_ab(blocks, is_script_run=False) is False
+
+ provider = _FakeExperimentationProvider({WORKFLOW_TASK_V3_AB_FLAG: True})
+ await _resolve(scoped_context, provider, workflow_run_id="wr_mixed", run_is_eligible=False)
+
+ for block in blocks:
+ assert block.resolve_engine("wr_mixed") == RunEngine.skyvern_v1
+ # An ineligible run never even asks the provider -- there is nothing to bucket.
+ assert provider.calls == []
+
+
+async def test_explicit_block_engine_is_never_overridden_by_treatment_arm(scoped_context: SkyvernContext) -> None:
+ provider = _FakeExperimentationProvider({WORKFLOW_TASK_V3_AB_FLAG: True})
+ await _resolve(scoped_context, provider, workflow_run_id="wr_pinned", run_is_eligible=True)
+ assert scoped_context.workflow_block_engine_override == RunEngine.skyvern_v3
+
+ cua_block = _make_block(TaskBlock, label="cua", engine=RunEngine.openai_cua)
+ v2_block = _make_block(TaskBlock, label="v2", engine=RunEngine.skyvern_v2)
+
+ assert cua_block.resolve_engine("wr_pinned") == RunEngine.openai_cua
+ assert v2_block.resolve_engine("wr_pinned") == RunEngine.skyvern_v2
+
+
+def test_pinned_non_default_engine_block_disqualifies_the_run() -> None:
+ eligible = _make_block(TaskBlock, label="ok")
+ # Pinned as-authored in both arms, but that leaves control mixed-engine, so it
+ # disqualifies the whole run rather than being skipped.
+ pinned = _make_block(
+ NavigationBlock, label="pinned", navigation_goal="Apply to the job", engine=RunEngine.openai_cua
+ )
+
+ assert run_is_eligible_for_v3_ab([eligible, pinned], is_script_run=False) is False
+
+
+async def test_all_eligible_run_resolves_every_block_to_treatment(scoped_context: SkyvernContext) -> None:
+ blocks: list[BaseTaskBlock] = [
+ _make_block(TaskBlock, label="t1"),
+ _make_block(NavigationBlock, label="t2", navigation_goal="Apply to the job"),
+ _make_block(ActionBlock, label="t3"),
+ ]
+ assert run_is_eligible_for_v3_ab(blocks, is_script_run=False) is True
+
+ provider = _FakeExperimentationProvider({WORKFLOW_TASK_V3_AB_FLAG: True})
+ await _resolve(scoped_context, provider, workflow_run_id="wr_treatment", run_is_eligible=True)
+
+ for block in blocks:
+ assert block.resolve_engine("wr_treatment") == RunEngine.skyvern_v3
+
+
+async def test_arm_resolved_once_per_run_survives_mid_run_flag_flip(scoped_context: SkyvernContext) -> None:
+ provider = _FakeExperimentationProvider({WORKFLOW_TASK_V3_AB_FLAG: True})
+ await _resolve(scoped_context, provider, workflow_run_id="wr_once", run_is_eligible=True)
+ assert scoped_context.workflow_block_engine_override == RunEngine.skyvern_v3
+
+ # Invalidate the provider's own 300s cache and flip the flag, so a second query would
+ # return False if it actually reached the provider. The idempotency guard must still
+ # short-circuit on context.workflow_block_engine_resolved_run_id before that happens.
+ provider.invalidate_resolution_caches()
+ provider.flags[WORKFLOW_TASK_V3_AB_FLAG] = False
+ await _resolve(scoped_context, provider, workflow_run_id="wr_once", run_is_eligible=True)
+
+ assert scoped_context.workflow_block_engine_override == RunEngine.skyvern_v3
+
+
+async def test_different_run_id_on_same_context_reresolves_instead_of_inheriting(
+ scoped_context: SkyvernContext,
+) -> None:
+ provider = _FakeExperimentationProvider({WORKFLOW_TASK_V3_AB_FLAG: True})
+ await _resolve(scoped_context, provider, workflow_run_id="wr_A", run_is_eligible=True)
+ assert workflow_block_engine_override("wr_A") == RunEngine.skyvern_v3
+
+ provider.flags[WORKFLOW_TASK_V3_AB_FLAG] = False
+ await _resolve(scoped_context, provider, workflow_run_id="wr_B", run_is_eligible=True)
+
+ assert workflow_block_engine_override("wr_B") is None
+ # The pin moved to B: A must not read as still-treatment via a stale resolution.
+ assert workflow_block_engine_override("wr_A") is None
+
+
+async def test_unresolved_run_id_reads_control_without_resolving(scoped_context: SkyvernContext) -> None:
+ provider = _FakeExperimentationProvider({WORKFLOW_TASK_V3_AB_FLAG: True})
+ await _resolve(scoped_context, provider, workflow_run_id="wr_A", run_is_eligible=True)
+ assert workflow_block_engine_override("wr_A") == RunEngine.skyvern_v3
+
+ # wr_B was never resolved (task_v2 / cached-script helper paths never call the resolver for
+ # their run), so the reader must not fall back to A's pin or to a bare "is anything pinned".
+ assert workflow_block_engine_override("wr_B") is None
+ assert all(distinct_id == "wr_A" for _, distinct_id, _ in provider.calls)
+
+
+async def test_resolver_matches_execute_step_flag_contract(scoped_context: SkyvernContext) -> None:
+ """Derives the expected DISABLE_TASK_V3 call from the real execute_step gate instead of a
+ hardcoded literal, so a drift in agent.py's distinct_id or properties reds this test.
+ """
+ gate_provider = _FakeExperimentationProvider()
+ await _run_execute_step_gate(
+ engine=RunEngine.skyvern_v3,
+ task_block=_make_block(TaskBlock, label="contract"),
+ experimentation_provider=gate_provider,
+ workflow_run_id="wr_contract",
+ )
+ gate_disable_calls = [call for call in gate_provider.calls if call[0] == DISABLE_TASK_V3_FLAG]
+ assert len(gate_disable_calls) == 1
+ gate_call = gate_disable_calls[0]
+ assert gate_call[1] == "wr_contract"
+ # Pinned separately from the equality below: both callers now build this dict in one shared
+ # place, so dropping it would keep them agreeing with each other while silently losing the
+ # organization targeting the flag's release conditions are written against.
+ assert gate_call[2] == {"organization_id": make_organization(datetime.now(UTC)).organization_id}
+
+ resolver_provider = _FakeExperimentationProvider({WORKFLOW_TASK_V3_AB_FLAG: True})
+ await _resolve(
+ scoped_context,
+ resolver_provider,
+ workflow_run_id="wr_contract",
+ run_is_eligible=True,
+ organization_id=(gate_call[2] or {}).get("organization_id"),
+ workflow_permanent_id="wpid_contract",
+ )
+ resolver_disable_calls = [call for call in resolver_provider.calls if call[0] == DISABLE_TASK_V3_FLAG]
+ assert len(resolver_disable_calls) == 1
+ assert resolver_disable_calls[0] == gate_call
+
+ assert any(
+ call[0] == WORKFLOW_TASK_V3_AB_FLAG and (call[2] or {}).get("workflow_permanent_id") == "wpid_contract"
+ for call in resolver_provider.calls
+ )
+
+
+async def test_disable_flag_wins_over_ab_flag(scoped_context: SkyvernContext) -> None:
+ provider = _FakeExperimentationProvider({WORKFLOW_TASK_V3_AB_FLAG: True, DISABLE_TASK_V3_FLAG: True})
+ await _resolve(scoped_context, provider, workflow_run_id="wr_disabled", run_is_eligible=True)
+
+ assert scoped_context.workflow_block_engine_override is None
+ block = _make_block(TaskBlock, label="disabled_block")
+ assert block.resolve_engine("wr_disabled") == RunEngine.skyvern_v1
+
+
+async def test_provider_exception_fails_closed_to_control(scoped_context: SkyvernContext) -> None:
+ provider = _FakeExperimentationProvider(raise_error=True)
+ await _resolve(scoped_context, provider, workflow_run_id="wr_err", run_is_eligible=True)
+
+ assert scoped_context.workflow_block_engine_override is None
+ block = _make_block(TaskBlock, label="err_block")
+ assert block.resolve_engine("wr_err") == RunEngine.skyvern_v1
+
+
+def test_script_run_is_never_eligible() -> None:
+ blocks: list[BaseTaskBlock] = [
+ _make_block(TaskBlock, label="t1"),
+ _make_block(NavigationBlock, label="t2", navigation_goal="Apply to the job"),
+ ]
+ assert run_is_eligible_for_v3_ab(blocks, is_script_run=True) is False
+
+
+async def test_noop_provider_never_queried_and_leaves_engine_unchanged(scoped_context: SkyvernContext) -> None:
+ provider = NoOpExperimentationProvider()
+ spy = AsyncMock(wraps=provider._is_feature_enabled)
+ with patch(WORKFLOW_BLOCK_ENGINE_APP_TARGET) as mock_app, patch.object(provider, "_is_feature_enabled", spy):
+ mock_app.EXPERIMENTATION_PROVIDER = provider
+ await resolve_workflow_block_engine_arm(
+ scoped_context,
+ workflow_run_id="wr_noop",
+ organization_id="org_1",
+ workflow_permanent_id="wpid_1",
+ run_is_eligible=True,
+ )
+
+ spy.assert_not_called()
+ assert scoped_context.workflow_block_engine_override is None
+ block = _make_block(TaskBlock, label="noop_block")
+ assert block.resolve_engine("wr_noop") == RunEngine.skyvern_v1
+
+
+def test_non_task_blocks_ignored_but_nested_loop_task_blocks_considered() -> None:
+ code_block = CodeBlock(label="code", output_parameter=_make_output_parameter("code"), code="pass")
+ eligible = _make_block(TaskBlock, label="ok")
+
+ flat_without_loop = get_all_blocks([code_block, eligible])
+ assert run_is_eligible_for_v3_ab(flat_without_loop, is_script_run=False) is True
+
+ ineligible_nested = _make_block(ActionBlock, label="nested_dl", complete_on_download=True)
+ loop = ForLoopBlock(
+ label="loop",
+ output_parameter=_make_output_parameter("loop"),
+ loop_blocks=[ineligible_nested],
+ )
+
+ flat_with_loop = get_all_blocks([code_block, eligible, loop])
+ assert ineligible_nested in flat_with_loop
+ assert run_is_eligible_for_v3_ab(flat_with_loop, is_script_run=False) is False
+
+
+def test_inert_blocks_do_not_disqualify_an_otherwise_eligible_run() -> None:
+ # Nearly every workflow starts with a Go-to-URL block; treating it (or a trailing
+ # HumanInteractionBlock) as a disqualifier would kill nearly all experiment traffic.
+ url_block = _make_block(UrlBlock, label="goto", url="https://example.com")
+ human_block = _make_block(HumanInteractionBlock, label="human")
+ eligible = _make_block(TaskBlock, label="ok")
+
+ assert run_is_eligible_for_v3_ab([url_block, human_block, eligible], is_script_run=False) is True
+
+
+def test_run_with_only_inert_or_non_task_blocks_is_not_eligible() -> None:
+ code_block = CodeBlock(label="code", output_parameter=_make_output_parameter("code"), code="pass")
+ url_block = _make_block(UrlBlock, label="goto", url="https://example.com")
+ human_block = _make_block(HumanInteractionBlock, label="human")
+
+ assert run_is_eligible_for_v3_ab([code_block, url_block, human_block], is_script_run=False) is False
+
+
+async def test_inert_blocks_resolve_to_v1_in_a_treated_run(scoped_context: SkyvernContext) -> None:
+ # Eligibility skips GOTO_URL/HumanInteraction as engine-inert, so resolve_engine must skip
+ # them too -- otherwise their workflow_run_blocks rows claim an engine that never ran.
+ provider = _FakeExperimentationProvider({WORKFLOW_TASK_V3_AB_FLAG: True})
+ await _resolve(scoped_context, provider, workflow_run_id="wr_inert", run_is_eligible=True)
+ assert scoped_context.workflow_block_engine_override == RunEngine.skyvern_v3
+
+ url_block = _make_block(UrlBlock, label="goto", url="https://example.com")
+ human_block = _make_block(HumanInteractionBlock, label="human")
+
+ assert url_block.resolve_engine("wr_inert") == RunEngine.skyvern_v1
+ assert human_block.resolve_engine("wr_inert") == RunEngine.skyvern_v1
+
+
+async def test_exclude_from_engine_ab_block_is_never_rerouted(scoped_context: SkyvernContext) -> None:
+ provider = _FakeExperimentationProvider({WORKFLOW_TASK_V3_AB_FLAG: True})
+ await _resolve(scoped_context, provider, workflow_run_id="wr_excluded", run_is_eligible=True)
+ assert scoped_context.workflow_block_engine_override == RunEngine.skyvern_v3
+
+ excluded_block = _make_block(ActionBlock, label="excluded")
+ excluded_block._exclude_from_engine_ab = True
+ assert excluded_block.resolve_engine("wr_excluded") == RunEngine.skyvern_v1
+
+
+async def test_execute_safe_persists_the_resolved_engine(scoped_context: SkyvernContext) -> None:
+ scoped_context.workflow_block_engine_resolved_run_id = "wr_persist"
+ scoped_context.workflow_block_engine_override = RunEngine.skyvern_v3
+ block = _make_block(TaskBlock, label="persist_block")
+
+ with (
+ patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app,
+ patch.object(BaseTaskBlock, "execute", new_callable=AsyncMock, return_value=_block_result()),
+ patch.object(Block, "_generate_workflow_run_block_description", new_callable=AsyncMock),
+ ):
+ _setup_mocks(mock_app)
+
+ await block.execute_safe(workflow_run_id="wr_persist")
+
+ persisted_engine = mock_app.DATABASE.observer.create_workflow_run_block.await_args.kwargs["engine"]
+ assert persisted_engine == RunEngine.skyvern_v3
+
+
+class _EngineCaptured(BaseException):
+ """Raised from the create_workflow_run_block mock once the dispatched engine is captured.
+
+ Subclasses BaseException, not Exception, so it escapes the `except Exception` handlers in
+ Block.execute_safe, WorkflowService._execute_block_via_agent_if_allowed, and
+ WorkflowService._execute_single_block instead of being swallowed into a failed BlockResult.
+ """
+
+
+async def test_base_task_block_execute_dispatches_with_the_resolved_engine(scoped_context: SkyvernContext) -> None:
+ """Drives the real BaseTaskBlock.execute (not a mock of it) up to the app.agent.execute_step
+ call. A revert of engine=self.resolve_engine(...) back to engine=self.engine only shows up
+ here -- the persist-side test mocks BaseTaskBlock.execute out entirely.
+ """
+ scoped_context.workflow_block_engine_resolved_run_id = "wr_missing_starter_url_test"
+ scoped_context.workflow_block_engine_override = RunEngine.skyvern_v3
+ block = _make_block(TaskBlock, label="dispatch_block")
+
+ captured: dict[str, Any] = {}
+
+ async def _capture_engine_and_abort(**kwargs: Any) -> Any:
+ captured["engine"] = kwargs.get("engine")
+ raise _EngineCaptured()
+
+ with _mock_block_execute_deps(working_page_url="https://example.com/dashboard") as deps:
+ deps["agent"].execute_step = AsyncMock(side_effect=_capture_engine_and_abort)
+
+ with pytest.raises(_EngineCaptured):
+ await block.execute(
+ workflow_run_id="wr_missing_starter_url_test",
+ workflow_run_block_id="wrb_test",
+ organization_id="o_test",
+ )
+
+ assert captured["engine"] == RunEngine.skyvern_v3
+
+
+async def test_execute_workflow_blocks_pins_the_context_execute_safe_reads_from(
+ scoped_context: SkyvernContext,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Drives the real WorkflowService._execute_workflow_blocks -> _execute_single_block ->
+ Block.execute_safe chain for a single eligible TaskBlock, forcing only the experimentation
+ provider. If resolve_workflow_block_engine_arm pinned the arm on a different SkyvernContext
+ object than the one execute_safe's resolve_engine() reads back from, this fails: the
+ persisted engine would be skyvern_v1 instead of skyvern_v3.
+ """
+ provider = _FakeExperimentationProvider({WORKFLOW_TASK_V3_AB_FLAG: True})
+ monkeypatch.setattr(app, "EXPERIMENTATION_PROVIDER", provider)
+
+ block = _make_block(TaskBlock, label="e2e_block")
+ workflow = MagicMock()
+ workflow.workflow_definition.blocks = [block]
+ workflow.workflow_definition.version = 1
+ workflow.workflow_definition.finally_block_label = None
+
+ workflow_run = MagicMock()
+ workflow_run.workflow_run_id = "wr_e2e"
+ workflow_run.workflow_permanent_id = "wpid_e2e"
+ workflow_run.organization_id = "org_e2e"
+ workflow_run.run_with = None
+ workflow_run.retried_from_workflow_run_id = None
+
+ organization = MagicMock()
+ organization.organization_id = "org_e2e"
+
+ # update_workflow_run_if_not_final's return value feeds datetime arithmetic in
+ # mark_workflow_run_as_running; it needs real datetimes, not MagicMock, to avoid an
+ # unrelated crash before execution ever reaches the resolver.
+ now = datetime.now(UTC)
+ running_run = MagicMock(organization_id="org_e2e", started_at=now, created_at=now, finished_at=None)
+ monkeypatch.setattr(app.DATABASE.workflow_runs, "get_workflow_run", AsyncMock(return_value=None))
+ monkeypatch.setattr(
+ app.DATABASE.workflow_runs, "update_workflow_run_if_not_final", AsyncMock(return_value=running_run)
+ )
+ monkeypatch.setattr(app.WORKFLOW_CONTEXT_MANAGER, "get_workflow_run_context", MagicMock(return_value=MagicMock()))
+ monkeypatch.setattr(app.WORKFLOW_CONTEXT_MANAGER, "register_block_parameters_for_workflow_run", AsyncMock())
+
+ captured: dict[str, Any] = {}
+
+ async def _capture_engine_and_abort(**kwargs: Any) -> Any:
+ captured["engine"] = kwargs.get("engine")
+ raise _EngineCaptured()
+
+ monkeypatch.setattr(
+ app.DATABASE.observer, "create_workflow_run_block", AsyncMock(side_effect=_capture_engine_and_abort)
+ )
+
+ service = WorkflowService()
+ monkeypatch.setattr(service, "should_run_script", AsyncMock(return_value=False))
+
+ with pytest.raises(_EngineCaptured):
+ await service._execute_workflow_blocks(
+ workflow=workflow,
+ workflow_run=workflow_run,
+ organization=organization,
+ )
+
+ assert captured["engine"] == RunEngine.skyvern_v3
diff --git a/tests/unit/test_workflow_copilot_route.py b/tests/unit/test_workflow_copilot_route.py
index 850be425a..3dad15e55 100644
--- a/tests/unit/test_workflow_copilot_route.py
+++ b/tests/unit/test_workflow_copilot_route.py
@@ -3766,7 +3766,7 @@ async def test_finalise_normal_turn_persists_deadline_cause_and_keeps_timeout_co
auto_accept=False,
)
original_workflow = SimpleNamespace(workflow_id="wf-canonical")
- timeout_copy = "I ran out of time processing your request. Here's what I have so far."
+ timeout_copy = agent_module._TIMEOUT_REPLY_DEFAULT
envelope = assemble_terminal_envelope(
response_type="REPLY",
verified=False,
diff --git a/tests/unit/test_workflow_copilot_route_helpers.py b/tests/unit/test_workflow_copilot_route_helpers.py
index 1093d7392..45e95c51c 100644
--- a/tests/unit/test_workflow_copilot_route_helpers.py
+++ b/tests/unit/test_workflow_copilot_route_helpers.py
@@ -19,6 +19,7 @@ from unittest.mock import MagicMock
import pytest
from pydantic import ValidationError
+from skyvern.forge.sdk.copilot.agent import _build_timeout_exit_result
from skyvern.forge.sdk.copilot.context import AgentResult
from skyvern.forge.sdk.copilot.workflow_credential_utils import workflow_credential_ids
from skyvern.forge.sdk.routes.workflow_copilot import (
@@ -648,3 +649,45 @@ def test_run_grant_yaml_ignores_a_binding_that_exists_only_on_the_submitted_canv
def test_run_grant_yaml_is_none_when_the_row_has_no_blocks() -> None:
assert _run_grant_workflow_yaml(None) is None
+
+
+def _timed_out_ctx(*, workflow_yaml: str | None, last_test_ok: bool | None) -> MagicMock:
+ ctx = MagicMock()
+ ctx.last_workflow = MagicMock(name="wf")
+ ctx.last_workflow_yaml = workflow_yaml
+ ctx.last_test_ok = last_test_ok
+ ctx.last_full_workflow_test_ok = False
+ ctx.last_test_suspicious_success = False
+ ctx.copilot_total_timeout_exceeded = True
+ ctx.last_failure_category_top = None
+ ctx.workflow_persisted = False
+ ctx.total_tokens_used = None
+ ctx.last_good_workflow = None
+ ctx.last_good_workflow_yaml = None
+ ctx.tool_activity = []
+ ctx.latest_diagnosis_repair_contract = None
+ ctx.test_after_update_done = last_test_ok is not None
+ ctx.last_update_block_count = None
+ ctx.has_staged_proposal = True
+ return ctx
+
+
+class TestTimedOutFailedTestDraftIsNotAutoApplied:
+ def test_timeout_failed_test_result_offers_review_instead_of_committing(self) -> None:
+ ctx = _timed_out_ctx(workflow_yaml="version: '1.0'", last_test_ok=False)
+
+ result = _build_timeout_exit_result(ctx, global_llm_context=None)
+
+ assert result.updated_workflow is ctx.last_workflow
+ assert result.proposal_disposition == "review_untested"
+ assert _effective_auto_accept(True, result) is False
+ assert _should_commit_staged_workflow(True, result) is False
+
+ def test_empty_timeout_result_does_not_commit_a_staged_workflow(self) -> None:
+ ctx = _timed_out_ctx(workflow_yaml=None, last_test_ok=None)
+
+ result = _build_timeout_exit_result(ctx, global_llm_context=None)
+
+ assert result.updated_workflow is None
+ assert result.proposal_disposition == "no_proposal"
+ assert _should_commit_staged_workflow(True, result) is False
diff --git a/tests/unit/test_workflow_runtime_completion.py b/tests/unit/test_workflow_runtime_completion.py
index 2a2c0d8bf..dab8b6344 100644
--- a/tests/unit/test_workflow_runtime_completion.py
+++ b/tests/unit/test_workflow_runtime_completion.py
@@ -11,6 +11,7 @@ from unittest.mock import AsyncMock
import pytest
+from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.workflow import service as service_module
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
from skyvern.forge.sdk.workflow.runtime_completion import (
@@ -403,9 +404,10 @@ def test_no_stored_contract_leaves_the_definition_untouched() -> None:
async def test_finalize_counts_session_scoped_downloads_not_yet_claimed(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """Session downloads are tagged with the run id during cleanup, after this grade runs."""
+ """The watcher tags a session download with its producing run when it observes the file, so a
+ row can already exist for this run before any claim reaches it."""
service, run, statuses = _wire_finalize(monkeypatch, contract=_DERIVED_CONTRACT, downloaded=[])
- monkeypatch.setattr(service, "_session_download_count", AsyncMock(return_value=1))
+ monkeypatch.setattr(service, "_session_download_artifact_ids", AsyncMock(return_value={"a_1"}))
await service._finalize_workflow_run_status(
workflow_run_id=run.workflow_run_id,
@@ -417,6 +419,56 @@ async def test_finalize_counts_session_scoped_downloads_not_yet_claimed(
assert statuses == [WorkflowRunStatus.completed]
+async def test_an_id_less_registered_file_and_a_session_row_are_counted_separately(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Without HMAC signing the run read lists the run's own storage prefix, which cannot contain a
+ browser-session download, so the two reads report different files and both count."""
+ contract = {
+ "schema_version": 1,
+ "criteria": [{"id": "declared_download", "kind": "registered_download", "min_count": 2}],
+ }
+ service, run, statuses = _wire_finalize(
+ monkeypatch, contract=contract, downloaded=[FileInfo(url="s3://b/one.pdf", artifact_id=None)]
+ )
+ monkeypatch.setattr(service, "_session_download_artifact_ids", AsyncMock(return_value={"a_1"}))
+
+ await service._finalize_workflow_run_status(
+ workflow_run_id=run.workflow_run_id,
+ workflow_run=run,
+ pre_finally_status=WorkflowRunStatus.running,
+ pre_finally_failure_reason=None,
+ )
+
+ assert statuses == [WorkflowRunStatus.completed]
+
+
+async def test_one_file_reported_by_both_download_sources_does_not_satisfy_a_two_file_contract(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The session read and the run read overlap on the same run key, so a single stamped download
+ appears in both. Counting it twice would pass a contract the run never met."""
+ contract = {
+ "schema_version": 1,
+ "criteria": [{"id": "declared_download", "kind": "registered_download", "min_count": 2}],
+ }
+ service, run, statuses = _wire_finalize(
+ monkeypatch, contract=contract, downloaded=[FileInfo(url="s3://b/one.pdf", artifact_id="a_1")]
+ )
+ monkeypatch.setattr(service, "_session_download_artifact_ids", AsyncMock(return_value={"a_1"}))
+
+ await service._finalize_workflow_run_status(
+ workflow_run_id=run.workflow_run_id,
+ workflow_run=run,
+ pre_finally_status=WorkflowRunStatus.running,
+ pre_finally_failure_reason=None,
+ )
+
+ assert statuses == [WorkflowRunStatus.terminated]
+
+
def test_interactive_copilot_routes_do_not_own_completion_contract_lifecycle() -> None:
from skyvern.forge.sdk.routes import workflow_copilot as route
diff --git a/tests/unit/test_workflow_webhook_delivery.py b/tests/unit/test_workflow_webhook_delivery.py
index 11911ea3b..e08cd3253 100644
--- a/tests/unit/test_workflow_webhook_delivery.py
+++ b/tests/unit/test_workflow_webhook_delivery.py
@@ -1,18 +1,23 @@
from __future__ import annotations
+import hashlib
+import hmac
+import json
from datetime import datetime, timezone
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import httpx
import pytest
+from structlog.testing import capture_logs
+from skyvern.forge.sdk.core.security import generate_skyvern_webhook_signature
from skyvern.forge.sdk.workflow import service as service_module
from skyvern.forge.sdk.workflow.service import WorkflowService
class _StatusResponse:
- def __init__(self) -> None:
+ def __init__(self, extra_payload: dict | None = None) -> None:
now = datetime.now(timezone.utc)
self.status = "completed"
self.outputs: dict = {}
@@ -25,6 +30,7 @@ class _StatusResponse:
self.parameters: dict = {}
self.errors: list = []
self.total_steps = 1
+ self.extra_payload = extra_payload or {}
self.created_at = now
self.modified_at = now
self.queued_at = now
@@ -32,7 +38,7 @@ class _StatusResponse:
self.finished_at = now
def model_dump_json(self) -> str:
- return '{"workflow_run_id":"wr_abc","status":"completed"}'
+ return json.dumps({"workflow_run_id": "wr_abc", "status": "completed", **self.extra_payload})
class _WebhookRunResponse:
@@ -72,7 +78,6 @@ def webhook_service(monkeypatch: pytest.MonkeyPatch) -> tuple[WorkflowService, A
service_module,
"generate_skyvern_webhook_signature",
lambda payload, api_key: SimpleNamespace(
- payload_for_log='{"safe":true}',
headers={"x-skyvern-signature": "sig"},
signed_payload='{"signed":true}',
),
@@ -107,6 +112,65 @@ async def test_prepare_workflow_webhook_builds_request_without_delivery(
deliver.assert_not_awaited()
+async def test_execute_workflow_webhook_logs_named_fields_without_the_payload_object(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, build_response, _update_run = webhook_service
+ synthetic_credential = "synthetic-webhook-credential"
+ build_response.return_value = _StatusResponse({"output": {"destinations": [{"signing_key": synthetic_credential}]}})
+ monkeypatch.setattr(service_module, "generate_skyvern_webhook_signature", generate_skyvern_webhook_signature)
+ deliver = AsyncMock(return_value=_response(200, "ok"))
+ monkeypatch.setattr(service_module, "deliver_webhook_with_retries", deliver)
+
+ with capture_logs() as logs:
+ await svc.execute_workflow_webhook(_workflow_run())
+
+ webhook_events = [
+ event
+ for event in logs
+ if event["event"]
+ in {
+ "Prepared webhook run status for webhook callback url",
+ "Sending webhook run status to webhook callback url",
+ }
+ ]
+ assert len(webhook_events) == 2
+ assert all("payload" not in event for event in webhook_events)
+ assert all(event["workflow_run_id"] == "wr_abc" for event in webhook_events)
+ assert all(event["webhook_callback_url"] == "https://example.com/hook" for event in webhook_events)
+ assert synthetic_credential not in json.dumps(logs)
+ dispatched_payload = deliver.await_args.kwargs["payload"]
+ assert synthetic_credential in dispatched_payload
+ expected_signature = hmac.new(b"api-key", dispatched_payload.encode("utf-8"), hashlib.sha256).hexdigest()
+ assert deliver.await_args.kwargs["headers"]["x-skyvern-signature"] == expected_signature
+
+
+async def test_failed_webhook_logs_no_payload_copy(
+ webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ svc, build_response, _update_run = webhook_service
+ synthetic_credential = "synthetic-webhook-credential"
+ build_response.return_value = _StatusResponse({"output": {"destinations": [{"signing_key": synthetic_credential}]}})
+ monkeypatch.setattr(service_module, "generate_skyvern_webhook_signature", generate_skyvern_webhook_signature)
+ deliver = AsyncMock(return_value=_response(400, "bad request"))
+ monkeypatch.setattr(service_module, "deliver_webhook_with_retries", deliver)
+
+ with capture_logs() as logs:
+ await svc.execute_workflow_webhook(_workflow_run())
+
+ failures = [event for event in logs if event["event"] == "Webhook failed"]
+ assert len(failures) == 1
+ assert failures[0]["resp_code"] == 400
+ assert "webhook_data" not in failures[0]
+ # No default=str: serializability doubles as the guard against logging raw response objects.
+ assert synthetic_credential not in json.dumps(logs)
+ assert synthetic_credential in deliver.await_args.kwargs["payload"]
+
+
@pytest.mark.asyncio
async def test_execute_workflow_webhook_records_customer_failure_without_raising(
webhook_service: tuple[WorkflowService, AsyncMock, AsyncMock],