Skip to content

Automate browser based workflows with AI

Document an email-forwarding path for email-based 2FA (#9002)

Aaron Perez7927d1b99e8a
diff --git a/docs/credentials.mdx b/docs/credentials.mdx
index bd9366eba..72e8bfda3 100644
--- a/docs/credentials.mdx
+++ b/docs/credentials.mdx
@@ -245,7 +245,7 @@ Set 2FA up on the password credential itself: expand **Two-Factor Authentication
| Method | How Skyvern gets the code |
|---|---|
| **Authenticator App** | Generates it from the stored key. No waiting, no setup outside Skyvern. Use this whenever the site offers it. |
-| **Email** | Reads it from a [connected inbox](#connect-an-inbox), or waits for you to [push it](#push-a-code). |
+| **Email** | Reads it from a [connected inbox](#connect-an-inbox), or waits for a code you [forward](#forward-codes-automatically) or [push](#push-a-code). |
| **Text Message** | Waits for you to [push it](#push-a-code). |
| **Passkey** | Enterprise plan. |
@@ -296,6 +296,13 @@ When a run reaches the code prompt, Skyvern waits for a code sent to that identi
On the **2FA** or **Magic Links** tab, click **Connect an inbox**. It opens [Integrations](/cloud/integrations), where you connect Gmail or Outlook. Skyvern then finds verification codes and magic links in that inbox on its own, with no forwarding.
+Two things have to line up:
+
+- The account's row on Integrations shows **Read inbox**. An account connected for sending only is skipped.
+- The credential's **TOTP Identifier (Username or Email)** is that inbox's address.
+
+Skyvern reads only mail that arrives after the run starts waiting, so a code sent earlier is ignored. When you can't connect the inbox — a Workspace admin blocks third-party apps, or the connection doesn't go through — [forward the codes](#forward-codes-automatically) instead. Forwarding works for any number of inboxes and needs no connection.
+
### Push a code
Without a connected inbox, deliver email and SMS codes yourself.
@@ -316,7 +323,7 @@ Without a connected inbox, deliver email and SMS codes yourself.
<img src="/images/cloud/credentials-2fa-push-form.png" alt="2FA tab with the Automatic 2FA from your inbox card and the Push a 2FA Code form" />
</Tab>
<Tab title="With code">
- Forward the email or SMS to a script (a Gmail filter to a webhook, a Twilio function) that posts it to Skyvern. Send the whole message body; Skyvern extracts the code.
+ Post the code to Skyvern yourself, or have a [relay](#forward-codes-automatically) do it. Send the whole message body; Skyvern extracts the code.
<CodeGroup>
```python Python
@@ -349,11 +356,92 @@ Without a connected inbox, deliver email and SMS codes yourself.
- `source` is a free-text label for your own tracking.
- Add `workflow_run_id`, `workflow_id` or `task_id` to target one run.
- - Set `type` to `magic_link` to push a sign-in link.
+ - A sign-in link needs no extra field. Skyvern detects a magic link from the content; the `type` field is deprecated and ignored.
- List received codes with `GET /v1/credentials/totp`. Filter with `totp_identifier`, `workflow_run_id` and `otp_type` (`totp` or `magic_link`); `limit` defaults to 50, maximum 200.
</Tab>
</Tabs>
+### Forward codes automatically
+
+A relay takes the person out of the loop: the inbox forwards the code email to a service that posts it to `POST /v1/credentials/totp`. Every inbox can forward to the same relay, so this scales to as many accounts as you have.
+
+<Steps>
+ <Step title="Build the relay">
+ Use anything that receives mail and makes an HTTP request: [Zapier](/cloud/integrations#zapier), Make, n8n, a mail-handling Lambda, or the Apps Script below.
+
+ In Zapier, an inbound email trigger needs a paid plan:
+
+ 1. Trigger: **Email by Zapier** → **New Inbound Email**. Zapier gives you an address such as `[email protected]`. Keep that address: it is the relay address below.
+ 2. Action: **Webhooks by Zapier** → **POST**.
+ - **URL**: `https://api.skyvern.com/v1/credentials/totp`
+ - **Payload Type**: `json`
+ - **Data**: `totp_identifier` → **To Email**, `content` → **Body Plain**, `source` → `email`
+ - **Headers**: `x-api-key` → your Skyvern API key
+ 3. Publish the Zap.
+
+ `totp_identifier` has to come out as the address that received the code, not the relay address. The last step checks it.
+ </Step>
+ <Step title="Forward the code mail from each inbox">
+ In Gmail, open **Settings → Forwarding and POP/IMAP → Add a forwarding address**, enter the relay address and confirm the verification mail Gmail sends to it. In Zapier, that mail shows up in the trigger's test data.
+
+ Then open **Settings → Filters and Blocked Addresses → Create a new filter**. Match the mail that carries codes, by the sender address of the site or by a subject such as `verification code`. Click **Create filter**, check **Forward it to** and pick the relay address.
+
+ Repeat for each inbox. They can all forward to the same relay address.
+ </Step>
+ <Step title="Point the credential at the inbox">
+ On the password credential, set **Two-Factor Authentication** to **Email** and put that inbox's address in **TOTP Identifier (Username or Email)**.
+
+ Matching an email identifier ignores case and nothing else. `[email protected]` and `[email protected]` are two different identifiers.
+ </Step>
+ <Step title="Test it end to end">
+ Forward an old code email to the relay address by hand, then read back what Skyvern stored:
+
+ ```bash
+ curl -G "https://api.skyvern.com/v1/credentials/totp" \
+ -H "x-api-key: $SKYVERN_API_KEY" \
+ --data-urlencode "[email protected]"
+ ```
+
+ The newest entry's `totp_identifier` is the inbox address and `code` is the code from the mail. If the identifier came out as the relay address or carries a display name, map `totp_identifier` from a different field of the trigger, or give that inbox its own relay address and set `totp_identifier` to a fixed value in its Zap.
+ </Step>
+</Steps>
+
+<Accordion title="Forward from Gmail with Google Apps Script">
+No second service, and the identifier can't come out wrong, because the script runs inside the inbox. Set it up once per inbox.
+
+1. In Gmail, create a filter for the code mail with **Apply the label** → a new label `skyvern-2fa`.
+2. Open [script.google.com](https://script.google.com), create a project and paste:
+
+ ```javascript
+ const LABEL = 'skyvern-2fa';
+
+ function forwardCodes() {
+ const apiKey = PropertiesService.getScriptProperties().getProperty('SKYVERN_API_KEY');
+ const label = GmailApp.getUserLabelByName(LABEL);
+ const identifier = Session.getEffectiveUser().getEmail();
+ label.getThreads(0, 10).forEach((thread) => {
+ const message = thread.getMessages().pop();
+ UrlFetchApp.fetch('https://api.skyvern.com/v1/credentials/totp', {
+ method: 'post',
+ contentType: 'application/json',
+ headers: { 'x-api-key': apiKey },
+ payload: JSON.stringify({
+ totp_identifier: identifier,
+ content: message.getPlainBody(),
+ source: 'gmail-apps-script',
+ }),
+ });
+ thread.removeLabel(label);
+ });
+ }
+ ```
+
+3. In **Project Settings → Script properties**, add `SKYVERN_API_KEY` with your API key.
+4. In **Triggers**, add a trigger for `forwardCodes`, **Time-driven** → **Minutes timer** → **Every minute**, and approve the Gmail and external-request permissions.
+
+A code waits up to a minute for the next trigger. Runs wait 15 minutes for a code, so that leaves room, but push a code by hand if the site expires its codes faster.
+</Accordion>
+
### Let Skyvern fetch codes from your endpoint
If codes land in a system you control, give Skyvern a URL to ask instead. Skyvern sends a `POST` with `task_id`, plus `workflow_run_id` and `workflow_permanent_id` for agent runs, signed with the `x-skyvern-signature` header (see [Going to production](/developers/production) to verify it).
@@ -373,7 +461,7 @@ Where to set the URL:
### Magic links
-Some sites email a one-time sign-in link instead of a code. With a [connected inbox](#connect-an-inbox), Skyvern finds and opens the link. Otherwise paste the message into **Push a Magic Link** on the **Magic Links** tab, or push it with `send_totp_code`. Skyvern attaches the link to the waiting run and opens it.
+Some sites email a one-time sign-in link instead of a code. With a [connected inbox](#connect-an-inbox), Skyvern finds and opens the link. Otherwise paste the message into **Push a Magic Link** on the **Magic Links** tab, or push it with `send_totp_code`. A [relay](#forward-codes-automatically) handles magic links too: post the whole message and Skyvern detects the link. Skyvern attaches the link to the waiting run and opens it.
### Passkey
@@ -392,6 +480,8 @@ Some sites email a one-time sign-in link instead of a code. With a [connected in
| Run ends on the login page and nothing was typed | The Login block's **Credential** field or the credential input is set, and the credential still exists. For a vault source, the vault tile on Integrations is connected and the item IDs are right. |
| "Invalid username or password" | Sign in by hand with the same values. Some sites want the email, not a username. Re-enter the password to rule out a trailing space. |
| Run times out waiting for a code (`OTP_TIMEOUT`) | The identifier on the credential or run matches the one you push to, character for character. Check the code list on the **2FA** tab or `GET /v1/credentials/totp`. For an endpoint, read the failure reason for the status codes it returned. |
+| A connected inbox never produces a code | The account's row on [Integrations](/cloud/integrations) shows **Read inbox**, the credential's identifier is that inbox's address, and the code mail arrives after the run starts waiting. If the inbox can't be connected, [forward the codes](#forward-codes-automatically). |
+| Your relay gets an error from `POST /v1/credentials/totp` | 502 means code extraction is briefly unavailable, so have the relay retry. 400 and 402 come from very large bodies: post the plain-text part of the mail, not the full HTML. |
| "Code expired" or the code is rejected | Push codes as soon as they arrive. On self-hosted servers, keep the clock in sync (NTP). Retry the run. |
| **Save browser session for future logins** fails | The **Login Page URL** opens the sign-in form. Add **Login instructions (optional)** for unusual flows such as SSO. Inline testing is not available for every 2FA method. |
| Extra captchas or "new device" prompts | Turn on **Use a consistent IP address**, or reuse a signed-in [browser profile](/browsers#browser-profiles). |
diff --git a/skyvern/errors/errors.py b/skyvern/errors/errors.py
index f9629128f..bd26c17b5 100644
--- a/skyvern/errors/errors.py
+++ b/skyvern/errors/errors.py
@@ -1,5 +1,6 @@
+from collections.abc import Sequence
from enum import StrEnum
-from typing import Literal
+from typing import Any, Literal
from pydantic import BaseModel, Field, PrivateAttr, field_validator
@@ -78,6 +79,23 @@ def resolve_error_code_mapping_key(code: object, error_code_mapping: dict[str, s
return matches[0] if len(matches) == 1 else None
+BROWSER_DOWNLOAD_PARTIAL_FAILURE_CODE = "BROWSER_DOWNLOAD_PARTIAL_FAILURE"
+
+
+def drop_unsolicited_download_errors(
+ errors: list[dict[str, Any]],
+ *,
+ downloaded_files: Sequence[object] | None,
+) -> list[dict[str, Any]]:
+ """Keep the unsolicited-download failure only when a file lookup confirms that none landed.
+
+ ``None`` means the caller never fetched the files, so it cannot support the failure's no-file claim.
+ """
+ if downloaded_files is not None and not downloaded_files:
+ return errors
+ return [error for error in errors if error.get("error_code") != BROWSER_DOWNLOAD_PARTIAL_FAILURE_CODE]
+
+
class SkyvernDefinedError(BaseModel):
error_code: str
reasoning: str
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 171107faa..0d3bd220e 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -3260,6 +3260,10 @@ class ForgeAgent:
outcome = await run_task_v3_agent_loop(
page_provider=_page_provider,
+ # Read through browser_state each time: a recovered browser brings a new context.
+ intercepted_submissions=lambda: app.AGENT_FUNCTION.task_v3_intercepted_submissions(
+ browser_state.browser_context
+ ),
resolve_typed_text=resolve_typed_text,
credential_release_guard=release_guard,
resolve_totp_placeholder=verification_state.resolve_totp_placeholder,
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index 98f30f0c6..fa0d51254 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -116,6 +116,7 @@ if TYPE_CHECKING:
from skyvern.forge.sdk.workflow.models.tags import CallerType
from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowRun, WorkflowRunStatus
from skyvern.forge.taskv3.answer_basis_audit import AnswerBasisAudit
+ from skyvern.forge.taskv3.intercepted_submission import InterceptedSubmission
from skyvern.forge.taskv3.loop import ToolSpec
from skyvern.forge.taskv3.tools import PageProvider
from skyvern.schemas.workflows import WorkflowStatus
@@ -1186,6 +1187,11 @@ class AgentFunction:
def task_v3_application_defaults(self, parameters: dict[str, Any] | None) -> tuple[str | None, str] | None:
return None
+ # The submissions a page-level interceptor in this process held for the browser context, oldest first. Must stay a
+ # local read with no page or CDP call: the finish tool reads it on every non-completed verdict. OSS has none.
+ def task_v3_intercepted_submissions(self, browser_context: Any) -> tuple[InterceptedSubmission, ...]:
+ return ()
+
# An audit of the answers a run entered, consulted before the form moves on, or None (OSS: none).
def task_v3_answer_basis_audit(
self, parameters: dict[str, Any] | None, *, goal: str, organization_id: str | None, step: Step | None
diff --git a/skyvern/forge/sdk/schemas/tasks.py b/skyvern/forge/sdk/schemas/tasks.py
index 83b4dc5f2..9be325ee3 100644
--- a/skyvern/forge/sdk/schemas/tasks.py
+++ b/skyvern/forge/sdk/schemas/tasks.py
@@ -8,6 +8,7 @@ from fastapi import status
from pydantic import BaseModel, Field, field_serializer, field_validator, model_validator
from typing_extensions import Self
+from skyvern.errors.errors import drop_unsolicited_download_errors
from skyvern.exceptions import (
InvalidTaskStatusTransition,
SkyvernHTTPException,
@@ -419,7 +420,7 @@ class Task(TaskBase):
browser_console_log_url=browser_console_log_url,
downloaded_files=downloaded_files,
downloaded_file_urls=[file.url for file in downloaded_files] if downloaded_files else None,
- errors=self.errors,
+ errors=drop_unsolicited_download_errors(self.errors, downloaded_files=downloaded_files),
max_steps_per_run=self.max_steps_per_run,
workflow_run_id=self.workflow_run_id,
max_screenshot_scrolls=self.max_screenshot_scrolls,
@@ -494,7 +495,7 @@ class TaskOutput(BaseModel):
status=task.status,
extracted_information=task.extracted_information,
failure_reason=task.failure_reason,
- errors=task.errors,
+ errors=drop_unsolicited_download_errors(task.errors, downloaded_files=downloaded_files),
failure_category=task.failure_category,
downloaded_files=downloaded_files,
downloaded_file_urls=downloaded_file_urls,
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index f08812609..0e913c183 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -2718,7 +2718,7 @@ class BaseTaskBlock(Block):
)
success = updated_task.status == TaskStatus.completed
- downloaded_files: list[FileInfo] = []
+ downloaded_files: list[FileInfo] | None = None
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
downloaded_files = await app.STORAGE.get_current_attempt_downloaded_files(
@@ -2731,11 +2731,12 @@ class BaseTaskBlock(Block):
LOG.warning("Timeout getting downloaded files", task_id=updated_task.task_id)
# SKY-7005: scope downloaded files to the current loop iteration
- downloaded_files = filter_downloaded_files_for_current_iteration(
- downloaded_files,
- current_context.loop_internal_state if current_context else None,
- aliases=app.STORAGE.get_downloaded_file_signature_aliases,
- )
+ if downloaded_files is not None:
+ downloaded_files = filter_downloaded_files_for_current_iteration(
+ downloaded_files,
+ current_context.loop_internal_state if current_context else None,
+ aliases=app.STORAGE.get_downloaded_file_signature_aliases,
+ )
task_screenshot_artifacts = await app.WORKFLOW_SERVICE.get_recent_task_screenshot_artifacts(
organization_id=workflow_run.organization_id,
@@ -2824,7 +2825,7 @@ class BaseTaskBlock(Block):
)
will_retry = False
retry_message = f", retrying task {current_retry}/{self.max_retries}" if will_retry else ""
- downloaded_files = []
+ downloaded_files = None
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
downloaded_files = await app.STORAGE.get_current_attempt_downloaded_files(
@@ -2838,11 +2839,12 @@ class BaseTaskBlock(Block):
LOG.warning("Timeout getting downloaded files", task_id=updated_task.task_id)
# SKY-7005: scope downloaded files to the current loop iteration
- downloaded_files = filter_downloaded_files_for_current_iteration(
- downloaded_files,
- current_context.loop_internal_state if current_context else None,
- aliases=app.STORAGE.get_downloaded_file_signature_aliases,
- )
+ if downloaded_files is not None:
+ downloaded_files = filter_downloaded_files_for_current_iteration(
+ downloaded_files,
+ current_context.loop_internal_state if current_context else None,
+ aliases=app.STORAGE.get_downloaded_file_signature_aliases,
+ )
task_screenshot_artifacts = await app.WORKFLOW_SERVICE.get_recent_task_screenshot_artifacts(
organization_id=workflow_run.organization_id,
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index bcda1a89e..c4d3ca78a 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -51,6 +51,7 @@ from skyvern.constants import (
GET_DOWNLOADED_FILES_TIMEOUT,
SAVE_DOWNLOADED_FILES_TIMEOUT,
)
+from skyvern.errors.errors import drop_unsolicited_download_errors
from skyvern.exceptions import (
BlockedHost,
BlockNotFound,
@@ -15074,10 +15075,11 @@ class WorkflowService:
attempt_rows: Sequence[Any] | None = None,
attempt_number: int | None = None,
historical_artifacts: list[Artifact] | None = None,
- ) -> tuple[list[FileInfo], list[str] | None]:
+ ) -> tuple[list[FileInfo] | None, list[str] | None]:
"""Fetch downloaded files for a workflow run, including task_v2 files when present."""
- downloaded_files: list[FileInfo] = []
+ downloaded_files: list[FileInfo] | None = None
downloaded_file_urls: list[str] | None = None
+ workflow_run_downloaded_files: list[FileInfo] | None = None
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
context = skyvern_context.current()
@@ -15106,6 +15108,9 @@ class WorkflowService:
attempt_number=attempt_number,
artifact_ids=artifact_ids,
)
+ workflow_run_downloaded_files = downloaded_files
+ if workflow_run_downloaded_files:
+ downloaded_file_urls = [file_info.url for file_info in workflow_run_downloaded_files]
if task_v2:
task_v2_downloaded_files = await app.STORAGE.get_downloaded_files(
organization_id=workflow_run.organization_id,
@@ -15145,12 +15150,14 @@ class WorkflowService:
"Timeout to get downloaded files",
workflow_run_id=workflow_run.workflow_run_id,
)
+ downloaded_files = workflow_run_downloaded_files or None
except Exception:
LOG.warning(
"Failed to get downloaded files",
exc_info=True,
workflow_run_id=workflow_run.workflow_run_id,
)
+ downloaded_files = workflow_run_downloaded_files or None
return downloaded_files, downloaded_file_urls
async def build_workflow_run_status_response(
@@ -15400,6 +15407,8 @@ class WorkflowService:
),
workflow_run_id=workflow_run_id,
)
+ # After the merge so a code copied onto a block's error_codes is filtered too.
+ errors = drop_unsolicited_download_errors(errors, downloaded_files=downloaded_files)
parameters_with_value = {wfp.key: wfrp.value for wfp, wfrp in workflow_parameter_tuples}
diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.py
index d90a8dc71..bf90d3519 100644
--- a/skyvern/forge/taskv3/engine.py
+++ b/skyvern/forge/taskv3/engine.py
@@ -26,7 +26,7 @@ import functools
import json
import time
from datetime import UTC, datetime
-from typing import Any, Awaitable, Callable, Collection
+from typing import Any, Awaitable, Callable, Collection, Sequence
import litellm
import structlog
@@ -59,6 +59,7 @@ from skyvern.forge.taskv3.goal_check import (
run_unlisted_reask,
)
from skyvern.forge.taskv3.goal_composition import CodeTypedValue, build_user_prompt, typed_value_rows
+from skyvern.forge.taskv3.intercepted_submission import InterceptedSubmission
from skyvern.forge.taskv3.llm_call_params import build_call_kwargs
from skyvern.forge.taskv3.loop import (
DEFAULT_MAX_SETTLE_DEFERRALS,
@@ -76,6 +77,7 @@ from skyvern.forge.taskv3.loop import (
VerificationBlocker,
make_finish_tool,
run_agent_tool_loop,
+ submissions_since,
)
from skyvern.forge.taskv3.opaque_refs import OpaqueUrlRefs, is_signed_url, mask_opaque_urls
from skyvern.forge.taskv3.tools import (
@@ -323,6 +325,8 @@ async def run_task_v3_agent_loop(
# Appended to the goal, whose Code outline section is last, only as far as the request has room for them.
code_typed_values: tuple[CodeTypedValue, ...] = (),
anthropic_cache_markers: bool = False,
+ # The submissions a page-level interceptor held for the run's browser context; a local read, never a page call.
+ intercepted_submissions: Callable[[], Sequence[InterceptedSubmission]] | None = None,
) -> LoopOutcome:
"""Run one Task V3 task to completion against `page`, returning the loop outcome.
@@ -456,6 +460,11 @@ async def run_task_v3_agent_loop(
refuse_input_entry = block_type == BlockType.EXTRACTION
refuse_navigation = block_type == BlockType.VALIDATION
deadline_at = time.monotonic() + deadline_seconds if deadline_seconds is not None else None
+ block_submissions = (
+ submissions_since(intercepted_submissions, time.monotonic())
+ if intercepted_submissions is not None and not page_free
+ else None
+ )
# A block with its own completion verifier is left to it by every completion judge; the terminate check is not one.
judge_eligible = goal_check_eligible(
page_free=page_free,
@@ -617,6 +626,7 @@ async def run_task_v3_agent_loop(
completion_gate=None if page_free else completion_gate,
download_facts=failure_watch.facts if failure_watch is not None else None,
error_code_mapping=error_code_mapping,
+ intercepted_submissions=block_submissions,
)
tools = browser_tools + (extra_tools or []) + [finish_tool]
# The COMPLETE dispatch list, not just the browser tools: auth / captcha / code tools and finish
diff --git a/skyvern/forge/taskv3/intercepted_submission.py b/skyvern/forge/taskv3/intercepted_submission.py
new file mode 100644
index 000000000..181443dca
--- /dev/null
+++ b/skyvern/forge/taskv3/intercepted_submission.py
@@ -0,0 +1,34 @@
+"""A form submission a page-level interceptor held and released, as the task loop reads it."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import StrEnum
+
+
+class SubmissionOutcome(StrEnum):
+ HELD = "held"
+ # The page received a response. Says nothing about whether the site accepted the submission.
+ DELIVERED = "delivered"
+ # The page received the site's own typed machine rejection, after the interceptor's recovery ran out.
+ REJECTED_BY_SITE = "rejected_by_site"
+ # The interceptor failed, was canceled, or could not see the response the page got.
+ UNKNOWN = "unknown"
+
+
+@dataclass(frozen=True)
+class InterceptedSubmission:
+ # Unique within the process and increasing in the order the interceptor saw the requests.
+ record_id: int
+ outcome: SubmissionOutcome
+ # time.monotonic() readings.
+ started_at: float
+ released_at: float | None = None
+ delivered_at: float | None = None
+ # The site's machine error code, set only on REJECTED_BY_SITE.
+ site_error_type: str | None = None
+
+ @property
+ def effect_at(self) -> float | None:
+ """When the page could last have changed because of this submission; None while it is still held."""
+ return self.delivered_at if self.delivered_at is not None else self.released_at
diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.py
index 9a8593098..e8173cff7 100644
--- a/skyvern/forge/taskv3/loop.py
+++ b/skyvern/forge/taskv3/loop.py
@@ -43,6 +43,7 @@ from skyvern.forge.taskv3.goal_check import (
UnlistedReask,
)
from skyvern.forge.taskv3.handoff_redaction import MAX_HANDOFF_URL_CHARS, normalized_url, sanitize_published_url
+from skyvern.forge.taskv3.intercepted_submission import InterceptedSubmission, SubmissionOutcome
from skyvern.forge.taskv3.target_label import describe_target
from skyvern.schemas.workflows import ERROR_CODE_MAPPING_MAX_ENTRIES, ERROR_CODE_MAPPING_MAX_UTF8_BYTES
from skyvern.webeye.navigation import clear_task_nav_error_code, redact_url_secrets
@@ -366,6 +367,8 @@ _ENTRY_RECORD: ContextVar[dict[str, Any] | None] = ContextVar("taskv3_entry_reco
_TEXT_DELTA: ContextVar[tuple[float, int | None, int, bool, str | None, int] | None] = ContextVar(
"taskv3_text_delta", default=None
)
+# How many of this call's own newly read lines its result actually showed the model; read by the submission hold.
+_TEXT_DELTA_SHOWN_FRESH: ContextVar[int] = ContextVar("taskv3_text_delta_shown_fresh", default=0)
# The ordinal of the tool call being dispatched, so a tool can say how many calls a report spans.
_TOOL_CALL_SEQ: ContextVar[int | None] = ContextVar("taskv3_tool_call_seq", default=None)
@@ -415,8 +418,10 @@ def record_text_delta(
over_bound: bool = False,
skipped: str | None = None,
pending: int = 0,
+ shown_fresh: int = 0,
) -> None:
- """Record the text-delta read. Telemetry only. `lines` is None when the read failed, timed out or
+ """Record the text-delta read. Telemetry, except `shown_fresh`: how many of this call's own new lines the
+ result showed after the char budget cut, which the finish tool's submission hold reads. `lines` is None when the read failed, timed out or
was past the char bound (`over_bound`), or when the tool errored after a read before it ran; else
how many lines rose, counted before the char budget cut them. `chars` is the section's length.
`skipped` names why a call did not read at all: "over_bound" (this document was already read past
@@ -426,6 +431,7 @@ def record_text_delta(
read succeeded, and still reported when it did not (`lines` None). A call that does not report
records it too when it carries flushed lines."""
_TEXT_DELTA.set((seconds, lines, chars, over_bound, skipped, pending))
+ _TEXT_DELTA_SHOWN_FRESH.set(shown_fresh)
def current_tool_call_seq() -> int | None:
@@ -1483,6 +1489,11 @@ FAILURE_EVIDENCE_MIN_TURNS = 3
# of that cycle, so the 60s above would let the gate convert an honest failure into the
# budget-exhausted end it exists to prevent. Not imported from auth_tools: that module imports this one.
VERIFICATION_GIVEUP_MIN_DEADLINE_HEADROOM_SECONDS = 180.0
+# An interceptor holds a submission while it retries the site (observed holding one for ~20s).
+SUBMISSION_HELD_WAIT_MAX_SECONDS = 30.0
+SUBMISSION_HELD_POLL_SECONDS = 0.5
+# A read that starts this soon after a response reached the page may still show the page before the page rendered it.
+SUBMISSION_RENDER_MARGIN_SECONDS = 0.5
def _is_enter_submit(tool_name: str, args: dict[str, Any]) -> bool:
@@ -1698,6 +1709,10 @@ class ActivityRecency:
action_attempts: int = 0
# Successful perceptions (the compactable tools: observe / get_html / look).
perceptions: int = 0
+ # When the newest page read the model has received STARTED (a read begun before a response landed can return
+ # after it showing the old page); this batch's reads wait in `batch_read_started_at` until the next model turn.
+ read_started_at: float | None = None
+ batch_read_started_at: float | None = None
# State at the FIRST failed/terminated finish past the failure-evidence gate, emitted once per run
# by the engine's summary line. Not the run's first verdict: a zero-action `completed` refused by a
# gate above reaches this point later as failed/terminated.
@@ -1708,6 +1723,31 @@ class ActivityRecency:
def armed(self, window: int = FAILURE_EVIDENCE_WINDOW_TURNS) -> bool:
return self.last_trigger_turn is not None and (self.turn - self.last_trigger_turn) <= window
+ def record_read(self, started_at: float) -> None:
+ if self.batch_read_started_at is None or started_at > self.batch_read_started_at:
+ self.batch_read_started_at = started_at
+
+ def deliver_batch_reads(self) -> None:
+ """Called as the batch's results go to the model."""
+ if self.batch_read_started_at is not None and (
+ self.read_started_at is None or self.batch_read_started_at > self.read_started_at
+ ):
+ self.read_started_at = self.batch_read_started_at
+ self.batch_read_started_at = None
+
+
+def submissions_since(
+ source: Callable[[], Sequence[InterceptedSubmission]], started_at: float
+) -> Callable[[], tuple[InterceptedSubmission, ...]]:
+ """`source` without the submissions whose response reached the page before `started_at` (an earlier block's),
+ except within the render margin: the page may still have been rendering one, so the read-start check decides."""
+ cutoff = started_at - SUBMISSION_RENDER_MARGIN_SECONDS
+
+ def read() -> tuple[InterceptedSubmission, ...]:
+ return tuple(r for r in source() if r.effect_at is None or r.effect_at >= cutoff)
+
+ return read
+
def _names_submit_control(tool_name: str, args: dict[str, Any], ok: bool, data: dict[str, Any]) -> str | None:
"""The selector of a control a successful action acted on directly, or None.
@@ -2644,6 +2684,7 @@ def make_finish_tool(
terminate_premise: TerminatePremiseCheck | None = None,
download_facts: DownloadFailureFacts | None = None,
error_code_mapping: dict[str, str] | None = None,
+ intercepted_submissions: Callable[[], Sequence[InterceptedSubmission]] | None = None,
) -> ToolSpec:
"""`page_fingerprint` samples an opaque fingerprint of the page's rendered content (None when no
page is available). A finish(completed) is deferred (bounded by `max_settle_deferrals`, then
@@ -2664,8 +2705,8 @@ def make_finish_tool(
run is still awaiting a sign-in link it has unspent polling budget for -- a give-up at one 120s slice of
a 15-minute budget throws away minutes of waiting the run already owns. The hold is bounded by
the callee (the budget shrinks under every productive hold) and refused here without the deadline
- headroom to fund the blocking poll slice it asks for. Apart from that gate, terminated is
- ungated on both sides.
+ headroom to fund the blocking poll slice it asks for. Apart from that gate and the submission hold
+ below, terminated is ungated on both sides.
`pending_marker` reports the text the page still shows the control in `submit_watch` as in
flight with, or None. A settled page is not a submitted one -- a submit frozen mid-flight is
@@ -2689,13 +2730,73 @@ def make_finish_tool(
`unseen_text` holds a completed verdict, on its own budget, while the page shows text no result the model read
carried, or a result in the finish's own batch carried page text or download lines.
- `terminate_premise` checks every terminated finish past the holds above, alongside any re-ask, and changes nothing."""
+ `terminate_premise` checks every terminated finish past the holds above, alongside any re-ask, and changes nothing.
+
+ `intercepted_submissions` lists the submissions a page-level interceptor held this block. A failed or terminated
+ verdict is held once per submission whose response reached the page after the newest read the model received
+ started: the verdict may describe the page before the response. One still held is waited on first (bounded) and,
+ if still held, holds once on the wait; when it is released later its response can hold once more. The hold asks
+ for a re-observe and never implies the response was an acceptance."""
error_code_mapping = _offered_error_codes(error_code_mapping)
deferrals = 0
stale_holds = 0
failure_deferrals = 0
premise_checks = 0
reask_asked = False
+ submission_holds: set[int] = set()
+ # Held while the interceptor still held them: the hold spent waiting on the request, not on its response, so a
+ # response released later is held for once more; while still held they are neither waited on nor held again.
+ submission_held_pending: set[int] = set()
+ submission_would_holds: set[int] = set()
+ # The turn a submission hold fired in and its message: a later finish in that batch has not received it either.
+ submission_hold_turn: int | None = None
+ submission_hold_message = ""
+
+ def _read_submissions() -> list[InterceptedSubmission]:
+ assert intercepted_submissions is not None
+ try:
+ return list(intercepted_submissions())
+ except Exception:
+ LOG.warning("taskv3 intercepted submissions could not be read", exc_info=True)
+ return []
+
+ def _unseen_submissions(records: list[InterceptedSubmission]) -> list[InterceptedSubmission]:
+ read_started_at = activity.read_started_at if activity is not None else None
+ return [
+ record
+ for record in records
+ if record.record_id not in submission_holds
+ and not (record.record_id in submission_held_pending and record.outcome is SubmissionOutcome.HELD)
+ and (
+ record.effect_at is None
+ or read_started_at is None
+ or read_started_at < record.effect_at + SUBMISSION_RENDER_MARGIN_SECONDS
+ )
+ ]
+
+ async def _released_submissions() -> list[InterceptedSubmission]:
+ """The records once no unheld-before one is still held, waiting at most SUBMISSION_HELD_WAIT_MAX_SECONDS."""
+ records = _read_submissions()
+ cap_at = time.monotonic() + SUBMISSION_HELD_WAIT_MAX_SECONDS
+ while any(
+ r.outcome is SubmissionOutcome.HELD
+ and r.record_id not in submission_holds
+ and r.record_id not in submission_held_pending
+ for r in records
+ ):
+ wait = min(SUBMISSION_HELD_POLL_SECONDS, cap_at - time.monotonic())
+ if deadline_at is not None:
+ wait = min(wait, deadline_at - time.monotonic())
+ if wait <= 0:
+ break
+ await asyncio.sleep(wait)
+ try:
+ if should_cancel is not None and await should_cancel():
+ break
+ except Exception:
+ break
+ records = _read_submissions()
+ return records
async def _bounded_fingerprint() -> str | None:
"""page_fingerprint(), timed out against whatever is left of the run's deadline instead of
@@ -2872,6 +2973,7 @@ def make_finish_tool(
async def handler(args: dict[str, Any]) -> ToolResult:
nonlocal deferrals, stale_holds, failure_deferrals, reask_asked, premise_checks
+ nonlocal submission_hold_turn, submission_hold_message
status = args.get("status")
if status not in ("completed", "failed", "terminated"):
return ToolResult.error(
@@ -3027,6 +3129,63 @@ def make_finish_tool(
if not gate_passed:
LOG.info("taskv3 completed verdict refused by the completion gate")
return ToolResult.error(COMPLETION_GATE_REFUSAL)
+ if status in ("failed", "terminated") and intercepted_submissions is not None and activity is not None:
+ if submission_hold_turn == activity.turn:
+ return ToolResult.error(submission_hold_message)
+ unseen = _unseen_submissions(_read_submissions())
+ can_hold = bool(unseen) and _has_hold_headroom(activity, deadline_at)
+ if can_hold:
+ unseen = _unseen_submissions(await _released_submissions())
+ # The wait spent deadline, so the hold must still have the headroom it asks the model to spend.
+ can_hold = bool(unseen) and _has_hold_headroom(activity, deadline_at)
+ if unseen and not can_hold:
+ new = [r.record_id for r in unseen if r.record_id not in submission_would_holds]
+ if new:
+ submission_would_holds.update(new)
+ LOG.info(
+ "taskv3 finish would hold on an unseen submission response",
+ status=status,
+ record_ids=new,
+ turn=activity.turn,
+ )
+ elif unseen:
+ for r in unseen:
+ if r.outcome is SubmissionOutcome.HELD:
+ submission_held_pending.add(r.record_id)
+ else:
+ submission_holds.add(r.record_id)
+ if status == "failed":
+ # The failure-evidence hold below asks for the same re-observe; one is enough.
+ failure_deferrals = max_failure_deferrals
+ now = time.monotonic()
+ LOG.info(
+ "taskv3 finish held on an unseen submission response",
+ status=status,
+ record_ids=[r.record_id for r in unseen],
+ outcomes=[str(r.outcome) for r in unseen],
+ seconds_since_response=[
+ None if r.effect_at is None else round(now - r.effect_at, 2) for r in unseen
+ ],
+ read_age_seconds=None
+ if activity.read_started_at is None
+ else round(now - activity.read_started_at, 2),
+ turn=activity.turn,
+ )
+ still_held = any(r.outcome is SubmissionOutcome.HELD for r in unseen)
+ submission_hold_turn = activity.turn
+ submission_hold_message = (
+ "verdict held once: a form submission on this page "
+ + (
+ "is still waiting for the site's response"
+ if still_held
+ else "got the site's response after your last look at the page"
+ )
+ + ", so the page may no longer show what this verdict describes. That response is not by "
+ "itself a confirmation or a rejection. Re-observe the page (waiting briefly first if it may "
+ "still be processing) and finish on what it shows now: status=completed only on a positive "
+ "confirmation of the goal; otherwise finish again with your verdict and it will stand."
+ )
+ return ToolResult.error(submission_hold_message)
if (
status == "failed"
and activity is not None
@@ -4175,6 +4334,7 @@ async def run_agent_tool_loop(
activity.final_turn_active = True
st.turns += 1
if activity is not None:
+ activity.deliver_batch_reads()
activity.turn = st.turns
activity.turns_remaining = st.max_turns - st.turns
activity.tool_calls_remaining = st.max_tool_calls - st.total_tool_calls
@@ -4867,6 +5027,7 @@ async def run_agent_tool_loop(
_CLICK_DISPATCHED.set(False)
_ENTRY_RECORD.set(None)
_TEXT_DELTA.set(None)
+ _TEXT_DELTA_SHOWN_FRESH.set(0)
_TOOL_CALL_SEQ.set(st.total_tool_calls)
dispatch_ctx = skyvern_context.current()
runtime_secrets_before = len(dispatch_ctx.runtime_secret_values) if dispatch_ctx is not None else 0
@@ -4910,6 +5071,17 @@ async def run_agent_tool_loop(
tool_duration_seconds = time.monotonic() - tool_started_at
st.tool_seconds += tool_duration_seconds
news_at = (result.data or {}).get("delta_at")
+ # A delta can show only lines an earlier read held back (flushed after this call's read failed, or filling the
+ # char budget ahead of this call's own lines): that is the page from before this call, so it counts as a
+ # fresh read only if the result showed at least one line this call's own read found.
+ fresh_delta = type(news_at) is int and _TEXT_DELTA_SHOWN_FRESH.get() > 0
+ if (
+ activity is not None
+ and spec is not None
+ and result.status == "ok"
+ and (spec.compactable or fresh_delta)
+ ):
+ activity.record_read(tool_started_at)
if unseen_text is not None and result.status == "ok" and type(news_at) is int:
news_end = (result.data or {}).get("delta_end")
end = news_end if type(news_end) is int and news_at <= news_end else len(result.content)
diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.py
index 4cfeff860..fd68fd095 100644
--- a/skyvern/forge/taskv3/tools.py
+++ b/skyvern/forge/taskv3/tools.py
@@ -14875,13 +14875,22 @@ def build_browser_tools(
section += "\n" + shown
if cut and since is not None:
_defer(page, [risen[i][0] for i in cut], prior, since)
+ left_out = set(cut)
+ # Rank 0 is a held line rising again: the page before this call, not this call's own read.
+ shown_fresh = sum(1 for i, (_, rank) in enumerate(risen) if rank != 0 and i not in left_out)
+ else:
+ shown_fresh = 0
if not section:
record_text_delta(time.monotonic() - started, 0)
return result
returned = sum(1 for _, rank in risen if rank == 0)
earlier = len(before) + held + returned - pending_held
record_text_delta(
- time.monotonic() - started, earlier + len(risen) - returned, len(section), pending=earlier
+ time.monotonic() - started,
+ earlier + len(risen) - returned,
+ len(section),
+ pending=earlier,
+ shown_fresh=shown_fresh,
)
return _with_delta_section(result, section)
diff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.py
index 9d6efb8ab..4806dbcf3 100644
--- a/skyvern/services/script_service.py
+++ b/skyvern/services/script_service.py
@@ -1060,7 +1060,7 @@ async def _update_workflow_block(
)
if run_lease_tasks_enabled() and lease_lost:
return
- downloaded_files: list[FileInfo] = []
+ downloaded_files: list[FileInfo] | None = None
try:
async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
downloaded_files = await app.STORAGE.get_current_attempt_downloaded_files(
@@ -1069,11 +1069,12 @@ async def _update_workflow_block(
)
except asyncio.TimeoutError:
LOG.warning("Timeout getting downloaded files", task_id=task_id)
- downloaded_files = _filter_downloaded_files_for_current_iteration(
- downloaded_files,
- context.loop_internal_state,
- aliases=app.STORAGE.get_downloaded_file_signature_aliases,
- )
+ if downloaded_files is not None:
+ downloaded_files = _filter_downloaded_files_for_current_iteration(
+ downloaded_files,
+ context.loop_internal_state,
+ aliases=app.STORAGE.get_downloaded_file_signature_aliases,
+ )
task_screenshot_artifacts = await app.WORKFLOW_SERVICE.get_recent_task_screenshot_artifacts(
organization_id=context.organization_id,
diff --git a/skyvern/webeye/cdp_download_interceptor.py b/skyvern/webeye/cdp_download_interceptor.py
index 18ba4cf9a..b8b842fc4 100644
--- a/skyvern/webeye/cdp_download_interceptor.py
+++ b/skyvern/webeye/cdp_download_interceptor.py
@@ -49,6 +49,7 @@ from skyvern.constants import (
BROWSER_INTERCEPTOR_DISABLE_TIMEOUT,
BROWSER_PAGE_CLOSE_TIMEOUT,
)
+from skyvern.errors.errors import BROWSER_DOWNLOAD_PARTIAL_FAILURE_CODE
from skyvern.exceptions import DownloadFileMaxSizeExceeded, redact_cdp_endpoint_urls
from skyvern.forge.sdk.api import files as file_api
from skyvern.forge.sdk.core.hashing import diagnostic_fingerprint
@@ -1000,15 +1001,17 @@ class CDPDownloadInterceptor:
}
def consume_unsolicited_download_error(self) -> dict[str, Any] | None:
+ # States only what this call observed: whether the run ends up with a file is unknown here,
+ # and the row is persisted for readers that never consult the download count.
if not self._unsolicited_download_failures:
return None
reasons = dict(sorted(self._unsolicited_download_failures.items()))
self._unsolicited_download_failures.clear()
failed_count = sum(reasons.values())
- noun = "download was" if failed_count == 1 else "downloads were"
+ subject = "A browser download" if failed_count == 1 else f"{failed_count} browser downloads"
return {
- "error_code": "BROWSER_DOWNLOAD_PARTIAL_FAILURE",
- "reasoning": f"{failed_count if failed_count > 1 else 'One'} unsolicited browser {noun} not saved.",
+ "error_code": BROWSER_DOWNLOAD_PARTIAL_FAILURE_CODE,
+ "reasoning": f"{subject} could not be saved.",
"error_type": "SYSTEM_DEFINED_ERROR",
"details": {"failed_download_count": failed_count, "reasons": reasons},
}
diff --git a/tests/unit/test_background_task_executor.py b/tests/unit/test_background_task_executor.py
index fee201c2f..19da8ad27 100644
--- a/tests/unit/test_background_task_executor.py
+++ b/tests/unit/test_background_task_executor.py
@@ -1525,6 +1525,7 @@ async def test_historical_child_artifacts_use_parent_attempt(
attempt_number=1,
historical_artifacts=[],
)
+ assert files is not None
assert [file.artifact_id for file in files] == ["child_1_pdf"]
assert urls == ["https://example.com/child_1_pdf"]
assert lookup.await_count == 4
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index 6d26e0fca..b899a2962 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -35,6 +35,7 @@ from skyvern.forge.taskv3.auth_tools import _MAX_GIVEUP_DEFERRALS, VerificationF
from skyvern.forge.taskv3.engine import MAX_TOKENS_CEILING, MAX_TOKENS_PER_ACTION_STEP, taskv3_runaway_backstops
from skyvern.forge.taskv3.goal_check import GoalVerdict, ToolTrail, run_goal_check
from skyvern.forge.taskv3.handoff_redaction import ELIDED_URL_PATH, caller_known_published_urls
+from skyvern.forge.taskv3.intercepted_submission import InterceptedSubmission, SubmissionOutcome
from skyvern.forge.taskv3.loop import (
ACTION_BLOCK_TARGET_ACTION_RESERVE,
ACTION_BUDGET_EXTENDED_EVENT,
@@ -49,6 +50,7 @@ from skyvern.forge.taskv3.loop import (
COMPLETION_GATE_REFUSAL,
DOWNLOAD_FAILURE_MAX_LINES,
DOWNLOAD_NO_FILE_FACT,
+ FAILURE_EVIDENCE_MIN_DEADLINE_HEADROOM_SECONDS,
FAILURE_EVIDENCE_MIN_TOOL_CALLS,
FAILURE_EVIDENCE_MIN_TURNS,
FINAL_TURN_GRANTED_EVENT,
@@ -71,6 +73,8 @@ from skyvern.forge.taskv3.loop import (
PROGRESS_LEDGER_SHADOW_EVENT,
PROGRESS_LEDGER_WINDOW,
STALE_READ_MAX_HOLDS,
+ SUBMISSION_HELD_WAIT_MAX_SECONDS,
+ SUBMISSION_RENDER_MARGIN_SECONDS,
TARGET_ACTION_ROUND_EVENT,
TOKEN_BUDGET_EXTENDED_EVENT,
TOKEN_BUDGET_EXTENSION_REFUSED_EVENT,
@@ -104,7 +108,9 @@ from skyvern.forge.taskv3.loop import (
record_covered_layer,
record_hit_class,
record_resolve_seconds,
+ record_text_delta,
run_agent_tool_loop,
+ submissions_since,
)
from skyvern.forge.taskv3.opaque_refs import mask_opaque_urls
from skyvern.forge.taskv3.tools import build_browser_tools
@@ -6999,6 +7005,404 @@ async def test_finish_terminated_after_submit_click_stands_without_a_relook() ->
assert fp_calls["n"] == 0
+class _FakeSubmissions:
+ """What a page-level interceptor's ledger reports, driven by the test's own tools."""
+
+ def __init__(self) -> None:
+ self.records: list[InterceptedSubmission] = []
+
+ def __call__(self) -> tuple[InterceptedSubmission, ...]:
+ return tuple(self.records)
+
+ def deliver(self, *, ago: float = 0.0, outcome: SubmissionOutcome = SubmissionOutcome.DELIVERED) -> None:
+ at = time.monotonic() - ago
+ self.records.append(
+ InterceptedSubmission(
+ record_id=len(self.records) + 1, outcome=outcome, started_at=at - 0.5, released_at=at, delivered_at=at
+ )
+ )
+
+ def hold(self) -> int:
+ record_id = len(self.records) + 1
+ self.records.append(
+ InterceptedSubmission(record_id=record_id, outcome=SubmissionOutcome.HELD, started_at=time.monotonic())
+ )
+ return record_id
+
+ def release(self, record_id: int) -> None:
+ now = time.monotonic()
+ self.records[record_id - 1] = dataclasses.replace(
+ self.records[record_id - 1], outcome=SubmissionOutcome.DELIVERED, released_at=now, delivered_at=now
+ )
+
+
+def _submission_tools(
+ submissions: _FakeSubmissions,
+ activity: ActivityRecency,
+ *,
+ observe_delivers_mid_read: bool = False,
+ click_delivers: bool = False,
+ click_settles: bool = False,
+ **finish_kwargs: Any,
+) -> list[ToolSpec]:
+ async def click(args: dict[str, Any]) -> ToolResult:
+ if click_delivers:
+ submissions.deliver()
+ if click_settles:
+ await asyncio.sleep(SUBMISSION_RENDER_MARGIN_SECONDS + 0.2)
+ return ToolResult.ok("click done")
+
+ async def observe(args: dict[str, Any]) -> ToolResult:
+ if observe_delivers_mid_read:
+ # The reference run: the read started before the response reached the page and returned after it.
+ submissions.deliver()
+ await asyncio.sleep(SUBMISSION_RENDER_MARGIN_SECONDS + 0.2)
+ return ToolResult.ok("url=x text: 'Submit application'")
+
+ return [
+ ToolSpec(name="click", description="c", parameters={}, handler=click, billable=True),
+ ToolSpec(name="observe", description="o", parameters={}, handler=observe, compactable=True),
+ make_finish_tool(activity=activity, intercepted_submissions=submissions, **finish_kwargs),
+ ]
+
+
+async def test_terminated_held_once_when_a_submission_response_landed_after_the_last_read() -> None:
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ tools = _submission_tools(submissions, activity, click_delivers=True)
+ script = [
+ [("observe", {})],
+ [("click", {"selector": "#submit"})],
+ [("finish", {"status": "terminated", "reason": "form still shows submit"})],
+ [("observe", {})],
+ [("finish", {"status": "completed", "reason": "confirmation shown"})],
+ ]
+ with capture_logs() as logs:
+ outcome, caller = await _run(script, tools, activity=activity)
+ assert outcome.status == "completed"
+ assert outcome.turns == 5
+ held = [e for e in logs if e["event"] == "taskv3 finish held on an unseen submission response"]
+ assert [e["record_ids"] for e in held] == [[1]]
+ hold_result = next(m for m in caller.message_history if m.get("role") == "tool" and "verdict held" in m["content"])
+ assert "not by itself a confirmation" in hold_result["content"]
+
+
+async def test_submission_hold_counts_a_read_from_its_start_not_its_end() -> None:
+ # A read that began before the response reached the page and returned after it can still show the old page.
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ tools = _submission_tools(submissions, activity, observe_delivers_mid_read=True)
+ script = [
+ [("observe", {})],
+ [("finish", {"status": "terminated", "reason": "nothing happened"})],
+ [("finish", {"status": "terminated", "reason": "nothing happened, re-checked"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "terminated"
+ assert outcome.reason == "nothing happened, re-checked"
+
+
+async def test_submission_hold_ignores_page_text_in_the_finishs_own_batch() -> None:
+ # The model emitted finish alongside the reads, so it decided before any of them came back.
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ tools = _submission_tools(submissions, activity, click_delivers=True, click_settles=True)
+ script = [
+ [("click", {"selector": "#submit"}), ("observe", {}), ("finish", {"status": "terminated", "reason": "r1"})],
+ [("observe", {})],
+ [("finish", {"status": "terminated", "reason": "r2"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "terminated"
+ assert outcome.reason == "r2"
+
+
+ ("own_read_lines", "earlier_lines", "shown_fresh", "counts"),
+ # (41, 40, 0): the budget cut every line this call found, so only held lines reached the model.
+ [(1, 0, 1, True), (2, 1, 1, True), (None, 1, 0, False), (1, 1, 0, False), (41, 40, 0, False)],
+)
+async def test_action_result_page_text_counts_as_a_read_only_when_this_call_read_it(
+ own_read_lines: int | None, earlier_lines: int, shown_fresh: int, counts: bool
+) -> None:
+ # Lines held back by an earlier read and flushed by this call show the page from before it.
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ submissions.deliver(ago=5.0)
+
+ async def type_(args: dict[str, Any]) -> ToolResult:
+ record_text_delta(0.0, own_read_lines, pending=earlier_lines, shown_fresh=shown_fresh)
+ return ToolResult.ok("typed\nThe page newly shows: 'Thanks'", data={"delta_at": 6})
+
+ tools = [
+ ToolSpec(name="type", description="t", parameters={}, handler=type_, billable=True),
+ make_finish_tool(activity=activity, intercepted_submissions=submissions),
+ ]
+ script = [
+ [("type", {"selector": "#q", "text": "x"})],
+ [("finish", {"status": "terminated", "reason": "r1"})],
+ [("finish", {"status": "terminated", "reason": "r2"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.reason == ("r1" if counts else "r2")
+
+
+async def test_submission_hold_negatives_leave_the_verdict_alone() -> None:
+ # A response the model's last read already covered, no submissions, and a completed verdict.
+ for setup, status in (("covered", "terminated"), ("none", "terminated"), ("fresh", "completed")):
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ if setup == "covered":
+ submissions.deliver(ago=5.0)
+ tools = _submission_tools(submissions, activity, click_delivers=setup == "fresh")
+ script = [
+ [("observe", {})],
+ [("click", {"selector": "#submit"})] if setup == "fresh" else [("observe", {})],
+ [("finish", {"status": status, "reason": "r"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert (setup, outcome.status, outcome.turns) == (setup, status, 3)
+
+
+async def test_failed_submission_hold_replaces_the_failure_evidence_hold() -> None:
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ fingerprint, _ = _fingerprint_seq(["fp"])
+ tools = _submission_tools(
+ submissions,
+ activity,
+ click_delivers=True,
+ page_fingerprint=fingerprint,
+ settle_wait_seconds=0.0,
+ failure_settle_max_seconds=0.01,
+ )
+ script = [
+ [("click", {"selector": "#submit"})],
+ [("finish", {"status": "failed", "reason": "r1"})],
+ [("observe", {})],
+ [("finish", {"status": "failed", "reason": "r2"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert (outcome.status, outcome.reason, outcome.turns) == ("failed", "r2", 4)
+
+
+async def test_submission_hold_without_headroom_only_logs() -> None:
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ tools = _submission_tools(submissions, activity, click_delivers=True)
+ script = [[("click", {"selector": "#submit"})], [("finish", {"status": "terminated", "reason": "r"})]]
+ with capture_logs() as logs:
+ outcome, _ = await _run(script, tools, activity=activity, max_turns=3)
+ assert (outcome.status, outcome.turns) == ("terminated", 2)
+ events = [e["event"] for e in logs]
+ assert "taskv3 finish would hold on an unseen submission response" in events
+ assert "taskv3 finish held on an unseen submission response" not in events
+
+
+async def test_submission_hold_waits_for_a_held_submission_then_holds() -> None:
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ record_id = submissions.hold()
+
+ async def release_soon() -> None:
+ await asyncio.sleep(0.3)
+ submissions.release(record_id)
+
+ tools = _submission_tools(submissions, activity)
+ script = [
+ [("observe", {})],
+ [("finish", {"status": "terminated", "reason": "r1"})],
+ [("finish", {"status": "terminated", "reason": "r2"})],
+ ]
+ releaser = asyncio.create_task(release_soon())
+ with capture_logs() as logs:
+ outcome, _ = await _run(script, tools, activity=activity)
+ await releaser
+ assert (outcome.status, outcome.reason) == ("terminated", "r2")
+ held = next(e for e in logs if e["event"] == "taskv3 finish held on an unseen submission response")
+ assert held["outcomes"] == ["delivered"]
+
+
+async def test_submission_hold_wait_on_a_held_submission_ends_on_cancel() -> None:
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ submissions.hold()
+
+ async def canceled() -> bool:
+ return True
+
+ finish = make_finish_tool(activity=activity, intercepted_submissions=submissions, should_cancel=canceled)
+ started = time.monotonic()
+ result = await finish.handler({"status": "terminated", "reason": "r"})
+ assert result.status == "error"
+ assert "still waiting" in result.content
+ assert time.monotonic() - started < SUBMISSION_HELD_WAIT_MAX_SECONDS / 2
+
+
+async def test_submission_hold_rechecks_headroom_after_waiting_on_a_held_submission() -> None:
+ # The wait spends deadline; a hold issued without the headroom it needs would end the run budget_exhausted.
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ record_id = submissions.hold()
+
+ async def release_soon() -> None:
+ await asyncio.sleep(0.3)
+ submissions.release(record_id)
+
+ finish = make_finish_tool(
+ activity=activity,
+ intercepted_submissions=submissions,
+ deadline_at=time.monotonic() + FAILURE_EVIDENCE_MIN_DEADLINE_HEADROOM_SECONDS + 0.2,
+ )
+ releaser = asyncio.create_task(release_soon())
+ with capture_logs() as logs:
+ result = await finish.handler({"status": "terminated", "reason": "r"})
+ await releaser
+ assert result.status == "ok"
+ events = [e["event"] for e in logs]
+ assert "taskv3 finish would hold on an unseen submission response" in events
+ assert "taskv3 finish held on an unseen submission response" not in events
+
+
+async def test_a_second_finish_in_the_held_batch_is_held_too() -> None:
+ # Neither finish in the batch has seen the hold, so the second must not stand without the re-observe.
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ tools = _submission_tools(submissions, activity, click_delivers=True)
+ script = [
+ [("observe", {})],
+ [("click", {"selector": "#submit"})],
+ [("finish", {"status": "terminated", "reason": "r1"}), ("finish", {"status": "terminated", "reason": "r2"})],
+ [("observe", {})],
+ [("finish", {"status": "terminated", "reason": "r3"})],
+ ]
+ with capture_logs() as logs:
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert (outcome.status, outcome.reason, outcome.turns) == ("terminated", "r3", 5)
+ held = [e for e in logs if e["event"] == "taskv3 finish held on an unseen submission response"]
+ assert len(held) == 1
+
+
[email protected]("status", ["terminated", "failed"])
+async def test_a_submission_released_after_the_wait_cap_is_still_shown_before_the_verdict_stands(
+ status: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # The interceptor can hold longer than the wait: the hold that fired while it was held must not spend the
+ # chance to see the response it later delivers, here behind a read that started before that response.
+ monkeypatch.setattr(loop_module, "SUBMISSION_HELD_WAIT_MAX_SECONDS", 0.2)
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ record_id = submissions.hold()
+ reads = [0]
+
+ async def observe(args: dict[str, Any]) -> ToolResult:
+ reads[0] += 1
+ if reads[0] == 2:
+ submissions.release(record_id)
+ await asyncio.sleep(SUBMISSION_RENDER_MARGIN_SECONDS + 0.2)
+ return ToolResult.ok("url=x text: 'Submit application'")
+
+ tools = [
+ ToolSpec(name="observe", description="o", parameters={}, handler=observe, compactable=True),
+ make_finish_tool(activity=activity, intercepted_submissions=submissions),
+ ]
+ script = [
+ [("observe", {})],
+ [("finish", {"status": status, "reason": "r1"})],
+ [("observe", {})],
+ [("finish", {"status": status, "reason": "r2"})],
+ [("observe", {})],
+ [("finish", {"status": status, "reason": "r3"})],
+ ]
+ with capture_logs() as logs:
+ outcome, _ = await _run(script, tools, activity=activity)
+ held = [e["outcomes"] for e in logs if e["event"] == "taskv3 finish held on an unseen submission response"]
+ assert held == [["held"], ["delivered"]]
+ assert (outcome.status, outcome.reason) == (status, "r3")
+
+
+async def test_a_submission_still_held_after_its_hold_is_not_waited_on_or_held_again(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(loop_module, "SUBMISSION_HELD_WAIT_MAX_SECONDS", 0.3)
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ submissions.hold()
+ tools = _submission_tools(submissions, activity)
+ script = [
+ [("observe", {})],
+ [("finish", {"status": "terminated", "reason": "r1"})],
+ [("finish", {"status": "terminated", "reason": "r2"})],
+ ]
+ started = time.monotonic()
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert (outcome.status, outcome.reason) == ("terminated", "r2")
+ assert time.monotonic() - started < 0.3 * 2
+
+
+async def test_a_new_response_does_not_re_wait_on_a_submission_already_held_for(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(loop_module, "SUBMISSION_HELD_WAIT_MAX_SECONDS", 0.6)
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ submissions.hold()
+ finish = make_finish_tool(activity=activity, intercepted_submissions=submissions)
+ await finish.handler({"status": "terminated", "reason": "r1"})
+ submissions.deliver()
+ activity.turn += 1
+ started = time.monotonic()
+ second = await finish.handler({"status": "terminated", "reason": "r2"})
+ assert second.status == "error" and "got the site's response" in second.content
+ assert time.monotonic() - started < 0.6
+
+
+async def test_a_late_released_submission_without_headroom_only_logs(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(loop_module, "SUBMISSION_HELD_WAIT_MAX_SECONDS", 0.2)
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ record_id = submissions.hold()
+ finish = make_finish_tool(activity=activity, intercepted_submissions=submissions)
+ first = await finish.handler({"status": "terminated", "reason": "r1"})
+ submissions.release(record_id)
+ activity.turn += 1
+ activity.final_turn_active = True
+ with capture_logs() as logs:
+ second = await finish.handler({"status": "terminated", "reason": "r2"})
+ assert (first.status, second.status) == ("error", "ok")
+ assert "taskv3 finish would hold on an unseen submission response" in [e["event"] for e in logs]
+
+
+def test_submissions_since_keeps_a_response_landing_within_the_render_margin_before_the_block() -> None:
+ # The page may still be rendering a response that landed just before the block began, so the read-start check,
+ # not the block boundary, decides whether this block saw it.
+ submissions = _FakeSubmissions()
+ started_at = time.monotonic()
+ inside = started_at - SUBMISSION_RENDER_MARGIN_SECONDS / 2
+ outside = started_at - SUBMISSION_RENDER_MARGIN_SECONDS * 2
+ for at in (outside, inside):
+ submissions.records.append(
+ InterceptedSubmission(
+ record_id=len(submissions.records) + 1,
+ outcome=SubmissionOutcome.DELIVERED,
+ started_at=at - 0.1,
+ released_at=at,
+ delivered_at=at,
+ )
+ )
+ assert [r.record_id for r in submissions_since(submissions, started_at)()] == [2]
+
+
+def test_submissions_since_drops_an_earlier_blocks_settled_records() -> None:
+ submissions = _FakeSubmissions()
+ submissions.deliver(ago=5.0)
+ submissions.hold()
+ read = submissions_since(submissions, time.monotonic() - 1.0)
+ assert [r.record_id for r in read()] == [2]
+ submissions.deliver()
+ assert [r.record_id for r in read()] == [2, 3]
+
+
@pytest.mark.asyncio
async def test_failure_gate_off_without_activity_tracker() -> None:
# Fenced like the completed-side probe: without an activity tracker (bare callers) the failure
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index 505d235f2..2fa166cfe 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import ast
import asyncio
import contextlib
+import dataclasses
import decimal
import html
import html as html_lib
@@ -43126,6 +43127,127 @@ document.getElementById('go').addEventListener('click', () => {
assert _delta_section(await observe.handler({})) is None
+@_skip_no_browser
+async def test_a_delta_whose_cap_only_held_old_lines_is_not_a_fresh_page_read() -> None:
+ # Held lines go out first and can fill the whole section, so this call's own new line is left out: the model
+ # still has not seen the page after the response, though the call's own read succeeded and found the line.
+ from skyvern.forge.taskv3.loop import ActivityRecency, make_finish_tool, run_agent_tool_loop # noqa: PLC0415
+ from tests.unit.test_taskv3_loop import _FakeSubmissions # noqa: PLC0415
+
+ html_page = """<!doctype html><html><body><button id="go" type="button">Load</button>
+<button id="more" type="button">Send</button><ul id="rows"></ul><script>
+document.getElementById('go').addEventListener('click', () => {
+ for (let i = 0; i < 40; i++) {
+ const li = document.createElement('li'); li.textContent = 'Row ' + i + ' ' + 'x'.repeat(40);
+ document.getElementById('rows').appendChild(li);
+ }
+});
+document.getElementById('more').addEventListener('click', () => {
+ const li = document.createElement('li'); li.textContent = 'Submission received ' + 'y'.repeat(90);
+ document.getElementById('rows').appendChild(li);
+});
+</script></body></html>"""
+ async with _live_page(html_page) as page:
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ tools = build_browser_tools(_fixed_page_provider(page))
+ click = _tool(tools, "click")
+
+ async def click_then_response_lands(args: dict[str, Any]) -> Any:
+ result = await click.handler(args)
+ if args.get("selector") == "#go":
+ submissions.deliver()
+ await asyncio.sleep(taskv3_loop.SUBMISSION_RENDER_MARGIN_SECONDS + 0.2)
+ return result
+
+ tools = [dataclasses.replace(t, handler=click_then_response_lands) if t.name == "click" else t for t in tools]
+ script = [
+ [("observe", {})],
+ [("click", {"selector": "#go"})],
+ [("click", {"selector": "#more"})],
+ [("finish", {"status": "terminated", "reason": "r1"})],
+ [("finish", {"status": "terminated", "reason": "r2"})],
+ ]
+ outcome = await run_agent_tool_loop(
+ llm_caller=_ScriptedCaller(script),
+ system_prompt="sys",
+ user_prompt="goal",
+ tools=tools + [make_finish_tool(activity=activity, intercepted_submissions=submissions)],
+ max_turns=10,
+ max_tool_calls=20,
+ activity=activity,
+ )
+ clicks = [m["content"] for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
+ assert "Submission received" not in clicks[1] and "Row " in clicks[1], clicks[1]
+ assert (outcome.status, outcome.reason) == ("terminated", "r2")
+
+
+@_skip_no_browser
+async def test_held_lines_flushed_after_a_failed_read_do_not_count_as_a_fresh_page_read(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Lines held from an earlier read go out with the next call even when that call cannot read the page; that
+ # result shows old text, so a submission response that landed in between is still one the model has not seen.
+ import skyvern.utils.url_validators as urlv # noqa: PLC0415
+ from skyvern.forge.taskv3.loop import ActivityRecency, make_finish_tool, run_agent_tool_loop # noqa: PLC0415
+ from tests.unit.test_taskv3_loop import _FakeSubmissions # noqa: PLC0415
+
+ monkeypatch.setattr(urlv, "validate_fetch_url", lambda url: url)
+ served = {
+ "/": """<!doctype html><html><body><button id="go" type="button">Load</button>
+<a id="broken" href="/broken">Broken</a><ul id="rows"></ul><script>
+document.getElementById('go').addEventListener('click', () => {
+ for (let i = 0; i < 40; i++) {
+ const li = document.createElement('li'); li.textContent = 'Row ' + i; document.getElementById('rows').appendChild(li);
+ }
+});
+</script></body></html>""",
+ "/broken": """<!doctype html><html><body><p>Broken page</p><script>
+Object.defineProperty(window, '__skyvern_doc_nonce', { configurable: true, get() { throw new Error('x'); }, set() {} });
+</script></body></html>""",
+ }
+ async with _live_page("") as page:
+ await page.route(
+ "http://rows.test/**",
+ lambda route: route.fulfill(body=served[urlparse(route.request.url).path], content_type="text/html"),
+ )
+ await page.goto("http://rows.test/")
+ submissions, activity = _FakeSubmissions(), ActivityRecency()
+ tools = build_browser_tools(_fixed_page_provider(page))
+ click = _tool(tools, "click")
+
+ async def click_then_response_lands(args: dict[str, Any]) -> Any:
+ result = await click.handler(args)
+ if args.get("selector") == "#go":
+ submissions.deliver()
+ await asyncio.sleep(taskv3_loop.SUBMISSION_RENDER_MARGIN_SECONDS + 0.2)
+ return result
+
+ tools = [dataclasses.replace(t, handler=click_then_response_lands) if t.name == "click" else t for t in tools]
+ script = [
+ [("observe", {})],
+ [("click", {"selector": "#go"})],
+ [("click", {"selector": "#broken"})],
+ [("finish", {"status": "terminated", "reason": "r1"})],
+ [("finish", {"status": "terminated", "reason": "r2"})],
+ ]
+ outcome = await run_agent_tool_loop(
+ llm_caller=_ScriptedCaller(script),
+ system_prompt="sys",
+ user_prompt="goal",
+ tools=tools + [make_finish_tool(activity=activity, intercepted_submissions=submissions)],
+ max_turns=10,
+ max_tool_calls=20,
+ activity=activity,
+ )
+ clicks = [m["content"] for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
+ # The second click's own read failed; all it carries is what the first click's read held back.
+ assert "before this call ran, the page newly showed" in clicks[1] and "Row 39" in clicks[1], clicks[1]
+ assert page.url == "http://rows.test/broken"
+ assert (outcome.status, outcome.reason) == ("terminated", "r2")
+
+
@_skip_no_browser
@pytest.mark.asyncio
@pytest.mark.parametrize(