Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Let the copilot finish download requests instead of stalling at the results page (#8125)
Andrew Neilsonac5959e4e003
diff --git a/skyvern-frontend/src/routes/streaming/cdpInputUtils.ts b/skyvern-frontend/src/routes/streaming/cdpInputUtils.tsindex 9937da288..bb378a69f 100644--- a/skyvern-frontend/src/routes/streaming/cdpInputUtils.ts+++ b/skyvern-frontend/src/routes/streaming/cdpInputUtils.ts@@ -4,6 +4,47 @@ export function mouseButtonName(button: number): string {return "left";}+// CDP's Input.dispatchKeyEvent only performs the browser's default edit action (delete+// forward/backward, arrow-key caret movement, etc.) for non-printable keys when given a+// windowsVirtualKeyCode alongside eventType "rawKeyDown" - key/code alone are a no-op.+const VIRTUAL_KEY_CODES: Record<string, number> = {+ Backspace: 8,+ Tab: 9,+ Enter: 13,+ Escape: 27,+ PageUp: 33,+ PageDown: 34,+ End: 35,+ Home: 36,+ ArrowLeft: 37,+ ArrowUp: 38,+ ArrowRight: 39,+ ArrowDown: 40,+ Insert: 45,+ Delete: 46,+ F1: 112,+ F2: 113,+ F3: 114,+ F4: 115,+ F5: 116,+ F6: 117,+ F7: 118,+ F8: 119,+ F9: 120,+ F10: 121,+ F11: 122,+ F12: 123,+};++export function virtualKeyCodeFor(+ e: Pick<KeyboardEvent, "key" | "code">,+): number | undefined {+ if (e.key === " ") {+ return 32;+ }+ return VIRTUAL_KEY_CODES[e.key] ?? VIRTUAL_KEY_CODES[e.code];+}+export function getModifiers(e: Pick<KeyboardEvent, "altKey" | "ctrlKey" | "metaKey" | "shiftKey">,): number {diff --git a/skyvern-frontend/src/routes/streaming/useCdpInput.test.ts b/skyvern-frontend/src/routes/streaming/useCdpInput.test.tsindex 6f2c4583c..262d576c5 100644--- a/skyvern-frontend/src/routes/streaming/useCdpInput.test.ts+++ b/skyvern-frontend/src/routes/streaming/useCdpInput.test.ts@@ -64,6 +64,44 @@ async function renderInputHook() {});}+async function renderControllingInputHook() {+ const { result } = renderHook(() =>+ useCdpInput({+ inputWsUrl: "wss://input.test",+ interactive: true,+ viewportWidth: 1280,+ viewportHeight: 720,+ }),+ );++ await act(async () => {+ await Promise.resolve();+ });+ act(() => {+ result.current.setUserIsControlling(true);+ });++ return result;+}++function fakeKeyboardEvent(key: string, code: string): React.KeyboardEvent {+ return {+ key,+ code,+ altKey: false,+ ctrlKey: false,+ metaKey: false,+ shiftKey: false,+ preventDefault: vi.fn(),+ } as unknown as React.KeyboardEvent;+}++function latestSocketSend() {+ const socket = MockWebSocket.instances[MockWebSocket.instances.length - 1];+ if (!socket) throw new Error("No WebSocket was constructed");+ return socket.send;+}+function closeLatestSocket(code: number) {const socket = MockWebSocket.instances[MockWebSocket.instances.length - 1];if (!socket) throw new Error("No WebSocket was constructed");@@ -129,3 +167,133 @@ describe("useCdpInput reconnects", () => {expect(MockWebSocket.instances).toHaveLength(6);});});++describe("useCdpInput key handling", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ MockWebSocket.instances = [];+ vi.stubGlobal("WebSocket", MockWebSocket);+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ });++ // SKY-13682: Delete (and every other non-printable key - Backspace, Enter, arrows, ...) was a+ // no-op in the remote page. CDP's Input.dispatchKeyEvent only performs the default edit action+ // when non-printable keys carry a windowsVirtualKeyCode, dispatched as eventType "rawKeyDown".+ it("sends windowsVirtualKeyCode and eventType rawKeyDown for Delete", async () => {+ const result = await renderControllingInputHook();++ act(() => {+ result.current.handlers.handleKeyDown(+ fakeKeyboardEvent("Delete", "Delete"),+ );+ });++ const send = latestSocketSend();+ expect(send).toHaveBeenCalledWith(+ JSON.stringify({+ type: "keyEvent",+ eventType: "rawKeyDown",+ key: "Delete",+ code: "Delete",+ text: "",+ modifiers: 0,+ windowsVirtualKeyCode: 46,+ }),+ );+ });++ it("sends windowsVirtualKeyCode and eventType rawKeyDown for Backspace", async () => {+ const result = await renderControllingInputHook();++ act(() => {+ result.current.handlers.handleKeyDown(+ fakeKeyboardEvent("Backspace", "Backspace"),+ );+ });++ const send = latestSocketSend();+ expect(send).toHaveBeenCalledWith(+ JSON.stringify({+ type: "keyEvent",+ eventType: "rawKeyDown",+ key: "Backspace",+ code: "Backspace",+ text: "",+ modifiers: 0,+ windowsVirtualKeyCode: 8,+ }),+ );+ });++ // Numpad Delete with NumLock off reports key "Delete" (same as the main Delete key) with a+ // different `code`; the vk lookup keys off `key` first so both resolve to the same edit action.+ it("resolves numpad Delete (NumLock off) the same as the main Delete key", async () => {+ const result = await renderControllingInputHook();++ act(() => {+ result.current.handlers.handleKeyDown(+ fakeKeyboardEvent("Delete", "NumpadDecimal"),+ );+ });++ const send = latestSocketSend();+ expect(send).toHaveBeenCalledWith(+ JSON.stringify({+ type: "keyEvent",+ eventType: "rawKeyDown",+ key: "Delete",+ code: "NumpadDecimal",+ text: "",+ modifiers: 0,+ windowsVirtualKeyCode: 46,+ }),+ );+ });++ it("still sends printable text entry as keyDown with no windowsVirtualKeyCode", async () => {+ const result = await renderControllingInputHook();++ act(() => {+ result.current.handlers.handleKeyDown(fakeKeyboardEvent("a", "KeyA"));+ });++ const send = latestSocketSend();+ expect(send).toHaveBeenCalledWith(+ JSON.stringify({+ type: "keyEvent",+ eventType: "keyDown",+ key: "a",+ code: "KeyA",+ text: "a",+ modifiers: 0,+ }),+ );+ });++ it("includes windowsVirtualKeyCode on keyUp for non-printable keys", async () => {+ const result = await renderControllingInputHook();++ act(() => {+ result.current.handlers.handleKeyUp(+ fakeKeyboardEvent("Delete", "Delete"),+ );+ });++ const send = latestSocketSend();+ expect(send).toHaveBeenCalledWith(+ JSON.stringify({+ type: "keyEvent",+ eventType: "keyUp",+ key: "Delete",+ code: "Delete",+ modifiers: 0,+ windowsVirtualKeyCode: 46,+ }),+ );+ });+});diff --git a/skyvern-frontend/src/routes/streaming/useCdpInput.ts b/skyvern-frontend/src/routes/streaming/useCdpInput.tsindex 42f39abca..2891bb9bc 100644--- a/skyvern-frontend/src/routes/streaming/useCdpInput.ts+++ b/skyvern-frontend/src/routes/streaming/useCdpInput.ts@@ -7,6 +7,7 @@ import {getModifiers,mapCoordinates,mapMouseCoordinates,+ virtualKeyCodeFor,} from "./cdpInputUtils";// 4411 is emitted mid-session (page resolution or dispatch failed), so unlike a setup-time close it@@ -318,14 +319,20 @@ export function useCdpInput({(e: React.KeyboardEvent) => {if (!interactive || !userIsControlling) return;e.preventDefault();- sendInputEvent({+ const isPrintable = e.key.length === 1;+ const windowsVirtualKeyCode = virtualKeyCodeFor(e);+ const payload: Record<string, unknown> = {type: "keyEvent",- eventType: "keyDown",+ eventType: isPrintable ? "keyDown" : "rawKeyDown",key: e.key,code: e.code,- text: e.key.length === 1 ? e.key : "",+ text: isPrintable ? e.key : "",modifiers: getModifiers(e),- });+ };+ if (windowsVirtualKeyCode !== undefined) {+ payload.windowsVirtualKeyCode = windowsVirtualKeyCode;+ }+ sendInputEvent(payload);},[interactive, userIsControlling, sendInputEvent],);@@ -334,13 +341,18 @@ export function useCdpInput({(e: React.KeyboardEvent) => {if (!interactive || !userIsControlling) return;e.preventDefault();- sendInputEvent({+ const windowsVirtualKeyCode = virtualKeyCodeFor(e);+ const payload: Record<string, unknown> = {type: "keyEvent",eventType: "keyUp",key: e.key,code: e.code,modifiers: getModifiers(e),- });+ };+ if (windowsVirtualKeyCode !== undefined) {+ payload.windowsVirtualKeyCode = windowsVirtualKeyCode;+ }+ sendInputEvent(payload);},[interactive, userIsControlling, sendInputEvent],);diff --git a/skyvern-frontend/src/routes/workflows/components/BulkActionBar.tsx b/skyvern-frontend/src/routes/workflows/components/BulkActionBar.tsxindex 4206d13c7..3ce7a36e1 100644--- a/skyvern-frontend/src/routes/workflows/components/BulkActionBar.tsx+++ b/skyvern-frontend/src/routes/workflows/components/BulkActionBar.tsx@@ -269,7 +269,7 @@ function BulkActionBar({}downloadFile(`agents-export-${selectedWorkflows.length}.zip`,- new Uint8Array(zipSync(entries)),+ zipSync(entries),"application/zip",);}diff --git a/skyvern-frontend/src/routes/workflows/importWorkflowYaml.test.ts b/skyvern-frontend/src/routes/workflows/importWorkflowYaml.test.tsindex 36a56e98f..cbbf100d0 100644--- a/skyvern-frontend/src/routes/workflows/importWorkflowYaml.test.ts+++ b/skyvern-frontend/src/routes/workflows/importWorkflowYaml.test.ts@@ -15,12 +15,6 @@ function titlesOf(yamls: string[]): Array<string | null> {return yamls.map((yaml) => extractTitleFromYaml(yaml));}-// fflate is loaded in Node's realm while Vitest runs tests in jsdom's realm.-// Copy encoded bytes so zipSync recognizes them as Uint8Array file contents.-function archiveBytes(text: string): Uint8Array {- return new Uint8Array(strToU8(text));-}-describe("expandFileToWorkflowYamls", () => {it("splits the bulk YAML export format into one workflow per document", () => {// Matches BulkActionBar.handleBulkExport: docs joined by "---\n".@@ -95,8 +89,8 @@ describe("unzipArchive", () => {// Mirrors BulkActionBar.handleBulkExport's ZIP branch: one sanitized,// deduped entry per agent.const zipped = zipSync({- "Workflow A.yaml": archiveBytes(convertToYAML(workflowA)),- "Workflow B.yaml": archiveBytes(convertToYAML(workflowB)),+ "Workflow A.yaml": strToU8(convertToYAML(workflowA)),+ "Workflow B.yaml": strToU8(convertToYAML(workflowB)),});const entries = unzipArchive(zipped);@@ -109,8 +103,8 @@ describe("unzipArchive", () => {it("round-trips zipped per-agent files back into individual workflows", () => {const zipped = zipSync({- "Workflow A.yaml": archiveBytes(convertToYAML(workflowA)),- "Workflow B.yaml": archiveBytes(convertToYAML(workflowB)),+ "Workflow A.yaml": strToU8(convertToYAML(workflowA)),+ "Workflow B.yaml": strToU8(convertToYAML(workflowB)),});const expanded = unzipArchive(zipped).flatMap((entry) =>@@ -123,7 +117,7 @@ describe("unzipArchive", () => {it("ignores empty entries", () => {const zipped = zipSync({"empty.yaml": new Uint8Array(0),- "Workflow A.yaml": archiveBytes(convertToYAML(workflowA)),+ "Workflow A.yaml": strToU8(convertToYAML(workflowA)),});const entries = unzipArchive(zipped);@@ -133,10 +127,10 @@ describe("unzipArchive", () => {it("ignores non-workflow files, including macOS zip metadata junk", () => {const zipped = zipSync({- "Workflow A.yaml": archiveBytes(convertToYAML(workflowA)),- "__MACOSX/._Workflow A.yaml": archiveBytes("junk"),- ".DS_Store": archiveBytes("junk"),- "notes.txt": archiveBytes("not a workflow"),+ "Workflow A.yaml": strToU8(convertToYAML(workflowA)),+ "__MACOSX/._Workflow A.yaml": strToU8("junk"),+ ".DS_Store": strToU8("junk"),+ "notes.txt": strToU8("not a workflow"),});const entries = unzipArchive(zipped);@@ -153,7 +147,7 @@ describe("unzipArchive", () => {it("rejects an archive with too many entries", () => {const files: Record<string, Uint8Array> = {};for (let i = 0; i < 201; i++) {- files[`workflow-${i}.yaml`] = archiveBytes(convertToYAML(workflowA));+ files[`workflow-${i}.yaml`] = strToU8(convertToYAML(workflowA));}const zipped = zipSync(files);diff --git a/skyvern/cli/mcp_tools/__init__.py b/skyvern/cli/mcp_tools/__init__.pyindex 66585c3ae..294094986 100644--- a/skyvern/cli/mcp_tools/__init__.py+++ b/skyvern/cli/mcp_tools/__init__.py@@ -564,7 +564,7 @@ mcp.tool(tags={"workflow"}, annotations=_mut("Update Workflow"))(skyvern_workflomcp.tool(tags={"workflow"}, annotations=_mut("Move Workflow to Folder"))(skyvern_workflow_update_folder)mcp.tool(tags={"workflow"}, annotations=_dest("Delete Workflow"))(skyvern_workflow_delete)mcp.tool(tags={"workflow"}, annotations=_web_dest("Run Workflow"))(skyvern_workflow_run)-mcp.tool(tags={"workflow"}, annotations=_ro("Get Workflow Run Status"))(skyvern_workflow_status)+mcp.tool(tags={"workflow"}, annotations=_ro("Get Workflow Run Status"))(size_capped(skyvern_workflow_status))mcp.tool(tags={"workflow"}, annotations=_web_dest("Retry Workflow Run"))(skyvern_workflow_retry)mcp.tool(tags={"workflow"}, annotations=_dest("Cancel Workflow Run"))(skyvern_workflow_cancel)diff --git a/skyvern/cli/mcp_tools/workflow.py b/skyvern/cli/mcp_tools/workflow.pyindex bbb25c557..60d9d0c8b 100644--- a/skyvern/cli/mcp_tools/workflow.py+++ b/skyvern/cli/mcp_tools/workflow.py@@ -2233,15 +2233,54 @@ async def skyvern_workflow_status(error=make_error(ErrorCode.API_ERROR, str(e), "Check the run ID and your API key"),)- data = _serialize_run_full(run) if verbosity == "full" else _serialize_run_summary(run)+ def _payload_for(selected_verbosity: str) -> dict[str, Any]:+ payload = _serialize_run_full(run) if selected_verbosity == "full" else _serialize_run_summary(run)+ if run_id.startswith("wr_"):+ payload["sdk_equivalent"] = (+ f"await skyvern_workflow_status(run_id={run_id!r}, verbosity={selected_verbosity!r})"+ )+ else:+ verbosity_arg = "" if selected_verbosity == "summary" else f", verbosity={selected_verbosity!r}"+ payload["sdk_equivalent"] = (+ f"await skyvern.get_run({run_id!r}) # or skyvern_workflow_status(run_id={run_id!r}{verbosity_arg})"+ )+ return payload++ result = make_result("skyvern_workflow_status", data=_payload_for(verbosity), timing_ms=timer.timing_ms)+ if _response_size(result) <= MCP_MAX_RESPONSE_CHARS:+ return result++ # The generic size cap preserves only top-level `ok`/`error`/`*_id`, and this result+ # nests the run under `data` — so it would strip run_id and status and leave a polling+ # caller nothing to act on. Degrade to the compact payload instead; the full output is+ # still retrievable over the HTTP API, which is not capped.+ oversized_warning = (+ f"Full output exceeded the {MCP_MAX_RESPONSE_CHARS}-char MCP response limit; "+ f"returning a reduced payload. Fetch the full run over the HTTP API at /v1/runs/{run_id}."+ )+ summary_result = make_result(+ "skyvern_workflow_status",+ data=_payload_for("summary"),+ timing_ms=timer.timing_ms,+ warnings=[oversized_warning],+ )+ if _response_size(summary_result) <= MCP_MAX_RESPONSE_CHARS:+ return summary_result++ # The summary is itself unbounded — it copies fields like failure_reason verbatim. Fall+ # back to the identifiers a poller needs so it never lands in the stripped envelope.+ summary_data = _payload_for("summary")+ minimal: dict[str, Any] = {"run_id": run_id, "status": summary_data.get("status")}if run_id.startswith("wr_"):- data["sdk_equivalent"] = f"await skyvern_workflow_status(run_id={run_id!r}, verbosity={verbosity!r})"+ minimal["sdk_equivalent"] = f"await skyvern_workflow_status(run_id={run_id!r}, verbosity='summary')"else:- verbosity_arg = "" if verbosity == "summary" else f", verbosity={verbosity!r}"- data["sdk_equivalent"] = (- f"await skyvern.get_run({run_id!r}) # or skyvern_workflow_status(run_id={run_id!r}{verbosity_arg})"- )- return make_result("skyvern_workflow_status", data=data, timing_ms=timer.timing_ms)+ minimal["sdk_equivalent"] = f"await skyvern.get_run({run_id!r})"+ return make_result(+ "skyvern_workflow_status",+ data=minimal,+ timing_ms=timer.timing_ms,+ warnings=[oversized_warning],+ )async def skyvern_workflow_cancel(diff --git a/skyvern/config.py b/skyvern/config.pyindex 4ad34de80..95f966b08 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -828,6 +828,10 @@ class Settings(BaseSettings):OTEL_SERVICE_NAME: str = "skyvern"OTEL_EXPORTER_OTLP_ENDPOINT: str = ""OTEL_METRICS_ENABLED: bool = True+ # Comma-separated instrument-name globs allowed to export; everything else is+ # dropped at the SDK so accidental instrumentation cannot inflate metrics cost.+ # Empty disables the allowlist (export everything).+ OTEL_METRICS_ALLOWLIST: str = "skyvern.*,persistent_browsers.*,redis.connection_pool.*,db.connection_pool.*,api.event_loop.*,webeye.browser_factory.*,analytics.*"OTEL_LOGS_ENABLED: bool = TrueOTEL_EXPORTER_INSECURE: bool = True# Log level for the OTLP gRPC exporter's own logger. Raise above WARNING (e.g.diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex 18785065c..b7f7f6339 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -4364,6 +4364,16 @@ class ForgeAgent:)extra_action_guidance = await app.AGENT_FUNCTION.get_extra_extract_action_guidance(task)+ # SKY-9983: render per-step-changing sections (action history, dialogs, tabs) after the+ # element tree so provider prefix caches can hit the tree across steps on the same page.+ stable_prefix_ordering = False+ if template == EXTRACT_ACTION_TEMPLATE:+ stable_prefix_ordering = await app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached(+ "EXTRACT_ACTION_STABLE_PREFIX",+ task.workflow_run_id if task.workflow_run_id else task.task_id,+ properties={"task_url": task.url, "organization_id": task.organization_id},+ )+# Offer PASTE_TEXT (fill a spreadsheet grid with one tab/newline block) only under the umbrella,# so grid-fill guidance is scoped to the eval org until proven out.planner_mini_goal_improvements = settings.PLANNER_MINI_GOAL_IMPROVEMENTS@@ -4419,6 +4429,7 @@ class ForgeAgent:"llm_screenshots_enabled": llm_screenshots_enabled,"enriched_tree_enabled": enriched_tree_enabled,"slim_output": slim_output,+ "stable_prefix_ordering": stable_prefix_ordering,}cache_variant = self._build_extract_action_cache_variant(verification_code_check=verification_code_check,@@ -4494,6 +4505,7 @@ class ForgeAgent:task_id=task.task_id,prompt_name=EXTRACT_ACTION_PROMPT_NAME,cache_variant=cache_variant,+ stable_prefix_ordering=stable_prefix_ordering,)# Map template to prompt_name for logging/caching guardsprompt_name = EXTRACT_ACTION_PROMPT_NAME if template == EXTRACT_ACTION_TEMPLATE else template@@ -4552,6 +4564,7 @@ class ForgeAgent:llm_screenshots_enabled=llm_screenshots_enabled,enriched_tree_enabled=enriched_tree_enabled,slim_output=slim_output,+ stable_prefix_ordering=stable_prefix_ordering,lean_compress_long_href=False,lean_compress_image_src=context.enable_lean_element_tree,lean_strip_url_query_strings=context.enable_lean_element_tree,@@ -4567,6 +4580,7 @@ class ForgeAgent:_prompt_build_span.set_attribute("prompt_name", prompt_name)_prompt_build_span.set_attribute("prompt_tokens", count_tokens(full_prompt))_prompt_build_span.set_attribute("use_caching", bool(use_caching))+ _prompt_build_span.set_attribute("stable_prefix_ordering", stable_prefix_ordering)if recent_dialog_messages_str is not None:context.clear_recent_dialog_messages()@@ -5560,11 +5574,11 @@ class ForgeAgent:if getattr(task, key) != value}+ start_time = task.started_at.replace(tzinfo=UTC) if task.started_at else task.created_at.replace(tzinfo=UTC)+ duration_seconds = (datetime.now(UTC) - start_time).total_seconds()# Track task duration when task is completed, failed, or terminatedif status in [TaskStatus.completed, TaskStatus.failed, TaskStatus.terminated]:- start_time = task.started_at.replace(tzinfo=UTC) if task.started_at else task.created_at.replace(tzinfo=UTC)queued_seconds = (start_time - task.created_at.replace(tzinfo=UTC)).total_seconds()- duration_seconds = (datetime.now(UTC) - start_time).total_seconds()LOG.info("Task duration metrics",task_id=task.task_id,@@ -5575,14 +5589,22 @@ class ForgeAgent:organization_id=task.organization_id,failure_reason=failure_reason,)-await save_task_logs(task.task_id)LOG.info("Updating task in db", task_id=task.task_id, diff=update_comparison, sampling=True)- return await app.DATABASE.tasks.update_task(+ updated_task = await app.DATABASE.tasks.update_task(task.task_id,organization_id=task.organization_id,**updates,)+ # Minutes emit after the terminal write lands and only on the non-final ->+ # final transition (task holds the pre-write status), so neither a retried+ # failed write nor a repeated terminal update double-counts the run;+ # is_final() includes canceled and timed_out, matching the workflow-run gate.+ if task.workflow_run_id is None and status.is_final() and not task.status.is_final():+ await app.AGENT_FUNCTION.record_run_duration(+ run_type="task_v1", status=str(status), duration_seconds=duration_seconds+ )+ return updated_taskasync def _handle_completed_step_with_parallel_verification(self,diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex 30f129c19..f4b61a2f4 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -857,6 +857,21 @@ async def _convert_css_shape_to_string(class AgentFunction:+ async def record_run_duration(+ self,+ run_type: str,+ status: str,+ duration_seconds: float,+ workflow_run_id: str | None = None,+ organization_id: str | None = None,+ ) -> None:+ """Cloud overrides this to emit run-duration telemetry; the OSS default is a no-op.++ workflow_run_id/organization_id let the override refine run_type (e.g. a+ workflow run that backs a task_v2) without the caller paying for the lookup.+ """+ return None+workflow_schedules_enabled: bool = settings.ENABLE_WORKFLOW_SCHEDULES"""Whether the workflow scheduler routes should serve traffic on this build.diff --git a/skyvern/forge/prompts/skyvern/extract-action-dynamic.j2 b/skyvern/forge/prompts/skyvern/extract-action-dynamic.j2index 409667ff1..e0fdb36ef 100644--- a/skyvern/forge/prompts/skyvern/extract-action-dynamic.j2+++ b/skyvern/forge/prompts/skyvern/extract-action-dynamic.j2@@ -1,4 +1,4 @@-{% if recent_dialog_messages_str %}Browser alert messages raised during the previous step (the agent auto-accepted each one). Use these as additional context: if a message indicates a validation error or that the previous action was rejected, change the value, its format, or the target element before retrying — do NOT retry the same INPUT_TEXT with the same text on the same field. Treat purely informational messages (e.g. "Saved successfully") as confirmation, not as a signal to change anything.+{% if recent_dialog_messages_str and not stable_prefix_ordering %}Browser alert messages raised during the previous step (the agent auto-accepted each one). Use these as additional context: if a message indicates a validation error or that the previous action was rejected, change the value, its format, or the target element before retrying — do NOT retry the same INPUT_TEXT with the same text on the same field. Treat purely informational messages (e.g. "Saved successfully") as confirmation, not as a signal to change anything.{% endif %}{% if complete_criterion and not complete_criterion_is_untrusted %}Complete criterion:@@ -27,7 +27,30 @@ User details:{{ navigation_payload_str }}```+{% if stable_prefix_ordering %}BEGIN_UNTRUSTED_WEB_PAGE_DATA+```text{% if complete_criterion and complete_criterion_is_untrusted %}+Planner-proposed complete criterion:+{{ complete_criterion | untrusted }}+{% endif %}+Current URL: {{ current_url | untrusted }}+Clickable elements:+{{ elements | untrusted }}+Action history from previous steps:+{{ action_history | untrusted }}+{% if recent_dialog_messages_str %}+Browser alert messages raised during the previous step:+{{ recent_dialog_messages_str | untrusted }}+{% endif %}{% if open_tabs_context %}+Open browser tabs:+{{ open_tabs_context | untrusted }}+{% endif %}+```+END_UNTRUSTED_WEB_PAGE_DATA{% if recent_dialog_messages_str %}++The browser alert messages listed above were raised during the previous step (the agent auto-accepted each one). Use these as additional context: if a message indicates a validation error or that the previous action was rejected, change the value, its format, or the target element before retrying — do NOT retry the same INPUT_TEXT with the same text on the same field. Treat purely informational messages (e.g. "Saved successfully") as confirmation, not as a signal to change anything.{% endif %}{% if open_tabs_context %}++For the open browser tabs listed above: {% if show_switch_tab_action %}use SWITCH_TAB with the tab's number to make a different tab active; CLOSE_PAGE closes the tab marked [current], or set its "tab_index" to close a specific tab{% else %}CLOSE_PAGE closes the tab marked [current] by default, or set its "tab_index" to the number of a specific tab to close that one{% endif %}.{% endif %}{% else %}{% if open_tabs_context %}Open browser tabs ({% if show_switch_tab_action %}use SWITCH_TAB with the tab's number to make a different tab active; CLOSE_PAGE closes the tab marked [current], or set its "tab_index" to close a specific tab{% else %}CLOSE_PAGE closes the tab marked [current] by default, or set its "tab_index" to the number of a specific tab to close that one{% endif %}):{% endif %}@@ -50,7 +73,7 @@ Current URL: {{ current_url | untrusted }}Clickable elements:{{ elements | untrusted }}```-END_UNTRUSTED_WEB_PAGE_DATA+END_UNTRUSTED_WEB_PAGE_DATA{% endif %}Current datetime, ISO format:```diff --git a/skyvern/forge/prompts/skyvern/extract-action.j2 b/skyvern/forge/prompts/skyvern/extract-action.j2index 8a7e7d579..ccb27fae8 100644--- a/skyvern/forge/prompts/skyvern/extract-action.j2+++ b/skyvern/forge/prompts/skyvern/extract-action.j2@@ -68,7 +68,7 @@ Reply in JSON format with the following keys:{% endif %}Consider the action history from the last step{% if llm_screenshots_enabled %} and the screenshot{% endif %} together, if actions from the last step don't yield positive impact, try other actions or other action combinations.Action history from previous steps: (note: even if the action history suggests goal is achieved, check{% if llm_screenshots_enabled %} the screenshot and{% endif %} the DOM elements to make sure the goal is achieved)-{% if recent_dialog_messages_str %}Browser alert messages raised during the previous step (the agent auto-accepted each one). Use these as additional context: if a message indicates a validation error or that the previous action was rejected, change the value, its format, or the target element before retrying — do NOT retry the same INPUT_TEXT with the same text on the same field. Treat purely informational messages (e.g. "Saved successfully") as confirmation, not as a signal to change anything.+{% if recent_dialog_messages_str and not stable_prefix_ordering %}Browser alert messages raised during the previous step (the agent auto-accepted each one). Use these as additional context: if a message indicates a validation error or that the previous action was rejected, change the value, its format, or the target element before retrying — do NOT retry the same INPUT_TEXT with the same text on the same field. Treat purely informational messages (e.g. "Saved successfully") as confirmation, not as a signal to change anything.{% endif %}{% if complete_criterion and not complete_criterion_is_untrusted %}@@ -98,7 +98,30 @@ User details:{{ navigation_payload_str }}```+{% if stable_prefix_ordering %}BEGIN_UNTRUSTED_WEB_PAGE_DATA+```text{% if complete_criterion and complete_criterion_is_untrusted %}+Planner-proposed complete criterion:+{{ complete_criterion | untrusted }}+{% endif %}+Current URL: {{ current_url | untrusted }}+Clickable elements:+{{ elements | untrusted }}+Action history from previous steps:+{{ action_history | untrusted }}+{% if recent_dialog_messages_str %}+Browser alert messages raised during the previous step:+{{ recent_dialog_messages_str | untrusted }}+{% endif %}{% if open_tabs_context %}+Open browser tabs:+{{ open_tabs_context | untrusted }}+{% endif %}+```+END_UNTRUSTED_WEB_PAGE_DATA{% if recent_dialog_messages_str %}++The browser alert messages listed above were raised during the previous step (the agent auto-accepted each one). Use these as additional context: if a message indicates a validation error or that the previous action was rejected, change the value, its format, or the target element before retrying — do NOT retry the same INPUT_TEXT with the same text on the same field. Treat purely informational messages (e.g. "Saved successfully") as confirmation, not as a signal to change anything.{% endif %}{% if open_tabs_context %}++For the open browser tabs listed above: {% if show_switch_tab_action %}use SWITCH_TAB with the tab's number to make a different tab active; CLOSE_PAGE closes the tab marked [current], or set its "tab_index" to close a specific tab{% else %}CLOSE_PAGE closes the tab marked [current] by default, or set its "tab_index" to the number of a specific tab to close that one{% endif %}.{% endif %}{% else %}{% if open_tabs_context %}Open browser tabs ({% if show_switch_tab_action %}use SWITCH_TAB with the tab's number to make a different tab active; CLOSE_PAGE closes the tab marked [current], or set its "tab_index" to close a specific tab{% else %}CLOSE_PAGE closes the tab marked [current] by default, or set its "tab_index" to the number of a specific tab to close that one{% endif %}):{% endif %}@@ -121,7 +144,7 @@ Current URL: {{ current_url | untrusted }}Clickable elements:{{ elements | untrusted }}```-END_UNTRUSTED_WEB_PAGE_DATA+END_UNTRUSTED_WEB_PAGE_DATA{% endif %}Current datetime, ISO format:```diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2index 23bd2616f..1034fdaef 100644--- a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2@@ -294,12 +294,12 @@ When `goal_reached` is `true`, you are asserting "the workflow I built and teste{"type": "ASK_QUESTION","user_response": "A clear, specific question to ask the user — aim for 1-2 sentences (~200 characters), but never drop the observed field/control or a required part of a multi-part question to hit that length; specificity wins over brevity.",- "ask_subject": "One of: output_schema | credentials | target_url | disambiguation | other. The category of information the question is about.",+ "ask_subject": "One of: output_schema | credentials | target_url | disambiguation | deliverable_permission | other. The category of information the question is about. Use deliverable_permission ONLY when asking whether to go ahead with a download or file-save the request already ordered — never for submitting, paying, or any other side effect; use disambiguation when several concrete candidates match and you are asking which one.","refs": ["output.number_of_website_visitors"],"global_llm_context": { ...same structured object as above... }}-`refs` are output-path identifiers copied verbatim from the `requested_output_paths` list in the request policy summary, when `ask_subject` is `output_schema`. Omit `refs` for other subjects.+`refs` are output-path identifiers copied verbatim from the `requested_output_paths` list in the request policy summary, when `ask_subject` is `output_schema` or `deliverable_permission` — for `deliverable_permission`, cite the output path of the deliverable you are asking about. Omit `refs` for other subjects.IMPORTANT: Always preserve and extend global_llm_context across turns using the structured JSON format above. Each slot has a specific purpose:- user_goal: The user's high-level objective. Set this on the first turn, update if the goal evolves.diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.pyindex b956cdfaf..5112f878c 100644--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py@@ -3018,7 +3018,16 @@ def synthesize_code_block(})- if compile_download_target and reached_download_target is not None:+ if (+ compile_download_target+ and reached_download_target is not None+ and reached_download_target.download_kind == "observed_render"+ ):+ # A render-type affordance fires no download event, so the expect_download terminal below+ # would hang; registering captured bytes needs the execution layer (blocked on the+ # render-capture registration ticket), so no terminal is emitted for this kind yet.+ pass+ elif compile_download_target and reached_download_target is not None:# The download affordance is observed in nav_targets, not necessarily a trajectory click, so the# download is an appended terminal step compiled from the typed target — never an in-place click upgrade.# Awaiting the download value lands the file in the run-scoped downloads dir; the execution-layerdiff --git a/skyvern/forge/sdk/copilot/config.py b/skyvern/forge/sdk/copilot/config.pyindex 9184c3ae1..78f5150f1 100644--- a/skyvern/forge/sdk/copilot/config.py+++ b/skyvern/forge/sdk/copilot/config.py@@ -60,17 +60,6 @@ POST_NAVIGATE_NUDGE = ("to inspect the page before responding. Do NOT answer from memory.")-POST_INTERMEDIATE_SUCCESS_NUDGE = (- "STOP — do NOT respond to the user yet. "- "Your workflow only covers a subset of what the user asked for. "- "You MUST add the next block now: call update_and_run_blocks with the complete "- "workflow YAML, but pass only the next 1-2 unverified block labels when the "- "workflow has several page-changing stages. Keep later blocks in the YAML; "- "shrink only the block_labels test frontier. "- "Only respond to the user when every distinct action they requested is covered "- "by a workflow block, or you have clear evidence that continuing is infeasible."-)-POST_FAILED_TEST_NUDGE = ("STOP — your last test run FAILED. Do NOT respond to the user yet.\n""1. First, call get_run_results — pass the workflow_run_id from the prior "@@ -308,7 +297,6 @@ DEFAULT_ENFORCEMENT_NUDGES: dict[str, str] = {"screenshot_dropped": SCREENSHOT_DROPPED_NUDGE,"post_update": POST_UPDATE_NUDGE,"post_navigate": POST_NAVIGATE_NUDGE,- "post_intermediate_success": POST_INTERMEDIATE_SUCCESS_NUDGE,"post_failed_test": POST_FAILED_TEST_NUDGE,"post_failed_test_inspect_first": POST_FAILED_TEST_INSPECT_FIRST_NUDGE,"post_explore_without_workflow": POST_EXPLORE_WITHOUT_WORKFLOW_NUDGE,diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.pyindex f975cbf07..3f13e6dab 100644--- a/skyvern/forge/sdk/copilot/context.py+++ b/skyvern/forge/sdk/copilot/context.py@@ -31,7 +31,7 @@ ResponseType = Literal["REPLY", "ASK_QUESTION", "REPLACE_WORKFLOW"]COPILOT_RESPONSE_TYPES: tuple[ResponseType, ...] = get_args(ResponseType)ProposalDisposition = Literal["no_proposal", "auto_applicable", "review_untested", "review_tested"]-AskSubject = Literal["output_schema", "credentials", "target_url", "disambiguation", "other"]+AskSubject = Literal["output_schema", "credentials", "target_url", "disambiguation", "deliverable_permission", "other"]COPILOT_ASK_SUBJECTS: tuple[AskSubject, ...] = get_args(AskSubject)@@ -769,7 +769,6 @@ class CopilotContext(AgentContext):update_workflow_called: bool = Falsetest_after_update_done: bool = Falsepost_update_nudge_count: int = 0- coverage_nudge_count: int = 0format_nudge_count: int = 0no_workflow_nudge_count: int = 0copilot_total_timeout_exceeded: bool = Falsediff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.pyindex f40891c6c..54e41e13c 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport copy+import dataclassesimport jsonimport osimport re@@ -110,6 +111,7 @@ from skyvern.forge.sdk.copilot.output_utils import (looks_like_workflow_delivery_claim,parse_final_response,)+from skyvern.forge.sdk.copilot.reached_download_target import can_deliver_registered_downloadfrom skyvern.forge.sdk.copilot.request_policy import (REGISTERED_DOWNLOAD_REQUESTED_OUTPUT_PATHS,CompletionCriterion,@@ -144,6 +146,7 @@ from skyvern.forge.sdk.copilot.terminal_predicates import (outcome_criteria_evaluated,outcome_fully_verified,)+from skyvern.forge.sdk.copilot.todo_list import _inapplicable_criterion_ids, unmet_action_deliverable_criteriafrom skyvern.forge.sdk.copilot.tracing_setup import copilot_spanfrom skyvern.forge.sdk.copilot.turn_halt import (blocker_signal_is_genuinely_terminal,@@ -174,10 +177,8 @@ if TYPE_CHECKING:LOG = structlog.get_logger()POST_FORMAT_NUDGE = copilot_config_defaults.POST_FORMAT_NUDGE-POST_INTERMEDIATE_SUCCESS_NUDGE = copilot_config_defaults.POST_INTERMEDIATE_SUCCESS_NUDGEMAX_POST_UPDATE_NUDGES = 2-MAX_INTERMEDIATE_NUDGES = 8MAX_FAILED_TEST_NUDGES = 2# Repair rounds the typed obligation may force past the ordinary nudge budget before a turn is# allowed to report an unrepairable failure.@@ -202,7 +203,6 @@ REPEATED_FRONTIER_STREAK_STOP_AT = 3# trips fall through to the repeated-frontier escalation path.MAX_PER_TOOL_BUDGET_NUDGES = 2_NO_PROGRESS_INTERACTION_REASON_CODES = frozenset({"loop_detected_no_forward_progress_interaction"})-MIN_BLOCKS_FOR_AUTO_COMPLETE = 10TOTAL_TIMEOUT_SECONDS = settings.WORKFLOW_COPILOT_TOTAL_TIMEOUT_SECONDS or 900# Floor for the per-iteration ``wait_for`` deadline so an already-spent budget# never yields ``wait_for(timeout=0)`` (which raises immediately). Kept as a@@ -262,6 +262,13 @@ PRESENT_COMPLETION_CONTRACT_ASK_RETRY = ("required input is missing under RequestPolicy or TurnIntent.")+DELIVERABLE_PERMISSION_ASK_RETRY = (+ "Permission for this deliverable is already granted: the request's completion contract orders it "+ "({criterion_outcomes}), so do not ask whether to produce it — produce it and verify it. If several "+ "concrete candidates match the request, pick the one the request best describes and say in your reply "+ "which you took and anything about it the user could not have known."+)+def _is_progress_narration(user_response: Any) -> bool:if not isinstance(user_response, str) or not user_response:@@ -773,7 +780,7 @@ def built_complete_without_evaluated_outcome(ctx: CopilotContext) -> bool:and latest_diagnosis_contract_satisfies_goal(ctx)):return False- return not _verified_goal_likely_needs_more_work(ctx)+ return Truedef built_unverified_repair_inert_context(ctx: CopilotContext) -> bool:@@ -783,7 +790,6 @@ def built_unverified_repair_inert_context(ctx: CopilotContext) -> bool:and _outcome_criteria_evaluated(ctx)and _latest_diagnosis_contract_selects_no_repair(ctx)and _completion_verification_only_structural_abstentions(ctx)- and not _verified_goal_likely_needs_more_work(ctx))@@ -801,7 +807,7 @@ def gate_decision_trace_fields(ctx: CopilotContext) -> dict[str, bool]:Captured wherever the gate is evaluated (including when it returns False, thesignal that explains why the turn continued) so a single trace shows whetherthe gate failed on the test, the full-workflow run, the diagnosis contract,- the absence of outcome verification, or the block-count heuristic.+ or the absence of outcome verification."""return {"gate_satisfied": verified_goal_satisfied_context(ctx),@@ -813,20 +819,10 @@ def gate_decision_trace_fields(ctx: CopilotContext) -> dict[str, bool]:"gate_diagnosis_contract_satisfies_goal": latest_diagnosis_contract_satisfies_goal(ctx),"gate_outcome_criteria_evaluated": _outcome_criteria_evaluated(ctx),"gate_artifact_health_blocked": artifact_health_blocked(ctx),- "gate_likely_needs_more_work": _verified_goal_likely_needs_more_work(ctx),"gate_evaluated_this_turn": True,}-def _verified_goal_likely_needs_more_work(ctx: CopilotContext) -> bool:- block_count = ctx.last_update_block_count- if not isinstance(block_count, int):- return False- user_message = ctx.user_message- completion_contract = _request_completion_contract(ctx)- return _goal_likely_needs_more_blocks(user_message, block_count, completion_contract)--def _mark_copilot_total_timeout(ctx: Any, *, elapsed_seconds: float, iteration: int) -> None:already_marked = ctx.copilot_total_timeout_exceeded is Truectx.copilot_total_timeout_exceeded = True@@ -928,40 +924,6 @@ def _raise_if_unrecoverable_contract_stop(ctx: Any) -> None:raise CopilotUnrecoverableToolError(tool_name, reason)-_ACTION_CATEGORIES: list[list[str]] = [- ["navigate", "go to", "open", "visit"],- ["download", "save", "export"],- ["extract", "scrape", "collect", "gather", "get all", "grab", "capture", "retrieve", "pull"],- ["login", "log in", "sign in", "authenticate"],- ["search", "find", "look for", "look up", "check", "verify"],- ["fill", "enter", "type", "submit", "complete the form", "input"],- ["click", "select", "choose", "pick"],- ["upload", "attach"],-]--_SEQUENTIAL_CONNECTORS = [" and then ", " then ", " after that ", " next ", " followed by ", " afterward "]---def _request_completion_contract(ctx: Any) -> str | None:- request_policy = getattr(ctx, "request_policy", None)- completion_contract = getattr(request_policy, "completion_contract", None)- if isinstance(completion_contract, str) and completion_contract.strip():- return completion_contract.strip()- return None---def _request_completion_contract_status(ctx: Any) -> str:- request_policy = getattr(ctx, "request_policy", None)- status = getattr(request_policy, "completion_contract_status", None)- if status in ("present", "absent", "unknown"):- return status- return "present" if _request_completion_contract(ctx) else "absent"---def _completion_contract_unknown_due_to_policy_fallback(ctx: Any) -> bool:- return _request_completion_contract_status(ctx) == "unknown"--_AUTHORING_TURN_INTENT_MODES = frozenset({TurnIntentMode.BUILD, TurnIntentMode.EDIT, TurnIntentMode.DRAFT_ONLY})@@ -1000,6 +962,56 @@ def recycle_admits_present_completion_contract_ask(ctx: CopilotContext) -> bool:return not ctx.has_genuine_workflow_attempt()+def deliverable_permission_ask_bounced(+ *,+ ask_subject: AskSubject | None,+ admission_base: bool,+ retry_admitted: bool,+ unmet_criteria: Sequence[CompletionCriterion],+ ask_refs: Sequence[str],+) -> bool:+ """Pure decision shared by the live gate and offline replay: a permission ask for a+ download the contract already orders bounces back to the build.++ The ask must cite an unmet criterion's own output path. The subject label is model-chosen,+ so without that binding a confirmation for an unrelated irreversible side effect (a payment+ on a request that also downloads a receipt) could be answered by a download's authority.+ """+ if retry_admitted or ask_subject != "deliverable_permission" or not admission_base:+ return False+ ordered_paths = {criterion.output_path for criterion in unmet_criteria if criterion.output_path}+ return bool(ordered_paths) and bool(ordered_paths & set(ask_refs))+++def _dump_ask_gate_decision(ctx: CopilotContext, parsed: dict[str, Any], *, outcome: str) -> None:+ """Write the ask-gate decision and its inputs when a local run asks for them, so an admission+ change replays offline against real captured asks instead of costing a live turn each."""+ directory = os.environ.get("COPILOT_DUMP_ASK_INPUTS")+ if not directory or settings.ENV != "local":+ return+ try:+ os.makedirs(directory, mode=0o700, exist_ok=True)+ policy = ctx.request_policy+ criteria = policy.graded_completion_criteria() if isinstance(policy, RequestPolicy) else []+ satisfied_ids = sorted(_inapplicable_criterion_ids(ctx))+ payload = {+ "outcome": outcome,+ "ask_subject": coerce_ask_subject(parsed.get("ask_subject")),+ "ask_refs": parsed_ask_refs(parsed.get("refs")),+ "user_response": parsed.get("user_response"),+ "admission_base": _present_completion_contract_ask_admission_base(ctx),+ "has_genuine_workflow_attempt": ctx.has_genuine_workflow_attempt(),+ "turn_intent_mode": ctx.turn_intent.mode if ctx.turn_intent else None,+ "criteria": [dataclasses.asdict(criterion) for criterion in criteria],+ "satisfied_criterion_ids": satisfied_ids,+ }+ target = os.path.join(directory, f"ask-{outcome}-{uuid.uuid4().hex[:8]}.json")+ with open(os.open(target, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o600), "w") as handle:+ json.dump(payload, handle, default=str)+ except Exception:+ LOG.info("copilot_ask_gate_input_dump_failed", exc_info=True)++def _present_completion_contract_ask_retry(ctx: CopilotContext, parsed: dict[str, Any]) -> EnforcementDecision | None:if parsed.get("type") != "ASK_QUESTION":return None@@ -1010,8 +1022,33 @@ def _present_completion_contract_ask_retry(ctx: CopilotContext, parsed: dict[strif _present_completion_contract_ask_admission_base(ctx):auto_answer = _typed_ask_subject_auto_answer(ctx, ask_subject, parsed)if auto_answer is not None:+ _dump_ask_gate_decision(ctx, parsed, outcome="auto_answered")return EnforcementDecision(rule="typed_ask_subject_auto_answer", message=auto_answer)retry_admitted = recycle_admits_present_completion_contract_ask(ctx)+ ordered = unmet_action_deliverable_criteria(ctx)+ if deliverable_permission_ask_bounced(+ ask_subject=ask_subject,+ admission_base=_present_completion_contract_ask_admission_base(ctx),+ retry_admitted=retry_admitted,+ unmet_criteria=ordered,+ ask_refs=parsed_ask_refs(parsed.get("refs")),+ ):+ if ordered:+ _dump_ask_gate_decision(ctx, parsed, outcome="deliverable_permission_retry")+ LOG.info(+ "copilot_ask_subject_passed_through",+ subject=ask_subject,+ outcome="deliverable_permission_retry",+ criterion_ids=[criterion.id for criterion in ordered],+ **ctx.genuine_attempt_parity_fields(),+ )+ return EnforcementDecision(+ rule="deliverable_permission_ask_retry",+ message=DELIVERABLE_PERMISSION_ASK_RETRY.format(+ criterion_outcomes="; ".join(criterion.outcome for criterion in ordered)+ ),+ )+ _dump_ask_gate_decision(ctx, parsed, outcome="build_first_retry" if retry_admitted else "reached_user")if ask_subject is not None:LOG.info("copilot_ask_subject_passed_through",@@ -1111,23 +1148,6 @@ def _decision(config: CopilotConfig | None, key: str) -> EnforcementDecision:return EnforcementDecision(rule=key, message=_nudge(config, key))-def _goal_likely_needs_more_blocks(user_message: Any, block_count: int, completion_contract: str | None = None) -> bool:- """Return True when the goal likely requires more blocks than currently exist."""- if block_count >= MIN_BLOCKS_FOR_AUTO_COMPLETE:- return False- if not isinstance(user_message, str):- return False- text = user_message.lower()- has_sequential = any(conn in text for conn in _SEQUENTIAL_CONNECTORS)- if block_count >= 1 and completion_contract:- return has_sequential and block_count < 2-- matched_categories = sum(1 for category in _ACTION_CATEGORIES if any(keyword in text for keyword in category))-- estimated_min_blocks = max(matched_categories, 2) if has_sequential else matched_categories- return block_count < estimated_min_blocks--def _same_page(left: str | None, right: str | None) -> bool:if not left or not right:return False@@ -1232,11 +1252,11 @@ def _post_discovery_entrypoint_url_question_nudge()-def _response_coverage_nudge(+def _response_output_nudge(ctx: Any, parsed: dict[str, Any], config: CopilotConfig | None = None) -> EnforcementDecision | None:- """Peek at the model's final output and return a decision for coverage gaps- or progress-narration format. ASK_QUESTION is let through so the agent+ """Peek at the model's final output for unsupported delivery claims or+ progress-narration format. ASK_QUESTION is let through so the agentcan request missing credentials or disambiguation, except when discoveryresolved a candidate and the agent has not yet inspected or composed fromthat candidate.@@ -1269,27 +1289,6 @@ def _response_coverage_nudge(ctx.no_workflow_nudge_count = nudge_count + 1return _decision(config, "post_no_workflow_delivery")- workflow_tested_ok = (- getattr(ctx, "last_test_ok", None) is True- and getattr(ctx, "update_workflow_called", False)- and getattr(ctx, "test_after_update_done", False)- )- if workflow_tested_ok:- block_count = getattr(ctx, "last_update_block_count", None)- # ctx.user_message is set by the agent orchestrator in a later stack PR- # (06c). The getattr default keeps this gate working on partial stacks.- user_message = getattr(ctx, "user_message", "")- completion_contract = _request_completion_contract(ctx)- if (- isinstance(block_count, int)- and not _completion_contract_unknown_due_to_policy_fallback(ctx)- and _goal_likely_needs_more_blocks(user_message, block_count, completion_contract)- ):- nudge_count = getattr(ctx, "coverage_nudge_count", 0)- if nudge_count < MAX_INTERMEDIATE_NUDGES:- ctx.coverage_nudge_count = nudge_count + 1- return _decision(config, "post_intermediate_success")-if _is_progress_narration(parsed.get("user_response")):nudge_count = getattr(ctx, "format_nudge_count", 0)if nudge_count < MAX_FORMAT_NUDGES:@@ -1612,14 +1611,14 @@ def enforcement_decision(ctx.repair_obligation_nudge_count = _get_int(ctx, "repair_obligation_nudge_count") + 1return _decision(config, "post_failed_test")- # Response-time gate: peek at the model's final output to tell ASK_QUESTION- # (always allowed) from a REPLY with a coverage gap or progress-narration.+ # Response-time gate: peek at the model's final output to catch unsupported+ # delivery claims or progress narration. ASK_QUESTION remains allowed.# Only runs when no state-based nudge fired.if result is not None:parsed = _parse_normalized_final_response(result)if parsed is None:return None- return _response_coverage_nudge(ctx, parsed, config)+ return _response_output_nudge(ctx, parsed, config)return None@@ -1979,7 +1978,6 @@ _NUDGE_TYPE_BY_KEY: dict[str, str] = {"post_failed_test": "post_failed_test","post_failed_test_inspect_first": "post_failed_test_inspect_first","screenshot_dropped": "screenshot_dropped_on_recovery",- "post_intermediate_success": "intermediate_success","post_format": "format",# Self-mapped so the table enumerates every emittable rule; these two carry a# hardcoded message and so have no nudge key to shorten.@@ -2456,7 +2454,7 @@ def download_satisfied_requested_output_paths(ctx: AgentContext) -> set[str]:``registered_download`` deliverables. Empty unless a download target with a captured selectorwas reached. Author-time seam classification only — it never credits scout coverage."""download = ctx.reached_download_target- if download is None or not download.selector:+ if download is None or not download.selector or not can_deliver_registered_download(download):return set()requested = _requested_output_paths_for_ctx(ctx)# The scout reads page scalars; it can never read a file that exists only once a download fires.diff --git a/skyvern/forge/sdk/copilot/reached_download_target.py b/skyvern/forge/sdk/copilot/reached_download_target.pyindex 5416e44cf..49748602a 100644--- a/skyvern/forge/sdk/copilot/reached_download_target.py+++ b/skyvern/forge/sdk/copilot/reached_download_target.py@@ -9,7 +9,7 @@ from dataclasses import dataclassfrom enum import Enumfrom typing import Any, Literal, cast-DownloadKind = Literal["registered", "attribute", "extension", "observed"]+DownloadKind = Literal["registered", "attribute", "extension", "observed", "observed_render"]# ``registered`` (S1) and ``observed`` (S3) are backed by an actual browser download having fired;# ``attribute``/``extension`` are S2 predictions from a scouted link's href shape.@@ -20,6 +20,10 @@ DOWNLOAD_KIND_EXTENSION: DownloadKind = "extension"# serving a file via Content-Disposition has no extension and no ``download`` attribute, so the# href-shape prediction is blind to it and only the fired download proves the affordance.DOWNLOAD_KIND_OBSERVED: DownloadKind = "observed"+# A document the scout's click opened as an inline render (a bill image in a new tab). No browser+# download event ever fires for these, so the dir-diff proof above cannot see them; the popup whose+# document is the file (image content-type, no attachment disposition) is the equivalent proof.+DOWNLOAD_KIND_OBSERVED_RENDER: DownloadKind = "observed_render"# S2 may only mint a prediction; ``registered`` is S1-only and must never come from a nav target._PREDICTED_DOWNLOAD_KINDS: frozenset[str] = frozenset({DOWNLOAD_KIND_ATTRIBUTE, DOWNLOAD_KIND_EXTENSION})@@ -74,6 +78,7 @@ class _SourceStepKind(str, Enum):trajectory_recency = "trajectory_recency"registered_output = "registered_output"observed_download = "observed_download"+ observed_render = "observed_render"@dataclass(frozen=True)@@ -86,6 +91,9 @@ class ReachedDownloadTarget:# Stored ``trajectory_index`` of the last scouted interaction at the moment the affordance was# observed; the synthesizer sequences the download terminal here instead of after the whole trajectory.trajectory_anchor: int | None = None+ # For ``observed_render`` only: the click-proven URL the popup rendered. Provenance is the+ # scout's own click, never a model guess, which is what licenses saving from it.+ rendered_url: str = ""def to_dict(self) -> dict[str, Any]:return {@@ -94,6 +102,7 @@ class ReachedDownloadTarget:"download_kind": self.download_kind,"source_step": self.source_step,"already_registered": self.already_registered,+ "rendered_url": self.rendered_url,}@@ -172,6 +181,25 @@ def derive_from_observed_download(*, selector: str, affordance_text: str = "") -)+def derive_from_observed_render(+ *, selector: str, rendered_url: str, affordance_text: str = ""+) -> ReachedDownloadTarget | None:+ """S3 sibling: mint a target from a document the scout's click opened as an inline image render,+ so the guidance layer can steer the model away from the download idioms that cannot work on it."""+ selector = _summary_str(selector)+ rendered_url = _summary_str(rendered_url)+ if not selector or not rendered_url:+ return None+ return ReachedDownloadTarget(+ selector=selector,+ affordance_text=_summary_str(affordance_text),+ download_kind=DOWNLOAD_KIND_OBSERVED_RENDER,+ source_step=_SourceStepKind.observed_render.value,+ already_registered=False,+ rendered_url=rendered_url,+ )++def derive_from_block_outputs(block_outputs_by_label: Any) -> ReachedDownloadTarget | None:"""S1: confirm a reached download from a browser download already registered into a block output.@@ -206,8 +234,29 @@ _CONFIRMED_DOWNLOAD_GUIDANCE = ("URLs in the chat reply.")+_OBSERVED_RENDER_GUIDANCE = (+ "This click opens the document as an inline render in a new tab — no browser download event "+ "fires here, so do NOT author page.expect_download for this affordance (it waits forever) and "+ "do not return a downloaded_files entry the platform did not register. If the viewer offers a "+ "real download/print/export control, exercise that instead; otherwise report plainly that the "+ "document renders on screen but cannot be registered as a downloaded file yet."+)+++def can_deliver_registered_download(target: ReachedDownloadTarget | None) -> bool:+ """Whether this target can still become a registered download in the generated workflow.++ An ``observed_render`` affordance compiles no terminal (registering its bytes needs the+ execution layer), so it must never credit a download deliverable as reachable or reached.+ """+ if target is None:+ return False+ return target.download_kind != DOWNLOAD_KIND_OBSERVED_RENDER+def guidance_for(target: ReachedDownloadTarget) -> str:+ if target.download_kind == DOWNLOAD_KIND_OBSERVED_RENDER:+ return _OBSERVED_RENDER_GUIDANCEreturn _CONFIRMED_DOWNLOAD_GUIDANCE if target.already_registered else _AUTHOR_DOWNLOAD_GUIDANCEdiff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex b0c193db1..4e07821df 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -309,7 +309,6 @@ class AgentContext:update_workflow_called: bool = Falsetest_after_update_done: bool = Falsepost_update_nudge_count: int = 0- coverage_nudge_count: int = 0format_nudge_count: int = 0copilot_total_timeout_exceeded: bool = Falsefailed_test_nudge_count: int = 0@@ -555,6 +554,8 @@ class AgentContext:# Browser-session download filenames snapshotted before a scout click, so the post-hook can tell# a download this click produced from one an earlier click left behind.pending_scout_download_snapshot: frozenset[str] | None = None+ pending_scout_popup: Page | None = None+ pending_scout_popup_content_type: str | None = Nonerepair_obligation_nudge_count: int = 0# (selector, ambiguous) verdict from a pre-dispatch live count probe, applied to the recorded# interaction only when the post-action resolved selector matches the probed one.diff --git a/skyvern/forge/sdk/copilot/todo_list.py b/skyvern/forge/sdk/copilot/todo_list.pyindex b49dbd17d..415968124 100644--- a/skyvern/forge/sdk/copilot/todo_list.py+++ b/skyvern/forge/sdk/copilot/todo_list.py@@ -2,6 +2,8 @@from __future__ import annotations+from collections.abc import Sequence+from collections.abc import Set as AbstractSetfrom typing import Anyimport structlog@@ -121,6 +123,36 @@ def _interactions_line(ctx: AgentContext) -> str | None:return "The site has not been acted on yet (0 interactions recorded)"+def _inapplicable_criterion_ids(ctx: AgentContext) -> set[str]:+ """Criteria that no longer need action: satisfied, or structurally unfired because their+ antecedent condition did not hold (a conditional download on a branch the run did not take)."""+ result = ctx.completion_verification_result+ if result is None:+ return set()+ ids = {verdict.criterion_id for verdict in result.verdicts if verdict.satisfied}+ ids |= set(getattr(result, "structural_unfired_criterion_ids", ()) or ())+ return ids+++def unmet_action_deliverable_criteria_from(+ criteria: Sequence[CompletionCriterion], inapplicable_ids: AbstractSet[str]+) -> list[CompletionCriterion]:+ """Run-plane criteria whose deliverable needs an action on the page (today: a registered+ browser download) and which no verification verdict has satisfied yet. Pure over its inputs+ so offline replay runs the same decision the live gate ran."""+ return [+ criterion+ for criterion in criteria+ if "registered_download" in (criterion.deliverable_kind, criterion.declared_deliverable_kind)+ and criterion.level == "run"+ and criterion.id not in inapplicable_ids+ ]+++def unmet_action_deliverable_criteria(ctx: AgentContext) -> list[CompletionCriterion]:+ return unmet_action_deliverable_criteria_from(_minted_criteria(ctx), _inapplicable_criterion_ids(ctx))++def render_todo_list(ctx: AgentContext) -> str | None:lines = [line for line in (_login_line(ctx), _outputs_line(ctx)) if line]if not lines:diff --git a/skyvern/forge/sdk/copilot/tools/completion.py b/skyvern/forge/sdk/copilot/tools/completion.pyindex 9ff9ea9f2..ea6a39e35 100644--- a/skyvern/forge/sdk/copilot/tools/completion.py+++ b/skyvern/forge/sdk/copilot/tools/completion.py@@ -51,7 +51,6 @@ from skyvern.forge.sdk.copilot.completion_verification import (summarize_unsatisfied_outcomes,verdict_missing_evidence,)-from skyvern.forge.sdk.copilot.enforcement import _goal_likely_needs_more_blocksfrom skyvern.forge.sdk.copilot.llm_config import resolve_main_copilot_handlerfrom skyvern.forge.sdk.copilot.outcome_verification_trace import record_completion_verificationfrom skyvern.forge.sdk.copilot.output_utils import iter_failure_reasons@@ -1953,15 +1952,8 @@ def _tool_visible_result_after_completion_verification(def _emit_completion_verification_trace(copilot_ctx: Any, completion_verification: CompletionVerificationResult) -> None:- block_count = getattr(copilot_ctx, "last_update_block_count", None)- policy = getattr(copilot_ctx, "request_policy", None)- contract = policy.completion_contract if policy is not None else None- heuristic_would_block = isinstance(block_count, int) and _goal_likely_needs_more_blocks(- getattr(copilot_ctx, "user_message", ""), block_count, contract- )trace_data = {**completion_verification.to_trace_data(),- "heuristic_would_block": heuristic_would_block,"evidence_block_present": _current_workflow_has_evidence_block(copilot_ctx),"warrants_repair": _outcome_failure_warrants_repair(copilot_ctx, completion_verification),}diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.pyindex 04a02ec4b..580ba429a 100644--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py@@ -75,6 +75,7 @@ from .page_observation import (from .scouting import (_PRE_NAVIGATION_ROLE_NAME_TIMEOUT_SECONDS,_actionable_targets_for_result,+ _arm_scout_popup_listener,_attach_scout_page_summary,_capture_post_interaction_screenshot,_capture_scout_ambiguity,@@ -87,6 +88,7 @@ from .scouting import (_mark_page_inspected,_mark_pending_browser_interaction_observation,_maybe_attach_observed_download_target,+ _maybe_attach_observed_render_target,_maybe_attach_reached_download_target,_prenav_ambiguity_for_selector,_prenav_dynamic_row_for_selector,@@ -380,6 +382,8 @@ async def _click_pre_hook(ctx.pending_scout_ambiguous = Nonectx.pending_scout_dynamic_row = Nonectx.pending_scout_download_snapshot = None+ ctx.pending_scout_popup = None+ ctx.pending_scout_popup_content_type = Noneawait _capture_scout_source_url(ctx)deterministic_result = _strip_intent_for_code_only_selector_action(params, ctx, tool_name="click")if deterministic_result is not None:@@ -407,6 +411,7 @@ async def _click_pre_hook(if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER:await _capture_scout_dynamic_row(ctx, selector)ctx.pending_scout_download_snapshot = await _scout_session_download_names(ctx)+ await _arm_scout_popup_listener(ctx)return None@@ -623,6 +628,7 @@ async def _click_post_hook(# A download this click produced is proof the affordance works, so it outranks the# href-shape prediction — and is the only source that sees a command-URL download.await _maybe_attach_observed_download_target(ctx, result, selector=selector, url=url)+ await _maybe_attach_observed_render_target(ctx, result, selector=selector, url=url)if page_evidence is not None:_attach_scout_page_summary(result, page_evidence)if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER:diff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.pyindex 427b5ff45..960affcf0 100644--- a/skyvern/forge/sdk/copilot/tools/scouting.py+++ b/skyvern/forge/sdk/copilot/tools/scouting.py@@ -1,15 +1,20 @@from __future__ import annotationsimport asyncio+import dataclassesimport hashlibimport json+import osimport reimport time+import uuid+from collections.abc import Sequencefrom dataclasses import replacefrom typing import Any, Literal, castfrom urllib.parse import urlparseimport structlog+from playwright.async_api import Page, Responsefrom skyvern.config import settingsfrom skyvern.forge import app@@ -68,6 +73,7 @@ from skyvern.forge.sdk.copilot.enforcement import ()from skyvern.forge.sdk.copilot.reached_download_target import (DOWNLOAD_KIND_OBSERVED,+ DOWNLOAD_KIND_OBSERVED_RENDER,ReachedDownloadTarget,)from skyvern.forge.sdk.copilot.reached_download_target import (@@ -75,8 +81,10 @@ from skyvern.forge.sdk.copilot.reached_download_target import ()from skyvern.forge.sdk.copilot.reached_download_target import (derive_from_observed_download,+ derive_from_observed_render,)from skyvern.forge.sdk.copilot.reached_download_target import guidance_for as _reached_download_guidance_for+from skyvern.forge.sdk.copilot.request_policy import CompletionCriterionfrom skyvern.forge.sdk.copilot.result_evidence import (LoadedResultCompositionEvidence,loaded_result_composition_evidence_from_page,@@ -90,6 +98,12 @@ from skyvern.forge.sdk.copilot.runtime import (resolve_browser_state_for_context,)from skyvern.forge.sdk.copilot.screenshot_utils import enqueue_screenshot_from_result+from skyvern.forge.sdk.copilot.todo_list import (+ _inapplicable_criterion_ids,+ _minted_criteria,+ _satisfied_output_paths,+ unmet_action_deliverable_criteria,+)from skyvern.forge.sdk.workflow.models.block import (CodeBlockCaptchaError,_bounded_code_block_recaptcha_token_populated,@@ -1844,6 +1858,42 @@ def _record_scout_page_observation(ctx: AgentContext, page_evidence: dict[str, Actx.last_scout_observation_has_password_control = _page_evidence_has_password_control(page_evidence)+def composition_steer_bypassed_for_action_goal(+ unmet_criteria: Sequence[CompletionCriterion], parsed: dict[str, Any], *, download_target_reached: bool+) -> bool:+ """Pure decision shared by the live steer and offline replay: while an action deliverable is+ unmet and its affordance is not yet click-proven, actionable targets stay visible."""+ return bool(unmet_criteria) and not download_target_reached and bool(_actionable_target_identities(parsed))+++def _dump_steer_decision(ctx: AgentContext, parsed: dict[str, Any], *, url: str, outcome: str) -> None:+ """Write the evaluate-steer decision and its inputs when a local run asks for them, so a+ steering change replays offline against real captures instead of costing a live turn each.+ The evidence carries page text, so writing requires the explicit path plus a local environment."""+ directory = os.environ.get("COPILOT_DUMP_STEER_INPUTS")+ if not directory or settings.ENV != "local":+ return+ try:+ os.makedirs(directory, mode=0o700, exist_ok=True)+ payload = {+ "outcome": outcome,+ "url": url,+ "page_evidence": parsed,+ "criteria": [dataclasses.asdict(criterion) for criterion in _minted_criteria(ctx)],+ "satisfied_output_paths": sorted(_satisfied_output_paths(ctx)),+ "satisfied_criterion_ids": sorted(_inapplicable_criterion_ids(ctx)),+ "download_target_reached": ctx.reached_download_target is not None,+ "reached_download_target": ctx.reached_download_target.to_dict() if ctx.reached_download_target else None,+ "last_evaluate_actionable_signature": ctx.last_evaluate_actionable_signature,+ "last_evaluate_actionable_url": ctx.last_evaluate_actionable_url,+ }+ target = os.path.join(directory, f"steer-{outcome}-{uuid.uuid4().hex[:8]}.json")+ with open(os.open(target, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o600), "w") as handle:+ json.dump(payload, handle, default=str)+ except Exception:+ LOG.info("copilot_steer_input_dump_failed", exc_info=True)++async def _maybe_steer_evaluate_to_action(ctx: AgentContext,result: dict[str, Any],@@ -1879,13 +1929,31 @@ async def _maybe_steer_evaluate_to_action(overlay_only = packet_describes_a_clearable_overlay(parsed)if overlay_only:LOG.info("copilot_evaluate_result_composition_deferred_to_obstruction", url=url)+ # An unmet action deliverable outranks reading the page it must be earned on: composing an+ # extraction here would hide the very affordances the goal still needs clicked, and no+ # extraction can satisfy a registered-download criterion (SKY incident: the July-invoice+ # billing table read; see reached_download_target.py for why only a click can prove these).+ unmet_action_criteria = unmet_action_deliverable_criteria(ctx)+ preserve_targets_for_goal = composition_steer_bypassed_for_action_goal(+ unmet_action_criteria, parsed, download_target_reached=ctx.reached_download_target is not None+ )+ if preserve_targets_for_goal:+ LOG.info(+ "copilot_evaluate_composition_steer_bypassed_for_unmet_action_goal",+ url=url,+ criterion_ids=[criterion.id for criterion in unmet_action_criteria],+ )# Recording an observation is independent of whether it steers. A page whose relations do not# mint a loaded result is steered as actionable instead, and appending only on the composition# branch discarded those packets outright: the log page carrying the requested count was# observed, steered as actionable, and never reached the binder at all (SKY-13226).if has_bounded_page_schema(parsed):_append_flow_evidence(ctx, parsed, reached_via="current_page")- loaded_results = None if overlay_only else _mint_current_loaded_result_source(ctx, parsed, url=url)+ loaded_results = (+ None+ if (overlay_only or preserve_targets_for_goal)+ else _mint_current_loaded_result_source(ctx, parsed, url=url)+ )if loaded_results is not None:_reset_evaluate_tracker(ctx)ctx.latest_evaluate_result_composition_steer = loaded_results@@ -1902,6 +1970,7 @@ async def _maybe_steer_evaluate_to_action(result_container_count=loaded_results.result_container_count,table_result_container_count=loaded_results.table_result_container_count,)+ _dump_steer_decision(ctx, parsed, url=url, outcome="composition_steer")# The result is patched in-place; returning False keeps the normal tool-loop guard active.return Falsectx.latest_evaluate_result_composition_steer = None@@ -1940,6 +2009,7 @@ async def _maybe_steer_evaluate_to_action(is_repeat=is_repeat,steered=is_repeat and bool(targets),)+ _dump_steer_decision(ctx, parsed, url=url, outcome="actionable_path")except Exception:data.pop("actionable_targets", None)data.pop("composition_targets", None)@@ -2006,6 +2076,108 @@ async def _scout_session_download_names(ctx: AgentContext) -> frozenset[str] | Nreturn frozenset(str(name) for name in files or ())+def _record_popup_navigation_headers(ctx: AgentContext, response: Response) -> None:+ """Record the popup's own document content type as the browser received it.++ Re-requesting the URL to read headers would send the context's cookies to an address the page+ chose, replaying one-click confirm links and sign-in redirects, and many document endpoints+ answer HEAD differently or refuse it. The navigation response the browser already made costs+ nothing and, unlike `document.contentType`, cannot be shadowed by page script.+ """+ try:+ if ctx.pending_scout_popup_content_type is None and response.request.is_navigation_request():+ ctx.pending_scout_popup_content_type = str(response.headers.get("content-type", ""))+ except Exception:+ LOG.debug("copilot_popup_navigation_headers_unreadable", exc_info=True)+++async def _arm_scout_popup_listener(ctx: AgentContext) -> None:+ """Arm a one-shot popup listener before a click dispatches.++ Playwright reports the popup the click opened by identity, so nothing polls and an ordinary+ click costs nothing; a URL-set diff would both stall every click and mistake a same-tab+ navigation for a new tab."""+ ctx.pending_scout_popup = None+ ctx.pending_scout_popup_content_type = None+ try:+ browser_state = await resolve_browser_state_for_context(ctx)+ if browser_state is None:+ return+ page = await browser_state.get_or_create_page()++ def _capture(popup: Page) -> None:+ ctx.pending_scout_popup = popup+ popup.on("response", lambda response: _record_popup_navigation_headers(ctx, response))++ page.once("popup", _capture)+ except Exception:+ LOG.warning("copilot_scout_popup_listener_failed", exc_info=True)+++# Bounded so a page that stalls the probe cannot spend the turn budget one click at a time.+_RENDER_PROBE_TIMEOUT_MS = 5000.0+++def _attach_reached_download_target(+ ctx: AgentContext, data: dict[str, Any], target: ReachedDownloadTarget, *, url: str+) -> None:+ data["reached_download_target"] = target.to_dict()+ data["reached_download_guidance"] = _reached_download_guidance_for(target)+ ctx.reached_download_target = _with_trajectory_anchor(ctx, target)+ if ctx.synthesized_block_offered and not ctx.update_workflow_called:+ ctx.synthesized_block_offered = False+ ctx.synthesized_block_offered_goal_complete = False+ _register_reached_download_scout_interaction(ctx, target, url=url)+ LOG.info(+ "copilot_reached_download_target_steer",+ url=url,+ download_kind=target.download_kind,+ already_registered=target.already_registered,+ )+++async def _maybe_attach_observed_render_target(+ ctx: AgentContext,+ result: dict[str, Any],+ *,+ selector: str,+ url: str,+) -> None:+ """S3 sibling: pin the clicked affordance when the click opened a new tab that renders the+ document inline — the proof class the download-dir diff above can never see."""+ if ctx.reached_download_target is not None and _is_click_proven_download_target(ctx.reached_download_target):+ return+ data = result.get("data")+ if not isinstance(data, dict) or not selector:+ return+ popup = ctx.pending_scout_popup+ ctx.pending_scout_popup = None+ if popup is None:+ return+ try:+ await popup.wait_for_load_state("domcontentloaded", timeout=_RENDER_PROBE_TIMEOUT_MS)+ popup_url = str(popup.url)+ content_type = ctx.pending_scout_popup_content_type or ""+ ctx.pending_scout_popup_content_type = None+ if not content_type:+ # The popup's navigation response is often already dispatched before the handler+ # attaches. document.contentType is page-scriptable, but this target only drives+ # guidance now (it compiles nothing and credits no download), so a spoofed value+ # costs a missing download step rather than a false one.+ content_type = str(await popup.evaluate("document.contentType") or "")+ if not content_type.lower().startswith("image/"):+ LOG.debug("copilot_observed_render_declined", reason="not_image_render", url=url, content_type=content_type)+ return+ target = derive_from_observed_render(+ selector=selector, rendered_url=popup_url, affordance_text=_scout_click_text(result)+ )+ if target is None:+ return+ _attach_reached_download_target(ctx, data, target, url=url)+ except Exception:+ LOG.warning("copilot_observed_render_target_attach_failed", exc_info=True)++async def _maybe_attach_observed_download_target(ctx: AgentContext,result: dict[str, Any],@@ -2031,19 +2203,7 @@ async def _maybe_attach_observed_download_target(target = derive_from_observed_download(selector=selector, affordance_text=_scout_click_text(result))if target is None:return- data["reached_download_target"] = target.to_dict()- data["reached_download_guidance"] = _reached_download_guidance_for(target)- ctx.reached_download_target = _with_trajectory_anchor(ctx, target)- if ctx.synthesized_block_offered and not ctx.update_workflow_called:- ctx.synthesized_block_offered = False- ctx.synthesized_block_offered_goal_complete = False- _register_reached_download_scout_interaction(ctx, target, url=url)- LOG.info(- "copilot_reached_download_target_steer",- url=url,- download_kind=target.download_kind,- already_registered=target.already_registered,- )+ _attach_reached_download_target(ctx, data, target, url=url)except Exception:LOG.warning("copilot_observed_download_target_attach_failed", exc_info=True)@@ -2056,8 +2216,10 @@ def _scout_click_text(result: dict[str, Any]) -> str:return text if isinstance(text, str) else ""-def _is_observed_download_target(target: object) -> bool:- return getattr(target, "download_kind", None) == DOWNLOAD_KIND_OBSERVED+def _is_click_proven_download_target(target: ReachedDownloadTarget | None) -> bool:+ # Both kinds carry proof from the scout's own click, so neither may be repointed by a+ # shape prediction nothing has exercised.+ return target is not None and target.download_kind in (DOWNLOAD_KIND_OBSERVED, DOWNLOAD_KIND_OBSERVED_RENDER)async def _maybe_attach_reached_download_target(@@ -2087,9 +2249,9 @@ async def _maybe_attach_reached_download_target(target = _derive_reached_download_from_nav_targets(parsed.get("navigation_targets"))if target is None:return- if _is_observed_download_target(ctx.reached_download_target):- # A download that actually fired outranks a prediction from link shape; without this the- # later writer would repoint the target at an affordance nothing has exercised.+ if _is_click_proven_download_target(ctx.reached_download_target):+ # A download or render that actually happened outranks a prediction from link shape;+ # without this the later writer would repoint the target at an unexercised affordance.LOG.info("copilot_reached_download_target_prediction_yielded_to_observed", url=url)returndata["reached_download_target"] = target.to_dict()diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex 40c60e282..d2c212d40 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -182,6 +182,7 @@ from skyvern.forge.sdk.copilot.output_utils import INTERNAL_VALIDATION_FAILURE_Pfrom skyvern.forge.sdk.copilot.reached_download_target import (REGISTERED_DOWNLOAD_OUTPUT_KEYS,ReachedDownloadTarget,+ can_deliver_registered_download,code_is_download_intent,)from skyvern.forge.sdk.copilot.request_policy import (@@ -5879,7 +5880,12 @@ def _submitted_code_block_changed(block: Mapping[str, Any], prior_yaml: str | Nodef _should_impose_after_update_attempt(ctx: AgentContext, *, repeated_identical_omission: bool = False) -> bool:target = ctx.reached_download_targetreturn (- (isinstance(target, ReachedDownloadTarget) and not target.already_registered and bool(target.selector.strip()))+ (+ isinstance(target, ReachedDownloadTarget)+ and can_deliver_registered_download(target)+ and not target.already_registered+ and bool(target.selector.strip())+ )or synthesized_persistence_reopened_after_failed_run(ctx)or ctx.synthesized_block_reopened_for_credential_scoutor repeated_identical_omissiondiff --git a/skyvern/forge/sdk/db/repositories/scripts.py b/skyvern/forge/sdk/db/repositories/scripts.pyindex 2af8dafe9..1dd4d4cd3 100644--- a/skyvern/forge/sdk/db/repositories/scripts.py+++ b/skyvern/forge/sdk/db/repositories/scripts.py@@ -792,6 +792,25 @@ class ScriptsRepository(BaseRepository):session.add(record)await session.commit()+ @db_operation("update_workflow_script_status")+ async def update_workflow_script_status(+ self,+ *,+ workflow_script_id: str,+ organization_id: str,+ status: ScriptStatus,+ ) -> None:+ async with self.Session() as session:+ await session.execute(+ update(WorkflowScriptModel)+ .where(+ WorkflowScriptModel.workflow_script_id == workflow_script_id,+ WorkflowScriptModel.organization_id == organization_id,+ )+ .values(status=status.value if isinstance(status, ScriptStatus) else status)+ )+ await session.commit()+@db_operation("upsert_workflow_script")async def upsert_workflow_script(self,diff --git a/skyvern/forge/sdk/db/repositories/workflow_runs.py b/skyvern/forge/sdk/db/repositories/workflow_runs.pyindex 22198154f..24c44b05b 100644--- a/skyvern/forge/sdk/db/repositories/workflow_runs.py+++ b/skyvern/forge/sdk/db/repositories/workflow_runs.py@@ -478,6 +478,7 @@ class WorkflowRunsRepository(BaseRepository):status: WorkflowRunStatus,failure_reason: str | None = None,run_with: str | None = None,+ ai_fallback: bool | None = None,failure_category: list[dict[str, Any]] | None = None,) -> WorkflowRun | None:"""Transition a workflow run to ``status`` only if it is not already in a@@ -502,6 +503,8 @@ class WorkflowRunsRepository(BaseRepository):values["failure_reason"] = failure_reasonif run_with is not None:values["run_with"] = run_with+ if ai_fallback is not None:+ values["ai_fallback"] = ai_fallbackif failure_category is not None:values["failure_category"] = failure_categorydiff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.pyindex 04978943c..6c8c1e7bd 100644--- a/skyvern/forge/sdk/routes/agent_protocol.py+++ b/skyvern/forge/sdk/routes/agent_protocol.py@@ -99,7 +99,10 @@ from skyvern.forge.sdk.routes.code_samples import (UPDATE_WORKFLOW_CODE_SAMPLE_TS,)from skyvern.forge.sdk.routes.routers import base_router, legacy_base_router, legacy_v2_router-from skyvern.forge.sdk.routes.trigger_type import workflow_run_trigger_type_from_user_agent+from skyvern.forge.sdk.routes.trigger_type import (+ caps_run_response_values,+ workflow_run_trigger_type_from_user_agent,+)from skyvern.forge.sdk.schemas.ai_suggestions import AISuggestionBase, AISuggestionRequestfrom skyvern.forge.sdk.schemas.organizations import (GetOrganizationAPIKeysResponse,@@ -141,6 +144,7 @@ from skyvern.forge.sdk.workflow.models.workflow import (WorkflowRunStatus,WorkflowRunWithWorkflowResponse,)+from skyvern.forge.sdk.workflow.service import capped_task_v1_response, capped_task_v2from skyvern.schemas.artifacts import EntityType, entity_type_to_paramfrom skyvern.schemas.folders import Folder, FolderCreate, FolderUpdate, UpdateWorkflowFolderRequestfrom skyvern.schemas.runs import (@@ -665,8 +669,13 @@ async def get_run(..., description="The id of the task run or the workflow run.", examples=["tsk_123", "tsk_v2_123", "wr_123"]),current_org: Organization = Depends(org_auth_service.get_current_org),+ x_user_agent: Annotated[str | None, Header(include_in_schema=False)] = None,) -> RunResponse:- run_response = await run_service.get_run_response(run_id, organization_id=current_org.organization_id)+ run_response = await run_service.get_run_response(+ run_id,+ organization_id=current_org.organization_id,+ cap_output_values=caps_run_response_values(x_user_agent),+ )if not run_response:raise HTTPException(status_code=http_status.HTTP_404_NOT_FOUND,@@ -3253,11 +3262,16 @@ async def get_run_timeline(..., description="The id of the workflow run or task_v2 run.", examples=["wr_123", "tsk_v2_123"]),current_org: Organization = Depends(org_auth_service.get_current_org),+ x_user_agent: Annotated[str | None, Header(include_in_schema=False)] = None,) -> list[WorkflowRunTimeline]:analytics.capture("skyvern-oss-run-timeline-get")+ cap_output_values = caps_run_response_values(x_user_agent)- # Check if the run exists- run_response = await run_service.get_run_response(run_id, organization_id=current_org.organization_id)+ # Check if the run exists. Capped even though the response is discarded: building it+ # uncapped walks and URL-refreshes the full output for nothing.+ run_response = await run_service.get_run_response(+ run_id, organization_id=current_org.organization_id, cap_output_values=cap_output_values+ )if not run_response:raise HTTPException(status_code=http_status.HTTP_404_NOT_FOUND,@@ -3266,7 +3280,9 @@ async def get_run_timeline(# Handle workflow runs directlyif run_response.run_type == RunType.workflow_run:- return await _flatten_workflow_run_timeline(current_org.organization_id, run_id)+ return await _flatten_workflow_run_timeline(+ current_org.organization_id, run_id, cap_output_values=cap_output_values+ )# Handle task_v2 runs by getting their associated workflow_run_idif run_response.run_type == RunType.task_v2:@@ -3285,7 +3301,9 @@ async def get_run_timeline(detail=f"Task v2 {run_id} has no associated workflow run",)- return await _flatten_workflow_run_timeline(current_org.organization_id, task_v2.workflow_run_id)+ return await _flatten_workflow_run_timeline(+ current_org.organization_id, task_v2.workflow_run_id, cap_output_values=cap_output_values+ )# Timeline not available for other run typesraise HTTPException(@@ -3536,9 +3554,15 @@ async def run_task_v1(async def get_task_v1(task_id: str,current_org: Organization = Depends(org_auth_service.get_current_org),+ x_user_agent: Annotated[str | None, Header(include_in_schema=False)] = None,) -> TaskResponse:analytics.capture("skyvern-oss-agent-task-get")- return await task_v1_service.get_task_v1_response(task_id=task_id, organization_id=current_org.organization_id)+ task_response = await task_v1_service.get_task_v1_response(+ task_id=task_id, organization_id=current_org.organization_id+ )+ if caps_run_response_values(x_user_agent):+ return capped_task_v1_response(task_response)+ return task_response@legacy_base_router.post(@@ -4692,6 +4716,7 @@ async def get_workflow_run_with_workflow_id(workflow_id: str,workflow_run_id: str,current_org: Organization = Depends(org_auth_service.get_current_org),+ x_user_agent: Annotated[str | None, Header(include_in_schema=False)] = None,) -> dict[str, Any]:analytics.capture("skyvern-oss-agent-workflow-run-get")workflow_run_status_response = await app.WORKFLOW_SERVICE.build_workflow_run_status_response(@@ -4699,6 +4724,7 @@ async def get_workflow_run_with_workflow_id(workflow_run_id=workflow_run_id,organization_id=current_org.organization_id,include_cost=True,+ cap_output_values=caps_run_response_values(x_user_agent),)return_dict = workflow_run_status_response.model_dump(by_alias=True)@@ -4725,6 +4751,7 @@ async def get_workflow_run_with_workflow_id(async def get_workflow_and_run_from_workflow_run_id(workflow_run_id: str,current_org: Organization = Depends(org_auth_service.get_current_org),+ x_user_agent: Annotated[str | None, Header(include_in_schema=False)] = None,) -> WorkflowRunWithWorkflowResponse:analytics.capture("skyvern-oss-agent-workflow-run-get")workflow = await app.WORKFLOW_SERVICE.get_workflow_by_workflow_run_id(@@ -4739,6 +4766,7 @@ async def get_workflow_and_run_from_workflow_run_id(organization_id=current_org.organization_id,include_cost=True,allow_deleted=True,+ cap_output_values=caps_run_response_values(x_user_agent),)workflow_run_status_api_response = workflow_run_status_response.model_dump(by_alias=True)@@ -4774,8 +4802,11 @@ async def get_workflow_run_timeline(page: int = Query(1, ge=1),page_size: int = Query(20, ge=1),current_org: Organization = Depends(org_auth_service.get_current_org),+ x_user_agent: Annotated[str | None, Header(include_in_schema=False)] = None,) -> list[WorkflowRunTimeline]:- return await _flatten_workflow_run_timeline(current_org.organization_id, workflow_run_id)+ return await _flatten_workflow_run_timeline(+ current_org.organization_id, workflow_run_id, cap_output_values=caps_run_response_values(x_user_agent)+ )@legacy_base_router.get(@@ -4794,11 +4825,13 @@ async def get_workflow_run_timeline(async def get_workflow_run(workflow_run_id: str,current_org: Organization = Depends(org_auth_service.get_current_org),+ x_user_agent: Annotated[str | None, Header(include_in_schema=False)] = None,) -> WorkflowRunResponseBase:analytics.capture("skyvern-oss-agent-workflow-run-get")return await app.WORKFLOW_SERVICE.build_workflow_run_status_response_by_workflow_id(workflow_run_id=workflow_run_id,organization_id=current_org.organization_id,+ cap_output_values=caps_run_response_values(x_user_agent),)@@ -5515,16 +5548,22 @@ async def run_task_v2(async def get_task_v2(task_id: str,organization: Organization = Depends(org_auth_service.get_current_org),+ x_user_agent: Annotated[str | None, Header(include_in_schema=False)] = None,) -> dict[str, Any]:task_v2 = await task_v2_service.get_task_v2(task_id, organization.organization_id)if not task_v2:raise HTTPException(status_code=404, detail=f"Task v2 {task_id} not found")+ # RunRouter resolves a tsk_v2_* URL through this endpoint before redirecting, so an+ # uncapped output freezes the tab on exactly the payloads the run-detail reads bound.+ if caps_run_response_values(x_user_agent):+ task_v2 = capped_task_v2(task_v2)return task_v2.model_dump(by_alias=True)async def _flatten_workflow_run_timeline_recursive(timeline: WorkflowRunTimeline,organization_id: str,+ cap_output_values: bool = False,) -> list[WorkflowRunTimeline]:"""Recursively flatten a timeline item and its children, handling TaskV2 blocks.@@ -5541,6 +5580,7 @@ async def _flatten_workflow_run_timeline_recursive(nested_timeline = await _flatten_workflow_run_timeline(organization_id=organization_id,workflow_run_id=timeline.block.block_workflow_run_id,+ cap_output_values=cap_output_values,)result.extend(nested_timeline)else:@@ -5558,6 +5598,7 @@ async def _flatten_workflow_run_timeline_recursive(child_results = await _flatten_workflow_run_timeline_recursive(timeline=child,organization_id=organization_id,+ cap_output_values=cap_output_values,)new_children.extend(child_results)@@ -5575,7 +5616,9 @@ async def _flatten_workflow_run_timeline_recursive(return result-async def _flatten_workflow_run_timeline(organization_id: str, workflow_run_id: str) -> list[WorkflowRunTimeline]:+async def _flatten_workflow_run_timeline(+ organization_id: str, workflow_run_id: str, cap_output_values: bool = False+) -> list[WorkflowRunTimeline]:"""Get the timeline workflow runs including the nested workflow runs in a flattened list"""@@ -5589,6 +5632,7 @@ async def _flatten_workflow_run_timeline(organization_id: str, workflow_run_id:workflow_run_block_timeline = await app.WORKFLOW_SERVICE.get_workflow_run_timeline(workflow_run_id=workflow_run_id,organization_id=organization_id,+ cap_output_values=cap_output_values,)# Recursively flatten the timeline, handling TaskV2 blocks at any nesting level@@ -5600,6 +5644,7 @@ async def _flatten_workflow_run_timeline(organization_id: str, workflow_run_id:flattened = await _flatten_workflow_run_timeline_recursive(timeline=timeline,organization_id=organization_id,+ cap_output_values=cap_output_values,)final_workflow_run_block_timeline.extend(flattened)@@ -5607,6 +5652,7 @@ async def _flatten_workflow_run_timeline(organization_id: str, workflow_run_id:thought_timeline = await task_v2_service.get_thought_timelines(task_v2_id=task_v2_obj.observer_cruise_id,organization_id=organization_id,+ cap_output_values=cap_output_values,)final_workflow_run_block_timeline.extend(thought_timeline)final_workflow_run_block_timeline.sort(key=lambda x: x.created_at, reverse=True)diff --git a/skyvern/forge/sdk/routes/streaming/cdp_input.py b/skyvern/forge/sdk/routes/streaming/cdp_input.pyindex 0795192cc..2f4209d03 100644--- a/skyvern/forge/sdk/routes/streaming/cdp_input.py+++ b/skyvern/forge/sdk/routes/streaming/cdp_input.py@@ -22,7 +22,11 @@ from skyvern.forge.sdk.routes.streaming.registries import (stream_ref_dec,try_stream_ref_inc,)-from skyvern.forge.sdk.routes.streaming.screencast import _resolve_working_page, wait_for_browser_state+from skyvern.forge.sdk.routes.streaming.screencast import (+ _resolve_working_page,+ release_browser_state,+ wait_for_browser_state,+)from skyvern.forge.sdk.schemas.persistent_browser_sessions import is_final_statusfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatusfrom skyvern.webeye.browser_state import BrowserState@@ -371,6 +375,7 @@ async def cdp_input_stream(cdp_session: CDPSession | None = Noneinput_session: ActivePageCdpInputSession | None = None+ browser_state: BrowserState | None = Nonestream_registered = Falsetry:deadline = time.monotonic() + 120@@ -429,6 +434,7 @@ async def cdp_input_stream(except Exception:LOG.warning("CDP input: unexpected error", workflow_run_id=workflow_run_id, exc_info=True)finally:+ await release_browser_state(browser_state, "workflow_run", workflow_run_id)if stream_registered:await stream_ref_dec(workflow_run_id)if input_session is not None:@@ -461,6 +467,7 @@ async def cdp_input_browser_session_stream()input_session: ActivePageCdpInputSession | None = None+ browser_state: BrowserState | None = Nonetry:session = await app.PERSISTENT_SESSIONS_MANAGER.get_session(session_id=browser_session_id,@@ -507,6 +514,7 @@ async def cdp_input_browser_session_stream(except Exception:LOG.warning("CDP input: unexpected error", browser_session_id=browser_session_id, exc_info=True)finally:+ await release_browser_state(browser_state, "browser_session", browser_session_id)if input_session is not None:await input_session.close()await channel.close()diff --git a/skyvern/forge/sdk/routes/streaming/channels/execution.py b/skyvern/forge/sdk/routes/streaming/channels/execution.pyindex 96f96b2f0..cf18515b3 100644--- a/skyvern/forge/sdk/routes/streaming/channels/execution.py+++ b/skyvern/forge/sdk/routes/streaming/channels/execution.py@@ -299,7 +299,7 @@ async def execution_for_message_channel(# Imports kept local to avoid a circular import (this module is imported by message.py,# and the persistent sessions manager pulls in app/cloud bootstrapping).from skyvern.forge import app- from skyvern.forge.sdk.routes.streaming.screencast import wait_for_browser_state+ from skyvern.forge.sdk.routes.streaming.screencast import release_browser_state, wait_for_browser_stateif message_channel.browser_session is None:raise RuntimeError("execution_for_message_channel: no browser session on message channel")@@ -321,11 +321,14 @@ async def execution_for_message_channel(if browser_state is None:raise RuntimeError(f"execution_for_message_channel: browser state timeout for {browser_session_id}")- page = await browser_state.get_working_page()- if page is None:- raise RuntimeError(f"execution_for_message_channel: no working page for {browser_session_id}")+ try:+ page = await browser_state.get_working_page()+ if page is None:+ raise RuntimeError(f"execution_for_message_channel: no working page for {browser_session_id}")- yield LocalExecutionChannel(page=page)+ yield LocalExecutionChannel(page=page)+ finally:+ await release_browser_state(browser_state, "browser_session", browser_session_id)@asynccontextmanagerdiff --git a/skyvern/forge/sdk/routes/trigger_type.py b/skyvern/forge/sdk/routes/trigger_type.pyindex 9eaf1c7e7..1fd480aa4 100644--- a/skyvern/forge/sdk/routes/trigger_type.py+++ b/skyvern/forge/sdk/routes/trigger_type.py@@ -8,3 +8,14 @@ def workflow_run_trigger_type_from_user_agent(x_user_agent: str | None) -> Workfif x_user_agent == SKYVERN_MCP_USER_AGENT:return WorkflowRunTriggerType.mcpreturn WorkflowRunTriggerType.api+++def caps_run_response_values(x_user_agent: str | None) -> bool:+ """Whether a run-detail read should bound its output values (SKY-13015).++ Only the app bounds them: it renders outputs with ``JSON.stringify`` on the main+ thread, so a multi-megabyte value freezes the page. Programmatic callers — SDK,+ webhooks, replay — get the stored value in full. MCP is bounded separately at its+ own, much lower, response ceiling.+ """+ return x_user_agent == SKYVERN_UI_USER_AGENTdiff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 733603573..1634346c5 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -11,7 +11,7 @@ import textwrapimport timeimport uuidfrom collections import deque-from collections.abc import Awaitable, Callable, Sequence+from collections.abc import Awaitable, Callable, Iterable, Sequencefrom dataclasses import dataclass, fieldfrom datetime import UTC, datetime, timedeltafrom hashlib import sha256@@ -220,6 +220,7 @@ from skyvern.services.webhook_delivery import (deliver_webhook_with_retries,describe_delivery_error,)+from skyvern.services.workflow_script_service import BLOCK_TYPES_THAT_SHOULD_BE_CACHEDfrom skyvern.utils.css_selector import build_action_summaries_with_timing # shared with script_servicefrom skyvern.utils.secret_headers import merge_masked_headersfrom skyvern.utils.secret_redaction import redact_console_log_bytes, redact_har_bytes@@ -227,6 +228,7 @@ from skyvern.utils.strings import is_uuidfrom skyvern.utils.url_validators import prepend_scheme_and_validate_urlfrom skyvern.utils.url_validators import validate_url as validate_url_with_blocked_host_checkfrom skyvern.webeye.actions.action_types import ActionType+from skyvern.webeye.actions.actions import Actionfrom skyvern.webeye.browser_state import BrowserStatefrom skyvern.webeye.profile_cookie_merge import cookie_delta, seed_cookie_values, union_cookies_into_profile_dirfrom skyvern.webeye.session_cookies import (@@ -287,6 +289,442 @@ DEBUG_SESSION_PROFILE_INCOMPATIBLE_CODE = "debug_session_profile_incompatible"DEBUG_SESSION_PROFILE_REASON_NO_PROFILE = "pbs_no_profile"DEBUG_SESSION_PROFILE_REASON_DIFFERENT = "pbs_different_profile"+# Per-value cap for run-detail API responses (SKY-13015). One block output — a sheet or+# file read — is echoed verbatim into every run-detail read (app run page, MCP get_run,+# run timeline); observed values reach 78MB, which wedges the browser's JSON view and+# overruns MCP's result limits. OUTPUT_PARAMETER_MAX_VALUE_BYTES stays the storage-side+# net; this is the far lower bound a synchronous JSON response can actually carry.+RUN_RESPONSE_MAX_VALUE_BYTES = 2 * 1024 * 1024++# Each level of sibling-preserving trim re-serializes its whole subtree, so unbounded+# recursion costs O(depth x size): a 2.5MB value nested 400 deep serializes 1.27GB and+# blocks the event loop for ~2s. Real block outputs need one or two levels; past this+# the whole value is marked instead of descending further.+RUN_RESPONSE_MAX_TRIM_DEPTH = 4++LOOP_VALUE_TRUNCATED_PLACEHOLDER = "[truncated]"+++def _response_value_size_bytes(value: Any, log_context: dict[str, Any]) -> int | None:+ """Serialized size as FastAPI would put it on the wire, or None if it can't be measured."""+ try:+ # Mirrors FastAPI's JSONResponse.render. ensure_ascii=False because the default+ # escapes non-ASCII to \uXXXX (double-counting CJK); the compact separators because+ # the defaults add ", " and ": ", ~12% on a wide row-array.+ return len(json.dumps(value, default=str, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))+ except Exception:+ LOG.warning("Failed to measure run response value size; passing through", exc_info=True, **log_context)+ return None+++# Room reserved so the trailing marker still fits inside the cap alongside kept entries.+_TRUNCATION_MARKER_RESERVE_BYTES = 512++TRUNCATION_MARKER_KEY = "_truncated"+++def _truncation_marker(+ size_bytes: int,+ *,+ limit_bytes: int | None = None,+ original_count: int | None = None,+ kept_count: int | None = None,+) -> dict:+ effective_limit = RUN_RESPONSE_MAX_VALUE_BYTES if limit_bytes is None else limit_bytes+ marker = {+ "truncated": True,+ "reason": "exceeded_max_run_response_value_size",+ "original_size_bytes": size_bytes,+ "limit_bytes": effective_limit,+ }+ if original_count is not None:+ marker["original_count"] = original_count+ marker["kept_count"] = kept_count+ return marker+++def _string_wire_size(value: str) -> int:+ """Serialized size of a string including JSON quoting and escapes."""+ return len(json.dumps(value, ensure_ascii=False).encode("utf-8"))+++def capped_task_v2(task_v2: Any) -> Any:+ """Cap the output on an embedded TaskV2, which rides the workflow run response."""+ if task_v2 is None:+ return task_v2+ capped_output = truncate_oversized_response_value(+ task_v2.output, task_v2_id=getattr(task_v2, "observer_cruise_id", None), field="output"+ )+ if capped_output is task_v2.output:+ return task_v2+ return task_v2.model_copy(update={"output": capped_output})+++def capped_task_v1_response(task_response: Any) -> Any:+ """Cap the per-value task-v1 fields returned to the interactive run-detail page."""+ capped_extracted_information = truncate_oversized_response_value(+ task_response.extracted_information,+ task_id=task_response.task_id,+ field="extracted_information",+ )+ capped_failure_reason = truncate_oversized_response_text(task_response.failure_reason)+ if (+ capped_extracted_information is task_response.extracted_information+ and capped_failure_reason is task_response.failure_reason+ ):+ return task_response+ return task_response.model_copy(+ update={+ "extracted_information": capped_extracted_information,+ "failure_reason": capped_failure_reason,+ }+ )+++ACTION_TEXT_FIELDS = ("response", "value", "text", "reasoning", "intention", "file_url")+++def _cap_action_payloads(action: Action, **log_context: Any) -> None:+ """Cap the unbounded fields an action carries into a timeline block, in place."""+ for text_field in ACTION_TEXT_FIELDS:+ if hasattr(action, text_field):+ setattr(action, text_field, truncate_oversized_response_text(getattr(action, text_field)))+ for action_field in ("output", "skyvern_element_data"):+ setattr(+ action,+ action_field,+ truncate_oversized_response_value(getattr(action, action_field), field=action_field, **log_context),+ )+++# Every WorkflowRunBlock field that can hold unbounded model- or user-supplied content.+# Enumerated rather than extended one reviewer comment at a time; test_timeline_block_field+# _coverage fails if a new field on the model is neither capped here nor explicitly exempt.+UNBOUNDED_BLOCK_JSON_FIELDS = (+ "output",+ "navigation_payload",+ "data_schema",+)++# Typed list[str]: the JSON trim would replace an oversized element with a marker dict and+# break the declared type, so these cap element-wise and keep every element a string.+UNBOUNDED_BLOCK_TEXT_LIST_FIELDS = (+ "recipients",+ "attachments",+)++UNBOUNDED_BLOCK_TEXT_FIELDS = (+ "description",+ "failure_reason",+ "navigation_goal",+ "data_extraction_goal",+ "terminate_criterion",+ "complete_criterion",+ "subject",+ "body",+ "prompt",+ "instructions",+ "positive_descriptor",+ "negative_descriptor",+ "executed_branch_expression",+ "url",+ "current_value",+ "final_url",+)+++@overload+def truncate_oversized_response_text(current_value: None, *, limit_bytes: int | None = None) -> None: ...+++@overload+def truncate_oversized_response_text(current_value: str, *, limit_bytes: int | None = None) -> str: ...+++def truncate_oversized_response_text(current_value: str | None, *, limit_bytes: int | None = None) -> str | None:+ """Cap one unbounded text field on a timeline block.++ Prompts, email bodies, rendered branch expressions and ``str(loop_over_value)`` are all+ persisted without a size guard. Stays a string, since every one of these is typed+ ``str | None``, keeping a readable prefix in the same shape as the DecisionBlock cap.+ """+ if current_value is None:+ return current_value+ effective_limit = RUN_RESPONSE_MAX_VALUE_BYTES if limit_bytes is None else limit_bytes+ if _string_wire_size(current_value) <= effective_limit:+ return current_value+ # JSON escaping inflates quotes, backslashes and control characters — up to 6x for a+ # control character — so a raw byte count understates the serialized size by as much as+ # half. Shrink until the encoded form actually fits rather than trusting len().+ keep = min(len(current_value), effective_limit)+ while keep > 0:+ candidate = f"{current_value[:keep]}...[truncated {len(current_value) - keep} chars]"+ if _string_wire_size(candidate) <= effective_limit:+ return candidate+ keep //= 2+ return "...[truncated]"+++def _capped_text_list(values: list[str] | None, **log_context: Any) -> list[str] | None:+ """Cap a ``list[str]`` without inserting a JSON marker object into it."""+ if not values:+ return values+ size_bytes = _response_value_size_bytes(values, log_context)+ if size_bytes is None or size_bytes <= RUN_RESPONSE_MAX_VALUE_BYTES:+ return values++ kept: list[str] = []+ running_size = 2+ for value in values:+ values_after_current = len(values) - len(kept) - 1+ if values_after_current == 0:+ item_separator = 1 if kept else 0+ available_for_item = RUN_RESPONSE_MAX_VALUE_BYTES - running_size - item_separator+ capped_value = truncate_oversized_response_text(value, limit_bytes=available_for_item)+ item_size = _string_wire_size(capped_value)+ if running_size + item_separator + item_size <= RUN_RESPONSE_MAX_VALUE_BYTES:+ kept.append(capped_value)+ break++ remaining_count = len(values) - len(kept)+ marker = f"...[truncated {remaining_count} values]"+ marker_size = _string_wire_size(marker)+ item_separator = 1 if kept else 0+ available_for_item = RUN_RESPONSE_MAX_VALUE_BYTES - running_size - item_separator - marker_size - 1+ if available_for_item <= _string_wire_size("...[truncated]"):+ break+ capped_value = truncate_oversized_response_text(value, limit_bytes=available_for_item)+ item_size = _string_wire_size(capped_value)+ if running_size + item_separator + item_size + 1 + marker_size > RUN_RESPONSE_MAX_VALUE_BYTES:+ break+ kept.append(capped_value)+ running_size += item_separator + item_size++ if len(kept) == len(values):+ return kept++ marker = f"...[truncated {len(values) - len(kept)} values]"+ LOG.warning(+ "Trimming oversized run response string list",+ original_size_bytes=size_bytes,+ kept_count=len(kept),+ original_count=len(values),+ **log_context,+ )+ return [*kept, marker]+++def _capped_loop_values(loop_values: list[Any] | None, **log_context: Any) -> list[Any] | None:+ """Cap ``loop_values`` without changing how many iterations it reports.++ The run-detail page reads the iteration count off ``loop_values.length`` and resolves a+ selected iteration by index, so collapsing the list would render a finished 200-iteration+ loop as 200/1 and strand every selection past the first.+ """+ if not loop_values:+ return loop_values++ capped = truncate_oversized_response_value(loop_values, field="loop_values", **log_context)+ # A same-length list means every iteration survived (some trimmed in place). A shorter+ # one is the partial-plus-marker shape, which would misreport the iteration count here.+ if isinstance(capped, list) and len(capped) == len(loop_values):+ return capped+ # Per-element trimming could not fit either. Repeat a compact placeholder so the count+ # and index lookups still line up; repeating the full marker would re-exceed the cap on+ # a long list. The sizes are on the warning the call above already emitted.+ placeholders = [LOOP_VALUE_TRUNCATED_PLACEHOLDER] * len(loop_values)+ placeholder_size = _response_value_size_bytes(placeholders, log_context)+ if placeholder_size is not None and placeholder_size <= RUN_RESPONSE_MAX_VALUE_BYTES:+ return placeholders+ # Even one placeholder per iteration overruns the cap (~150k entries). The count has to+ # move into bounded metadata rather than stay encoded as list length.+ size_bytes = _response_value_size_bytes(loop_values, log_context) or 0+ return [_truncation_marker(size_bytes, original_count=len(loop_values), kept_count=0)]+++def truncate_oversized_response_value(+ value: Any,+ _remaining_trim_depth: int | None = None,+ _loop_payload_budget_granted: bool = False,+ _limit_bytes: int | None = None,+ **log_context: Any,+) -> Any:+ """Fail-open cap for one value echoed into a run-detail API response (SKY-13015).++ A dict or list keeps every element that fits; only oversized ones are replaced, so+ structure the UI reads survives alongside the one huge field — a block's+ ``downloaded_file_urls``, a trigger block's ``workflow_run_id``, and the per-iteration+ entries of a for-loop's ``list[list[dict]]`` output. A replaced element becomes an+ opaque marker rather than a partial value: a truncated list is indistinguishable from+ a complete one to an SDK caller.+ """+ if value is None or isinstance(value, (bool, int, float)):+ return value++ effective_limit = RUN_RESPONSE_MAX_VALUE_BYTES if _limit_bytes is None else _limit_bytes+ remaining_trim_depth = RUN_RESPONSE_MAX_TRIM_DEPTH if _remaining_trim_depth is None else _remaining_trim_depth+ size_bytes = _response_value_size_bytes(value, log_context)+ if size_bytes is None or size_bytes <= effective_limit:+ return value++ if isinstance(value, (dict, list)) and remaining_trim_depth > 0:+ is_loop_output_envelope = (+ isinstance(value, dict)+ and "output_value" in value+ and ("output_parameter" in value or "loop_value" in value)+ )+ if is_loop_output_envelope and isinstance(value, dict):+ # The transport wrapper is cheap and the UI needs all of it. Reserve its+ # encoded bytes, then trim only output_value to what remains; otherwise a+ # marginally oversized entry can keep loop metadata and drop the payload.+ trimmed_envelope = {+ key: truncate_oversized_response_value(+ entry,+ _remaining_trim_depth=remaining_trim_depth - 1,+ _loop_payload_budget_granted=_loop_payload_budget_granted,+ _limit_bytes=effective_limit,+ **log_context,+ )+ for key, entry in value.items()+ if key != "output_value"+ }+ envelope_size = _response_value_size_bytes(trimmed_envelope, log_context)+ output_key_size = _response_value_size_bytes("output_value", log_context)+ if envelope_size is not None and output_key_size is not None:+ output_overhead = (1 if trimmed_envelope else 0) + output_key_size + 1+ output_limit = effective_limit - envelope_size - output_overhead+ if output_limit > 0:+ grants_loop_payload_budget = not _loop_payload_budget_granted+ trimmed_output = truncate_oversized_response_value(+ value["output_value"],+ _remaining_trim_depth=(+ RUN_RESPONSE_MAX_TRIM_DEPTH if grants_loop_payload_budget else remaining_trim_depth - 1+ ),+ _loop_payload_budget_granted=True,+ _limit_bytes=output_limit,+ **log_context,+ )+ candidate = {+ key: trimmed_output if key == "output_value" else trimmed_envelope[key] for key in value+ }+ candidate_size = _response_value_size_bytes(candidate, log_context)+ if candidate_size is not None and candidate_size <= effective_limit:+ return candidate++ # Reserve the encoded size of every sibling before trimming one child. Without this,+ # a trimmable child can consume nearly the entire parent budget, after which the+ # parent falls back to one bare marker and drops UI metadata such as screenshot URLs.+ # This mirrors the loop-envelope allocation above, but applies to ordinary dicts+ # and lists too. The direct formula is the child size that would make the original+ # collection fit: cap - original collection size + original child size. Attempt it+ # lazily while accumulating: pre-scanning a many-row list would reintroduce the+ # synchronous breadth work this cap is meant to avoid.+ items: Iterable[tuple[Any, Any]]+ if isinstance(value, dict):+ items = value.items()+ is_dict = True+ else:+ items = enumerate(value)+ is_dict = False++ # Accumulate as we go and stop once the kept elements fill the cap. Entries that+ # fit are kept and a trailing marker records what was dropped, so a table 1% over+ # the limit still renders instead of vanishing. The marker is what keeps this from+ # being a silent truncation — a bare prefix would be indistinguishable from the+ # whole value to an SDK caller.+ # Start at the enclosing braces/brackets and charge each entry its separators —+ # and, for a dict, its quoted key. Summing child values alone under-counts a+ # key-heavy dict by roughly half, which would let a payload through at ~2x the cap.+ running_size = 2+ trimmed_pairs: list[tuple[Any, Any]] = []+ dropped_any = False+ # The loop's list/list/entry wrappers are transport structure, not payload depth.+ # Give output_value one fresh, bounded trim budget so nested extracted data and+ # links survive while the one heavy sub-value is replaced. The grant flag prevents+ # nested or model-produced envelopes from resetting the budget repeatedly.+ for key, entry in items:+ raw_entry_size = _response_value_size_bytes(entry, log_context)+ entry_limit = effective_limit - size_bytes + raw_entry_size if raw_entry_size is not None else 0+ grants_loop_payload_budget = (+ is_loop_output_envelope and key == "output_value" and not _loop_payload_budget_granted+ )+ child_remaining_trim_depth = (+ RUN_RESPONSE_MAX_TRIM_DEPTH if grants_loop_payload_budget else remaining_trim_depth - 1+ )+ if raw_entry_size is not None and 0 < entry_limit < raw_entry_size:+ sibling_reserved_entry = truncate_oversized_response_value(+ entry,+ _remaining_trim_depth=child_remaining_trim_depth,+ _loop_payload_budget_granted=_loop_payload_budget_granted or grants_loop_payload_budget,+ _limit_bytes=entry_limit,+ **log_context,+ )+ sibling_candidate: dict[Any, Any] | list[Any]+ if isinstance(value, dict):+ sibling_candidate = {**value, key: sibling_reserved_entry}+ else:+ sibling_candidate = list(value)+ sibling_candidate[key] = sibling_reserved_entry+ candidate_size = _response_value_size_bytes(sibling_candidate, log_context)+ if candidate_size is not None and candidate_size <= effective_limit:+ return sibling_candidate+ trimmed_entry = truncate_oversized_response_value(+ entry,+ _remaining_trim_depth=child_remaining_trim_depth,+ _loop_payload_budget_granted=_loop_payload_budget_granted or grants_loop_payload_budget,+ _limit_bytes=effective_limit,+ **log_context,+ )+ entry_size = _response_value_size_bytes(trimmed_entry, log_context)+ if entry_size is None:+ dropped_any = True+ break+ # +1 for the comma; for a dict also the serialized key and its colon.+ running_size += entry_size + 1+ if is_dict:+ key_size = _response_value_size_bytes(key, log_context)+ if key_size is None:+ dropped_any = True+ break+ running_size += key_size + 1+ if running_size > effective_limit - _TRUNCATION_MARKER_RESERVE_BYTES:+ dropped_any = True+ break+ trimmed_pairs.append((key, trimmed_entry))+ # `dropped_any`, not the running total: the loop stops a marker's width below the+ # cap, so a size check here would call a partial result complete and drop entries+ # with nothing recording it.+ if not dropped_any:+ if is_dict:+ return dict(trimmed_pairs)+ return [entry for _, entry in trimmed_pairs]+ if trimmed_pairs:+ marker = _truncation_marker(+ size_bytes,+ limit_bytes=effective_limit,+ original_count=len(value),+ kept_count=len(trimmed_pairs),+ )+ LOG.warning(+ "Trimming oversized run response collection",+ original_size_bytes=size_bytes,+ kept_count=len(trimmed_pairs),+ original_count=len(value),+ **log_context,+ )+ if is_dict:+ return {**dict(trimmed_pairs), TRUNCATION_MARKER_KEY: marker}+ return [*(entry for _, entry in trimmed_pairs), marker]+ # Nothing fit at all — fall through to replacing the whole value.++ LOG.warning(+ "Truncating oversized run response value",+ original_size_bytes=size_bytes,+ limit_bytes=effective_limit,+ **log_context,+ )+ return _truncation_marker(size_bytes, limit_bytes=effective_limit)+@dataclass(frozen=True)class DebugSessionProfileDecision:@@ -390,17 +828,6 @@ def _select_recording_urls_in_window(CacheInvalidationReason = Literal["updated_block", "new_block", "removed_block"]-BLOCK_TYPES_THAT_SHOULD_BE_CACHED = {- BlockType.TASK,- BlockType.TaskV2,- BlockType.ACTION,- BlockType.NAVIGATION,- BlockType.EXTRACTION,- BlockType.LOGIN,- BlockType.FILE_DOWNLOAD,- BlockType.FOR_LOOP,- BlockType.WHILE_LOOP,-}def _collect_uncached_loop_children(@@ -4573,6 +5000,14 @@ class WorkflowService:if context.is_static_script:return+ # Per-block mints exist to cache block functions incrementally. A workflow+ # with no cacheable block types has nothing block-level to cache — its+ # script is fully derivable at end of run, so mint once there (SKY-13659).+ if not any(+ block.block_type in BLOCK_TYPES_THAT_SHOULD_BE_CACHED for block in workflow.workflow_definition.blocks+ ):+ return+disable_script_generation = await app.EXPERIMENTATION_PROVIDER.is_feature_enabled_cached("DISABLE_GENERATE_SCRIPT_AFTER_BLOCK",workflow_run.workflow_run_id,@@ -7713,15 +8148,31 @@ class WorkflowService:ai_fallback: bool | None = None,failure_category: list[dict] | None = None,) -> WorkflowRun:- workflow_run = await app.DATABASE.workflow_runs.update_workflow_run(- workflow_run_id=workflow_run_id,- status=status,- failure_reason=failure_reason,- run_with=run_with,- ai_fallback=ai_fallback,- failure_category=failure_category,- )- await self._after_workflow_run_status_write(workflow_run, status)+ # Final transitions are claimed conditionally so run-minutes emit exactly once+ # per run even when a cancel and the run's own finalizer race; the loser still+ # performs the unconditional overwrite the finalizer has always done, silently.+ flipped_to_final = False+ workflow_run: WorkflowRun | None = None+ if status.is_final():+ workflow_run = await app.DATABASE.workflow_runs.update_workflow_run_if_not_final(+ workflow_run_id=workflow_run_id,+ status=status,+ failure_reason=failure_reason,+ run_with=run_with,+ ai_fallback=ai_fallback,+ failure_category=failure_category,+ )+ flipped_to_final = workflow_run is not None+ if workflow_run is None:+ workflow_run = await app.DATABASE.workflow_runs.update_workflow_run(+ workflow_run_id=workflow_run_id,+ status=status,+ failure_reason=failure_reason,+ run_with=run_with,+ ai_fallback=ai_fallback,+ failure_category=failure_category,+ )+ await self._after_workflow_run_status_write(workflow_run, status, emit_run_minutes=flipped_to_final)return workflow_runasync def _update_workflow_run_status_if_not_final(@@ -7766,7 +8217,9 @@ class WorkflowService:await self._after_workflow_run_status_write(workflow_run, WorkflowRunStatus.timed_out)return workflow_run- async def _after_workflow_run_status_write(self, workflow_run: WorkflowRun, status: WorkflowRunStatus) -> None:+ async def _after_workflow_run_status_write(+ self, workflow_run: WorkflowRun, status: WorkflowRunStatus, emit_run_minutes: bool = True+ ) -> None:workflow_run_id = workflow_run.workflow_run_idif status.is_final():# Free extraction-cache entries for this run.@@ -7791,6 +8244,14 @@ class WorkflowService:trigger_type=workflow_run.trigger_type,workflow_schedule_id=workflow_run.workflow_schedule_id,)+ if emit_run_minutes and workflow_run.parent_workflow_run_id is None:+ await app.AGENT_FUNCTION.record_run_duration(+ run_type="workflow_run",+ status=str(status),+ duration_seconds=duration_seconds,+ workflow_run_id=workflow_run_id,+ organization_id=workflow_run.organization_id,+ )await self._apply_completion_run_tags_best_effort(workflow_run)self._schedule_workflow_run_terminal_hooks(workflow_run_id=workflow_run_id,@@ -8268,6 +8729,14 @@ class WorkflowService:trigger_type=updated.trigger_type,workflow_schedule_id=updated.workflow_schedule_id,)+ if updated.parent_workflow_run_id is None:+ await app.AGENT_FUNCTION.record_run_duration(+ run_type="workflow_run",+ status=str(WorkflowRunStatus.canceled),+ duration_seconds=duration_seconds,+ workflow_run_id=workflow_run_id,+ organization_id=updated.organization_id,+ )await self._apply_completion_run_tags_best_effort(updated)self._schedule_workflow_run_terminal_hooks(@@ -8650,6 +9119,7 @@ class WorkflowService:organization_id: str | None = None,include_cost: bool = False,include_step_count: bool = False,+ cap_output_values: bool = False,) -> WorkflowRunResponseBase:workflow_run = await self.get_workflow_run(workflow_run_id=workflow_run_id, organization_id=organization_id)if workflow_run is None:@@ -8662,6 +9132,7 @@ class WorkflowService:organization_id=organization_id,include_cost=include_cost,include_step_count=include_step_count,+ cap_output_values=cap_output_values,)async def _fetch_recording_urls(@@ -8788,7 +9259,12 @@ class WorkflowService:include_cost: bool = False,include_step_count: bool = False,allow_deleted: bool = False,+ cap_output_values: bool = False,) -> WorkflowRunResponseBase:+ # ``cap_output_values`` defaults off so webhook delivery and replay keep full+ # fidelity; only the interactive read surfaces that must fit in one JSON+ # response opt in. See RUN_RESPONSE_MAX_VALUE_BYTES.+ ## ``allow_deleted=True`` is used by the cleanup/webhook path after a# long-running run completes: the workflow row may have been# soft-deleted (e.g. eval harness teardown fired while the orphan@@ -8857,16 +9333,36 @@ class WorkflowService:outputs = NoneEXTRACTED_INFORMATION_KEY = "extracted_information"if output_parameter_tuples:- outputs = {output_parameter.key: output.value for output_parameter, output in output_parameter_tuples}++ def _cap(value: Any, output_key: str) -> Any:+ if not cap_output_values:+ return value+ return truncate_oversized_response_value(value, workflow_run_id=workflow_run_id, output_key=output_key)++ # Collect from the raw values, not the capped ones: a loop output whose entries+ # are individually small but collectively over the cap still has every+ # iteration's extracted_information, and only the collected list gets capped.extracted_information: list[Any] = []for _, output in output_parameter_tuples:if output.value is not None:extracted_information.extend(WorkflowService._collect_extracted_information(output.value))- outputs[EXTRACTED_INFORMATION_KEY] = extracted_information++ outputs = {+ output_parameter.key: _cap(output.value, output_parameter.key)+ for output_parameter, output in output_parameter_tuples+ }+ outputs[EXTRACTED_INFORMATION_KEY] = _cap(extracted_information, EXTRACTED_INFORMATION_KEY)# Refresh any expired presigned screenshot URLs in the outputsoutputs = await self._refresh_output_urls(outputs, organization_id=organization_id, workflow_run_id=workflow_run_id)+ # The refresh expands artifact IDs into presigned URLs and FileInfo objects —+ # ~25x on an ID-dense value — so a value that fit before it can exceed the cap+ # after. Gating this on artifact IDs is not safe: the legacy `has_old_format`+ # branch rewrites task/workflow screenshots from a `task_id` alone, with no IDs+ # to detect. The pre-refresh pass above still stands: it bounds the refresh walk.+ if cap_output_values:+ outputs = {key: _cap(value, key) for key, value in outputs.items()}errors: list[dict[str, Any]] = []for task in workflow_run_tasks:@@ -8907,7 +9403,11 @@ class WorkflowService:workflow_id=workflow.workflow_permanent_id,workflow_run_id=workflow_run_id,status=workflow_run.status,- failure_reason=workflow_run.failure_reason,+ failure_reason=(+ truncate_oversized_response_text(workflow_run.failure_reason)+ if cap_output_values+ else workflow_run.failure_reason+ ),failure_category=workflow_run.failure_category,retried_from_workflow_run_id=workflow_run.retried_from_workflow_run_id,retried_by_workflow_run_id=retried_by_workflow_run_id,@@ -8940,7 +9440,7 @@ class WorkflowService:browser_profile_id=workflow_run.browser_profile_id,browser_seed_source=workflow_run.browser_seed_source,max_screenshot_scrolls=workflow_run.max_screenshot_scrolls,- task_v2=task_v2,+ task_v2=capped_task_v2(task_v2) if cap_output_values else task_v2,browser_address=workflow_run.browser_address,run_with=workflow_run.run_with,script_run=workflow_run.script_run,@@ -10350,6 +10850,7 @@ class WorkflowService:self,workflow_run_id: str,organization_id: str | None = None,+ cap_output_values: bool = False,) -> list[WorkflowRunTimeline]:"""build the tree structure of the workflow run timeline@@ -10358,6 +10859,38 @@ class WorkflowService:workflow_run_id=workflow_run_id,organization_id=organization_id,)+ if cap_output_values:+ for block in workflow_run_blocks:+ # The jsonb write guard covers only `output`, so every other unbounded jsonb+ # field on the block reaches this response uncapped.+ for block_field in UNBOUNDED_BLOCK_JSON_FIELDS:+ setattr(+ block,+ block_field,+ truncate_oversized_response_value(+ getattr(block, block_field),+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=block.workflow_run_block_id,+ field=block_field,+ ),+ )+ for text_field in UNBOUNDED_BLOCK_TEXT_FIELDS:+ setattr(block, text_field, truncate_oversized_response_text(getattr(block, text_field)))+ for list_field in UNBOUNDED_BLOCK_TEXT_LIST_FIELDS:+ setattr(+ block,+ list_field,+ _capped_text_list(+ getattr(block, list_field),+ workflow_run_id=workflow_run_id,+ field=list_field,+ ),+ )+ block.loop_values = _capped_loop_values(+ block.loop_values,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=block.workflow_run_block_id,+ )# get all the actions for all workflow run blockstask_ids = [block.task_id for block in workflow_run_blocks if block.task_id]task_id_to_block: dict[str, WorkflowRunBlock] = {@@ -10367,6 +10900,10 @@ class WorkflowService:for action in actions:if not action.task_id:continue+ # Actions ride the block they hydrate, and a completion/extraction action can+ # carry a multi-megabyte response or output of its own.+ if cap_output_values:+ _cap_action_payloads(action, workflow_run_id=workflow_run_id)task_block = task_id_to_block[action.task_id]task_block.actions.append(action)@@ -10721,17 +11258,64 @@ class WorkflowService:blocks_to_update_count=len(blocks_to_update),)- created_script = await app.DATABASE.scripts.create_script(+ # The published lookup above cannot see the pending script this run's+ # per-block mints created. Reuse it (regenerate + promote) instead of+ # minting a duplicate script with identical content (SKY-13659). The+ # regeneration also closes the race with the fire-and-forget last+ # per-block mint, which may still be in flight.+ pending_script = None+ pending_workflow_script = await app.DATABASE.scripts.get_workflow_script(organization_id=workflow.organization_id,- run_id=workflow_run.workflow_run_id,+ workflow_permanent_id=workflow.workflow_permanent_id,+ workflow_run_id=workflow_run.workflow_run_id,+ statuses=[ScriptStatus.pending],)+ if pending_workflow_script:+ pending_script = await app.DATABASE.scripts.get_script(+ script_id=pending_workflow_script.script_id,+ organization_id=workflow.organization_id,+ )++ if pending_script:+ # Mint a NEW revision under the pending script_id rather than writing+ # into the pending revision itself: script_files is unique on+ # (script_revision_id, file_path) and create_script_file conflict-noops,+ # so regenerating in place would keep the stale pending main.py — which+ # the still-in-flight per-block mint can overwrite. A fresh revision+ # persists the final source and wins the cache lookup (latest version).+ version_stats = await app.DATABASE.scripts.get_script_version_stats(+ organization_id=workflow.organization_id,+ script_ids=[pending_script.script_id],+ )+ latest_version, _ = version_stats.get(pending_script.script_id, (pending_script.version, 0))+ created_script = await app.DATABASE.scripts.create_script(+ organization_id=workflow.organization_id,+ run_id=workflow_run.workflow_run_id,+ script_id=pending_script.script_id,+ version=latest_version + 1,+ )+ LOG.info(+ "Reusing run's pending script id for final mint instead of creating a new script",+ workflow_permanent_id=workflow.workflow_permanent_id,+ workflow_run_id=workflow_run.workflow_run_id,+ script_id=created_script.script_id,+ pending_revision_id=pending_script.script_revision_id,+ new_revision_id=created_script.script_revision_id,+ new_version=created_script.version,+ cache_key_value=rendered_cache_key_value,+ )+ else:+ created_script = await app.DATABASE.scripts.create_script(+ organization_id=workflow.organization_id,+ run_id=workflow_run.workflow_run_id,+ )await workflow_script_service.generate_workflow_script(workflow_run=workflow_run,workflow=workflow,script=created_script,rendered_cache_key_value=rendered_cache_key_value,- cached_script=None,+ cached_script=pending_script,updated_block_labels=None,)diff --git a/skyvern/services/run_service.py b/skyvern/services/run_service.pyindex 6fab9c836..ac3f1cbc0 100644--- a/skyvern/services/run_service.py+++ b/skyvern/services/run_service.py@@ -8,6 +8,10 @@ from skyvern.exceptions import OrganizationNotFound, TaskNotFound, WorkflowRunNofrom skyvern.forge import appfrom skyvern.forge.sdk.schemas.tasks import TaskStatusfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus+from skyvern.forge.sdk.workflow.service import (+ truncate_oversized_response_text,+ truncate_oversized_response_value,+)from skyvern.schemas.runs import (BulkCancelRunsResponse,RunEngine,@@ -22,7 +26,9 @@ from skyvern.services import task_v1_service, task_v2_service, webhook_service,LOG = structlog.get_logger()-async def get_run_response(run_id: str, organization_id: str | None = None) -> RunResponse | None:+async def get_run_response(+ run_id: str, organization_id: str | None = None, cap_output_values: bool = False+) -> RunResponse | None:run = await app.DATABASE.tasks.get_run(run_id, organization_id=organization_id)if not run:# try to see if it's a workflow run id for task v2@@ -61,8 +67,16 @@ async def get_run_response(run_id: str, organization_id: str | None = None) -> Rrun_id=run.run_id,run_type=run.task_run_type,status=str(task_v1_response.status),- output=task_v1_response.extracted_information,- failure_reason=task_v1_response.failure_reason,+ output=(+ truncate_oversized_response_value(task_v1_response.extracted_information, run_id=run.run_id)+ if cap_output_values+ else task_v1_response.extracted_information+ ),+ failure_reason=(+ truncate_oversized_response_text(task_v1_response.failure_reason)+ if cap_output_values+ else task_v1_response.failure_reason+ ),queued_at=task_v1_response.queued_at,started_at=task_v1_response.started_at,finished_at=task_v1_response.finished_at,@@ -93,9 +107,11 @@ async def get_run_response(run_id: str, organization_id: str | None = None) -> Rtask_v2 = await app.DATABASE.observer.get_task_v2(run.run_id, organization_id=organization_id)if not task_v2:return None- return await task_v2_service.build_task_v2_run_response(task_v2)+ return await task_v2_service.build_task_v2_run_response(task_v2, cap_output_values=cap_output_values)elif run.task_run_type == RunType.workflow_run:- return await workflow_service.get_workflow_run_response(run.run_id, organization_id=organization_id)+ return await workflow_service.get_workflow_run_response(+ run.run_id, organization_id=organization_id, cap_output_values=cap_output_values+ )raise ValueError(f"Invalid task run type: {run.task_run_type}")diff --git a/skyvern/services/task_v2_service.py b/skyvern/services/task_v2_service.pyindex bc0e51ef0..527e1b3f3 100644--- a/skyvern/services/task_v2_service.py+++ b/skyvern/services/task_v2_service.py@@ -2135,7 +2135,14 @@ async def _generate_goto_url_task()-async def get_thought_timelines(*, task_v2_id: str, organization_id: str) -> list[WorkflowRunTimeline]:+async def get_thought_timelines(+ *, task_v2_id: str, organization_id: str, cap_output_values: bool = False+) -> list[WorkflowRunTimeline]:+ from skyvern.forge.sdk.workflow.service import ( # noqa: PLC0415+ truncate_oversized_response_text,+ truncate_oversized_response_value,+ )+thoughts = await app.DATABASE.observer.get_thoughts(task_v2_id=task_v2_id,organization_id=organization_id,@@ -2144,6 +2151,23 @@ async def get_thought_timelines(*, task_v2_id: str, organization_id: str) -> lisThoughtType.user_goal_check,],)+ if cap_output_values:+ # A thought's generated text and structured output ride this response beside+ # block outputs and are rendered directly by the run-detail UI.+ thoughts = [+ thought.model_copy(+ update={+ "output": truncate_oversized_response_value(+ thought.output, thought_id=thought.observer_thought_id, field="output"+ ),+ **{+ field: truncate_oversized_response_text(getattr(thought, field))+ for field in ("user_input", "observation", "thought", "answer")+ },+ }+ )+ for thought in thoughts+ ]return [WorkflowRunTimeline(type=WorkflowRunTimelineType.thought,@@ -2627,15 +2651,18 @@ async def _summarize_task_v2()-async def build_task_v2_run_response(task_v2: TaskV2) -> TaskRunResponse:+async def build_task_v2_run_response(task_v2: TaskV2, cap_output_values: bool = False) -> TaskRunResponse:"""Build TaskRunResponse object for webhook backward compatibility."""+ from skyvern.forge.sdk.workflow.service import truncate_oversized_response_value # noqa: PLC0415from skyvern.services import workflow_service # noqa: PLC0415workflow_run_resp = Noneif task_v2.workflow_run_id:try:workflow_run_resp = await workflow_service.get_workflow_run_response(- task_v2.workflow_run_id, organization_id=task_v2.organization_id+ task_v2.workflow_run_id,+ organization_id=task_v2.organization_id,+ cap_output_values=cap_output_values,)except Exception:LOG.warning(@@ -2652,7 +2679,11 @@ async def build_task_v2_run_response(task_v2: TaskV2) -> TaskRunResponse:run_id=task_v2.observer_cruise_id,run_type=RunType.task_v2,status=task_v2.status,- output=task_v2.output,+ output=(+ truncate_oversized_response_value(task_v2.output, task_v2_id=task_v2.observer_cruise_id)+ if cap_output_values+ else task_v2.output+ ),failure_reason=workflow_run_resp.failure_reason if workflow_run_resp else None,queued_at=task_v2.queued_at,started_at=task_v2.started_at,diff --git a/skyvern/services/workflow_script_service.py b/skyvern/services/workflow_script_service.pyindex 0f6ee23d1..e8a648fac 100644--- a/skyvern/services/workflow_script_service.py+++ b/skyvern/services/workflow_script_service.py@@ -41,6 +41,33 @@ LOG = structlog.get_logger()jinja_sandbox_env = SandboxedEnvironment()strict_jinja_sandbox_env = SandboxedEnvironment(undefined=StrictUndefined)+# Block types that produce cached ScriptBlock functions. Other block types+# (goto/code/etc.) are deterministic already and get inlined into main.py+# without ScriptBlock rows — treating them as "missing" forces regeneration+# on every mint.+BLOCK_TYPES_THAT_SHOULD_BE_CACHED = {+ BlockType.TASK,+ BlockType.TaskV2,+ BlockType.ACTION,+ BlockType.NAVIGATION,+ BlockType.EXTRACTION,+ BlockType.LOGIN,+ BlockType.FILE_DOWNLOAD,+ BlockType.FOR_LOOP,+ BlockType.WHILE_LOOP,+}+++def cacheable_missing_labels(workflow_blocks: list[dict[str, Any]], cached_labels: set[str]) -> set[str]:+ return {+ block["label"]+ for block in workflow_blocks+ if block.get("label")+ and block.get("block_type") in BLOCK_TYPES_THAT_SHOULD_BE_CACHED+ and block["label"] not in cached_labels+ }++# Shared regex for parsing @skyvern.cached decorator lines in main.py source._CACHED_DECORATOR_RE = re.compile(r"^@skyvern\.cached\(\s*cache_key\s*=\s*['\"]([^'\"]+)['\"]\s*\)",@@ -493,10 +520,34 @@ async def generate_or_update_pending_workflow_script(context = skyvern_context.current()if not context:return+script_id = context.script_id+ script_revision_id = context.script_revision_idscript = None- if script_id:- script = await app.DATABASE.scripts.get_script(script_id=script_id, organization_id=organization_id)+ if script_id and script_revision_id:+ # A pending mint can outlive finalize. Bind it to the revision captured+ # when the mint began; resolving the latest script version here can+ # overwrite finalize's newly published main.py.+ script = await app.DATABASE.scripts.get_script_revision(+ script_revision_id=script_revision_id,+ organization_id=organization_id,+ )+ if not script or script.script_id != script_id:+ LOG.warning(+ "Skipping pending script mint with unavailable revision lease",+ workflow_run_id=workflow_run.workflow_run_id,+ script_id=script_id,+ script_revision_id=script_revision_id,+ )+ return+ elif script_id or script_revision_id:+ LOG.warning(+ "Skipping pending script mint with incomplete revision lease",+ workflow_run_id=workflow_run.workflow_run_id,+ script_id=script_id,+ script_revision_id=script_revision_id,+ )+ returnif not script:script = await app.DATABASE.scripts.create_script(@@ -834,6 +885,65 @@ async def _load_cached_script_block_sources(return cached_blocks+async def _record_workflow_script_mapping(+ *,+ workflow: Workflow,+ workflow_run: WorkflowRun,+ script: Script,+ rendered_cache_key_value: str,+ pending: bool,+) -> None:+ existing_workflow_script = await app.DATABASE.scripts.get_workflow_script(+ organization_id=workflow.organization_id,+ workflow_permanent_id=workflow.workflow_permanent_id,+ workflow_run_id=workflow_run.workflow_run_id,+ statuses=[ScriptStatus.pending, ScriptStatus.published],+ )++ if pending:+ if existing_workflow_script:+ return+ await app.DATABASE.scripts.create_workflow_script(+ organization_id=workflow.organization_id,+ script_id=script.script_id,+ workflow_permanent_id=workflow.workflow_permanent_id,+ cache_key=workflow.cache_key or "",+ cache_key_value=rendered_cache_key_value,+ workflow_id=workflow.workflow_id,+ workflow_run_id=workflow_run.workflow_run_id,+ status=ScriptStatus.pending,+ )+ return++ if existing_workflow_script and existing_workflow_script.script_id == script.script_id:+ # Promote the run's own pending mapping instead of minting a duplicate+ # published row for the same content (SKY-13659).+ await app.DATABASE.scripts.update_workflow_script_status(+ workflow_script_id=existing_workflow_script.workflow_script_id,+ organization_id=workflow.organization_id,+ status=ScriptStatus.published,+ )+ LOG.info(+ "Promoted pending workflow script to published",+ workflow_run_id=workflow_run.workflow_run_id,+ workflow_permanent_id=workflow.workflow_permanent_id,+ script_id=script.script_id,+ cache_key_value=rendered_cache_key_value,+ )+ return++ await app.DATABASE.scripts.create_workflow_script(+ organization_id=workflow.organization_id,+ script_id=script.script_id,+ workflow_permanent_id=workflow.workflow_permanent_id,+ cache_key=workflow.cache_key or "",+ cache_key_value=rendered_cache_key_value,+ workflow_id=workflow.workflow_id,+ workflow_run_id=workflow_run.workflow_run_id,+ status=ScriptStatus.published,+ )++async def generate_workflow_script(workflow_run: WorkflowRun,workflow: Workflow,@@ -873,7 +983,7 @@ async def generate_workflow_script(else:updated_block_labels = set(updated_block_labels)- missing_labels = {label for label in block_labels if label and label not in cached_block_sources}+ missing_labels = cacheable_missing_labels(codegen_input.workflow_blocks, set(cached_block_sources))updated_block_labels.update(missing_labels)updated_block_labels.add(settings.WORKFLOW_START_BLOCK_LABEL)@@ -1012,29 +1122,13 @@ async def generate_workflow_script(allow_invalid_python_syntax=True,)- # check if an existing draft workflow script exists for this workflow run- existing_pending_workflow_script = None- status = ScriptStatus.published- if pending:- status = ScriptStatus.pending- existing_pending_workflow_script = await app.DATABASE.scripts.get_workflow_script(- organization_id=workflow.organization_id,- workflow_permanent_id=workflow.workflow_permanent_id,- workflow_run_id=workflow_run.workflow_run_id,- statuses=[status],- )- if not existing_pending_workflow_script:- # Record the workflow->script mapping for cache lookup- await app.DATABASE.scripts.create_workflow_script(- organization_id=workflow.organization_id,- script_id=script.script_id,- workflow_permanent_id=workflow.workflow_permanent_id,- cache_key=workflow.cache_key or "",- cache_key_value=rendered_cache_key_value,- workflow_id=workflow.workflow_id,- workflow_run_id=workflow_run.workflow_run_id,- status=status,- )+ await _record_workflow_script_mapping(+ workflow=workflow,+ workflow_run=workflow_run,+ script=script,+ rendered_cache_key_value=rendered_cache_key_value,+ pending=pending,+ )# 5) Mint-time static audit — only on published mints, not pending# intermediate revisions. The pending path fires per-block during adiff --git a/skyvern/services/workflow_service.py b/skyvern/services/workflow_service.pyindex 25fad8193..6b96f1ed6 100644--- a/skyvern/services/workflow_service.py+++ b/skyvern/services/workflow_service.py@@ -201,7 +201,7 @@ async def run_workflow(async def get_workflow_run_response(- workflow_run_id: str, organization_id: str | None = None+ workflow_run_id: str, organization_id: str | None = None, cap_output_values: bool = False) -> WorkflowRunResponse | None:workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(workflow_run_id, organization_id=organization_id)if not workflow_run:@@ -210,6 +210,7 @@ async def get_workflow_run_response(workflow_run_id=workflow_run.workflow_run_id,organization_id=organization_id,include_step_count=True,+ cap_output_values=cap_output_values,)app_url = f"{settings.SKYVERN_APP_URL.rstrip('/')}/runs/{workflow_run.workflow_run_id}"# A fresh run reads/writes no saved memory; its run_request echoes start_fresh_browser and drops thediff --git a/tests/unit/forge/sdk/routes/streaming/test_cdp_input_teardown_gate.py b/tests/unit/forge/sdk/routes/streaming/test_cdp_input_teardown_gate.pyindex 818c30f98..4cebdde16 100644--- a/tests/unit/forge/sdk/routes/streaming/test_cdp_input_teardown_gate.py+++ b/tests/unit/forge/sdk/routes/streaming/test_cdp_input_teardown_gate.py@@ -1,7 +1,9 @@+import asynciofrom types import SimpleNamespacefrom unittest.mock import AsyncMockimport pytest+from fastapi import WebSocketDisconnectfrom skyvern.forge.sdk.routes.streaming import cdp_input, registriesfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus@@ -32,3 +34,91 @@ async def test_public_workflow_stream_rejects_attach_after_closing_tombstone(websocket.close.assert_awaited_once_with(code=4409, reason="workflow_run_closing")websocket.send_json.assert_not_awaited()wait_for_browser_state.assert_not_awaited()+++async def test_browser_session_route_releases_adopted_browser_state_on_teardown(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """wait_for_browser_state hands browser_session-scoped ownership to its caller (see the+ docstring on screencast.py's wait_for_browser_state); the caller must give it back via+ release_browser_state on every exit path or the adopted Playwright driver + CDP websocket is+ never closed and leaks for the life of the process."""+ browser_session_id = "pbs_leak_check"+ browser_state = SimpleNamespace(name="adopted_browser_state")+ session = SimpleNamespace(status="running")++ class _FakeCdpSession:+ async def detach(self) -> None:+ return None++ class _FakeContext:+ async def new_cdp_session(self, page: object) -> "_FakeCdpSession":+ return _FakeCdpSession()++ fake_page = SimpleNamespace(context=_FakeContext(), url="https://example.test/")++ websocket = SimpleNamespace(+ close=AsyncMock(),+ send_json=AsyncMock(),+ receive_text=AsyncMock(side_effect=WebSocketDisconnect()),+ )+ fake_app = SimpleNamespace(+ PERSISTENT_SESSIONS_MANAGER=SimpleNamespace(get_session=AsyncMock(return_value=session)),+ )+ monkeypatch.setattr(cdp_input, "app", fake_app)+ monkeypatch.setattr(cdp_input, "auth", AsyncMock(return_value="org_stream"))+ monkeypatch.setattr(cdp_input, "wait_for_browser_state", AsyncMock(return_value=browser_state))+ monkeypatch.setattr(cdp_input, "_resolve_working_page", AsyncMock(return_value=fake_page))+ release_browser_state = AsyncMock()+ # raising=False: pre-fix, cdp_input does not import release_browser_state at all.+ monkeypatch.setattr(cdp_input, "release_browser_state", release_browser_state, raising=False)++ await cdp_input.cdp_input_browser_session_stream(websocket, browser_session_id, client_id="client_leak_check")++ release_browser_state.assert_awaited_once_with(browser_state, "browser_session", browser_session_id)+++async def test_browser_session_route_releases_before_input_session_close_can_swallow_it(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """ActivePageCdpInputSession.close() catches `except Exception`, which does not catch+ CancelledError. release_browser_state must run before input_session.close() in the finally+ block, matching screenshot.py:416 - otherwise a cancellation during input_session teardown+ skips the release entirely."""+ browser_session_id = "pbs_leak_check_cancel"+ browser_state = SimpleNamespace(name="adopted_browser_state")+ session = SimpleNamespace(status="running")++ class _FakeCdpSession:+ async def detach(self) -> None:+ raise asyncio.CancelledError()++ class _FakeContext:+ async def new_cdp_session(self, page: object) -> "_FakeCdpSession":+ return _FakeCdpSession()++ fake_page = SimpleNamespace(context=_FakeContext(), url="https://example.test/")++ websocket = SimpleNamespace(+ close=AsyncMock(),+ send_json=AsyncMock(),+ receive_text=AsyncMock(side_effect=WebSocketDisconnect()),+ )+ fake_app = SimpleNamespace(+ PERSISTENT_SESSIONS_MANAGER=SimpleNamespace(get_session=AsyncMock(return_value=session)),+ )+ monkeypatch.setattr(cdp_input, "app", fake_app)+ monkeypatch.setattr(cdp_input, "auth", AsyncMock(return_value="org_stream"))+ monkeypatch.setattr(cdp_input, "wait_for_browser_state", AsyncMock(return_value=browser_state))+ monkeypatch.setattr(cdp_input, "_resolve_working_page", AsyncMock(return_value=fake_page))+ release_browser_state = AsyncMock()+ monkeypatch.setattr(cdp_input, "release_browser_state", release_browser_state, raising=False)++ with pytest.raises(asyncio.CancelledError):+ await cdp_input.cdp_input_browser_session_stream(+ websocket, browser_session_id, client_id="client_leak_check_cancel"+ )++ release_browser_state.assert_awaited_once_with(browser_state, "browser_session", browser_session_id)diff --git a/tests/unit/forge/sdk/routes/streaming/test_execution_channel.py b/tests/unit/forge/sdk/routes/streaming/test_execution_channel.pyindex 137d5605c..9a2d6ce23 100644--- a/tests/unit/forge/sdk/routes/streaming/test_execution_channel.py+++ b/tests/unit/forge/sdk/routes/streaming/test_execution_channel.py@@ -3,7 +3,8 @@from __future__ import annotationsimport asyncio-from unittest.mock import MagicMock+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMockimport pytestfrom playwright._impl._errors import TargetClosedError@@ -72,3 +73,76 @@ async def test_local_execution_channel_stop_is_safe() -> None:await channel.stop()assert channel._closing is True+++def _fake_message_channel(browser_session_id: str, client_id: str) -> SimpleNamespace:+ return SimpleNamespace(+ client_id=client_id,+ organization_id="org_exec",+ browser_session=SimpleNamespace(persistent_browser_session_id=browser_session_id),+ )+++async def test_execution_for_message_channel_releases_adopted_browser_state_on_exit(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The local-dev path (no VncChannel registered for the client) adopts a+ browser_session-scoped browser_state via wait_for_browser_state, whose docstring hands+ ownership to the caller. execution_for_message_channel must give it back on every exit or+ the adopted Playwright driver + CDP websocket leaks once per JS-exec/message operation,+ not just once per connection."""+ from skyvern.forge import app as forge_app+ from skyvern.forge.sdk.routes.streaming import screencast+ from skyvern.forge.sdk.routes.streaming.channels import execution as execution_module++ browser_session_id = "pbs_exec_leak_check"+ browser_state = SimpleNamespace(get_working_page=AsyncMock(return_value=MagicMock()))+ message_channel = _fake_message_channel(browser_session_id, "client_exec_leak_check")++ monkeypatch.setattr(execution_module, "get_vnc_channel", lambda client_id: None)+ monkeypatch.setattr(+ forge_app,+ "PERSISTENT_SESSIONS_MANAGER",+ SimpleNamespace(get_session=AsyncMock(return_value=SimpleNamespace(status="running"))),+ )+ monkeypatch.setattr(screencast, "wait_for_browser_state", AsyncMock(return_value=browser_state))+ release_browser_state = AsyncMock()+ monkeypatch.setattr(screencast, "release_browser_state", release_browser_state)++ async with execution_module.execution_for_message_channel(message_channel):+ pass++ release_browser_state.assert_awaited_once_with(browser_state, "browser_session", browser_session_id)+++async def test_execution_for_message_channel_releases_on_no_working_page_error(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Ownership must also be given back when the context manager body never runs at all -+ e.g. the adopted browser has no working page yet, which raises before the caller's+ `async with` block gets control."""+ from skyvern.forge import app as forge_app+ from skyvern.forge.sdk.routes.streaming import screencast+ from skyvern.forge.sdk.routes.streaming.channels import execution as execution_module++ browser_session_id = "pbs_exec_leak_check_exc"+ browser_state = SimpleNamespace(get_working_page=AsyncMock(return_value=None))+ message_channel = _fake_message_channel(browser_session_id, "client_exec_leak_check_exc")++ monkeypatch.setattr(execution_module, "get_vnc_channel", lambda client_id: None)+ monkeypatch.setattr(+ forge_app,+ "PERSISTENT_SESSIONS_MANAGER",+ SimpleNamespace(get_session=AsyncMock(return_value=SimpleNamespace(status="running"))),+ )+ monkeypatch.setattr(screencast, "wait_for_browser_state", AsyncMock(return_value=browser_state))+ release_browser_state = AsyncMock()+ monkeypatch.setattr(screencast, "release_browser_state", release_browser_state)++ with pytest.raises(RuntimeError, match="no working page"):+ async with execution_module.execution_for_message_channel(message_channel):+ pass++ release_browser_state.assert_awaited_once_with(browser_state, "browser_session", browser_session_id)diff --git a/tests/unit/test_cached_script_deploy_service.py b/tests/unit/test_cached_script_deploy_service.pyindex 95cf7963d..d1ec607f9 100644--- a/tests/unit/test_cached_script_deploy_service.py+++ b/tests/unit/test_cached_script_deploy_service.py@@ -282,6 +282,9 @@ def _stub_app(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:previous_workflow_script=state.previous_workflow_script,)+ async def get_workflow_script(self, **kwargs: object) -> None:+ return None+async def create_workflow_script(self, **kwargs: object) -> SimpleNamespace:state.workflow_script_upserts.append(kwargs)return SimpleNamespace(**kwargs)diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.pyindex 8ee5821fd..fa8d1b36d 100644--- a/tests/unit/test_copilot_agent_helpers.py+++ b/tests/unit/test_copilot_agent_helpers.py@@ -2352,7 +2352,6 @@ workflow_definition:assert json.loads(result)["ok"] is Trueassert captured["workflow_yaml"] == clean_yamlassert captured["run_called"] is True- assert ctx.coverage_nudge_count == 0assert "Achieve the following mini goal" not in captured["workflow_yaml"]diff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.pyindex 9bb93906b..3b7dfce85 100644--- a/tests/unit/test_copilot_code_block_synthesis.py+++ b/tests/unit/test_copilot_code_block_synthesis.py@@ -5610,3 +5610,32 @@ def test_a_designated_read_waits_for_a_figure_the_page_has_not_rendered_yet() ->relation_label="Visitors",)assert "wait_for_timeout" not in "\n".join(_key_value_scalar_read_statements(relation, "_value", guard_empty=True))+++class TestObservedRenderSynthesis:+ def test_observed_render_target_emits_no_download_terminal(self) -> None:+ target = _download_target(+ download_kind="observed_render",+ source_step="observed_render",+ selector='a[href="Command?op=getImage&image=07/10/2025"]',+ affordance_text="07/10/2025",+ rendered_url="https://example.com/Command?op=getImage&image=07/10/2025",+ )+ result = synthesize_code_block([_nav_click()], reached_download_target=target)+ assert result is not None+ # A render-type affordance never fires a browser download, so expect_download would hang;+ # byte capture needs execution-layer registration, so no terminal of any kind is compiled.+ assert "expect_download" not in result.code+ assert "screenshot" not in result.code+ assert '"downloaded_files"' not in result.code+ ast.parse("async def _block(page):\n" + result.code)++ def test_observed_render_requires_rendered_url(self) -> None:+ from skyvern.forge.sdk.copilot.reached_download_target import derive_from_observed_render++ assert derive_from_observed_render(selector="a.bill", rendered_url="") is None+ assert derive_from_observed_render(selector="", rendered_url="https://example.com/x") is None+ target = derive_from_observed_render(selector="a.bill", rendered_url="https://example.com/x")+ assert target is not None+ assert target.download_kind == "observed_render"+ assert target.to_dict()["rendered_url"] == "https://example.com/x"diff --git a/tests/unit/test_copilot_context.py b/tests/unit/test_copilot_context.pyindex b35f5d8d4..146be4323 100644--- a/tests/unit/test_copilot_context.py+++ b/tests/unit/test_copilot_context.py@@ -643,7 +643,6 @@ class TestCopilotContext:"update_workflow_called","test_after_update_done","post_update_nudge_count",- "coverage_nudge_count","format_nudge_count","explore_without_workflow_nudge_count","user_message",@@ -671,7 +670,6 @@ class TestCopilotContext:)assert ctx.navigate_called is Falseassert ctx.update_workflow_called is False- assert ctx.coverage_nudge_count == 0assert ctx.format_nudge_count == 0assert ctx.explore_without_workflow_nudge_count == 0assert ctx.user_message == ""diff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.pyindex d265736ac..beb1ac09e 100644--- a/tests/unit/test_copilot_enforcement_pruning.py+++ b/tests/unit/test_copilot_enforcement_pruning.py@@ -117,7 +117,6 @@ class _Ctx:self.persisted_draft_browser_calls = Noneself.test_after_update_done = Falseself.post_update_nudge_count = 0- self.coverage_nudge_count = 0self.format_nudge_count = 0self.user_message = ""self.last_update_block_count = None@@ -1757,7 +1756,6 @@ class TestEnforcement:ctx.update_workflow_called = Falsectx.test_after_update_done = Falsectx.post_update_nudge_count = 0- ctx.coverage_nudge_count = 0ctx.format_nudge_count = 0ctx.explore_without_workflow_nudge_count = 0ctx.last_test_suspicious_success = False@@ -1822,71 +1820,7 @@ class TestEnforcement:assert nudge is not Noneassert nudge.rule == "post_navigate"- def test_intermediate_success_nudge_for_multistep_goal(self) -> None:- ctx = self._make_ctx(- update_workflow_called=True,- test_after_update_done=True,- last_test_ok=True,- last_update_block_count=1,- user_message="Go to france.fr and then download all french regulations",- coverage_nudge_count=0,- )- # Coverage gate only fires when the model tries to emit a REPLY.- nudge = enforcement_decision(ctx, self._reply_result("draft response"))- assert nudge.rule == "post_intermediate_success"- assert ctx.coverage_nudge_count == 1-- def test_no_intermediate_success_nudge_for_single_step_goal(self) -> None:- ctx = self._make_ctx(- update_workflow_called=True,- test_after_update_done=True,- last_test_ok=True,- last_update_block_count=1,- user_message="Go to france.fr",- coverage_nudge_count=0,- )- assert enforcement_decision(ctx, self._reply_result("done")) is None-- def test_intermediate_success_nudge_fires_for_two_blocks(self) -> None:- """Key regression: nudge must fire even when block_count > 1."""-- ctx = self._make_ctx(- update_workflow_called=True,- test_after_update_done=True,- last_test_ok=True,- last_update_block_count=2,- user_message="Go to france.fr and then download all french regulations and extract the titles",- coverage_nudge_count=0,- )- nudge = enforcement_decision(ctx, self._reply_result("two-block draft"))- assert nudge.rule == "post_intermediate_success"-- def test_intermediate_nudge_respects_global_cap(self) -> None:- from skyvern.forge.sdk.copilot.enforcement import MAX_INTERMEDIATE_NUDGES-- ctx = self._make_ctx(- update_workflow_called=True,- test_after_update_done=True,- last_test_ok=True,- last_update_block_count=2,- user_message="Go to france.fr and then download all french regulations",- coverage_nudge_count=MAX_INTERMEDIATE_NUDGES,- )- assert enforcement_decision(ctx, self._reply_result("capped")) is None-- def test_intermediate_nudge_does_not_fire_for_ten_plus_blocks(self) -> None:- ctx = self._make_ctx(- update_workflow_called=True,- test_after_update_done=True,- last_test_ok=True,- last_update_block_count=10,- user_message="Go to france.fr and then download all french regulations",- coverage_nudge_count=0,- )- assert enforcement_decision(ctx, self._reply_result("ten blocks")) is None-- def test_ask_question_always_passes_even_with_coverage_gap(self) -> None:- """Regression guard: ASK_QUESTION must never be blocked by coverage."""+ def test_ask_question_passes_response_enforcement(self) -> None:import jsonctx = self._make_ctx(@@ -1895,21 +1829,19 @@ class TestEnforcement:last_test_ok=True,last_update_block_count=1,user_message="Go to france.fr and then download all french regulations",- coverage_nudge_count=0,)ask = MagicMock()ask.final_output = json.dumps({"type": "ASK_QUESTION", "user_response": "Which source?"})ask.new_items = []assert enforcement_decision(ctx, ask) is None- def test_plain_labeled_ask_question_passes_even_with_coverage_gap(self) -> None:+ def test_plain_labeled_ask_question_passes_response_enforcement(self) -> None:ctx = self._make_ctx(update_workflow_called=True,test_after_update_done=True,last_test_ok=True,last_update_block_count=1,user_message="Go to france.fr and then download all french regulations",- coverage_nudge_count=0,)ask = MagicMock()ask.final_output = "ASK_QUESTION\nWhich source?"@@ -2070,45 +2002,6 @@ class TestEnforcement:assert ctx.post_update_nudge_count == 1-class TestGoalLikelyNeedsMoreBlocks:- @staticmethod- def _check(user_message: str, block_count: int, completion_contract: str | None = None) -> bool:- from skyvern.forge.sdk.copilot.enforcement import _goal_likely_needs_more_blocks-- return _goal_likely_needs_more_blocks(user_message, block_count, completion_contract)-- def test_navigate_and_download_needs_two(self) -> None:- assert self._check("Go to france.fr and then download regulations", 1) is True- assert self._check("Go to france.fr and then download regulations", 2) is False-- def test_login_search_and_extract_needs_three(self) -> None:- assert self._check("Login to the site, search for products, and extract prices", 1) is True- assert self._check("Login to the site, search for products, and extract prices", 2) is True- assert self._check("Login to the site, search for products, and extract prices", 3) is False-- def test_single_action_does_not_need_more(self) -> None:- assert self._check("Go to france.fr", 1) is False-- def test_completion_contract_does_not_force_extra_blocks_after_success(self) -> None:- user_message = "Go to example.com/contact, fill out the form, and submit it."- assert self._check(user_message, 1, "confirmation banner appears") is False-- def test_completion_contract_still_requires_sequential_blocks(self) -> None:- user_message = "Go to example.com and then download the report."- assert self._check(user_message, 1, "download starts") is True- assert self._check(user_message, 2, "download starts") is False-- def test_sequential_connector_needs_at_least_two(self) -> None:- assert self._check("Do X and then do Y", 1) is True-- def test_ten_plus_blocks_always_false(self) -> None:- assert self._check("Go to X and then download Y and extract Z", 10) is False-- def test_non_string_returns_false(self) -> None:- assert self._check(None, 1) is False # type: ignore[arg-type]- assert self._check(123, 1) is False # type: ignore[arg-type]--LISTING_DETAIL_URL = "http://localhost:8901/record/1457803926"# Generic multi-field detail DOM: exercises the contract's label/header binding vs thediff --git a/tests/unit/test_copilot_fill_credential_field.py b/tests/unit/test_copilot_fill_credential_field.pyindex 9d9cb9b95..a307f9011 100644--- a/tests/unit/test_copilot_fill_credential_field.py+++ b/tests/unit/test_copilot_fill_credential_field.py@@ -60,6 +60,9 @@ def _ctx(**overrides: Any) -> SimpleNamespace:observed_browser_urls=[],pending_scout_source_url=None,pending_scout_download_snapshot=None,+ pending_scout_popup=None,+ pending_scout_popup_content_type=None,+ reached_download_target=None,pending_browser_interaction_observation=None,discovery_mcp_server=None,secret_scrub_values=[],diff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.pyindex 4bbbc529d..e506d62c5 100644--- a/tests/unit/test_copilot_hooks.py+++ b/tests/unit/test_copilot_hooks.py@@ -1004,6 +1004,9 @@ class TestBrowserInteractionObservationHooks:pending_scout_reanchor=None,pending_scout_dynamic_row=None,pending_scout_download_snapshot=None,+ pending_scout_popup=None,+ pending_scout_popup_content_type=None,+ reached_download_target=None,discovery_mcp_server=None,scouted_interactions=[],scout_trajectory=[],@@ -1045,6 +1048,9 @@ class TestBrowserInteractionObservationHooks:pending_scout_reanchor=None,pending_scout_dynamic_row=None,pending_scout_download_snapshot=None,+ pending_scout_popup=None,+ pending_scout_popup_content_type=None,+ reached_download_target=None,discovery_mcp_server=None,scouted_interactions=[],scout_trajectory=[],@@ -1104,6 +1110,9 @@ class TestScoutedInteractionCapture:pending_scout_reanchor=None,pending_scout_dynamic_row=None,pending_scout_download_snapshot=None,+ pending_scout_popup=None,+ pending_scout_popup_content_type=None,+ reached_download_target=None,discovery_mcp_server=None,browser_session_id=None,scouted_interactions=[],diff --git a/tests/unit/test_copilot_model_telemetry.py b/tests/unit/test_copilot_model_telemetry.pyindex 070e609c8..27c103d31 100644--- a/tests/unit/test_copilot_model_telemetry.py+++ b/tests/unit/test_copilot_model_telemetry.py@@ -454,7 +454,14 @@ def test_model_call_cost_uses_runtime_litellm_pricing(monkeypatch: pytest.Monkey}-def test_model_call_cost_prices_dated_gpt56_response_with_base_rates() -> None:+def test_model_call_cost_normalizes_dated_gpt56_response_model(monkeypatch: pytest.MonkeyPatch) -> None:+ priced_models: list[str] = []++ def fake_cost_per_token(**kwargs: Any) -> tuple[float, float]:+ priced_models.append(kwargs["model"])+ return 0.25, 0.125++ monkeypatch.setattr(model_telemetry_module.litellm, "cost_per_token", fake_cost_per_token)telemetry = model_telemetry_module.CopilotModelCallTelemetry(model_call_index=1,input_tokens=40_000,@@ -471,6 +478,7 @@ def test_model_call_cost_prices_dated_gpt56_response_with_base_rates() -> None:assert dated_cost is not Noneassert dated_cost == pytest.approx(base_cost)+ assert priced_models == ["gpt-5.6-sol", "gpt-5.6-sol"]def test_completed_model_call_emits_datadog_usage_with_explicit_zeroes(diff --git a/tests/unit/test_copilot_output_policy.py b/tests/unit/test_copilot_output_policy.pyindex 945d2bb73..8ff068752 100644--- a/tests/unit/test_copilot_output_policy.py+++ b/tests/unit/test_copilot_output_policy.py@@ -24,7 +24,7 @@ from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignalfrom skyvern.forge.sdk.copilot.build_phase import BuildPhasefrom skyvern.forge.sdk.copilot.context import CopilotContextfrom skyvern.forge.sdk.copilot.enforcement import (- _response_coverage_nudge,+ _response_output_nudge,)from skyvern.forge.sdk.copilot.loop_detection import tool_step_identityfrom skyvern.forge.sdk.copilot.output_policy import (@@ -2974,7 +2974,7 @@ def test_seam_ordering_avoidable_ask_defers_then_recycle_fires() -> None:assert diagnostics["deferred_reason_codes"] == [OutputPolicyReason.AVOIDABLE_OUTPUT_FIELD_CONFIRMATION.value]assert diagnostics["final_output_policy_allowed"] is True- assert _response_coverage_nudge(ctx, _AVOIDABLE_ASK).rule == "present_completion_contract_ask_retry"+ assert _response_output_nudge(ctx, _AVOIDABLE_ASK).rule == "present_completion_contract_ask_retry"@pytest.mark.asyncio@@ -3016,7 +3016,7 @@ def test_avoidable_deferral_iff_recycle_admits(**marker,)- recycle_decision = _response_coverage_nudge(ctx, _AVOIDABLE_ASK)+ recycle_decision = _response_output_nudge(ctx, _AVOIDABLE_ASK)recycle_admits = recycle_decision is not None and recycle_decision.rule == "present_completion_contract_ask_retry"assert recycle_admits is expected_admitdiff --git a/tests/unit/test_copilot_pre_discovery_url_nudge.py b/tests/unit/test_copilot_pre_discovery_url_nudge.pyindex cc6b2345d..24a4d072b 100644--- a/tests/unit/test_copilot_pre_discovery_url_nudge.py+++ b/tests/unit/test_copilot_pre_discovery_url_nudge.py@@ -25,7 +25,7 @@ from skyvern.forge.sdk.copilot.enforcement import (MAX_PRE_DISCOVERY_URL_QUESTION_NUDGES,PRESENT_COMPLETION_CONTRACT_ASK_RETRY,_pre_discovery_url_question_nudge,- _response_coverage_nudge,+ _response_output_nudge,enforcement_decision,)from skyvern.forge.sdk.copilot.request_policy import CompletionCriterion, RequestPolicy@@ -41,12 +41,11 @@ class _Ctx:self.discovery_calls_this_turn = 0self.pre_discovery_url_question_nudge_count = 0self.request_policy = None- # Fields the post-discovery sibling reads when _response_coverage_nudge runs.+ # Fields the post-discovery sibling reads when _response_output_nudge runs.self.resolved_discovery_entrypoint_url = Noneself.resolved_discovery_failure_reason = Noneself.update_workflow_called = Falseself.no_workflow_nudge_count = 0- self.coverage_nudge_count = 0self.format_nudge_count = 0self.test_after_update_done = Falseself.workflow_persisted = False@@ -56,6 +55,8 @@ class _Ctx:self.last_run_blocks_workflow_run_id = Noneself.last_successful_run_blocks_workflow_run_id = Noneself.last_outcome_gate_workflow_run_id = None+ self.completion_criteria_turn_state = None+ self.completion_verification_result = Nonedef has_genuine_workflow_attempt(self) -> bool:return CopilotContext.has_genuine_workflow_attempt(self) # type: ignore[arg-type]@@ -118,7 +119,7 @@ def test_pre_discovery_url_ask_in_initial_phase_steers_to_discovery() -> None:def test_pre_discovery_url_ask_fires_through_response_coverage_gate() -> None:ctx = _Ctx()- assert _response_coverage_nudge(ctx, _URL_ASK).rule == "pre_discovery_url_question"+ assert _response_output_nudge(ctx, _URL_ASK).rule == "pre_discovery_url_question"def test_pre_discovery_url_ask_in_discovering_phase_steers_to_discovery() -> None:@@ -225,14 +226,14 @@ def test_pre_discovery_nudge_is_bounded() -> None:def test_present_completion_contract_ask_returns_internal_retry() -> None:ctx = _present_contract_ctx()- assert _response_coverage_nudge(ctx, _OUTPUT_CONFIRMATION_ASK).rule == "present_completion_contract_ask_retry"+ assert _response_output_nudge(ctx, _OUTPUT_CONFIRMATION_ASK).rule == "present_completion_contract_ask_retry"def test_present_completion_contract_ask_has_no_per_rule_cap() -> None:ctx = _present_contract_ctx()- assert _response_coverage_nudge(ctx, _OUTPUT_CONFIRMATION_ASK).rule == "present_completion_contract_ask_retry"- assert _response_coverage_nudge(ctx, _OUTPUT_CONFIRMATION_ASK).rule == "present_completion_contract_ask_retry"+ assert _response_output_nudge(ctx, _OUTPUT_CONFIRMATION_ASK).rule == "present_completion_contract_ask_retry"+ assert _response_output_nudge(ctx, _OUTPUT_CONFIRMATION_ASK).rule == "present_completion_contract_ask_retry"@pytest.mark.parametrize(@@ -270,7 +271,7 @@ def test_present_completion_contract_ask_has_no_per_rule_cap() -> None:def test_present_completion_contract_ask_allows_clarification(overrides: dict[str, object]) -> None:ctx = _present_contract_ctx(**overrides)- assert _response_coverage_nudge(ctx, _OUTPUT_CONFIRMATION_ASK) is None+ assert _response_output_nudge(ctx, _OUTPUT_CONFIRMATION_ASK) is None@pytest.mark.parametrize(@@ -290,7 +291,7 @@ def test_present_completion_contract_ask_suppressed_by_genuine_attempt(marker: dctx = _present_contract_ctx(**marker)assert ctx.has_genuine_workflow_attempt() is True- assert _response_coverage_nudge(ctx, _OUTPUT_CONFIRMATION_ASK) is None+ assert _response_output_nudge(ctx, _OUTPUT_CONFIRMATION_ASK) is None_REQUESTED_OUTPUT_PATHS = ("output.number_of_new_signups", "output.number_of_website_visitors")@@ -345,7 +346,7 @@ def test_output_schema_ask_auto_answers_when_the_contract_only_holds_anonymous_sctx = _mid_build_ctx(_anonymous_slot_contract_policy())with capture_logs() as logs:- nudge = _response_coverage_nudge(ctx, _output_schema_ask(["output.azure_error_count"]))+ nudge = _response_output_nudge(ctx, _output_schema_ask(["output.azure_error_count"]))assert nudge is not Noneassert nudge != PRESENT_COMPLETION_CONTRACT_ASK_RETRY@@ -362,7 +363,7 @@ def test_output_schema_ask_with_covered_refs_routes_to_the_declaring_read() -> Nctx = _mid_build_ctx(_output_path_contract_policy())with capture_logs() as logs:- nudge = _response_coverage_nudge(ctx, _output_schema_ask([_REQUESTED_OUTPUT_PATHS[1]]))+ nudge = _response_output_nudge(ctx, _output_schema_ask([_REQUESTED_OUTPUT_PATHS[1]]))assert nudge is not Noneassert nudge != PRESENT_COMPLETION_CONTRACT_ASK_RETRY@@ -388,7 +389,7 @@ def test_output_schema_ask_passes_through_when_any_requested_path_is_nameable()ctx = _mid_build_ctx(policy)with capture_logs() as logs:- nudge = _response_coverage_nudge(ctx, _output_schema_ask(["output.unknown_field"]))+ nudge = _response_output_nudge(ctx, _output_schema_ask(["output.unknown_field"]))assert nudge is Noneassert not [entry for entry in logs if entry["event"] == "copilot_ask_subject_auto_answered"]@@ -398,7 +399,7 @@ def test_output_schema_ask_with_covering_refs_auto_answers() -> None:ctx = _present_contract_ctx(request_policy=_output_path_contract_policy())with capture_logs() as logs:- nudge = _response_coverage_nudge(ctx, _output_schema_ask(list(_REQUESTED_OUTPUT_PATHS)))+ nudge = _response_output_nudge(ctx, _output_schema_ask(list(_REQUESTED_OUTPUT_PATHS)))assert nudge is not Noneassert nudge != PRESENT_COMPLETION_CONTRACT_ASK_RETRY@@ -422,7 +423,7 @@ def test_output_schema_ask_without_full_coverage_passes_through(refs: list[str])ctx = _mid_build_ctx(_output_path_contract_policy())with capture_logs() as logs:- nudge = _response_coverage_nudge(ctx, _output_schema_ask(refs))+ nudge = _response_output_nudge(ctx, _output_schema_ask(refs))assert nudge is Noneassert not [entry for entry in logs if entry["event"] == "copilot_ask_subject_auto_answered"]@@ -438,7 +439,7 @@ _CREDENTIALS_ASK = {def test_non_output_schema_subject_ask_passes_through() -> None:ctx = _mid_build_ctx(_output_path_contract_policy())- assert _response_coverage_nudge(ctx, _CREDENTIALS_ASK) is None+ assert _response_output_nudge(ctx, _CREDENTIALS_ASK) is None@pytest.mark.parametrize(@@ -454,7 +455,7 @@ def test_typed_subject_ask_before_a_genuine_attempt_keeps_the_legacy_retry(ask:build-first retry; only a resolved auto-answer skips it."""ctx = _present_contract_ctx(request_policy=_output_path_contract_policy())- assert _response_coverage_nudge(ctx, ask).rule == "present_completion_contract_ask_retry"+ assert _response_output_nudge(ctx, ask).rule == "present_completion_contract_ask_retry"@pytest.mark.parametrize(@@ -474,7 +475,7 @@ def test_typed_subject_ask_before_a_genuine_attempt_keeps_the_legacy_retry(ask:)def test_unresolved_typed_ask_logs_which_outcome_it_got(ctx_factory: Callable[[], _Ctx], expected_outcome: str) -> None:with capture_logs() as logs:- _response_coverage_nudge(ctx_factory(), _CREDENTIALS_ASK)+ _response_output_nudge(ctx_factory(), _CREDENTIALS_ASK)events = [entry for entry in logs if entry["event"] == "copilot_ask_subject_passed_through"]assert len(events) == 1@@ -484,7 +485,7 @@ def test_unresolved_typed_ask_logs_which_outcome_it_got(ctx_factory: Callable[[]def test_absent_subject_present_contract_ask_keeps_legacy_retry() -> None:ctx = _present_contract_ctx(request_policy=_output_path_contract_policy())- assert _response_coverage_nudge(ctx, _OUTPUT_CONFIRMATION_ASK).rule == "present_completion_contract_ask_retry"+ assert _response_output_nudge(ctx, _OUTPUT_CONFIRMATION_ASK).rule == "present_completion_contract_ask_retry"def test_definition_level_output_path_does_not_count_as_coverage() -> None:@@ -503,14 +504,14 @@ def test_definition_level_output_path_does_not_count_as_coverage() -> None:)ctx = _mid_build_ctx(policy)- assert _response_coverage_nudge(ctx, _output_schema_ask(["output.number_of_website_visitors"])) is None+ assert _response_output_nudge(ctx, _output_schema_ask(["output.number_of_website_visitors"])) is Nonedef test_present_completion_contract_ask_admits_after_scout_only_marker() -> None:ctx = _present_contract_ctx(test_after_update_done=True)assert ctx.has_genuine_workflow_attempt() is False- assert _response_coverage_nudge(ctx, _OUTPUT_CONFIRMATION_ASK).rule == "present_completion_contract_ask_retry"+ assert _response_output_nudge(ctx, _OUTPUT_CONFIRMATION_ASK).rule == "present_completion_contract_ask_retry"_PARITY_MARKER_STATES = [@@ -530,7 +531,7 @@ _PARITY_MARKER_STATES = [def test_recycle_admission_is_superset_of_backstop_block(marker: dict[str, object]) -> None:ctx = _present_contract_ctx(**marker)workflow_attempted = ctx.has_genuine_workflow_attempt()- recycle_decision = _response_coverage_nudge(ctx, _OUTPUT_CONFIRMATION_ASK)+ recycle_decision = _response_output_nudge(ctx, _OUTPUT_CONFIRMATION_ASK)recycle_admits = recycle_decision is not None and recycle_decision.rule == "present_completion_contract_ask_retry"backstop_would_fire = not workflow_attempted@@ -573,7 +574,7 @@ def _mid_build_ctx(policy: RequestPolicy) -> _Ctx:def test_output_schema_ask_auto_answers_after_genuine_attempt() -> None:ctx = _mid_build_ctx(_output_path_contract_policy())- nudge = _response_coverage_nudge(ctx, _output_schema_ask(list(_REQUESTED_OUTPUT_PATHS)))+ nudge = _response_output_nudge(ctx, _output_schema_ask(list(_REQUESTED_OUTPUT_PATHS)))assert nudge is not Noneassert nudge != PRESENT_COMPLETION_CONTRACT_ASK_RETRY@@ -585,7 +586,7 @@ def test_floor_rekeyed_contract_covers_output_schema_ask() -> None:ctx = _mid_build_ctx(_rekeyed_contract_policy())with capture_logs() as logs:- nudge = _response_coverage_nudge(ctx, _output_schema_ask(list(_REQUESTED_OUTPUT_PATHS)))+ nudge = _response_output_nudge(ctx, _output_schema_ask(list(_REQUESTED_OUTPUT_PATHS)))assert nudge is not Noneevents = [entry for entry in logs if entry["event"] == "copilot_ask_subject_auto_answered"]@@ -609,14 +610,14 @@ def test_credentials_ask_after_genuine_attempt_passes_through() -> None:"ask_subject": "credentials",}- assert _response_coverage_nudge(ctx, ask) is None+ assert _response_output_nudge(ctx, ask) is Nonedef test_uncovered_output_schema_ask_after_genuine_attempt_passes_through() -> None:ctx = _mid_build_ctx(_rekeyed_contract_policy())with capture_logs() as logs:- nudge = _response_coverage_nudge(ctx, _output_schema_ask(["output.unknown_field"]))+ nudge = _response_output_nudge(ctx, _output_schema_ask(["output.unknown_field"]))assert nudge is Noneassert not [entry for entry in logs if entry["event"] == "copilot_ask_subject_auto_answered"]@@ -635,13 +636,13 @@ def test_definition_level_rekeyed_path_does_not_count_as_coverage() -> None:)ctx = _mid_build_ctx(policy)- assert _response_coverage_nudge(ctx, _output_schema_ask([_REQUESTED_OUTPUT_PATHS[1]])) is None+ assert _response_output_nudge(ctx, _output_schema_ask([_REQUESTED_OUTPUT_PATHS[1]])) is Nonedef test_clarification_reason_keeps_output_schema_ask_with_the_user() -> None:ctx = _mid_build_ctx(_rekeyed_contract_policy(clarification_reason="credentials"))- assert _response_coverage_nudge(ctx, _output_schema_ask(list(_REQUESTED_OUTPUT_PATHS))) is None+ assert _response_output_nudge(ctx, _output_schema_ask(list(_REQUESTED_OUTPUT_PATHS))) is Nonedef _enforcement_ctx(policy: RequestPolicy) -> CopilotContext:@@ -686,3 +687,69 @@ def test_definition_level_rekeyed_path_stays_out_of_the_prompt_summary() -> None)assert "requested_output_paths:" not in policy.prompt_summary()+++def _deliverable_contract_policy() -> RequestPolicy:+ return _output_path_contract_policy(+ completion_criteria=[+ CompletionCriterion(+ id="dl",+ outcome="the invoice for July is downloaded",+ deliverable_kind="registered_download",+ output_path="output.downloaded_files",+ ),+ ],+ )+++def _deliverable_ask(subject: str, refs: list[str] | None = None) -> dict[str, object]:+ return {+ "type": "ASK_QUESTION",+ "user_response": "Should I download that July 2025 invoice?",+ "ask_subject": subject,+ "refs": refs if refs is not None else ["output.downloaded_files"],+ }+++def test_deliverable_permission_ask_bounces_after_genuine_attempt() -> None:+ # The contract already orders the download, so permission to produce it is not a+ # question the user owes an answer to — even after a genuine build attempt.+ ctx = _mid_build_ctx(_deliverable_contract_policy())+ assert ctx.has_genuine_workflow_attempt()++ nudge = _response_output_nudge(ctx, _deliverable_ask("deliverable_permission"))++ assert nudge is not None+ assert nudge.rule == "deliverable_permission_ask_retry"+ assert "the invoice for July is downloaded" in nudge.message+ # Bouncing a permission question must not silence what it would have told the user: the+ # reply owes the pick and any fact the user could not have known.+ assert "produce it and verify it" in nudge.message+ assert "which you took and anything about it the user could not have known" in nudge.message+++def test_disambiguation_ask_still_reaches_user_after_genuine_attempt() -> None:+ ctx = _mid_build_ctx(_deliverable_contract_policy())++ assert _response_output_nudge(ctx, _deliverable_ask("disambiguation")) is None+++def test_deliverable_permission_ask_reaches_user_once_criterion_satisfied() -> None:+ ctx = _mid_build_ctx(_deliverable_contract_policy())+ ctx.completion_verification_result = SimpleNamespace(verdicts=[SimpleNamespace(criterion_id="dl", satisfied=True)])++ assert _response_output_nudge(ctx, _deliverable_ask("deliverable_permission")) is None+++def test_deliverable_permission_ask_for_an_unrelated_side_effect_reaches_user() -> None:+ # The subject label is model-chosen. A payment confirmation on a request that also downloads+ # a receipt must never be answered by the download's authority, however it is labeled.+ ctx = _mid_build_ctx(_deliverable_contract_policy())+ payment_ask = {+ "type": "ASK_QUESTION",+ "user_response": "Should I submit this $4,812 payment?",+ "ask_subject": "deliverable_permission",+ "refs": ["output.payment_confirmation"],+ }++ assert _response_output_nudge(ctx, payment_ask) is Nonediff --git a/tests/unit/test_copilot_response_coverage_gate.py b/tests/unit/test_copilot_response_coverage_gate.pyindex 432f33c3a..889f9fe23 100644--- a/tests/unit/test_copilot_response_coverage_gate.py+++ b/tests/unit/test_copilot_response_coverage_gate.py@@ -1,11 +1,8 @@-"""Tests for the response-aware coverage gate in enforcement_decision.--Covers a regression where a 2-action user goal slipped past enforcement-because the old `premature_completion_nudge_done` latch was bypassed by a-no-op turn (model emits REPLY JSON without calling any update tool). The-new gate peeks at the final response text to distinguish REPLY with a-coverage gap (nudge), REPLY with progress-narration prose (nudge), and-ASK_QUESTION (always allowed).+"""Tests for response-aware enforcement decisions.++The response peek still rejects delivery claims without a workflow and+progress narration, but demonstrated outcomes are terminal regardless of+how many user actions one executable block covers."""from __future__ import annotations@@ -15,14 +12,15 @@ from dataclasses import dataclass, fieldfrom types import SimpleNamespacefrom typing import Any+from skyvern.forge.sdk.copilot.completion_verification import CompletionVerificationResult, CriterionVerdictfrom skyvern.forge.sdk.copilot.enforcement import (MAX_DISCOVERY_ENTRYPOINT_URL_QUESTION_NUDGES,MAX_FORMAT_NUDGES,- MAX_INTERMEDIATE_NUDGES,MAX_NO_WORKFLOW_NUDGES,_is_progress_narration,- _response_coverage_nudge,+ _response_output_nudge,enforcement_decision,+ verified_goal_satisfied_context,)@@ -36,12 +34,13 @@ class _Ctx:self.update_workflow_called = Falseself.test_after_update_done = Falseself.post_update_nudge_count = 0- self.coverage_nudge_count = 0self.format_nudge_count = 0self.no_workflow_nudge_count = 0self.discovery_entrypoint_url_question_nudge_count = 0self.user_message = ""self.request_policy = None+ self.completion_criteria_turn_state = None+ self.completion_verification_result = Noneself.resolved_discovery_entrypoint_url = Noneself.resolved_discovery_failure_reason = Noneself.resolved_discovery_entrypoint_inspection_baseline = 0@@ -60,6 +59,7 @@ class _Ctx:self.repeated_failure_nudge_emitted_at_streak = 0self.last_artifact_health_blocker_reason = Noneself.completion_verification_result = None+ self.copilot_total_timeout_exceeded = False@dataclass@@ -95,25 +95,16 @@ def _post_success_ctx(user_message: str, block_count: int = 1) -> _Ctx:# ----------------------------------------------------------------------------# _response_coverage_nudge — direct unit tests+# _response_output_nudge — direct unit tests# ----------------------------------------------------------------------------def test_reply_with_coverage_gap_fires_nudge() -> None:- ctx = _post_success_ctx("go to example.com and download the regulations")- parsed = {"type": "REPLY", "user_response": "I created a nav block."}- nudge = _response_coverage_nudge(ctx, parsed)- assert nudge.rule == "post_intermediate_success"- assert ctx.coverage_nudge_count == 1--def test_reply_after_success_with_request_policy_completion_contract_passes_through() -> None:ctx = _post_success_ctx("Go to https://example.com/contact. Fill out the contact form and submit it.")ctx.request_policy = SimpleNamespace(completion_contract="confirmation banner appears")parsed = {"type": "REPLY", "user_response": "I created and tested the workflow."}- assert _response_coverage_nudge(ctx, parsed) is None- assert ctx.coverage_nudge_count == 0+ assert _response_output_nudge(ctx, parsed) is Nonedef test_reply_after_success_with_unknown_fallback_contract_passes_through() -> None:@@ -121,24 +112,13 @@ def test_reply_after_success_with_unknown_fallback_contract_passes_through() ->ctx.request_policy = SimpleNamespace(completion_contract_status="unknown")parsed = {"type": "REPLY", "user_response": "I created and tested the workflow."}- assert _response_coverage_nudge(ctx, parsed) is None- assert ctx.coverage_nudge_count == 0+ assert _response_output_nudge(ctx, parsed) is None-def test_coverage_nudge_respects_counter_cap() -> None:- ctx = _post_success_ctx("go to X and download Y")- parsed = {"type": "REPLY", "user_response": "one block draft"}- for _ in range(MAX_INTERMEDIATE_NUDGES):- assert _response_coverage_nudge(ctx, parsed).rule == "post_intermediate_success"- # One more call — the cap should now let the response through.- assert _response_coverage_nudge(ctx, parsed) is None---def test_ask_question_passes_through_even_with_coverage_gap() -> None:+def test_ask_question_passes_through_after_success() -> None:ctx = _post_success_ctx("go to site and download file")parsed = {"type": "ASK_QUESTION", "user_response": "Which file do you mean?"}- assert _response_coverage_nudge(ctx, parsed) is None- assert ctx.coverage_nudge_count == 0+ assert _response_output_nudge(ctx, parsed) is Nonedef test_ask_question_before_acting_on_discovery_candidate_fires_nudge() -> None:@@ -149,7 +129,7 @@ def test_ask_question_before_acting_on_discovery_candidate_fires_nudge() -> None"user_response": "Which file should I download?",}- nudge = _response_coverage_nudge(ctx, parsed)+ nudge = _response_output_nudge(ctx, parsed)assert nudge is not Noneassert nudge.rule == "post_discovery_entrypoint_url_question"@@ -163,7 +143,7 @@ def test_ask_question_after_discovery_failure_still_passes_through() -> None:ctx.resolved_discovery_failure_reason = "could_not_resolve_site_name"parsed = {"type": "ASK_QUESTION", "user_response": "Which URL should I use?"}- assert _response_coverage_nudge(ctx, parsed) is None+ assert _response_output_nudge(ctx, parsed) is Nonedef test_ask_question_before_acting_on_discovery_candidate_caps_nudges() -> None:@@ -172,9 +152,9 @@ def test_ask_question_before_acting_on_discovery_candidate_caps_nudges() -> Noneparsed = {"type": "ASK_QUESTION", "user_response": "Which file should I download?"}for expected_count in range(1, MAX_DISCOVERY_ENTRYPOINT_URL_QUESTION_NUDGES + 1):- assert _response_coverage_nudge(ctx, parsed) is not None+ assert _response_output_nudge(ctx, parsed) is not Noneassert ctx.discovery_entrypoint_url_question_nudge_count == expected_count- assert _response_coverage_nudge(ctx, parsed) is None+ assert _response_output_nudge(ctx, parsed) is Noneassert ctx.discovery_entrypoint_url_question_nudge_count == MAX_DISCOVERY_ENTRYPOINT_URL_QUESTION_NUDGES@@ -189,7 +169,7 @@ def test_ask_question_after_page_inspection_of_discovery_candidate_passes_throug}parsed = {"type": "ASK_QUESTION", "user_response": "Which account should I use?"}- assert _response_coverage_nudge(ctx, parsed) is None+ assert _response_output_nudge(ctx, parsed) is Nonedef test_ask_question_after_unrelated_page_inspection_of_discovery_candidate_still_fires_nudge() -> None:@@ -203,7 +183,7 @@ def test_ask_question_after_unrelated_page_inspection_of_discovery_candidate_sti}parsed = {"type": "ASK_QUESTION", "user_response": "Which account should I use?"}- assert _response_coverage_nudge(ctx, parsed) is not None+ assert _response_output_nudge(ctx, parsed) is not Nonedef test_ask_question_after_stale_candidate_page_inspection_still_fires_nudge() -> None:@@ -218,7 +198,7 @@ def test_ask_question_after_stale_candidate_page_inspection_still_fires_nudge()}parsed = {"type": "ASK_QUESTION", "user_response": "Which account should I use?"}- assert _response_coverage_nudge(ctx, parsed) is not None+ assert _response_output_nudge(ctx, parsed) is not Nonedef test_ask_question_after_mutating_from_discovery_candidate_passes_through() -> None:@@ -227,14 +207,13 @@ def test_ask_question_after_mutating_from_discovery_candidate_passes_through() -ctx.update_workflow_called = Trueparsed = {"type": "ASK_QUESTION", "user_response": "Which account should I use?"}- assert _response_coverage_nudge(ctx, parsed) is None+ assert _response_output_nudge(ctx, parsed) is None-def test_reply_without_coverage_gap_passes_through() -> None:- # 2-action goal and 2 blocks — no gap.+def test_clean_reply_after_success_passes_through() -> None:ctx = _post_success_ctx("go to X and download Y", block_count=2)parsed = {"type": "REPLY", "user_response": "Done. I created a 2-block workflow."}- assert _response_coverage_nudge(ctx, parsed) is None+ assert _response_output_nudge(ctx, parsed) is Nonedef test_reply_before_any_successful_test_passes_through() -> None:@@ -242,14 +221,14 @@ def test_reply_before_any_successful_test_passes_through() -> None:ctx.user_message = "go to X and download Y"# last_test_ok is None — no successful test yet.parsed = {"type": "REPLY", "user_response": "Working on it."}- assert _response_coverage_nudge(ctx, parsed) is None+ assert _response_output_nudge(ctx, parsed) is Nonedef test_reply_claiming_workflow_without_update_fires_nudge() -> None:ctx = _Ctx()parsed = {"type": "REPLY", "user_response": "Here's the workflow."}- assert _response_coverage_nudge(ctx, parsed).rule == "post_no_workflow_delivery"+ assert _response_output_nudge(ctx, parsed).rule == "post_no_workflow_delivery"assert ctx.no_workflow_nudge_count == 1@@ -260,7 +239,7 @@ def test_initial_part_workflow_claim_without_update_fires_nudge() -> None:"user_response": "In the meantime, I've drafted the initial part of your workflow with placeholders.",}- assert _response_coverage_nudge(ctx, parsed).rule == "post_no_workflow_delivery"+ assert _response_output_nudge(ctx, parsed).rule == "post_no_workflow_delivery"assert ctx.no_workflow_nudge_count == 1@@ -269,8 +248,8 @@ def test_no_workflow_delivery_nudge_respects_counter_cap() -> None:parsed = {"type": "REPLY", "user_response": "I created a workflow for this."}for _ in range(MAX_NO_WORKFLOW_NUDGES):- assert _response_coverage_nudge(ctx, parsed).rule == "post_no_workflow_delivery"- assert _response_coverage_nudge(ctx, parsed) is None+ assert _response_output_nudge(ctx, parsed).rule == "post_no_workflow_delivery"+ assert _response_output_nudge(ctx, parsed) is Nonedef test_no_workflow_delivery_nudge_ignores_existing_update_path() -> None:@@ -278,14 +257,14 @@ def test_no_workflow_delivery_nudge_ignores_existing_update_path() -> None:ctx.update_workflow_called = Trueparsed = {"type": "REPLY", "user_response": "Here's the workflow."}- assert _response_coverage_nudge(ctx, parsed) is None+ assert _response_output_nudge(ctx, parsed) is Nonedef test_reply_after_failed_test_passes_through() -> None:ctx = _post_success_ctx("go to X and download Y")ctx.last_test_ok = False # test failedparsed = {"type": "REPLY", "user_response": "The test failed."}- assert _response_coverage_nudge(ctx, parsed) is None+ assert _response_output_nudge(ctx, parsed) is None# ---------------------------------------------------------------------------@@ -314,14 +293,13 @@ def test_is_progress_narration_empty_inputs() -> None:assert not _is_progress_narration(None) # type: ignore[arg-type]-def test_format_nudge_fires_for_progress_narration_without_coverage_gap() -> None:- # 2 blocks, so no coverage gap. But the text is future-tense progress.+def test_format_nudge_fires_for_progress_narration() -> None:ctx = _post_success_ctx("go to X and download Y", block_count=2)parsed = {"type": "REPLY","user_response": "I ran the first block. Next I will proceed to add the rest.",}- nudge = _response_coverage_nudge(ctx, parsed)+ nudge = _response_output_nudge(ctx, parsed)assert nudge.rule == "post_format"assert ctx.format_nudge_count == 1@@ -330,17 +308,15 @@ def test_format_nudge_respects_counter_cap() -> None:ctx = _post_success_ctx("go to X and download Y", block_count=2)parsed = {"type": "REPLY", "user_response": "Next I will proceed."}for _ in range(MAX_FORMAT_NUDGES):- assert _response_coverage_nudge(ctx, parsed).rule == "post_format"- assert _response_coverage_nudge(ctx, parsed) is None+ assert _response_output_nudge(ctx, parsed).rule == "post_format"+ assert _response_output_nudge(ctx, parsed) is None-def test_coverage_nudge_takes_priority_over_format_nudge() -> None:- # Coverage gap AND progress narration — coverage fires first, counter advances.+def test_progress_narration_nudge_is_independent_of_workflow_block_count() -> None:ctx = _post_success_ctx("go to X and download Y", block_count=1)parsed = {"type": "REPLY", "user_response": "Next I will proceed with more blocks."}- assert _response_coverage_nudge(ctx, parsed).rule == "post_intermediate_success"- assert ctx.coverage_nudge_count == 1- assert ctx.format_nudge_count == 0+ assert _response_output_nudge(ctx, parsed).rule == "post_format"+ assert ctx.format_nudge_count == 1# ---------------------------------------------------------------------------@@ -348,38 +324,53 @@ def test_coverage_nudge_takes_priority_over_format_nudge() -> None:# ---------------------------------------------------------------------------+def test_ph1_one_block_login_and_extraction_with_requested_output_terminates() -> None:+ """A demonstrated requested output is terminal even when one code block+ covers multiple actions from the user's prompt."""+ observed_azure_errors = 27+ ctx = _post_success_ctx(+ "Log in to Datadog with the saved credential and then extract the number of Azure errors.",+ block_count=1,+ )+ ctx.request_policy = SimpleNamespace(completion_contract="Return the number of Azure errors")+ ctx.last_full_workflow_test_ok = True+ ctx.verified_block_outputs = {+ "login_and_extract": {"azure_error_count": observed_azure_errors},+ }+ ctx.completion_verification_result = CompletionVerificationResult(+ status="evaluated",+ criterion_ids=["azure_error_count"],+ verdicts=[+ CriterionVerdict(+ criterion_id="azure_error_count",+ state="satisfied",+ reason_code="evidence_confirms",+ evidence_ref="block_outputs:login_and_extract.azure_error_count",+ output_path="output.azure_error_count",+ )+ ],+ )+ result = _reply_result(f"The workflow ran successfully. Azure errors: {observed_azure_errors}.")++ assert ctx.verified_block_outputs["login_and_extract"]["azure_error_count"] == observed_azure_errors+ assert verified_goal_satisfied_context(ctx) is True+ assert enforcement_decision(ctx, result) is None+ assert ctx.copilot_total_timeout_exceeded is False++def test_no_op_turn_bypass_closed_goes_to_phrasing() -> None:- """Simulate the regression's final turn: workflow has 1 block, test passed,- model emits REPLY without any new tool calls. Before the fix, the latch- blocked re-nudging. After the fix, the response-aware gate fires — in- this specific message the lexical coverage heuristic matches only- 'download' (not 'goes to' — the bigram is 'goes to' vs 'go to'), so the- coverage branch lets it through. The progress-narration format branch- catches the future-tense REPLY instead."""+ """Progress narration remains non-terminal after the block-count veto is deleted."""ctx = _post_success_ctx("make a workflow that goes to example.com and downloads the latest regulations")result = _reply_result("I ran the first block (open_home). The navigation block completed. ""I did not attempt further blocks yet. Next I will proceed.")nudge = enforcement_decision(ctx, result)- # Either branch is a valid fix for the regression — verify the format- # branch specifically since the coverage heuristic misses this phrasing.assert nudge.rule == "post_format"-def test_no_op_turn_bypass_closed_multi_action() -> None:- """Same structural bug, with a message the coverage heuristic does match- (explicit 'go to' + 'download'). The coverage branch fires."""- ctx = _post_success_ctx("go to example.com and download the regulations")- result = _reply_result("Ran one block; will do the rest next.")- nudge = enforcement_decision(ctx, result)- assert nudge.rule == "post_intermediate_success"--def test_ask_question_reaches_user_after_any_state() -> None:- """Regression guard for CORR-2: once the intermediate-success latch was- removed, we must still let ASK_QUESTION through even when coverage is- incomplete, so the agent can ask for credentials / disambiguate."""+ """ASK_QUESTION still reaches the user for credentials or disambiguation."""ctx = _post_success_ctx("login and download my records")result = _ask_question_result("Which credential should I use for this login?")assert enforcement_decision(ctx, result) is Nonediff --git a/tests/unit/test_copilot_scout_act_observe.py b/tests/unit/test_copilot_scout_act_observe.pyindex 211c1ffb3..9efbfe429 100644--- a/tests/unit/test_copilot_scout_act_observe.py+++ b/tests/unit/test_copilot_scout_act_observe.py@@ -155,6 +155,10 @@ def _ctx(*, server: Any = None, source_url: str | None = _SOURCE_URL) -> SimpleNscout_observed_terminal_criterion_ids=set(),request_policy=None,org_credentials_for_turn=None,+ completion_verification_result=None,+ reached_download_target=None,+ pending_scout_popup=None,+ pending_scout_popup_content_type=None,)diff --git a/tests/unit/test_evaluate_actionable_target.py b/tests/unit/test_evaluate_actionable_target.pyindex 14632338f..bb08fce4e 100644--- a/tests/unit/test_evaluate_actionable_target.py+++ b/tests/unit/test_evaluate_actionable_target.py@@ -1,9 +1,12 @@from __future__ import annotationsimport json+from types import SimpleNamespaceimport pytest+from skyvern.forge.sdk.copilot.completion_criteria_store import CompletionCriteriaTurnState, ReconcileDecision+from skyvern.forge.sdk.copilot.request_policy import CompletionCriterionfrom skyvern.forge.sdk.copilot.result_evidence import loaded_result_source_produciblefrom skyvern.forge.sdk.copilot.runtime import AgentContextfrom skyvern.forge.sdk.copilot.tools import scouting@@ -109,6 +112,9 @@ def _single_max_structural_loaded_result_packet() -> dict:def _ctx() -> AgentContext:ctx = AgentContext.__new__(AgentContext)ctx.scout_trajectory = []+ ctx.completion_criteria_turn_state = None+ ctx.request_policy = None+ ctx.completion_verification_result = Nonereturn ctx@@ -1099,3 +1105,96 @@ async def test_auto_act_front_runs_the_third_evaluate(monkeypatch) -> None:detect_tool_loop(tripping, "evaluate")detect_tool_loop(tripping, "evaluate")assert detect_tool_loop(tripping, "evaluate") is not None+++def _ctx_with_unmet_download_goal() -> AgentContext:+ ctx = _ctx()+ criterion = CompletionCriterion(+ id="c0",+ outcome="the invoice for July is downloaded",+ deliverable_kind="registered_download",+ )+ ctx.completion_criteria_turn_state = CompletionCriteriaTurnState(+ decision=ReconcileDecision(action="create", reason="first", epoch=1, criteria=(criterion,))+ )+ return ctx+++async def test_result_table_with_unmet_download_goal_keeps_actionable_targets(monkeypatch) -> None:+ """A page can be both a results table and the place a download must be earned. While a+ registered-download criterion is unmet, the composition steer must not hide the click+ affordances the goal still needs."""++ async def fake_evidence(ctx, *, url):+ return _result_table_packet()++ monkeypatch.setattr(scouting, "_scout_act_observe_page_evidence", fake_evidence)+ ctx = _ctx_with_unmet_download_goal()+ ctx.last_evaluate_actionable_signature = "stale"+ ctx.last_evaluate_actionable_url = "https://example.com/previous"+ result = {+ "ok": True,+ "data": {+ "url": "https://example.com/results",+ "actionable_targets": [{"selector": "#details", "text": "Details"}],+ },+ }++ await scouting._maybe_steer_evaluate_to_action(ctx, result, url="https://example.com/results")++ assert result["data"].get("next_action") != "compose_extraction"+ assert "actionable_targets" in result["data"]+ assert "composition_targets" not in result["data"]+++async def test_result_table_with_satisfied_download_goal_still_composes(monkeypatch) -> None:+ async def fake_evidence(ctx, *, url):+ return _result_table_packet()++ monkeypatch.setattr(scouting, "_scout_act_observe_page_evidence", fake_evidence)+ ctx = _ctx_with_unmet_download_goal()+ ctx.completion_verification_result = SimpleNamespace(verdicts=[SimpleNamespace(criterion_id="c0", satisfied=True)])+ ctx.last_evaluate_actionable_signature = "stale"+ ctx.last_evaluate_actionable_url = "https://example.com/previous"+ result = {+ "ok": True,+ "data": {+ "url": "https://example.com/results",+ "actionable_targets": [{"selector": "#details", "text": "Details"}],+ },+ }++ await scouting._maybe_steer_evaluate_to_action(ctx, result, url="https://example.com/results")++ assert result["data"].get("next_action") == "compose_extraction"+ assert "actionable_targets" not in result["data"]+++async def test_result_table_composes_again_once_download_target_is_reached(monkeypatch) -> None:+ from skyvern.forge.sdk.copilot.reached_download_target import derive_from_observed_render++ async def fake_evidence(ctx, *, url):+ return _result_table_packet()++ monkeypatch.setattr(scouting, "_scout_act_observe_page_evidence", fake_evidence)+ ctx = _ctx_with_unmet_download_goal()+ ctx.reached_download_target = derive_from_observed_render(+ selector="a.bill", rendered_url="https://example.com/bill-image"+ )+ ctx.last_evaluate_actionable_signature = "stale"+ ctx.last_evaluate_actionable_url = "https://example.com/previous"+ result = {+ "ok": True,+ "data": {+ "url": "https://example.com/results",+ "actionable_targets": [{"selector": "#details", "text": "Details"}],+ },+ }++ await scouting._maybe_steer_evaluate_to_action(ctx, result, url="https://example.com/results")++ assert result["data"].get("next_action") == "compose_extraction"+ assert "actionable_targets" not in result["data"]diff --git a/tests/unit/test_extract_action_stable_prefix.py b/tests/unit/test_extract_action_stable_prefix.pynew file mode 100644index 000000000..d1d5dcfcf--- /dev/null+++ b/tests/unit/test_extract_action_stable_prefix.py@@ -0,0 +1,100 @@+"""Tests for the flag-gated stable-prefix ordering of extract-action prompts (SKY-9983)."""++from typing import Any++import pytest++from skyvern.forge.prompts import prompt_engine++_BASE_KWARGS: dict[str, Any] = {+ "navigation_goal": "goal-sentinel",+ "navigation_payload_str": "payload-sentinel",+ "starting_url": "https://start.test",+ "current_url": "https://current.test/page",+ "data_extraction_goal": None,+ "action_history": "history-sentinel",+ "error_code_mapping_str": None,+ "local_datetime": "2026-08-02T00:00:00Z",+ "verification_code_check": False,+ "complete_criterion": None,+ "terminate_criterion": None,+ "elements": "elements-sentinel",+ "recent_dialog_messages_str": "dialog-sentinel",+ "open_tabs_context": "tabs-sentinel",+ "show_close_page_action": True,+ "show_switch_tab_action": True,+}++TEMPLATES = ["extract-action", "extract-action-dynamic"]++DIALOG_GUIDANCE_MARKER = "the agent auto-accepted each one"+++def _render(template: str, **overrides: Any) -> str:+ return prompt_engine.load_prompt(template, **{**_BASE_KWARGS, **overrides})++[email protected]("template", TEMPLATES)+class TestDefaultOrdering:+ def test_history_renders_before_elements(self, template: str) -> None:+ rendered = _render(template)+ assert rendered.index("history-sentinel") < rendered.index("elements-sentinel")++ def test_flag_false_matches_flag_absent(self, template: str) -> None:+ assert _render(template) == _render(template, stable_prefix_ordering=False)++[email protected]("template", TEMPLATES)+class TestStablePrefixOrdering:+ def test_elements_render_before_per_step_sections(self, template: str) -> None:+ rendered = _render(template, stable_prefix_ordering=True)+ elements_at = rendered.index("elements-sentinel")+ assert rendered.index("Current URL: https://current.test/page") < elements_at+ assert elements_at < rendered.index("history-sentinel")+ assert elements_at < rendered.index("dialog-sentinel")+ assert elements_at < rendered.index("tabs-sentinel")++ def test_dialog_guidance_moves_after_untrusted_block(self, template: str) -> None:+ rendered = _render(template, stable_prefix_ordering=True)+ assert rendered.index(DIALOG_GUIDANCE_MARKER) > rendered.index("END_UNTRUSTED_WEB_PAGE_DATA")++ def test_guidance_sections_omitted_without_their_data(self, template: str) -> None:+ rendered = _render(+ template,+ stable_prefix_ordering=True,+ recent_dialog_messages_str=None,+ open_tabs_context=None,+ show_close_page_action=False,+ show_switch_tab_action=False,+ )+ assert DIALOG_GUIDANCE_MARKER not in rendered+ assert "open browser tabs listed above" not in rendered++ def test_untrusted_values_stay_inside_delimiters(self, template: str) -> None:+ rendered = _render(+ template,+ stable_prefix_ordering=True,+ complete_criterion="criterion-sentinel",+ complete_criterion_is_untrusted=True,+ )+ begin = rendered.index("BEGIN_UNTRUSTED_WEB_PAGE_DATA")+ end = rendered.index("END_UNTRUSTED_WEB_PAGE_DATA")+ for sentinel in (+ "criterion-sentinel",+ "https://current.test/page",+ "elements-sentinel",+ "history-sentinel",+ "dialog-sentinel",+ "tabs-sentinel",+ ):+ assert begin < rendered.index(sentinel) < end, sentinel++ def test_datetime_stays_last(self, template: str) -> None:+ rendered = _render(template, stable_prefix_ordering=True)+ assert rendered.index("2026-08-02T00:00:00Z") > rendered.index("END_UNTRUSTED_WEB_PAGE_DATA")+++def test_static_template_ignores_flag() -> None:+ off = prompt_engine.load_prompt("extract-action-static", stable_prefix_ordering=False, **_BASE_KWARGS)+ on = prompt_engine.load_prompt("extract-action-static", stable_prefix_ordering=True, **_BASE_KWARGS)+ assert off == ondiff --git a/tests/unit/test_onboarding_milestone_hooks.py b/tests/unit/test_onboarding_milestone_hooks.pyindex 12241403c..2b40fe87d 100644--- a/tests/unit/test_onboarding_milestone_hooks.py+++ b/tests/unit/test_onboarding_milestone_hooks.py@@ -326,6 +326,8 @@ class TestWorkflowRunCompleteHookFires:mock_status.is_final.return_value = Truemock_db = MagicMock()+ # Final transitions claim the flip via the conditional update first.+ mock_db.workflow_runs.update_workflow_run_if_not_final = AsyncMock(return_value=mock_workflow_run)mock_db.workflow_runs.update_workflow_run = AsyncMock(return_value=mock_workflow_run)mock_db.tags.apply_system_run_tag_changes = AsyncMock()diff --git a/tests/unit/test_output_parameter_size_guards.py b/tests/unit/test_output_parameter_size_guards.pyindex c7d148fd5..20b0dcc59 100644--- a/tests/unit/test_output_parameter_size_guards.py+++ b/tests/unit/test_output_parameter_size_guards.py@@ -1,22 +1,47 @@-"""Tests for SKY-9779: three-layer guard against oversized JSON-column block outputs.+"""Guards against oversized JSON block outputs (SKY-9779 storage, SKY-13015 API reads).-Covers the three helpers added by the fix:- - ``truncate_oversized_jsonb_value`` (Layer 1: DB-write chokepoint)- - ``_maybe_truncate_loop_outputs`` (Layer 2: loop accumulator OOM guard)- - ``_trim_branch_evaluations`` / ``_cap_debug_field`` (Layer 3: DecisionBlock filter)+- ``truncate_oversized_jsonb_value`` (Layer 1: DB-write chokepoint)+- ``_maybe_truncate_loop_outputs`` (Layer 2: loop accumulator OOM guard)+- ``_trim_branch_evaluations`` / ``_cap_debug_field`` (Layer 3: DecisionBlock filter)+- ``truncate_oversized_response_value`` (Layer 4: run-detail API read path)"""import json+from datetime import datetime, timezone+from types import SimpleNamespacefrom typing import Any-from unittest.mock import patch+from unittest.mock import AsyncMock, MagicMock, patch+import pytest++from skyvern.constants import SKYVERN_UI_USER_AGENTfrom skyvern.forge.sdk.db.utils import _custom_json_serializer, truncate_oversized_jsonb_value+from skyvern.forge.sdk.routes import agent_protocol+from skyvern.forge.sdk.routes.trigger_type import caps_run_response_values+from skyvern.forge.sdk.schemas.task_v2 import Thought+from skyvern.forge.sdk.schemas.tasks import TaskStatus+from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock+from skyvern.forge.sdk.workflow import service as workflow_service_modulefrom skyvern.forge.sdk.workflow.models.block import (DECISION_BLOCK_FIELD_MAX_BYTES,_cap_debug_field,_maybe_truncate_loop_outputs,_trim_branch_evaluations,)+from skyvern.forge.sdk.workflow.models.workflow import (+ Workflow,+ WorkflowDefinition,+ WorkflowRun,+ WorkflowRunResponseBase,+ WorkflowRunStatus,+ WorkflowStatus,+)+from skyvern.forge.sdk.workflow.service import WorkflowService, truncate_oversized_response_value+from skyvern.schemas.runs import RunType+from skyvern.schemas.workflows import BlockType+from skyvern.services import run_service, task_v2_service+from skyvern.webeye.actions.action_types import ActionType+from skyvern.webeye.actions.actions import Action# ---------- Layer 1: truncate_oversized_jsonb_value ----------@@ -233,3 +258,1058 @@ def test_custom_json_serializer_preserves_literal_unicode_escape_strings() -> Nopayload = {"x": literal_six_chars, "y": "abc" + literal_six_chars + "def"}serialized = _custom_json_serializer(payload)assert json.loads(serialized) == payload+++# ---------- Layer 4: truncate_oversized_response_value (API read path) ----------+++def test_truncate_oversized_response_value_passes_small_value_through() -> None:+ value = {"rows": [[1, 2], [3, 4]]}+ assert truncate_oversized_response_value(value, workflow_run_id="wr_x") is value+++def test_truncate_oversized_response_value_returns_marker_above_cap() -> None:+ cap = 64 * 1024+ big = ["x" * 1024 for _ in range(cap // 512)]+ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = truncate_oversized_response_value(big, workflow_run_id="wr_x", output_key="sheet_read_output")+ # Entries that fit are kept; the trailing marker is what makes the drop explicit.+ marker = result[-1]+ assert marker["truncated"] is True+ assert marker["reason"] == "exceeded_max_run_response_value_size"+ assert marker["limit_bytes"] == cap+ assert marker["original_size_bytes"] > cap+ assert marker["original_count"] == len(big)+ assert 0 < marker["kept_count"] < len(big)+ assert len(json.dumps(result, separators=(",", ":")).encode("utf-8")) <= cap+++def test_truncate_oversized_response_value_fails_open_on_serialization_error() -> None:+ class _Unencodable:+ __slots__ = ()++ def __repr__(self) -> str:+ raise RuntimeError("boom")++ value: Any = {"u": _Unencodable()}+ with patch("skyvern.forge.sdk.workflow.service.LOG") as log:+ assert truncate_oversized_response_value(value, workflow_run_id="wr_x") is value+ log.warning.assert_called_once()+++def test_truncate_oversized_response_value_fast_path_skips_serialization_for_scalars() -> None:+ with patch("skyvern.forge.sdk.workflow.service.json.dumps") as dumps:+ for v in (None, True, False, 0, 42, 3.14):+ assert truncate_oversized_response_value(v) is v+ dumps.assert_not_called()+++async def test_get_workflow_run_timeline_caps_oversized_block_output(monkeypatch: pytest.MonkeyPatch) -> None:+ """A single sheet/file-read block output must not reach the timeline response (SKY-13015)."""+ now = datetime.now(timezone.utc)+ cap = 64 * 1024+ block = WorkflowRunBlock(+ workflow_run_block_id="wrb_1",+ workflow_run_id="wr_1",+ organization_id="o_1",+ block_type=BlockType.GOOGLE_SHEETS_READ,+ output={"values": ["x" * 1024 for _ in range(cap // 512)]},+ created_at=now,+ modified_at=now,+ )++ monkeypatch.setattr(+ workflow_service_module.app,+ "DATABASE",+ SimpleNamespace(+ observer=SimpleNamespace(get_workflow_run_blocks=AsyncMock(return_value=[block])),+ tasks=SimpleNamespace(get_tasks_actions=AsyncMock(return_value=[])),+ ),+ )+ monkeypatch.setattr(workflow_service_module, "RUN_RESPONSE_MAX_VALUE_BYTES", cap)++ timeline = await WorkflowService().get_workflow_run_timeline(+ workflow_run_id="wr_1", organization_id="o_1", cap_output_values=True+ )++ assert len(timeline) == 1+ output = timeline[0].block.output+ assert output["values"][-1]["truncated"] is True+ assert output["values"][-1]["reason"] == "exceeded_max_run_response_value_size"+++def _oversized_value(cap: int) -> dict[str, Any]:+ return {"values": ["x" * 1024 for _ in range(cap // 512)]}+++async def _build_status_response(+ monkeypatch: pytest.MonkeyPatch,+ *,+ cap: int,+ cap_output_values: bool,+ output_value: Any = None,+ refresh_output_urls: Any = None,+ failure_reason: str | None = None,+) -> WorkflowRunResponseBase:+ now = datetime.now(timezone.utc)+ workflow = Workflow(+ workflow_id="w_1",+ organization_id="o_1",+ title="T",+ workflow_permanent_id="wpid_1",+ version=1,+ is_saved_task=False,+ workflow_definition=WorkflowDefinition(parameters=[], blocks=[]),+ created_at=now,+ modified_at=now,+ status=WorkflowStatus.published,+ )+ workflow_run = WorkflowRun(+ workflow_run_id="wr_1",+ workflow_id="w_1",+ workflow_permanent_id="wpid_1",+ organization_id="o_1",+ status=WorkflowRunStatus.failed if failure_reason else WorkflowRunStatus.completed,+ failure_reason=failure_reason,+ created_at=now,+ modified_at=now,+ )+ output_parameter = SimpleNamespace(key="sheet_read_output")+ output = SimpleNamespace(value=_oversized_value(cap) if output_value is None else output_value)++ monkeypatch.setattr(+ workflow_service_module.app,+ "DATABASE",+ SimpleNamespace(+ workflows=SimpleNamespace(get_workflow_for_workflow_run=AsyncMock(return_value=workflow)),+ observer=SimpleNamespace(get_task_v2_by_workflow_run_id=AsyncMock(return_value=None)),+ tasks=SimpleNamespace(get_tasks_by_workflow_run_id=AsyncMock(return_value=[])),+ workflow_runs=SimpleNamespace(+ get_workflow_run_parameters=AsyncMock(return_value=[]),+ get_workflow_run_block_errors=AsyncMock(return_value=[]),+ get_workflow_run_retried_by=AsyncMock(return_value=None),+ ),+ ),+ )+ monkeypatch.setattr(workflow_service_module, "RUN_RESPONSE_MAX_VALUE_BYTES", cap)++ service = WorkflowService()+ monkeypatch.setattr(service, "get_workflow_run", AsyncMock(return_value=workflow_run))+ monkeypatch.setattr(service, "get_recent_workflow_screenshot_urls", AsyncMock(return_value=[]))+ monkeypatch.setattr(+ service,+ "get_output_parameter_workflow_run_output_parameter_tuples",+ AsyncMock(return_value=[(output_parameter, output)]),+ )+ monkeypatch.setattr(service, "_fetch_recording_urls", AsyncMock(return_value=([], False)))+ monkeypatch.setattr(service, "_fetch_downloaded_files", AsyncMock(return_value=([], None)))+ # Identity by default: URL refresh is orthogonal to most of the cases under test.+ monkeypatch.setattr(+ service,+ "_refresh_output_urls",+ AsyncMock(side_effect=refresh_output_urls or (lambda value, **_: value)),+ )++ return await service.build_workflow_run_status_response(+ workflow_permanent_id="wpid_1",+ workflow_run_id="wr_1",+ organization_id="o_1",+ cap_output_values=cap_output_values,+ )+++async def test_status_response_caps_oversized_output_when_opted_in(monkeypatch: pytest.MonkeyPatch) -> None:+ cap = 64 * 1024+ response = await _build_status_response(monkeypatch, cap=cap, cap_output_values=True)+ assert response.outputs["sheet_read_output"]["values"][-1]["truncated"] is True+++async def test_status_response_leaves_output_intact_for_webhook_delivery(monkeypatch: pytest.MonkeyPatch) -> None:+ """Webhook delivery and replay must keep full fidelity; capping is opt-in."""+ cap = 64 * 1024+ response = await _build_status_response(monkeypatch, cap=cap, cap_output_values=False)+ assert response.outputs["sheet_read_output"] == _oversized_value(cap)+++async def test_status_response_caps_failure_reason_only_when_opted_in(monkeypatch: pytest.MonkeyPatch) -> None:+ cap = 4 * 1024+ failure_reason = "upstream response: " + "x" * (cap * 3)++ capped = await _build_status_response(+ monkeypatch,+ cap=cap,+ cap_output_values=True,+ failure_reason=failure_reason,+ )+ assert capped.failure_reason is not None+ assert capped.failure_reason.startswith("upstream response:")+ assert "[truncated" in capped.failure_reason+ assert len(json.dumps(capped.failure_reason).encode("utf-8")) <= cap++ uncapped = await _build_status_response(+ monkeypatch,+ cap=cap,+ cap_output_values=False,+ failure_reason=failure_reason,+ )+ assert uncapped.failure_reason == failure_reason+++async def test_task_run_response_caps_failure_reason_only_when_opted_in(monkeypatch: pytest.MonkeyPatch) -> None:+ cap = 4 * 1024+ failure_reason = "upstream response: " + "x" * (cap * 3)+ run = SimpleNamespace(run_id="tsk_1", task_run_type=RunType.task_v1)+ task_v1_response = MagicMock(+ task_id="tsk_1",+ status=TaskStatus.failed,+ extracted_information=None,+ failure_reason=failure_reason,+ )+ monkeypatch.setattr(+ run_service.app,+ "DATABASE",+ SimpleNamespace(tasks=SimpleNamespace(get_run=AsyncMock(return_value=run))),+ )+ monkeypatch.setattr(run_service.task_v1_service, "get_task_v1_response", AsyncMock(return_value=task_v1_response))+ monkeypatch.setattr(run_service, "TaskRunResponse", lambda **kwargs: SimpleNamespace(**kwargs))+ monkeypatch.setattr(run_service, "TaskRunRequest", lambda **kwargs: SimpleNamespace(**kwargs))+ monkeypatch.setattr(workflow_service_module, "RUN_RESPONSE_MAX_VALUE_BYTES", cap)++ capped = await run_service.get_run_response("tsk_1", organization_id="o_1", cap_output_values=True)+ assert capped is not None+ assert capped.failure_reason is not None+ assert capped.failure_reason.startswith("upstream response:")+ assert "[truncated" in capped.failure_reason+ assert len(json.dumps(capped.failure_reason).encode("utf-8")) <= cap+++def test_truncate_oversized_response_value_measures_non_ascii_at_wire_size() -> None:+ """Default json.dumps escapes non-ASCII to \\uXXXX, over-counting CJK ~2x vs the UTF-8 wire form."""+ cap = 64 * 1024+ # Under the cap as UTF-8 (3 bytes/char), over it as escaped ASCII (6 bytes/char).+ value = {"text": "世" * 15000}+ assert len(json.dumps(value, ensure_ascii=False).encode("utf-8")) < cap+ assert len(json.dumps(value).encode("utf-8")) > cap+ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ assert truncate_oversized_response_value(value, workflow_run_id="wr_x") is value+++def test_truncate_oversized_response_value_keeps_small_siblings_of_an_oversized_entry() -> None:+ """The UI reads downloaded_file_urls / workflow_run_id structurally — they must survive."""+ cap = 64 * 1024+ value = {+ "values": _oversized_value(cap)["values"],+ "downloaded_file_urls": ["https://example.com/a.pdf"],+ "workflow_run_id": "wr_child_1",+ }+ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = truncate_oversized_response_value(value, workflow_run_id="wr_x")+ assert result["downloaded_file_urls"] == ["https://example.com/a.pdf"]+ assert result["workflow_run_id"] == "wr_child_1"+ assert result["values"][-1]["truncated"] is True+++def test_truncate_oversized_response_value_reserves_budget_for_siblings_of_a_large_collection() -> None:+ """A large child collection must not consume the parent value's entire budget."""+ cap = 64 * 1024+ value = {+ "task_output": ["x" * 1024 for _ in range(200)],+ "downloaded_file_urls": [f"https://example.com/{index}/{'a' * 96}" for index in range(12)],+ "task_screenshot_artifact_ids": [f"artifact_{index}_{'b' * 32}" for index in range(12)],+ }+ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = truncate_oversized_response_value(value, workflow_run_id="wr_x")++ assert result["downloaded_file_urls"] == value["downloaded_file_urls"]+ assert result["task_screenshot_artifact_ids"] == value["task_screenshot_artifact_ids"]+ assert result["task_output"][-1]["truncated"] is True+ assert len(json.dumps(result, separators=(",", ":")).encode("utf-8")) <= cap+++def test_truncate_oversized_response_value_reserves_budget_for_later_list_elements() -> None:+ """The same reservation applies when a list's large first child has later metadata."""+ cap = 64 * 1024+ later_metadata = {+ "downloaded_file_urls": [f"https://example.com/{index}/{'a' * 96}" for index in range(12)],+ "task_screenshot_artifact_ids": [f"artifact_{index}_{'b' * 32}" for index in range(12)],+ }+ value = [["x" * 1024 for _ in range(200)], later_metadata]+ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = truncate_oversized_response_value(value, workflow_run_id="wr_x")++ assert result[1] == later_metadata+ assert result[0][-1]["truncated"] is True+ assert len(json.dumps(result, separators=(",", ":")).encode("utf-8")) <= cap+++def test_truncate_oversized_response_value_marks_whole_value_when_no_single_entry_is_oversized() -> None:+ """Many medium siblings — trimming per-entry can't get under the cap, so mark the whole value."""+ cap = 64 * 1024+ value = {f"k{i}": "x" * (cap // 4) for i in range(8)}+ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = truncate_oversized_response_value(value, workflow_run_id="wr_x")+ marker = result[workflow_service_module.TRUNCATION_MARKER_KEY]+ assert marker["truncated"] is True+ assert marker["reason"] == "exceeded_max_run_response_value_size"+ # Some siblings survive rather than the whole dict collapsing.+ assert 0 < marker["kept_count"] < len(value)+ assert len(json.dumps(result, separators=(",", ":")).encode("utf-8")) <= cap+++async def test_status_response_keeps_extracted_information_from_an_oversized_loop_output(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A loop output over the cap still yields every iteration's extracted_information."""+ cap = 64 * 1024+ iterations = [{"raw_page": "x" * 2048, "extracted_information": [{"row": i}]} for i in range(60)]+ response = await _build_status_response(+ monkeypatch, cap=cap, cap_output_values=True, output_value={"iterations": iterations}+ )+ assert response.outputs["sheet_read_output"]["iterations"][-1]["truncated"] is True+ assert [entry["row"] for entry in response.outputs["extracted_information"]] == list(range(60))+++def test_truncate_oversized_response_value_measures_at_compact_separator_size() -> None:+ """JSONResponse.render uses separators=(",", ":"); the defaults add ", "/": " (~12% wider)."""+ cap = 64 * 1024+ rows = [[f"cell{c}" for c in range(7)] for _ in range(1100)]+ wire = len(json.dumps(rows, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))+ padded = len(json.dumps(rows, ensure_ascii=False).encode("utf-8"))+ assert wire < cap < padded, "fixture must straddle the cap between the two encodings"+ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ assert truncate_oversized_response_value(rows, workflow_run_id="wr_x") is rows+++def test_truncate_oversized_response_value_stops_descending_past_the_depth_cap() -> None:+ """Unbounded recursion re-serializes each subtree: 400 levels cost 1.27GB and ~2s."""+ cap = 64 * 1024+ value: Any = {"blob": "x" * (cap * 2)}+ for _ in range(50):+ value = {"n": value}++ calls = 0+ real_dumps = json.dumps++ def counting_dumps(*args: Any, **kwargs: Any) -> str:+ nonlocal calls+ calls += 1+ return real_dumps(*args, **kwargs)++ with (+ patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap),+ patch("skyvern.forge.sdk.workflow.service.json.dumps", side_effect=counting_dumps),+ ):+ result = truncate_oversized_response_value(value, workflow_run_id="wr_x")++ # Depth cap of 4 => at most one measure + one trimmed-measure per level, plus leaves.+ assert calls <= 4 * (2 + 2) + 2, calls+ # Siblings are preserved down to the cap, then the remaining subtree is marked —+ # the 50-level tail below is never walked.+ marker = result["n"]["n"]["n"]["n"]+ assert marker["truncated"] is True+++async def test_get_workflow_run_timeline_caps_oversized_loop_values(monkeypatch: pytest.MonkeyPatch) -> None:+ """loop_values rides the same response and no write guard covers it."""+ now = datetime.now(timezone.utc)+ cap = 64 * 1024+ block = WorkflowRunBlock(+ workflow_run_block_id="wrb_1",+ workflow_run_id="wr_1",+ organization_id="o_1",+ block_type=BlockType.FOR_LOOP,+ loop_values=[{"row": i, "pad": "x" * 1024} for i in range(200)],+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(+ workflow_service_module.app,+ "DATABASE",+ SimpleNamespace(+ observer=SimpleNamespace(get_workflow_run_blocks=AsyncMock(return_value=[block])),+ tasks=SimpleNamespace(get_tasks_actions=AsyncMock(return_value=[])),+ ),+ )+ monkeypatch.setattr(workflow_service_module, "RUN_RESPONSE_MAX_VALUE_BYTES", cap)++ timeline = await WorkflowService().get_workflow_run_timeline(+ workflow_run_id="wr_1", organization_id="o_1", cap_output_values=True+ )++ loop_values = timeline[0].block.loop_values+ # Still a list, so the declared list[Any] | None contract holds for SDK callers.+ assert isinstance(loop_values, list)+ # 200/200, not 200/1: the run-detail page reads its iteration count off this length.+ assert len(loop_values) == 200+ assert loop_values[0] == workflow_service_module.LOOP_VALUE_TRUNCATED_PLACEHOLDER+ assert len(json.dumps(loop_values, separators=(",", ":")).encode("utf-8")) <= cap+++async def test_get_workflow_run_timeline_leaves_small_loop_values_untouched(monkeypatch: pytest.MonkeyPatch) -> None:+ now = datetime.now(timezone.utc)+ block = WorkflowRunBlock(+ workflow_run_block_id="wrb_1",+ workflow_run_id="wr_1",+ organization_id="o_1",+ block_type=BlockType.FOR_LOOP,+ loop_values=["alpha", "beta"],+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(+ workflow_service_module.app,+ "DATABASE",+ SimpleNamespace(+ observer=SimpleNamespace(get_workflow_run_blocks=AsyncMock(return_value=[block])),+ tasks=SimpleNamespace(get_tasks_actions=AsyncMock(return_value=[])),+ ),+ )+ timeline = await WorkflowService().get_workflow_run_timeline(+ workflow_run_id="wr_1", organization_id="o_1", cap_output_values=True+ )+ assert timeline[0].block.loop_values == ["alpha", "beta"]+++async def test_status_response_recaps_after_url_refresh_expands_artifact_ids(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """_refresh_output_urls turns artifact IDs into presigned URLs (~25x), so re-cap after it."""+ cap = 64 * 1024+ small_with_ids = {"task_screenshot_artifact_ids": [f"a_{i}" for i in range(50)]}+ assert len(json.dumps(small_with_ids, separators=(",", ":")).encode("utf-8")) < cap++ # _refresh_output_urls receives the whole outputs dict and substitutes in place.+ def expand(outputs: Any, **_: Any) -> Any:+ outputs["sheet_read_output"]["task_screenshots"] = ["https://example.com/" + "s" * 2048 for _ in range(50)]+ return outputs++ response = await _build_status_response(+ monkeypatch,+ cap=cap,+ cap_output_values=True,+ output_value=small_with_ids,+ refresh_output_urls=expand,+ )+ assert response.outputs["sheet_read_output"]["task_screenshots"][-1]["truncated"] is True+++def test_truncate_oversized_response_value_preserves_list_envelope() -> None:+ """A ForLoopBlock output parameter is list[list[dict]]; collapsing it loses every iteration."""+ cap = 64 * 1024+ iterations: list[list[dict[str, Any]]] = [+ [{"output_value": {"downloaded_file_urls": [f"https://example.com/{i}.pdf"]}}] for i in range(3)+ ]+ iterations[1][0]["output_value"]["blob"] = "x" * (cap * 2)+ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = truncate_oversized_response_value(iterations, workflow_run_id="wr_x")+ assert isinstance(result, list) and len(result) == 3+ # Untouched iterations keep their nested per-block data.+ assert result[0][0]["output_value"]["downloaded_file_urls"] == ["https://example.com/0.pdf"]+ assert result[2][0]["output_value"]["downloaded_file_urls"] == ["https://example.com/2.pdf"]+ assert result[1][0]["output_value"]["blob"]["truncated"] is True+++def test_truncate_oversized_response_value_preserves_nested_loop_output_envelopes() -> None:+ cap = 4 * 1024+ loop_output = [+ [+ {+ "loop_value": {"row": 1},+ "output_parameter": {"key": "child_output"},+ "output_value": {+ "extracted_information": {+ "answer": "keep me",+ "raw": "x" * (cap * 3),+ },+ "downloaded_file_urls": ["https://files.invalid/result.pdf"],+ "workflow_run_id": "wr_child",+ "outputs": {+ "nested_trigger_output": {+ "workflow_run_id": "wr_grandchild",+ "downloaded_file_urls": ["https://files.invalid/child.pdf"],+ "raw": "y" * (cap * 3),+ }+ },+ },+ }+ ]+ ]++ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = truncate_oversized_response_value(loop_output, workflow_run_id="wr_x")++ output_value = result[0][0]["output_value"]+ assert output_value["extracted_information"]["answer"] == "keep me"+ assert output_value["extracted_information"]["raw"]["truncated"] is True+ assert output_value["downloaded_file_urls"] == ["https://files.invalid/result.pdf"]+ assert output_value["workflow_run_id"] == "wr_child"+ nested_output = output_value["outputs"]["nested_trigger_output"]+ assert nested_output["workflow_run_id"] == "wr_grandchild"+ assert nested_output["downloaded_file_urls"] == ["https://files.invalid/child.pdf"]+ assert nested_output["raw"]["truncated"] is True+ assert len(json.dumps(result, separators=(",", ":")).encode("utf-8")) <= cap+++def test_truncate_oversized_response_value_reserves_loop_envelope_overhead() -> None:+ """Small loop metadata must not crowd an otherwise-under-cap output_value out."""+ cap = 4 * 1024+ entry = {+ "loop_value": {"row": 1, "metadata": "m" * 200},+ "output_parameter": {"key": "child_output", "description": "p" * 200},+ "output_value": {"answer": "keep me", "blob": "x" * 3600},+ }+ value = [[entry]]+ assert len(json.dumps(entry["output_value"], separators=(",", ":")).encode("utf-8")) < cap+ assert len(json.dumps(value, separators=(",", ":")).encode("utf-8")) > cap++ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = truncate_oversized_response_value(value, workflow_run_id="wr_x")++ capped_entry = result[0][0]+ assert capped_entry["loop_value"]["row"] == 1+ assert capped_entry["output_parameter"]["key"] == "child_output"+ assert capped_entry["output_value"]["answer"] == "keep me"+ assert capped_entry["output_value"]["blob"]["truncated"] is True+ assert len(json.dumps(result, separators=(",", ":")).encode("utf-8")) <= cap+++def test_truncate_oversized_response_value_bounds_nested_loop_envelope_depth() -> None:+ cap = 4 * 1024+ nested_output: dict[str, Any] = {"blob": "x" * (cap * 2)}+ for index in range(12):+ nested_output = {+ "loop_value": index,+ "output_parameter": {"key": f"nested_{index}"},+ "output_value": nested_output,+ }++ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = truncate_oversized_response_value([[nested_output]], workflow_run_id="wr_x")++ assert json.dumps(result, separators=(",", ":")).count('"output_value"') < 12+ assert '"truncated":true' in json.dumps(result, separators=(",", ":"))+++async def test_get_workflow_run_timeline_caps_navigation_payload_and_data_schema(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Both are unbounded jsonb copied from the task and ride the same response."""+ now = datetime.now(timezone.utc)+ cap = 64 * 1024+ block = WorkflowRunBlock(+ workflow_run_block_id="wrb_1",+ workflow_run_id="wr_1",+ organization_id="o_1",+ block_type=BlockType.TASK,+ navigation_payload={"rows": ["x" * 1024 for _ in range(200)]},+ data_schema={"rows": ["y" * 1024 for _ in range(200)]},+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(+ workflow_service_module.app,+ "DATABASE",+ SimpleNamespace(+ observer=SimpleNamespace(get_workflow_run_blocks=AsyncMock(return_value=[block])),+ tasks=SimpleNamespace(get_tasks_actions=AsyncMock(return_value=[])),+ ),+ )+ monkeypatch.setattr(workflow_service_module, "RUN_RESPONSE_MAX_VALUE_BYTES", cap)++ timeline = await WorkflowService().get_workflow_run_timeline(+ workflow_run_id="wr_1", organization_id="o_1", cap_output_values=True+ )++ assert timeline[0].block.navigation_payload["rows"][-1]["truncated"] is True+ assert timeline[0].block.data_schema["rows"][-1]["truncated"] is True+++def test_truncate_oversized_response_value_bails_out_before_serializing_every_element() -> None:+ """Many-small-rows can never fit; stop once the kept elements alone clear the cap."""+ cap = 64 * 1024+ rows = [{"row": i, "pad": "x" * 512} for i in range(4000)]++ calls = 0+ real_dumps = json.dumps++ def counting_dumps(*args: Any, **kwargs: Any) -> str:+ nonlocal calls+ calls += 1+ return real_dumps(*args, **kwargs)++ with (+ patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap),+ patch("skyvern.forge.sdk.workflow.service.json.dumps", side_effect=counting_dumps),+ ):+ result = truncate_oversized_response_value(rows, workflow_run_id="wr_x")++ assert result[-1]["truncated"] is True+ # Bails after ~cap/512 elements rather than walking all 4000 and re-serializing the copy.+ assert calls < 500, calls+++def test_truncate_oversized_response_value_counts_dict_keys_and_separators() -> None:+ """Summing child values alone under-counts a key-heavy dict by ~half."""+ cap = 64 * 1024+ # Children total under the cap; keys plus separators push the real payload over it.+ value = {f"{'k' * 40}{i:04d}": "v" * 20 for i in range(1200)}+ children_only = sum(len(json.dumps(v, separators=(",", ":")).encode("utf-8")) for v in value.values())+ real = len(json.dumps(value, separators=(",", ":")).encode("utf-8"))+ assert children_only < cap < real, (children_only, cap, real)++ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = truncate_oversized_response_value(value, workflow_run_id="wr_x")++ # Whatever comes back must actually fit on the wire.+ assert len(json.dumps(result, separators=(",", ":")).encode("utf-8")) <= cap+++async def test_get_workflow_run_timeline_caps_current_value(monkeypatch: pytest.MonkeyPatch) -> None:+ """A loop child block persists str(loop_over_value); a multi-MB item lands here in full."""+ now = datetime.now(timezone.utc)+ cap = 4 * 1024+ block = WorkflowRunBlock(+ workflow_run_block_id="wrb_1",+ workflow_run_id="wr_1",+ organization_id="o_1",+ block_type=BlockType.TASK,+ current_value="z" * (cap * 4),+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(+ workflow_service_module.app,+ "DATABASE",+ SimpleNamespace(+ observer=SimpleNamespace(get_workflow_run_blocks=AsyncMock(return_value=[block])),+ tasks=SimpleNamespace(get_tasks_actions=AsyncMock(return_value=[])),+ ),+ )+ monkeypatch.setattr(workflow_service_module, "RUN_RESPONSE_MAX_VALUE_BYTES", cap)++ timeline = await WorkflowService().get_workflow_run_timeline(+ workflow_run_id="wr_1", organization_id="o_1", cap_output_values=True+ )++ current_value = timeline[0].block.current_value+ # Still a str, so the declared str | None contract holds, and it identifies the iteration.+ assert isinstance(current_value, str)+ assert current_value.startswith("zzz")+ assert "[truncated" in current_value+++# ---------- Which surfaces bound their output values ----------+++def test_only_the_app_user_agent_caps_run_response_values() -> None:+ """The app renders outputs with JSON.stringify on the main thread; nothing else needs a bound."""+ assert caps_run_response_values(SKYVERN_UI_USER_AGENT) is True+ # SDK/webhook/replay callers and MCP (bounded at its own ceiling) keep full fidelity.+ assert caps_run_response_values(None) is False+ assert caps_run_response_values("skyvern-mcp") is False+ assert caps_run_response_values("python-httpx/0.27") is False+++async def test_get_workflow_run_timeline_leaves_blocks_untouched_for_api_callers(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """An SDK caller on get_run_timeline gets the stored block output in full."""+ now = datetime.now(timezone.utc)+ cap = 64 * 1024+ stored_output = {"values": ["x" * 1024 for _ in range(200)]}+ block = WorkflowRunBlock(+ workflow_run_block_id="wrb_1",+ workflow_run_id="wr_1",+ organization_id="o_1",+ block_type=BlockType.GOOGLE_SHEETS_READ,+ output=stored_output,+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(+ workflow_service_module.app,+ "DATABASE",+ SimpleNamespace(+ observer=SimpleNamespace(get_workflow_run_blocks=AsyncMock(return_value=[block])),+ tasks=SimpleNamespace(get_tasks_actions=AsyncMock(return_value=[])),+ ),+ )+ monkeypatch.setattr(workflow_service_module, "RUN_RESPONSE_MAX_VALUE_BYTES", cap)++ timeline = await WorkflowService().get_workflow_run_timeline(workflow_run_id="wr_1", organization_id="o_1")++ assert timeline[0].block.output == stored_output+++def test_capped_loop_values_keeps_placeholder_list_under_the_cap() -> None:+ """At ~150k iterations even one placeholder each overruns the cap."""+ cap = 64 * 1024+ placeholder_cost = len(json.dumps(workflow_service_module.LOOP_VALUE_TRUNCATED_PLACEHOLDER)) + 1+ count = (cap // placeholder_cost) + 500+ loop_values = [{"row": i, "pad": "x" * 64} for i in range(count)]++ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = workflow_service_module._capped_loop_values(loop_values, workflow_run_id="wr_x")++ assert result is not None+ assert len(json.dumps(result, separators=(",", ":")).encode("utf-8")) <= cap+ # The count moves into bounded metadata once it can no longer be the list length.+ assert result[0]["original_count"] == count+++def test_capped_response_text_measures_at_json_wire_size() -> None:+ """JSON escaping inflates quotes and control chars; a raw byte count understates it ~2x."""+ cap = 64 * 1024+ # Under the cap as raw UTF-8, over it once JSON escapes every character.+ value = '"' * (cap - 1000)+ assert len(value.encode("utf-8")) < cap < len(json.dumps(value).encode("utf-8"))++ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = workflow_service_module.truncate_oversized_response_text(value)++ assert isinstance(result, str)+ assert len(json.dumps(result).encode("utf-8")) <= cap+ assert "[truncated" in result+++def test_truncate_oversized_response_value_keeps_rows_from_a_marginally_oversized_table() -> None:+ """A table just over the cap must still render, not vanish — the freeze was at 16.6MB."""+ cap = 64 * 1024+ row = [f"cell{c}" for c in range(7)]+ # Size the table a few percent over the cap, which is the case that used to vanish.+ per_row = len(json.dumps(row, separators=(",", ":")).encode("utf-8")) + 1+ count = int(cap / per_row * 1.05)+ rows = [list(row) for _ in range(count)]+ assert len(json.dumps(rows, separators=(",", ":")).encode("utf-8")) > cap++ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = truncate_oversized_response_value(rows, workflow_run_id="wr_x")++ marker = result[-1]+ assert marker["original_count"] == count+ # The overwhelming majority of rows survive rather than the table collapsing.+ assert marker["kept_count"] > count * 0.9+ assert result[0] == rows[0]+ assert len(json.dumps(result, separators=(",", ":")).encode("utf-8")) <= cap+++def test_truncate_oversized_response_value_never_drops_entries_without_a_marker() -> None:+ """The loop stops a marker's width below the cap; that gap must not read as 'complete'."""+ cap = 64 * 1024+ for row_size in (256, 512, 1024, 2048):+ rows = [{"pad": "x" * row_size} for _ in range(400)]+ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = truncate_oversized_response_value(rows, workflow_run_id="wr_x")+ if isinstance(result, list) and len(result) < len(rows):+ assert result[-1].get("truncated") is True, f"silent drop at row_size={row_size}"+++async def test_get_task_v2_caps_output_for_the_app_only(monkeypatch: pytest.MonkeyPatch) -> None:+ """RunRouter resolves a tsk_v2_* URL through this endpoint before redirecting."""+ now = datetime.now(timezone.utc)+ cap = 64 * 1024+ stored_output = {"rows": ["x" * 1024 for _ in range(200)]}+ task_v2 = SimpleNamespace(+ observer_cruise_id="tsk_v2_1",+ output=stored_output,+ model_copy=lambda update: SimpleNamespace(+ observer_cruise_id="tsk_v2_1",+ output=update["output"],+ model_dump=lambda by_alias: {"output": update["output"]},+ ),+ model_dump=lambda by_alias: {"output": stored_output},+ )+ monkeypatch.setattr(agent_protocol.task_v2_service, "get_task_v2", AsyncMock(return_value=task_v2), raising=False)+ monkeypatch.setattr(workflow_service_module, "RUN_RESPONSE_MAX_VALUE_BYTES", cap)+ organization = SimpleNamespace(organization_id="o_1")+ assert now is not None++ from_app = await agent_protocol.get_task_v2(+ task_id="tsk_v2_1", organization=organization, x_user_agent=SKYVERN_UI_USER_AGENT+ )+ assert from_app["output"]["rows"][-1]["truncated"] is True++ from_sdk = await agent_protocol.get_task_v2(task_id="tsk_v2_1", organization=organization, x_user_agent=None)+ assert from_sdk["output"] == stored_output+++async def test_get_task_v1_caps_extracted_information_for_the_app_only(monkeypatch: pytest.MonkeyPatch) -> None:+ """A tsk_* run URL reaches this direct task-v1 endpoint before the UI renders it."""+ cap = 64 * 1024+ stored_output = {"rows": ["x" * 1024 for _ in range(200)]}++ def model_copy(update: dict[str, Any]) -> SimpleNamespace:+ return SimpleNamespace(+ task_id="tsk_1",+ extracted_information=update["extracted_information"],+ failure_reason=update["failure_reason"],+ )++ task_response = SimpleNamespace(+ task_id="tsk_1",+ extracted_information=stored_output,+ failure_reason="f" * (cap * 2),+ model_copy=model_copy,+ )+ monkeypatch.setattr(+ agent_protocol.task_v1_service,+ "get_task_v1_response",+ AsyncMock(return_value=task_response),+ )+ monkeypatch.setattr(agent_protocol.analytics, "capture", MagicMock())+ monkeypatch.setattr(workflow_service_module, "RUN_RESPONSE_MAX_VALUE_BYTES", cap)+ organization = SimpleNamespace(organization_id="o_1")++ from_app = await agent_protocol.get_task_v1(+ task_id="tsk_1", current_org=organization, x_user_agent=SKYVERN_UI_USER_AGENT+ )+ assert from_app.extracted_information["rows"][-1]["truncated"] is True+ assert from_app.failure_reason.endswith("chars]")+ assert len(json.dumps(from_app.failure_reason).encode("utf-8")) <= cap++ from_sdk = await agent_protocol.get_task_v1(task_id="tsk_1", current_org=organization, x_user_agent=None)+ assert from_sdk is task_response+ assert from_sdk.extracted_information == stored_output+ assert from_sdk.failure_reason == task_response.failure_reason+++# Fields whose type could hold unbounded content but which are bounded by construction.+_EXEMPT_BLOCK_FIELDS = {+ "workflow_run_block_id",+ "block_workflow_run_id",+ "workflow_run_id",+ "organization_id",+ "parent_workflow_run_block_id",+ "task_id",+ "label",+ "status",+ "executed_branch_id",+ "executed_branch_next_block",+ "error_codes", # enum codes+ "loop_values", # capped separately, count-preserving+ "actions", # capped per-action as they are hydrated+ "script_run", # fixed-shape record+}+++def test_timeline_block_field_coverage() -> None:+ """A new unbounded field on the model must be capped or explicitly exempted.++ This guard exists because the cap was extended one reviewer comment at a time across+ several rounds; without it the next field added is silently uncapped.+ """+ capped = (+ set(workflow_service_module.UNBOUNDED_BLOCK_JSON_FIELDS)+ | set(workflow_service_module.UNBOUNDED_BLOCK_TEXT_FIELDS)+ | set(workflow_service_module.UNBOUNDED_BLOCK_TEXT_LIST_FIELDS)+ )+ unbounded_types = set()+ for name, field in WorkflowRunBlock.model_fields.items():+ annotation = str(field.annotation)+ if "str" in annotation or "dict" in annotation or "list" in annotation or "Any" in annotation:+ unbounded_types.add(name)++ uncovered = unbounded_types - capped - _EXEMPT_BLOCK_FIELDS+ assert not uncovered, (+ f"WorkflowRunBlock fields can hold unbounded content but are neither capped nor exempt: "+ f"{sorted(uncovered)}. Add them to the matching UNBOUNDED_BLOCK field group, "+ f"or to _EXEMPT_BLOCK_FIELDS with a reason."+ )+ # Guard against the lists drifting to name fields that no longer exist.+ assert not (capped - set(WorkflowRunBlock.model_fields)), "capped list names a non-existent field"+++async def test_get_workflow_run_timeline_caps_unbounded_text_fields(monkeypatch: pytest.MonkeyPatch) -> None:+ """Prompts, email bodies and human-interaction instructions ride the same response."""+ now = datetime.now(timezone.utc)+ cap = 4 * 1024+ block = WorkflowRunBlock(+ workflow_run_block_id="wrb_1",+ workflow_run_id="wr_1",+ organization_id="o_1",+ block_type=BlockType.TASK,+ prompt="p" * (cap * 3),+ body="b" * (cap * 3),+ instructions="i" * (cap * 3),+ failure_reason="f" * (cap * 3),+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(+ workflow_service_module.app,+ "DATABASE",+ SimpleNamespace(+ observer=SimpleNamespace(get_workflow_run_blocks=AsyncMock(return_value=[block])),+ tasks=SimpleNamespace(get_tasks_actions=AsyncMock(return_value=[])),+ ),+ )+ monkeypatch.setattr(workflow_service_module, "RUN_RESPONSE_MAX_VALUE_BYTES", cap)++ timeline = await WorkflowService().get_workflow_run_timeline(+ workflow_run_id="wr_1", organization_id="o_1", cap_output_values=True+ )++ capped_block = timeline[0].block+ for field in ("prompt", "body", "instructions", "failure_reason"):+ value = getattr(capped_block, field)+ assert isinstance(value, str), field+ assert "[truncated" in value, field+ assert len(json.dumps(value).encode("utf-8")) <= cap, field+++def test_capped_text_list_keeps_every_element_a_string() -> None:+ """recipients/attachments are list[str]; a marker dict inside them breaks the type."""+ cap = 4 * 1024+ values = ["a" * (cap * 2) + "@example.com", "[email protected]"]+ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = workflow_service_module._capped_text_list(values, workflow_run_id="wr_x")+ assert result is not None+ assert all(isinstance(v, str) for v in result), [type(v).__name__ for v in result]+ assert len(json.dumps(result, separators=(",", ":")).encode("utf-8")) <= cap+++def test_capped_text_list_marker_is_a_string_when_many_entries_drop() -> None:+ cap = 4 * 1024+ values = [f"{'x' * 200}{i}@example.com" for i in range(200)]+ with patch("skyvern.forge.sdk.workflow.service.RUN_RESPONSE_MAX_VALUE_BYTES", cap):+ result = workflow_service_module._capped_text_list(values, workflow_run_id="wr_x")+ assert result is not None+ assert all(isinstance(v, str) for v in result)+ assert "truncated" in result[-1]+ assert len(json.dumps(result, separators=(",", ":")).encode("utf-8")) <= cap+++def test_timeline_block_list_fields_never_receive_a_marker_dict() -> None:+ """Regression: the JSON trim would have put a dict into these typed list[str] fields."""+ for field in workflow_service_module.UNBOUNDED_BLOCK_TEXT_LIST_FIELDS:+ annotation = str(WorkflowRunBlock.model_fields[field].annotation)+ assert "str" in annotation and "dict" not in annotation, f"{field}: {annotation}"+ assert field not in workflow_service_module.UNBOUNDED_BLOCK_JSON_FIELDS+++async def test_get_workflow_run_timeline_caps_action_text(monkeypatch: pytest.MonkeyPatch) -> None:+ now = datetime.now(timezone.utc)+ cap = 4 * 1024+ block = WorkflowRunBlock(+ workflow_run_block_id="wrb_1",+ workflow_run_id="wr_1",+ organization_id="o_1",+ block_type=BlockType.TASK,+ task_id="tsk_1",+ created_at=now,+ modified_at=now,+ )+ action = Action(+ action_type=ActionType.INPUT_TEXT,+ task_id="tsk_1",+ response="r" * (cap * 3),+ text="t" * (cap * 3),+ )+ monkeypatch.setattr(+ workflow_service_module.app,+ "DATABASE",+ SimpleNamespace(+ observer=SimpleNamespace(get_workflow_run_blocks=AsyncMock(return_value=[block])),+ tasks=SimpleNamespace(get_tasks_actions=AsyncMock(return_value=[action])),+ ),+ )+ monkeypatch.setattr(workflow_service_module, "RUN_RESPONSE_MAX_VALUE_BYTES", cap)++ timeline = await WorkflowService().get_workflow_run_timeline(+ workflow_run_id="wr_1", organization_id="o_1", cap_output_values=True+ )++ capped_action = timeline[0].block.actions[0]+ for field in ("response", "text"):+ value = getattr(capped_action, field)+ assert isinstance(value, str), field+ assert "[truncated" in value, field+ assert len(json.dumps(value).encode("utf-8")) <= cap, field+++async def test_get_thought_timelines_caps_text_fields_when_opted_in(monkeypatch: pytest.MonkeyPatch) -> None:+ now = datetime.now(timezone.utc)+ cap = 4 * 1024+ oversized_text = "t" * (cap * 3)+ thought = Thought(+ thought_id="th_1",+ task_id="tsk_v2_1",+ organization_id="o_1",+ **dict.fromkeys(("user_input", "observation", "thought", "answer"), oversized_text),+ output={"value": "o" * (cap * 3)},+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(+ task_v2_service.app,+ "DATABASE",+ SimpleNamespace(observer=SimpleNamespace(get_thoughts=AsyncMock(return_value=[thought]))),+ )+ monkeypatch.setattr(workflow_service_module, "RUN_RESPONSE_MAX_VALUE_BYTES", cap)++ capped = await task_v2_service.get_thought_timelines(+ task_v2_id="tsk_v2_1", organization_id="o_1", cap_output_values=True+ )+ capped_thought = capped[0].thought+ assert capped_thought is not None+ for field in ("user_input", "observation", "thought", "answer"):+ value = getattr(capped_thought, field)+ assert isinstance(value, str) and "[truncated" in value, field+ assert len(json.dumps(value).encode("utf-8")) <= cap, field+ assert capped_thought.output["value"]["truncated"] is True+++async def test_get_workflow_run_timeline_preserves_string_list_field_types(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ now = datetime.now(timezone.utc)+ cap = 4 * 1024+ block = WorkflowRunBlock(+ workflow_run_block_id="wrb_1",+ workflow_run_id="wr_1",+ organization_id="o_1",+ block_type=BlockType.SEND_EMAIL,+ recipients=[f"recipient-{i}@example.invalid" for i in range(500)],+ attachments=[f"https://files.invalid/{i}/attachment.pdf" for i in range(500)],+ created_at=now,+ modified_at=now,+ )+ monkeypatch.setattr(+ workflow_service_module.app,+ "DATABASE",+ SimpleNamespace(+ observer=SimpleNamespace(get_workflow_run_blocks=AsyncMock(return_value=[block])),+ tasks=SimpleNamespace(get_tasks_actions=AsyncMock(return_value=[])),+ ),+ )+ monkeypatch.setattr(workflow_service_module, "RUN_RESPONSE_MAX_VALUE_BYTES", cap)++ timeline = await WorkflowService().get_workflow_run_timeline(+ workflow_run_id="wr_1", organization_id="o_1", cap_output_values=True+ )++ capped_block = timeline[0].block+ for field in ("recipients", "attachments"):+ values = getattr(capped_block, field)+ assert isinstance(values, list), field+ assert all(isinstance(value, str) for value in values), field+ assert "[truncated" in values[-1], field+ assert len(json.dumps(values, separators=(",", ":")).encode("utf-8")) <= cap, fielddiff --git a/tests/unit/test_pending_script_promotion.py b/tests/unit/test_pending_script_promotion.pynew file mode 100644index 000000000..87e35683e--- /dev/null+++ b/tests/unit/test_pending_script_promotion.py@@ -0,0 +1,377 @@+"""+Tests for pending-script promotion and per-block mint convergence (SKY-13659).++Defect A: the end-of-run finalize looked up only published scripts, missed the+pending script the same run minted per-block, and created a duplicate script row+with identical content.++Defect B: the per-block pending-mint path counted non-cacheable blocks (goto/code)+as "missing" forever, so code/goto-only workflows regenerated the full script after+every block instead of once.+"""++import asyncio+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++from skyvern.forge import app+from skyvern.forge.sdk.core import skyvern_context+from skyvern.forge.sdk.core.skyvern_context import SkyvernContext+from skyvern.forge.sdk.workflow.service import WorkflowService+from skyvern.schemas.scripts import ScriptStatus+from skyvern.schemas.workflows import BlockStatus, BlockType+from skyvern.services import workflow_script_service+++def make_workflow(block_types: list[BlockType]) -> SimpleNamespace:+ blocks = [SimpleNamespace(block_type=block_type, label=f"block_{i}") for i, block_type in enumerate(block_types)]+ return SimpleNamespace(+ organization_id="o_1",+ workflow_id="w_1",+ workflow_permanent_id="wpid_1",+ cache_key="",+ generate_script_on_terminal=False,+ workflow_definition=SimpleNamespace(blocks=blocks),+ )+++def make_workflow_run() -> SimpleNamespace:+ return SimpleNamespace(workflow_run_id="wr_1", organization_id="o_1", code_gen=None, run_with=None)+++def make_scripts_db(pending_row: SimpleNamespace | None) -> MagicMock:+ scripts = MagicMock()+ scripts.get_workflow_script = AsyncMock(return_value=pending_row)+ scripts.create_workflow_script = AsyncMock()+ scripts.update_workflow_script_status = AsyncMock()++ async def create_script(+ organization_id: str,+ run_id: str | None = None,+ script_id: str | None = None,+ version: int | None = None,+ ) -> SimpleNamespace:+ return SimpleNamespace(+ script_id=script_id or "s_new",+ script_revision_id=f"sr_{script_id or 'new'}_v{version or 1}",+ version=version or 1,+ )++ scripts.create_script = AsyncMock(side_effect=create_script)+ scripts.get_script = AsyncMock(+ return_value=SimpleNamespace(script_id="s_pending", script_revision_id="sr_pending", version=3)+ )+ scripts.get_script_version_stats = AsyncMock(return_value={"s_pending": (3, 3)})+ scripts.get_script_files = AsyncMock(return_value=["main.py"])+ scripts.get_script_blocks_by_script_revision_id = AsyncMock(return_value=["block"])+ scripts.soft_delete_script_by_revision = AsyncMock()+ return scripts+++class TestCacheableMissingLabels:+ def test_excludes_non_cacheable_block_types(self) -> None:+ blocks = [+ {"label": "open_target", "block_type": BlockType.GOTO_URL},+ {"label": "smoke_page_evaluate", "block_type": BlockType.CODE},+ {"label": "fill_form", "block_type": BlockType.TASK},+ ]+ missing = workflow_script_service.cacheable_missing_labels(blocks, cached_labels=set())+ assert missing == {"fill_form"}++ def test_accepts_plain_string_block_types(self) -> None:+ blocks = [+ {"label": "open_target", "block_type": "goto_url"},+ {"label": "fill_form", "block_type": "task"},+ ]+ missing = workflow_script_service.cacheable_missing_labels(blocks, cached_labels=set())+ assert missing == {"fill_form"}++ def test_empty_when_cacheable_blocks_already_cached(self) -> None:+ blocks = [{"label": "fill_form", "block_type": BlockType.TASK}]+ assert workflow_script_service.cacheable_missing_labels(blocks, cached_labels={"fill_form"}) == set()+++class TestPendingMintSkipsNonCacheableWorkflows:+ async def _run_hook(self, workflow: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> list:+ monkeypatch.setattr(+ app,+ "EXPERIMENTATION_PROVIDER",+ SimpleNamespace(is_feature_enabled_cached=AsyncMock(return_value=False)),+ raising=False,+ )+ calls: list = []++ async def record(wf: object, run: object) -> None:+ calls.append(run)++ stub_self = SimpleNamespace(_do_generate_pending_script=record)+ block_result = SimpleNamespace(status=BlockStatus.completed)+ skyvern_context.set(SkyvernContext())+ try:+ await WorkflowService._generate_pending_script_for_block(+ stub_self, workflow, make_workflow_run(), block_result+ )+ await asyncio.sleep(0)+ finally:+ skyvern_context.reset()+ return calls++ @pytest.mark.asyncio+ async def test_skips_when_workflow_has_no_cacheable_blocks(self, monkeypatch: pytest.MonkeyPatch) -> None:+ workflow = make_workflow([BlockType.GOTO_URL, BlockType.CODE, BlockType.CODE])+ calls = await self._run_hook(workflow, monkeypatch)+ assert calls == []++ @pytest.mark.asyncio+ async def test_still_mints_when_workflow_has_cacheable_blocks(self, monkeypatch: pytest.MonkeyPatch) -> None:+ workflow = make_workflow([BlockType.GOTO_URL, BlockType.TASK])+ calls = await self._run_hook(workflow, monkeypatch)+ assert len(calls) == 1+++class TestRecordWorkflowScriptMapping:+ @pytest.mark.asyncio+ async def test_publish_promotes_existing_pending_row_for_same_script(self, monkeypatch: pytest.MonkeyPatch) -> None:+ pending_row = SimpleNamespace(workflow_script_id="ws_1", script_id="s_pending")+ scripts = make_scripts_db(pending_row)+ monkeypatch.setattr(app, "DATABASE", SimpleNamespace(scripts=scripts), raising=False)++ await workflow_script_service._record_workflow_script_mapping(+ workflow=make_workflow([BlockType.CODE]),+ workflow_run=make_workflow_run(),+ script=SimpleNamespace(script_id="s_pending", script_revision_id="sr_pending", version=1),+ rendered_cache_key_value="default:site",+ pending=False,+ )++ scripts.update_workflow_script_status.assert_awaited_once_with(+ workflow_script_id="ws_1",+ organization_id="o_1",+ status=ScriptStatus.published,+ )+ scripts.create_workflow_script.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_publish_creates_row_when_no_pending_exists(self, monkeypatch: pytest.MonkeyPatch) -> None:+ scripts = make_scripts_db(pending_row=None)+ monkeypatch.setattr(app, "DATABASE", SimpleNamespace(scripts=scripts), raising=False)++ await workflow_script_service._record_workflow_script_mapping(+ workflow=make_workflow([BlockType.CODE]),+ workflow_run=make_workflow_run(),+ script=SimpleNamespace(script_id="s_new", script_revision_id="sr_new", version=1),+ rendered_cache_key_value="default:site",+ pending=False,+ )++ scripts.create_workflow_script.assert_awaited_once()+ assert scripts.create_workflow_script.await_args.kwargs["status"] == ScriptStatus.published+ scripts.update_workflow_script_status.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_publish_creates_row_when_pending_points_at_different_script(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ pending_row = SimpleNamespace(workflow_script_id="ws_1", script_id="s_other")+ scripts = make_scripts_db(pending_row)+ monkeypatch.setattr(app, "DATABASE", SimpleNamespace(scripts=scripts), raising=False)++ await workflow_script_service._record_workflow_script_mapping(+ workflow=make_workflow([BlockType.CODE]),+ workflow_run=make_workflow_run(),+ script=SimpleNamespace(script_id="s_new", script_revision_id="sr_new", version=1),+ rendered_cache_key_value="default:site",+ pending=False,+ )++ scripts.create_workflow_script.assert_awaited_once()+ scripts.update_workflow_script_status.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_pending_creates_row_once(self, monkeypatch: pytest.MonkeyPatch) -> None:+ scripts = make_scripts_db(pending_row=None)+ monkeypatch.setattr(app, "DATABASE", SimpleNamespace(scripts=scripts), raising=False)++ await workflow_script_service._record_workflow_script_mapping(+ workflow=make_workflow([BlockType.CODE]),+ workflow_run=make_workflow_run(),+ script=SimpleNamespace(script_id="s_pending", script_revision_id="sr_pending", version=1),+ rendered_cache_key_value="default:site",+ pending=True,+ )+ scripts.create_workflow_script.assert_awaited_once()+ assert scripts.create_workflow_script.await_args.kwargs["status"] == ScriptStatus.pending++ @pytest.mark.asyncio+ async def test_pending_does_not_duplicate_existing_row(self, monkeypatch: pytest.MonkeyPatch) -> None:+ pending_row = SimpleNamespace(workflow_script_id="ws_1", script_id="s_pending")+ scripts = make_scripts_db(pending_row)+ monkeypatch.setattr(app, "DATABASE", SimpleNamespace(scripts=scripts), raising=False)++ await workflow_script_service._record_workflow_script_mapping(+ workflow=make_workflow([BlockType.CODE]),+ workflow_run=make_workflow_run(),+ script=SimpleNamespace(script_id="s_pending", script_revision_id="sr_pending", version=1),+ rendered_cache_key_value="default:site",+ pending=True,+ )+ scripts.create_workflow_script.assert_not_awaited()+++class TestPendingMintUsesOriginalRevision:+ """Per-block mints must keep writing to their original pending revision.++ ``script_files`` is unique on ``(script_revision_id, file_path)``. A straggler+ must never resolve the newer published revision for the same script id.+ """++ @pytest.mark.asyncio+ async def test_uses_context_revision_after_finalize_mints_newer_version(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ scripts = MagicMock()+ original_revision = SimpleNamespace(script_id="s_pending", script_revision_id="sr_pending", version=1)+ scripts.get_script_revision = AsyncMock(return_value=original_revision)+ scripts.get_script = AsyncMock(+ return_value=SimpleNamespace(script_id="s_pending", script_revision_id="sr_published", version=2)+ )+ scripts.get_workflow_script = AsyncMock(return_value=None)+ scripts.create_script = AsyncMock()+ monkeypatch.setattr(app, "DATABASE", SimpleNamespace(scripts=scripts), raising=False)+ monkeypatch.setattr(+ workflow_script_service,+ "get_workflow_script",+ AsyncMock(return_value=(None, "default:site", False)),+ )+ generate_mock = AsyncMock()+ monkeypatch.setattr(workflow_script_service, "generate_workflow_script", generate_mock)++ skyvern_context.set(SkyvernContext(script_id="s_pending", script_revision_id="sr_pending"))+ try:+ await workflow_script_service.generate_or_update_pending_workflow_script(+ workflow_run=make_workflow_run(),+ workflow=make_workflow([BlockType.TASK]),+ )+ finally:+ skyvern_context.reset()++ minted_script = generate_mock.await_args.kwargs["script"]+ assert minted_script.script_revision_id == "sr_pending"+ scripts.get_script_revision.assert_awaited_once_with(+ script_revision_id="sr_pending",+ organization_id="o_1",+ )+ scripts.get_script.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_does_not_recreate_pending_mapping_after_finalize_promotes_it(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ scripts = MagicMock()+ published_mapping = SimpleNamespace(+ workflow_script_id="ws_1",+ script_id="s_pending",+ status=ScriptStatus.published,+ )++ async def get_mapping(**kwargs: object) -> SimpleNamespace | None:+ if kwargs["statuses"] == [ScriptStatus.pending, ScriptStatus.published]:+ return published_mapping+ return None++ scripts.get_workflow_script = AsyncMock(side_effect=get_mapping)+ scripts.create_workflow_script = AsyncMock()+ monkeypatch.setattr(app, "DATABASE", SimpleNamespace(scripts=scripts), raising=False)++ await workflow_script_service._record_workflow_script_mapping(+ workflow=make_workflow([BlockType.TASK]),+ workflow_run=make_workflow_run(),+ script=SimpleNamespace(script_id="s_pending", script_revision_id="sr_pending", version=1),+ rendered_cache_key_value="default:site",+ pending=True,+ )++ scripts.create_workflow_script.assert_not_awaited()+++class TestFinalizeReusesPendingScript:+ def _patch_common(self, monkeypatch: pytest.MonkeyPatch, scripts: MagicMock) -> AsyncMock:+ monkeypatch.setattr(app, "DATABASE", SimpleNamespace(scripts=scripts), raising=False)+ monkeypatch.setattr(app, "ARTIFACT_MANAGER", SimpleNamespace(upload_aiotasks_map={}), raising=False)+ monkeypatch.setattr(+ workflow_script_service,+ "get_workflow_script",+ AsyncMock(return_value=(None, "default:site", False)),+ )+ generate_mock = AsyncMock()+ monkeypatch.setattr(workflow_script_service, "generate_workflow_script", generate_mock)+ return generate_mock++ @pytest.mark.asyncio+ async def test_first_run_finalize_reuses_pending_script_id_without_minting_duplicate(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ pending_row = SimpleNamespace(workflow_script_id="ws_1", script_id="s_pending")+ scripts = make_scripts_db(pending_row)+ generate_mock = self._patch_common(monkeypatch, scripts)++ await WorkflowService().generate_script_if_needed(+ workflow=make_workflow([BlockType.GOTO_URL, BlockType.CODE]),+ workflow_run=make_workflow_run(),+ )++ assert generate_mock.await_args.kwargs["script"].script_id == "s_pending"+ assert scripts.create_script.await_args.kwargs["script_id"] == "s_pending"++ @pytest.mark.asyncio+ async def test_finalize_writes_to_a_fresh_revision_not_the_pending_one(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """script_files is unique on (script_revision_id, file_path) and create_script_file+ conflict-noops, so regenerating into the pending revision would keep the stale+ pending main.py — which the in-flight per-block mint can still overwrite."""+ pending_row = SimpleNamespace(workflow_script_id="ws_1", script_id="s_pending")+ scripts = make_scripts_db(pending_row)+ generate_mock = self._patch_common(monkeypatch, scripts)++ await WorkflowService().generate_script_if_needed(+ workflow=make_workflow([BlockType.GOTO_URL, BlockType.CODE]),+ workflow_run=make_workflow_run(),+ )++ minted = generate_mock.await_args.kwargs["script"]+ assert minted.script_revision_id != "sr_pending"+ assert scripts.create_script.await_args.kwargs["version"] == 4++ @pytest.mark.asyncio+ async def test_finalize_does_not_pass_pending_revision_as_cached_source(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ pending_row = SimpleNamespace(workflow_script_id="ws_1", script_id="s_pending")+ scripts = make_scripts_db(pending_row)+ generate_mock = self._patch_common(monkeypatch, scripts)++ await WorkflowService().generate_script_if_needed(+ workflow=make_workflow([BlockType.GOTO_URL, BlockType.CODE]),+ workflow_run=make_workflow_run(),+ )++ cached = generate_mock.await_args.kwargs["cached_script"]+ assert cached is not None and cached.script_revision_id == "sr_pending"++ @pytest.mark.asyncio+ async def test_first_run_finalize_creates_script_when_no_pending_exists(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ scripts = make_scripts_db(pending_row=None)+ generate_mock = self._patch_common(monkeypatch, scripts)++ await WorkflowService().generate_script_if_needed(+ workflow=make_workflow([BlockType.GOTO_URL, BlockType.CODE]),+ workflow_run=make_workflow_run(),+ )++ scripts.create_script.assert_awaited_once()+ assert generate_mock.await_args.kwargs["script"].script_id == "s_new"diff --git a/tests/unit/test_quickstart_command.py b/tests/unit/test_quickstart_command.pyindex 51127157a..3fb72f21f 100644--- a/tests/unit/test_quickstart_command.py+++ b/tests/unit/test_quickstart_command.py@@ -10,8 +10,10 @@ import sysimport timeimport typesfrom pathlib import Path+from unittest.mock import MagicMockimport pytest+import structlogfrom structlog.testing import capture_logsfrom typer.testing import CliRunner@@ -27,6 +29,25 @@ from skyvern.utils.env_paths import (resolve_backend_env_path,)+[email protected](autouse=True)+def _structlog_config_capture_can_see(monkeypatch: pytest.MonkeyPatch) -> None:+ # capture_logs() swaps processors but keeps the configured wrapper_class, so a+ # filtering wrapper above WARNING or a logger cached under an earlier config makes+ # this module's warning assertions silently fail depending on shard order.+ saved = structlog.get_config()+ structlog.configure(+ wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),+ logger_factory=structlog.stdlib.LoggerFactory(),+ cache_logger_on_first_use=False,+ )+ from skyvern.cli import run_commands++ monkeypatch.setattr(run_commands.LOG, "_logger", None, raising=False)+ yield+ structlog.configure(**saved)++_BLOCKING_SWEEP_WITH_DESCENDANT = """import subprocessimport sys@@ -369,7 +390,7 @@ def test_run_mcp_prepares_cloud_env_before_starting_mcp(tmp_path, monkeypatch) -@pytest.mark.parametrize("failure_stage", ["import", "call"])-def test_run_mcp_logs_sweep_failure_and_continues(monkeypatch, caplog, failure_stage: str) -> None:+def test_run_mcp_logs_sweep_failure_and_continues(monkeypatch, failure_stage: str) -> None:events: list[str] = []run_commands = _patch_minimal_run_mcp_dependencies(monkeypatch, events, lambda: events.append("run"))@@ -390,20 +411,15 @@ def test_run_mcp_logs_sweep_failure_and_continues(monkeypatch, caplog, failure_sfake_local_browser_profile.sweep_local_browser_profiles_with_budget = failing_sweepmonkeypatch.setitem(sys.modules, "skyvern.library.local_browser_profile", fake_local_browser_profile)- with capture_logs() as logs, caplog.at_level(logging.WARNING, logger="skyvern.cli.run_commands"):- run_commands.run_mcp()+ # Assert on the logger call itself rather than capture_logs: capture depends on+ # process-global structlog state that other tests in the shard can leave behind.+ recording_logger = MagicMock()+ monkeypatch.setattr(run_commands, "LOG", recording_logger)+ run_commands.run_mcp()assert events == ["prepare", "run", "cleanup"]- structlog_warning = any(- log.get("event") == "local_browser_profile_startup_sweep_failed"- and (log.get("log_level") or log.get("level")) == "warning"- for log in logs- )- stdlib_warning = any(- record.levelno == logging.WARNING and "local_browser_profile_startup_sweep_failed" in record.getMessage()- for record in caplog.records- )- assert structlog_warning or stdlib_warning+ warned_events = [call.args[0] for call in recording_logger.warning.call_args_list if call.args]+ assert "local_browser_profile_startup_sweep_failed" in warned_eventsdef test_run_mcp_starts_within_sweep_budget_and_stops_blocking_child(tmp_path: Path, monkeypatch) -> None: