Skip to content

Automate browser based workflows with AI

Check a Task V3 job application's legal-standing answers against the data before the form moves on (#8869)

pedrohsdb069f87ef9dcc
diff --git a/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsx b/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsx
index da2da3ec0..c65dd33ff 100644
--- a/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsx
+++ b/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsx
@@ -126,13 +126,6 @@ function TaskDetails() {
queryClient.invalidateQueries({
queryKey: ["taskWorkflowRun", task.workflow_run_id],
});
- queryClient.invalidateQueries({
- queryKey: [
- "workflowRun",
- workflow?.workflow_permanent_id,
- task.workflow_run_id,
- ],
- });
}
toast({
variant: "success",
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.test.tsx
index 864ba146c..7032cef51 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/components/NodeHeader.test.tsx
@@ -279,7 +279,7 @@ describe("NodeHeader block controls vs a retained run payload (SKY-15507)", () =
}
test("a live run targeted by the URL still makes the block controls inert", () => {
- queryClient.setQueryData(["workflowRun", "wf-test", "wr_1"], {
+ queryClient.setQueryData(["workflowRun", "wr_1"], {
workflow_run_id: "wr_1",
status: Status.Running,
});
@@ -292,7 +292,7 @@ describe("NodeHeader block controls vs a retained run payload (SKY-15507)", () =
});
test("a payload retained after the targeted run clears does not", () => {
- queryClient.setQueryData(["workflowRun", "wf-test", undefined], {
+ queryClient.setQueryData(["workflowRun", undefined], {
workflow_run_id: "wr_1",
status: Status.Running,
});
@@ -302,7 +302,7 @@ describe("NodeHeader block controls vs a retained run payload (SKY-15507)", () =
});
test("a paused block run leaves per-block controls idle", () => {
- queryClient.setQueryData(["workflowRun", "wf-test", "wr_paused"], {
+ queryClient.setQueryData(["workflowRun", "wr_paused"], {
workflow_run_id: "wr_paused",
status: Status.Paused,
});
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.test.tsx b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.test.tsx
index 207607a37..e256e0d76 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.test.tsx
@@ -225,7 +225,6 @@ function harness(client: QueryClient, path: string) {
// key of the run now being requested, which is what keepPreviousData hands over.
function seedRetained(client: QueryClient, requestedId: string, run: unknown) {
client.setQueryData(["workflowRun", requestedId], run);
- client.setQueryData(["workflowRun", "wpid_1", requestedId], run);
}
beforeEach(() => {
@@ -268,6 +267,33 @@ describe("run read path", () => {
expect(getClientMock).toHaveBeenCalledWith(undefined, "sans-api-v1");
expect(get.mock.calls[0]?.[0]).toBe(`/workflows/runs/${RUN_A_ID}`);
});
+
+ // Both hooks read this route, and the run page mounts both. Separate keys made
+ // the server build the whole run response twice per view and poll it twice over.
+ test("both run hooks share one cache entry, so a run is read once", async () => {
+ const get = vi.fn((url: string) =>
+ url.includes(RUN_A_ID)
+ ? Promise.resolve({ data: buildRun(RUN_A_ID, Status.Completed) })
+ : new Promise(() => {}),
+ );
+ getClientMock.mockResolvedValue({ get, post: vi.fn() });
+ const client = makeClient();
+ const { result } = renderHook(
+ () => ({
+ plain: useWorkflowRunQuery({ workflowRunId: RUN_A_ID }),
+ withWorkflow: useWorkflowRunWithWorkflowQuery({
+ workflowRunId: RUN_A_ID,
+ }),
+ }),
+ { wrapper: harness(client, "/agents/wpid_1/studio") },
+ );
+
+ await waitFor(() => {
+ expect(result.current.plain.data?.workflow_run_id).toBe(RUN_A_ID);
+ expect(result.current.withWorkflow.data?.workflow_run_id).toBe(RUN_A_ID);
+ });
+ expect(get.mock.calls).toHaveLength(1);
+ });
});
describe("run identity withholding", () => {
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.ts
index caa2ab158..571688382 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.ts
@@ -4,7 +4,7 @@ import { getClient } from "@/api/AxiosClient";
import {
Status,
WorkflowRunRetryFields,
- WorkflowRunStatusApiResponse,
+ WorkflowRunStatusApiResponseWithWorkflow,
} from "@/api/types";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { useFirstParam } from "@/hooks/useFirstParam";
@@ -53,31 +53,30 @@ function getRunStatusRefetchInterval(state: {
return RUN_STATUS_POLL_INTERVAL_MS;
}
-// The key is required so that passing an options object always states a run, even
-// when that run is undefined; omitting the object entirely is what defers to the
-// route. Optional-key typing made those two cases identical to tsc.
-function useWorkflowRunQuery(options?: { workflowRunId: string | undefined }) {
- const urlWorkflowRunId = useFirstParam("workflowRunId", "runId");
- const workflowRunId = options ? options.workflowRunId : urlWorkflowRunId;
- const workflowPermanentId = useWorkflowPermanentId();
+// Every reader of this route shares one cache entry. A second key over the same
+// run builds the whole response again per view and doubles the status poll.
+function useWorkflowRunByIdQuery(
+ workflowRunId: string | undefined,
+ enabled: boolean,
+) {
const credentialGetter = useCredentialGetter();
const activeOrgId = useActiveOrgId();
const activeOrgQueryKeyScope = getActiveOrgQueryKeyScope(activeOrgId);
// A fresh arrow each render defeats query-core's select memo, re-running the
// comparison and a deep equality check over the whole payload every time.
const selectRequestedRun = useCallback(
- (run: WorkflowRunStatusApiResponse) =>
+ (run: WorkflowRunStatusApiResponseWithWorkflow) =>
run.workflow_run_id === workflowRunId ? run : undefined,
[workflowRunId],
);
return useQuery<
- WorkflowRunStatusApiResponse,
+ WorkflowRunStatusApiResponseWithWorkflow,
DefaultError,
- WorkflowRunStatusApiResponse | undefined
+ WorkflowRunStatusApiResponseWithWorkflow | undefined
>({
queryKey: getOrgScopedQueryKey(
- ["workflowRun", workflowPermanentId, workflowRunId],
+ ["workflowRun", workflowRunId],
activeOrgQueryKeyScope,
),
// The by-run-id route still serves a run whose workflow version was retired
@@ -109,14 +108,25 @@ function useWorkflowRunQuery(options?: { workflowRunId: string | undefined }) {
}
return runIsLogicallyActive(query.state.data);
},
- enabled: !!workflowPermanentId && !!workflowRunId,
+ enabled: enabled && !!workflowRunId,
});
}
+// The key is required so that passing an options object always states a run, even
+// when that run is undefined; omitting the object entirely is what defers to the
+// route. Optional-key typing made those two cases identical to tsc.
+function useWorkflowRunQuery(options?: { workflowRunId: string | undefined }) {
+ const urlWorkflowRunId = useFirstParam("workflowRunId", "runId");
+ const workflowRunId = options ? options.workflowRunId : urlWorkflowRunId;
+ const workflowPermanentId = useWorkflowPermanentId();
+ return useWorkflowRunByIdQuery(workflowRunId, !!workflowPermanentId);
+}
+
export {
getRunStatusRefetchInterval,
POLL_OUTAGE_BUDGET_MS,
RUN_STATUS_OUTAGE_RETRY_INTERVAL_MS,
RUN_STATUS_POLL_INTERVAL_MS,
+ useWorkflowRunByIdQuery,
useWorkflowRunQuery,
};
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunWithWorkflowQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunWithWorkflowQuery.ts
index 65930ce01..661a8613b 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunWithWorkflowQuery.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunWithWorkflowQuery.ts
@@ -1,21 +1,5 @@
-import { runIsLogicallyActive } from "@/routes/workflows/workflowRun/runRetryState";
-import { useCallback } from "react";
-import { getClient } from "@/api/AxiosClient";
-import { WorkflowRunStatusApiResponseWithWorkflow } from "@/api/types";
-import { useCredentialGetter } from "@/hooks/useCredentialGetter";
-
-import {
- DefaultError,
- keepPreviousData,
- useQuery,
-} from "@tanstack/react-query";
import { useFirstParam } from "@/hooks/useFirstParam";
-import { getRunStatusRefetchInterval } from "./useWorkflowRunQuery";
-import {
- getActiveOrgQueryKeyScope,
- getOrgScopedQueryKey,
- useActiveOrgId,
-} from "@/store/ActiveOrgContext";
+import { useWorkflowRunByIdQuery } from "./useWorkflowRunQuery";
// The key is required so that passing an options object always states a run, even
// when that run is undefined; omitting the object entirely is what defers to the
@@ -26,55 +10,7 @@ function useWorkflowRunWithWorkflowQuery(options?: {
}) {
const urlWorkflowRunId = useFirstParam("workflowRunId", "runId");
const workflowRunId = options ? options.workflowRunId : urlWorkflowRunId;
- const credentialGetter = useCredentialGetter();
- const activeOrgId = useActiveOrgId();
- const activeOrgQueryKeyScope = getActiveOrgQueryKeyScope(activeOrgId);
- // A fresh arrow each render defeats query-core's select memo, re-running the
- // comparison and a deep equality check over the whole payload every time.
- const selectRequestedRun = useCallback(
- (run: WorkflowRunStatusApiResponseWithWorkflow) =>
- run.workflow_run_id === workflowRunId ? run : undefined,
- [workflowRunId],
- );
-
- return useQuery<
- WorkflowRunStatusApiResponseWithWorkflow,
- DefaultError,
- WorkflowRunStatusApiResponseWithWorkflow | undefined
- >({
- queryKey: getOrgScopedQueryKey(
- ["workflowRun", workflowRunId],
- activeOrgQueryKeyScope,
- ),
- queryFn: async ({ signal }) => {
- const client = await getClient(credentialGetter, "sans-api-v1");
- return client
- .get(`/workflows/runs/${encodeURIComponent(workflowRunId ?? "")}`, {
- signal,
- })
- .then((response) => response.data);
- },
- refetchInterval: (query) => getRunStatusRefetchInterval(query.state),
- // required for OS-level notifications to work (workflow run completion)
- refetchIntervalInBackground: true,
- placeholderData: keepPreviousData,
- // keepPreviousData serves the previous run's payload whenever the requested run
- // changes or clears, so withhold it rather than present it as the run in view.
- select: selectRequestedRun,
- refetchOnMount: (query) => {
- if (!query.state.data) {
- return false;
- }
- return runIsLogicallyActive(query.state.data) ? "always" : false;
- },
- refetchOnWindowFocus: (query) => {
- if (!query.state.data) {
- return false;
- }
- return runIsLogicallyActive(query.state.data);
- },
- enabled: (options?.enabled ?? true) && !!workflowRunId,
- });
+ return useWorkflowRunByIdQuery(workflowRunId, options?.enabled ?? true);
}
export { useWorkflowRunWithWorkflowQuery };
diff --git a/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsx b/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsx
index 43e7a48a0..3755d6495 100644
--- a/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/StudioTopBar.tsx
@@ -429,9 +429,6 @@ export function RunStopButton({ stopOnly = false }: { stopOnly?: boolean }) {
});
}
queryClient.invalidateQueries({ queryKey: ["workflowRun", activeRunId] });
- queryClient.invalidateQueries({
- queryKey: ["workflowRun", workflowPermanentId, activeRunId],
- });
queryClient.invalidateQueries({ queryKey: ["workflowRuns"] });
if (activeRunId) {
claimRunCompletionNotice(activeRunId, () => {
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/RunParametersDialog.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/RunParametersDialog.test.tsx
new file mode 100644
index 000000000..95aadddb1
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/RunParametersDialog.test.tsx
@@ -0,0 +1,82 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { render, waitFor } from "@testing-library/react";
+import { MemoryRouter, Route, Routes } from "react-router-dom";
+import { expect, test, vi } from "vitest";
+
+import { TooltipProvider } from "@/components/ui/tooltip";
+
+import { RunParametersDialog } from "./RunParametersDialog";
+
+vi.mock("@/hooks/useCredentialGetter", () => ({
+ useCredentialGetter: () => undefined,
+}));
+
+const RUN_ID = "wr_sched_e90d5502d63a672a2971";
+const WPID = "wpid_evidence";
+
+// Only the shared by-run-id entry is seeded, and no HTTP client is provided, so
+// the dialog can only render these inputs by reading that one cache entry.
+test("run inputs render from the shared by-run-id cache entry", async () => {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ client.setQueryData(["workflowRun", RUN_ID], {
+ workflow_run_id: RUN_ID,
+ status: "completed",
+ parameters: {
+ invoice_number: "INV-4471",
+ portal_url: "https://billing.example.com/invoices",
+ max_retries: 3,
+ notify: true,
+ },
+ workflow: { workflow_permanent_id: WPID, deleted_at: null },
+ });
+ client.setQueryData(["workflow", WPID], {
+ workflow_permanent_id: WPID,
+ workflow_definition: {
+ parameters: [
+ {
+ key: "invoice_number",
+ parameter_type: "workflow",
+ description: "Invoice to look up in the billing portal",
+ },
+ {
+ key: "portal_url",
+ parameter_type: "workflow",
+ description: "Billing portal entry point",
+ },
+ { key: "max_retries", parameter_type: "workflow", description: null },
+ { key: "notify", parameter_type: "workflow", description: null },
+ ],
+ },
+ });
+
+ const { baseElement } = render(
+ <QueryClientProvider client={client}>
+ <TooltipProvider delayDuration={0}>
+ <MemoryRouter initialEntries={[`/agents/${WPID}`]}>
+ <Routes>
+ <Route
+ path="/agents/:workflowPermanentId"
+ element={
+ <RunParametersDialog
+ open
+ onOpenChange={() => {}}
+ workflowPermanentId={WPID}
+ workflowRunId={RUN_ID}
+ />
+ }
+ />
+ </Routes>
+ </MemoryRouter>
+ </TooltipProvider>
+ </QueryClientProvider>,
+ );
+
+ await waitFor(() =>
+ expect(baseElement.textContent).toContain("invoice_number"),
+ );
+ expect(baseElement.textContent).toContain("Run Inputs");
+ expect(baseElement.textContent).toContain("portal_url");
+ expect(baseElement.textContent).toContain("max_retries");
+});
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/RunParametersDialog.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/RunParametersDialog.tsx
index 8f3fbdadf..37d35b798 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/RunParametersDialog.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/RunParametersDialog.tsx
@@ -1,17 +1,8 @@
import { ParametersDialogBase } from "../components/ParametersDialogBase";
-import { useGlobalWorkflowsQuery } from "../hooks/useGlobalWorkflowsQuery";
-import { useCredentialGetter } from "@/hooks/useCredentialGetter";
-import { getClient } from "@/api/AxiosClient";
-import { useQuery } from "@tanstack/react-query";
import { useWorkflowQuery } from "../hooks/useWorkflowQuery";
-import { WorkflowRunStatusApiResponse } from "@/api/types";
+import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWorkflowQuery";
import { Parameter } from "../types/workflowTypes";
import { getOrderedRunParameters } from "../utils";
-import {
- getActiveOrgQueryKeyScope,
- getOrgScopedQueryKey,
- useActiveOrgId,
-} from "@/store/ActiveOrgContext";
type Props = {
open: boolean;
@@ -26,33 +17,12 @@ export function RunParametersDialog({
workflowPermanentId,
workflowRunId,
}: Props) {
- const { data: globalWorkflows } = useGlobalWorkflowsQuery();
- const credentialGetter = useCredentialGetter();
const { data: workflow } = useWorkflowQuery({ workflowPermanentId });
- const activeOrgId = useActiveOrgId();
- const activeOrgQueryKeyScope = getActiveOrgQueryKeyScope(activeOrgId);
- const { data: run } = useQuery<WorkflowRunStatusApiResponse>({
- queryKey: getOrgScopedQueryKey(
- ["workflowRun", workflowPermanentId, workflowRunId, "dialog"],
- activeOrgQueryKeyScope,
- ),
- queryFn: async ({ signal }) => {
- const client = await getClient(credentialGetter);
- const params = new URLSearchParams();
- const isGlobalWorkflow = globalWorkflows?.some(
- (workflow) => workflow.workflow_permanent_id === workflowPermanentId,
- );
- if (isGlobalWorkflow) {
- params.set("template", "true");
- }
- return client
- .get(`/workflows/${workflowPermanentId}/runs/${workflowRunId}`, {
- params,
- signal,
- })
- .then((r) => r.data);
- },
- enabled: !!workflowPermanentId && !!workflowRunId && !!globalWorkflows,
+ // Reads the run through the shared by-run-id entry, so opening the dialog
+ // reuses whatever the run surfaces already fetched instead of building the
+ // whole run response again under a key of its own.
+ const { data: run } = useWorkflowRunWithWorkflowQuery({
+ workflowRunId: workflowRunId ?? undefined,
});
const defByKey = new Map(
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOverview.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOverview.tsx
index 97cb5cb6f..f1b2e166d 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOverview.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOverview.tsx
@@ -76,8 +76,6 @@ function WorkflowRunOverviewAttempt() {
useWorkflowRunTimelineQuery();
const workflowRunId = workflowRun?.workflow_run_id;
- const workflow = workflowRun?.workflow;
- const workflowPermanentId = workflow?.workflow_permanent_id;
const browserSessionId = workflowRun?.browser_session_id;
const { streamTransport } = useStreamTransport(browserSessionId);
@@ -85,7 +83,7 @@ function WorkflowRunOverviewAttempt() {
const invalidateQueries = useCallback(() => {
if (workflowRunId) {
queryClient.invalidateQueries({
- queryKey: ["workflowRun", workflowPermanentId, workflowRunId],
+ queryKey: ["workflowRun", workflowRunId],
});
queryClient.invalidateQueries({ queryKey: ["workflowRuns"] });
queryClient.invalidateQueries({
@@ -93,7 +91,7 @@ function WorkflowRunOverviewAttempt() {
});
queryClient.invalidateQueries({ queryKey: ["runs"] });
}
- }, [queryClient, workflowPermanentId, workflowRunId]);
+ }, [queryClient, workflowRunId]);
const handleVncClose = useCallback(() => {
setVncFailed(true);
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx
index 35d96235a..0a40403a4 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx
@@ -257,9 +257,6 @@ function WorkflowRunStream({
queryClient.invalidateQueries({
queryKey: ["workflowRuns"],
});
- queryClient.invalidateQueries({
- queryKey: ["workflowRun", workflowPermanentId, workflowRunId],
- });
queryClient.invalidateQueries({
queryKey: ["workflowRun", workflowRunId],
});
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index adbad8019..56764539e 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -2660,15 +2660,37 @@ class ForgeAgent:
step_cap=step_cap,
max_tokens=max_tokens,
)
- # Per-action persistence (parity with the step engine): the loop hands us each successful
- # action round, and we persist one DB row per action + one screenshot per round, so the Task
- # API's action_screenshot_urls and GET /tasks/{id}/actions are populated for v3. Additive and
- # best-effort — billing still meters off outcome.billable_actions below.
+ # Per-action persistence (parity with the step engine): the loop hands us the batch's actions
+ # as it dispatches them, and we persist one DB row + screenshot per hand-off, so the Task
+ # API's action_screenshot_urls and GET /tasks/{id}/actions are populated for v3 and the run
+ # view shows a long batch progressing instead of publishing it all at once (SKY-18164).
+ # Additive and best-effort — billing still meters off outcome.billable_actions below.
v3_persisted_actions: list[Action] = []
v3_round_index = 0
+ v3_round_billed = False
- async def _on_action_round(round_actions: list[RoundAction], turn_reasoning: str | None) -> None:
- nonlocal v3_round_index
+ def _close_v3_action_round() -> None:
+ nonlocal v3_round_index, v3_round_billed
+ # One budget unit per CHARGED round, not per action: every row a round produced shares
+ # the index, so it advances only once the round closes.
+ if v3_round_billed:
+ v3_round_index += 1
+ v3_round_billed = False
+
+ async def _on_action_round(
+ round_actions: list[RoundAction], turn_reasoning: str | None, /, *, round_done: bool
+ ) -> None:
+ try:
+ if round_actions:
+ await _persist_v3_action_rows(round_actions, turn_reasoning)
+ finally:
+ # In a `finally` so a persist that raised anyway cannot leave the index behind and
+ # make the next round's rows share this one's.
+ if round_done:
+ _close_v3_action_round()
+
+ async def _persist_v3_action_rows(round_actions: list[RoundAction], turn_reasoning: str | None) -> None:
+ nonlocal v3_round_billed
screenshot_artifact_id: str | None = None
try:
screenshot = await browser_state.take_post_action_screenshot(scrolling_number=0)
@@ -2687,13 +2709,14 @@ class ForgeAgent:
turn_reasoning, secret_values, placeholder_ids=placeholder_ids
)
turn_reasoning = turn_reasoning[:_TASKV3_REASONING_MAX_CHARS]
- # A round that bills nothing claims no budget unit, so its rows ride the LAST consumed
- # index (or the single Step's own order 0) the way the decision row below does: a fresh
- # index nothing later claims would be a distinct (task_id, step_order) pair, and the
- # workflow-run step budget counts those pairs.
- billable_round = any(entry.billable for entry in round_actions)
- row_step_order = v3_round_index if billable_round else max(v3_round_index - 1, 0)
for round_action in round_actions:
+ v3_round_billed = v3_round_billed or round_action.billable
+ # A row that bills nothing rides the LAST consumed index (or the single Step's own
+ # order 0) the way the decision row below does: the workflow-run step budget counts
+ # distinct (task_id, step_order) pairs, and a fresh index nothing later claims would
+ # open one of its own. Read per row because a row publishes before the rest of its
+ # batch has run, so it cannot see whether a later call bills.
+ row_step_order = v3_round_index if v3_round_billed else max(v3_round_index - 1, 0)
name, args, succeeded = round_action.tool, round_action.args, round_action.succeeded
try:
tool_args = _redact_tool_args(
@@ -2746,8 +2769,6 @@ class ForgeAgent:
)
except Exception:
LOG.warning("task_v3 failed to persist action row", task_id=task.task_id, exc_info=True)
- if billable_round:
- v3_round_index += 1
pre_submit_ring: PreSubmitCaptureRing | None = None
if not page_free_validation and is_run_sampled(
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index d748fae33..6e26b96c6 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -111,6 +111,7 @@ if TYPE_CHECKING:
from skyvern.forge.sdk.workflow.models.code_block_recorder import DocumentFailureReceipt, RecordingPage
from skyvern.forge.sdk.workflow.models.tags import CallerType
from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowRun, WorkflowRunStatus
+ from skyvern.forge.taskv3.answer_basis_audit import AnswerBasisAudit
from skyvern.forge.taskv3.loop import ToolSpec
from skyvern.forge.taskv3.tools import PageProvider
from skyvern.schemas.workflows import WorkflowStatus
@@ -1013,6 +1014,12 @@ class AgentFunction:
def task_v3_application_defaults(self, parameters: dict[str, Any] | None) -> tuple[str | None, str] | None:
return None
+ # An audit of the answers a run entered, consulted before the form moves on, or None (OSS: none).
+ def task_v3_answer_basis_audit(
+ self, parameters: dict[str, Any] | None, *, goal: str, organization_id: str | None, step: Step | None
+ ) -> AnswerBasisAudit | None:
+ return None
+
# The v3 code tool, or None when this deployment cannot run model-authored code under a sandbox.
# Uncalled while frame perception withholds the code tool on every run; it stays as the seam for
# when the action ledger records code-driven work. OSS ships no runner and always returns None.
diff --git a/skyvern/forge/sdk/api/llm/api_handler_factory.py b/skyvern/forge/sdk/api/llm/api_handler_factory.py
index b3af85c83..6d9c81861 100644
--- a/skyvern/forge/sdk/api/llm/api_handler_factory.py
+++ b/skyvern/forge/sdk/api/llm/api_handler_factory.py
@@ -2340,11 +2340,13 @@ class LLMAPIHandlerFactory:
# so litellm's router fallback (which only fires on exceptions) never
# recovers it. Gemini's non-configurable safety filters block PII-heavy
# prompts that safety_settings=BLOCK_NONE cannot recover, so retrying on
- # another Gemini tier hits the same block — jump straight to the first
- # non-Gemini fallback group. Fires for any Gemini model that produced the
- # block, including a standard tier litellm already fell back to (SKY-11766).
+ # another Gemini tier hits the same block — jump straight to a non-Gemini
+ # group: the config's dedicated escape group when it names one, else the
+ # first non-Gemini group in the fallback chain. Fires for any Gemini model
+ # that produced the block, including a standard tier litellm already fell
+ # back to (SKY-11766, SKY-18083).
if is_content_filtered_response(response) and "gemini" in (model_used or "").lower():
- non_gemini_fallback = next(
+ non_gemini_fallback = llm_config.content_filter_fallback_model_group or next(
(group for group in fallback_groups if "gemini" not in group.lower()), None
)
if non_gemini_fallback is not None:
@@ -2659,8 +2661,10 @@ class LLMAPIHandlerFactory:
parsed_response = parse_api_response(
response, llm_config.add_assistant_prefix, force_dict, prompt_name
)
- except BaseLLMError:
+ except BaseLLMError as e:
_llm_span.set_attribute("status", "error")
+ e.llm_key = llm_key
+ e.prompt_name = prompt_name
raise
parsed_response_json = json.dumps(parsed_response, indent=2)
if should_persist_llm_artifacts:
@@ -3313,8 +3317,10 @@ class LLMAPIHandlerFactory:
parsed_response = parse_api_response(
response, llm_config.add_assistant_prefix, force_dict, prompt_name
)
- except BaseLLMError:
+ except BaseLLMError as e:
_llm_span.set_attribute("status", "error")
+ e.llm_key = llm_key
+ e.prompt_name = prompt_name
raise
parsed_response_json = json.dumps(parsed_response, indent=2)
if should_persist_llm_artifacts:
@@ -4139,8 +4145,10 @@ class LLMCaller:
parsed_response = parse_api_response(
response, self.llm_config.add_assistant_prefix, force_dict, prompt_name
)
- except BaseLLMError:
+ except BaseLLMError as e:
_llm_span.set_attribute("status", "error")
+ e.llm_key = self.llm_key
+ e.prompt_name = prompt_name
raise
parsed_response_json = json.dumps(parsed_response, indent=2)
if should_persist_llm_artifacts:
diff --git a/skyvern/forge/sdk/api/llm/exceptions.py b/skyvern/forge/sdk/api/llm/exceptions.py
index ff3e51bbb..8ee88ff8c 100644
--- a/skyvern/forge/sdk/api/llm/exceptions.py
+++ b/skyvern/forge/sdk/api/llm/exceptions.py
@@ -6,7 +6,11 @@ LLM_PROVIDER_ERROR_RETRYABLE_TASK_TYPE = "LLMProviderErrorRetryableTask"
class BaseLLMError(SkyvernException):
- pass
+ # Stamped by the handler the error escaped from. Response-shape errors are raised deep in
+ # parsing, where neither is known, so callers that only see the exception (e.g. the complete
+ # verification) can't otherwise say which model route and prompt produced it.
+ llm_key: str | None = None
+ prompt_name: str | None = None
class MissingLLMProviderEnvVarsError(BaseLLMError):
diff --git a/skyvern/forge/taskv3/answer_basis_audit.py b/skyvern/forge/taskv3/answer_basis_audit.py
new file mode 100644
index 000000000..bfa8eae97
--- /dev/null
+++ b/skyvern/forge/taskv3/answer_basis_audit.py
@@ -0,0 +1,161 @@
+"""Check the answers Task V3 entered before a click that may move the form on, through a supplied audit.
+
+The audit decides which recorded answers have no basis in the run's data; this module only records what was
+answered and refuses every moving action while a flagged answer is unchanged, so the model switches it to a decline
+option, clears it or stops. With no audit supplied (the default), nothing is wrapped.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import re
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass
+from typing import Any, Protocol
+
+import structlog
+
+from skyvern.forge.taskv3.loop import (
+ CODE_TOOL_NAME,
+ OPENED_LIST_ERROR_CLASSES,
+ PICKED_OPTION_DATA_KEY,
+ TARGET_KIND_DATA_KEY,
+ TARGET_LABEL_DATA_KEY,
+ ToolRefusal,
+ ToolResult,
+ ToolSpec,
+ _may_submit,
+)
+
+LOG = structlog.get_logger(__name__)
+
+_MENU_ROW = re.compile(r"data-tv3-menu=")
+# The click tool's census of a menu it opened (tools._menu_note_fields).
+_MENU_NOTE_KEY = "menu_note"
+# Free text only: a typed password, email, URL, phone or number is never sent to the audit.
+_FREE_TEXT_KINDS = frozenset({"textbox", "textarea", "combobox"})
+# Longer typed text is a cover letter or a description, never a legal-standing answer.
+_MAX_AUDITED_WORDS = 25
+
+
+@dataclass(frozen=True)
+class RecordedAnswer:
+ question: str
+ value: str
+
+
+class AnswerBasisAudit(Protocol):
+ async def unsupported(self, answers: list[RecordedAnswer]) -> list[RecordedAnswer]:
+ """The answers to hold: no basis found, or an unreadable verdict; empty when the check could not run."""
+ ...
+
+
+# A field is its question label and the selector it was answered through: two questions can share a label.
+Field = tuple[str, str]
+
+
+def _data(result: ToolResult) -> dict[str, Any]:
+ return result.data if isinstance(result.data, dict) else {}
+
+
+def _label(result: ToolResult) -> str:
+ return str(_data(result).get(TARGET_LABEL_DATA_KEY) or "").strip()
+
+
+def _selector(args: dict[str, Any]) -> str:
+ return str(args.get("selector") or "").strip()
+
+
+def _may_move_on(tool: str, args: dict[str, Any]) -> bool:
+ # A click on a listed menu row picks an answer; it moves nothing on.
+ return _may_submit(tool, args) and not (tool == "click" and _MENU_ROW.search(_selector(args)))
+
+
+def apply_answer_basis_audit(tools: list[ToolSpec], audit: AnswerBasisAudit | None) -> None:
+ if audit is None:
+ return
+ # Each answer's audit starts when it is recorded, so the call overlaps the model's next turns instead of delaying
+ # the moving click.
+ pending: dict[Field, tuple[str, asyncio.Task[list[RecordedAnswer]]]] = {}
+ flagged: dict[Field, str] = {}
+ open_menu: dict[str, Field | None] = {"field": None}
+
+ def record(field: Field, value: str) -> None:
+ previous = pending.pop(field, None)
+ if previous is not None:
+ previous[1].cancel()
+ # An emptied field holds no answer, so its flag goes with it.
+ flagged.pop(field, None)
+ if field[0] and value:
+ pending[field] = (value, asyncio.create_task(audit.unsupported([RecordedAnswer(field[0], value)])))
+
+ async def hold(spec: ToolSpec, args: dict[str, Any]) -> bool:
+ """Refuse the moving action while a flagged answer is unchanged; True when it passes as that field's repair."""
+ while pending:
+ field, (value, task) = pending.popitem()
+ try:
+ found = await task
+ except Exception:
+ LOG.warning("taskv3 answer basis audit raised; not blocking", exc_info=True)
+ found = []
+ if found:
+ flagged[field] = value
+ if not flagged:
+ return False
+ # A click cannot be told from a submit before it lands, so only the flagged field's own control, or a row of an
+ # open list, goes through: that is the repair. A ref or mark is compared as the field was recorded, resolved.
+ if spec.name == "click":
+ selector, menu_row = await spec.address_probe(args) if spec.address_probe else (_selector(args), False)
+ if menu_row or any(selector == field[1] for field in flagged):
+ return True
+ LOG.info("taskv3 answer basis hold", tool=spec.name, flagged=len(flagged))
+ named = "; ".join(f"'{q}' answered '{v}' (field {s})" for (q, s), v in flagged.items())
+ raise ToolRefusal(
+ f"Not done: nothing in the data supports these answers: {named}. For each, choose the field's decline "
+ "option, such as prefer not to say, if it offers one. Otherwise, if the question is required, stop, naming "
+ "it; if it is optional, clear it and continue. Until each is changed, only a click on that field or on a "
+ "row of its open list goes through.",
+ error_class="answer_without_basis",
+ )
+
+ for spec in tools:
+ if spec.name not in ("click", "type", "select_option", "select_combobox", "press_key", CODE_TOOL_NAME):
+ continue
+
+ async def wrapped(
+ args: dict[str, Any],
+ _handler: Callable[[dict[str, Any]], Awaitable[ToolResult]] = spec.handler,
+ _spec: ToolSpec = spec,
+ ) -> ToolResult:
+ _tool = _spec.name
+ repair = _may_move_on(_tool, args) and await hold(_spec, args)
+ result = await _handler(args)
+ data = _data(result)
+ picked = str(data.get(PICKED_OPTION_DATA_KEY) or "") if _tool == "click" and result.status == "ok" else ""
+ opened = bool(data.get(_MENU_NOTE_KEY)) or result.error_class in OPENED_LIST_ERROR_CLASSES
+ if repair:
+ # A click let through as a repair that neither opened a list nor picked a row went somewhere else.
+ LOG.info("taskv3 answer basis hold passed", kind="repair" if picked or opened else "bypass")
+ if picked and open_menu["field"] is not None:
+ record(open_menu["field"], picked)
+ # A control that opened a list names the open question, an error included (a select_combobox with no
+ # match leaves its list open). A pick or any other completed action ends it, so a later pick is never
+ # credited to an earlier menu's question; an error that changed nothing leaves it open.
+ if opened:
+ open_menu["field"] = (_label(result), _selector(args))
+ elif result.status == "ok":
+ open_menu["field"] = None
+ if result.status != "ok" or picked:
+ return result
+ field = (_label(result), _selector(args))
+ if _tool == "select_combobox":
+ record(field, str(args.get("value") or ""))
+ elif _tool == "select_option":
+ record(field, str(args.get("label") or args.get("value") or ""))
+ elif _tool == "type" and str(data.get(TARGET_KIND_DATA_KEY) or "") in _FREE_TEXT_KINDS:
+ text = str(args.get("text") or "")
+ if len(text.split()) <= _MAX_AUDITED_WORDS:
+ record(field, text)
+ return result
+
+ spec.handler = wrapped
diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.py
index 4a0a4d424..a130857a1 100644
--- a/skyvern/forge/taskv3/engine.py
+++ b/skyvern/forge/taskv3/engine.py
@@ -37,6 +37,7 @@ from skyvern.forge.sdk.api.llm.config_registry import LLMConfigRegistry
from skyvern.forge.sdk.api.llm.exceptions import LLMProviderErrorRetryableTask
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.workflow.models.credential_release import CredentialReleaseGuard
+from skyvern.forge.taskv3.answer_basis_audit import apply_answer_basis_audit
from skyvern.forge.taskv3.code_surface import apply_surface, configured_surface
from skyvern.forge.taskv3.goal_check import (
GOAL_CHECK_TIMEOUT_SECONDS,
@@ -58,12 +59,12 @@ from skyvern.forge.taskv3.llm_call_params import build_call_kwargs
from skyvern.forge.taskv3.loop import (
DEFAULT_MAX_SETTLE_DEFERRALS,
PERCEPTION_RETAIN_CHARS_HIGH,
+ ActionRoundSink,
ActivityRecency,
CompletionBlocker,
CompletionGate,
CompletionProbe,
LoopOutcome,
- RoundAction,
SemanticCommitStats,
SubmitWatch,
ToolSpec,
@@ -262,7 +263,7 @@ async def run_task_v3_agent_loop(
prompt_name: str = "taskv3-agent-loop",
step: Any = None,
should_cancel: Callable[[], Awaitable[bool]] | None = None,
- on_action_round: Callable[[list[RoundAction], str | None], Awaitable[None]] | None = None,
+ on_action_round: ActionRoundSink | None = None,
on_pre_action: Callable[[str, dict[str, Any]], Awaitable[None]] | None = None,
extra_tools: list[ToolSpec] | None = None,
extra_system_guidance: str = "",
@@ -581,6 +582,18 @@ async def run_task_v3_agent_loop(
application_defaults = None if page_free else app.AGENT_FUNCTION.task_v3_application_defaults(parameters)
application_defaults_text, application_defaults_reason = application_defaults or (None, None)
defaults_text = "\n\n".join(text for text in (age_default_text, application_defaults_text) if text)
+ # The judge sees the data and the customer's instructions as the model does.
+ answer_audit = (
+ None
+ if page_free
+ else app.AGENT_FUNCTION.task_v3_answer_basis_audit(
+ refs.masked,
+ goal="\n\n".join(part for part in (model_goal, goal_instructions) if part),
+ organization_id=organization_id,
+ step=step,
+ )
+ )
+ apply_answer_basis_audit(tools, answer_audit)
# Only the acting model gets typed rows: the judge and re-ask read `model_goal` on their own model, and an oversized
# judge prompt fails open. Rows stay unminted because resolve_typed_text was chained to refs above.
prompt_goal = model_goal
diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.py
index 828b746ac..22882f03f 100644
--- a/skyvern/forge/taskv3/loop.py
+++ b/skyvern/forge/taskv3/loop.py
@@ -24,7 +24,7 @@ from collections import deque
from contextvars import ContextVar
from dataclasses import dataclass, field
from enum import Enum
-from typing import Any, Awaitable, Callable, Collection, Iterator, Literal, NamedTuple, Sequence, TypeVar
+from typing import Any, Awaitable, Callable, Collection, Iterator, Literal, NamedTuple, Protocol, Sequence, TypeVar
from urllib.parse import urlsplit
import structlog
@@ -130,6 +130,8 @@ ToolErrorClass = Literal[
"unsupported_argument",
"list_not_opened",
"rows_are_navigation",
+ # A click that may move the form on was held: answers entered this run have no basis in the data.
+ "answer_without_basis",
"rows_under_categories",
"list_unread",
"list_ambiguous",
@@ -309,6 +311,10 @@ class ToolRefusal(Exception):
# tokens. The label composition itself -- the floor vocabulary, the shape filter, the secret matcher --
# lives in target_label.py; this module only carries the two raw values from probe to `RoundAction`.
TARGET_LABEL_DATA_KEY = "target_label"
+# The option text a click on a menu row committed (page text: never on the call record).
+PICKED_OPTION_DATA_KEY = "picked_option"
+# A list the control opened but could not settle a row in: the list stays open for a pick.
+OPENED_LIST_ERROR_CLASSES = frozenset({"list_no_match", "list_unread", "list_ambiguous", "identical_rows"})
TARGET_KIND_DATA_KEY = "target_kind"
# The tool-result `data` key a recorded action's outcome rides on: the machine facts about what the
# call achieved (`requested_url`, `url`, `http_status`, `page_transitioned`, `navigation_dead_end`),
@@ -563,6 +569,21 @@ class RoundAction(NamedTuple):
error: str | None = None
+class ActionRoundSink(Protocol):
+ """Receives dispatched actions as they happen, in dispatch order.
+
+ Each call carries only what was recorded since the previous one, so a batch arrives in pieces
+ while it is still running. `round_done` marks the batch's last call — the only one whose list may
+ be empty, and where a caller advances per-round bookkeeping.
+ """
+
+ # Positional-only: the loop passes both by position, and binding their names here would force
+ # every implementation to spell them the same way.
+ async def __call__(
+ self, actions: list[RoundAction], turn_reasoning: str | None, /, *, round_done: bool
+ ) -> None: ...
+
+
# 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
@@ -610,6 +631,9 @@ class ToolSpec:
# Whether a call's target carries the toggle state observe prints (checked/pressed). Consulted only
# to exempt a click from the post-failure submit skip; set by the browser tools on click alone.
toggle_probe: Callable[[dict[str, Any]], Awaitable[bool]] | None = None
+ # The selector a click's arguments resolve to as the call's record keeps it after dispatch (a ref's durable
+ # selector, a mark's act tag), and whether it names a row of an open list; set on click alone.
+ address_probe: Callable[[dict[str, Any]], Awaitable[tuple[str, bool]]] | None = None
@property
def touches_page(self) -> bool:
@@ -3285,7 +3309,7 @@ async def run_agent_tool_loop(
organization_id: str | None = None,
call_kwargs: dict[str, Any] | None = None,
should_cancel: Callable[[], Awaitable[bool]] | None = None,
- on_action_round: Callable[[list[RoundAction], str | None], Awaitable[None]] | None = None,
+ on_action_round: ActionRoundSink | None = None,
on_pre_action: Callable[[str, dict[str, Any]], Awaitable[None]] | None = None,
max_tokens: int | None = None,
# The fixed input re-sent on every call is charged against max_tokens only up to this size, so a large task
@@ -4061,6 +4085,30 @@ async def run_agent_tool_loop(
st.reload_failed_nudge_due = False
action_nudges_due: list[tuple[str, dict[str, Any], int]] = []
round_actions: list[RoundAction] = []
+ # How much of `round_actions` the caller has already been handed. Waiting for the whole batch
+ # before handing anything over hid a long batch's progress and then published it at once
+ # (SKY-18164).
+ handed_off = 0
+
+ async def _hand_off_actions(*, round_done: bool) -> None:
+ """Hand the caller everything recorded since the last call so it can persist as we go.
+
+ A persistence hiccup must not abort an otherwise-good run, so failures are contained here.
+ """
+ nonlocal handed_off
+ if on_action_round is None or not round_actions:
+ return
+ fresh = round_actions[handed_off:]
+ # The closing call fires even with nothing fresh left: a batch whose last recorded action
+ # was already handed over mid-flight still has to be told its round ended.
+ if not fresh and not round_done:
+ return
+ handed_off = len(round_actions)
+ try:
+ await on_action_round(fresh, text or reasoning_summary or None, round_done=round_done)
+ except Exception:
+ LOG.warning("taskv3 on_action_round callback failed", turn=st.turns, exc_info=True)
+
# A hard 404/410 from an in-loop navigate, applied only AFTER the batch so a same-turn fallback
# navigate can clear it — the model is told to batch aggressively, and terminating on the first
# of a batched [navigate(dead), navigate(live)] would discard the recovery it planned.
@@ -4106,6 +4154,10 @@ async def run_agent_tool_loop(
st.canonical.progress(_ProgressEvidence.CROSS_BATCH_MOVEMENT)
batch_fp_after: str | None = None
for idx, (tool_call_id, tool_name, args) in enumerate(tool_calls):
+ # Publish the previous call's action before this one runs, while the page still holds
+ # what that action left behind. At the top because every exit below is a `break` or a
+ # pre-dispatch `continue`; the closing hand-off flushes the last iteration's work.
+ await _hand_off_actions(round_done=False)
# Enforce the cap per tool call so one batched turn cannot overrun it, and honor a
# cancellation that arrives mid-batch before the next click/type/submit runs. Neither
# this call nor the rest of the batch executes, so answer them as skipped.
@@ -5388,14 +5440,9 @@ async def run_agent_tool_loop(
# under-counts equivalent work.
if turn_charged:
st.action_steps += 1
- # Hand the round's executed actions to the caller so it can persist per-action artifacts
- # (screenshot, DB rows) — kept out of this transport-agnostic core, like should_cancel. A
- # persistence hiccup must not abort an otherwise-good run, so failures are contained here.
- if round_actions and on_action_round is not None:
- try:
- await on_action_round(round_actions, text or reasoning_summary or None)
- except Exception:
- LOG.warning("taskv3 on_action_round callback failed", turn=st.turns, exc_info=True)
+ # Close the round: flush whatever the batch's last call recorded and tell the caller the
+ # round ended, so its per-round bookkeeping (the action row's round index) advances once.
+ await _hand_off_actions(round_done=True)
if st.outcome is None:
st.outcome = LoopOutcome("loop_error", "loop exited without an outcome")
diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.py
index 625378441..79bc32e98 100644
--- a/skyvern/forge/taskv3/tools.py
+++ b/skyvern/forge/taskv3/tools.py
@@ -84,7 +84,9 @@ from skyvern.forge.taskv3.loop import (
CLICK_DISPATCHED_DATA_KEY,
FILL_TOOLS,
NAVIGATION_DEAD_END_STATUSES,
+ OPENED_LIST_ERROR_CLASSES,
PAGE_UNAVAILABLE_ERROR,
+ PICKED_OPTION_DATA_KEY,
REF_SELECTOR_RE,
TARGET_KIND_DATA_KEY,
TARGET_LABEL_DATA_KEY,
@@ -14063,8 +14065,10 @@ def build_browser_tools(
# Only a call that acted carries a name/kind. The probe resolves the selector on its own,
# so on a refusal the two can disagree about which element the selector meant -- a cloned
# marker matching twice resolves here to the clone and is then refused for exactly that
- # ambiguity, and naming the twin nobody touched is worse than naming nothing.
- if (name is None and kind is None) or result.status != "ok":
+ # ambiguity, and naming the twin nobody touched is worse than naming nothing. A list that could not
+ # settle a row is not a refusal: the control was opened and its list waits for a pick.
+ acted = result.status == "ok" or result.error_class in OPENED_LIST_ERROR_CLASSES
+ if (name is None and kind is None) or not acted:
return result
data = {**(result.data or {})}
if name is not None:
@@ -14180,6 +14184,7 @@ def build_browser_tools(
# What the last menu-open note reported, for the click's call record; reset before each reaction read.
menu_note_census: dict[str, Any] = {}
+ menu_pick: dict[str, str] = {}
def _menu_note(found: dict[str, Any], selector: str, *, clicked_row: bool = False) -> str:
menu_note_census.clear()
@@ -14196,6 +14201,11 @@ def build_browser_tools(
# Returns (note, commit_error) — at most one set. Raises are the caller's to swallow (fail-open:
# a probe failure must degrade to the bare pre-feature ok, never fail the click).
opt = _DOWNLOAD_NOTICE_SANITIZE_RE.sub("", _model_text(pre.get("optText") or "", 80)) or selector
+
+ def _selected(text: str) -> str:
+ menu_pick[PICKED_OPTION_DATA_KEY] = text
+ return f"Selected option {text!r}"
+
if pre.get("isOption"):
# Commit evidence, any one suffices: navigation, the menu closing, the option's own state
# changing vs the post-hover baseline (multi-select menus commit WITHOUT closing), or a
@@ -14313,21 +14323,18 @@ def build_browser_tools(
await asyncio.sleep(0.3)
async def _state_change_note(opt_text: str, after: dict[str, Any]) -> str:
- picked = f"Selected option {opt_text!r} — its state changed (the menu stayed open)."
# A row that did not grow cannot have expanded into itself, so nothing competes with
# the commit reading and the probe is not worth its page walk -- which is the
# ordinary multi-select click.
- if not _grew(after):
- return picked
- child = await _child_menu_note()
+ child = await _child_menu_note() if _grew(after) else None
if not child:
- return picked
+ return f"{_selected(opt_text)} — its state changed (the menu stayed open)."
# It grew AND opened child rows, so a selection attribute means it did both and
# dropping either half would be a false report. Without the "menu stayed open" clause:
# the child note has just renumbered the markers, so what the model was holding is
# precisely what did not stay.
if _picked(after):
- return f"Selected option {opt_text!r} — its state changed.\n{child}"
+ return f"{_selected(opt_text)} — its state changed.\n{child}"
return child
async def _same_document() -> bool | None:
@@ -14344,19 +14351,19 @@ def build_browser_tools(
if url_before and url_now and url_now != url_before and await _same_document() is not True:
# A moved URL is a navigation unless the page says it is the same document --
# a menu that syncs its selection into the query string never left.
- return f"Selected option {opt!r} — {_navigated_phrase()}.", None
+ return f"{_selected(opt)} — {_navigated_phrase()}.", None
after, navigated = await _after_read()
if after is None and navigated:
- return f"Selected option {opt!r} — {_navigated_phrase()}.", None
+ return f"{_selected(opt)} — {_navigated_phrase()}.", None
if after is not None and not after.get("stillOpen"):
child = await _cascade_child_note()
if child:
return child, None
- return f"Selected option {opt!r} — the menu closed.", None
+ return f"{_selected(opt)} — the menu closed.", None
if after is not None and _committed_state(after):
held, failure = await _state_holds(after.get("optState") or "")
if failure == "navigated":
- return f"Selected option {opt!r} — {_navigated_phrase()}.", None
+ return f"{_selected(opt)} — {_navigated_phrase()}.", None
if failure == "unreadable":
return _unverified("state-hold")
if held is not None:
@@ -14368,17 +14375,17 @@ def build_browser_tools(
settled, navigated = await _after_read()
if settled is None:
if navigated:
- return f"Selected option {opt!r} — {_navigated_phrase()}.", None
+ return f"{_selected(opt)} — {_navigated_phrase()}.", None
return _unverified("post-click" if after is None else "settle")
if not settled.get("stillOpen"):
child = await _cascade_child_note()
if child:
return child, None
- return f"Selected option {opt!r} — the menu closed.", None
+ return f"{_selected(opt)} — the menu closed.", None
if _committed_state(settled):
held, failure = await _state_holds(settled.get("optState") or "")
if failure == "navigated":
- return f"Selected option {opt!r} — {_navigated_phrase()}.", None
+ return f"{_selected(opt)} — {_navigated_phrase()}.", None
if failure == "unreadable":
return _unverified("state-hold")
if held is not None:
@@ -14540,7 +14547,23 @@ def build_browser_tools(
except Exception:
reach_pre = None
enable_deadline = time.monotonic() + _DISABLED_CLICK_GRACE_SECONDS
- while isinstance(reach_pre, dict) and reach_pre.get("exists") and reach_pre.get("disabled"):
+
+ async def _gate_refuses() -> bool:
+ """Whether the driver would refuse this target as not enabled, right now.
+
+ Asked of the driver rather than re-derived: its rule is wider than `:disabled` and the
+ remainder is version-dependent (see cloud_docs/task-v3/README.md).
+ """
+ if isinstance(reach_pre, dict) and reach_pre.get("exists") and reach_pre.get("disabled"):
+ return True
+ if isinstance(reach_pre, dict) and not reach_pre.get("exists"):
+ # Nothing to ask about, and asking costs the resolve timeout before failing open.
+ return False
+ # In-page first: `_engine_enabled` fails open on a selector it cannot resolve, so asking it
+ # about a target re-rendered away mid-grace would skip the stale-selector branch below.
+ return not await _engine_enabled(page, selector)
+
+ while await _gate_refuses():
if time.monotonic() >= enable_deadline:
return ToolResult.error(
f"{selector} is disabled — it cannot be clicked until the page enables it",
@@ -14899,6 +14922,7 @@ def build_browser_tools(
# option); the menu reaction is the authority on that before the toggle verdict stands.
if pre is not None:
menu_note_census.clear()
+ menu_pick.clear()
try:
note, commit_error = await _click_reaction(
page, selector, pre, url_before, doc_planted=doc_planted
@@ -14906,6 +14930,7 @@ def build_browser_tools(
except Exception:
note, commit_error = None, None
transition_data.update(menu_note_census)
+ transition_data.update(menu_pick)
if commit_error is not None:
return ToolResult.error(commit_error, data=transition_data)
if note:
@@ -14919,12 +14944,14 @@ def build_browser_tools(
if pre is None:
return ToolResult.ok(base, data=transition_data)
menu_note_census.clear()
+ menu_pick.clear()
try:
note, commit_error = await _click_reaction(page, selector, pre, url_before, doc_planted=doc_planted)
except Exception:
LOG.debug("taskv3 click reaction probe failed", selector=selector, exc_info=True)
return ToolResult.ok(base, data=transition_data)
transition_data.update(menu_note_census)
+ transition_data.update(menu_pick)
if commit_error is not None:
return ToolResult.error(commit_error, data=transition_data)
return ToolResult.ok(base + "\n" + note if note else base, data=transition_data)
@@ -14996,8 +15023,29 @@ def build_browser_tools(
if isinstance(probe, dict) and probe.get("exists"):
# fill() waits for "enabled" and "editable" on its own, so without these the run pays a
# second full timeout for a state the probe has already read.
- if probe.get("disabled") or probe.get("readOnly"):
- raise _FieldNotEditable(selector, bool(probe.get("readOnly")))
+ if probe.get("readOnly"):
+ raise _FieldNotEditable(selector, True)
+ if probe.get("disabled"):
+ raise _FieldNotEditable(selector, False)
+ # `disabled` above is the page script's `:disabled`, narrower than what fill() waits on, so
+ # the driver is asked for the rest of its rule -- see the click gate. Held for that gate's
+ # grace rather than refused outright, because fill()'s own wait used to cover a field the
+ # page releases a moment later.
+ enable_deadline = time.monotonic() + _DISABLED_CLICK_GRACE_SECONDS
+ while not await _engine_enabled(page, selector):
+ if time.monotonic() >= enable_deadline:
+ raise _FieldNotEditable(selector, False)
+ await asyncio.sleep(0.1)
+ # Re-read rather than only polling the driver: a page that answers the grace by making
+ # the field readonly has made it un-typable for a different reason, and the accurate
+ # message is the one the caller renders.
+ held: Any = None
+ with contextlib.suppress(Exception):
+ held = await _probe_evaluate(
+ page, _TYPING_REACH_PROBE_JS, selector, await _probe_arg(page, selector)
+ )
+ if isinstance(held, dict) and held.get("exists") and held.get("readOnly"):
+ raise _FieldNotEditable(selector, True)
occluded = bool(isinstance(probe, dict) and probe.get("occluded"))
occluder = probe.get("occluder") if isinstance(probe, dict) else None
if occluded and not probe.get("skinned"):
@@ -21447,6 +21495,33 @@ def build_browser_tools(
result = await _resolve_toggle_target(dict(args))
return result.status == "ok" and result.data is not None and result.data.get("toggle") is True
+ async def _address_target(args: dict[str, Any]) -> ToolResult:
+ page, error = await _resolve_page()
+ if error is not None:
+ return error
+ target = page.locator(str(args.get("selector") or ""))
+ row = None
+ if await target.count() == 1:
+ row = await target.get_attribute("data-tv3-menu", timeout=_TOGGLE_PROBE_EVALUATE_TIMEOUT_MS)
+ return ToolResult.ok("", data={"menu_row": row is not None})
+
+ _resolve_address_target = _with_act_by_mark(
+ _with_ref_resolution("address_probe", _with_selector_guard(_address_target))
+ )
+
+ async def _click_address(args: dict[str, Any]) -> tuple[str, bool]:
+ selector = str(args.get("selector") or "")
+ if args.get("mark") is None and not REF_SELECTOR_RE.match(selector):
+ return selector, False
+ resolved = dict(args)
+ try:
+ result = await _resolve_address_target(resolved)
+ except Exception:
+ return "", False
+ if result.status != "ok":
+ return "", False
+ return str(resolved.get("selector") or ""), bool((result.data or {}).get("menu_row"))
+
tools = [
_spec(
"observe",
@@ -21681,6 +21756,7 @@ def build_browser_tools(
_tool_spec.handler = _with_refusal_result(_tool_spec.handler)
if _tool_spec.name == "click":
_tool_spec.toggle_probe = _click_targets_toggle
+ _tool_spec.address_probe = _click_address
# Inside the download signal, so a download notice stays the last thing in a result.
_apply_text_delta(tools)
_apply_download_signal(tools, downloads_dir)
diff --git a/skyvern/library/ai_locator.py b/skyvern/library/ai_locator.py
index b159e7ac7..f855a0fb4 100644
--- a/skyvern/library/ai_locator.py
+++ b/skyvern/library/ai_locator.py
@@ -12,7 +12,7 @@ from playwright.async_api import Locator, Page
from skyvern.core.script_generations.skyvern_page_ai import SkyvernPageAi
from skyvern.exceptions import ActionDeadlineExceeded
-from skyvern.webeye.action_deadline import under_action_deadline
+from skyvern.webeye.action_deadline import cancellable_driver_call, under_action_deadline
LOCATOR_CHAIN_METHODS = {
"nth",
@@ -74,7 +74,7 @@ class AILocator(Locator):
selector_locator = self._page.locator(self._selector, **self._selector_kwargs)
# The probe is a driver call, so it shares the bound the caller's action carries.
async with under_action_deadline(budget_ms=budget_ms):
- count = await selector_locator.count()
+ count = await cancellable_driver_call(selector_locator.count)
if count > 0:
self._resolved_locator = selector_locator
return self._resolved_locator
@@ -134,6 +134,6 @@ class AILocator(Locator):
# Inference inside the resolve stays unbounded; the driver call carries its own timeout,
# which a driver that stopped answering never honours.
async with under_action_deadline(budget_ms=budget_ms):
- return await method(*args, **kwargs)
+ return await cancellable_driver_call(lambda: method(*args, **kwargs))
return async_method_wrapper
diff --git a/skyvern/schemas/llm.py b/skyvern/schemas/llm.py
index 10f1434ba..8e3e23d1f 100644
--- a/skyvern/schemas/llm.py
+++ b/skyvern/schemas/llm.py
@@ -160,6 +160,12 @@ class LLMRouterConfig(LLMConfigBase):
# Gemini and Anthropic still apply their own thinking-budget shapes.
# Appended last so no existing field's positional slot shifts.
pin_reasoning_effort: bool = False
+ # A model group that only the handler's Gemini content-filter escape hatch dispatches to.
+ # Deliberately outside fallback_model_group: a Gemini-only chain cannot recover a
+ # content_filter block (every tier reproduces it), but adding a non-Gemini group to the
+ # chain would also change ordinary error failover and cost. Set it to name a filter-free
+ # group reachable only on that one path.
+ content_filter_fallback_model_group: str | None = None
def __post_init__(self) -> None:
_resolve_generation_defaults(self, self.max_tokens, self.temperature)
diff --git a/skyvern/webeye/action_deadline.py b/skyvern/webeye/action_deadline.py
index dfe208829..acba4263e 100644
--- a/skyvern/webeye/action_deadline.py
+++ b/skyvern/webeye/action_deadline.py
@@ -1,9 +1,11 @@
from __future__ import annotations
import asyncio
+import contextvars
import math
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Awaitable, Callable
from contextlib import asynccontextmanager
+from typing import Any, TypeVar
from skyvern.exceptions import ActionDeadlineExceeded
from skyvern.forge.sdk.core import skyvern_context
@@ -12,6 +14,9 @@ from skyvern.webeye.browser_health import BrowserOperation
ACTION_DEADLINE_HEADROOM_MS = 5000
DEADLINE_REARM_INTERVAL_SECONDS = 1.0
+T = TypeVar("T")
+_UNSET = object()
+
def cancellation_pending() -> bool:
"""Whether this task carries an unhandled cancellation request.
@@ -37,6 +42,51 @@ def record_browser_timeout(operation: BrowserOperation = BrowserOperation.EVALUA
skyvern_context.record_browser_timeout(operation)
+def _retrieve_outcome(call: asyncio.Task[Any]) -> None:
+ # A call cancelled too late to stop can still end in an error, and by then nobody is awaiting it.
+ if not call.cancelled():
+ call.exception()
+
+
+def _publish_context_writes(context: contextvars.Context) -> None:
+ for var in context:
+ if var.get(_UNSET) is not context[var]:
+ var.set(context[var])
+
+
+async def cancellable_driver_call(call: Callable[[], Awaitable[T]]) -> T:
+ """Issue a driver call in a task of its own, so cancelling the caller reaches the driver's cleanup.
+
+ playwright and patchright abandon a pending protocol reply from a done-callback on the task that
+ issued the call, and only when that task ends cancelled (``_impl/_connection.py::ProtocolCallback``).
+ A deadline cancels the coroutine that awaits the call inside a task which carries on, so a call
+ awaited directly keeps its reply pending and the driver's late error lands on a future nobody
+ retrieves -- which asyncio reports at error level as an exception that was never retrieved."""
+ # A cancellation request lives on the task that received it, and the task below is a fresh one, so
+ # a guard inside the call (``cancel_aware``) can no longer see one the caller already carries.
+ # Issuing the call at all is what that guard is there to prevent, so answer it here instead.
+ raise_if_cancelled()
+
+ async def issue() -> T:
+ return await call()
+
+ context = contextvars.copy_context()
+ call_task = asyncio.create_task(issue(), context=context)
+ call_task.add_done_callback(_retrieve_outcome)
+ try:
+ return await call_task
+ except asyncio.CancelledError:
+ # A cancellation that arrives after the call has answered never reached the task.
+ call_task.cancel()
+ raise
+ finally:
+ # The task ran in a copy of this context, so a write inside the call would otherwise be lost.
+ # A cancelled call may still be unwinding, and publishing a binding it is about to restore
+ # would outlive the call, so only a finished one is published.
+ if call_task.done() and not call_task.cancelled():
+ _publish_context_writes(context)
+
+
@asynccontextmanager
async def under_action_deadline(
*, budget_ms: int | None, operation: BrowserOperation | None = None
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index b01d918a0..9d5d38024 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -114,7 +114,7 @@ from skyvern.forge.sdk.api.llm.api_handler_factory import (
get_org_aware_primary_llm_api_handler,
get_org_aware_secondary_llm_api_handler,
)
-from skyvern.forge.sdk.api.llm.exceptions import LLMProviderError
+from skyvern.forge.sdk.api.llm.exceptions import BaseLLMError, LLMProviderError
from skyvern.forge.sdk.api.llm.schema_validator import extraction_shape_matches, validate_and_fill_extraction_result
from skyvern.forge.sdk.artifact.storage.base import get_download_retry_started_at, is_file_from_retry_attempt
from skyvern.forge.sdk.browser_action_preflight import preflight_action, preflight_derived_action
@@ -10950,6 +10950,8 @@ async def handle_complete_action(
LOG.exception(
"Failed to verify the complete action",
workflow_run_id=task.workflow_run_id,
+ llm_key=e.llm_key if isinstance(e, BaseLLMError) else None,
+ prompt_name=e.prompt_name if isinstance(e, BaseLLMError) else None,
)
return [ActionFailure(exception=e)]
diff --git a/skyvern/webeye/utils/page.py b/skyvern/webeye/utils/page.py
index 4c98d0415..d92df8949 100644
--- a/skyvern/webeye/utils/page.py
+++ b/skyvern/webeye/utils/page.py
@@ -36,7 +36,7 @@ from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.settings_manager import SettingsManager
from skyvern.forge.sdk.trace import apply_context_attrs, traced, traced_span
from skyvern.utils.contained_effects import contained_effect
-from skyvern.webeye.action_deadline import under_action_deadline
+from skyvern.webeye.action_deadline import cancellable_driver_call, under_action_deadline
from skyvern.webeye.browser_driver_errors import is_driver_error, is_driver_timeout_error
from skyvern.webeye.browser_engine import SKYCDP_ENGINE_NAME, BrowserEngineSelection
from skyvern.webeye.browser_errors import BrowserTargetClosedError
@@ -989,7 +989,9 @@ async def _bounded_page_screenshot(
# The driver's own screenshot timeout has been seen not to fire for hours on an unresponsive page. The
# action deadline also re-cancels a driver that swallows the first cancellation and rejects a late image.
async with under_action_deadline(budget_ms=int(timeout)):
- screenshot = await page.screenshot(path=file_path, timeout=timeout, full_page=full_page, animations=animations)
+ screenshot = await cancellable_driver_call(
+ lambda: page.screenshot(path=file_path, timeout=timeout, full_page=full_page, animations=animations)
+ )
return screenshot
@@ -2027,7 +2029,7 @@ class SkyvernFrame:
deadline = deadline if deadline is not None else loop.time() + timeout_ms / 1000
try:
async with asyncio.timeout_at(deadline):
- result = await evaluate_expression()
+ result = await cancellable_driver_call(evaluate_expression)
except asyncio.TimeoutError as error:
skyvern_context.record_browser_timeout(BrowserOperation.EVALUATE)
# Re-raised and handled by the caller (scrape retries / failure classification),
@@ -2128,7 +2130,7 @@ class SkyvernFrame:
async with asyncio.timeout(inject_budget):
# Same dispatch helper so a prefixed Page re-injects
# JS_FUNCTION_DEFS via Runtime.evaluate (preserving the marker).
- await _dispatch_evaluate(frame, JS_FUNCTION_DEFS, None)
+ await cancellable_driver_call(lambda: _dispatch_evaluate(frame, JS_FUNCTION_DEFS, None))
except asyncio.TimeoutError as error:
LOG.warning(
"Skyvern timed out trying to analyze the page during domUtils.js re-injection",
@@ -2162,7 +2164,7 @@ class SkyvernFrame:
raise SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page")
try:
async with asyncio.timeout(retry_budget):
- result = await evaluate_expression()
+ result = await cancellable_driver_call(evaluate_expression)
# The final evaluate answered, so this run-wide health tally is no longer stale.
skyvern_context.record_browser_success()
return result
diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py
index 85e8875d8..04d40e717 100644
--- a/tests/unit/conftest.py
+++ b/tests/unit/conftest.py
@@ -949,6 +949,45 @@ async def settle_or_fail(coro: Awaitable[_T], wait_seconds: float = 2.0) -> tupl
return task, elapsed
+class DriverReplyProbe:
+ """A driver call that keeps its protocol reply the way playwright and patchright do.
+
+ The pending reply is abandoned from a done-callback on the task that issued the call, and only if
+ that task ends cancelled (``_impl/_connection.py::ProtocolCallback``). A caller that is cancelled
+ without its task ending therefore leaves the reply live, and the driver's late error lands on it
+ with nobody left to retrieve it."""
+
+ def __init__(self, error: BaseException, answers_after_seconds: float = 0.05) -> None:
+ self._error = error
+ self._answers_after_seconds = answers_after_seconds
+ self.called = asyncio.Event()
+ self.reply: asyncio.Future[Any] | None = None
+
+ async def __call__(self, *args: object, **kwargs: object) -> Any:
+ loop = asyncio.get_running_loop()
+ reply: asyncio.Future[Any] = loop.create_future()
+ self.reply = reply
+ self.called.set()
+ issuing_task = asyncio.current_task()
+ assert issuing_task is not None
+
+ def abandon_reply(task: asyncio.Task[Any]) -> None:
+ if task.cancelled():
+ reply.cancel()
+
+ issuing_task.add_done_callback(abandon_reply)
+ loop.call_later(self._answers_after_seconds, lambda: reply.done() or reply.set_exception(self._error))
+ # The driver abandons an unanswered reply on the line after this await, which cancellation skips.
+ await asyncio.wait({reply}, return_when=asyncio.FIRST_COMPLETED)
+ return reply.result()
+
+ async def orphaned_reply(self, wait_seconds: float = 2.0) -> bool:
+ """Whether the late reply carries an error nobody retrieved -- asyncio's never-retrieved line."""
+ assert self.reply is not None, "the driver was never called"
+ await asyncio.wait({self.reply}, timeout=wait_seconds)
+ return self.reply.done() and not self.reply.cancelled() and self.reply.exception() is not None
+
+
def stalled_scrolling_capture(entered: asyncio.Event, timeout_ms: float) -> AsyncMock:
"""A ``take_fullpage_screenshot`` stand-in that drives the real ``take_scrolling_screenshot`` with a stalled
stitched-capture helper, so a caller test exercises the primitive's own deadline."""
diff --git a/tests/unit/force_stub_app.py b/tests/unit/force_stub_app.py
index 38ecec451..2f4afd735 100644
--- a/tests/unit/force_stub_app.py
+++ b/tests/unit/force_stub_app.py
@@ -86,6 +86,7 @@ def create_forge_stub_app() -> ForgeApp:
fake_app_module.AGENT_FUNCTION.MAGIC_LINK_CLOSE_SIGNALS = base_agent_function.MAGIC_LINK_CLOSE_SIGNALS
fake_app_module.AGENT_FUNCTION.task_v3_age_default = base_agent_function.task_v3_age_default
fake_app_module.AGENT_FUNCTION.task_v3_application_defaults = base_agent_function.task_v3_application_defaults
+ fake_app_module.AGENT_FUNCTION.task_v3_answer_basis_audit = base_agent_function.task_v3_answer_basis_audit
fake_app_module.AGENT_FUNCTION.serialize_codeblock_parameters = base_agent_function.serialize_codeblock_parameters
fake_app_module.AGENT_FUNCTION.redact_codeblock_parameter_values = (
base_agent_function.redact_codeblock_parameter_values
diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.py
index 695db9cc8..d1a068b1b 100644
--- a/tests/unit/test_agent_task_v3.py
+++ b/tests/unit/test_agent_task_v3.py
@@ -198,7 +198,10 @@ async def _run_execute_task_v3(
if cb is not None and action_rounds:
for i, round_actions in enumerate(action_rounds):
turn_text = action_round_texts[i] if action_round_texts and i < len(action_round_texts) else None
- await cb(round_actions, turn_text)
+ # Mirrors the real loop: each dispatched action is handed over on its own as the
+ # batch runs, and the round's last hand-off closes it.
+ for position, round_action in enumerate(round_actions):
+ await cb([round_action], turn_text, round_done=position == len(round_actions) - 1)
if on_loop is not None:
on_loop(kwargs)
if on_loop_async is not None:
@@ -1156,9 +1159,9 @@ async def test_resolve_v3_llm_key_falls_back_when_flag_read_raises(monkeypatch:
@pytest.mark.asyncio
async def test_execute_task_v3_persists_per_action_screenshots_and_rows(monkeypatch: pytest.MonkeyPatch) -> None:
- # The loop reports two successful action rounds; the closure must capture one screenshot per
- # round and persist one actions-table row per action (FK'ing the round's screenshot), so the
- # Task API's action_screenshot_urls and GET /tasks/{id}/actions are populated for v3.
+ # The loop reports three successful actions across two rounds; the closure must capture one
+ # screenshot per ACTION and persist one actions-table row per action (FK'ing that screenshot), so
+ # the Task API's action_screenshot_urls and GET /tasks/{id}/actions are populated for v3.
from skyvern.forge import agent as agent_mod
outcome = LoopOutcome(status="completed", reason="done", billable_actions=["click", "type", "click"])
@@ -1180,9 +1183,10 @@ async def test_execute_task_v3_persists_per_action_screenshots_and_rows(monkeypa
extracted_information_schema=None,
)
assert step.status == StepStatus.completed
- # One SCREENSHOT_ACTION artifact per action round plus one for the terminal decision row;
- # one actions-table row per action plus the decision row itself.
- assert agent_mod.app.ARTIFACT_MANAGER.create_artifact.await_count == 3
+ # One SCREENSHOT_ACTION artifact per ACTION plus one for the terminal decision row: rows publish
+ # as each action is dispatched, so each one is shot on the page it left behind rather than
+ # sharing the frame the batch ended on. One actions-table row per action plus the decision row.
+ assert agent_mod.app.ARTIFACT_MANAGER.create_artifact.await_count == 4
assert agent_mod.app.DATABASE.workflow_params.create_action.await_count == 4
persisted = [c.kwargs["action"] for c in agent_mod.app.DATABASE.workflow_params.create_action.await_args_list[:-1]]
# organization_id/task_id/step_id must be set, or GET /tasks/{id}/actions filters the rows out;
@@ -1236,7 +1240,7 @@ async def test_execute_task_v3_persists_a_navigation_as_a_goto_url_row(monkeypat
assert navigation.status == ActionStatus.completed
assert navigation.intention == f"Navigated to {_GOTO_OUTCOME['requested_url']}"
assert navigation.reasoning == "the contact link 404s, typing the contact URL instead"
- assert navigation.screenshot_artifact_id == "artifact-1" # the round's own screenshot
+ assert navigation.screenshot_artifact_id == "artifact-1" # the action's own screenshot
assert navigation.response is not None
assert _GOTO_OUTCOME["url"] in navigation.response and "HTTP 200" in navigation.response
# Recorded, never metered: the navigation round leaves the step index where it was, so the click
@@ -4917,6 +4921,37 @@ async def test_execute_task_v3_recordable_round_persists_without_budget_unit(
]
+async def test_execute_task_v3_mixed_round_opens_one_budget_pair_per_charged_round(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # A row publishes before the rest of its batch has run, so a navigation sitting AHEAD of a click
+ # in the same round cannot see that the click will bill, and it stamps the previous round's index
+ # instead of the one the click goes on to claim. What has to hold is the budget's own unit — the
+ # count of distinct (task_id, step_order) pairs, one per charged round — not which of the two
+ # indices a non-billable row rides.
+ outcome = LoopOutcome(status="completed", reason="done", billable_actions=["click", "click"])
+ nav = RoundAction("navigate", {"url": _GOTO_OUTCOME["requested_url"]}, True, None, None, False, _GOTO_OUTCOME)
+ click = RoundAction("click", {"selector": "#send"}, True, billable=True)
+ await _run_execute_task_v3(
+ monkeypatch,
+ outcome,
+ action_rounds=[[nav, click], [nav, click]],
+ data_extraction_goal=None,
+ extracted_information_schema=None,
+ )
+ calls = agent_module.app.DATABASE.workflow_params.create_action.await_args_list
+ stamped = [(c.kwargs["action"].action_type, c.kwargs["action"].step_order) for c in calls]
+ assert stamped == [
+ (ActionType.GOTO_URL, 0),
+ (ActionType.CLICK, 0),
+ (ActionType.GOTO_URL, 0),
+ (ActionType.CLICK, 1),
+ (ActionType.COMPLETE, 1),
+ ]
+ assert len({step_order for _action_type, step_order in stamped}) == 2 # two charged rounds
+
+
@pytest.mark.asyncio
async def test_execute_task_v3_refused_round_persists_a_failed_row_without_a_budget_unit(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_api_handler_factory.py b/tests/unit/test_api_handler_factory.py
index 8ceb559b5..d92b736c8 100644
--- a/tests/unit/test_api_handler_factory.py
+++ b/tests/unit/test_api_handler_factory.py
@@ -1724,12 +1724,16 @@ def _make_three_tier_router_config(
fallback_groups: list[str],
redis_max_connections: int | None = None,
litellm_models: dict[str, str] | None = None,
+ content_filter_fallback_model_group: str | None = None,
) -> LLMRouterConfig:
"""Synthetic 3+ tier router config that doesn't depend on the cloud
`LLMConfigRegistry` registration that's conditional on prod env vars.
`litellm_models` overrides the per-group litellm model string (flex-style
- routers point two groups at the same underlying model)."""
+ routers point two groups at the same underlying model).
+ `content_filter_fallback_model_group` adds a deployment that is reachable but
+ deliberately absent from the fallback chain, like the flex routers' escape hatch."""
litellm_models = litellm_models or {}
+ escape_groups = [content_filter_fallback_model_group] if content_filter_fallback_model_group else []
deployments = [
LLMRouterModelConfig(
model_name="primary-group",
@@ -1740,7 +1744,7 @@ def _make_three_tier_router_config(
model_name=group,
litellm_params={"model": litellm_models.get(group, f"openai/{group}"), "timeout": 60},
)
- for group in fallback_groups
+ for group in [*fallback_groups, *escape_groups]
]
return LLMRouterConfig(
model_name="test-router",
@@ -1754,6 +1758,7 @@ def _make_three_tier_router_config(
redis_max_connections=redis_max_connections,
main_model_group="primary-group",
fallback_model_group=fallback_groups,
+ content_filter_fallback_model_group=content_filter_fallback_model_group,
routing_strategy="simple-shuffle",
num_retries=0,
disable_cooldowns=True,
@@ -2050,6 +2055,69 @@ async def test_router_does_not_retry_content_filter_without_non_gemini_fallback(
assert calls == ["primary-group"], f"must not retry when there is no non-Gemini fallback; got calls={calls}"
+async def test_router_retries_content_filter_on_dedicated_escape_group(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The two-tier Gemini flex routers fall back flex -> standard, both Gemini, so a content_filter
+ block has no filter-free tier in the chain and used to surface as a parse failure. They now name
+ a non-Gemini escape group that stays OUT of the chain — litellm's ordinary failover and the flex
+ cost profile are untouched, and only this retry reaches it (SKY-18083)."""
+
+ calls: list[str] = []
+
+ class _FilterThenEscapeRouter:
+ def __init__(self, **kwargs: Any) -> None:
+ pass
+
+ async def acompletion(self, *, model: str, messages: Any, **kwargs: Any) -> FakeLLMResponse:
+ calls.append(model)
+ if len(calls) == 1:
+ return FakeLLMResponse("gemini-3.1-flash-lite", content=None, finish_reason="content_filter")
+ return FakeLLMResponse("gpt-5", content='{"actions": []}')
+
+ monkeypatch.setattr(api_handler_factory.litellm, "Router", _FilterThenEscapeRouter)
+
+ config = _make_three_tier_router_config(
+ fallback_groups=["vertex-gemini-standard-fallback"],
+ content_filter_fallback_model_group="gpt-5-fallback",
+ )
+ _stub_for_router_test(monkeypatch, llm_key="TEST_CONTENT_FILTER_ESCAPE_GROUP", config=config)
+
+ handler = LLMAPIHandlerFactory.get_llm_api_handler_with_router("TEST_CONTENT_FILTER_ESCAPE_GROUP")
+ result = await handler(prompt='{"actions": []}', prompt_name="extract-actions")
+
+ assert calls == ["primary-group", "gpt-5-fallback"], (
+ f"handler must retry the escape group named by the config, skipping the Gemini tier; got calls={calls}"
+ )
+ assert result == {"actions": []}
+
+
+async def test_parse_failure_names_the_llm_key_and_prompt(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A response-shape failure is raised deep in parsing, so callers that only catch the exception
+ (the complete verification logs it as `Failed to verify the complete action`) could not say which
+ route produced it. The handler stamps the attribution on the way out (SKY-18083)."""
+ from skyvern.forge.sdk.api.llm.exceptions import BaseLLMError
+
+ class _UnparseableContentRouter:
+ def __init__(self, **kwargs: Any) -> None:
+ pass
+
+ async def acompletion(self, *, model: str, messages: Any, **kwargs: Any) -> FakeLLMResponse:
+ return FakeLLMResponse("gemini-3.1-flash-lite", content=None, finish_reason="content_filter")
+
+ monkeypatch.setattr(api_handler_factory.litellm, "Router", _UnparseableContentRouter)
+
+ config = _make_three_tier_router_config(fallback_groups=[])
+ _stub_for_router_test(monkeypatch, llm_key="TEST_PARSE_FAILURE_ATTRIBUTION", config=config)
+
+ handler = LLMAPIHandlerFactory.get_llm_api_handler_with_router("TEST_PARSE_FAILURE_ATTRIBUTION")
+ with pytest.raises(BaseLLMError) as excinfo:
+ await handler(prompt='{"actions": []}', prompt_name="check-user-goal")
+
+ assert excinfo.value.llm_key == "TEST_PARSE_FAILURE_ATTRIBUTION"
+ assert excinfo.value.prompt_name == "check-user-goal"
+
+
@pytest.mark.asyncio
async def test_router_does_not_retry_content_filter_for_non_gemini_model(monkeypatch: pytest.MonkeyPatch) -> None:
"""The escape hatch is scoped to Gemini's non-configurable filter. A content_filter from a
diff --git a/tests/unit/test_navigation_recovery.py b/tests/unit/test_navigation_recovery.py
index b2baf78fb..7cf790156 100644
--- a/tests/unit/test_navigation_recovery.py
+++ b/tests/unit/test_navigation_recovery.py
@@ -16,6 +16,7 @@ from skyvern.webeye.utils.page import (
_wait_for_navigation_settle,
with_dom_utils,
)
+from tests.unit.conftest import DriverReplyProbe
class TestIsNavigationContextLost:
@@ -136,6 +137,19 @@ class TestEvaluateWithNavigationRecovery:
result = await SkyvernFrame.evaluate(frame=frame, expression="() => 42", timeout_ms=30000)
assert result == 42
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("message", ["Execution context was destroyed", "Frame has been detached."])
+ async def test_an_abandoned_evaluate_leaves_the_driver_no_unretrieved_reply(self, message: str) -> None:
+ """A navigation that destroys the context answers an evaluate the deadline already gave up on."""
+ probe = DriverReplyProbe(PlaywrightError(f"Page.evaluate: {message}"))
+ frame = AsyncMock()
+ frame.evaluate = probe
+
+ with pytest.raises(SkyvernPageAnalysisTimeout):
+ await SkyvernFrame.evaluate(frame=frame, expression="() => 42", timeout_ms=25)
+
+ assert not await probe.orphaned_reply()
+
@pytest.mark.asyncio
@pytest.mark.parametrize("error_type", [PlaywrightError, RuntimeError])
async def test_reference_error_propagates_without_recovery(self, error_type: type[Exception]) -> None:
diff --git a/tests/unit/test_taskv3_answer_basis_audit.py b/tests/unit/test_taskv3_answer_basis_audit.py
new file mode 100644
index 000000000..329134567
--- /dev/null
+++ b/tests/unit/test_taskv3_answer_basis_audit.py
@@ -0,0 +1,200 @@
+from typing import Any
+
+import pytest
+from structlog.testing import capture_logs
+
+from skyvern.forge.taskv3.answer_basis_audit import RecordedAnswer, apply_answer_basis_audit
+from skyvern.forge.taskv3.loop import (
+ CODE_TOOL_NAME,
+ PICKED_OPTION_DATA_KEY,
+ TARGET_KIND_DATA_KEY,
+ TARGET_LABEL_DATA_KEY,
+ ToolRefusal,
+ ToolResult,
+ ToolSpec,
+)
+
+DEBARMENT = "Have you ever been excluded from a federal program?"
+
+
+class _Audit:
+ def __init__(self, flag: set[str] | None = None, fail: bool = False) -> None:
+ self.flag = flag or set()
+ self.fail = fail
+ self.seen: list[list[RecordedAnswer]] = []
+
+ async def unsupported(self, answers: list[RecordedAnswer]) -> list[RecordedAnswer]:
+ self.seen.append(answers)
+ if self.fail:
+ raise TimeoutError
+ return [a for a in answers if a.value in self.flag]
+
+
+# What each ref resolves to, and whether it is a row of an open list.
+_REFS = {"ref=7": ('[data-tv3="7"]', True), "ref=30": ("#q1", False), "ref=40": ("#submit", False)}
+
+
+async def _address(args: dict[str, Any]) -> tuple[str, bool]:
+ selector = str(args.get("selector") or "")
+ return _REFS.get(selector, (selector, False))
+
+
+def _tools(dispatched: list[tuple[str, dict[str, Any]]]) -> list[ToolSpec]:
+ def make(name: str) -> ToolSpec:
+ async def handler(args: dict[str, Any]) -> ToolResult:
+ dispatched.append((name, args))
+ sel = str(args.get("selector") or "")
+ if name == "click" and "_row" in args:
+ return ToolResult("ok", f"clicked {sel}", {PICKED_OPTION_DATA_KEY: args["_row"]})
+ if name == "click" and sel.startswith("#q"):
+ # A question's opener: its menu opens.
+ data = {TARGET_LABEL_DATA_KEY: args.get("_label", DEBARMENT), "menu_note": "listed"}
+ return ToolResult("ok", f"clicked {sel}", data)
+ label = args.get("_label", "")
+ if name == "select_combobox" and args.get("_no_match"):
+ content = f"opened {sel} but no option matched {args['value']!r}"
+ return ToolResult("error", content, {TARGET_LABEL_DATA_KEY: label}, error_class="list_no_match")
+ return ToolResult("ok", f"{name} done", {TARGET_LABEL_DATA_KEY: label, TARGET_KIND_DATA_KEY: "textbox"})
+
+ return ToolSpec(name=name, description="", parameters={}, handler=handler, address_probe=_address)
+
+ names = ("click", "type", "select_option", "select_combobox", "press_key", CODE_TOOL_NAME, "observe")
+ return [make(n) for n in names]
+
+
+def _by_name(tools: list[ToolSpec], name: str) -> ToolSpec:
+ return next(t for t in tools if t.name == name)
+
+
+async def _held(tools: list[ToolSpec], name: str, args: dict[str, Any]) -> str:
+ with pytest.raises(ToolRefusal) as held:
+ await _by_name(tools, name).handler(args)
+ assert held.value.error_class == "answer_without_basis"
+ return str(held.value)
+
+
+async def test_an_unsupported_answer_holds_every_moving_action_until_it_is_replaced() -> None:
+ dispatched: list[tuple[str, dict[str, Any]]] = []
+ tools = _tools(dispatched)
+ apply_answer_basis_audit(tools, _Audit(flag={"No"}))
+ click = _by_name(tools, "click").handler
+ submit = {"selector": "#submit"}
+
+ # A menu pick is recorded against the question whose menu it closed.
+ await click({"selector": "#q1"})
+ await click({"selector": '[data-tv3-menu="2"]', "_row": "No"})
+ message = await _held(tools, "click", submit)
+ assert DEBARMENT in message and "#q1" in message
+ # Neither a resubmit, the next question's opener, a submit by ref, an Enter nor the code tool spends the hold: each
+ # is refused and Submit stays refused after them.
+ await _held(tools, "click", submit)
+ await _held(tools, "click", {"selector": "#q2", "_label": "Are you willing to relocate?"})
+ await _held(tools, "click", {"selector": "ref=40"})
+ await _held(tools, "press_key", {"key": "Enter"})
+ await _held(tools, CODE_TOOL_NAME, {"code": "await page.click('#submit')"})
+ await _held(tools, "click", submit)
+ assert [args for name, args in dispatched if name == "click"].count(submit) == 0
+
+ # Repair: the flagged field's own opener and a ref pick of a list row go through.
+ with capture_logs() as logs:
+ await click({"selector": "#q1"})
+ await click({"selector": "ref=7", "_row": "I prefer not to answer"})
+ assert [e["kind"] for e in logs if e["event"] == "taskv3 answer basis hold passed"] == ["repair", "repair"]
+ await click(submit)
+ assert ("click", submit) in dispatched
+
+ # Picking the held value again brings the hold back.
+ await click({"selector": "#q1"})
+ await click({"selector": '[data-tv3-menu="2"]', "_row": "No"})
+ await _held(tools, "click", submit)
+
+
+async def test_a_click_let_through_as_a_repair_that_picks_nothing_is_logged_as_a_bypass() -> None:
+ tools = _tools([])
+ apply_answer_basis_audit(tools, _Audit(flag={"No"}))
+ click = _by_name(tools, "click").handler
+ await click({"selector": "#q1"})
+ await click({"selector": '[data-tv3-menu="2"]', "_row": "No"})
+ await click({"selector": "#q1"})
+ with capture_logs() as logs:
+ await click({"selector": "ref=30"})
+ assert [e["kind"] for e in logs if e["event"] == "taskv3 answer basis hold passed"] == ["bypass"]
+
+
+async def test_two_fields_with_the_same_label_are_audited_apart() -> None:
+ tools = _tools([])
+ audit = _Audit(flag={"United States"})
+ apply_answer_basis_audit(tools, audit)
+ select = _by_name(tools, "select_option").handler
+ await select({"selector": "#citizenship-country", "label": "United States", "_label": "Country"})
+ await select({"selector": "#address-country", "label": "Canada", "_label": "Country"})
+
+ message = await _held(tools, "click", {"selector": "#submit"})
+ assert "'Country' answered 'United States' (field #citizenship-country)" in message
+ assert "Canada" not in message
+
+
+async def test_the_refusal_stops_only_on_a_required_question_and_a_cleared_answer_lifts_the_hold() -> None:
+ dispatched: list[tuple[str, dict[str, Any]]] = []
+ tools = _tools(dispatched)
+ apply_answer_basis_audit(tools, _Audit(flag={"Canadian", "Yes"}))
+ await _by_name(tools, "type").handler({"selector": "#nat", "text": "Canadian", "_label": "Nationality"})
+ await _by_name(tools, "select_combobox").handler({"selector": "#auth", "value": "Yes", "_label": "Authorized?"})
+
+ message = await _held(tools, "click", {"selector": "#next"})
+ assert "if the question is required, stop" in message and "if it is optional, clear it and continue" in message
+ assert "'Nationality' answered 'Canadian'" in message and "'Authorized?' answered 'Yes'" in message
+
+ await _by_name(tools, "type").handler({"selector": "#nat", "text": "", "_label": "Nationality"})
+ await _by_name(tools, "select_combobox").handler({"selector": "#auth", "value": "", "_label": "Authorized?"})
+ await _by_name(tools, "click").handler({"selector": "#next"})
+ assert ("click", {"selector": "#next"}) in dispatched
+
+
+async def test_a_pick_is_credited_to_the_menu_left_open_never_to_an_earlier_one() -> None:
+ tools = _tools([])
+ audit = _Audit(flag={"Other"})
+ apply_answer_basis_audit(tools, audit)
+ click = _by_name(tools, "click").handler
+ combobox = _by_name(tools, "select_combobox").handler
+
+ await click({"selector": "#q1"})
+ await click({"selector": '[data-tv3-menu="1"]', "_row": "I don't need sponsorship"})
+ # A select_combobox with no matching row fails but leaves its list open for a pick.
+ await combobox({"selector": "ref=11", "value": "United States", "_label": "Nationality", "_no_match": True})
+ await click({"selector": '[data-tv3-menu="2"]', "_row": "Other"})
+ # A pick with no menu left open is credited to no question.
+ await click({"selector": '[data-tv3-menu="1"]', "_row": "Yes"})
+ # Return submits like Enter, so it waits for the audits and is held.
+ assert "'Nationality' answered 'Other'" in await _held(tools, "press_key", {"key": "Return"})
+
+ recorded = sum(audit.seen, [])
+ assert RecordedAnswer(DEBARMENT, "I don't need sponsorship") in recorded
+ assert RecordedAnswer("Nationality", "Other") in recorded
+ assert RecordedAnswer(DEBARMENT, "Other") not in recorded
+ assert all(a.value != "Yes" for a in recorded)
+
+
+async def test_reads_add_no_audit_and_an_audit_that_raises_never_blocks() -> None:
+ dispatched: list[tuple[str, dict[str, Any]]] = []
+ tools = _tools(dispatched)
+ audit = _Audit(fail=True)
+ apply_answer_basis_audit(tools, audit)
+ await _by_name(tools, "select_combobox").handler({"value": "Yes", "_label": "Authorized to work?"})
+ # The audit starts when the answer is recorded; a read neither starts nor waits for one.
+ await _by_name(tools, "observe").handler({})
+ await _by_name(tools, "click").handler({"selector": "#next"})
+ assert ("click", {"selector": "#next"}) in dispatched and len(audit.seen) == 1
+
+
+def test_no_audit_leaves_every_handler_untouched() -> None:
+ tools = _tools([])
+ before = [t.handler for t in tools]
+ apply_answer_basis_audit(tools, None)
+ assert [t.handler for t in tools] == before
diff --git a/tests/unit/test_taskv3_engine.py b/tests/unit/test_taskv3_engine.py
index 79493bbae..05af1a0db 100644
--- a/tests/unit/test_taskv3_engine.py
+++ b/tests/unit/test_taskv3_engine.py
@@ -1600,6 +1600,42 @@ async def test_operator_defaults_ride_the_task_message_only_and_leave_the_system
assert (age_log["application_defaults_rendered"], age_log["application_defaults_reason"]) == (False, None)
+async def test_the_answer_audit_wraps_the_run_tools_and_sees_the_instructions(monkeypatch: pytest.MonkeyPatch) -> None:
+ hook_calls: list[dict[str, Any]] = []
+ applied: list[tuple[list[str], object]] = []
+ audit = object()
+
+ def hook(parameters: Any, *, goal: str, organization_id: Any, step: Any) -> object:
+ hook_calls.append({"parameters": parameters, "goal": goal})
+ return audit
+
+ def spy(tools: list[Any], answer_audit: Any) -> None:
+ applied.append(([t.name for t in tools], answer_audit))
+
+ monkeypatch.setattr(app.AGENT_FUNCTION, "task_v3_answer_basis_audit", hook)
+ monkeypatch.setattr(engine_mod, "apply_answer_basis_audit", spy)
+ signed = "https://files.example.test/uploads/deadbeef/resume.pdf?token=eyJhbGciOiJIUzI1NiJ9.c2lnbmVk.QQ"
+ for page_free in (False, True):
+ await run_task_v3_agent_loop(
+ page_provider=_fixed_page_provider(_FakePage()),
+ llm_caller=_ScriptedCaller([[("finish", {"status": "completed", "reason": "ok"})]]),
+ goal="Apply.",
+ goal_instructions="Answer citizenship from the resume.",
+ parameters={"resume": "text", "file": signed},
+ page_free=page_free,
+ )
+
+ # Only the run with a page is audited, and its judge reads the instructions beside the goal and the data with
+ # signed URLs masked: a raw one would hand its token to the judge's model.
+ assert len(hook_calls) == 1
+ assert hook_calls[0]["parameters"] == mask_opaque_urls({"resume": "text", "file": signed}).masked
+ assert "eyJhbGci" not in str(hook_calls[0]["parameters"]) and "text" in str(hook_calls[0]["parameters"])
+ assert "Apply." in hook_calls[0]["goal"] and "Answer citizenship from the resume." in hook_calls[0]["goal"]
+ assert "click" in applied[0][0] and applied[0][1] is audit
+ assert applied[1][1] is None
+
+
@pytest.mark.asyncio
async def test_terminal_log_carries_duration_and_block_type() -> None:
# The v1-vs-v3 wall-time dashboard reads this log line; it needs the loop's own wall-clock and
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index 5bbfda4e8..afe64474b 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -3230,7 +3230,7 @@ async def _atomic_block_run(
clicks: list[tuple[str, dict[str, Any]]] = []
rounds: list[list[RoundAction]] = []
- async def _on_round(round_actions: list[RoundAction], _text: str | None) -> None:
+ async def _on_round(round_actions: list[RoundAction], _text: str | None, *, round_done: bool) -> None:
rounds.append(list(round_actions))
script = [
@@ -4516,39 +4516,44 @@ def test_budget_extension_gate_credits_the_headroom_the_grant_itself_creates() -
@pytest.mark.asyncio
-async def test_on_action_round_fires_once_per_action_round() -> None:
- # The callback fires once per action ROUND (a turn with >=1 successful billable action), not per
- # tool and not on perception-only turns, and receives that round's (name, args) list plus the
- # assistant text the SAME turn produced.
- rounds: list[list[tuple[str, dict[str, Any]]]] = []
+async def test_on_action_round_hands_each_action_over_before_the_next_one_dispatches() -> None:
+ # A batch's actions reach the caller as they are dispatched, so rows land while the batch is
+ # still running: handing the whole batch over at the end left a run's five actions executing over
+ # ~16s and then published all five rows at once, hiding the progress (SKY-18164). Perception-only
+ # turns still hand over nothing, and every call carries the SAME turn's assistant text.
+ log: list[Any] = []
round_texts: list[str | None] = []
- async def _on_round(actions: list[tuple[str, dict[str, Any]]], turn_text: str | None) -> None:
- rounds.append(actions)
+ async def _on_round(actions: list[RoundAction], turn_text: str | None, *, round_done: bool) -> None:
+ log.append(("handed", [action.tool for action in actions], round_done))
round_texts.append(turn_text)
- obs, clk, typ = [], [], []
- observe = _recording_tool("observe", obs) # perception, not billable
- click = _recording_tool("click", clk)
+ observe = _recording_tool("observe", log) # perception, not billable
+ click = _recording_tool("click", log)
click.billable = True
- type_ = _recording_tool("type", typ)
+ type_ = _recording_tool("type", log)
type_.billable = True
script = [
[("observe", {})], # perception-only -> no callback
- [("click", {"selector": "#a"}), ("type", {"selector": "#b", "text": "x"})], # 1 round, 2 tools -> 1 call
+ [("click", {"selector": "#a"}), ("type", {"selector": "#b", "text": "x"})],
[("finish", {"status": "completed", "reason": "ok"})],
]
texts = ["looking around", "clicking the field and typing into it", "done"]
outcome, _ = await _run(script, [observe, click, type_, make_finish_tool()], on_action_round=_on_round, texts=texts)
assert outcome.status == "completed"
- assert len(rounds) == 1
- assert rounds[0] == [
- RoundAction("click", {"selector": "#a"}, True, billable=True),
- RoundAction("type", {"selector": "#b", "text": "x"}, True, billable=True),
+ assert log == [
+ ("observe", {}),
+ ("click", {"selector": "#a"}),
+ # The click is published BEFORE the type below runs — the page still shows what the click
+ # did, which is the frame a caller's post-action screenshot needs.
+ ("handed", ["click"], False),
+ ("type", {"selector": "#b", "text": "x"}),
+ # Closing the round flushes the batch's last action and advances the caller's round index once.
+ ("handed", ["type"], True),
]
- # The action round's text is the SECOND turn's ("clicking the field..."), not the first
- # (perception-only) or third (finish) turn's text.
- assert round_texts == [texts[1]]
+ # Both hand-offs carry the SECOND turn's text, not the first (perception-only) or third
+ # (finish) turn's.
+ assert round_texts == [texts[1], texts[1]]
@pytest.mark.asyncio
@@ -4557,7 +4562,9 @@ async def test_on_action_round_falls_back_to_reasoning_summary_when_text_empty()
# reasoning summary (message.reasoning_content) is the only readable turn text available.
round_texts: list[str | None] = []
- async def _on_round(_actions: list[tuple[str, dict[str, Any], bool]], turn_text: str | None) -> None:
+ async def _on_round(
+ _actions: list[tuple[str, dict[str, Any], bool]], turn_text: str | None, *, round_done: bool
+ ) -> None:
round_texts.append(turn_text)
clk = []
@@ -4582,7 +4589,9 @@ async def test_on_action_round_falls_back_to_reasoning_summary_when_text_empty()
async def test_on_action_round_prefers_content_over_reasoning_summary() -> None:
round_texts: list[str | None] = []
- async def _on_round(_actions: list[tuple[str, dict[str, Any], bool]], turn_text: str | None) -> None:
+ async def _on_round(
+ _actions: list[tuple[str, dict[str, Any], bool]], turn_text: str | None, *, round_done: bool
+ ) -> None:
round_texts.append(turn_text)
clk = []
@@ -4631,7 +4640,7 @@ async def test_on_action_round_fires_for_all_failed_round_with_failure_flag() ->
# callback (flagged unsuccessful) so the round persists into the workflow-run step budget.
rounds: list[list[RoundAction]] = []
- async def _on_round(actions: list[RoundAction], _turn_text: str | None) -> None:
+ async def _on_round(actions: list[RoundAction], _turn_text: str | None, *, round_done: bool) -> None:
rounds.append(actions)
clk: list[tuple[str, dict[str, Any]]] = []
@@ -4646,7 +4655,7 @@ async def test_on_action_round_fires_for_all_failed_round_with_failure_flag() ->
@pytest.mark.asyncio
async def test_on_action_round_failure_does_not_abort_run() -> None:
- async def _boom(actions: list[tuple[str, dict[str, Any]]], _turn_text: str | None) -> None:
+ async def _boom(actions: list[tuple[str, dict[str, Any]]], _turn_text: str | None, *, round_done: bool) -> None:
raise RuntimeError("persist boom")
clk: list[tuple[str, dict[str, Any]]] = []
@@ -6112,7 +6121,7 @@ _NAV_URL = "https://forms.example.test/contact-us"
def _recordable_navigate(sink: list[tuple[str, dict[str, Any]]], *, outcome: dict[str, Any] | None = None) -> ToolSpec:
"""The production navigate shape (SKY-16374): recordable so the navigation persists as an action
- row with the round's screenshot, never billable, and carrying the outcome the caller writes onto
+ row with its own screenshot, never billable, and carrying the outcome the caller writes onto
that row."""
async def handler(args: dict[str, Any]) -> ToolResult:
@@ -6142,7 +6151,7 @@ async def test_a_navigation_reaches_the_round_with_its_outcome_and_costs_no_budg
# a navigation is not a page-mutating step, and a recorded row must never start metering.
rounds: list[list[RoundAction]] = []
- async def _on_round(actions: list[RoundAction], _turn_text: str | None) -> None:
+ async def _on_round(actions: list[RoundAction], _turn_text: str | None, *, round_done: bool) -> None:
rounds.append(actions)
navs: list[tuple[str, dict[str, Any]]] = []
@@ -6164,7 +6173,7 @@ async def test_a_navigation_that_answered_an_http_error_is_recorded_as_a_failed_
# to read as a failed one there, or a run that died on a 404 shows a terminate out of nowhere.
rounds: list[list[RoundAction]] = []
- async def _on_round(actions: list[RoundAction], _turn_text: str | None) -> None:
+ async def _on_round(actions: list[RoundAction], _turn_text: str | None, *, round_done: bool) -> None:
rounds.append(actions)
navs: list[tuple[str, dict[str, Any]]] = []
@@ -6189,7 +6198,7 @@ async def test_a_recorded_call_that_failed_carries_its_error_text_to_the_round()
# nothing reads as a navigation that broke for no reason.
rounds: list[list[RoundAction]] = []
- async def _on_round(actions: list[RoundAction], _turn_text: str | None) -> None:
+ async def _on_round(actions: list[RoundAction], _turn_text: str | None, *, round_done: bool) -> None:
rounds.append(actions)
navs: list[tuple[str, dict[str, Any]]] = []
@@ -6214,7 +6223,7 @@ async def test_repeated_navigations_to_one_url_are_recorded_without_arming_the_a
# Recording a row must not change what ends a run.
rounds: list[list[RoundAction]] = []
- async def _on_round(actions: list[RoundAction], _turn_text: str | None) -> None:
+ async def _on_round(actions: list[RoundAction], _turn_text: str | None, *, round_done: bool) -> None:
rounds.append(actions)
navs: list[tuple[str, dict[str, Any]]] = []
@@ -8259,7 +8268,7 @@ async def test_completion_probe_ends_loop_mid_batch_without_finish() -> None:
script = [[("click", {"selector": "#a"}), ("click", {"selector": "#b"})]]
recorded_rounds: list[list[RoundAction]] = []
- async def on_action_round(round_actions: list[RoundAction], _turn_text: str | None) -> None:
+ async def on_action_round(round_actions: list[RoundAction], _turn_text: str | None, *, round_done: bool) -> None:
recorded_rounds.append(round_actions)
outcome, _ = await _run(script, tools, completion_probe=probe, on_action_round=on_action_round)
@@ -9869,7 +9878,7 @@ async def test_refresh_reload_is_recorded_in_the_action_round() -> None:
rounds: list[list[RoundAction]] = []
- async def on_round(actions: list[RoundAction], _turn_text: str | None) -> None:
+ async def on_round(actions: list[RoundAction], _turn_text: str | None, *, round_done: bool) -> None:
rounds.append(list(actions))
click_calls: list[tuple[str, dict[str, Any]]] = []
@@ -11740,7 +11749,7 @@ async def test_a_round_carries_billability_from_the_spec_not_from_a_name_list()
"""
rounds: list[list[RoundAction]] = []
- async def _on_round(actions: list[RoundAction], reasoning: str | None) -> None:
+ async def _on_round(actions: list[RoundAction], reasoning: str | None, *, round_done: bool) -> None:
rounds.append(actions)
async def handler(args: dict[str, Any]) -> ToolResult:
diff --git a/tests/unit/test_taskv3_pre_submit_capture.py b/tests/unit/test_taskv3_pre_submit_capture.py
index 2b18272a8..c5f30a28c 100644
--- a/tests/unit/test_taskv3_pre_submit_capture.py
+++ b/tests/unit/test_taskv3_pre_submit_capture.py
@@ -813,7 +813,7 @@ async def test_a_mark_click_persists_the_element_it_acted_on() -> None:
pw, browser, page = await _browser_page(_MARK_SUBMIT_FIXTURE)
rounds: list[list[RoundAction]] = []
- async def _capture(actions: list[RoundAction], _text: str | None) -> None:
+ async def _capture(actions: list[RoundAction], _text: str | None, *, round_done: bool) -> None:
rounds.append(actions)
try:
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index 76d6b4a2f..cdfbc2594 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -57,6 +57,7 @@ from skyvern.forge.sdk.workflow.models.credential_release import (
)
from skyvern.forge.sdk.workflow.models.parameter import CredentialParameter
from skyvern.forge.taskv3 import input_dispatch
+from skyvern.forge.taskv3.answer_basis_audit import RecordedAnswer, apply_answer_basis_audit
from skyvern.forge.taskv3.auth_tools import VerificationState
from skyvern.forge.taskv3.code_surface import (
CodeToolSurface,
@@ -67,7 +68,9 @@ from skyvern.forge.taskv3.field_commit import Tier
from skyvern.forge.taskv3.loop import (
ACTION_OUTCOME_DATA_KEY,
CODE_TOOL_NAME,
+ PICKED_OPTION_DATA_KEY,
SemanticCommitStats,
+ ToolRefusal,
ToolResult,
ToolSpec,
_navigate_record_fields,
@@ -602,6 +605,9 @@ _DISABLED_CLICK_HTML = """
<button id="soon-on" disabled>Soon on</button>
<button id="swap-off" disabled>Swap off</button>
<button id="blink-on" disabled>Blink on</button>
+ <button id="aria-off" aria-disabled="true">Aria off</button>
+ <button id="aria-soon-on" aria-disabled="true">Aria soon on</button>
+ <div aria-disabled="true"><button id="aria-under-wrapper">Aria under wrapper</button></div>
<div id="declared-off" aria-disabled="true" style="cursor:pointer;width:120px">Declared off</div>
</body></html>
"""
@@ -636,8 +642,21 @@ async def test_click_refuses_a_natively_disabled_target_before_the_actionability
" b.textContent = 'Blink on'; document.body.append(b); }, 500); }"
)
blinked = await click({"selector": "#blink-on"})
- # Playwright ignores aria-disabled on a role-less element and clicks it, so the tool must too.
- declared = await click({"selector": "#declared-off"})
+ # The gate stands in for the driver's own enabled check, so the contract is agreement with it,
+ # asserted against `is_enabled` rather than against a hardcoded rule. Which shapes the driver
+ # refuses is version-dependent (`aria-disabled` on an ANCESTOR is refused by 1.61 and clicked
+ # by 1.58), and a test naming the shapes pins the gate to whichever driver it was written on.
+ aria: dict[str, tuple[bool, str | None, str, float]] = {}
+ for selector in ("#aria-off", "#aria-under-wrapper", "#declared-off"):
+ driver_refuses = not await page.locator(selector).is_enabled()
+ start = time.monotonic()
+ r = await click({"selector": selector})
+ aria[selector] = (driver_refuses, r.error_class, r.status, time.monotonic() - start)
+ # The grace waits out a declared-disabled control the page releases, as it does a native one.
+ await page.evaluate(
+ "() => setTimeout(() => document.getElementById('aria-soon-on').removeAttribute('aria-disabled'), 500)"
+ )
+ aria_soon = await click({"selector": "#aria-soon-on"})
downs = await page.evaluate("() => window.downs")
assert off.error_class == "disabled", off.content
assert "is disabled — it cannot be clicked until the page enables it" in off.content
@@ -647,8 +666,17 @@ async def test_click_refuses_a_natively_disabled_target_before_the_actionability
assert swapped.error_class == "stale_selector", swapped.content
assert swapped_seconds < 5, swapped_seconds
assert blinked.status == "ok", blinked.content
- assert declared.status == "ok", declared.content
- assert downs == {"submit-on": 1, "soon-on": 1, "blink-on": 1, "declared-off": 1}, downs
+ # Refused exactly when the driver would refuse, told apart from every other failure by its own
+ # error class, and never at the cost of the full actionability wait.
+ for selector, (driver_refuses, error_class, status, seconds) in aria.items():
+ assert (status == "error") is driver_refuses, (selector, aria)
+ assert (error_class == "disabled") is driver_refuses, (selector, aria)
+ assert seconds < 5, (selector, aria)
+ # At least one shape must land on each side, or the agreement above is vacuous.
+ assert len({driver_refuses for driver_refuses, *_ in aria.values()}) == 2, aria
+ assert aria_soon.status == "ok", aria_soon.content
+ clicked_aria = {sel.lstrip("#"): 1 for sel, (refuses, *_) in aria.items() if not refuses}
+ assert downs == {"submit-on": 1, "soon-on": 1, "blink-on": 1, "aria-soon-on": 1, **clicked_aria}, (downs, aria)
@_skip_no_browser
@@ -6978,7 +7006,7 @@ async def test_navigate_is_recordable_and_reports_the_outcome_of_the_navigation(
monkeypatch: pytest.MonkeyPatch,
) -> None:
# SKY-16374: a URL the model typed itself is an action the customer must see, so navigate is
- # recordable (one action row + that round's screenshot) while staying out of billing and the
+ # recordable (one action row + its own screenshot) while staying out of billing and the
# action-step budget. The row is only worth having if it says what HAPPENED, so the handler
# reports where it asked to go, where it landed, what the page answered, and whether the page
# moved -- the facts the caller persists on the row.
@@ -8725,7 +8753,7 @@ async def test_navigate_dead_end_terminates_run_through_real_handler(monkeypatch
]
rounds: list[list[Any]] = []
- async def _on_round(round_actions: list[Any], _turn_text: str | None) -> None:
+ async def _on_round(round_actions: list[Any], _turn_text: str | None, *, round_done: bool) -> None:
rounds.append(round_actions)
outcome = await run_agent_tool_loop(
@@ -8951,6 +8979,7 @@ async def test_click_option_commit_verified_by_menu_close() -> None:
assert r.status == "ok"
assert "Selected option 'Most popular'" in r.content
assert "menu closed" in r.content
+ assert (r.data or {}).get(PICKED_OPTION_DATA_KEY) == "Most popular"
# commit judged against the POST-hover baseline: the handler hovered before clicking
assert ("hover", '[data-tv3-menu="3"]') in page.calls
@@ -9322,6 +9351,7 @@ async def test_click_option_that_is_marked_and_also_grows_reports_both(monkeypat
assert "Selected option 'Referral' — its state changed." in r.content
assert "the menu stayed open" not in r.content
assert "opened a menu of 2 options" in r.content
+ assert (r.data or {}).get(PICKED_OPTION_DATA_KEY) == "Referral"
@pytest.mark.asyncio
@@ -9997,6 +10027,53 @@ async def test_dom_a_menu_note_lists_each_multi_element_option_row_whole() -> No
assert await page.evaluate("() => window.__picked") is None
+class _FlagAnswers:
+ def __init__(self, flag: str) -> None:
+ self.flag = flag
+
+ async def unsupported(self, answers: list[RecordedAnswer]) -> list[RecordedAnswer]:
+ return [a for a in answers if a.value == self.flag]
+
+
+@_skip_no_browser
+async def test_a_held_answer_is_repaired_by_ref_while_a_submit_by_ref_stays_held() -> None:
+ # The hold compares a click with the field as recorded, after the ref resolver rewrote it to CSS.
+ html = (
+ _LONG_OPTION_MENU_FIXTURE_HTML.replace("__OPTIONS__", json.dumps(["Yes", "No", "I prefer not to answer"]))
+ .replace("__ROWS__", _PLAIN_OPTION_ROW_JS)
+ .replace('<button id="trigger"', '<button id="trigger" aria-label="Excluded from a federal program?"')
+ .replace(
+ "<script>",
+ '<button id="submit" style="position:absolute;top:400px;left:40px" '
+ 'onclick="window.__submitted = true">Submit</button><script>',
+ 1,
+ )
+ )
+ async with _content_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ apply_answer_basis_audit(tools, _FlagAnswers("No"))
+ click = _tool(tools, "click").handler
+ seen = await _tool(tools, "observe").handler({})
+ opener, submit = _ref_line(seen.content, "federal program"), _ref_line(seen.content, "Submit")
+ opened = await click({"selector": opener})
+ row = {text: n for n, text in _menu_note_entries(opened.content)}["No"]
+ await click({"selector": f'[data-tv3-menu="{row}"]'})
+
+ with pytest.raises(ToolRefusal, match="Excluded from a federal program"):
+ await click({"selector": submit})
+ assert await page.evaluate("() => window.__submitted") is None
+ reopened = await click({"selector": opener})
+ assert "opened a menu of 3 options" in reopened.content, reopened.content
+ with pytest.raises(ToolRefusal):
+ await click({"selector": submit})
+ decline = _ref_line((await _tool(tools, "observe").handler({})).content, "option 'I prefer not to answer'")
+ await click({"selector": decline})
+ assert await page.evaluate("() => window.__picked") == "I prefer not to answer"
+ await click({"selector": submit})
+ assert await page.evaluate("() => window.__submitted") is True
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_dom_a_menu_note_lists_no_rows_it_cannot_read_whole() -> None:
@@ -12364,7 +12441,7 @@ async def test_every_uncharged_refusal_is_issued_before_the_page_is_touched(
before = (page.url, await page.evaluate(_PAGE_FINGERPRINT_PROBE_JS))
rounds: list[list[taskv3_loop.RoundAction]] = []
- async def _on_round(actions: list[taskv3_loop.RoundAction], _text: str | None) -> None:
+ async def _on_round(actions: list[taskv3_loop.RoundAction], _text: str | None, *, round_done: bool) -> None:
rounds.append(list(actions))
outcome = await taskv3_loop.run_agent_tool_loop(
@@ -15490,6 +15567,67 @@ async def test_type_says_a_disabled_field_is_disabled_instead_of_waiting_for_it(
assert elapsed < 10, elapsed
+@_skip_no_browser
+async def test_type_says_an_aria_disabled_field_is_disabled_instead_of_waiting_for_it() -> None:
+ # fill() waits on the driver's own rule, which is wider than `:disabled`, so a gate reading
+ # `:disabled` alone pays the full timeout on a field the driver was never going to fill. Asserted
+ # as agreement with `is_enabled` rather than per shape: which shapes it refuses moves between
+ # driver versions (`aria-disabled` on an ANCESTOR is refused by 1.61 and filled by 1.58).
+ html = (
+ '<input id="own" type="text" aria-disabled="true" style="width:200px;height:30px">'
+ '<div aria-disabled="true"><input id="under" type="text" style="width:200px;height:30px"></div>'
+ )
+ async with _content_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ typed = {}
+ for name in ("own", "under"):
+ driver_refuses = not await page.locator(f"#{name}").is_enabled()
+ start = time.monotonic()
+ r = await _tool(tools, "type").handler({"selector": f"#{name}", "text": "Iowa City"})
+ typed[name] = (driver_refuses, r.status, "disabled" in r.content, time.monotonic() - start)
+ for name, (driver_refuses, status, says_disabled, elapsed) in typed.items():
+ assert (status == "error") is driver_refuses, (name, typed)
+ assert says_disabled is driver_refuses, (name, typed)
+ assert elapsed < 10, (name, typed)
+ # The own-attribute field is refused by every driver version we run, so this test always has a leg
+ # that exercises the gate rather than only agreeing with a driver that refuses nothing.
+ assert typed["own"][0] is True, typed
+
+
+@_skip_no_browser
+async def test_type_waits_out_an_aria_disabled_field_the_page_releases() -> None:
+ # fill()'s own wait used to cover this, so asking the driver up front must hold the same grace the
+ # click gate does -- otherwise consulting it turns a fill that succeeded into an instant refusal.
+ html = '<input id="soon" type="text" aria-disabled="true" style="width:200px;height:30px">'
+ async with _content_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ await page.evaluate(
+ "() => setTimeout(() => document.getElementById('soon').removeAttribute('aria-disabled'), 500)"
+ )
+ r = await _tool(tools, "type").handler({"selector": "#soon", "text": "Iowa City"})
+ assert r.status == "ok", r.content
+ assert await page.eval_on_selector("#soon", "el => el.value") == "Iowa City"
+
+
+@_skip_no_browser
+async def test_type_reports_readonly_when_the_page_locks_the_field_during_the_grace() -> None:
+ # A page that answers the grace by making the field readonly has made it un-typable for a different
+ # reason, so the grace must re-read rather than only poll the driver's enabled answer.
+ html = '<input id="soon" type="text" aria-disabled="true" style="width:200px;height:30px">'
+ async with _content_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ await page.evaluate(
+ "() => setTimeout(() => { const f = document.getElementById('soon');"
+ " f.readOnly = true; f.removeAttribute('aria-disabled'); }, 300)"
+ )
+ r = await _tool(tools, "type").handler({"selector": "#soon", "text": "Iowa City"})
+ assert r.error_class == "not_editable", r.content
+ assert "is readonly" in r.content, r.content
+
+
# The skin is a link. Forcing the click follows it, and the selector may well match something on the
# destination -- so "did the field stop resolving" cannot tell this from a re-render, but the URL can.
# Needs a routed origin: set_content leaves the page on about:blank, where nothing navigates.
diff --git a/tests/unit/webeye/test_screenshot_runtime_events.py b/tests/unit/webeye/test_screenshot_runtime_events.py
index 3ac29a319..478be806d 100644
--- a/tests/unit/webeye/test_screenshot_runtime_events.py
+++ b/tests/unit/webeye/test_screenshot_runtime_events.py
@@ -28,7 +28,7 @@ from skyvern.webeye.browser_runtime_events import BrowserRuntimeLogContext, brow
from skyvern.webeye.real_browser_state import RealBrowserState
from skyvern.webeye.utils import page as page_module
from skyvern.webeye.utils.page import ScreenshotMode, SkyvernFrame
-from tests.unit.conftest import stalling_async_mock
+from tests.unit.conftest import DriverReplyProbe, stalling_async_mock
from tests.unit.forge_log_capture import capture_runtime_logs
@@ -176,6 +176,30 @@ async def test_owned_deadline_emits_timeout_after_local_conversion(
assert events[0]["elapsed_ms"] >= 20
[email protected]("stop", ["owned_deadline", "caller_deadline", "external_cancel"])
+async def test_an_abandoned_capture_leaves_the_driver_no_unretrieved_reply(page: MagicMock, stop: str) -> None:
+ probe = DriverReplyProbe(PlaywrightTimeoutError("Timeout 25ms exceeded.\nCall log:\ntaking page screenshot"))
+ page.screenshot = probe
+ capture = functools.partial(
+ SkyvernFrame.take_scrolling_screenshot, page, mode=ScreenshotMode.LITE, scrolling_number=1
+ )
+ if stop == "external_cancel":
+ task = asyncio.create_task(capture(timeout=5000))
+ await asyncio.wait_for(probe.called.wait(), timeout=2)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ elif stop == "caller_deadline":
+ with pytest.raises(TimeoutError):
+ async with asyncio.timeout(0.025):
+ await capture(timeout=5000)
+ else:
+ with pytest.raises(TimeoutError):
+ await capture(timeout=25)
+ assert not await probe.orphaned_reply()
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("outer_deadline", [False, True])
@pytest.mark.parametrize("scrolling_number", [0, 1])
@@ -497,12 +521,14 @@ async def test_foreign_cancellation_never_becomes_a_partial_screenshot(page: Mag
frame.scroll_to_next_page.side_effect = [30, 60, 90]
entered = asyncio.Event()
png = page.screenshot.return_value
+ capturing: list[asyncio.Task[bytes]] = []
if stop == "deadline_cancel_collision":
async def collide(**kwargs: Any) -> bytes:
- # Block past the own deadline without yielding, then request an external cancel: both land together.
+ # Block past the own deadline without yielding, then cancel the capture the way a foreign
+ # canceller does: both land together.
time.sleep(0.06)
- asyncio.current_task().cancel() # type: ignore[union-attr]
+ capturing[0].cancel()
return await _stall(entered)(**kwargs)
page.screenshot.side_effect = _viewport_capture(png, frames=1, then=collide)
@@ -521,6 +547,7 @@ async def test_foreign_cancellation_never_becomes_a_partial_screenshot(page: Mag
await capture(timeout=5000)
else:
task = asyncio.create_task(capture(timeout=20 if stop == "deadline_cancel_collision" else 5000))
+ capturing.append(task)
await asyncio.wait_for(entered.wait(), timeout=2)
if stop == "external_cancel":
task.cancel()