Skip to content

Automate browser based workflows with AI

Show where an agent's actions go, block by block, on the agent page (#8902)

Aaron Perez34a47d501370
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.json
index 8f634dd18..ad5ae276c 100644
--- a/docs/api-reference/openapi.json
+++ b/docs/api-reference/openapi.json
@@ -14749,6 +14749,11 @@
"title": "Include Body",
"default": true
},
+ "download_attachments": {
+ "type": "boolean",
+ "title": "Download Attachments",
+ "default": false
+ },
"parameters": {
"items": {
"oneOf": [
@@ -14952,6 +14957,12 @@
"title": "Include Body",
"default": true
},
+ "download_attachments": {
+ "type": "boolean",
+ "title": "Download Attachments",
+ "description": "Download non-inline attachments from matched emails for downstream blocks.",
+ "default": false
+ },
"parameter_keys": {
"anyOf": [
{
diff --git a/fern/openapi/skyvern_openapi.json b/fern/openapi/skyvern_openapi.json
index 94e1064a9..6f637252c 100644
--- a/fern/openapi/skyvern_openapi.json
+++ b/fern/openapi/skyvern_openapi.json
@@ -14564,6 +14564,11 @@
"title": "Include Body",
"default": true
},
+ "download_attachments": {
+ "type": "boolean",
+ "title": "Download Attachments",
+ "default": false
+ },
"parameters": {
"items": {
"oneOf": [
@@ -14767,6 +14772,11 @@
"title": "Include Body",
"default": true
},
+ "download_attachments": {
+ "type": "boolean",
+ "title": "Download Attachments",
+ "default": false
+ },
"parameter_keys": {
"anyOf": [
{
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx
index 1ad20de3c..f6441eced 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx
@@ -106,6 +106,10 @@ vi.mock("./hooks/useWorkflowQuery", () => ({
}),
}));
+vi.mock("./hooks/useGlobalWorkflowsQuery", () => ({
+ useGlobalWorkflowsQuery: () => ({ data: [], isError: false }),
+}));
+
vi.mock("./hooks/useWorkflowRunsQuery", () => ({
useWorkflowRunsQuery: (props: unknown) => mockWorkflowRunsQuery(props),
}));
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
index 2f3739423..68491aa2c 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
@@ -180,9 +180,15 @@ function WorkflowPage() {
}
}, [workflowRuns, isLoading, page, searchParams, setSearchParams]);
- const { data: workflow, isLoading: workflowIsLoading } = useWorkflowQuery({
+ const {
+ data: workflow,
+ isLoading: workflowIsLoading,
+ isError: workflowIsError,
+ } = useWorkflowQuery({
workflowPermanentId,
});
+ // useWorkflowQuery stays disabled (never loading, never errored) when this one fails.
+ const { isError: globalWorkflowsIsError } = useGlobalWorkflowsQuery();
const { data: workflowTagsMap = {} } = useWorkflowTagsBatchQuery(
workflowPermanentId ? [workflowPermanentId] : [],
@@ -260,6 +266,14 @@ function WorkflowPage() {
return null; // this should never happen
}
+ const analyticsWorkflow =
+ workflow?.workflow_permanent_id === workflowPermanentId
+ ? workflow
+ : undefined;
+ // A disabled or placeholder workflow query is not loading, but its data is not this agent's yet.
+ const analyticsWorkflowIsLoading =
+ !analyticsWorkflow && !workflowIsError && !globalWorkflowsIsError;
+
return (
<div className="space-y-8">
<header className="flex flex-col gap-4">
@@ -331,7 +345,11 @@ function WorkflowPage() {
</div>
</div>
{WorkflowAnalyticsPanel ? (
- <WorkflowAnalyticsPanel workflowPermanentId={workflowPermanentId} />
+ <WorkflowAnalyticsPanel
+ workflowPermanentId={workflowPermanentId}
+ workflow={analyticsWorkflow}
+ workflowIsLoading={analyticsWorkflowIsLoading}
+ />
) : null}
<WorkflowReliabilityPanel workflowPermanentId={workflowPermanentId} />
</header>
diff --git a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts b/skyvern-frontend/src/routes/workflows/editor/helpContent.ts
index af4e06c53..53ce6efd3 100644
--- a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/helpContent.ts
@@ -137,6 +137,8 @@ export const helpTooltips = {
newerThanDays: "Only include emails newer than this many days.",
maxResults: "Maximum number of emails to return.",
includeBody: "Include email body text in matching results.",
+ downloadAttachments:
+ "Download non-inline attachments from matched emails for downstream blocks.",
},
google_sheets_write: {
...baseHelpTooltipContent,
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/EmailInboxEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/EmailInboxEditor.tsx
index 975ad462e..21a171f1e 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/EmailInboxEditor.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/EmailInboxEditor.tsx
@@ -312,6 +312,21 @@ function EmailInboxEditorBody({
}
/>
</div>
+
+ <div className="flex items-center justify-between">
+ <FieldLabel
+ field="downloadAttachments"
+ label="Download Attachments"
+ fallback="Download non-inline attachments from matched emails for downstream blocks."
+ />
+ <Switch
+ aria-label="Download Attachments"
+ checked={data.downloadAttachments}
+ onCheckedChange={(checked) =>
+ update({ downloadAttachments: checked })
+ }
+ />
+ </div>
</div>
</AccordionContent>
</AccordionItem>
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/types.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/types.ts
index da1067414..a07dae838 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/types.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/EmailInboxNode/types.ts
@@ -14,6 +14,7 @@ export type EmailInboxNodeData = NodeBaseData & {
newerThanDays: number | null;
maxResults: number;
includeBody: boolean;
+ downloadAttachments: boolean;
parameterKeys: Array<string>;
};
@@ -34,6 +35,7 @@ export const emailInboxNodeDefaultData: EmailInboxNodeData = {
newerThanDays: null,
maxResults: 25,
includeBody: true,
+ downloadAttachments: false,
parameterKeys: [],
};
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/EmailInboxBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/EmailInboxBlockForm.test.tsx
index 0f6697181..850aa908d 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/EmailInboxBlockForm.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/EmailInboxBlockForm.test.tsx
@@ -156,6 +156,18 @@ describe("EmailInboxBlockForm", () => {
});
});
+ test("enables attachment downloads from the block editor", () => {
+ render(<EmailInboxBlockForm blockId="email-1" />);
+
+ const toggle = screen.getByRole("switch", { name: "Download Attachments" });
+ expect(toggle.getAttribute("aria-checked")).toBe("false");
+ fireEvent.click(toggle);
+
+ expect(updateNodeData).toHaveBeenCalledWith("email-1", {
+ downloadAttachments: true,
+ });
+ });
+
test("replaces a stale credential parameter key", () => {
mockNodes.set("email-1", {
id: "email-1",
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/EmailInboxBlockForm.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/EmailInboxBlockForm.tsx
index 97e704c49..96069584b 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/EmailInboxBlockForm.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/EmailInboxBlockForm.tsx
@@ -39,6 +39,7 @@ function EmailInboxBlockFormBody({
newerThanDays: data.newerThanDays,
maxResults: data.maxResults,
includeBody: data.includeBody,
+ downloadAttachments: data.downloadAttachments,
parameterKeys: data.parameterKeys,
}),
[
@@ -51,6 +52,7 @@ function EmailInboxBlockFormBody({
data.newerThanDays,
data.maxResults,
data.includeBody,
+ data.downloadAttachments,
data.parameterKeys,
],
);
diff --git a/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.ts b/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.ts
index 70d37b4ab..3b4f0e6db 100644
--- a/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/sortable/roundTrip.test.ts
@@ -281,6 +281,7 @@ function makeEmailInboxBlock(
newer_than_days: null,
max_results: 25,
include_body: true,
+ download_attachments: false,
parameters,
};
}
@@ -427,6 +428,7 @@ describe("round-trip reorder → save → reload (M1 top-level)", () => {
const emailNode = nodes.find((node) => node.type === "emailInbox");
expect(emailNode?.data).toMatchObject({
parameterKeys: ["microsoft_credential_id"],
+ downloadAttachments: false,
});
const saved = getWorkflowBlocks(nodes, edges);
@@ -434,6 +436,7 @@ describe("round-trip reorder → save → reload (M1 top-level)", () => {
expect(saved[0]).toMatchObject({
block_type: "email_inbox",
parameter_keys: ["microsoft_credential_id"],
+ download_attachments: false,
});
});
diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
index 5502f7a08..220ea8681 100644
--- a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
@@ -1469,6 +1469,7 @@ function convertToNode(
newerThanDays: block.newer_than_days ?? null,
maxResults: block.max_results ?? 25,
includeBody: block.include_body ?? true,
+ downloadAttachments: block.download_attachments ?? false,
parameterKeys: (block.parameters ?? []).map((p) => p.key),
},
};
@@ -3885,6 +3886,7 @@ function getWorkflowBlock(
newer_than_days: node.data.newerThanDays,
max_results: node.data.maxResults,
include_body: node.data.includeBody,
+ download_attachments: node.data.downloadAttachments,
parameter_keys: node.data.parameterKeys,
};
}
@@ -5490,6 +5492,7 @@ function convertBlocksToBlockYAML(
newer_than_days: block.newer_than_days,
max_results: block.max_results,
include_body: block.include_body,
+ download_attachments: block.download_attachments,
parameter_keys: (block.parameters ?? []).map((p) => p.key),
};
return blockYaml;
diff --git a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
index 8bb14caab..e63258fc1 100644
--- a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
@@ -732,6 +732,7 @@ export type EmailInboxBlock = WorkflowBlockBase & {
newer_than_days: number | null;
max_results: number;
include_body: boolean;
+ download_attachments: boolean;
parameters: Array<WorkflowParameter>;
};
diff --git a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
index 8f6f293d4..29805b349 100644
--- a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
@@ -582,6 +582,7 @@ export type EmailInboxBlockYAML = BlockYAMLBase & {
newer_than_days: number | null;
max_results: number;
include_body: boolean;
+ download_attachments: boolean;
parameter_keys?: Array<string> | null;
};
diff --git a/skyvern-frontend/src/store/PageSlots.ts b/skyvern-frontend/src/store/PageSlots.ts
index 9a9d0df9f..7d9f5ba6b 100644
--- a/skyvern-frontend/src/store/PageSlots.ts
+++ b/skyvern-frontend/src/store/PageSlots.ts
@@ -1,7 +1,10 @@
import { createContext, useContext } from "react";
+import type { WorkflowApiResponse } from "@/routes/workflows/types/workflowTypes";
export type WorkflowAnalyticsPanelProps = {
workflowPermanentId: string;
+ workflow?: WorkflowApiResponse;
+ workflowIsLoading?: boolean;
};
export type WorkflowRunMilestoneCardProps = Readonly<{
workflowRunId: string;
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index dc28efa58..48fdc61ba 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -168,6 +168,7 @@ from skyvern.forge.sdk.experimentation.transient_ui_capture import (
)
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.forge_log import exception_log_fields
from skyvern.forge.sdk.log_artifacts import save_step_logs, save_task_logs
from skyvern.forge.sdk.models import SpeculativeLLMMetadata, Step, StepStatus
from skyvern.forge.sdk.schemas.files import FileInfo
@@ -321,8 +322,14 @@ from skyvern.webeye.actions.parse_actions import (
parse_ui_tars_actions,
)
from skyvern.webeye.actions.responses import STALE_TARGET_TOOL_RESULT, ActionFailure, ActionResult, ActionSuccess
-from skyvern.webeye.browser_engine import BrowserEngineSelection
-from skyvern.webeye.browser_errors import BrowserTargetClosedError
+from skyvern.webeye.browser_driver_errors import is_driver_error
+from skyvern.webeye.browser_engine import BrowserEngineSelection, is_any_engine_error
+from skyvern.webeye.browser_errors import (
+ BrowserTargetClosedError,
+ is_content_navigating_message,
+ is_context_lost_message,
+ is_target_closed_message,
+)
from skyvern.webeye.browser_state import BrowserState, get_browser_state_diagnostic
from skyvern.webeye.cdp_download_interceptor import (
consume_unsolicited_download_error_for_context,
@@ -1443,6 +1450,19 @@ def _task_v3_run_secret_values(task: Task) -> set[str]:
)
+def _is_transient_page_read_refusal(exc: BaseException) -> bool:
+ """Whether a browser refused a read because the page closed, is mid-navigation, or lost the
+ document's context. Matched on the message across every driver family the image can hold,
+ because these refusals arrive carrying more than one of those identities.
+ """
+ if not (is_driver_error(exc) or is_any_engine_error(exc)):
+ return False
+ message = str(exc)
+ return (
+ is_target_closed_message(message) or is_content_navigating_message(message) or is_context_lost_message(message)
+ )
+
+
async def _settle_before_post_action_screenshot(browser_state: BrowserState) -> None:
# Never raises: `safe_wait_for_animation_end` swallows its own timeout, and a page or frame this
# cannot reach is one the capture that follows has to handle anyway.
@@ -7106,6 +7126,7 @@ class ForgeAgent:
exc_info=True,
)
+ html: str | None = None
try:
if skyvern_frame is None:
skyvern_frame = await SkyvernFrame.create_instance(
@@ -7113,30 +7134,43 @@ class ForgeAgent:
engine_selection=browser_state.engine_selection,
)
html = await skyvern_frame.get_content()
- _ctx = skyvern_context.current()
- # Encode once to fix the html_bytes char-vs-byte mismatch and avoid a
- # second pass through html.encode() in the chosen branch.
- html_bytes = html.encode("utf-8")
- _bundled = bool(step and not step.is_speculative and _ctx)
- _tracer = otel_trace.get_tracer("skyvern")
- with traced_span(_tracer, "skyvern.agent.artifact.html_action") as _html_art_span:
- apply_context_attrs(_html_art_span)
- _html_art_span.set_attribute("html_bytes", len(html_bytes))
- _html_art_span.set_attribute("bundled", _bundled)
- if _bundled:
- app.ARTIFACT_MANAGER.accumulate_action_html_to_archive(step=step, html_action=html_bytes)
- else:
- artifacts.append(
- await app.ARTIFACT_MANAGER.prepare_llm_artifact(
- data=html_bytes,
- artifact_type=ArtifactType.HTML_ACTION,
- step=step,
- )
- )
- except SkyvernPageAnalysisTimeout:
+ except (SkyvernPageAnalysisTimeout, TimeoutError):
+ # get_content bounds frame.content() with asyncio.timeout, which raises the builtin TimeoutError.
LOG.warning("Timed out reading the post-action html, skipping it")
- except Exception:
- LOG.exception("Failed to record html after action")
+ except Exception as e:
+ if _is_transient_page_read_refusal(e):
+ LOG.warning(
+ "Skipping the post-action html because the page closed or was mid-navigation",
+ error=str(e),
+ **exception_log_fields(e),
+ )
+ else:
+ LOG.exception("Failed to read the post-action html")
+
+ if html is not None:
+ try:
+ _ctx = skyvern_context.current()
+ # Encode once to fix the html_bytes char-vs-byte mismatch and avoid a
+ # second pass through html.encode() in the chosen branch.
+ html_bytes = html.encode("utf-8")
+ _bundled = bool(step and not step.is_speculative and _ctx)
+ _tracer = otel_trace.get_tracer("skyvern")
+ with traced_span(_tracer, "skyvern.agent.artifact.html_action") as _html_art_span:
+ apply_context_attrs(_html_art_span)
+ _html_art_span.set_attribute("html_bytes", len(html_bytes))
+ _html_art_span.set_attribute("bundled", _bundled)
+ if _bundled:
+ app.ARTIFACT_MANAGER.accumulate_action_html_to_archive(step=step, html_action=html_bytes)
+ else:
+ artifacts.append(
+ await app.ARTIFACT_MANAGER.prepare_llm_artifact(
+ data=html_bytes,
+ artifact_type=ArtifactType.HTML_ACTION,
+ step=step,
+ )
+ )
+ except Exception:
+ LOG.exception("Failed to record html after action")
if artifacts:
_tracer = otel_trace.get_tracer("skyvern")
diff --git a/skyvern/forge/sdk/db/exceptions.py b/skyvern/forge/sdk/db/exceptions.py
index a569d59aa..8d8c64279 100644
--- a/skyvern/forge/sdk/db/exceptions.py
+++ b/skyvern/forge/sdk/db/exceptions.py
@@ -32,6 +32,20 @@ class NotFoundError(Exception):
pass
+class RunsListSearchCanceled(Exception):
+ """A statement timeout cancelled the statement carrying a runs-list search filter.
+
+ Raised for that statement only, so a cancellation anywhere else in the same request keeps its
+ own error and its own logging. ``statement_timeout_seconds`` is the budget that applied, or
+ None when the read ran under the connection's own timeout.
+ """
+
+ def __init__(self, *, indexed_search: bool, statement_timeout_seconds: float | None) -> None:
+ super().__init__("A runs list search statement was cancelled")
+ self.indexed_search = indexed_search
+ self.statement_timeout_seconds = statement_timeout_seconds
+
+
class DuplicateCopilotTurnError(Exception):
def __init__(self, turn_id: str) -> None:
super().__init__(f"Copilot turn {turn_id} already owns this idempotency key")
diff --git a/skyvern/forge/sdk/db/repositories/browser_sessions.py b/skyvern/forge/sdk/db/repositories/browser_sessions.py
index d068d30ff..97044b551 100644
--- a/skyvern/forge/sdk/db/repositories/browser_sessions.py
+++ b/skyvern/forge/sdk/db/repositories/browser_sessions.py
@@ -769,7 +769,8 @@ class BrowserSessionsRepository(BaseRepository):
return PersistentBrowserSession.model_validate(persistent_browser_session)
return None
- @db_operation("get_persistent_browser_session")
+ @read_retry()
+ @db_operation("get_persistent_browser_session", log_errors=False)
async def get_persistent_browser_session(
self,
session_id: str,
diff --git a/skyvern/forge/sdk/db/repositories/workflow_runs.py b/skyvern/forge/sdk/db/repositories/workflow_runs.py
index fdafe70b1..6bb0a9ce4 100644
--- a/skyvern/forge/sdk/db/repositories/workflow_runs.py
+++ b/skyvern/forge/sdk/db/repositories/workflow_runs.py
@@ -52,7 +52,7 @@ from skyvern.forge.sdk.db.base_alchemy_db import read_retry
from skyvern.forge.sdk.db.base_repository import BaseRepository
from skyvern.forge.sdk.db.datetime_utils import naive_utc_now, to_naive_utc
from skyvern.forge.sdk.db.enums import DispatchFinalizationStatus, WorkflowRunTriggerType
-from skyvern.forge.sdk.db.exceptions import NotFoundError
+from skyvern.forge.sdk.db.exceptions import NotFoundError, RunsListSearchCanceled
from skyvern.forge.sdk.db.id import BROWSER_PROFILE_PREFIX, CREDENTIAL_PREFIX, PERSISTENT_BROWSER_SESSION_ID
from skyvern.forge.sdk.db.statement_timeout import apply_statement_timeout, is_statement_timeout
from skyvern.forge.sdk.db.tag_filters import run_tag_run_id_subqueries
@@ -155,6 +155,17 @@ def is_indexed_runs_list_search_key(search_key: str) -> bool:
return _runs_list_search_id_prefix(search_key) in (BROWSER_PROFILE_PREFIX, PERSISTENT_BROWSER_SESSION_ID)
+def _is_bounded_runs_list_read(session: AsyncSession, search_key: str | None) -> bool:
+ """Whether a runs-list read runs under ``RUNS_LIST_STATEMENT_TIMEOUT_SECONDS``.
+
+ Only the unindexed free-text search is capped: query plans for the other filter shapes are not
+ known, and a complete browser identifier resolves through an indexed equality lookup.
+ """
+ if not search_key or is_indexed_runs_list_search_key(search_key):
+ return False
+ return session.bind.dialect.name == "postgresql"
+
+
@dataclass(frozen=True)
class WorkflowRunDispatchFinalization:
disposition: Literal["accepted", "already_terminal", "denied"]
@@ -1662,13 +1673,7 @@ class WorkflowRunsRepository(BaseRepository):
exc.hide_parameters = True
raise
- # Only cap the unindexed free-text search until query plans for other filter shapes are known.
- bounded_read = (
- session.bind.dialect.name == "postgresql"
- and search_key is not None
- and search_key != ""
- and not is_indexed_runs_list_search_key(search_key)
- )
+ bounded_read = _is_bounded_runs_list_read(session, search_key)
if bounded_read:
# Start after checkout so pool wait does not consume the connection-hold budget.
await session.connection()
@@ -3131,7 +3136,7 @@ class WorkflowRunsRepository(BaseRepository):
workflow_runs = (await session.scalars(query)).all()
return [convert_to_workflow_run(workflow_run) for workflow_run in workflow_runs]
- @db_operation("get_workflow_runs_for_workflow_permanent_id")
+ @db_operation("get_workflow_runs_for_workflow_permanent_id", expected_errors=(RunsListSearchCanceled,))
async def get_workflow_runs_for_workflow_permanent_id(
self,
workflow_permanent_id: str,
@@ -3151,6 +3156,12 @@ class WorkflowRunsRepository(BaseRepository):
and complete browser or credential identifiers.
"""
async with self.Session() as session:
+ statement_timeout_seconds: float | None = None
+ if _is_bounded_runs_list_read(session, search_key):
+ # Start after checkout so pool wait does not consume the connection-hold budget.
+ await session.connection()
+ statement_timeout_seconds = RUNS_LIST_STATEMENT_TIMEOUT_SECONDS
+ await apply_statement_timeout(session, statement_timeout_seconds)
db_page = page - 1 # offset logic is 0 based
query = (
select(WorkflowRunModel, WorkflowModel.title)
@@ -3172,7 +3183,18 @@ class WorkflowRunsRepository(BaseRepository):
for subquery in run_tag_run_id_subqueries(run_tags, organization_id):
query = query.filter(WorkflowRunModel.workflow_run_id.in_(subquery))
query = query.order_by(WorkflowRunModel.created_at.desc()).limit(page_size).offset(db_page * page_size)
- workflow_runs_and_titles_tuples = (await session.execute(query)).all()
+ try:
+ workflow_runs_and_titles_tuples = (await session.execute(query)).all()
+ except StatementError as exc:
+ if not search_key or not is_statement_timeout(exc):
+ raise
+ # Typed for the route to report, and only for this statement: a cancellation in any
+ # other query of the request is not the search's and keeps its own error and log.
+ exc.hide_parameters = True
+ raise RunsListSearchCanceled(
+ indexed_search=is_indexed_runs_list_search_key(search_key),
+ statement_timeout_seconds=statement_timeout_seconds,
+ ) from exc
workflow_runs = [
convert_to_workflow_run(run, workflow_title=title, debug_enabled=self.debug_enabled)
for run, title in workflow_runs_and_titles_tuples
diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.py
index 7a1c034c4..36f924301 100644
--- a/skyvern/forge/sdk/routes/agent_protocol.py
+++ b/skyvern/forge/sdk/routes/agent_protocol.py
@@ -71,6 +71,7 @@ from skyvern.forge.sdk.db.enums import (
OrganizationAuthTokenType,
is_job_recipe_workflow_run_trigger_type,
)
+from skyvern.forge.sdk.db.exceptions import RunsListSearchCanceled
from skyvern.forge.sdk.db.repositories.tags import (
RunTagWorkflowRunMismatch,
TagValueAlreadyExists,
@@ -4565,28 +4566,33 @@ async def _parse_and_gate_tag_filter_terms(
_RUNS_LIST_TIMEOUT_RETRY_AFTER_SECONDS = 15
+_RUNS_LIST_SEARCH_TIMEOUT_DETAIL = (
+ "Free-text run search exceeded its time limit. Try an exact browser profile or session ID."
+)
+_WORKFLOW_RUNS_SEARCH_TIMEOUT_DETAIL = (
+ "Free-text run search exceeded its time limit. Retry with a created_at_start/created_at_end "
+ "window of a few weeks or less, or search an exact browser profile or session ID."
+)
-def _runs_list_filter_names(
- *,
- status: list[RunStatus] | None,
- search_key: str | None,
- run_type: list[RunType] | None,
- workflow_permanent_id: list[str] | None,
- tags: list[str] | None,
- failure_category: str | None,
-) -> list[str]:
+def _runs_list_filter_names(**filters: object | None) -> list[str]:
"""Names of the filters the request carried. Never the values: a search term, tag or agent id can
be customer data, and the name alone identifies which query shape was slow."""
- supplied: dict[str, object | None] = {
- "status": status,
- "search_key": search_key,
- "run_type": run_type,
- "workflow_permanent_id": workflow_permanent_id,
- "tags": tags,
- "failure_category": failure_category,
- }
- return sorted(name for name, value in supplied.items() if value)
+ return sorted(name for name, value in filters.items() if value)
+
+
+def _runs_list_timeout_error(*, indexed_search: bool, search_detail: str) -> HTTPException:
+ """The client-facing form of a runs-list search that ran out of time. An unindexed free-text
+ search is the caller's to narrow; an exact browser identifier resolves through indexed equality
+ lookups, so its timeout is transient and retryable."""
+ if not indexed_search:
+ # Do not suggest a rarer substring: the unindexed search can still walk the whole org.
+ return HTTPException(status_code=http_status.HTTP_400_BAD_REQUEST, detail=search_detail)
+ return HTTPException(
+ status_code=http_status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail="This run list could not be computed in time. Please retry shortly.",
+ headers={"Retry-After": str(_RUNS_LIST_TIMEOUT_RETRY_AFTER_SECONDS)},
+ )
# NOTE: v2 returns TaskRunListItem from the unified task_runs table,
@@ -4688,6 +4694,7 @@ async def get_runs_v2(
except SQLAlchemyError as exc:
if not is_statement_timeout(exc) or not search_key:
raise
+ indexed_search = is_indexed_runs_list_search_key(search_key)
LOG.warning(
"runs_list_statement_timeout",
organization_id=current_org.organization_id,
@@ -4702,19 +4709,13 @@ async def get_runs_v2(
),
page=page,
page_size=page_size,
- statement_timeout_seconds=RUNS_LIST_STATEMENT_TIMEOUT_SECONDS,
+ # Null for an indexed identifier search: it is not capped, so it ran under the
+ # connection's own timeout rather than this budget.
+ statement_timeout_seconds=None if indexed_search else RUNS_LIST_STATEMENT_TIMEOUT_SECONDS,
)
- if not is_indexed_runs_list_search_key(search_key):
- # Do not suggest a rarer substring: the unindexed search can still walk the whole org.
- raise HTTPException(
- status_code=http_status.HTTP_400_BAD_REQUEST,
- detail="Free-text run search exceeded its time limit. Try an exact browser profile or session ID.",
- ) from exc
- # Exact browser identifiers use indexed equality lookups; a timeout is retryable.
- raise HTTPException(
- status_code=http_status.HTTP_503_SERVICE_UNAVAILABLE,
- detail="This run list could not be computed in time. Please retry shortly.",
- headers={"Retry-After": str(_RUNS_LIST_TIMEOUT_RETRY_AFTER_SECONDS)},
+ raise _runs_list_timeout_error(
+ indexed_search=indexed_search,
+ search_detail=_RUNS_LIST_SEARCH_TIMEOUT_DETAIL,
) from exc
items = [TaskRunListItem.model_validate(row) for row in rows]
workflow_run_ids = [row["run_id"] for row in rows if row["task_run_type"] == RunType.workflow_run.value]
@@ -5138,19 +5139,45 @@ async def _get_workflow_runs_by_id(
run_tags: Sequence[tuple[str | None, str | None]] | None = None,
) -> list[WorkflowRun]:
analytics.capture("skyvern-oss-agent-workflow-runs-get")
- return await app.WORKFLOW_SERVICE.get_workflow_runs_for_workflow_permanent_id(
- workflow_permanent_id=workflow_id,
- organization_id=organization_id,
- page=page,
- page_size=page_size,
- status=status,
- search_key=search_key,
- error_code=error_code,
- exclude_child_runs=exclude_child_runs,
- created_at_start=created_at_start,
- created_at_end=created_at_end,
- run_tags=run_tags,
- )
+ try:
+ return await app.WORKFLOW_SERVICE.get_workflow_runs_for_workflow_permanent_id(
+ workflow_permanent_id=workflow_id,
+ organization_id=organization_id,
+ page=page,
+ page_size=page_size,
+ status=status,
+ search_key=search_key,
+ error_code=error_code,
+ exclude_child_runs=exclude_child_runs,
+ created_at_start=created_at_start,
+ created_at_end=created_at_end,
+ run_tags=run_tags,
+ )
+ except RunsListSearchCanceled as exc:
+ # Only the search statement raises this, so a cancellation in the attempt lookup that
+ # follows it stays a server error instead of being reported as a slow search.
+ LOG.warning(
+ "runs_list_statement_timeout",
+ organization_id=organization_id,
+ workflow_permanent_id=workflow_id,
+ # Names, never values: a search term or tag can carry customer data.
+ filters=_runs_list_filter_names(
+ status=status,
+ search_key=search_key,
+ error_code=error_code,
+ created_at_start=created_at_start,
+ created_at_end=created_at_end,
+ tags=run_tags,
+ exclude_child_runs=exclude_child_runs,
+ ),
+ page=page,
+ page_size=page_size,
+ statement_timeout_seconds=exc.statement_timeout_seconds,
+ )
+ raise _runs_list_timeout_error(
+ indexed_search=exc.indexed_search,
+ search_detail=_WORKFLOW_RUNS_SEARCH_TIMEOUT_DETAIL,
+ ) from exc
@base_router.get(
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index c22c09599..699eb816c 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -655,10 +655,54 @@ def extract_file_url_from_block_output(value: Any) -> str | None:
def sanitize_filename(filename: str, default: str = "document") -> str:
- sanitized = re.sub(r'[<>:"/\\|?*]', "_", filename).strip(". ")
+ sanitized = re.sub(r'[<>:"/\\|?*\x00-\x1f\ud800-\udfff]', "_", filename).strip(". ")
return sanitized[:200] if sanitized else default
+async def register_workflow_downloads(
+ *,
+ organization_id: str | None,
+ run_download_id: str | None,
+ workflow_run_id: str,
+ workflow_run_block_id: str,
+) -> list[FileInfo]:
+ if not organization_id:
+ return []
+ try:
+ async with asyncio.timeout(SAVE_DOWNLOADED_FILES_TIMEOUT):
+ await app.STORAGE.save_downloaded_files(organization_id=organization_id, run_id=run_download_id)
+ except TimeoutError:
+ LOG.warning(
+ "Timeout saving workflow downloads; workflow finalization will retry",
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ )
+ return []
+ except DownloadSaveIncompleteError:
+ pass
+ except Exception:
+ LOG.warning(
+ "Failed to register workflow downloads; workflow finalization will retry",
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ exc_info=True,
+ )
+ return []
+ try:
+ async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
+ return await app.STORAGE.get_current_attempt_downloaded_files(
+ organization_id=organization_id, run_id=run_download_id
+ )
+ except Exception:
+ LOG.warning(
+ "Failed to read registered workflow downloads",
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ exc_info=True,
+ )
+ return []
+
+
class ParquetExportMixin:
"""Shared Parquet-export execution: schema-directed serialization, filename
resolution (with loop-iteration suffixing), atomic file write, and download
@@ -685,50 +729,6 @@ class ParquetExportMixin:
stem = f"{stem}-{current_index + 1:04d}"
return f"{stem}.parquet"
- async def _register_export_download(
- self,
- *,
- organization_id: str | None,
- run_download_id: str | None,
- workflow_run_id: str,
- workflow_run_block_id: str,
- ) -> list[FileInfo]:
- if not organization_id:
- return []
- try:
- async with asyncio.timeout(SAVE_DOWNLOADED_FILES_TIMEOUT):
- await app.STORAGE.save_downloaded_files(organization_id=organization_id, run_id=run_download_id)
- except asyncio.TimeoutError:
- LOG.warning(
- "Timeout saving Parquet export; workflow finalization will retry",
- workflow_run_id=workflow_run_id,
- workflow_run_block_id=workflow_run_block_id,
- )
- return []
- except DownloadSaveIncompleteError:
- pass
- except Exception:
- LOG.warning(
- "Failed to register Parquet export; workflow finalization will retry",
- workflow_run_id=workflow_run_id,
- workflow_run_block_id=workflow_run_block_id,
- exc_info=True,
- )
- return []
- try:
- async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
- return await app.STORAGE.get_current_attempt_downloaded_files(
- organization_id=organization_id, run_id=run_download_id
- )
- except Exception:
- LOG.warning(
- "Failed to read registered Parquet exports",
- workflow_run_id=workflow_run_id,
- workflow_run_block_id=workflow_run_block_id,
- exc_info=True,
- )
- return []
-
async def write_parquet_export(
self,
*,
@@ -773,7 +773,7 @@ class ParquetExportMixin:
raise ParquetExportError(f"failed to write {filename}: {exc}") from exc
filename = path.name
- downloaded_files = await self._register_export_download(
+ downloaded_files = await register_workflow_downloads(
organization_id=organization_id,
run_download_id=run_download_id,
workflow_run_id=workflow_run_id,
@@ -15630,54 +15630,89 @@ class HumanInteractionBlock(BaseTaskBlock):
)
log_that_we_are_waiting = False
- # Check if timeout_seconds has elapsed
- if elapsed_time_seconds >= self.timeout_seconds:
+ # Run status is read before the session because cancel paths also close the session.
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ )
+
+ if workflow_run and workflow_run.status != WorkflowRunStatus.paused:
LOG.info(
- "Human Interaction block timeout_seconds reached",
+ "Workflow run status changed from paused",
workflow_run_id=workflow_run_id,
- elapsed_time_seconds=elapsed_time_seconds,
+ new_status=workflow_run.status,
browser_session_id=browser_session_id,
)
+ if workflow_run.status == WorkflowRunStatus.running:
+ success, status = True, BlockStatus.completed
+ elif workflow_run.status == WorkflowRunStatus.canceled:
+ success, status = False, BlockStatus.canceled
+ elif workflow_run.status == WorkflowRunStatus.terminated:
+ success, status = False, BlockStatus.terminated
+ else:
+ success, status = False, BlockStatus.failed
+ reason = f"status_changed:{workflow_run.status}"
workflow_run_context = self.get_workflow_run_context(workflow_run_id)
- success = False
- reason = "Timeout elapsed with no human interaction"
result_dict = {"success": success, "reason": reason}
await self.record_output_parameter_value(workflow_run_context, workflow_run_id, result_dict)
return await self.build_block_result(
success=success,
- failure_reason=reason,
+ failure_reason=None if success else reason,
output_parameter_value=result_dict,
- status=BlockStatus.timed_out,
+ status=status,
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
)
- workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
- workflow_run_id=workflow_run_id,
- organization_id=organization_id,
- )
+ if browser_session_id and organization_id:
+ browser_session = await app.DATABASE.browser_sessions.get_persistent_browser_session(
+ browser_session_id, organization_id
+ )
+ if browser_session and browser_session.completed_at:
+ LOG.info(
+ "Browser session closed while waiting for human interaction",
+ workflow_run_id=workflow_run_id,
+ browser_session_id=browser_session_id,
+ )
- if workflow_run and workflow_run.status != WorkflowRunStatus.paused:
+ workflow_run_context = self.get_workflow_run_context(workflow_run_id)
+ reason = "Browser session was closed while waiting for human interaction"
+ result_dict = {"success": False, "reason": reason}
+
+ await self.record_output_parameter_value(workflow_run_context, workflow_run_id, result_dict)
+
+ return await self.build_block_result(
+ success=False,
+ failure_reason=reason,
+ output_parameter_value=result_dict,
+ status=BlockStatus.failed,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ )
+
+ if elapsed_time_seconds >= self.timeout_seconds:
LOG.info(
- "Workflow run status changed from paused",
+ "Human Interaction block timeout_seconds reached",
workflow_run_id=workflow_run_id,
- new_status=workflow_run.status,
+ elapsed_time_seconds=elapsed_time_seconds,
browser_session_id=browser_session_id,
)
workflow_run_context = self.get_workflow_run_context(workflow_run_id)
- result_dict = {"success": True, "reason": f"status_changed:{workflow_run.status}"}
+ success = False
+ reason = "Timeout elapsed with no human interaction"
+ result_dict = {"success": success, "reason": reason}
await self.record_output_parameter_value(workflow_run_context, workflow_run_id, result_dict)
return await self.build_block_result(
- success=True,
- failure_reason=None,
+ success=success,
+ failure_reason=reason,
output_parameter_value=result_dict,
- status=BlockStatus.completed,
+ status=BlockStatus.timed_out,
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
)
diff --git a/skyvern/forge/sdk/workflow/models/email_inbox_block.py b/skyvern/forge/sdk/workflow/models/email_inbox_block.py
index 057e7f249..65d36c149 100644
--- a/skyvern/forge/sdk/workflow/models/email_inbox_block.py
+++ b/skyvern/forge/sdk/workflow/models/email_inbox_block.py
@@ -1,14 +1,27 @@
import asyncio
+import os
+from pathlib import Path
from typing import Any, ClassVar, Literal
+import httpx
+import structlog
+
+from skyvern.config import settings
+from skyvern.constants import BROWSER_DOWNLOADING_SUFFIX
from skyvern.forge import app
+from skyvern.forge.sdk.api.files import get_path_for_workflow_download_directory, resolve_run_download_id
+from skyvern.forge.sdk.artifact.storage.base import get_download_retry_started_at, is_file_from_retry_attempt
+from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.services import google_oauth_service
from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
-from skyvern.forge.sdk.workflow.models.block import Block
+from skyvern.forge.sdk.workflow.models.block import Block, register_workflow_downloads, sanitize_filename
from skyvern.forge.sdk.workflow.models.parameter import PARAMETER_TYPE
from skyvern.schemas.workflows import BlockResult, BlockStatus, BlockType
from skyvern.services import email
+LOG = structlog.get_logger()
+
class EmailInboxBlock(Block):
block_type: Literal[BlockType.EMAIL_INBOX] = BlockType.EMAIL_INBOX # type: ignore
@@ -22,6 +35,7 @@ class EmailInboxBlock(Block):
newer_than_days: int | None = None
max_results: int = 25
include_body: bool = True
+ download_attachments: bool = False
parameters: list[PARAMETER_TYPE] = []
TEMPLATABLE_FIELDS: ClassVar[frozenset[str]] = frozenset({"credential_id", "folder", "prompt", "sender", "subject"})
@@ -80,6 +94,172 @@ class EmailInboxBlock(Block):
results = await asyncio.gather(*(_match(candidate) for candidate in candidates))
return [candidate for candidate, matches in zip(candidates, results) if matches]
+ async def _download_matched_attachments(
+ self,
+ messages: list[email.EmailMessage],
+ *,
+ access_token: str,
+ organization_id: str,
+ workflow_run_context: WorkflowRunContext,
+ workflow_run_id: str,
+ workflow_run_block_id: str,
+ ) -> tuple[list[dict[str, Any]], list[FileInfo]]:
+ failed = next((message for message in messages if message.attachment_list_error), None)
+ if failed is not None:
+ raise email.OutlookAPIError(
+ status=502,
+ code=failed.attachment_list_error,
+ message="Could not list every attachment on a matched email",
+ )
+ email_outputs = [message.model_dump(mode="json") for message in messages]
+ if not any(message.attachments for message in messages):
+ return email_outputs, []
+
+ run_download_id = resolve_run_download_id(skyvern_context.current(), fallback_run_id=workflow_run_id)
+ download_dir = get_path_for_workflow_download_directory(run_download_id)
+ # A retried run keeps earlier attempts' files; only this attempt's files count toward the caps.
+ attempt_started_at = await get_download_retry_started_at(organization_id, run_download_id)
+ existing_files = [
+ path
+ for path in download_dir.iterdir()
+ if path.is_file()
+ and not path.is_symlink()
+ and not path.name.endswith(BROWSER_DOWNLOADING_SUFFIX)
+ and is_file_from_retry_attempt(str(path), attempt_started_at)
+ ]
+ file_count = len(existing_files)
+ run_size = sum(path.stat().st_size for path in existing_files)
+ file_limit = settings.BROWSER_DOWNLOAD_MAX_FILE_SIZE_BYTES
+ run_limit = settings.BROWSER_DOWNLOAD_MAX_RUN_SIZE_BYTES
+ count_limit = settings.BROWSER_DOWNLOAD_MAX_FILES_PER_RUN
+ loop_index = workflow_run_context.get_block_metadata(self.label).get("current_index")
+ saved_names: set[str] = set()
+
+ async with httpx.AsyncClient(timeout=20.0) as client:
+ for message, email_output in zip(messages, email_outputs):
+ attachment_outputs = email_output.get("attachments") or []
+ for attachment, attachment_output in zip(message.attachments, attachment_outputs):
+ if attachment.is_inline:
+ attachment_output["download_error"] = "inline_attachment_skipped"
+ continue
+ if not attachment.attachment_id and attachment.embedded_data is None:
+ attachment_output["download_error"] = "missing_attachment_id"
+ continue
+ if attachment.size is not None and attachment.size < 0:
+ attachment_output["download_error"] = "invalid_size"
+ continue
+ if file_count >= count_limit:
+ attachment_output["download_error"] = "file_count_limit"
+ continue
+ if attachment.size is not None:
+ if attachment.size > file_limit:
+ attachment_output["download_error"] = "file_size_limit"
+ continue
+ if run_size + attachment.size > run_limit:
+ attachment_output["download_error"] = "run_size_limit"
+ continue
+
+ try:
+ if attachment.embedded_data is not None:
+ content = email.gmail.decode_attachment_data(
+ attachment.embedded_data, max_size_bytes=file_limit
+ )
+ else:
+ content = await email.download_attachment(
+ email_client=self.email_client,
+ access_token=access_token,
+ message_id=message.id,
+ attachment_id=attachment.attachment_id or "",
+ max_size_bytes=file_limit,
+ client=client,
+ )
+ except (email.GmailAPIError, email.OutlookAPIError) as exc:
+ if exc.code == "reconnect_required":
+ safe_message = f"Reconnect the {self.email_client.title()} account to download attachments"
+ if isinstance(exc, email.GmailAPIError):
+ raise email.GmailAPIError(
+ status=exc.status, code=exc.code, message=safe_message
+ ) from exc
+ raise email.OutlookAPIError(status=exc.status, code=exc.code, message=safe_message) from exc
+ attachment_output["download_error"] = (
+ "file_size_limit" if exc.code == "file_size_limit" else "download_failed"
+ )
+ continue
+
+ if len(content) > file_limit:
+ attachment_output["download_error"] = "file_size_limit"
+ continue
+ if run_size + len(content) > run_limit:
+ attachment_output["download_error"] = "run_size_limit"
+ continue
+
+ # Split before sanitizing: its 200-character cap would otherwise cut off a long name's extension.
+ raw_stem, raw_extension = os.path.splitext(attachment.name)
+ stem = sanitize_filename(raw_stem, default="attachment")
+ extension = sanitize_filename(raw_extension, default="")
+ extension = f".{extension}" if extension else ""
+ if extension.lower() == BROWSER_DOWNLOADING_SUFFIX:
+ # The download subsystem treats this suffix as an in-progress browser download.
+ stem, extension = f"{stem}_{extension[1:]}", ""
+ # sanitize_filename bounds characters, but the filesystem limit (255) is in bytes.
+ extension = extension.encode()[:32].decode(errors="ignore")
+ stem = stem.encode()[: 200 - len(extension.encode())].decode(errors="ignore") or "attachment"
+ if isinstance(loop_index, int) and not isinstance(loop_index, bool):
+ stem = f"{stem}-{loop_index + 1:04d}"
+ suffix = 1
+ saved_path: Path | None = None
+ while True:
+ filename = f"{stem}{extension}" if suffix == 1 else f"{stem}-{suffix:04d}{extension}"
+ path = download_dir / filename
+ file_created = False
+ try:
+ with path.open("xb") as file:
+ file_created = True
+ file.write(content)
+ saved_path = path
+ break
+ except FileExistsError:
+ suffix += 1
+ except OSError:
+ attachment_output["download_error"] = "save_failed"
+ if file_created:
+ try:
+ path.unlink()
+ except FileNotFoundError:
+ pass
+ except OSError:
+ LOG.warning(
+ "Failed to remove incomplete email attachment download",
+ workflow_run_block_id=workflow_run_block_id,
+ )
+ break
+ if saved_path is None:
+ continue
+ file_count += 1
+ run_size += len(content)
+ saved_names.add(saved_path.name)
+ attachment_output["file_name"] = saved_path.name
+ attachment_output["file_path"] = str(saved_path)
+
+ registered_files = (
+ await register_workflow_downloads(
+ organization_id=organization_id,
+ run_download_id=run_download_id,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ )
+ if saved_names
+ else []
+ )
+ registered_by_name = {file.filename: file for file in registered_files if file.filename in saved_names}
+ for email_output in email_outputs:
+ for attachment_output in email_output.get("attachments") or []:
+ file_info = registered_by_name.get(attachment_output.get("file_name"))
+ if file_info:
+ attachment_output["url"] = file_info.url
+ block_files = [file for file in registered_files if file.filename in saved_names]
+ return email_outputs, block_files
+
async def execute(
self,
workflow_run_id: str,
@@ -156,6 +336,7 @@ class EmailInboxBlock(Block):
newer_than_days=self.newer_than_days,
max_results=self.max_results,
include_body=self.include_body,
+ include_attachments=self.download_attachments,
)
except email.GmailAPIError as e:
return await self._api_failure(
@@ -182,13 +363,46 @@ class EmailInboxBlock(Block):
if criteria
else candidates
)
+ emails = [message.model_dump(mode="json") for message in matched]
+ downloaded_files: list[FileInfo] = []
+ if self.download_attachments:
+ try:
+ emails, downloaded_files = await self._download_matched_attachments(
+ matched,
+ access_token=access_token,
+ organization_id=effective_org_id,
+ workflow_run_context=workflow_run_context,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ )
+ except email.GmailAPIError as e:
+ return await self._api_failure(
+ provider="Gmail",
+ exc=e,
+ workflow_run_context=workflow_run_context,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ )
+ except email.OutlookAPIError as e:
+ return await self._api_failure(
+ provider="Outlook",
+ exc=e,
+ workflow_run_context=workflow_run_context,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ )
output_data: dict[str, Any] = {
"email_client": self.email_client,
"folder": folder_used,
"candidate_count": len(candidates),
"matched_count": len(matched),
- "emails": [message.model_dump(mode="json") for message in matched],
+ "emails": emails,
}
+ if self.download_attachments:
+ output_data["downloaded_files"] = [file.model_dump() for file in downloaded_files]
+ output_data["downloaded_file_urls"] = [file.url for file in downloaded_files]
await self.record_output_parameter_value(workflow_run_context, workflow_run_id, output_data)
return await self.build_block_result(
success=True,
diff --git a/skyvern/forge/sdk/workflow/workflow_definition_converter.py b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
index 96ddcc7d0..beb31eee8 100644
--- a/skyvern/forge/sdk/workflow/workflow_definition_converter.py
+++ b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
@@ -1052,6 +1052,7 @@ def block_yaml_to_block(
newer_than_days=block_yaml.newer_than_days,
max_results=block_yaml.max_results,
include_body=block_yaml.include_body,
+ download_attachments=block_yaml.download_attachments,
parameters=email_inbox_parameters,
)
elif block_yaml.block_type == BlockType.GOOGLE_SHEETS_WRITE:
diff --git a/skyvern/schemas/emails.py b/skyvern/schemas/emails.py
index d96d62e38..531aadddb 100644
--- a/skyvern/schemas/emails.py
+++ b/skyvern/schemas/emails.py
@@ -1,6 +1,6 @@
from enum import StrEnum
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, field_validator
class EmailBodyFormat(StrEnum):
@@ -40,6 +40,15 @@ class EmailAttachment(BaseModel):
mime_type: str | None = None
size: int | None = None
attachment_id: str | None = None
+ is_inline: bool = Field(default=False, exclude=True)
+ # Gmail stores small attachment bytes in body.data instead of issuing an attachmentId.
+ embedded_data: str | None = Field(default=None, exclude=True, repr=False)
+
+ @field_validator("name")
+ @classmethod
+ def _replace_unpaired_surrogates(cls, name: str) -> str:
+ # Provider JSON can carry lone surrogates, which Postgres JSONB output rejects.
+ return name.encode("utf-8", "replace").decode("utf-8")
class EmailMessage(BaseModel):
@@ -56,5 +65,7 @@ class EmailMessage(BaseModel):
body_html: str | None = None
has_attachments: bool | None = None
attachments: list[EmailAttachment] = Field(default_factory=list)
+ # Provider error code when attachments were requested but could not all be listed.
+ attachment_list_error: str | None = Field(default=None, exclude=True)
is_read: bool = True
web_link: str | None = None
diff --git a/skyvern/schemas/workflows.py b/skyvern/schemas/workflows.py
index f4cfd4990..5d8b4285f 100644
--- a/skyvern/schemas/workflows.py
+++ b/skyvern/schemas/workflows.py
@@ -1697,6 +1697,9 @@ class EmailInboxBlockYAML(BlockYAML):
newer_than_days: int | None = None
max_results: int = 25
include_body: bool = True
+ download_attachments: bool = Field(
+ default=False, description="Download non-inline attachments from matched emails for downstream blocks."
+ )
parameter_keys: list[str] | None = None
diff --git a/skyvern/services/email/__init__.py b/skyvern/services/email/__init__.py
index 27642f4ef..0b6073bbe 100644
--- a/skyvern/services/email/__init__.py
+++ b/skyvern/services/email/__init__.py
@@ -1,6 +1,6 @@
from skyvern.services.email import gmail, outlook
from skyvern.services.email.gmail_client import GmailAPIError
-from skyvern.services.email.inbox import EmailMatchResult, list_folder_messages, match_email
+from skyvern.services.email.inbox import EmailMatchResult, download_attachment, list_folder_messages, match_email
from skyvern.services.email.outlook import OutlookAPIError
from skyvern.services.email.types import EmailAttachment, EmailMessage
@@ -10,6 +10,7 @@ __all__ = [
"EmailMessage",
"GmailAPIError",
"OutlookAPIError",
+ "download_attachment",
"gmail",
"list_folder_messages",
"match_email",
diff --git a/skyvern/services/email/gmail.py b/skyvern/services/email/gmail.py
index 2aad5180b..0d175fd79 100644
--- a/skyvern/services/email/gmail.py
+++ b/skyvern/services/email/gmail.py
@@ -1,3 +1,5 @@
+import base64
+import binascii
from dataclasses import dataclass
from datetime import timezone
from email.utils import getaddresses, parseaddr, parsedate_to_datetime
@@ -116,15 +118,28 @@ def _attachments(payload: dict[str, Any]) -> list[EmailAttachment]:
raw_body = payload.get("body")
body = raw_body if isinstance(raw_body, dict) else {}
attachment_id = body.get("attachmentId")
- if isinstance(filename, str) and filename and isinstance(attachment_id, str):
+ embedded_data = body.get("data") if not isinstance(attachment_id, str) else None
+ headers = {
+ header["name"].casefold(): header["value"]
+ for header in payload.get("headers") or []
+ if isinstance(header, dict) and isinstance(header.get("name"), str) and isinstance(header.get("value"), str)
+ }
+ disposition = headers.get("content-disposition", "").split(";", 1)[0].strip().casefold()
+ named = isinstance(filename, str) and bool(filename)
+ if (named or disposition == "attachment") and (isinstance(attachment_id, str) or isinstance(embedded_data, str)):
size = body.get("size")
mime_type = payload.get("mimeType")
+ # Content-ID alone marks a related part, but an explicit disposition wins: senders that
+ # stamp a Content-ID on a real attachment would otherwise have it skipped as inline.
+ is_inline = disposition == "inline" or (not disposition and bool(headers.get("content-id", "").strip()))
attachments.append(
EmailAttachment(
- name=filename,
+ name=filename if isinstance(filename, str) and filename else "attachment",
mime_type=mime_type if isinstance(mime_type, str) else None,
size=size if isinstance(size, int) else None,
- attachment_id=attachment_id,
+ attachment_id=attachment_id if isinstance(attachment_id, str) else None,
+ is_inline=is_inline,
+ embedded_data=embedded_data if isinstance(embedded_data, str) else None,
)
)
for part in payload.get("parts") or []:
@@ -153,7 +168,9 @@ def _date_header_to_iso(value: str | None) -> str | None:
return parsed.astimezone(timezone.utc).isoformat()
-def _message_from_gmail(message: dict[str, Any], include_body: bool) -> EmailMessage | None:
+def _message_from_gmail(
+ message: dict[str, Any], include_body: bool, *, include_attachments: bool = False
+) -> EmailMessage | None:
message_id = message.get("id")
if not isinstance(message_id, str):
return None
@@ -168,7 +185,7 @@ def _message_from_gmail(message: dict[str, Any], include_body: bool) -> EmailMes
html_parts = _payload_text_by_mime(payload, {"text/html"})
body_text = "\n".join(text_parts) if text_parts else "\n".join(payload_text(payload))
body_html = "\n".join(html_parts) if html_parts else None
- attachments = _attachments(payload) if include_body else []
+ attachments = _attachments(payload) if include_body or include_attachments else []
raw_label_ids = message.get("labelIds")
label_ids = raw_label_ids if isinstance(raw_label_ids, list) else []
thread_id = message.get("threadId") if isinstance(message.get("threadId"), str) else None
@@ -185,7 +202,7 @@ def _message_from_gmail(message: dict[str, Any], include_body: bool) -> EmailMes
snippet=message.get("snippet") if isinstance(message.get("snippet"), str) else "",
body_text=body_text,
body_html=body_html,
- has_attachments=bool(attachments) if include_body else None,
+ has_attachments=bool(attachments) if include_body or include_attachments else None,
attachments=attachments,
is_read="UNREAD" not in label_ids,
web_link=f"https://mail.google.com/mail/u/0/#all/{link_id}",
@@ -205,6 +222,7 @@ async def list_folder_messages(
newer_than_days: int | None = None,
max_results: int = 25,
include_body: bool = True,
+ include_attachments: bool = False,
client: httpx.AsyncClient | None = None,
) -> list[EmailMessage]:
async def _list(client_: httpx.AsyncClient) -> list[EmailMessage]:
@@ -233,17 +251,81 @@ async def list_folder_messages(
client_,
f"{GMAIL_API_BASE}/users/me/messages/{quote(message_id, safe='')}",
access_token=access_token,
- params={"format": "full" if include_body else "metadata"},
+ params={"format": "full" if include_body or include_attachments else "metadata"},
)
- normalized = _message_from_gmail(message, include_body)
+ normalized = _message_from_gmail(message, include_body, include_attachments=include_attachments)
if normalized:
messages.append(normalized)
return messages
+ try:
+ if client is None:
+ async with httpx.AsyncClient(timeout=20.0) as owned_client:
+ return await _list(owned_client)
+ return await _list(client)
+ except GmailAPIError as exc:
+ if include_attachments and exc.status == 401 and exc.code != "reconnect_required":
+ raise GmailAPIError(
+ status=exc.status,
+ code="reconnect_required",
+ message="Gmail attachment access requires reconnecting",
+ ) from exc
+ raise
+
+
+async def download_attachment(
+ *,
+ access_token: str,
+ message_id: str,
+ attachment_id: str,
+ max_size_bytes: int | None = None,
+ client: httpx.AsyncClient | None = None,
+) -> bytes:
+ async def _download(client_: httpx.AsyncClient) -> bytes:
+ try:
+ payload = await get_json(
+ client_,
+ f"{GMAIL_API_BASE}/users/me/messages/{quote(message_id, safe='')}/attachments/{quote(attachment_id, safe='')}",
+ access_token=access_token,
+ )
+ except GmailAPIError as exc:
+ if exc.status == 401 and exc.code != "reconnect_required":
+ raise GmailAPIError(
+ status=exc.status,
+ code="reconnect_required",
+ message="Gmail attachment access requires reconnecting",
+ ) from exc
+ raise
+ except (ValueError, TypeError, AttributeError) as exc:
+ raise GmailAPIError(
+ status=502, code="invalid_attachment", message="Gmail returned invalid attachment data"
+ ) from exc
+ if not isinstance(payload, dict):
+ raise GmailAPIError(status=502, code="invalid_attachment", message="Gmail returned invalid attachment data")
+ data = payload.get("data")
+ if not isinstance(data, str):
+ raise GmailAPIError(status=502, code="invalid_attachment", message="Gmail returned invalid attachment data")
+ return decode_attachment_data(data, max_size_bytes=max_size_bytes)
+
if client is None:
async with httpx.AsyncClient(timeout=20.0) as owned_client:
- return await _list(owned_client)
- return await _list(client)
+ return await _download(owned_client)
+ return await _download(client)
+
+
+def decode_attachment_data(data: str, *, max_size_bytes: int | None = None) -> bytes:
+ if max_size_bytes is not None and len(data) > 4 * ((max_size_bytes + 2) // 3):
+ raise GmailAPIError(status=413, code="file_size_limit", message="Gmail attachment exceeds the download limit")
+ try:
+ encoded = data.encode("ascii") + b"=" * (-len(data) % 4)
+ content = base64.b64decode(encoded, altchars=b"-_", validate=True)
+ except (binascii.Error, UnicodeEncodeError, ValueError) as exc:
+ raise GmailAPIError(
+ status=502, code="invalid_attachment", message="Gmail returned invalid attachment data"
+ ) from exc
+ if max_size_bytes is not None and len(content) > max_size_bytes:
+ raise GmailAPIError(status=413, code="file_size_limit", message="Gmail attachment exceeds the download limit")
+ return content
@dataclass(frozen=True)
diff --git a/skyvern/services/email/inbox.py b/skyvern/services/email/inbox.py
index 1e01f6b5f..efa22d699 100644
--- a/skyvern/services/email/inbox.py
+++ b/skyvern/services/email/inbox.py
@@ -28,6 +28,7 @@ async def list_folder_messages(
newer_than_days: int | None,
max_results: int,
include_body: bool,
+ include_attachments: bool = False,
client: httpx.AsyncClient | None = None,
) -> list[EmailMessage]:
if email_client == "gmail":
@@ -39,6 +40,7 @@ async def list_folder_messages(
newer_than_days=newer_than_days,
max_results=max_results,
include_body=include_body,
+ include_attachments=include_attachments,
client=client,
)
if email_client == "outlook":
@@ -50,6 +52,35 @@ async def list_folder_messages(
newer_than_days=newer_than_days,
max_results=max_results,
include_body=include_body,
+ include_attachments=include_attachments,
+ client=client,
+ )
+ raise ValueError(f"Unsupported email_client: {email_client}")
+
+
+async def download_attachment(
+ *,
+ email_client: str,
+ access_token: str,
+ message_id: str,
+ attachment_id: str,
+ max_size_bytes: int,
+ client: httpx.AsyncClient | None = None,
+) -> bytes:
+ if email_client == "gmail":
+ return await gmail.download_attachment(
+ access_token=access_token,
+ message_id=message_id,
+ attachment_id=attachment_id,
+ max_size_bytes=max_size_bytes,
+ client=client,
+ )
+ if email_client == "outlook":
+ return await outlook.download_attachment(
+ access_token=access_token,
+ message_id=message_id,
+ attachment_id=attachment_id,
+ max_size_bytes=max_size_bytes,
client=client,
)
raise ValueError(f"Unsupported email_client: {email_client}")
diff --git a/skyvern/services/email/outlook.py b/skyvern/services/email/outlook.py
index c1d0bfb7d..ebedd938f 100644
--- a/skyvern/services/email/outlook.py
+++ b/skyvern/services/email/outlook.py
@@ -136,6 +136,78 @@ async def _get_json(
raise OutlookAPIError(status=response.status_code, code=code, message=message)
+async def download_attachment(
+ *,
+ access_token: str,
+ message_id: str,
+ attachment_id: str,
+ max_size_bytes: int,
+ client: httpx.AsyncClient | None = None,
+) -> bytes:
+ async def _download(client_: httpx.AsyncClient) -> bytes:
+ url = (
+ f"{GRAPH_API_BASE}/me/messages/{quote(message_id, safe='')}/attachments/"
+ f"{quote(attachment_id, safe='')}/$value"
+ )
+ for attempt in range(1, _MAX_ATTEMPTS + 1):
+ try:
+ async with client_.stream(
+ "GET",
+ url,
+ headers={"Authorization": f"Bearer {access_token}", "Accept": "application/octet-stream"},
+ ) as response:
+ if response.status_code in _RETRYABLE_STATUSES and attempt < _MAX_ATTEMPTS:
+ retry_after = response.headers.get("Retry-After")
+ elif response.is_success:
+ body = bytearray()
+ chunks = response.aiter_bytes()
+ try:
+ async for chunk in chunks:
+ body.extend(chunk)
+ if len(body) > max_size_bytes:
+ raise OutlookAPIError(
+ status=413,
+ code="file_size_limit",
+ message="Outlook attachment exceeded the configured download limit",
+ )
+ finally:
+ await chunks.aclose()
+ return bytes(body)
+ else:
+ await response.aread()
+ try:
+ error = response.json().get("error")
+ code = error.get("code") if isinstance(error, dict) else None
+ except (ValueError, AttributeError):
+ code = None
+ if response.status_code == 401 or (
+ response.status_code == 403
+ and isinstance(code, str)
+ and code.casefold() in _RECONNECT_ERROR_CODES
+ ):
+ code = "reconnect_required"
+ raise OutlookAPIError(
+ status=response.status_code,
+ code=code,
+ message=f"Microsoft Graph attachment fetch failed (HTTP {response.status_code})",
+ )
+ except (httpx.TransportError, httpx.TimeoutException) as exc:
+ if attempt == _MAX_ATTEMPTS:
+ raise OutlookAPIError(
+ status=503, code="upstream_unavailable", message="Microsoft Graph attachment fetch failed"
+ ) from exc
+ retry_after = None
+ await asyncio.sleep(_compute_backoff(attempt, retry_after))
+ raise OutlookAPIError(
+ status=503, code="upstream_unavailable", message="Microsoft Graph attachment fetch failed"
+ )
+
+ if client is None:
+ async with httpx.AsyncClient(timeout=20.0) as owned_client:
+ return await _download(owned_client)
+ return await _download(client)
+
+
async def fetch_primary_account_email(
*,
access_token: str,
@@ -703,11 +775,13 @@ async def _attachments(
*,
access_token: str,
message_id: str,
+ raise_errors: bool = False,
) -> list[EmailAttachment]:
attachments: list[EmailAttachment] = []
request_url: str | None = f"{GRAPH_API_BASE}/me/messages/{quote(message_id, safe='')}/attachments"
- request_params: dict[str, Any] | None = {"$select": "id,name,contentType,size"}
+ request_params: dict[str, Any] | None = {"$select": "id,name,contentType,size,isInline"}
page_count = 0
+ raw_next_link: object = None
try:
while request_url and page_count < _MAX_ATTACHMENT_PAGES:
payload = await _get_json(client, request_url, access_token=access_token, params=request_params)
@@ -727,12 +801,22 @@ async def _attachments(
mime_type=content_type if isinstance(content_type, str) else None,
size=size if isinstance(size, int) else None,
attachment_id=attachment_id if isinstance(attachment_id, str) else None,
+ is_inline=bool(item.get("isInline")),
)
)
- request_url = _validated_next_link(payload.get("@odata.nextLink"))
+ raw_next_link = payload.get("@odata.nextLink")
+ request_url = _validated_next_link(raw_next_link)
request_params = None
+ # Checks the raw link: a page cap or a rejected continuation both leave attachments unlisted.
+ if raw_next_link and raise_errors:
+ raise OutlookAPIError(
+ status=413,
+ code="attachment_list_truncated",
+ message="Not every attachment on the message could be listed for download",
+ )
except OutlookAPIError as exc:
- if exc.code == "reconnect_required":
+ # A requested download must not look like an attachment-free message.
+ if exc.code == "reconnect_required" or raise_errors:
raise
LOG.warning(
"Failed to fetch Outlook message attachments",
@@ -810,6 +894,7 @@ async def list_folder_messages(
newer_than_days: int | None = None,
max_results: int = 25,
include_body: bool = True,
+ include_attachments: bool = False,
client: httpx.AsyncClient | None = None,
) -> list[EmailMessage]:
async def _list(client_: httpx.AsyncClient) -> list[EmailMessage]:
@@ -860,10 +945,24 @@ async def list_folder_messages(
continue
message_id = item.get("id")
item_attachments: list[EmailAttachment] = []
- if include_body and bool(item.get("hasAttachments")) and isinstance(message_id, str):
- item_attachments = await _attachments(client_, access_token=access_token, message_id=message_id)
+ attachment_list_error: str | None = None
+ if (
+ (include_body or include_attachments)
+ and bool(item.get("hasAttachments"))
+ and isinstance(message_id, str)
+ ):
+ try:
+ item_attachments = await _attachments(
+ client_, access_token=access_token, message_id=message_id, raise_errors=include_attachments
+ )
+ except OutlookAPIError as exc:
+ if exc.code == "reconnect_required":
+ raise
+ # Recorded rather than raised: only a message that later matches should fail the block.
+ attachment_list_error = exc.code or "attachment_list_failed"
message = _message_from_graph(item, item_attachments, include_body=include_body)
if message:
+ message.attachment_list_error = attachment_list_error
messages.append(message)
if len(messages) >= max_results_clamped:
break
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index 8109233ec..46c54e672 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -404,6 +404,11 @@ class CustomSelectFamilyOutcome(StrEnum):
terminal_unverified_toggle = "terminal_unverified_toggle"
+# Wall clock a date-related custom-select cascade may spend walking levels. Each level costs an LLM
+# round trip, so bounding the walk by time rather than by level count keeps a cheap deep walk (a
+# calendar stepped one month per click) while stopping a walk that cannot finish inside the action
+# execution deadline — the deadline cancels the action, which skips every recovery below.
+DATEPICKER_WALK_BUDGET_SECONDS = 300.0
DOWNLOAD_EVENT_ACTIVE_DIR_GRACE_SECONDS = 60
DOWNLOAD_IN_FLIGHT_EXTENSION_MAX_SECONDS = 120
DOWNLOAD_IN_FLIGHT_POLL_INTERVAL_SECONDS = 1.0
@@ -13134,10 +13139,16 @@ async def sequentially_select_from_dropdown(
)
return None
- # TODO: only support the third-level dropdown selection now, but for date picker, we need to support more levels as it will move the month, year, etc.
+ # A date picker takes more levels than a plain cascade since a pick can just move the month, so
+ # the count here is only a backstop: DATEPICKER_WALK_BUDGET_SECONDS is what bounds the walk.
MAX_DATEPICKER_DEPTH = 30
MAX_SELECT_DEPTH = 3
max_depth = MAX_DATEPICKER_DEPTH if input_or_select_context.is_date_related else MAX_SELECT_DEPTH
+ date_walk_deadline = (
+ asyncio.get_running_loop().time() + DATEPICKER_WALK_BUDGET_SECONDS
+ if input_or_select_context.is_date_related
+ else None
+ )
values: list[str | None] = []
select_history: list[CustomSingleSelectResult] = []
single_select_result: CustomSingleSelectResult | None = None
@@ -13185,6 +13196,14 @@ async def sequentially_select_from_dropdown(
)
break
+ if date_walk_deadline is not None and asyncio.get_running_loop().time() >= date_walk_deadline:
+ LOG.warning(
+ "Date selection spent its walk budget without finishing",
+ depth=i,
+ budget_seconds=DATEPICKER_WALK_BUDGET_SECONDS,
+ )
+ break
+
LOG.info(
"Seems to be a multi-level selection, continue to select until it finishes",
selected_time=i + 1,
@@ -13259,29 +13278,89 @@ async def sequentially_select_from_dropdown(
if json_response.get("is_mini_goal_finished", False):
LOG.info("The user has finished the selection for the current opened dropdown")
return single_select_result
- else:
- if input_or_select_context.is_date_related:
- if skyvern_element.get_tag_name() == InteractiveElement.INPUT and action.option.label:
- try:
- LOG.info("Try to input the date directly")
- await skyvern_element.input_sequentially(action.option.label)
- result = CustomSingleSelectResult(skyvern_frame=skyvern_frame)
- result.action_result = ActionSuccess()
- return result
- except Exception:
- LOG.warning(
- "Failed to input the date directly",
- exc_info=True,
- )
-
- if single_select_result and single_select_result.action_result:
- single_select_result.action_result.skip_remaining_actions = True
- return single_select_result
+ # Only a walk that ran out of budget or depth gets here: every other exit from the loop returns.
+ if input_or_select_context.is_date_related:
+ return await _give_up_date_walk(
+ skyvern_element=skyvern_element,
+ skyvern_frame=skyvern_frame,
+ date_label=action.option.label,
+ entry_action_type=entry_action_type,
+ target_value=target_value,
+ # is_done() is false for every level that got here, so the menu is still open. Carrying
+ # it is what makes the input_text caller close the picker before it types.
+ dropdown_menu=single_select_result.dropdown_menu if single_select_result else None,
+ task=task,
+ step=step,
+ )
return select_history[-1] if len(select_history) > 0 else None
+async def _give_up_date_walk(
+ *,
+ skyvern_element: SkyvernElement,
+ skyvern_frame: SkyvernFrame,
+ date_label: str | None,
+ entry_action_type: str,
+ target_value: str,
+ dropdown_menu: SkyvernElement | None,
+ task: Task,
+ step: Step,
+) -> CustomSingleSelectResult:
+ """End an unfinished date cascade without claiming a date that was never set.
+
+ The levels already clicked leave the picker open over a field that may still hold its old
+ value, so the only safe way to report this is a failure, except where this function can both
+ clear and type the date itself.
+ """
+ result = CustomSingleSelectResult(skyvern_frame=skyvern_frame)
+ result.dropdown_menu = dropdown_menu
+
+ if entry_action_type == "input_text":
+ # The input_text handler resumes its own text path on a non-terminal failure: it closes the
+ # picker, refuses a readonly field and types with replace semantics. Typing here instead
+ # would append to whatever the picker left behind.
+ LOG.info("Date selection did not finish, leaving the date to the input_text fallback")
+ result.action_result = _no_element_matched_failure(
+ target_value, "Date selection did not finish within its walk budget"
+ )
+ return result
+
+ if date_label and skyvern_element.get_tag_name() == InteractiveElement.INPUT:
+ try:
+ if await skyvern_element.is_readonly(dynamic=True):
+ LOG.warning(
+ "Try to input the date on a readonly element",
+ element_id=skyvern_element.get_id(),
+ task_id=task.task_id,
+ step_id=step.step_id,
+ )
+ result.action_result = ActionFailure(InputToReadonlyElement(element_id=skyvern_element.get_id()))
+ return result
+
+ LOG.info("Try to input the date directly")
+ # input_sequentially appends a value this short, so whatever the picker left in the
+ # field has to go first or the two dates concatenate.
+ await skyvern_element.input_clear()
+ await skyvern_element.input_sequentially(date_label)
+ result.action_result = ActionSuccess()
+ return result
+
+ except Exception:
+ LOG.warning(
+ "Failed to input the date directly",
+ exc_info=True,
+ )
+
+ result.action_result, _ = _terminal_custom_select_failure(
+ target_value=target_value,
+ matched_label=None,
+ reason="Date selection did not finish within its walk budget and the date could not be typed",
+ )
+ return result
+
+
def build_sequential_select_history(history_list: list[CustomSingleSelectResult]) -> list[dict[str, Any]]:
result = [
{
diff --git a/skyvern/webeye/browser_errors.py b/skyvern/webeye/browser_errors.py
index 894c1d220..41e7cb9d4 100644
--- a/skyvern/webeye/browser_errors.py
+++ b/skyvern/webeye/browser_errors.py
@@ -38,6 +38,9 @@ _CONTEXT_LOST_MESSAGE_MARKERS = (
"execution context is not available",
"uniquecontextid not found",
)
+# Neither of the two conditions above: the target is alive and its context intact, but a navigation
+# in flight leaves a read unanswerable until the document settles.
+_CONTENT_NAVIGATING_MESSAGE_MARKERS = ("page is navigating",)
def is_target_closed_message(message: str) -> bool:
@@ -45,6 +48,11 @@ def is_target_closed_message(message: str) -> bool:
return any(marker in lowered for marker in _TARGET_CLOSED_MESSAGE_MARKERS)
+def is_content_navigating_message(message: str) -> bool:
+ lowered = message.lower()
+ return any(marker in lowered for marker in _CONTENT_NAVIGATING_MESSAGE_MARKERS)
+
+
def is_context_lost_message(message: str) -> bool:
lowered = message.lower()
return any(marker in lowered for marker in _CONTEXT_LOST_MESSAGE_MARKERS)
diff --git a/tests/unit/forge/sdk/db/test_workflow_runs_repository.py b/tests/unit/forge/sdk/db/test_workflow_runs_repository.py
index 23ad6ae47..4458bbacb 100644
--- a/tests/unit/forge/sdk/db/test_workflow_runs_repository.py
+++ b/tests/unit/forge/sdk/db/test_workflow_runs_repository.py
@@ -30,6 +30,7 @@ from skyvern.forge.sdk.artifact.models import ArtifactType
from skyvern.forge.sdk.db.agent_db import AgentDB, _build_engine
from skyvern.forge.sdk.db.datetime_utils import naive_utc_now
from skyvern.forge.sdk.db.enums import BrowserSeedSource
+from skyvern.forge.sdk.db.exceptions import RunsListSearchCanceled
from skyvern.forge.sdk.db.models import (
ArtifactModel,
Base,
@@ -4708,6 +4709,127 @@ async def test_get_all_runs_v2_does_not_cap_unmeasured_or_indexed_query_shapes(
session.connection.assert_not_awaited()
+async def test_workflow_runs_search_caps_only_the_unindexed_free_text_read(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # The per-workflow runs list runs the same unindexed substring arms as the global list, so its
+ # free-text search has to hand the connection back instead of running to the statement timeout
+ # the connection itself carries.
+ applied: list[float] = []
+
+ async def _record(_session: Any, seconds: float) -> None:
+ applied.append(seconds)
+
+ monkeypatch.setattr(workflow_runs_repository, "apply_statement_timeout", _record)
+ session = MagicMock()
+ session.bind.dialect.name = "postgresql"
+ session.connection = AsyncMock()
+ session.execute = AsyncMock(return_value=_EmptyExecuteResult())
+ repo = WorkflowRunsRepository(session_factory=lambda: _SessionContext(session), debug_enabled=False)
+
+ await repo.get_workflow_runs_for_workflow_permanent_id(
+ workflow_permanent_id="wpid_test",
+ organization_id="o_test",
+ search_key="no-such-term",
+ )
+
+ assert applied == [workflow_runs_repository.RUNS_LIST_STATEMENT_TIMEOUT_SECONDS]
+
+ # An exact browser identifier resolves through indexed equality, and the other filter shapes have
+ # unmeasured plans; neither takes the cap.
+ await repo.get_workflow_runs_for_workflow_permanent_id(
+ workflow_permanent_id="wpid_test",
+ organization_id="o_test",
+ search_key="pbs_123",
+ )
+ await repo.get_workflow_runs_for_workflow_permanent_id(
+ workflow_permanent_id="wpid_test",
+ organization_id="o_test",
+ status=[WorkflowRunStatus.failed],
+ error_code="LOGIN_FAILED",
+ )
+
+ assert applied == [workflow_runs_repository.RUNS_LIST_STATEMENT_TIMEOUT_SECONDS]
+
+
+ ("search_key", "expected_indexed", "expected_budget"),
+ [
+ ("customer-private-search", False, workflow_runs_repository.RUNS_LIST_STATEMENT_TIMEOUT_SECONDS),
+ # Never capped, so it ran under the connection's own timeout rather than this budget.
+ ("pbs_123", True, None),
+ ],
+)
+async def test_cancelled_workflow_runs_search_is_typed_and_keeps_the_term_out_of_logs(
+ search_key: str,
+ expected_indexed: bool,
+ expected_budget: float | None,
+) -> None:
+ # The route reports this cancellation, so it is raised as its own type: logging it as a
+ # SQLAlchemyError would both double-report it and put the search term in reach of the log.
+ failure = OperationalError(
+ "SELECT ... WHERE workflow_run_parameters.value ILIKE :search_key",
+ {"search_key": search_key},
+ FakeQueryCanceled("canceling statement due to statement timeout"),
+ )
+
+ async def _execute(statement: Any, *_args: Any) -> _EmptyExecuteResult:
+ # Only the search statement is cancelled; the budget's own set_config has to succeed.
+ if "set_config" in str(statement):
+ return _EmptyExecuteResult()
+ raise failure
+
+ session = MagicMock()
+ session.bind.dialect.name = "postgresql"
+ session.connection = AsyncMock()
+ session.execute = AsyncMock(side_effect=_execute)
+ repo = WorkflowRunsRepository(session_factory=lambda: _SessionContext(session), debug_enabled=False)
+
+ with capture_logs() as logs:
+ with pytest.raises(RunsListSearchCanceled) as exc_info:
+ await repo.get_workflow_runs_for_workflow_permanent_id(
+ workflow_permanent_id="wpid_test",
+ organization_id="o_test",
+ search_key=search_key,
+ )
+
+ assert exc_info.value.indexed_search is expected_indexed
+ assert exc_info.value.statement_timeout_seconds == expected_budget
+ assert failure.hide_parameters is True
+ assert search_key not in repr(logs)
+ assert not any(log.get("event") == "SQLAlchemyError" for log in logs)
+
+
+async def test_cancelled_workflow_runs_read_without_a_search_stays_a_logged_server_error() -> None:
+ # Only the search statement is capped and reported to the caller. Any other filter's
+ # cancellation keeps the operation-tagged error line that production triage queries.
+ failure = OperationalError(
+ "SELECT ... WHERE tasks.errors @> :error_code",
+ {"error_code": "LOGIN_FAILED"},
+ FakeQueryCanceled("canceling statement due to statement timeout"),
+ )
+ session = MagicMock()
+ session.bind.dialect.name = "postgresql"
+ session.connection = AsyncMock()
+ session.execute = AsyncMock(side_effect=failure)
+ repo = WorkflowRunsRepository(session_factory=lambda: _SessionContext(session), debug_enabled=False)
+
+ with capture_logs() as logs:
+ with pytest.raises(OperationalError):
+ await repo.get_workflow_runs_for_workflow_permanent_id(
+ workflow_permanent_id="wpid_test",
+ organization_id="o_test",
+ error_code="LOGIN_FAILED",
+ )
+
+ assert [log["operation"] for log in logs if log.get("event") == "SQLAlchemyError"] == [
+ "get_workflow_runs_for_workflow_permanent_id"
+ ]
+
+
@pytest.mark.asyncio
async def test_get_all_runs_v2_hides_search_parameters_on_timeout_before_retry_logging() -> None:
search_key = "customer-private-search"
diff --git a/tests/unit/test_email_inbox_block.py b/tests/unit/test_email_inbox_block.py
index 3a893d243..ca58295cf 100644
--- a/tests/unit/test_email_inbox_block.py
+++ b/tests/unit/test_email_inbox_block.py
@@ -1,6 +1,7 @@
from __future__ import annotations
-from datetime import UTC, datetime
+import json
+from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, patch
@@ -8,11 +9,12 @@ from unittest.mock import AsyncMock, patch
import pytest
from skyvern.forge import app
+from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.workflow.models.block import Block
from skyvern.forge.sdk.workflow.models.email_inbox_block import EmailInboxBlock
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter
from skyvern.forge.sdk.workflow.workflow_definition_converter import block_yaml_to_block
-from skyvern.schemas.emails import EmailMessage
+from skyvern.schemas.emails import EmailAttachment, EmailMessage
from skyvern.schemas.workflows import BlockResult, BlockStatus, EmailInboxBlockYAML, WorkflowDefinitionYAML
from skyvern.services import email
@@ -31,9 +33,10 @@ class _FakeContextForTest:
self.workflow_run_outputs: dict[str, Any] = {}
self.browser_session_id: str | None = None
self.organization_id: str | None = organization_id
+ self.block_metadata: dict[str, dict[str, Any]] = {}
def get_block_metadata(self, label: str) -> dict[str, Any]:
- return {}
+ return self.block_metadata.get(label, {})
def build_workflow_run_summary(self) -> str:
return ""
@@ -66,8 +69,10 @@ async def _execute_block_for_test(
*,
workflow_run_id: str = "wr_test",
organization_id: str = "org_1",
+ block_metadata: dict[str, dict[str, Any]] | None = None,
) -> BlockResult:
ctx = _FakeContextForTest(organization_id=organization_id)
+ ctx.block_metadata = block_metadata or {}
async def _fake_build(self: Block, **kwargs: Any) -> BlockResult:
return BlockResult(
@@ -132,6 +137,7 @@ async def test_execute_reads_gmail_messages(monkeypatch: pytest.MonkeyPatch) ->
list_messages.assert_awaited_once()
assert list_messages.await_args.kwargs["email_client"] == "gmail"
assert list_messages.await_args.kwargs["folder"] == "INBOX"
+ assert list_messages.await_args.kwargs["include_attachments"] is False
@pytest.mark.asyncio
@@ -269,6 +275,7 @@ def test_email_inbox_yaml_workflow_converts_to_runtime_block() -> None:
"newer_than_days": 7,
"max_results": 10,
"include_body": False,
+ "download_attachments": True,
}
],
}
@@ -288,3 +295,359 @@ def test_email_inbox_yaml_workflow_converts_to_runtime_block() -> None:
assert block.newer_than_days == 7
assert block.max_results == 10
assert block.include_body is False
+ assert block.download_attachments is True
+
+
+async def test_download_attachments_are_opt_in_and_preserve_the_legacy_output(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ list_messages = AsyncMock(
+ return_value=[EmailMessage(id="msg_1", attachments=[EmailAttachment(name="sample.pdf", size=4)])]
+ )
+ download_attachment = AsyncMock(return_value=b"data")
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT"))
+ )
+ monkeypatch.setattr(email, "list_folder_messages", list_messages)
+ monkeypatch.setattr(email, "download_attachment", download_attachment)
+
+ result = await _execute_block_for_test(_make_block())
+
+ assert result.success is True
+ assert result.output_parameter_value is not None
+ assert "downloaded_files" not in result.output_parameter_value
+ assert result.output_parameter_value["emails"][0]["attachments"] == [
+ {"name": "sample.pdf", "mime_type": None, "size": 4, "attachment_id": None}
+ ]
+ download_attachment.assert_not_awaited()
+
+
+async def test_downloads_matched_attachments_without_email_body_and_registers_files(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ message = EmailMessage(
+ id="msg_1",
+ attachments=[
+ EmailAttachment(name="../invoice:1.pdf", mime_type="application/pdf", size=None, attachment_id="att_1")
+ ],
+ )
+ list_messages = AsyncMock(return_value=[message])
+ download_attachment = AsyncMock(return_value=b"pdf!")
+ file_info = FileInfo(url="https://example.test/attachment", filename="_invoice_1-0003-0002.pdf")
+ save_downloaded_files = AsyncMock()
+ get_downloaded_files = AsyncMock(return_value=[file_info])
+ download_dir = tmp_path / "workflow-downloads"
+ (download_dir / "_invoice_1-0003.pdf").parent.mkdir(parents=True)
+ (download_dir / "_invoice_1-0003.pdf").write_bytes(b"old")
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT"))
+ )
+ monkeypatch.setattr(email, "list_folder_messages", list_messages)
+ monkeypatch.setattr(email, "download_attachment", download_attachment)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.email_inbox_block.get_path_for_workflow_download_directory",
+ lambda _run_id: download_dir,
+ )
+ monkeypatch.setattr(app.STORAGE, "save_downloaded_files", save_downloaded_files)
+ monkeypatch.setattr(app.STORAGE, "get_current_attempt_downloaded_files", get_downloaded_files)
+
+ result = await _execute_block_for_test(
+ _make_block(include_body=False, download_attachments=True),
+ block_metadata={"read_email": {"current_index": 2}},
+ )
+
+ assert result.success is True
+ assert result.output_parameter_value is not None
+ list_messages.assert_awaited_once()
+ assert list_messages.await_args.kwargs["include_body"] is False
+ assert list_messages.await_args.kwargs["include_attachments"] is True
+ download_attachment.assert_awaited_once()
+ assert (download_dir / "_invoice_1-0003-0002.pdf").stat().st_size == 4
+ assert result.output_parameter_value["downloaded_files"] == [file_info.model_dump()]
+ assert result.output_parameter_value["downloaded_file_urls"] == [file_info.url]
+ assert result.output_parameter_value["emails"][0]["attachments"][0] == {
+ "name": "../invoice:1.pdf",
+ "mime_type": "application/pdf",
+ "size": None,
+ "attachment_id": "att_1",
+ "file_name": "_invoice_1-0003-0002.pdf",
+ "file_path": str(download_dir / "_invoice_1-0003-0002.pdf"),
+ "url": file_info.url,
+ }
+ save_downloaded_files.assert_awaited_once_with(organization_id="org_1", run_id="wr_test")
+
+
+async def test_unknown_attachment_size_is_checked_before_saving(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
+ message = EmailMessage(
+ id="msg_1", attachments=[EmailAttachment(name="large.pdf", size=None, attachment_id="att_1")]
+ )
+ download_attachment = AsyncMock(return_value=b"too large")
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT"))
+ )
+ monkeypatch.setattr(email, "list_folder_messages", AsyncMock(return_value=[message]))
+ monkeypatch.setattr(email, "download_attachment", download_attachment)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.email_inbox_block.get_path_for_workflow_download_directory",
+ lambda _run_id: tmp_path,
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.email_inbox_block.settings.BROWSER_DOWNLOAD_MAX_FILE_SIZE_BYTES", 4
+ )
+
+ result = await _execute_block_for_test(_make_block(download_attachments=True))
+
+ assert result.success is True
+ assert result.output_parameter_value is not None
+ assert result.output_parameter_value["emails"][0]["attachments"][0]["download_error"] == "file_size_limit"
+ assert list(tmp_path.iterdir()) == []
+ download_attachment.assert_awaited_once()
+
+
+async def test_saves_gmail_embedded_attachment_with_byte_bounded_non_ascii_name(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ name = "請求書" * 40 + "\x00\ud800.pdf"
+ message = EmailMessage(
+ id="msg_1",
+ attachments=[
+ EmailAttachment(name=name, size=4, embedded_data="JVBERg"),
+ EmailAttachment(name="invoice.CRDOWNLOAD", size=4, embedded_data="JVBERg"),
+ EmailAttachment(name="a" * 250 + ".pdf", size=4, embedded_data="JVBERg"),
+ ],
+ )
+ download_attachment = AsyncMock()
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT"))
+ )
+ monkeypatch.setattr(email, "list_folder_messages", AsyncMock(return_value=[message]))
+ monkeypatch.setattr(email, "download_attachment", download_attachment)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.email_inbox_block.get_path_for_workflow_download_directory",
+ lambda _run_id: tmp_path,
+ )
+ monkeypatch.setattr(app.STORAGE, "save_downloaded_files", AsyncMock())
+ monkeypatch.setattr(app.STORAGE, "get_current_attempt_downloaded_files", AsyncMock(return_value=[]))
+
+ result = await _execute_block_for_test(_make_block(download_attachments=True))
+
+ assert result.success is True
+ assert result.output_parameter_value is not None
+ assert all("download_error" not in a for a in result.output_parameter_value["emails"][0]["attachments"])
+ json.dumps(result.output_parameter_value, ensure_ascii=False).encode()
+ assert (tmp_path / "invoice_CRDOWNLOAD").read_bytes() == b"%PDF"
+ assert (tmp_path / ("a" * 196 + ".pdf")).read_bytes() == b"%PDF"
+ [saved] = [
+ path for path in tmp_path.iterdir() if path.name != "invoice_CRDOWNLOAD" and not path.name.startswith("a")
+ ]
+ assert saved.read_bytes() == b"%PDF"
+ assert saved.suffix == ".pdf"
+ assert len(saved.name.encode()) <= 255
+ download_attachment.assert_not_awaited()
+
+
+async def test_downloads_attachments_only_for_emails_matching_prompt(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
+ messages = [
+ EmailMessage(
+ id=message_id, attachments=[EmailAttachment(name=f"{message_id}.pdf", size=1, attachment_id=message_id)]
+ )
+ for message_id in ("msg_unmatched", "msg_matched")
+ ]
+ messages[0].attachment_list_error = "ServiceUnavailable"
+
+ async def match_email(*, email: EmailMessage, **_kwargs: Any) -> bool:
+ return email.id == "msg_matched"
+
+ download_attachment = AsyncMock(return_value=b"x")
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT"))
+ )
+ monkeypatch.setattr(email, "list_folder_messages", AsyncMock(return_value=messages))
+ monkeypatch.setattr(email, "match_email", match_email)
+ monkeypatch.setattr(email, "download_attachment", download_attachment)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.email_inbox_block.get_path_for_workflow_download_directory",
+ lambda _run_id: tmp_path,
+ )
+ monkeypatch.setattr(app.STORAGE, "save_downloaded_files", AsyncMock())
+ monkeypatch.setattr(
+ app.STORAGE,
+ "get_current_attempt_downloaded_files",
+ AsyncMock(return_value=[FileInfo(url="https://example.test/matched", filename="msg_matched.pdf")]),
+ )
+
+ result = await _execute_block_for_test(
+ _make_block(prompt="match one", download_attachments=True),
+ )
+
+ assert result.success is True
+ assert result.output_parameter_value is not None
+ assert [call.kwargs["message_id"] for call in download_attachment.await_args_list] == ["msg_matched"]
+ assert [message["id"] for message in result.output_parameter_value["emails"]] == ["msg_matched"]
+
+ messages[1].attachment_list_error = "attachment_list_truncated"
+ failed = await _execute_block_for_test(_make_block(prompt="match one", download_attachments=True))
+ assert failed.success is False
+ assert "Could not list every attachment" in (failed.failure_reason or "")
+
+
+async def test_skips_inline_and_oversized_attachments_before_fetching(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ message = EmailMessage(
+ id="msg_1",
+ attachments=[
+ EmailAttachment(name="logo.png", size=2, attachment_id="inline", is_inline=True),
+ EmailAttachment(name="large.pdf", size=11, attachment_id="large"),
+ ],
+ )
+ download_attachment = AsyncMock(return_value=b"not used")
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT"))
+ )
+ monkeypatch.setattr(email, "list_folder_messages", AsyncMock(return_value=[message]))
+ monkeypatch.setattr(email, "download_attachment", download_attachment)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.email_inbox_block.get_path_for_workflow_download_directory",
+ lambda _run_id: tmp_path,
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.email_inbox_block.settings.BROWSER_DOWNLOAD_MAX_FILE_SIZE_BYTES", 10
+ )
+
+ result = await _execute_block_for_test(_make_block(download_attachments=True))
+
+ assert result.success is True
+ assert result.output_parameter_value is not None
+ attachments = result.output_parameter_value["emails"][0]["attachments"]
+ assert attachments[0]["download_error"] == "inline_attachment_skipped"
+ assert attachments[1]["download_error"] == "file_size_limit"
+ assert result.output_parameter_value["downloaded_files"] == []
+ download_attachment.assert_not_awaited()
+
+
+ ("attachment_size", "existing_file_count", "existing_file_size", "expected_error"),
+ [
+ (11, 0, 0, "file_size_limit"),
+ (5, 1, 9, "run_size_limit"),
+ (5, 3, 0, "file_count_limit"),
+ ],
+)
+async def test_attachment_downloads_respect_run_caps_before_fetch(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+ attachment_size: int,
+ existing_file_count: int,
+ existing_file_size: int,
+ expected_error: str,
+) -> None:
+ download_dir = tmp_path / "workflow-downloads"
+ download_dir.mkdir()
+ for index in range(existing_file_count):
+ (download_dir / f"existing-{index}.dat").write_bytes(b"x" * existing_file_size)
+ message = EmailMessage(
+ id="msg_1",
+ attachments=[EmailAttachment(name="sample.bin", size=attachment_size, attachment_id="att_1")],
+ )
+ download_attachment = AsyncMock(return_value=b"small")
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT"))
+ )
+ monkeypatch.setattr(email, "list_folder_messages", AsyncMock(return_value=[message]))
+ monkeypatch.setattr(email, "download_attachment", download_attachment)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.email_inbox_block.get_path_for_workflow_download_directory",
+ lambda _run_id: download_dir,
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.email_inbox_block.settings.BROWSER_DOWNLOAD_MAX_FILE_SIZE_BYTES", 10
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.email_inbox_block.settings.BROWSER_DOWNLOAD_MAX_RUN_SIZE_BYTES", 10
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.email_inbox_block.settings.BROWSER_DOWNLOAD_MAX_FILES_PER_RUN", 3
+ )
+
+ result = await _execute_block_for_test(_make_block(download_attachments=True))
+
+ assert result.success is True
+ assert result.output_parameter_value is not None
+ assert result.output_parameter_value["emails"][0]["attachments"][0]["download_error"] == expected_error
+ download_attachment.assert_not_awaited()
+ if not existing_file_count:
+ return
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.email_inbox_block.get_download_retry_started_at",
+ AsyncMock(return_value=datetime.now(UTC) + timedelta(minutes=1)),
+ )
+ monkeypatch.setattr(app.STORAGE, "save_downloaded_files", AsyncMock())
+ monkeypatch.setattr(app.STORAGE, "get_current_attempt_downloaded_files", AsyncMock(return_value=[]))
+ retried = await _execute_block_for_test(_make_block(download_attachments=True))
+ assert retried.output_parameter_value is not None
+ assert retried.output_parameter_value["emails"][0]["attachments"][0].get("download_error") != expected_error
+
+
+async def test_attachment_download_failure_does_not_fail_block(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
+ message = EmailMessage(id="msg_1", attachments=[EmailAttachment(name="sample.pdf", size=4, attachment_id="att_1")])
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT"))
+ )
+ monkeypatch.setattr(email, "list_folder_messages", AsyncMock(return_value=[message]))
+ monkeypatch.setattr(
+ email,
+ "download_attachment",
+ AsyncMock(side_effect=email.GmailAPIError(status=500, code="upstream_unavailable", message="retry later")),
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.email_inbox_block.get_path_for_workflow_download_directory",
+ lambda _run_id: tmp_path,
+ )
+
+ result = await _execute_block_for_test(_make_block(download_attachments=True))
+
+ assert result.success is True
+ assert result.output_parameter_value is not None
+ assert result.output_parameter_value["emails"][0]["attachments"][0]["download_error"] == "download_failed"
+ assert result.output_parameter_value["downloaded_files"] == []
+
+
+async def test_attachment_reconnect_required_fails_block_without_provider_message(
+ monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ message = EmailMessage(id="msg_1", attachments=[EmailAttachment(name="sample.pdf", size=4, attachment_id="att_1")])
+ monkeypatch.setattr(
+ app.AGENT_FUNCTION, "get_google_workspace_credentials", AsyncMock(return_value=SimpleNamespace(token="AT"))
+ )
+ monkeypatch.setattr(email, "list_folder_messages", AsyncMock(return_value=[message]))
+ monkeypatch.setattr(
+ email,
+ "download_attachment",
+ AsyncMock(
+ side_effect=email.GmailAPIError(status=401, code="reconnect_required", message="private provider text")
+ ),
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.email_inbox_block.get_path_for_workflow_download_directory",
+ lambda _run_id: tmp_path,
+ )
+
+ result = await _execute_block_for_test(_make_block(download_attachments=True))
+
+ assert result.success is False
+ assert result.output_parameter_value == {
+ "status_code": 401,
+ "code": "reconnect_required",
+ "error": "Reconnect the Gmail account to download attachments",
+ }
diff --git a/tests/unit/test_email_service.py b/tests/unit/test_email_service.py
index 624be3038..9a19f94f0 100644
--- a/tests/unit/test_email_service.py
+++ b/tests/unit/test_email_service.py
@@ -1,7 +1,9 @@
from __future__ import annotations
+import base64
from datetime import datetime, timedelta, timezone
from typing import Any
+from unittest.mock import AsyncMock
import httpx
import pytest
@@ -179,6 +181,130 @@ async def test_gmail_list_folder_messages_uses_escaped_query(monkeypatch: pytest
assert messages[0].web_link == "https://mail.google.com/mail/u/0/#all/thread_1"
+async def test_gmail_list_fetches_attachments_without_email_body(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list[tuple[str, dict[str, Any] | None]] = []
+
+ async def fake_get_json(
+ client: httpx.AsyncClient,
+ url: str,
+ *,
+ access_token: str,
+ params: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ del client, access_token
+ calls.append((url, params))
+ if url.endswith("/users/me/messages"):
+ return {"messages": [{"id": "msg_1"}]}
+ return {
+ "id": "msg_1",
+ "payload": {
+ "headers": [],
+ "parts": [
+ {
+ "filename": "sample.pdf",
+ "mimeType": "application/pdf",
+ "body": {"attachmentId": "att_1", "size": 4},
+ }
+ ],
+ },
+ }
+
+ monkeypatch.setattr(email.gmail, "get_json", fake_get_json)
+
+ messages = await email.gmail.list_folder_messages(access_token="AT", include_body=False, include_attachments=True)
+
+ assert calls[1][1] == {"format": "full"}
+ assert messages[0].body_text == ""
+ assert messages[0].has_attachments is True
+ assert messages[0].attachments[0].attachment_id == "att_1"
+ assert "is_inline" not in messages[0].attachments[0].model_dump(mode="json")
+
+
+async def test_gmail_list_attachment_auth_failure_requires_reconnect(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ email.gmail,
+ "get_json",
+ AsyncMock(side_effect=email.GmailAPIError(status=401, code=None, message="private provider text")),
+ )
+
+ with pytest.raises(email.GmailAPIError) as exc_info:
+ await email.gmail.list_folder_messages(access_token="AT", include_body=False, include_attachments=True)
+
+ assert exc_info.value.code == "reconnect_required"
+ assert exc_info.value.message == "Gmail attachment access requires reconnecting"
+
+
+def test_gmail_attachment_parser_marks_inline_and_content_id_parts() -> None:
+ parsed = email.gmail._attachments(
+ {
+ "parts": [
+ {
+ "filename": "logo.png",
+ "body": {"attachmentId": "inline"},
+ "headers": [{"name": "Content-Disposition", "value": "inline"}],
+ },
+ {
+ "filename": "image.png",
+ "body": {"attachmentId": "cid"},
+ "headers": [{"name": "Content-ID", "value": "<image-1>"}],
+ },
+ {
+ "filename": "statement.pdf",
+ "body": {"attachmentId": "attached-with-cid"},
+ "headers": [
+ {"name": "Content-Disposition", "value": 'attachment; filename="statement.pdf"'},
+ {"name": "Content-ID", "value": "<[email protected]>"},
+ ],
+ },
+ {"filename": "invoice.pdf", "body": {"attachmentId": "file"}},
+ {"filename": "small.txt", "body": {"data": "aGk", "size": 2}},
+ {
+ "filename": "",
+ "body": {"attachmentId": "unnamed"},
+ "headers": [{"name": "Content-Disposition", "value": "attachment"}],
+ },
+ {"filename": "", "mimeType": "text/plain", "body": {"data": "Ym9keQ"}},
+ ]
+ }
+ )
+
+ assert [attachment.is_inline for attachment in parsed] == [True, True, False, False, False, False]
+ assert parsed[-1].name == "attachment"
+ assert email.gmail.decode_attachment_data(parsed[4].embedded_data or "") == b"hi"
+
+
+async def test_gmail_download_attachment_decodes_binary_data(monkeypatch: pytest.MonkeyPatch) -> None:
+ synthetic_bytes = b"\x00\xfffixture"
+ encoded = base64.urlsafe_b64encode(synthetic_bytes).decode().rstrip("=")
+ get_json = AsyncMock(return_value={"data": encoded})
+ monkeypatch.setattr(email.gmail, "get_json", get_json)
+
+ async with httpx.AsyncClient() as client:
+ actual_bytes = await email.gmail.download_attachment(
+ access_token="AT",
+ message_id="msg_1",
+ attachment_id="att_1",
+ max_size_bytes=32,
+ client=client,
+ )
+
+ assert actual_bytes == synthetic_bytes
+ assert get_json.await_args.args[1].endswith("/messages/msg_1/attachments/att_1")
+
+
+async def test_gmail_download_attachment_rejects_invalid_payload(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(email.gmail, "get_json", AsyncMock(return_value=[]))
+
+ with pytest.raises(email.GmailAPIError) as exc_info:
+ await email.gmail.download_attachment(access_token="AT", message_id="msg_1", attachment_id="att_1")
+
+ assert exc_info.value.code == "invalid_attachment"
+
+
@pytest.mark.asyncio
async def test_gmail_list_folder_messages_sets_include_spam_trash(monkeypatch: pytest.MonkeyPatch) -> None:
captured: dict[str, str] = {}
@@ -1417,9 +1543,13 @@ async def test_outlook_attachments_follow_next_link(monkeypatch: pytest.MonkeyPa
del client, access_token
calls.append((url, params))
if url == next_link:
- return {"value": [{"id": "att_2", "name": "b.pdf", "contentType": "application/pdf", "size": 2}]}
+ return {
+ "value": [
+ {"id": "att_2", "name": "b.pdf", "contentType": "application/pdf", "size": 2, "isInline": True}
+ ]
+ }
return {
- "value": [{"id": "att_1", "name": "a.pdf", "contentType": "application/pdf", "size": 1}],
+ "value": [{"id": "att_1", "name": "a.pdf", "contentType": "application/pdf", "size": 1, "isInline": False}],
"@odata.nextLink": next_link,
}
@@ -1428,9 +1558,48 @@ async def test_outlook_attachments_follow_next_link(monkeypatch: pytest.MonkeyPa
attachments = await email.outlook._attachments(httpx.AsyncClient(), access_token="AT", message_id="msg_1")
assert [attachment.name for attachment in attachments] == ["a.pdf", "b.pdf"]
- assert calls[0][1] == {"$select": "id,name,contentType,size"}
+ assert [attachment.is_inline for attachment in attachments] == [False, True]
+ assert calls[0][1] == {"$select": "id,name,contentType,size,isInline"}
assert calls[1] == (next_link, None)
+ monkeypatch.setattr(email.outlook, "_MAX_ATTACHMENT_PAGES", 1)
+ partial = await email.outlook._attachments(httpx.AsyncClient(), access_token="AT", message_id="msg_1")
+ assert [attachment.name for attachment in partial] == ["a.pdf"]
+ with pytest.raises(email.OutlookAPIError) as exc_info:
+ await email.outlook._attachments(httpx.AsyncClient(), access_token="AT", message_id="msg_1", raise_errors=True)
+ assert exc_info.value.code == "attachment_list_truncated"
+
+
+async def test_outlook_download_attachment_streams_synthetic_bytes_and_enforces_limit() -> None:
+ synthetic_bytes = b"synthetic attachment"
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.url.path.endswith("/messages/msg_1/attachments/att_1/$value")
+ return httpx.Response(200, content=synthetic_bytes)
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ actual_bytes = await email.outlook.download_attachment(
+ access_token="AT",
+ message_id="msg_1",
+ attachment_id="att_1",
+ max_size_bytes=64,
+ client=client,
+ )
+
+ assert actual_bytes == synthetic_bytes
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ with pytest.raises(email.OutlookAPIError) as exc_info:
+ await email.outlook.download_attachment(
+ access_token="AT",
+ message_id="msg_1",
+ attachment_id="att_1",
+ max_size_bytes=4,
+ client=client,
+ )
+ assert exc_info.value.code == "file_size_limit"
+
@pytest.mark.asyncio
async def test_outlook_attachments_reject_untrusted_next_link(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -1456,6 +1625,9 @@ async def test_outlook_attachments_reject_untrusted_next_link(monkeypatch: pytes
assert [attachment.name for attachment in attachments] == ["a.pdf"]
assert len(calls) == 1
+ with pytest.raises(email.OutlookAPIError) as exc_info:
+ await email.outlook._attachments(httpx.AsyncClient(), access_token="AT", message_id="msg_1", raise_errors=True)
+ assert exc_info.value.code == "attachment_list_truncated"
@pytest.mark.asyncio
@@ -1530,3 +1702,10 @@ async def test_outlook_list_folder_messages_keeps_message_when_attachment_fetch_
assert attachment_calls == 3
assert [message.id for message in messages] == ["msg_1"]
assert messages[0].attachments == []
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
+ requested = await email.outlook.list_folder_messages(
+ access_token="AT", include_body=False, include_attachments=True, client=client
+ )
+ assert messages[0].attachment_list_error is None
+ assert requested[0].attachment_list_error == "ServiceUnavailable"
diff --git a/tests/unit/test_no_available_option.py b/tests/unit/test_no_available_option.py
index 7602fe677..f9797e56a 100644
--- a/tests/unit/test_no_available_option.py
+++ b/tests/unit/test_no_available_option.py
@@ -68,6 +68,9 @@ class _FakeAnchorElement:
self.coordinate_click = AsyncMock()
self.press_key = AsyncMock()
self.blur = AsyncMock()
+ self.input_sequentially = AsyncMock()
+ self.input_clear = AsyncMock()
+ self.is_readonly = AsyncMock(return_value=False)
def get_locator(self) -> MagicMock:
return self._locator
@@ -2380,6 +2383,152 @@ class TestSequentialSelectMarksWidgetMutation:
assert excinfo.value.widget_mutated is False
+class TestDateWalkBudget:
+ """A date cascade that never closes its picker: it has to stop on its own budget, and whatever
+ it reports has to match whether a date actually landed in the field."""
+
+ @staticmethod
+ def _unfinished_level() -> SimpleNamespace:
+ # An INPUT_TEXT level that leaves the menu open advances the walk without the
+ # confirm-finish screenshot/LLM, which is the shape a calendar-arrow click takes.
+ return SimpleNamespace(
+ action_result=handler.ActionSuccess(),
+ action_type=ActionType.INPUT_TEXT,
+ dropdown_menu=object(),
+ value="next month",
+ is_done=AsyncMock(return_value=False),
+ )
+
+ async def _walk(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ anchor_element: _FakeAnchorElement,
+ entry_action_type: str = "select_option",
+ label: str | None = "2026-11-01",
+ budget_seconds: float = 0.0,
+ ) -> tuple[object, AsyncMock]:
+ skyvern_frame = MagicMock()
+ skyvern_frame.safe_wait_for_animation_end = AsyncMock()
+ incremental_scraped = MagicMock()
+ incremental_scraped.get_incremental_element_tree = AsyncMock(return_value=[{"id": "next-level"}])
+ select_level = AsyncMock(side_effect=lambda **kwargs: self._unfinished_level())
+ monkeypatch.setattr(handler, "select_from_dropdown", select_level)
+ monkeypatch.setattr(handler, "DATEPICKER_WALK_BUDGET_SECONDS", budget_seconds)
+ action = SelectOptionAction(element_id="field-control", option=SelectOption(label=label))
+
+ result = await handler.sequentially_select_from_dropdown(
+ action=action,
+ input_or_select_context=InputOrSelectContext(field="Start date", is_required=True, is_date_related=True),
+ page=MagicMock(),
+ dom=MagicMock(),
+ skyvern_element=anchor_element, # type: ignore[arg-type]
+ skyvern_frame=skyvern_frame,
+ incremental_scraped=incremental_scraped,
+ step=MagicMock(),
+ task=_task(), # type: ignore[arg-type]
+ force_select=True,
+ target_value="2026-11-01",
+ entry_action_type=entry_action_type,
+ )
+ return result, select_level
+
+ @pytest.mark.asyncio
+ async def test_walk_stops_when_the_budget_is_spent(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ anchor_element = _FakeAnchorElement(tag_name="input")
+
+ _, select_level = await self._walk(monkeypatch, anchor_element=anchor_element)
+
+ # Spent budget ends the walk at the level that spent it, rather than at the depth backstop.
+ assert select_level.await_count == 1
+
+ @pytest.mark.asyncio
+ async def test_cheap_levels_still_walk_past_a_calendar_s_worth_of_month_steps(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ anchor_element = _FakeAnchorElement(tag_name="input")
+
+ _, select_level = await self._walk(monkeypatch, anchor_element=anchor_element, budget_seconds=600.0)
+
+ # A month-stepped calendar needs a level per click; a walk whose levels are cheap keeps them.
+ assert select_level.await_count > 12
+
+ @pytest.mark.asyncio
+ async def test_select_option_entry_clears_the_field_before_typing_the_date(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ anchor_element = _FakeAnchorElement(tag_name="input")
+ order: list[str] = []
+ anchor_element.input_clear = AsyncMock(side_effect=lambda *a, **k: order.append("clear"))
+ anchor_element.input_sequentially = AsyncMock(side_effect=lambda *a, **k: order.append("type"))
+
+ result, _ = await self._walk(monkeypatch, anchor_element=anchor_element)
+
+ # input_sequentially appends a value this short, so an uncleared field concatenates dates.
+ assert order == ["clear", "type"]
+ anchor_element.input_sequentially.assert_awaited_once_with("2026-11-01")
+ assert isinstance(result.action_result, handler.ActionSuccess) # type: ignore[attr-defined]
+
+ @pytest.mark.asyncio
+ async def test_input_text_entry_hands_the_date_back_to_its_caller(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ anchor_element = _FakeAnchorElement(tag_name="input")
+
+ result, _ = await self._walk(monkeypatch, anchor_element=anchor_element, entry_action_type="input_text")
+
+ # Non-terminal, so handle_input_text_action resumes its own text path (close the picker,
+ # refuse a readonly field, type with replace semantics) instead of typing here.
+ assert isinstance(result.action_result, handler.ActionFailure) # type: ignore[attr-defined]
+ assert handler._is_terminal_custom_select_failure(result.action_result) is False # type: ignore[attr-defined]
+ anchor_element.input_sequentially.assert_not_awaited()
+ # That caller only quits a dropdown it is told is still open.
+ assert result.dropdown_menu is not None # type: ignore[attr-defined]
+
+ @pytest.mark.asyncio
+ async def test_unspent_walk_with_nothing_typed_fails_instead_of_reporting_success(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ # A button-triggered calendar cannot be typed into, so there is no date to claim.
+ anchor_element = _FakeAnchorElement(tag_name="button")
+
+ result, _ = await self._walk(monkeypatch, anchor_element=anchor_element)
+
+ assert isinstance(result.action_result, handler.ActionFailure) # type: ignore[attr-defined]
+ assert handler._is_terminal_custom_select_failure(result.action_result) is True # type: ignore[attr-defined]
+ anchor_element.input_sequentially.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_typing_that_raises_does_not_become_a_success(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ anchor_element = _FakeAnchorElement(tag_name="input")
+ anchor_element.input_sequentially = AsyncMock(side_effect=RuntimeError("not editable"))
+
+ result, _ = await self._walk(monkeypatch, anchor_element=anchor_element)
+
+ assert isinstance(result.action_result, handler.ActionFailure) # type: ignore[attr-defined]
+
+ @pytest.mark.asyncio
+ async def test_readonly_date_field_is_reported_rather_than_typed_into(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ anchor_element = _FakeAnchorElement(tag_name="input")
+ anchor_element.is_readonly = AsyncMock(return_value=True)
+
+ result, _ = await self._walk(monkeypatch, anchor_element=anchor_element)
+
+ assert result.action_result.exception_type == "InputToReadonlyElement" # type: ignore[attr-defined]
+ anchor_element.input_sequentially.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_value_only_action_with_no_label_fails_instead_of_reporting_success(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ anchor_element = _FakeAnchorElement(tag_name="input")
+
+ result, _ = await self._walk(monkeypatch, anchor_element=anchor_element, label=None)
+
+ assert isinstance(result.action_result, handler.ActionFailure) # type: ignore[attr-defined]
+ anchor_element.input_sequentially.assert_not_awaited()
+
+
class TestSameLevelClickMarksWidgetMutation:
@pytest.mark.asyncio
async def test_select_from_dropdown_marks_mutation_when_deterministic_clicked_then_missed(
diff --git a/tests/unit/test_runs_v2_route.py b/tests/unit/test_runs_v2_route.py
index d05756a65..1c0989889 100644
--- a/tests/unit/test_runs_v2_route.py
+++ b/tests/unit/test_runs_v2_route.py
@@ -19,6 +19,7 @@ from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.db.agent_db import AgentDB
from skyvern.forge.sdk.db.enums import WorkflowRunTriggerType
+from skyvern.forge.sdk.db.exceptions import RunsListSearchCanceled
from skyvern.forge.sdk.db.models import WorkflowModel, WorkflowRunAttemptModel
from skyvern.forge.sdk.executor.factory import AsyncExecutorFactory
from skyvern.forge.sdk.routes import agent_protocol
@@ -483,6 +484,65 @@ async def test_get_workflow_runs_by_id_child_filter_depends_on_route(
)
+ ("indexed_search", "expected_status", "expected_detail_fragment"),
+ [
+ (False, 400, "created_at_start"),
+ (True, 503, "retry shortly"),
+ ],
+)
+async def test_get_workflow_runs_by_id_reports_a_cancelled_search_as_a_typed_error(
+ monkeypatch: pytest.MonkeyPatch,
+ indexed_search: bool,
+ expected_status: int,
+ expected_detail_fragment: str,
+) -> None:
+ # A workflow's own runs list carries the same unindexed search arms as the global list, so its
+ # cancelled search is the caller's to narrow rather than a 500 on an interactive list.
+ cancelled = RunsListSearchCanceled(indexed_search=indexed_search, statement_timeout_seconds=30)
+ mock_service = SimpleNamespace(
+ get_workflow_runs_for_workflow_permanent_id=AsyncMock(side_effect=cancelled),
+ )
+ monkeypatch.setattr(agent_protocol.app, "WORKFLOW_SERVICE", mock_service)
+ monkeypatch.setattr(agent_protocol.analytics, "capture", lambda *args, **kwargs: None)
+
+ with pytest.raises(HTTPException) as exc_info:
+ await agent_protocol.get_workflow_runs_by_id(
+ workflow_id="wpid_123",
+ page=1,
+ page_size=10,
+ search_key="a-search-term",
+ current_org=SimpleNamespace(organization_id="org_123"),
+ )
+
+ assert exc_info.value.status_code == expected_status
+ assert expected_detail_fragment in exc_info.value.detail
+
+
+async def test_get_workflow_runs_by_id_does_not_blame_the_search_for_another_query_timeout(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # The service attaches attempt views with a second, uncapped query after the search read
+ # returns. Its cancellation is not the search's, so it must stay a server error even though the
+ # request carried a search term.
+ mock_service = SimpleNamespace(
+ get_workflow_runs_for_workflow_permanent_id=AsyncMock(side_effect=statement_timeout_error()),
+ )
+ monkeypatch.setattr(agent_protocol.app, "WORKFLOW_SERVICE", mock_service)
+ monkeypatch.setattr(agent_protocol.analytics, "capture", lambda *args, **kwargs: None)
+
+ with pytest.raises(OperationalError):
+ await agent_protocol.get_workflow_runs_by_id(
+ workflow_id="wpid_123",
+ page=1,
+ page_size=10,
+ search_key="a-search-term",
+ current_org=SimpleNamespace(organization_id="org_123"),
+ )
+
+
@pytest.mark.parametrize(
("original_trigger_type", "x_user_agent", "expected_trigger"),
[
diff --git a/tests/unit/test_screenshot_target_closed_callers.py b/tests/unit/test_screenshot_target_closed_callers.py
index cba09b358..6f7bbea22 100644
--- a/tests/unit/test_screenshot_target_closed_callers.py
+++ b/tests/unit/test_screenshot_target_closed_callers.py
@@ -26,11 +26,13 @@ from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from playwright._impl._errors import Error as DriverError
from playwright._impl._errors import TargetClosedError
import skyvern.forge.agent as agent_mod
import skyvern.services.task_v2_service as task_v2_mod
import skyvern.webeye.actions.handler as handler_mod
+import skyvern.webeye.browser_driver_errors as driver_errors_mod
import skyvern.webeye.scraper.scraper as scraper_mod
from skyvern.exceptions import (
BrowserStateDiagnostic,
@@ -163,6 +165,104 @@ class TestRecordArtifactsAfterActionTargetClosed:
assert any("Failed to record screenshot after action" in str(call.args[0]) for call in log.error.call_args_list)
+_NAVIGATING_REFUSAL = "Page.content: Unable to retrieve content because the page is navigating and changing the content"
+
+
+class _SecondPackageDriverError(Exception):
+ """Stands in for the second Playwright-family package's ``Error``. The browser image repoints the
+ driver import but leaves persistent-session pages on the un-rewritten package, so one process
+ holds two unrelated classes for the same refusal -- and this environment installs only one of
+ them, hence a local stand-in registered the way the image resolves both.
+ """
+
+
+class TestRecordArtifactsAfterActionHtmlCapture:
+ """The post-action html read is best-effort too, and it hits the same expected page states: the
+ tab closed, or the document is being replaced mid-navigation. Those refusals must not be ERRORs
+ with tracebacks, while a genuine failure to read or to record the html still must be.
+ """
+
+ @pytest.mark.parametrize(
+ "html_error, register_second_package",
+ [
+ (DriverError(_NAVIGATING_REFUSAL), False),
+ (TargetClosedError("Target page, context or browser has been closed"), False),
+ (DriverError("Execution context was destroyed, most likely because of a navigation"), False),
+ (_SecondPackageDriverError(_NAVIGATING_REFUSAL), True),
+ ],
+ ids=["navigating", "closed_target", "context_lost", "navigating_from_second_driver_package"],
+ )
+ @pytest.mark.asyncio
+ async def test_transient_refusals_warn_without_traceback(
+ self, monkeypatch: pytest.MonkeyPatch, html_error: Exception, register_second_package: bool
+ ) -> None:
+ if register_second_package:
+ monkeypatch.setattr(
+ driver_errors_mod,
+ "DRIVER_ERROR_TYPES",
+ driver_errors_mod.DRIVER_ERROR_TYPES + (_SecondPackageDriverError,),
+ )
+ log, kwargs = _agent_rig(monkeypatch, TimeoutError(), html_error=html_error)
+
+ await ForgeAgent.record_artifacts_after_action(MagicMock(), **kwargs)
+
+ log.error.assert_not_called()
+ log.exception.assert_not_called()
+ warning = next(
+ (call for call in log.warning.call_args_list if "Skipping the post-action html" in str(call.args[0])),
+ None,
+ )
+ assert warning is not None, f"refusal did not warn: {log.warning.call_args_list}"
+ assert not warning.kwargs.get("exc_info"), "the downgraded warning must carry no traceback"
+ # Keeps the downgraded lines splittable by driver class, which exc_info used to supply.
+ assert warning.kwargs["error_type"].endswith(type(html_error).__name__)
+
+ @pytest.mark.asyncio
+ async def test_read_deadline_timeout_warns(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """``get_content`` bounds the read with ``asyncio.timeout``, so expiry is the builtin
+ TimeoutError rather than a Skyvern one."""
+ log, kwargs = _agent_rig(monkeypatch, TimeoutError(), html_error=TimeoutError())
+
+ await ForgeAgent.record_artifacts_after_action(MagicMock(), **kwargs)
+
+ log.error.assert_not_called()
+ log.exception.assert_not_called()
+ assert any("Timed out reading the post-action html" in str(call.args[0]) for call in log.warning.call_args_list)
+
+ @pytest.mark.parametrize(
+ "html_error",
+ [RuntimeError("page is navigating"), DriverError("Target crashed")],
+ ids=["same_text_without_driver_identity", "driver_error_with_unrecognized_message"],
+ )
+ @pytest.mark.asyncio
+ async def test_non_transient_read_failures_keep_their_traceback(
+ self, monkeypatch: pytest.MonkeyPatch, html_error: Exception
+ ) -> None:
+ """Controls for both halves of the classification: the identity gate rejects an unrelated
+ exception carrying a refusal's text, and the message gate rejects a driver error that is a
+ real failure (a crash) rather than an expected page state."""
+ log, kwargs = _agent_rig(monkeypatch, TimeoutError(), html_error=html_error)
+
+ await ForgeAgent.record_artifacts_after_action(MagicMock(), **kwargs)
+
+ assert any("Failed to read the post-action html" in str(call.args[0]) for call in log.exception.call_args_list)
+
+ @pytest.mark.asyncio
+ async def test_artifact_write_failure_still_logs_exception(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """The narrowed read guard must not cover the artifact write: recording a page Skyvern did
+ read is not a transient page state, whatever the write raises."""
+ log, kwargs = _agent_rig(monkeypatch, TimeoutError())
+ monkeypatch.setattr(
+ agent_mod.app.ARTIFACT_MANAGER,
+ "accumulate_action_html_to_archive",
+ MagicMock(side_effect=TargetClosedError("Target page, context or browser has been closed")),
+ )
+
+ await ForgeAgent.record_artifacts_after_action(MagicMock(), **kwargs)
+
+ assert any("Failed to record html after action" in str(call.args[0]) for call in log.exception.call_args_list)
+
+
class TestScrapeWebsiteTargetClosed:
@pytest.mark.asyncio
async def test_closed_target_reraises_without_error_log(self, monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/tests/unit/test_send_email_block.py b/tests/unit/test_send_email_block.py
index c921880d8..f22c34497 100644
--- a/tests/unit/test_send_email_block.py
+++ b/tests/unit/test_send_email_block.py
@@ -73,6 +73,7 @@ from skyvern.forge.sdk.workflow.exceptions import (
InvalidWorkflowDefinition,
NoValidEmailRecipient,
)
+from skyvern.forge.sdk.workflow.models import block as block_module
from skyvern.forge.sdk.workflow.models.block import (
ForLoopBlock,
HumanInteractionBlock,
@@ -104,6 +105,7 @@ from skyvern.schemas.workflows import (
)
from skyvern.services import script_service
from skyvern.services.email import gmail as gmail_service
+from tests.unit.scoped_asyncio import ScopedAsyncio
def _output_parameter(label: str) -> OutputParameter:
@@ -922,8 +924,8 @@ def _paused_run_database() -> MagicMock:
database.observer.update_workflow_run_block = AsyncMock()
database.workflow_runs.update_workflow_run = AsyncMock()
database.workflow_runs.create_or_update_workflow_run_output_parameter = AsyncMock()
- # Any status other than paused ends the block's wait loop on its first check.
- database.workflow_runs.get_workflow_run = AsyncMock(return_value=MagicMock(status=WorkflowRunStatus.completed))
+ # An approved run ends the block's wait loop on its first check.
+ database.workflow_runs.get_workflow_run = AsyncMock(return_value=MagicMock(status=WorkflowRunStatus.running))
return database
@@ -941,6 +943,126 @@ async def _human_interaction_message(
return transport.call_args.kwargs["message"]
+def _waiting_run_database(statuses: list[WorkflowRunStatus], sessions: list[SimpleNamespace]) -> MagicMock:
+ database = _paused_run_database()
+ database.workflow_runs.get_workflow_run = AsyncMock(
+ side_effect=[MagicMock(status=status) for status in statuses] + [MagicMock(status=statuses[-1])] * 1000
+ )
+ database.browser_sessions.get_persistent_browser_session = AsyncMock(side_effect=sessions + [sessions[-1]] * 1000)
+ return database
+
+
+async def _wait_for_human_interaction(
+ monkeypatch: pytest.MonkeyPatch,
+ database: MagicMock,
+ timeout_seconds: int,
+ browser_session_id: str | None = "pbs_1",
+) -> tuple[BlockResult, list[float]]:
+ sleeps: list[float] = []
+ clock = SimpleNamespace(now=0.0)
+
+ async def fake_sleep(seconds: float) -> None:
+ sleeps.append(seconds)
+ clock.now += seconds
+
+ monkeypatch.setattr(
+ block_module,
+ "asyncio",
+ ScopedAsyncio(sleep=fake_sleep, get_event_loop=lambda: SimpleNamespace(time=lambda: clock.now)),
+ )
+ monkeypatch.setattr(
+ HumanInteractionBlock, "get_workflow_run_context", staticmethod(lambda _run_id: _workflow_run_context({}))
+ )
+ monkeypatch.setattr(app, "DATABASE", database)
+ block = _human_interaction_block(timeout_seconds=timeout_seconds)
+ with patch("skyvern.forge.sdk.api.email._send", AsyncMock(return_value=True)):
+ result = await block.execute("wr_1", "wrb_1", organization_id="o_1", browser_session_id=browser_session_id)
+ return result, sleeps
+
+
+async def test_human_interaction_wait_fails_when_the_browser_session_is_closed(
+ monkeypatch: pytest.MonkeyPatch, offline_address_validation: None
+) -> None:
+ database = _waiting_run_database(
+ [WorkflowRunStatus.paused],
+ [SimpleNamespace(completed_at=None), SimpleNamespace(completed_at=datetime.now(UTC))],
+ )
+
+ result, sleeps = await _wait_for_human_interaction(monkeypatch, database, timeout_seconds=600)
+
+ assert result.status == BlockStatus.failed
+ assert result.success is False
+ assert result.failure_reason == "Browser session was closed while waiting for human interaction"
+ assert "no human interaction" not in result.failure_reason
+ assert result.output_parameter_value == {"success": False, "reason": result.failure_reason}
+ assert sleeps == [5]
+
+
+ ("new_status", "block_status", "success"),
+ [
+ (WorkflowRunStatus.running, BlockStatus.completed, True),
+ (WorkflowRunStatus.canceled, BlockStatus.canceled, False),
+ (WorkflowRunStatus.terminated, BlockStatus.terminated, False),
+ (WorkflowRunStatus.failed, BlockStatus.failed, False),
+ (WorkflowRunStatus.completed, BlockStatus.failed, False),
+ ],
+)
+async def test_human_interaction_wait_maps_the_run_leaving_paused(
+ monkeypatch: pytest.MonkeyPatch,
+ offline_address_validation: None,
+ new_status: WorkflowRunStatus,
+ block_status: BlockStatus,
+ success: bool,
+) -> None:
+ open_session, closed_session = SimpleNamespace(completed_at=None), SimpleNamespace(completed_at=datetime.now(UTC))
+ # Cancel closes the session too, so the status change must win over the closed session in the same poll.
+ database = _waiting_run_database(
+ [WorkflowRunStatus.paused, WorkflowRunStatus.paused, new_status], [open_session, closed_session]
+ )
+
+ result, _ = await _wait_for_human_interaction(monkeypatch, database, timeout_seconds=600)
+
+ assert (result.status, result.success) == (block_status, success)
+ assert result.output_parameter_value == {"success": success, "reason": f"status_changed:{new_status}"}
+
+
+ ("new_status", "block_status"),
+ [(WorkflowRunStatus.running, BlockStatus.completed), (WorkflowRunStatus.canceled, BlockStatus.canceled)],
+)
+async def test_human_interaction_wait_honors_a_status_change_seen_at_the_deadline(
+ monkeypatch: pytest.MonkeyPatch,
+ offline_address_validation: None,
+ new_status: WorkflowRunStatus,
+ block_status: BlockStatus,
+) -> None:
+ database = _waiting_run_database(
+ [WorkflowRunStatus.paused, WorkflowRunStatus.paused, new_status], [SimpleNamespace(completed_at=None)]
+ )
+
+ result, sleeps = await _wait_for_human_interaction(monkeypatch, database, timeout_seconds=5)
+
+ assert sleeps == [5]
+ assert result.status == block_status
+
+
+async def test_human_interaction_wait_without_a_browser_session_still_times_out(
+ monkeypatch: pytest.MonkeyPatch, offline_address_validation: None
+) -> None:
+ database = _waiting_run_database([WorkflowRunStatus.paused], [SimpleNamespace(completed_at=datetime.now(UTC))])
+
+ result, _ = await _wait_for_human_interaction(monkeypatch, database, timeout_seconds=12, browser_session_id=None)
+
+ assert result.status == BlockStatus.timed_out
+ assert result.failure_reason == "Timeout elapsed with no human interaction"
+ database.browser_sessions.get_persistent_browser_session.assert_not_awaited()
+
+
def test_body_format_round_trips_from_yaml_for_both_blocks() -> None:
assert _send_email_block(body_format="html").body_format == EmailBodyFormat.HTML
human_yaml = HumanInteractionBlockYAML(label="approve", recipients=["[email protected]"], body_format="html")