Skip to content

Automate browser based workflows with AI

fix(SKY-8685): report action-based total_cost on workflow runs (#6627)

Aaron Perezed3e10a9c15a
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index bcc356853..0b914033a 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -742,11 +742,7 @@ class AgentFunction:
return
async def wait_for_challenge_solver(self, page: Page) -> None:
- """Wait for a cloud-managed challenge solver if one is attached to the page.
-
- OSS no-op. Cloud overrides this so OSS-synced browser/action code can
- wait at navigation/action boundaries without importing cloud modules.
- """
+ """Wait for a cloud-managed challenge solver if one is attached to the page."""
return None
async def should_shadow_extraction_cache_hit(self, task: Task) -> bool:
@@ -758,14 +754,7 @@ class AgentFunction:
workflow_permanent_id: str | None,
cache_key: str,
) -> Any | None:
- """Cross-run (wpid-scoped) extraction-cache read. OSS no-op.
-
- Cloud overrides this to consult the Redis tier (SKY-8873). Returns the
- cached extraction value on a hit or None on a miss / error / disabled
- flag. Implementations MUST swallow backend errors and return None so
- the extract path always falls through to a fresh LLM call rather than
- failing loud.
- """
+ """Cross-run (wpid-scoped) extraction-cache read. OSS no-op."""
return None
async def store_cross_run_extraction_cache(
@@ -774,14 +763,7 @@ class AgentFunction:
cache_key: str,
value: Any,
) -> None:
- """Cross-run (wpid-scoped) extraction-cache write. OSS no-op.
-
- Cloud overrides this to write to the Redis tier (SKY-8873) with a
- long TTL. Called after a fresh LLM extraction so subsequent runs of
- the same workflow against the same page content skip the LLM call.
- Implementations MUST swallow backend errors — write-path failures
- must never fail the user-visible request.
- """
+ """Cross-run (wpid-scoped) extraction-cache write. OSS no-op."""
return None
def build_workflow_schedule_id(self, workflow_schedule_id: str) -> str | None:
@@ -817,11 +799,16 @@ class AgentFunction:
return None
async def delete_workflow_schedule(self, backend_schedule_id: str) -> None:
- """Delete a schedule from the execution backend. OSS no-op.
+ """Delete a schedule from the execution backend. OSS no-op."""
+ return None
- Implementations must be idempotent — deleting an already-absent schedule
- should succeed silently rather than raising.
- """
+ async def calculate_workflow_run_total_cost(
+ self,
+ organization_id: str | None,
+ credits_used: int,
+ cached_credits_used: int,
+ ) -> float | None:
+ """Compute the user-facing ``total_cost`` for a workflow run. OSS returns None."""
return None
async def auto_solve_captchas(self, page: Page) -> bool:
diff --git a/skyvern/forge/sdk/workflow/models/workflow.py b/skyvern/forge/sdk/workflow/models/workflow.py
index 439b5f8ad..36ace66cf 100644
--- a/skyvern/forge/sdk/workflow/models/workflow.py
+++ b/skyvern/forge/sdk/workflow/models/workflow.py
@@ -364,8 +364,11 @@ class WorkflowRunResponseBase(BaseModel):
total_steps: int | None = None
total_cost: float | None = Field(
default=None,
- deprecated=True,
- description="Deprecated. Public workflow-run responses no longer expose cost; use credits_used fields instead.",
+ description=(
+ "Estimated workflow-run cost as the list-price value of credits consumed "
+ "(credits x list credit rate), not the amount invoiced; enterprise contract "
+ "pricing and legacy billing may differ. Null when cost is unavailable."
+ ),
)
credits_used: int = 0
cached_credits_used: int = 0
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 0a90d7ff2..e85fb8d61 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -5818,14 +5818,19 @@ class WorkflowService:
parameters_with_value = {wfp.key: wfrp.value for wfp, wfrp in workflow_parameter_tuples}
total_steps = None
+ total_cost: float | None = None
if include_step_count or include_cost:
- # `include_cost` is retained as a legacy alias for callers that
- # previously received `total_steps` alongside deprecated cost data.
step_count, _ = await app.DATABASE.tasks.get_step_counts_by_task_ids(
task_ids=[task.task_id for task in workflow_run_tasks], organization_id=organization_id
)
total_steps = step_count
+ if include_cost:
+ total_cost = await app.AGENT_FUNCTION.calculate_workflow_run_total_cost(
+ organization_id=organization_id,
+ credits_used=workflow_run.credits_used,
+ cached_credits_used=workflow_run.cached_credits_used,
+ )
return WorkflowRunResponseBase(
workflow_id=workflow.workflow_permanent_id,
workflow_run_id=workflow_run_id,
@@ -5858,7 +5863,7 @@ class WorkflowService:
downloaded_file_urls=downloaded_file_urls,
outputs=outputs,
total_steps=total_steps,
- total_cost=None,
+ total_cost=total_cost,
credits_used=workflow_run.credits_used,
cached_credits_used=workflow_run.cached_credits_used,
workflow_title=workflow.title,
diff --git a/skyvern/webeye/browser_factory.py b/skyvern/webeye/browser_factory.py
index fcb5f71b7..57874de6f 100644
--- a/skyvern/webeye/browser_factory.py
+++ b/skyvern/webeye/browser_factory.py
@@ -261,6 +261,11 @@ def initialize_download_dir() -> str:
async def rebind_download_dir(browser: Browser, run_id: str | None) -> None:
+ if not run_id:
+ # No run_id means no run-scoped dir to bind to, so the session keeps its current download
+ # binding. Adoption callers always pass a run id, so warn on the unexpected miss.
+ LOG.warning("rebind_download_dir skipped: missing run_id")
+ return
download_dir = get_download_dir(run_id)
cdp_session = await browser.new_browser_cdp_session()
await cdp_session.send(
@@ -270,8 +275,19 @@ async def rebind_download_dir(browser: Browser, run_id: str | None) -> None:
"downloadPath": download_dir,
},
)
+ rebound_interceptors = 0
+ for context in browser.contexts:
+ interceptor = getattr(context, "_skyvern_cdp_download_interceptor", None)
+ if interceptor is not None:
+ interceptor.set_download_dir(download_dir)
+ rebound_interceptors += 1
- LOG.info("setDownloadBehavior applied", download_dir=download_dir, run_id=run_id)
+ LOG.info(
+ "setDownloadBehavior applied",
+ download_dir=download_dir,
+ run_id=run_id,
+ rebound_interceptors=rebound_interceptors,
+ )
async def _apply_download_behaviour(browser: Browser) -> None:
@@ -964,6 +980,7 @@ async def _connect_to_cdp_browser(
browser_context.on("page", lambda page: asyncio.ensure_future(_on_new_page(page)))
browser_context._skyvern_cdp_download_active = True # type: ignore[attr-defined]
+ browser_context._skyvern_cdp_download_interceptor = interceptor # type: ignore[attr-defined]
LOG.info(
"CDP download interceptor enabled",
download_dir=download_dir,
diff --git a/tests/unit/test_download_dir_rebind.py b/tests/unit/test_download_dir_rebind.py
index c9104ead4..0e0190f9e 100644
--- a/tests/unit/test_download_dir_rebind.py
+++ b/tests/unit/test_download_dir_rebind.py
@@ -6,6 +6,7 @@ the dir must be rebound to downloads/<workflow_run_id>/ so downloads land
run-scoped and the listener logs the real run identity.
"""
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -24,6 +25,7 @@ def _recording_browser() -> tuple[MagicMock, MagicMock]:
cdp_session.send = AsyncMock()
browser = MagicMock()
browser.new_browser_cdp_session = AsyncMock(return_value=cdp_session)
+ browser.contexts = []
return browser, cdp_session
@@ -40,6 +42,38 @@ async def test_rebind_binds_download_path_to_run_dir() -> None:
assert "None" not in params["downloadPath"]
+async def test_rebind_skips_when_run_id_none() -> None:
+ browser, cdp_session = _recording_browser()
+
+ await rebind_download_dir(browser, run_id=None)
+
+ cdp_session.send.assert_not_awaited()
+
+
+async def test_rebind_also_rebinds_cdp_download_interceptor() -> None:
+ browser, cdp_session = _recording_browser()
+ interceptor = MagicMock()
+ context = MagicMock()
+ context._skyvern_cdp_download_interceptor = interceptor
+ browser.contexts = [context]
+
+ await rebind_download_dir(browser, run_id="wr_test")
+
+ interceptor.set_download_dir.assert_called_once_with(get_download_dir("wr_test"))
+
+
+async def test_rebind_ignores_context_without_interceptor() -> None:
+ browser, cdp_session = _recording_browser()
+ browser.contexts = [SimpleNamespace()]
+
+ await rebind_download_dir(browser, run_id="wr_test")
+
+ cdp_session.send.assert_awaited_once()
+
+
@pytest.mark.asyncio
async def test_apply_download_behaviour_uses_run_id_first_resolution() -> None:
browser, cdp_session = _recording_browser()