Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Log page-analysis deadline exhaustion at warning consistently (#8294)
Aaron Perez737ab8492c8b
diff --git a/skyvern-frontend/src/routes/runs/runViewTabBasePath.test.ts b/skyvern-frontend/src/routes/runs/runViewTabBasePath.test.tsnew file mode 100644index 000000000..41503047e--- /dev/null+++ b/skyvern-frontend/src/routes/runs/runViewTabBasePath.test.ts@@ -0,0 +1,22 @@+import { describe, expect, test } from "vitest";++import { runViewTabBasePath } from "./runViewTabBasePath";++describe("runViewTabBasePath keeps each mounted route family", () => {+ test("agent long-form route -> /agents/{workflowPermanentId}/{workflowRunId}", () => {+ expect(+ runViewTabBasePath({+ workflowPermanentId: "wpid_1",+ workflowRunId: "wr_1",+ }),+ ).toBe("/agents/wpid_1/wr_1");+ });++ test("task route -> /tasks/{taskId}", () => {+ expect(runViewTabBasePath({ taskId: "tsk_1" })).toBe("/tasks/tsk_1");+ });++ test("runs splat -> /runs/{runId}", () => {+ expect(runViewTabBasePath({ runId: "wr_1" })).toBe("/runs/wr_1");+ });+});diff --git a/skyvern-frontend/src/routes/runs/runViewTabBasePath.ts b/skyvern-frontend/src/routes/runs/runViewTabBasePath.tsnew file mode 100644index 000000000..3849c5adb--- /dev/null+++ b/skyvern-frontend/src/routes/runs/runViewTabBasePath.ts@@ -0,0 +1,21 @@+export type RunViewRouteParams = Readonly<{+ runId?: string;+ taskId?: string;+ workflowPermanentId?: string;+ workflowRunId?: string;+}>;++export function runViewTabBasePath(+ params: RunViewRouteParams,+): string | undefined {+ if (params.workflowPermanentId && params.workflowRunId) {+ return `/agents/${params.workflowPermanentId}/${params.workflowRunId}`;+ }+ if (params.taskId) {+ return `/tasks/${params.taskId}`;+ }+ if (params.runId) {+ return `/runs/${params.runId}`;+ }+ return undefined;+}diff --git a/skyvern-frontend/src/routes/runs/runViewTabsNavigation.test.tsx b/skyvern-frontend/src/routes/runs/runViewTabsNavigation.test.tsxnew file mode 100644index 000000000..20749e5bc--- /dev/null+++ b/skyvern-frontend/src/routes/runs/runViewTabsNavigation.test.tsx@@ -0,0 +1,179 @@+// @vitest-environment jsdom++import { render, screen, fireEvent } from "@testing-library/react";+import {+ createMemoryRouter,+ Navigate,+ Outlet,+ Route,+ Routes,+ RouterProvider,+ useParams,+} from "react-router-dom";+import { describe, expect, test } from "vitest";++import {+ SwitchBarNavigation,+ type SwitchBarNavigationOption,+} from "@/components/SwitchBarNavigation";++import { runViewTabBasePath } from "./runViewTabBasePath";++type Tabs = readonly [string, ...string[]];++function TabLayout({ tabs }: { tabs: Tabs }) {+ const base = runViewTabBasePath(useParams());+ const options: SwitchBarNavigationOption[] = tabs.map((tab) => ({+ label: tab,+ to: `${base}/${tab}`,+ }));+ return (+ <div>+ <SwitchBarNavigation options={options} />+ <Outlet />+ </div>+ );+}++function leafRoutes(tabs: Tabs) {+ return [+ { index: true, element: <Navigate to={tabs[0]} replace /> },+ ...tabs.map((tab) => ({ path: tab, element: <div>{`PANEL_${tab}`}</div> })),+ ];+}++function RunsSplat({ tabs }: { tabs: Tabs }) {+ return (+ <Routes>+ <Route element={<TabLayout tabs={tabs} />}>+ <Route index element={<Navigate to={tabs[0]} replace />} />+ {tabs.map((tab) => (+ <Route key={tab} path={tab} element={<div>{`PANEL_${tab}`}</div>} />+ ))}+ </Route>+ </Routes>+ );+}++function renderRouter(+ routes: Parameters<typeof createMemoryRouter>[0],+ entry: string,+) {+ return render(+ <RouterProvider+ router={createMemoryRouter(routes, { initialEntries: [entry] })}+ />,+ );+}++function hrefPath(name: string): string {+ const href = screen.getByRole("link", { name }).getAttribute("href");+ return new URL(href ?? "", "http://localhost").pathname;+}++function hrefSearch(name: string): string {+ const href = screen.getByRole("link", { name }).getAttribute("href");+ return new URL(href ?? "", "http://localhost").search;+}++function ariaCurrent(name: string): string | null {+ return screen.getByRole("link", { name }).getAttribute("aria-current");+}++const WF_TABS = [+ "overview",+ "output",+ "parameters",+ "recording",+ "code",+] as const;+const TASK_TABS = [+ "actions",+ "recording",+ "parameters",+ "diagnostics",+] as const;++describe("run view tab navigation stays in its mounted route family", () => {+ test("agent long-form route keeps /agents/{wpid}/{wrid} and the active tab", async () => {+ renderRouter(+ [+ {+ path: "agents/:workflowPermanentId/:workflowRunId",+ element: <TabLayout tabs={WF_TABS} />,+ children: leafRoutes(WF_TABS),+ },+ ],+ "/agents/wpid_1/wr_1/overview?active=act_1",+ );+ expect(hrefPath("output")).toBe("/agents/wpid_1/wr_1/output");+ expect(hrefSearch("output")).toBe("?active=act_1");+ expect(ariaCurrent("overview")).toBe("page");+ expect(ariaCurrent("output")).toBeNull();++ fireEvent.click(screen.getByRole("link", { name: "output" }));+ expect(await screen.findByText("PANEL_output")).toBeTruthy();+ expect(hrefPath("output")).toBe("/agents/wpid_1/wr_1/output");+ expect(ariaCurrent("output")).toBe("page");+ });++ test("task route keeps /tasks/{taskId} and the active tab", async () => {+ renderRouter(+ [+ {+ path: "tasks/:taskId",+ element: <TabLayout tabs={TASK_TABS} />,+ children: leafRoutes(TASK_TABS),+ },+ ],+ "/tasks/tsk_1/actions?active=act_1",+ );+ expect(hrefPath("recording")).toBe("/tasks/tsk_1/recording");+ expect(hrefSearch("recording")).toBe("?active=act_1");+ expect(ariaCurrent("actions")).toBe("page");++ fireEvent.click(screen.getByRole("link", { name: "recording" }));+ expect(await screen.findByText("PANEL_recording")).toBeTruthy();+ expect(hrefPath("recording")).toBe("/tasks/tsk_1/recording");+ });++ test("runs splat keeps /runs/{runId} and renders the panel on click", async () => {+ renderRouter(+ [{ path: "runs/:runId/*", element: <RunsSplat tabs={WF_TABS} /> }],+ "/runs/wr_1/overview?active=act_1",+ );+ expect(hrefPath("output")).toBe("/runs/wr_1/output");+ expect(hrefSearch("output")).toBe("?active=act_1");+ expect(ariaCurrent("overview")).toBe("page");++ fireEvent.click(screen.getByRole("link", { name: "output" }));+ expect(await screen.findByText("PANEL_output")).toBeTruthy();+ });++ test("a relative target under the runs splat misroutes against the matched segment", () => {+ function RelativeSplat() {+ return (+ <Routes>+ <Route index element={<Navigate to="overview" replace />} />+ <Route+ path="overview"+ element={+ <div>+ <SwitchBarNavigation+ options={[{ label: "output", to: "output" }]}+ />+ <div>PANEL_overview</div>+ </div>+ }+ />+ <Route path="output" element={<div>PANEL_output</div>} />+ </Routes>+ );+ }+ renderRouter(+ [{ path: "runs/:runId/*", element: <RelativeSplat /> }],+ "/runs/wr_1/overview?active=act_1",+ );+ expect(hrefPath("output")).toBe("/runs/wr_1/overview/output");+ });+});diff --git a/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsx b/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsxindex a90a6820d..28434b6f2 100644--- a/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsx+++ b/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsx@@ -35,7 +35,8 @@ import { type ApiCommandOptions } from "@/util/apiCommands";import { buildTaskRunPayload } from "@/util/taskRunPayload";import { PlayIcon, ReloadIcon } from "@radix-ui/react-icons";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { Link, Outlet } from "react-router-dom";+import { Link, Outlet, useParams } from "react-router-dom";+import { runViewTabBasePath } from "@/routes/runs/runViewTabBasePath";import { statusIsCancellable, statusIsFinalized } from "../types";import { MAX_STEPS_DEFAULT } from "../constants";import { useTaskQuery } from "./hooks/useTaskQuery";@@ -59,6 +60,7 @@ function createTaskRequestObject(values: TaskApiResponse) {function TaskDetails() {const taskId = useFirstParam("taskId", "runId");+ const runBasePath = runViewTabBasePath(useParams()) ?? `/runs/${taskId}`;const credentialGetter = useCredentialGetter();const queryClient = useQueryClient();const apiCredential = useApiCredential();@@ -367,19 +369,19 @@ function TaskDetails() {options={[{label: "Actions",- to: "actions",+ to: `${runBasePath}/actions`,},{label: "Recording",- to: "recording",+ to: `${runBasePath}/recording`,},{label: "Inputs",- to: "parameters",+ to: `${runBasePath}/parameters`,},{label: "Diagnostics",- to: "diagnostics",+ to: `${runBasePath}/diagnostics`,},]}/>diff --git a/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx b/skyvern-frontend/src/routes/workflows/WorkflowRun.tsxindex 649ef65ef..b5b97da71 100644--- a/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx+++ b/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx@@ -41,8 +41,10 @@ import {Outlet,useLocation,useNavigate,+ useParams,useSearchParams,} from "react-router-dom";+import { runViewTabBasePath } from "@/routes/runs/runViewTabBasePath";import { statusIsCancellable, statusIsFinalized } from "../tasks/types";import { useWorkflowRunWithWorkflowQuery } from "./hooks/useWorkflowRunWithWorkflowQuery";import { useRefreshOnboardingOnRunCompletion } from "./hooks/useRefreshOnboardingOnRunCompletion";@@ -563,26 +565,28 @@ function WorkflowRun() {webhookFailureReasonData) &&workflowRun.status === Status.Completed;+ const runBasePath =+ runViewTabBasePath(useParams()) ?? `/runs/${workflowRunId}`;const switchBarOptions: SwitchBarNavigationOption[] = [{label: "Overview",- to: "overview",+ to: `${runBasePath}/overview`,},{label: "Output",- to: "output",+ to: `${runBasePath}/output`,},{label: "Inputs",- to: "parameters",+ to: `${runBasePath}/parameters`,},{label: "Recording",- to: "recording",+ to: `${runBasePath}/recording`,},{label: "Code",- to: "code",+ to: `${runBasePath}/code`,icon: !isGeneratingCode ? (<CodeIcon className="inline-block size-5" />) : (diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex cd9bee8a0..f174ffc9d 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -7,12 +7,13 @@ import osimport randomimport reimport string+import timeimport uuidfrom asyncio.exceptions import CancelledErrorfrom dataclasses import dataclassfrom datetime import UTC, datetimefrom pathlib import Path-from typing import Any, Iterable, Literal, Tuple, cast+from typing import Any, Awaitable, Callable, Iterable, Literal, Tuple, castimport structlogfrom openai.types.responses.response import Response as OpenAIResponse@@ -1003,6 +1004,107 @@ class ForgeAgent:return files_to_rename+ async def _wait_for_in_flight_downloads(+ self,+ task: Task,+ task_block: BaseTaskBlock,+ organization_id: str,+ *,+ timeout_cap: float | None = None,+ exhausted: set[str] | None = None,+ should_cancel: Callable[[], Awaitable[bool]] | None = None,+ ) -> bool:+ """Block until any download the task already kicked off settles (or times out).++ `timeout_cap`, when given, only ever shrinks the wait to the caller's remaining budget+ (e.g. the v3 loop's deadline); `exhausted` excludes paths that already hit+ DownloadFileMaxWaitingTime once so they aren't re-awaited on every subsequent call.+ `should_cancel`, when given, is polled every second while the download wait is in flight+ (the v3 loop otherwise only polls between tool calls, which this wait can outlast) and+ cancels the wait early if it fires.++ Returns True only when `should_cancel` fired and cut the wait short; False in every other+ case (no in-flight downloads, budget already spent, normal completion, or a+ DownloadFileMaxWaitingTime timeout) so callers can tell a cancel apart from a landed file.+ """+ if timeout_cap is not None and timeout_cap <= 0:+ return False+ context = skyvern_context.current()+ workflow_download_directory = get_path_for_workflow_download_directory(+ resolve_run_download_id(context, fallback_run_id=task.workflow_run_id)+ )++ downloading_files = list_downloading_files_in_directory(workflow_download_directory)+ if task.browser_session_id:+ browser_session_downloading_files = await app.STORAGE.list_downloading_files_in_browser_session(+ organization_id=organization_id,+ browser_session_id=task.browser_session_id,+ )+ downloading_files = downloading_files + browser_session_downloading_files+ if exhausted:+ downloading_files = [path for path in downloading_files if path not in exhausted]+ if len(downloading_files) > 0:+ LOG.info(+ "Detecting files are still downloading, waiting for files to be completely downloaded.",+ downloading_files=downloading_files,+ )+ timeout = task_block.download_timeout or BROWSER_DOWNLOAD_TIMEOUT+ if timeout_cap is not None:+ timeout = min(timeout, timeout_cap)+ try:+ if should_cancel is None:+ await wait_for_download_finished(+ downloading_files=downloading_files,+ timeout=timeout,+ )+ else:+ return await self._wait_for_download_finished_cancellable(+ downloading_files=downloading_files,+ timeout=timeout,+ should_cancel=should_cancel,+ )+ except DownloadFileMaxWaitingTime as e:+ LOG.warning(+ "There're several long-time downloading files, these files might be broken",+ downloading_files=e.downloading_files,+ workflow_run_id=task.workflow_run_id,+ )+ if exhausted is not None:+ exhausted.update(e.downloading_files)+ return False++ async def _wait_for_download_finished_cancellable(+ self,+ *,+ downloading_files: list[str],+ timeout: float,+ should_cancel: Callable[[], Awaitable[bool]],+ ) -> bool:+ """Returns True when should_cancel fired and the wait was cut short; False on normal completion."""+ wait_task = asyncio.ensure_future(+ wait_for_download_finished(downloading_files=downloading_files, timeout=timeout)+ )+ try:+ while True:+ done, _pending = await asyncio.wait({wait_task}, timeout=1.0)+ if wait_task in done:+ await wait_task+ return False+ if await should_cancel():+ LOG.info(+ "Cancelling in-flight download wait: run was canceled",+ downloading_files=downloading_files,+ )+ wait_task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await wait_task+ return True+ finally:+ if not wait_task.done():+ wait_task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await wait_task+async def create_task_and_step_from_block(self,task_block: BaseTaskBlock,@@ -1219,12 +1321,13 @@ class ForgeAgent:from skyvern.forge.taskv3.auth_tools import build_auth_toolsfrom skyvern.forge.taskv3.captcha_tools import build_captcha_toolsfrom skyvern.forge.taskv3.engine import (+ DEFAULT_DEADLINE_SECONDS,MIN_ACTION_STEPS,coerce_v3_parameters,run_task_v3_agent_loop,taskv3_runaway_backstops,)- from skyvern.forge.taskv3.loop import DEFAULT_MAX_SETTLE_DEFERRALS+ from skyvern.forge.taskv3.loop import DEFAULT_MAX_SETTLE_DEFERRALS, CompletionBlocker, CompletionProbefrom skyvern.forge.taskv3.tools import pending_marker# Workflow-block tasks re-resolve the live working page on every tool call, so a click that@@ -1369,6 +1472,133 @@ class ForgeAgent:return Falsedownload_id = resolve_run_download_id(context, fallback_run_id=task.task_id)++ # Same baseline v1 takes before its per-step download check, so a file that was already+ # sitting in the run's download directory before this block started is never mistaken for+ # one this block produced.+ download_baseline_files: list[str] | None = None+ # Staged basenames are joined onto this dir so they match the full paths the finalizer diffs.+ workflow_download_directory: Path | None = None+ if (+ task_block is not None+ and task.workflow_run_id+ and (task_block.complete_on_download or task_block.download_suffix)+ ):+ workflow_download_directory = get_path_for_workflow_download_directory(+ resolve_run_download_id(context, fallback_run_id=task.workflow_run_id)+ )+ download_baseline_files = list_files_in_directory(workflow_download_directory)+ if task.browser_session_id:+ browser_session_downloaded_files = await app.STORAGE.list_downloaded_files_in_browser_session(+ organization_id=organization.organization_id,+ browser_session_id=task.browser_session_id,+ )+ download_baseline_files = download_baseline_files + browser_session_downloaded_files++ # Passed to the loop below as well, so a download-wait probe caps its wait at what's left+ # of the same deadline the loop enforces.+ loop_deadline_seconds = DEFAULT_DEADLINE_SECONDS+ loop_deadline_at = time.monotonic() + loop_deadline_seconds+ # Shared across every probe call: a path that already hit DownloadFileMaxWaitingTime once+ # is excluded from later waits instead of being re-awaited on every subsequent action.+ download_wait_exhausted: set[str] = set()++ download_finalized = False+ download_completion_reason: str | None = None++ # Owned here (not by the engine) so the final clean_up_task below can also exclude names+ # tools staged into the downloads dir this run, whether or not the probe ever finalized.+ class _StagedDownloads(set[str]):+ # file_upload reports a basename for every source, but only http(s) sources are staged+ # into the downloads dir; a name that isn't there must not shadow a later real download.+ def add(self, name: str) -> None:+ if workflow_download_directory is not None and (workflow_download_directory / name).exists():+ super().add(name)++ staged_downloads: set[str] = _StagedDownloads()+ completion_probe: CompletionProbe | None = None+ completion_blocker: CompletionBlocker | None = None+ if task_block is not None and task_block.complete_on_download and task.workflow_run_id:+ complete_on_download_block = task_block++ async def _download_completion_probe(staged: frozenset[str]) -> str | None:+ nonlocal download_finalized, download_completion_reason+ # A finish deferred by the settle gate re-probes; finalizing again would re-rename+ # the same file (or re-fetch a browser-session download).+ if download_finalized:+ return download_completion_reason+ assert workflow_download_directory is not None # set alongside complete_on_download above+ cancelled = await self._wait_for_in_flight_downloads(+ task,+ complete_on_download_block,+ organization.organization_id,+ timeout_cap=loop_deadline_at - time.monotonic(),+ exhausted=download_wait_exhausted,+ should_cancel=_should_cancel,+ )+ if cancelled:+ # The run is being canceled; even if a file landed while we waited, don't+ # finalize it into a `completed` result out from under the cancellation.+ return None+ staged_paths = [str(workflow_download_directory / name) for name in sorted(staged)]+ new_files = await self._finalize_downloaded_files_for_task(+ task,+ organization_id=organization.organization_id,+ download_suffix=complete_on_download_block.download_suffix,+ list_files_before=[*(download_baseline_files or []), *staged_paths],+ randomize_if_missing=True,+ )+ if not new_files:+ return None+ download_finalized = True+ download_completion_reason = f"download completed ({len(new_files)} new file(s))"+ LOG.info(+ "Task V3 task completed due to download",+ task_id=task.task_id,+ num_new_files=len(new_files),+ )+ return download_completion_reason++ async def _download_completion_blocker(staged: frozenset[str]) -> str | None:+ reason = await _download_completion_probe(staged)+ if reason:+ return None+ return (+ "This task only completes once a file download finishes, and no download has "+ "been detected yet. Trigger the download, or finish with status=failed or "+ "status=terminated if it cannot be triggered."+ )++ # A data-extraction goal needs the model to keep the turn and call finish() itself;+ # ending the loop from the probe would drop the extraction. The blocker still+ # withholds completion until the download lands.+ if not (task.data_extraction_goal or task.extracted_information_schema):+ completion_probe = _download_completion_probe+ completion_blocker = _download_completion_blocker+ elif (+ task_block is not None+ and task_block.download_timeout is not None+ and not task_block.complete_on_download+ and task.workflow_run_id+ ):+ # download_timeout alone carries no completion semantics; v1 bounds a post-action+ # download-settle wait with it, so v3 gets an equivalent wait-only probe that never+ # ends the run or blocks finish.+ wait_only_block = task_block++ async def _download_wait_only_probe(staged: frozenset[str]) -> str | None:+ await self._wait_for_in_flight_downloads(+ task,+ wait_only_block,+ organization.organization_id,+ timeout_cap=loop_deadline_at - time.monotonic(),+ exhausted=download_wait_exhausted,+ should_cancel=_should_cancel,+ )+ return None++ completion_probe = _download_wait_only_probe+# Honor a step cap (per-request override, task, or org, else the same MAX_STEPS_PER_RUN default# the step engine uses) as the ACTION-round budget: a v3 step is one action round (a turn that# mutates the page), matching a step-engine step, so perception rounds (observe/get_html) don't@@ -1602,6 +1832,10 @@ class ForgeAgent:extra_system_guidance="\n\n".join(part for part in (auth_guidance, captcha_guidance, task.workflow_system_prompt) if part),+ completion_probe=completion_probe,+ completion_blocker=completion_blocker,+ staged_downloads=staged_downloads,+ deadline_seconds=loop_deadline_seconds,)finally:if context and credential_parameter_key is not None:@@ -1779,6 +2013,15 @@ class ForgeAgent:)if refreshed:task = refreshed+ # A probe-finalized run must not be finalized again (double rename); otherwise the fallback+ # finalize still has to exclude tool-staged inputs from what counts as a download.+ cleanup_list_files_before: list[str] | None = None+ if not download_finalized and download_baseline_files is not None:+ assert workflow_download_directory is not None # set alongside download_baseline_files above+ cleanup_list_files_before = [+ *download_baseline_files,+ *(str(workflow_download_directory / name) for name in sorted(staged_downloads)),+ ]await self.clean_up_task(task=task,last_step=step,@@ -1786,6 +2029,8 @@ class ForgeAgent:need_call_webhook=need_call_webhook,close_browser_on_completion=close_browser_on_completion,browser_session_id=browser_session_id,+ download_suffix=task_block.download_suffix if task_block else None,+ list_files_before=cleanup_list_files_before,)return step, task@@ -1967,8 +2212,7 @@ class ForgeAgent:)return step, detailed_output, None- # A bare task always qualifies; a workflow block must be an allowed type with no- # download semantics (v3 doesn't implement complete_on_download/download_suffix).+ # A bare task always qualifies; a workflow block must be an allowed type.task_block_supports_v3 = task_block is None or _task_block_supports_v3(task_block)if engine == RunEngine.skyvern_v3 and task_block is not None and not task_block_supports_v3:LOG.info(@@ -2061,33 +2305,7 @@ class ForgeAgent:retry = Falseif task_block and task_block.complete_on_download and task.workflow_run_id:- workflow_download_directory = get_path_for_workflow_download_directory(- resolve_run_download_id(context, fallback_run_id=task.workflow_run_id)- )-- downloading_files = list_downloading_files_in_directory(workflow_download_directory)- if task.browser_session_id:- browser_session_downloading_files = await app.STORAGE.list_downloading_files_in_browser_session(- organization_id=organization.organization_id,- browser_session_id=task.browser_session_id,- )- downloading_files = downloading_files + browser_session_downloading_files- if len(downloading_files) > 0:- LOG.info(- "Detecting files are still downloading, waiting for files to be completely downloaded.",- downloading_files=downloading_files,- )- try:- await wait_for_download_finished(- downloading_files=downloading_files,- timeout=task_block.download_timeout or BROWSER_DOWNLOAD_TIMEOUT,- )- except DownloadFileMaxWaitingTime as e:- LOG.warning(- "There're several long-time downloading files, these files might be broken",- downloading_files=e.downloading_files,- workflow_run_id=task.workflow_run_id,- )+ await self._wait_for_in_flight_downloads(task, task_block, organization.organization_id)files_to_rename = await self._finalize_downloaded_files_for_task(task,diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex d8a7b7456..25b331125 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -1319,7 +1319,7 @@ class BaseTaskBlock(Block):totp_identifier: str | None = Nonecomplete_verification: bool = Trueinclude_action_history_in_verification: bool = False- download_timeout: float | None = None # minutes+ download_timeout: float | None = None # secondsinclude_extracted_text: bool = True_data_extraction_goal_is_prerendered: bool = PrivateAttr(default=False)@@ -15019,6 +15019,7 @@ _TASK_V3_SUPPORTED_BLOCK_TYPES = frozenset(BlockType.ACTION,BlockType.VALIDATION,BlockType.EXTRACTION,+ BlockType.FILE_DOWNLOAD,})@@ -15030,16 +15031,12 @@ _ENGINE_INERT_BLOCK_TYPES = frozenset({BlockType.GOTO_URL, BlockType.HUMAN_INTERdef _task_block_supports_v3(task_block: BaseTaskBlock) -> bool:- """Whether a workflow task block is eligible to dispatch to the Task V3 native engine.-- v3 doesn't implement download-completion semantics yet, so a block relying on them- (complete_on_download / download_suffix / download_timeout) stays on the step engine.- """- if task_block.block_type not in _TASK_V3_SUPPORTED_BLOCK_TYPES:+ """Whether a workflow task block is eligible to dispatch to the Task V3 native engine."""+ if task_block.block_type == BlockType.VALIDATION and task_block.complete_on_download:+ # A validation block never acts on the page, so it has no way to trigger the download it+ # would complete on.return False- if task_block.complete_on_download or task_block.download_suffix or task_block.download_timeout is not None:- return False- return True+ return task_block.block_type in _TASK_V3_SUPPORTED_BLOCK_TYPESdef run_is_eligible_for_v3_ab(blocks: list[BlockTypeVar], *, is_script_run: bool) -> bool:diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.pyindex 744c54424..2bca60202 100644--- a/skyvern/forge/taskv3/engine.py+++ b/skyvern/forge/taskv3/engine.py@@ -32,6 +32,8 @@ from skyvern.forge.sdk.api.llm.exceptions import LLMProviderErrorRetryableTaskfrom skyvern.forge.taskv3.loop import (DEFAULT_MAX_SETTLE_DEFERRALS,ActivityRecency,+ CompletionBlocker,+ CompletionProbe,LoopOutcome,SubmitWatch,ToolSpec,@@ -83,6 +85,14 @@ Rules:- When a submit is refused, find the page's own message in `observe`: a `text:` line that reads as a rejection or validation message, or a field marked `*invalid`. Fix the named field if the task's data allows; otherwise finish and quote that message as the reason. A captcha widget that is merely present on the page is not evidence that it blocked the submission.- Do not submit forms or take irreversible actions unless the goal explicitly instructs it."""+DOWNLOAD_COMPLETION_GUIDANCE = """++This task completes automatically once a file download finishes -- trigger the download and let it land; do not call finish(status=completed) yourself. If the download cannot be triggered, call finish with status=failed or status=terminated and say why."""++DOWNLOAD_REQUIRED_GUIDANCE = """++This task cannot finish as completed until a file download has finished. Trigger the download and let it land, then call finish(status=completed) with the extracted output. If the download cannot be triggered, call finish with status=failed or status=terminated and say why."""+def taskv3_runaway_backstops(max_action_steps: int | None) -> tuple[int, int]:"""Return (max_turns, max_tool_calls) anti-runaway guards for an action-step budget.@@ -175,6 +185,9 @@ async def run_task_v3_agent_loop(page_fingerprint: Callable[[], Awaitable[str | None]] | None = None,max_settle_deferrals: int = DEFAULT_MAX_SETTLE_DEFERRALS,pending_marker: Callable[[str], Awaitable[str | None]] | None = None,+ completion_probe: CompletionProbe | None = None,+ completion_blocker: CompletionBlocker | None = None,+ staged_downloads: set[str] | None = None,) -> LoopOutcome:"""Run one Task V3 task to completion against `page`, returning the loop outcome.@@ -203,6 +216,13 @@ async def run_task_v3_agent_loop(# run's deadline and cancellation so probing cannot overrun either. Page-free runs never probe.activity = ActivityRecency()submit_watch = SubmitWatch()+ if staged_downloads is None:+ staged_downloads = set()+ # A page-free run has no tool that could trigger a download, so a blocker would refuse every+ # completed verdict forever.+ if page_free:+ completion_probe = None+ completion_blocker = Nonefinish_tool = make_finish_tool(page_fingerprint=None if page_free else page_fingerprint,max_settle_deferrals=max_settle_deferrals,@@ -211,9 +231,17 @@ async def run_task_v3_agent_loop(should_cancel=should_cancel,deadline_at=time.monotonic() + deadline_seconds if deadline_seconds is not None else None,activity=activity,+ completion_blocker=completion_blocker,+ staged_downloads=staged_downloads,)tools = browser_tools + (extra_tools or []) + [finish_tool]base_system_prompt = PAGE_FREE_SYSTEM_PROMPT if page_free else SYSTEM_PROMPT+ # Keyed on which hooks are present, not completion_probe alone: an extraction blocker-only+ # case needs the model told it ends the run itself; a wait-only probe has nothing to explain.+ if completion_blocker is not None and completion_probe is not None:+ extra_system_guidance = extra_system_guidance + DOWNLOAD_COMPLETION_GUIDANCE+ elif completion_blocker is not None and completion_probe is None:+ extra_system_guidance = extra_system_guidance + DOWNLOAD_REQUIRED_GUIDANCEoutcome = await run_agent_tool_loop(llm_caller=llm_caller,system_prompt=base_system_prompt + extra_system_guidance,@@ -234,6 +262,8 @@ async def run_task_v3_agent_loop(max_call_retries=DEFAULT_MAX_CALL_RETRIES,activity=activity,submit_watch=None if page_free else submit_watch,+ completion_probe=completion_probe,+ staged_downloads=staged_downloads,)LOG.info("taskv3 engine loop finished",diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.pyindex 6b979ca90..2150becf7 100644--- a/skyvern/forge/taskv3/loop.py+++ b/skyvern/forge/taskv3/loop.py@@ -52,6 +52,13 @@ class ToolResult:ToolHandler = Callable[[dict[str, Any]], Awaitable[ToolResult]]+# A probe consulted after a billable/download-signaling tool result; a truthy return ends the run as+# completed with that reason, without the model ever calling finish. A blocker consulted from+# finish(completed) itself; a truthy return rejects that verdict with the message as the reason. Both+# receive the basenames tools staged into the downloads dir this run, to exclude from detection.+CompletionProbe = Callable[[frozenset[str]], Awaitable[str | None]]+CompletionBlocker = Callable[[frozenset[str]], Awaitable[str | None]]+@dataclassclass ToolSpec:@@ -534,6 +541,8 @@ def make_finish_tool(failure_settle_max_seconds: float = FAILURE_EVIDENCE_SETTLE_MAX_SECONDS,pending_marker: Callable[[str], Awaitable[str | None]] | None = None,submit_watch: SubmitWatch | None = None,+ completion_blocker: CompletionBlocker | None = None,+ staged_downloads: set[str] | None = None,) -> ToolSpec:"""`page_fingerprint` samples an opaque fingerprint of the page's rendered content (None when nopage is available). A finish(completed) is deferred (bounded by `max_settle_deferrals`, then@@ -633,6 +642,18 @@ def make_finish_tool("Finish with status=completed only once the page shows the submission ""landed; if it never resolves, say so with status=terminated.")+ if status == "completed" and completion_blocker is not None:+ try:+ blocker_message = await completion_blocker(frozenset(staged_downloads or ()))+ except Exception:+ # Fail closed: a download-gated task must not complete on a storage hiccup with no file.+ LOG.warning("taskv3 completion_blocker failed; failing closed", exc_info=True)+ return ToolResult.error(+ "Could not verify that a file download has finished; retry finish(status=completed) "+ "once the download has landed, or finish with status=failed or status=terminated."+ )+ if blocker_message:+ return ToolResult.error(blocker_message)if status == "completed" and page_fingerprint is not None and deferrals < max_settle_deferrals:try:settled = await _settled()@@ -790,6 +811,8 @@ async def run_agent_tool_loop(activity: ActivityRecency | None = None,submit_watch: SubmitWatch | None = None,telemetry_salt: str | None = None,+ completion_probe: CompletionProbe | None = None,+ staged_downloads: set[str] | None = None,) -> LoopOutcome:tool_by_name = {tool.name: tool for tool in tools}# Per run, never logged: the hashes it keys are stable within this run (the only scope any guard@@ -1049,6 +1072,8 @@ async def run_agent_tool_loop({"role": "tool", "tool_call_id": tool_call_id, "name": tool_name, "content": model_facing_content})result_data = result.data or {}+ if staged_downloads is not None and result_data.get("staged_download"):+ staged_downloads.add(result_data["staged_download"])if spec is not None and (result_data.get("download_notice") or result_data.get("page_state_changed")):# A download landing or a navigation is progress no matter which tool witnessed it# or whether that call itself errored: re-clicking the button that produces a file@@ -1168,6 +1193,25 @@ async def run_agent_tool_loop(if submit_selector is not None:submit_watch.record(submit_selector)+ if (+ completion_probe is not None+ and spec is not None+ and (spec.billable or result_data.get("download_notice"))+ # file_upload stages an http(s) source file into the same downloads dir; that landed+ # file is not the run's OWN download unless the wrapper also flagged download_notice.+ and not (result_data.get("staged_download") and not result_data.get("download_notice"))+ ):+ try:+ completion_reason = await completion_probe(frozenset(staged_downloads or ()))+ except Exception:+ LOG.warning("taskv3 completion_probe failed; not treating it as complete", exc_info=True)+ completion_reason = None+ if completion_reason:+ LOG.info("taskv3 loop completion probe fired", tool=tool_name, turn=turns)+ outcome = LoopOutcome("completed", completion_reason)+ _append_skipped_tool_results(messages, tool_calls[idx + 1 :], "completion probe fired")+ break+if spec is not None and spec.terminal and result.status == "ok":data = result.data or {}outcome = LoopOutcome(diff --git a/skyvern/webeye/utils/page.py b/skyvern/webeye/utils/page.pyindex 300e3216e..1cbc09bda 100644--- a/skyvern/webeye/utils/page.py+++ b/skyvern/webeye/utils/page.py@@ -1288,7 +1288,7 @@ class SkyvernFrame:if expression != JS_FUNCTION_DEFS:inject_budget = min(per_attempt_seconds, _remaining_seconds())if inject_budget <= 0:- LOG.error(+ LOG.warning("Skyvern timed out trying to analyze the page after navigation recovery",expression=expression,)@@ -1321,7 +1321,7 @@ class SkyvernFrame:retry_budget = min(per_attempt_seconds, _remaining_seconds())if retry_budget <= 0:- LOG.error(+ LOG.warning("Skyvern timed out trying to analyze the page after navigation recovery",expression=expression,)diff --git a/tests/unit/browser_extension/test_broker_server.py b/tests/unit/browser_extension/test_broker_server.pyindex 2a30bd9b5..393e22ab8 100644--- a/tests/unit/browser_extension/test_broker_server.py+++ b/tests/unit/browser_extension/test_broker_server.py@@ -2152,7 +2152,7 @@ async def test_legacy_scope_additions_stay_globally_fenced_while_create_is_pendiassert 91 not in server._pending_tab_eventswith pytest.raises(BrowserExtensionBrokerError) as error_info:- await second.request("tabs.activate", {"tabId": 91}, timeout=0.1)+ await second.request("tabs.activate", {"tabId": 91}, timeout=1.0)assert error_info.value.code == "LEASE_HELD"assert relay.requests == [("tabs.create", {"url": "about:blank"})]diff --git a/tests/unit/test_agent_cleanup_download_suffix.py b/tests/unit/test_agent_cleanup_download_suffix.pyindex de8223905..ed8d5852c 100644--- a/tests/unit/test_agent_cleanup_download_suffix.py+++ b/tests/unit/test_agent_cleanup_download_suffix.py@@ -2,12 +2,14 @@ from __future__ import annotationsimport asyncioimport os+import timefrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom structlog.testing import capture_logs+from skyvern.exceptions import DownloadFileMaxWaitingTimefrom skyvern.forge.agent import ForgeAgentfrom skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.schemas.runs import RunEngine@@ -739,3 +741,134 @@ async def test_execute_step_complete_on_download_emits_finalize_lineage(tmp_pathassert event["passed_download_suffix_fp"] == expected_fingerprint(suffix)assert event["context_download_suffix_fp"] == expected_fingerprint(suffix)assert (download_dir / f"{suffix}.zip").exists()+++async def test_wait_for_in_flight_downloads_caps_timeout_and_skips_exhausted_paths() -> None:+ agent = ForgeAgent()+ task = _make_task()+ task_block = SimpleNamespace(download_timeout=500.0)++ wait_mock = AsyncMock()+ with (+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value="/tmp/downloads"),+ patch("skyvern.forge.agent.list_downloading_files_in_directory", return_value=["a.pdf", "b.pdf"]),+ patch("skyvern.forge.agent.skyvern_context.current", return_value=None),+ patch("skyvern.forge.agent.wait_for_download_finished", wait_mock),+ ):+ exhausted = {"a.pdf"}+ await agent._wait_for_in_flight_downloads(+ task, task_block, task.organization_id, timeout_cap=30.0, exhausted=exhausted+ )++ # The block's 500s download_timeout is capped to the caller's 30s remaining budget, and the+ # already-exhausted path is excluded rather than re-awaited for its full timeout.+ wait_mock.assert_awaited_once()+ assert wait_mock.await_args.kwargs["downloading_files"] == ["b.pdf"]+ assert wait_mock.await_args.kwargs["timeout"] == 30.0+++async def test_wait_for_in_flight_downloads_skips_entirely_when_cap_is_spent() -> None:+ agent = ForgeAgent()+ task = _make_task()+ task_block = SimpleNamespace(download_timeout=None)++ wait_mock = AsyncMock()+ with (+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value="/tmp/downloads"),+ patch("skyvern.forge.agent.list_downloading_files_in_directory", return_value=["a.pdf"]),+ patch("skyvern.forge.agent.skyvern_context.current", return_value=None),+ patch("skyvern.forge.agent.wait_for_download_finished", wait_mock),+ ):+ await agent._wait_for_in_flight_downloads(task, task_block, task.organization_id, timeout_cap=0.0)++ wait_mock.assert_not_awaited()+++async def test_wait_for_in_flight_downloads_adds_timed_out_paths_to_exhausted() -> None:+ agent = ForgeAgent()+ task = _make_task()+ task_block = SimpleNamespace(download_timeout=None)++ wait_mock = AsyncMock(side_effect=DownloadFileMaxWaitingTime(downloading_files=["stuck.pdf"]))+ exhausted: set[str] = set()+ with (+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value="/tmp/downloads"),+ patch("skyvern.forge.agent.list_downloading_files_in_directory", return_value=["stuck.pdf"]),+ patch("skyvern.forge.agent.skyvern_context.current", return_value=None),+ patch("skyvern.forge.agent.wait_for_download_finished", wait_mock),+ ):+ await agent._wait_for_in_flight_downloads(task, task_block, task.organization_id, exhausted=exhausted)++ assert exhausted == {"stuck.pdf"}+++async def test_wait_for_in_flight_downloads_cancels_promptly_when_should_cancel_fires() -> None:+ agent = ForgeAgent()+ task = _make_task()+ task_block = SimpleNamespace(download_timeout=None)++ was_cancelled = False++ async def _slow_wait_for_download_finished(**_kwargs) -> None:+ nonlocal was_cancelled+ try:+ await asyncio.sleep(30)+ except asyncio.CancelledError:+ was_cancelled = True+ raise++ should_cancel_calls = 0++ async def _should_cancel() -> bool:+ nonlocal should_cancel_calls+ should_cancel_calls += 1+ return should_cancel_calls >= 2++ with (+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value="/tmp/downloads"),+ patch("skyvern.forge.agent.list_downloading_files_in_directory", return_value=["a.pdf"]),+ patch("skyvern.forge.agent.skyvern_context.current", return_value=None),+ patch("skyvern.forge.agent.wait_for_download_finished", _slow_wait_for_download_finished),+ ):+ start = time.monotonic()+ cancelled = await agent._wait_for_in_flight_downloads(+ task, task_block, task.organization_id, should_cancel=_should_cancel+ )+ elapsed = time.monotonic() - start++ assert elapsed < 5+ assert was_cancelled is True+ assert cancelled is True+++async def test_wait_for_in_flight_downloads_completes_normally_when_should_cancel_never_fires() -> None:+ agent = ForgeAgent()+ task = _make_task()+ task_block = SimpleNamespace(download_timeout=None)++ completed = False++ async def _fast_wait_for_download_finished(**_kwargs) -> None:+ nonlocal completed+ completed = True++ async def _should_cancel() -> bool:+ return False++ with (+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value="/tmp/downloads"),+ patch("skyvern.forge.agent.list_downloading_files_in_directory", return_value=["a.pdf"]),+ patch("skyvern.forge.agent.skyvern_context.current", return_value=None),+ patch("skyvern.forge.agent.wait_for_download_finished", _fast_wait_for_download_finished),+ ):+ cancelled = await agent._wait_for_in_flight_downloads(+ task, task_block, task.organization_id, should_cancel=_should_cancel+ )++ assert completed is True+ assert cancelled is Falsediff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.pyindex 0d03fd089..8d611d13b 100644--- a/tests/unit/test_agent_task_v3.py+++ b/tests/unit/test_agent_task_v3.py@@ -10,7 +10,9 @@ meters per action exactly like the step engine.from __future__ import annotationsimport asyncio+from collections.abc import Awaitable, Callablefrom datetime import UTC, datetime+from pathlib import Pathfrom types import SimpleNamespacefrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock, patch@@ -32,6 +34,7 @@ from skyvern.forge.sdk.workflow.models.block import (ActionBlock,BaseTaskBlock,ExtractionBlock,+ FileDownloadBlock,HumanInteractionBlock,LoginBlock,NavigationBlock,@@ -872,8 +875,9 @@ _ALLOWED_BLOCK_CASES: list[tuple[type[BaseTaskBlock], dict[str, Any]]] = [(ActionBlock, {}),(ValidationBlock, {}),(ExtractionBlock, {"data_extraction_goal": "Extract the price"}),+ (FileDownloadBlock, {"complete_on_download": True}),]-_ALLOWED_BLOCK_IDS = ["task", "navigation", "login", "action", "validation", "extraction"]+_ALLOWED_BLOCK_IDS = ["task", "navigation", "login", "action", "validation", "extraction", "file_download"]@pytest.mark.parametrize("block_cls,overrides", _ALLOWED_BLOCK_CASES, ids=_ALLOWED_BLOCK_IDS)@@ -897,8 +901,27 @@ def test_task_block_supports_v3_denies_unsupported_block_type() -> None:],ids=["complete_on_download", "download_suffix", "download_timeout"],)-def test_task_block_supports_v3_denies_download_semantics(overrides: dict[str, Any]) -> None:- assert agent_module._task_block_supports_v3(_make_block(ActionBlock, **overrides)) is False+def test_task_block_supports_v3_allows_download_semantics(overrides: dict[str, Any]) -> None:+ assert agent_module._task_block_supports_v3(_make_block(ActionBlock, **overrides)) is True+++ "block_cls", [ActionBlock, TaskBlock, FileDownloadBlock], ids=["action", "task", "file_download"]+)+def test_task_block_supports_v3_allows_complete_on_download_for_non_validation(+ block_cls: type[BaseTaskBlock],+) -> None:+ assert agent_module._task_block_supports_v3(_make_block(block_cls, complete_on_download=True)) is True+++def test_task_block_supports_v3_denies_download_gated_validation() -> None:+ # A validation block never acts on the page, so it can't trigger the download it would+ # complete on; this combination must stay on the step engine (SKY-14905).+ assert agent_module._task_block_supports_v3(_make_block(ValidationBlock, complete_on_download=True)) is False+++def test_task_block_supports_v3_allows_validation_without_complete_on_download() -> None:+ assert agent_module._task_block_supports_v3(_make_block(ValidationBlock)) is Trueclass _StepEngineDispatched(BaseException):@@ -991,11 +1014,12 @@ async def test_execute_step_dispatches_supported_block_types_to_v3(],ids=["complete_on_download", "download_suffix", "download_timeout"],)-async def test_execute_step_falls_through_to_step_engine_on_download_semantics(overrides: dict[str, Any]) -> None:+async def test_execute_step_dispatches_download_semantics_blocks_to_v3(overrides: dict[str, Any]) -> None:block = _make_block(ActionBlock, **overrides)v3_mock, step_engine_mock = await _run_execute_step_gate(engine=agent_module.RunEngine.skyvern_v3, task_block=block)- v3_mock.assert_not_awaited()- step_engine_mock.assert_awaited_once()+ v3_mock.assert_awaited_once()+ assert v3_mock.await_args.kwargs["task_block"] is block+ step_engine_mock.assert_not_awaited()@pytest.mark.asyncio@@ -1035,6 +1059,417 @@ async def test_execute_step_bare_task_with_verification_url_dispatches_to_v3() -step_engine_mock.assert_not_awaited()+# ---------------------------------------------------------------------------+# P2b: complete_on_download wiring -- the completion_probe/completion_blocker+# handed to run_task_v3_agent_loop, backed by the same finalize-and-rename path+# v1 uses (ForgeAgent._finalize_downloaded_files_for_task).+# ---------------------------------------------------------------------------+++async def _run_execute_task_v3_download(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ *,+ drop_file: bool,+ block_cls: type[BaseTaskBlock] = ActionBlock,+ task_id: str = "task-123",+ step_id: str = "step-download",+ download_suffix: str = "invoice",+ dropped_filename: str = "report.pdf",+ loop_fn: Callable[[dict[str, Any], dict[str, Any]], Awaitable[LoopOutcome]] | None = None,+) -> dict[str, Any]:+ """Drive _execute_task_v3 for a complete_on_download block, capturing the loop kwargs.++ The fake loop stands in for run_task_v3_agent_loop: it optionally drops a new file into the+ run's download directory (mimicking a tool call that triggered a download), then awaits the+ completion_probe/completion_blocker it was handed, exactly like the real loop does.++ ``loop_fn``, when given, fully replaces the default drop-then-probe-once loop body -- used to+ drive a block through a custom probe/blocker sequence (e.g. a second block in the same run,+ checked against a baseline that already contains an earlier block's file).+ """+ agent = ForgeAgent()+ now = datetime.now(UTC)+ organization = make_organization(now)+ task = make_task(+ now,+ organization,+ task_id=task_id,+ workflow_run_id="wr-download-test",+ data_extraction_goal=None,+ extracted_information_schema=None,+ )+ step = make_step(now, task, step_id=step_id, status=StepStatus.created, order=0, output=None)+ browser_state, _, page = make_browser_state()+ browser_state.must_get_working_page = AsyncMock(return_value=page)+ browser_state.get_working_page = AsyncMock(return_value=page)+ browser_state.take_post_action_screenshot = AsyncMock(return_value=b"png-bytes")++ block = _make_block(block_cls, complete_on_download=True, download_suffix=download_suffix)++ captured: dict[str, Any] = {}++ async def _default_loop_body(**kwargs: Any) -> LoopOutcome:+ if drop_file:+ (tmp_path / dropped_filename).write_bytes(b"file-bytes")+ captured["probe_reason"] = await kwargs["completion_probe"](frozenset())+ captured["blocker_message"] = await kwargs["completion_blocker"](frozenset())+ if captured["probe_reason"]:+ return LoopOutcome(status="completed", reason=captured["probe_reason"], billable_actions=["click"])+ return LoopOutcome(status="budget_exhausted", reason="no download detected", billable_actions=[])++ async def _loop(**kwargs: Any) -> LoopOutcome:+ if loop_fn is not None:+ return await loop_fn(kwargs, captured)+ return await _default_loop_body(**kwargs)++ loop_mock = AsyncMock(side_effect=_loop)+ monkeypatch.setattr("skyvern.forge.taskv3.engine.run_task_v3_agent_loop", loop_mock)+ monkeypatch.setattr("skyvern.forge.agent.LLMCaller", MagicMock())+ # get_path_for_workflow_download_directory (imported by agent.py) resolves through this same+ # module-level name at call time, so patching it here also redirects that call.+ monkeypatch.setattr("skyvern.forge.sdk.api.files.get_download_dir", lambda *_a, **_k: str(tmp_path))+ monkeypatch.setattr(+ "skyvern.forge.agent.app.ARTIFACT_MANAGER.create_artifact", AsyncMock(return_value="artifact-1")+ )+ monkeypatch.setattr(+ "skyvern.forge.agent.app.DATABASE.workflow_params.create_action",+ AsyncMock(side_effect=lambda action: action),+ )+ monkeypatch.setattr("skyvern.services.otp_service.has_credential_totp_candidate", lambda *_a, **_k: False)+ monkeypatch.setattr("skyvern.forge.agent.app.AGENT_FUNCTION.post_step_execution", AsyncMock())+ monkeypatch.setattr("skyvern.forge.agent.app.AGENT_FUNCTION.gate_step_completion", AsyncMock(return_value=True))++ async def fake_update_step(+ step: Step, status: StepStatus | None = None, output: Any = None, **_kwargs: Any+ ) -> Step:+ if status is not None:+ step.status = status+ if output is not None:+ step.output = output+ return step++ async def fake_update_task(task: Any, status: Any = None, **_kwargs: Any) -> Any:+ if status is not None:+ task.status = status+ if "failure_reason" in _kwargs:+ task.failure_reason = _kwargs["failure_reason"]+ return task++ agent.update_step = AsyncMock(side_effect=fake_update_step)+ agent.update_task = AsyncMock(side_effect=fake_update_task)+ agent.clean_up_task = AsyncMock()++ context = SkyvernContext(+ task_id=task.task_id,+ step_id=step.step_id,+ organization_id=task.organization_id,+ workflow_run_id=task.workflow_run_id,+ )+ skyvern_context.set(context)+ try:+ await agent._execute_task_v3(+ task=task,+ step=step,+ browser_state=browser_state,+ organization=organization,+ api_key=None,+ close_browser_on_completion=True,+ browser_session_id=None,+ task_block=block,+ )+ finally:+ skyvern_context.reset()++ captured["clean_up_kwargs"] = agent.clean_up_task.await_args.kwargs if agent.clean_up_task.await_args else {}+ return captured++[email protected]("block_cls", [ActionBlock, FileDownloadBlock], ids=["action", "file_download"])+async def test_execute_task_v3_download_completion_probe_finalizes_and_ends_the_loop(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, block_cls: type[BaseTaskBlock]+) -> None:+ captured = await _run_execute_task_v3_download(monkeypatch, tmp_path, drop_file=True, block_cls=block_cls)++ assert captured["probe_reason"]+ # Renamed per download_suffix="invoice", same as v1's finalize path.+ assert (tmp_path / "invoice.pdf").exists()+ assert not (tmp_path / "report.pdf").exists()+ # The probe already finalized against the pre-loop baseline; clean_up_task must not+ # finalize again (v1's no-double-finalize contract).+ assert captured["clean_up_kwargs"]["list_files_before"] is None+ assert captured["clean_up_kwargs"]["download_suffix"] == "invoice"++[email protected]("block_cls", [ActionBlock, FileDownloadBlock], ids=["action", "file_download"])+async def test_execute_task_v3_download_completion_probe_no_file_blocks_finish(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, block_cls: type[BaseTaskBlock]+) -> None:+ captured = await _run_execute_task_v3_download(monkeypatch, tmp_path, drop_file=False, block_cls=block_cls)++ assert captured["probe_reason"] is None+ assert captured["blocker_message"]+ assert isinstance(captured["blocker_message"], str)+++async def test_execute_task_v3_download_completion_probe_returns_none_when_wait_reports_cancellation(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ # A run being canceled races with a download landing: the wait reports the cancellation, but+ # a file already sits in the directory. The probe must not finalize it into a `completed`+ # result out from under the cancellation -- it must return None and leave finalize untouched.+ finalize_mock = AsyncMock()+ monkeypatch.setattr(ForgeAgent, "_wait_for_in_flight_downloads", AsyncMock(return_value=True))+ monkeypatch.setattr(ForgeAgent, "_finalize_downloaded_files_for_task", finalize_mock)++ captured = await _run_execute_task_v3_download(monkeypatch, tmp_path, drop_file=True)++ assert captured["probe_reason"] is None+ finalize_mock.assert_not_awaited()+++async def test_execute_task_v3_download_completion_with_extraction_goal_is_blocker_only(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # A data-extraction goal needs the model to keep the turn and call finish(completed,+ # extracted_output=...) itself; the probe would otherwise end the loop the moment a billable+ # action lands the download, before extraction ever happens.+ outcome = LoopOutcome(status="completed", reason="done", billable_actions=[])+ block = _make_block(ActionBlock, complete_on_download=True, download_suffix="invoice")+ _step, _task, loop_mock, _post = await _run_execute_task_v3(+ monkeypatch,+ outcome,+ task_block=block,+ workflow_run_id="wr_extract",+ data_extraction_goal="Extract the invoice total",+ extracted_information_schema=None,+ )+ assert loop_mock.await_args.kwargs["completion_probe"] is None+ assert loop_mock.await_args.kwargs["completion_blocker"] is not None+++async def test_execute_task_v3_download_timeout_only_gets_wait_only_probe_no_blocker(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # download_timeout alone carries no completion semantics; it must not go inert on v3 -- v1+ # bounds a post-action download-settle wait with it, so v3 gets an equivalent wait-only probe+ # that awaits the same in-flight-download wait and never ends the run or blocks finish.+ outcome = LoopOutcome(status="completed", reason="done", billable_actions=[])+ block = _make_block(ActionBlock, download_timeout=5.0)+ assert block.complete_on_download is False+ wait_mock = AsyncMock()+ monkeypatch.setattr(ForgeAgent, "_wait_for_in_flight_downloads", wait_mock)+ _step, _task, loop_mock, _post = await _run_execute_task_v3(+ monkeypatch,+ outcome,+ task_block=block,+ workflow_run_id="wr_wait_only",+ data_extraction_goal=None,+ extracted_information_schema=None,+ )+ probe = loop_mock.await_args.kwargs["completion_probe"]+ assert probe is not None+ assert loop_mock.await_args.kwargs["completion_blocker"] is None++ result = await probe(frozenset())+ assert result is None+ wait_mock.assert_awaited_once()+ assert wait_mock.await_args.kwargs["timeout_cap"] is not None+ assert isinstance(wait_mock.await_args.kwargs["exhausted"], set)+++async def test_execute_task_v3_download_baseline_is_scoped_per_block(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ # Two complete_on_download blocks in the same workflow run, sharing one download directory:+ # block 1 (ActionBlock) lands a.pdf and completes on it; block 2 (FileDownloadBlock) starts+ # with block 1's renamed file already sitting in the directory. Block 2's own baseline -- taken+ # fresh at the top of its own _execute_task_v3 call -- must already contain that leftover file,+ # so it is never mistaken for something block 2 downloaded.+ captured_block1 = await _run_execute_task_v3_download(+ monkeypatch,+ tmp_path,+ drop_file=True,+ block_cls=ActionBlock,+ task_id="task-block-1",+ step_id="step-block-1",+ download_suffix="first.pdf",+ dropped_filename="a.pdf",+ )+ assert captured_block1["probe_reason"]+ assert (tmp_path / "first.pdf").exists()+ assert not (tmp_path / "a.pdf").exists()+ assert captured_block1["clean_up_kwargs"]["list_files_before"] is None++ async def _block2_loop(kwargs: dict[str, Any], captured: dict[str, Any]) -> LoopOutcome:+ # No new file yet: block 2's baseline already contains first.pdf, so the probe must not+ # mistake it for a fresh download, and the blocker must withhold completion.+ captured["probe_before_new_file"] = await kwargs["completion_probe"](frozenset())+ captured["blocker_before_new_file"] = await kwargs["completion_blocker"](frozenset())++ (tmp_path / "b.pdf").write_bytes(b"file-bytes-b")+ captured["probe_after_new_file"] = await kwargs["completion_probe"](frozenset())+ if captured["probe_after_new_file"]:+ return LoopOutcome(status="completed", reason=captured["probe_after_new_file"], billable_actions=["click"])+ return LoopOutcome(status="budget_exhausted", reason="no download detected", billable_actions=[])++ captured_block2 = await _run_execute_task_v3_download(+ monkeypatch,+ tmp_path,+ drop_file=False,+ block_cls=FileDownloadBlock,+ task_id="task-block-2",+ step_id="step-block-2",+ download_suffix="second.pdf",+ loop_fn=_block2_loop,+ )++ assert captured_block2["probe_before_new_file"] is None+ assert isinstance(captured_block2["blocker_before_new_file"], str)+ assert captured_block2["blocker_before_new_file"]+ assert captured_block2["probe_after_new_file"]++ # Only b.pdf was new to block 2's run: it alone is finalized/renamed, and first.pdf (block 1's+ # already-baselined file) is left untouched.+ assert (tmp_path / "second.pdf").exists()+ assert not (tmp_path / "b.pdf").exists()+ assert (tmp_path / "first.pdf").exists()++ assert captured_block2["clean_up_kwargs"]["list_files_before"] is None+++async def test_execute_task_v3_download_completion_excludes_staged_download_persistently(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ # file_upload's staged http(s) source file sits in the same download directory and never goes+ # away on its own; the probe/blocker must exclude it by name on every later call this run, not+ # just the one call that staged it, or it gets finalized/renamed as if it were a real download.+ async def _loop(kwargs: dict[str, Any], captured: dict[str, Any]) -> LoopOutcome:+ (tmp_path / "in.pdf").write_bytes(b"staged-input-bytes")+ staged = frozenset({"in.pdf"})+ captured["probe_before_download"] = await kwargs["completion_probe"](staged)+ captured["blocker_before_download"] = await kwargs["completion_blocker"](staged)++ (tmp_path / "out.pdf").write_bytes(b"real-download-bytes")+ captured["probe_after_download"] = await kwargs["completion_probe"](staged)+ if captured["probe_after_download"]:+ return LoopOutcome(status="completed", reason=captured["probe_after_download"], billable_actions=["click"])+ return LoopOutcome(status="budget_exhausted", reason="no download detected", billable_actions=[])++ captured = await _run_execute_task_v3_download(monkeypatch, tmp_path, drop_file=False, loop_fn=_loop)++ assert captured["probe_before_download"] is None+ assert isinstance(captured["blocker_before_download"], str)+ assert captured["blocker_before_download"]+ assert captured["probe_after_download"]++ # Only the real download was finalized/renamed per download_suffix; the staged input is+ # untouched -- neither renamed nor deleted.+ assert (tmp_path / "invoice.pdf").exists()+ assert not (tmp_path / "out.pdf").exists()+ assert (tmp_path / "in.pdf").exists()+ assert (tmp_path / "in.pdf").read_bytes() == b"staged-input-bytes"+++ ("file_exists_at_add_time", "expect_finalized"),+ [+ pytest.param(False, True, id="managed_storage_source_not_shadowed"),+ pytest.param(True, False, id="http_staged_source_still_excluded"),+ ],+)+async def test_execute_task_v3_download_completion_staged_add_gated_by_existence(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, file_exists_at_add_time: bool, expect_finalized: bool+) -> None:+ # file_upload reports staged_download=<basename> for every source, but managed-file/s3://+ # sources are written to a temp file OUTSIDE the downloads dir -- only http(s) sources are+ # actually staged into it. Recording the name unconditionally would let a genuine later+ # browser download that happens to share the name (upload report.csv, site returns a+ # processed report.csv) get excluded and never finalized. Recording is gated on the file+ # existing in the downloads dir at add()-time, so the http-staged case still gets excluded.+ async def _loop(kwargs: dict[str, Any], captured: dict[str, Any]) -> LoopOutcome:+ staged_downloads = kwargs["staged_downloads"]+ if file_exists_at_add_time:+ (tmp_path / "report.csv").write_bytes(b"staged-input-bytes")+ staged_downloads.add("report.csv")+ if not file_exists_at_add_time:+ (tmp_path / "report.csv").write_bytes(b"real-download-bytes")++ captured["probe_reason"] = await kwargs["completion_probe"](frozenset(staged_downloads))+ if captured["probe_reason"]:+ return LoopOutcome(status="completed", reason=captured["probe_reason"], billable_actions=["click"])+ return LoopOutcome(status="budget_exhausted", reason="no download detected", billable_actions=[])++ captured = await _run_execute_task_v3_download(+ monkeypatch, tmp_path, drop_file=False, download_suffix="processed", loop_fn=_loop+ )++ if expect_finalized:+ assert captured["probe_reason"]+ assert (tmp_path / "processed.csv").exists()+ assert not (tmp_path / "report.csv").exists()+ else:+ assert captured["probe_reason"] is None+ assert (tmp_path / "report.csv").exists()+ assert (tmp_path / "report.csv").read_bytes() == b"staged-input-bytes"+++async def test_execute_task_v3_download_completion_probe_does_not_refinalize_once_cached(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ # A finish(completed) deferred by the settle gate re-probes after the first probe already+ # finalized the download. Without download_suffix, finalize renames to a fresh random name+ # every call, so re-finalizing on the re-probe would rename the file again and return a+ # different (but still truthy) reason. The cached-reason short-circuit must make every later+ # probe/blocker call a no-op: same reason, same directory listing, one finalize call total.+ original_finalize = ForgeAgent._finalize_downloaded_files_for_task+ finalize_calls = 0++ async def _spy_finalize(self: ForgeAgent, *args: Any, **kwargs: Any) -> Any:+ nonlocal finalize_calls+ finalize_calls += 1+ return await original_finalize(self, *args, **kwargs)++ monkeypatch.setattr(ForgeAgent, "_finalize_downloaded_files_for_task", _spy_finalize)++ async def _loop(kwargs: dict[str, Any], captured: dict[str, Any]) -> LoopOutcome:+ (tmp_path / "a.pdf").write_bytes(b"file-bytes")+ captured["probe_reason_1"] = await kwargs["completion_probe"](frozenset())+ captured["listing_1"] = sorted(p.name for p in tmp_path.iterdir())++ captured["probe_reason_2"] = await kwargs["completion_probe"](frozenset())+ captured["listing_2"] = sorted(p.name for p in tmp_path.iterdir())++ captured["blocker_reason_3"] = await kwargs["completion_blocker"](frozenset())+ captured["listing_3"] = sorted(p.name for p in tmp_path.iterdir())++ if captured["probe_reason_1"]:+ return LoopOutcome(status="completed", reason=captured["probe_reason_1"], billable_actions=["click"])+ return LoopOutcome(status="budget_exhausted", reason="no download detected", billable_actions=[])++ captured = await _run_execute_task_v3_download(+ monkeypatch, tmp_path, drop_file=False, download_suffix=None, loop_fn=_loop+ )++ assert captured["probe_reason_1"]+ assert captured["probe_reason_2"] == captured["probe_reason_1"]+ assert captured["blocker_reason_3"] is None++ assert captured["listing_2"] == captured["listing_1"]+ assert captured["listing_3"] == captured["listing_1"]++ assert finalize_calls == 1++# ---------------------------------------------------------------------------# P3: block-true budgets, task_type-aware goal framing, workflow-cancel detection# ---------------------------------------------------------------------------diff --git a/tests/unit/test_taskv3_engine.py b/tests/unit/test_taskv3_engine.pyindex 89eeb6a09..ec9dc2ab7 100644--- a/tests/unit/test_taskv3_engine.py+++ b/tests/unit/test_taskv3_engine.py@@ -446,3 +446,147 @@ async def test_engine_wires_the_pending_gate_and_withholds_it_from_page_free_runassert watches[1] is None, watchesassert loop_watches[0] is watches[0], (loop_watches, watches)assert loop_watches[1] is None, loop_watches+++async def test_engine_forwards_completion_hooks_and_gates_guidance_on_probe(monkeypatch: pytest.MonkeyPatch) -> None:+ # completion_probe must reach the loop and completion_blocker must reach the finish tool, and+ # the download-completion guidance is appended to the system prompt only when a probe is given.+ from skyvern.forge.taskv3 import engine as engine_mod+ from skyvern.forge.taskv3.engine import DOWNLOAD_COMPLETION_GUIDANCE+ from skyvern.forge.taskv3.loop import LoopOutcome++ loop_kwargs: dict[str, Any] = {}+ finish_kwargs: dict[str, Any] = {}++ async def fake_loop(**kwargs: Any) -> LoopOutcome:+ loop_kwargs.update(kwargs)+ return LoopOutcome(status="completed", reason="ok")++ real_make_finish_tool = engine_mod.make_finish_tool++ def capturing_make_finish_tool(*args: Any, **kwargs: Any) -> Any:+ finish_kwargs.update(kwargs)+ return real_make_finish_tool(*args, **kwargs)++ monkeypatch.setattr(engine_mod, "run_agent_tool_loop", fake_loop)+ monkeypatch.setattr(engine_mod, "make_finish_tool", capturing_make_finish_tool)++ async def probe(_staged: frozenset[str]) -> str | None:+ return "a file finished downloading"++ async def blocker(_staged: frozenset[str]) -> str | None:+ return None++ await run_task_v3_agent_loop(+ page_provider=_fixed_page_provider(_FakePage()),+ llm_caller=_ScriptedCaller([]),+ goal="download the file",+ completion_probe=probe,+ completion_blocker=blocker,+ )+ assert loop_kwargs["completion_probe"] is probe+ assert finish_kwargs["completion_blocker"] is blocker+ assert DOWNLOAD_COMPLETION_GUIDANCE in loop_kwargs["system_prompt"]+ # One staged_downloads set is shared between the loop and the finish tool -- a name staged via+ # a billable tool call must be visible to the SAME finish-tool blocker, not a divergent copy.+ assert loop_kwargs["staged_downloads"] is finish_kwargs["staged_downloads"]+ assert isinstance(loop_kwargs["staged_downloads"], set)++ loop_kwargs.clear()+ finish_kwargs.clear()+ await run_task_v3_agent_loop(+ page_provider=_fixed_page_provider(_FakePage()), llm_caller=_ScriptedCaller([]), goal="download the file"+ )+ assert loop_kwargs["completion_probe"] is None+ assert finish_kwargs["completion_blocker"] is None+ assert DOWNLOAD_COMPLETION_GUIDANCE not in loop_kwargs["system_prompt"]+++async def test_engine_guidance_keyed_on_which_hooks_are_present(monkeypatch: pytest.MonkeyPatch) -> None:+ # blocker-only (extraction tasks: the probe would end the loop before the model returns+ # extracted_output) gets the DOWNLOAD_REQUIRED variant naming finish(completed) as the model's+ # own job; probe-only (download_timeout alone, wait-only) has no completion semantics at all,+ # so it gets neither guidance string.+ from skyvern.forge.taskv3 import engine as engine_mod+ from skyvern.forge.taskv3.engine import DOWNLOAD_COMPLETION_GUIDANCE, DOWNLOAD_REQUIRED_GUIDANCE+ from skyvern.forge.taskv3.loop import LoopOutcome++ loop_kwargs: dict[str, Any] = {}++ async def fake_loop(**kwargs: Any) -> LoopOutcome:+ loop_kwargs.update(kwargs)+ return LoopOutcome(status="completed", reason="ok")++ monkeypatch.setattr(engine_mod, "run_agent_tool_loop", fake_loop)++ async def blocker(_staged: frozenset[str]) -> str | None:+ return None++ await run_task_v3_agent_loop(+ page_provider=_fixed_page_provider(_FakePage()),+ llm_caller=_ScriptedCaller([]),+ goal="download the file",+ completion_blocker=blocker,+ )+ assert DOWNLOAD_REQUIRED_GUIDANCE in loop_kwargs["system_prompt"]+ assert DOWNLOAD_COMPLETION_GUIDANCE not in loop_kwargs["system_prompt"]++ loop_kwargs.clear()++ async def probe(_staged: frozenset[str]) -> str | None:+ return None++ await run_task_v3_agent_loop(+ page_provider=_fixed_page_provider(_FakePage()),+ llm_caller=_ScriptedCaller([]),+ goal="download the file",+ completion_probe=probe,+ )+ assert DOWNLOAD_REQUIRED_GUIDANCE not in loop_kwargs["system_prompt"]+ assert DOWNLOAD_COMPLETION_GUIDANCE not in loop_kwargs["system_prompt"]+++async def test_engine_drops_download_hooks_in_page_free_mode(monkeypatch: pytest.MonkeyPatch) -> None:+ # No browser tools exist to trigger a download, so a blocker would refuse finish(completed)+ # forever; page-free runs get neither hook nor the download guidance.+ from skyvern.forge.taskv3 import engine as engine_mod+ from skyvern.forge.taskv3.engine import DOWNLOAD_COMPLETION_GUIDANCE, DOWNLOAD_REQUIRED_GUIDANCE+ from skyvern.forge.taskv3.loop import LoopOutcome++ loop_kwargs: dict[str, Any] = {}+ finish_kwargs: dict[str, Any] = {}++ async def fake_loop(**kwargs: Any) -> LoopOutcome:+ loop_kwargs.update(kwargs)+ return LoopOutcome(status="completed", reason="ok")++ real_make_finish_tool = engine_mod.make_finish_tool++ def capturing_make_finish_tool(*args: Any, **kwargs: Any) -> Any:+ finish_kwargs.update(kwargs)+ return real_make_finish_tool(*args, **kwargs)++ monkeypatch.setattr(engine_mod, "run_agent_tool_loop", fake_loop)+ monkeypatch.setattr(engine_mod, "make_finish_tool", capturing_make_finish_tool)++ async def probe(_staged: frozenset[str]) -> str | None:+ return "a file finished downloading"++ async def blocker(_staged: frozenset[str]) -> str | None:+ return "no download yet"++ await run_task_v3_agent_loop(+ page_provider=_fixed_page_provider(_FakePage()),+ llm_caller=_ScriptedCaller([]),+ goal="validate the record",+ page_free=True,+ completion_probe=probe,+ completion_blocker=blocker,+ )+ assert loop_kwargs["completion_probe"] is None+ assert finish_kwargs["completion_blocker"] is None+ assert DOWNLOAD_COMPLETION_GUIDANCE not in loop_kwargs["system_prompt"]+ assert DOWNLOAD_REQUIRED_GUIDANCE not in loop_kwargs["system_prompt"]diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.pyindex e4bf4fc1e..c5176d54e 100644--- a/tests/unit/test_taskv3_loop.py+++ b/tests/unit/test_taskv3_loop.py@@ -3422,3 +3422,238 @@ def test_canonicalization_covers_a_marker_fragment_left_open_at_the_tail() -> No'<a data-tv3="t9">y</a><b data-tv3="t8')assert _canonical_perception_content('tail closed data-tv3="t5"') == 'tail closed data-tv3="*"'+++async def test_completion_probe_ends_loop_mid_batch_without_finish() -> None:+ # A billable action's own result can carry the download-completion signal; the probe ends the+ # run right there, no finish tool call needed, and the rest of the batch never dispatches.+ clicks: list[tuple[str, dict[str, Any]]] = []++ async def probe(_staged: frozenset[str]) -> str | None:+ return "a file finished downloading"++ tools = [_billable_tool("click", clicks), make_finish_tool()]+ script = [[("click", {"selector": "#a"}), ("click", {"selector": "#b"})]]+ recorded_rounds: list[list[tuple[str, dict[str, Any], bool]]] = []++ async def on_action_round(round_actions: list[tuple[str, dict[str, Any], bool]]) -> None:+ recorded_rounds.append(round_actions)++ outcome, _ = await _run(script, tools, completion_probe=probe, on_action_round=on_action_round)++ assert outcome.status == "completed"+ assert outcome.reason == "a file finished downloading"+ assert len(clicks) == 1 # the second batched click never ran+ assert outcome.tool_calls == 1+ # The click that produced the download must be billed and persisted, not lost because the+ # probe fired before the recording step that appends it.+ assert outcome.billable_actions == ["click"]+ assert recorded_rounds == [[("click", {"selector": "#a"}, True)]]+++async def test_completion_probe_ignores_staged_download_unless_download_notice_too() -> None:+ # file_upload stages an http(s) source file into the same downloads dir and marks it via+ # staged_download; that must not read as the run's own landed download.+ probe_calls = 0++ async def probe(_staged: frozenset[str]) -> str | None:+ nonlocal probe_calls+ probe_calls += 1+ return "a file finished downloading"++ async def staged_only_handler(_args: dict[str, Any]) -> ToolResult:+ return ToolResult.ok("uploaded", data={"staged_download": "x.pdf"})++ staged_only_tool = ToolSpec(+ name="file_upload",+ description="file_upload",+ parameters={"type": "object", "properties": {}},+ handler=staged_only_handler,+ billable=True,+ )+ outcome, _ = await _run(+ [[("file_upload", {})], [("finish", {"status": "completed", "reason": "done"})]],+ [staged_only_tool, make_finish_tool()],+ completion_probe=probe,+ )+ assert outcome.status == "completed"+ assert outcome.reason == "done" # not the probe's reason -- it was never consulted+ assert probe_calls == 0++ async def staged_and_landed_handler(_args: dict[str, Any]) -> ToolResult:+ return ToolResult.ok("uploaded", data={"staged_download": "x.pdf", "download_notice": True})++ staged_and_landed_tool = ToolSpec(+ name="file_upload",+ description="file_upload",+ parameters={"type": "object", "properties": {}},+ handler=staged_and_landed_handler,+ billable=True,+ )+ outcome2, _ = await _run(+ [[("file_upload", {})]],+ [staged_and_landed_tool, make_finish_tool()],+ completion_probe=probe,+ )+ assert outcome2.status == "completed"+ assert outcome2.reason == "a file finished downloading"+ assert probe_calls == 1+++async def test_completion_probe_gated_on_billable_or_download_notice() -> None:+ probe_calls = 0++ async def probe(_staged: frozenset[str]) -> str | None:+ nonlocal probe_calls+ probe_calls += 1+ return None++ async def observe_handler(_args: dict[str, Any]) -> ToolResult:+ return ToolResult.ok("observed")++ observe_tool = ToolSpec(+ name="observe", description="observe", parameters={"type": "object", "properties": {}}, handler=observe_handler+ )++ async def check_download_handler(_args: dict[str, Any]) -> ToolResult:+ return ToolResult.ok("download seen", data={"download_notice": True})++ download_tool = ToolSpec(+ name="check_download",+ description="check_download",+ parameters={"type": "object", "properties": {}},+ handler=check_download_handler,+ )++ script = [+ [("observe", {})], # non-billable, no download_notice -> probe not consulted+ [("check_download", {})], # non-billable but download_notice -> probe consulted+ [("finish", {"status": "completed", "reason": "done"})],+ ]+ outcome, _ = await _run(script, [observe_tool, download_tool, make_finish_tool()], completion_probe=probe)++ assert outcome.status == "completed"+ assert probe_calls == 1+++async def test_completion_probe_exception_is_logged_and_treated_as_none() -> None:+ async def probe(_staged: frozenset[str]) -> str | None:+ raise RuntimeError("boom")++ clicks: list[tuple[str, dict[str, Any]]] = []+ tools = [_billable_tool("click", clicks), make_finish_tool()]+ script = [[("click", {"selector": "#a"})], [("finish", {"status": "completed", "reason": "done normally"})]]+ with capture_logs() as logs:+ outcome, _ = await _run(script, tools, completion_probe=probe)++ assert outcome.status == "completed"+ assert outcome.reason == "done normally"+ assert any(log["log_level"] == "warning" for log in logs)+++async def test_completion_blocker_gates_completed_status_only() -> None:+ # completed: blocked once, then allowed once the blocker clears.+ responses = iter(["wait: the download has not started yet", None])++ async def blocker(_staged: frozenset[str]) -> str | None:+ return next(responses)++ tools = [make_finish_tool(completion_blocker=blocker)]+ script = [+ [("finish", {"status": "completed", "reason": "first attempt"})],+ [("finish", {"status": "completed", "reason": "second attempt"})],+ ]+ outcome, caller = await _run(script, tools)+ assert outcome.status == "completed"+ assert outcome.reason == "second attempt"+ assert caller.calls == 2 # the first finish was rejected, forcing a second turn++ # failed: the blocker is never consulted, even though it would block if asked.+ async def always_blocks(_staged: frozenset[str]) -> str | None:+ return "should never be read"++ tools2 = [make_finish_tool(completion_blocker=always_blocks)]+ outcome2, _ = await _run([[("finish", {"status": "failed", "reason": "blocked reason"})]], tools2)+ assert outcome2.status == "failed"+ assert outcome2.reason == "blocked reason"+++async def test_completion_blocker_exception_fails_closed() -> None:+ # A transient storage error checking for a landed download is evidence of nothing -- it must+ # not let a download-gated task complete with no file. finish(failed) is unaffected.+ calls = 0++ async def blocker(_staged: frozenset[str]) -> str | None:+ nonlocal calls+ calls += 1+ raise RuntimeError("boom")++ tools = [make_finish_tool(completion_blocker=blocker)]+ script = [+ [("finish", {"status": "completed", "reason": "first attempt"})],+ [("finish", {"status": "failed", "reason": "give up"})],+ ]+ with capture_logs() as logs:+ outcome, caller = await _run(script, tools)++ assert outcome.status == "failed"+ assert outcome.reason == "give up"+ assert caller.calls == 2 # the completed attempt was rejected, forcing a second turn+ assert calls == 1 # a failed verdict never consults the blocker+ assert any(log["log_level"] == "warning" for log in logs)+ rejected_tool_messages = [+ m for m in outcome.messages if m.get("role") == "tool" and "Could not verify" in m.get("content", "")+ ]+ assert len(rejected_tool_messages) == 1+++async def test_staged_download_stays_excluded_for_the_rest_of_the_run() -> None:+ # file_upload's staged http(s) source fetch must not be treated as a landed download by any+ # LATER probe/blocker call this run -- not just skipped for the tool call that staged it.+ staged_downloads: set[str] = set()+ probe_seen: list[frozenset[str]] = []+ blocker_seen: list[frozenset[str]] = []++ async def probe(staged: frozenset[str]) -> str | None:+ probe_seen.append(staged)+ return None++ async def blocker(staged: frozenset[str]) -> str | None:+ blocker_seen.append(staged)+ return None++ async def stage_handler(_args: dict[str, Any]) -> ToolResult:+ return ToolResult.ok("uploaded", data={"staged_download": "in.pdf"})++ stage_tool = ToolSpec(+ name="file_upload",+ description="file_upload",+ parameters={"type": "object", "properties": {}},+ handler=stage_handler,+ billable=True,+ )+ click_calls: list[tuple[str, dict[str, Any]]] = []+ tools = [+ stage_tool,+ _billable_tool("click", click_calls),+ make_finish_tool(completion_blocker=blocker, staged_downloads=staged_downloads),+ ]+ script = [+ [("file_upload", {})],+ [("click", {"selector": "#a"})],+ [("finish", {"status": "completed", "reason": "done"})],+ ]+ outcome, _ = await _run(script, tools, completion_probe=probe, staged_downloads=staged_downloads)++ assert outcome.status == "completed"+ # The staging call itself never consults the probe (no download_notice); the next billable+ # call's probe already carries the name it staged.+ assert probe_seen == [frozenset({"in.pdf"})]+ assert blocker_seen == [frozenset({"in.pdf"})]diff --git a/tests/unit/test_workflow_block_engine.py b/tests/unit/test_workflow_block_engine.pyindex fea7aa991..0829408ca 100644--- a/tests/unit/test_workflow_block_engine.py+++ b/tests/unit/test_workflow_block_engine.py@@ -33,6 +33,7 @@ from skyvern.forge.sdk.workflow.models.block import (NavigationBlock,TaskBlock,UrlBlock,+ ValidationBlock,get_all_blocks,run_is_eligible_for_v3_ab,)@@ -96,21 +97,34 @@ async def _resolve()-def test_mixed_eligibility_run_download_block_disqualifies(scoped_context: SkyvernContext) -> None:+def test_mixed_eligibility_run_download_block_is_eligible(scoped_context: SkyvernContext) -> None:eligible_1 = _make_block(TaskBlock, label="t1")eligible_2 = _make_block(NavigationBlock, label="t2", navigation_goal="Apply to the job")download_block = _make_block(ActionBlock, label="dl", complete_on_download=True)blocks: list[BaseTaskBlock] = [eligible_1, eligible_2, download_block]- assert run_is_eligible_for_v3_ab(blocks, is_script_run=False) is False+ assert run_is_eligible_for_v3_ab(blocks, is_script_run=False) is True-def test_mixed_eligibility_run_file_download_block_disqualifies(scoped_context: SkyvernContext) -> None:+def test_mixed_eligibility_run_file_download_block_is_eligible(scoped_context: SkyvernContext) -> None:eligible_1 = _make_block(TaskBlock, label="t1")eligible_2 = _make_block(NavigationBlock, label="t2", navigation_goal="Apply to the job")file_download_block = _make_block(FileDownloadBlock, label="fd")blocks: list[BaseTaskBlock] = [eligible_1, eligible_2, file_download_block]+ assert run_is_eligible_for_v3_ab(blocks, is_script_run=False) is True+++def test_mixed_eligibility_run_download_gated_validation_block_is_not_eligible(+ scoped_context: SkyvernContext,+) -> None:+ # A validation block never acts on the page, so it can't trigger the download it would+ # complete on (SKY-14905); it must disqualify the whole run from the v3 A/B.+ eligible_1 = _make_block(TaskBlock, label="t1")+ eligible_2 = _make_block(NavigationBlock, label="t2", navigation_goal="Apply to the job")+ download_gated_validation = _make_block(ValidationBlock, label="dlv", complete_on_download=True)+ blocks: list[BaseTaskBlock] = [eligible_1, eligible_2, download_gated_validation]+assert run_is_eligible_for_v3_ab(blocks, is_script_run=False) is False@@ -311,7 +325,7 @@ def test_non_task_blocks_ignored_but_nested_loop_task_blocks_considered() -> Nonflat_without_loop = get_all_blocks([code_block, eligible])assert run_is_eligible_for_v3_ab(flat_without_loop, is_script_run=False) is True- ineligible_nested = _make_block(ActionBlock, label="nested_dl", complete_on_download=True)+ ineligible_nested = _make_block(TaskBlock, label="nested_pinned", engine=RunEngine.openai_cua)loop = ForLoopBlock(label="loop",output_parameter=_make_output_parameter("loop"),