Skip to content

Automate browser based workflows with AI

Serve browser test pages locally instead of from the internet (SKY-18854) (#9018)

Shuchang Zheng637ea803e056
diff --git a/skyvern/forge/sdk/api/llm/api_handler_factory.py b/skyvern/forge/sdk/api/llm/api_handler_factory.py
index cd5a9a431..19256aabd 100644
--- a/skyvern/forge/sdk/api/llm/api_handler_factory.py
+++ b/skyvern/forge/sdk/api/llm/api_handler_factory.py
@@ -826,6 +826,26 @@ def _response_finish_reason(response: object) -> str | None:
return None
+def _halved_reasoning_budget_parameters(active_parameters: dict[str, Any]) -> dict[str, Any] | None:
+ """A copy of these parameters with the declared reasoning budget halved.
+
+ None when the request declares no budget, and so has nothing it can hand back to the answer.
+ """
+ extra_body = active_parameters.get("extra_body")
+ if not isinstance(extra_body, dict):
+ return None
+ reasoning = extra_body.get("reasoning")
+ if not isinstance(reasoning, dict):
+ return None
+ budget = reasoning.get("max_tokens")
+ if not isinstance(budget, int) or isinstance(budget, bool) or budget < 2:
+ return None
+ return {
+ **active_parameters,
+ "extra_body": {**extra_body, "reasoning": {**reasoning, "max_tokens": budget // 2}},
+ }
+
+
def _usage_int_field(value: Any, *field_names: str) -> int | None:
for field_name in field_names:
field = value.get(field_name) if isinstance(value, dict) else getattr(value, field_name, None)
@@ -4091,6 +4111,7 @@ class LLMCaller:
t_llm_request = time.perf_counter()
llm_duration_seconds = 0.0
refused_call_stats: LLMCallStats | None = None
+ truncated_call_stats: LLMCallStats | None = None
try:
# `timeout` may already live in active_parameters via litellm_params (flex configs
# carry their own); passing it explicitly too collides on kwarg unpacking.
@@ -4103,6 +4124,10 @@ class LLMCaller:
response, refused_call_stats = await self._retry_refused_call_on_fallback(
response, messages, tools, active_parameters, prompt_name
)
+ if isinstance(response, ModelResponse) and is_truncated_response(response):
+ response, truncated_call_stats = await self._retry_truncated_call_with_less_reasoning(
+ response, messages, tools, active_parameters, prompt_name
+ )
llm_duration_seconds = time.perf_counter() - t_llm_request
if use_message_history and message_history_after_success is not None:
# only update message_history when the request is successful
@@ -4212,6 +4237,8 @@ class LLMCaller:
)
if refused_call_stats is not None:
call_stats = _combined_call_stats(call_stats, refused_call_stats)
+ if truncated_call_stats is not None:
+ call_stats = _combined_call_stats(call_stats, truncated_call_stats)
llm_response_json = _safe_model_dump_json(response)
if should_persist_llm_artifacts:
@@ -4455,13 +4482,50 @@ class LLMCaller:
raise LLMContentFilteredError(self.llm_key, [refused_on, fallback_group])
return fallback_response, refused_stats
- async def _log_refused_response(
+ async def _retry_truncated_call_with_less_reasoning(
+ self,
+ response: ModelResponse,
+ messages: list[dict[str, Any]],
+ tools: list | None,
+ active_parameters: dict[str, Any],
+ prompt_name: str | None,
+ ) -> tuple[ModelResponse | CustomStreamWrapper | AnthropicMessage | UITarsResponse, LLMCallStats | None]:
+ """A model that spent its whole completion budget reasoning stops at finish_reason=length with no
+ content, which arrives as a valid response the router's exception-driven fallback never sees. Send it
+ once more with the declared reasoning budget halved, so the answer has room (SKY-18857). A step retry
+ is no substitute: it re-sends the same budget and truncates the same way."""
+ retry_parameters = _halved_reasoning_budget_parameters(active_parameters)
+ usage = getattr(response, "usage", None)
+ usage_detail = getattr(usage, "completion_tokens_details", None)
+ LOG.warning(
+ "LLM spent its whole completion budget on reasoning and returned no content",
+ llm_key=self.llm_key,
+ prompt_name=prompt_name,
+ model=getattr(response, "model", None) or self.llm_config.model_name,
+ prompt_tokens=getattr(usage, "prompt_tokens", None),
+ completion_tokens=getattr(usage, "completion_tokens", None),
+ reasoning_tokens=getattr(usage_detail, "reasoning_tokens", None),
+ # False means the request declared no reasoning budget to lower, so this call fails as it
+ # did before. Read with retried_reasoning_budget to tell a recovery from a bare report.
+ retried=retry_parameters is not None,
+ retried_reasoning_budget=(
+ retry_parameters["extra_body"]["reasoning"]["max_tokens"] if retry_parameters else None
+ ),
+ )
+ if retry_parameters is None:
+ return response, None
+ truncated_stats = await self._log_discarded_response_stats(response, prompt_name)
+ return (
+ await self._dispatch_llm_call(messages=messages, tools=tools, **retry_parameters),
+ truncated_stats,
+ )
+
+ async def _log_discarded_response_stats(
self,
response: ModelResponse | CustomStreamWrapper | AnthropicMessage | UITarsResponse,
prompt_name: str | None,
- refused_on: str,
- fallback_group: str | None,
) -> LLMCallStats:
+ """Usage for a response this call is throwing away; its tokens were still spent and still bill."""
stats = await self.get_call_stats(response)
_emit_copilot_model_usage_for_response(
response,
@@ -4469,6 +4533,16 @@ class LLMCaller:
prompt_name=prompt_name,
cost=stats.llm_cost if stats.llm_cost_available else None,
)
+ return stats
+
+ async def _log_refused_response(
+ self,
+ response: ModelResponse | CustomStreamWrapper | AnthropicMessage | UITarsResponse,
+ prompt_name: str | None,
+ refused_on: str,
+ fallback_group: str | None,
+ ) -> LLMCallStats:
+ stats = await self._log_discarded_response_stats(response, prompt_name)
LOG.warning(
"LLM response refused or blocked by content filter",
llm_key=self.llm_key,
diff --git a/skyvern/forge/sdk/api/llm/config_registry.py b/skyvern/forge/sdk/api/llm/config_registry.py
index f0165a352..b1e5cb136 100644
--- a/skyvern/forge/sdk/api/llm/config_registry.py
+++ b/skyvern/forge/sdk/api/llm/config_registry.py
@@ -41,6 +41,23 @@ OPENINFERENCE_PROVIDER_SLUG = "open-inference"
# OpenRouter routes by provider SLUG and skips an unrecognised one silently, so a name here
# that no longer matches enforces nothing. Both are asserted in tests for that reason.
AMAZON_BEDROCK_PROVIDER_SLUG = "amazon-bedrock"
+# A completion cap bounds reasoning and answer together, so a reasoning model can spend the whole
+# cap thinking and stop at finish_reason=length with no content at all (SKY-18857). Reserve this
+# much of the cap for the answer and give reasoning the rest.
+OPENROUTER_ANSWER_TOKEN_RESERVE = 16_384
+# Shared by every OpenRouter config serving this model, so a reasoning budget derived from it can
+# never drift from the cap it has to fit inside.
+DEEPSEEK_V4_FLASH_MAX_COMPLETION_TOKENS = 65_536
+
+
+def openrouter_reasoning_budget(max_completion_tokens: int) -> dict[str, int]:
+ """OpenRouter's reasoning budget for a completion cap, leaving the answer room to be written.
+
+ Mutually exclusive with `reasoning.effort` / `reasoning_effort` upstream, so never set both.
+ """
+ return {
+ "max_tokens": max(max_completion_tokens - OPENROUTER_ANSWER_TOKEN_RESERVE, max_completion_tokens // 2),
+ }
@dataclass(frozen=True)
@@ -2057,13 +2074,16 @@ if settings.ENABLE_OPENROUTER:
["OPENROUTER_API_KEY"],
supports_vision=False,
add_assistant_prefix=False,
- max_completion_tokens=65536,
+ max_completion_tokens=DEEPSEEK_V4_FLASH_MAX_COMPLETION_TOKENS,
litellm_params=LiteLLMParams(
api_key=settings.OPENROUTER_API_KEY,
api_base=settings.OPENROUTER_API_BASE,
api_version=None,
model_info={"model_name": "openrouter/deepseek/deepseek-v4-flash"},
- extra_body={"provider": {"ignore": [OPENINFERENCE_PROVIDER_SLUG]}},
+ extra_body={
+ "provider": {"ignore": [OPENINFERENCE_PROVIDER_SLUG]},
+ "reasoning": openrouter_reasoning_budget(DEEPSEEK_V4_FLASH_MAX_COMPLETION_TOKENS),
+ },
),
),
)
@@ -2075,13 +2095,15 @@ if settings.ENABLE_OPENROUTER:
["OPENROUTER_API_KEY"],
supports_vision=False,
add_assistant_prefix=False,
- max_completion_tokens=65536,
+ max_completion_tokens=DEEPSEEK_V4_FLASH_MAX_COMPLETION_TOKENS,
litellm_params=LiteLLMParams(
api_key=settings.OPENROUTER_API_KEY,
api_base=settings.OPENROUTER_API_BASE,
api_version=None,
model_info={"model_name": "openrouter/deepseek/deepseek-v4-flash-0731"},
extra_body={
+ # Bounds reasoning by effort, not by openrouter_reasoning_budget: upstream treats
+ # the two as mutually exclusive, and effort is this config's reason for existing.
"reasoning_effort": "high",
"provider": {
"order": ["cloudflare", "parasail"],
diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py
index afec2ddf0..84d2e3eeb 100644
--- a/tests/unit/conftest.py
+++ b/tests/unit/conftest.py
@@ -64,7 +64,7 @@ from skyvern.services import workflow_run_group_service as group_service
from skyvern.webeye.utils import page as page_module
from skyvern.webeye.utils.page import ScreenshotMode
from tests.unit._fingerprint_expectations import FINGERPRINT_TEST_SECRET_KEY
-from tests.unit.dns_fixtures import no_env_proxy, public_dns # noqa: F401
+from tests.unit.dns_fixtures import no_env_proxy, public_dns, unresolvable_dns # noqa: F401
from tests.unit.force_stub_app import start_forge_stub_app
from tests.unit.google.conftest import mock_sheets_transport # noqa: F401
from tests.unit.litellm_model_registry import registered_gpt56_litellm_models
diff --git a/tests/unit/dns_fixtures.py b/tests/unit/dns_fixtures.py
index ebf70643e..d2f888323 100644
--- a/tests/unit/dns_fixtures.py
+++ b/tests/unit/dns_fixtures.py
@@ -21,6 +21,21 @@ def public_dns(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _resolve)
+def unresolvable_dns(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Answer every hostname lookup with no such host, so a name that never resolves fails without network DNS."""
+ real_getaddrinfo = socket.getaddrinfo
+
+ def _resolve(host: str, port: object = None, *args: object, **kwargs: object) -> list:
+ try:
+ ipaddress.ip_address(host)
+ except ValueError:
+ raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") from None
+ return real_getaddrinfo(host, port, *args, **kwargs)
+
+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _resolve)
+
+
_PROXY_ENV_VARS = ("http_proxy", "https_proxy", "all_proxy", "no_proxy")
diff --git a/tests/unit/embedded/test_tab_management_e2e.py b/tests/unit/embedded/test_tab_management_e2e.py
index fcc202e06..4bbf3fe04 100644
--- a/tests/unit/embedded/test_tab_management_e2e.py
+++ b/tests/unit/embedded/test_tab_management_e2e.py
@@ -11,10 +11,16 @@ from __future__ import annotations
import asyncio
from pathlib import Path
+from typing import TYPE_CHECKING
import pytest
import pytest_asyncio
+if TYPE_CHECKING:
+ from playwright.async_api import Route
+
+EXAMPLE_PAGE = "<!doctype html><title>Example Domain</title><h1>Example Domain</h1>"
+
def _has_playwright_browser() -> bool:
try:
@@ -32,8 +38,12 @@ _skip_no_browser = pytest.mark.skipif(
)
+async def _serve_example_page(route: Route) -> None:
+ await route.fulfill(status=200, content_type="text/html", body=EXAMPLE_PAGE)
+
+
@pytest_asyncio.fixture
-async def browser_session():
+async def browser_session(public_dns: None):
"""Launch a real local headless browser and wire up SessionState for MCP tools."""
from skyvern import Skyvern
from skyvern.cli.core.result import BrowserContext
@@ -41,6 +51,7 @@ async def browser_session():
skyvern = Skyvern.local(use_in_memory_db=True)
browser = await skyvern.launch_local_browser(headless=True)
+ await browser.route("https://example.com/**", _serve_example_page)
state = SessionState(
browser=browser,
diff --git a/tests/unit/test_background_task_executor.py b/tests/unit/test_background_task_executor.py
index 19da8ad27..632f30799 100644
--- a/tests/unit/test_background_task_executor.py
+++ b/tests/unit/test_background_task_executor.py
@@ -849,6 +849,7 @@ async def test_in_process_retry_continues_after_interim_payload_failure(
("time", "cloud", "running", False, True),
],
)
[email protected]("public_dns")
async def test_recovered_interim_payload_describes_target_attempt(
interim_retry_db: AgentDB,
monkeypatch: pytest.MonkeyPatch,
@@ -2219,6 +2220,7 @@ async def test_startup_retry_backoff_preserves_sweep_recovery_or_cancellation(
@pytest.mark.asyncio
[email protected]("public_dns")
async def test_startup_retry_with_definitively_missing_token_remains_abandonable(
interim_retry_db: AgentDB, monkeypatch: pytest.MonkeyPatch
) -> None:
diff --git a/tests/unit/test_code_block_downloads.py b/tests/unit/test_code_block_downloads.py
index 580c1daf3..f4e478070 100644
--- a/tests/unit/test_code_block_downloads.py
+++ b/tests/unit/test_code_block_downloads.py
@@ -1019,6 +1019,7 @@ async def test_an_inline_session_block_uploads_the_download_it_claimed_from_the_
@pytest.mark.asyncio
[email protected]("unresolvable_dns")
async def test_a_parameter_named_after_the_attach_helper_still_wins(
monkeypatch: pytest.MonkeyPatch, _isolated_download_path: str
) -> None:
diff --git a/tests/unit/test_code_block_sandbox.py b/tests/unit/test_code_block_sandbox.py
index e26428ab5..49617e7e3 100644
--- a/tests/unit/test_code_block_sandbox.py
+++ b/tests/unit/test_code_block_sandbox.py
@@ -3118,6 +3118,7 @@ class TestCodeBlockMagicLink:
assert fills == []
@pytest.mark.asyncio
+ @pytest.mark.usefixtures("public_dns")
async def test_anchors_created_after_at_call_time_not_run_start(self, monkeypatch: pytest.MonkeyPatch) -> None:
from skyvern.forge.sdk.schemas.totp_codes import OTPType
from skyvern.forge.sdk.workflow.models.block import _bind_code_block_magic_link
diff --git a/tests/unit/test_config_registry.py b/tests/unit/test_config_registry.py
index fa761ee90..e4e23a803 100644
--- a/tests/unit/test_config_registry.py
+++ b/tests/unit/test_config_registry.py
@@ -172,10 +172,30 @@ def test_openrouter_deepseek_v4_flash_0731_registry_config(monkeypatch: pytest.M
}
-def _openrouter_capture_server(captured: dict[str, Any]) -> HTTPServer:
+_OPENROUTER_ANSWER = '{"actions": []}'
+# The shape production truncation arrives in: the completion cap spent entirely on reasoning,
+# so finish_reason is length and there is no content to parse at all (SKY-18857).
+_TRUNCATED_USAGE = {
+ "prompt_tokens": 26869,
+ "completion_tokens": 65536,
+ "total_tokens": 92405,
+ "completion_tokens_details": {"reasoning_tokens": 72544},
+}
+
+
+def _openrouter_capture_server(
+ captured: dict[str, Any], replies: list[tuple[str | None, str]] | None = None
+) -> HTTPServer:
+ """Serve `replies` as (content, finish_reason) in request order, recording every request body."""
+ scripted = replies or [(_OPENROUTER_ANSWER, "stop")]
+
class _Handler(BaseHTTPRequestHandler):
def do_POST(self) -> None:
- captured["body"] = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
+ body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
+ bodies = captured.setdefault("bodies", [])
+ bodies.append(body)
+ captured["body"] = body
+ content, finish_reason = scripted[min(len(bodies), len(scripted)) - 1]
payload = json.dumps(
{
"id": "chatcmpl-test",
@@ -185,11 +205,13 @@ def _openrouter_capture_server(captured: dict[str, Any]) -> HTTPServer:
"choices": [
{
"index": 0,
- "message": {"role": "assistant", "content": '{"actions": []}'},
- "finish_reason": "stop",
+ "message": {"role": "assistant", "content": content},
+ "finish_reason": finish_reason,
}
],
- "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ "usage": _TRUNCATED_USAGE
+ if finish_reason == "length"
+ else {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
}
).encode()
self.send_response(200)
@@ -204,44 +226,81 @@ def _openrouter_capture_server(captured: dict[str, Any]) -> HTTPServer:
return HTTPServer(("127.0.0.1", 0), _Handler)
+def _pin_deepseek_v4_flash_at(server: HTTPServer, monkeypatch: pytest.MonkeyPatch) -> llm_schemas.LLMConfig:
+ """Re-register the registry against `server` and pin that config as the one the handler resolves."""
+ real_get_config = config_registry.LLMConfigRegistry.get_config
+ monkeypatch.setattr(config_registry.settings, "ENABLE_OPENROUTER", True)
+ monkeypatch.setattr(config_registry.settings, "OPENROUTER_API_KEY", "test-key")
+ monkeypatch.setattr(config_registry.settings, "OPENROUTER_API_BASE", f"http://127.0.0.1:{server.server_port}")
+ monkeypatch.setattr(llm_schemas, "_settings", lambda: config_registry.settings)
+ assert config_registry.__file__ is not None
+
+ registry_namespace = runpy.run_path(str(Path(config_registry.__file__)))
+ llm_config = registry_namespace["LLMConfigRegistry"].get_config("OPENROUTER_DEEPSEEK_V4_FLASH")
+ # The process-wide registry may hold a config issue for this key (no OpenRouter key in
+ # the environment), which would hand back the dummy handler instead of calling out.
+ monkeypatch.setattr(config_registry.LLMConfigRegistry, "get_config_issue", lambda _: None)
+ monkeypatch.setattr(
+ config_registry.LLMConfigRegistry,
+ "get_config",
+ lambda key: llm_config if key == "OPENROUTER_DEEPSEEK_V4_FLASH" else real_get_config(key),
+ )
+ monkeypatch.setattr(LLMAPIHandlerFactory, "_handler_cache", {})
+ return llm_config
+
+
@pytest.mark.asyncio
async def test_openrouter_deepseek_v4_flash_sends_provider_ignore_on_the_wire(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""OpenRouter skips an unrecognized slug in `ignore` silently instead of rejecting it, so a
- typo would leave the route on the defective provider while the config still looked right."""
+ typo would leave the route on the defective provider while the config still looked right.
+ The reasoning budget rides the same `extra_body`, which the OpenRouter dispatch path rebuilds
+ from an allowlist — a budget that never reaches the wire bounds nothing."""
captured: dict[str, Any] = {}
- real_get_config = config_registry.LLMConfigRegistry.get_config
with _openrouter_capture_server(captured) as server:
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
- monkeypatch.setattr(config_registry.settings, "ENABLE_OPENROUTER", True)
- monkeypatch.setattr(config_registry.settings, "OPENROUTER_API_KEY", "test-key")
- monkeypatch.setattr(
- config_registry.settings, "OPENROUTER_API_BASE", f"http://127.0.0.1:{server.server_port}"
- )
- monkeypatch.setattr(llm_schemas, "_settings", lambda: config_registry.settings)
- assert config_registry.__file__ is not None
-
- registry_namespace = runpy.run_path(str(Path(config_registry.__file__)))
- llm_config = registry_namespace["LLMConfigRegistry"].get_config("OPENROUTER_DEEPSEEK_V4_FLASH")
+ llm_config = _pin_deepseek_v4_flash_at(server, monkeypatch)
assert llm_config.litellm_params is not None
- assert llm_config.litellm_params["extra_body"] == {"provider": {"ignore": ["open-inference"]}}
-
- # The process-wide registry may hold a config issue for this key (no OpenRouter key in
- # the environment), which would hand back the dummy handler instead of calling out.
- monkeypatch.setattr(config_registry.LLMConfigRegistry, "get_config_issue", lambda _: None)
- monkeypatch.setattr(
- config_registry.LLMConfigRegistry,
- "get_config",
- lambda key: llm_config if key == "OPENROUTER_DEEPSEEK_V4_FLASH" else real_get_config(key),
- )
- monkeypatch.setattr(LLMAPIHandlerFactory, "_handler_cache", {})
+ assert llm_config.litellm_params["extra_body"] == {
+ "provider": {"ignore": ["open-inference"]},
+ "reasoning": {"max_tokens": 49152},
+ }
await LLMAPIHandlerFactory.get_llm_api_handler("OPENROUTER_DEEPSEEK_V4_FLASH")(prompt="hello")
finally:
server.shutdown()
thread.join(timeout=5)
assert captured["body"]["provider"] == {"ignore": ["open-inference"]}
+ assert captured["body"]["reasoning"] == {"max_tokens": 49152}
+ assert captured["body"]["max_completion_tokens"] == 65536
+
+
+async def test_reasoning_truncated_openrouter_call_is_retried_with_half_the_budget(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A model that spends the whole cap thinking answers 200 with finish_reason=length and no content,
+ so nothing in the router's exception-driven failover sees it and the step used to just fail. A step
+ retry re-sends the same budget and truncates again, so the retry has to lower it."""
+ captured: dict[str, Any] = {}
+ replies = [(None, "length"), (_OPENROUTER_ANSWER, "stop")]
+
+ with _openrouter_capture_server(captured, replies) as server:
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ _pin_deepseek_v4_flash_at(server, monkeypatch)
+ response = await LLMAPIHandlerFactory.get_llm_api_handler("OPENROUTER_DEEPSEEK_V4_FLASH")(prompt="hello")
+ finally:
+ server.shutdown()
+ thread.join(timeout=5)
+
+ assert response == {"actions": []}
+ budgets = [body["reasoning"]["max_tokens"] for body in captured["bodies"]]
+ assert budgets == [49152, 24576]
+ # The cap itself stays put: the answer needs the room reasoning just gave back.
+ assert [body["max_completion_tokens"] for body in captured["bodies"]] == [65536, 65536]
diff --git a/tests/unit/test_files_resolve_local_or_download.py b/tests/unit/test_files_resolve_local_or_download.py
index 5111484f7..cfd86e5c1 100644
--- a/tests/unit/test_files_resolve_local_or_download.py
+++ b/tests/unit/test_files_resolve_local_or_download.py
@@ -28,6 +28,8 @@ from skyvern.forge.sdk.artifact.signing import (
)
from skyvern.forge.sdk.artifact.storage.local import LocalStorage
+pytestmark = pytest.mark.usefixtures("public_dns")
+
class _FakeDownloadResponse:
def __init__(
diff --git a/tests/unit/test_llm_output_truncation.py b/tests/unit/test_llm_output_truncation.py
index 8c0891fb2..853816170 100644
--- a/tests/unit/test_llm_output_truncation.py
+++ b/tests/unit/test_llm_output_truncation.py
@@ -7,6 +7,7 @@ from unittest.mock import MagicMock
import pytest
from PIL import Image
+from skyvern.forge.sdk.api.llm.api_handler_factory import _halved_reasoning_budget_parameters
from skyvern.forge.sdk.api.llm.exceptions import LLMOutputTruncatedError
from skyvern.forge.sdk.api.llm.utils import (
is_content_filtered_response,
@@ -142,6 +143,42 @@ class TestIsContentFilteredResponse:
assert is_content_filtered_response(resp) is False
+class TestHalvedReasoningBudgetParameters:
+ """What arms the truncation retry. Arming it for a request that declares no reasoning budget
+ would re-send identical parameters and double the cost of every truncated call for nothing."""
+
+ def test_declared_budget_is_halved_without_touching_the_completion_cap(self) -> None:
+ reduced = _halved_reasoning_budget_parameters(
+ {
+ "max_completion_tokens": 65536,
+ "extra_body": {"provider": {"ignore": ["open-inference"]}, "reasoning": {"max_tokens": 49152}},
+ }
+ )
+ assert reduced == {
+ "max_completion_tokens": 65536,
+ "extra_body": {"provider": {"ignore": ["open-inference"]}, "reasoning": {"max_tokens": 24576}},
+ }
+
+ def test_frozen_config_parameters_are_not_mutated(self) -> None:
+ extra_body = {"reasoning": {"max_tokens": 49152}}
+ parameters = {"extra_body": extra_body}
+ _halved_reasoning_budget_parameters(parameters)
+ assert extra_body == {"reasoning": {"max_tokens": 49152}}
+
+ @pytest.mark.parametrize(
+ "parameters",
+ [
+ pytest.param({"max_completion_tokens": 65536}, id="no_extra_body"),
+ pytest.param({"extra_body": {"provider": {"order": ["cloudflare"]}}}, id="no_reasoning"),
+ pytest.param({"extra_body": {"reasoning": {"effort": "high"}}}, id="effort_not_budget"),
+ pytest.param({"extra_body": {"reasoning_effort": "high"}}, id="top_level_effort"),
+ pytest.param({"extra_body": {"reasoning": {"max_tokens": 1}}}, id="nothing_left_to_halve"),
+ ],
+ )
+ def test_requests_with_no_reducible_budget_are_left_alone(self, parameters: dict[str, Any]) -> None:
+ assert _halved_reasoning_budget_parameters(parameters) is None
+
+
class TestParseApiResponseTruncation:
def test_truncated_response_raises_llm_output_truncated_error(self) -> None:
resp = _make_response(finish_reason="length", content=None)
diff --git a/tests/unit/test_mcp_observe_v2.py b/tests/unit/test_mcp_observe_v2.py
index 3ba53adda..4036d4127 100644
--- a/tests/unit/test_mcp_observe_v2.py
+++ b/tests/unit/test_mcp_observe_v2.py
@@ -2604,6 +2604,7 @@ async def test_stale_document_cleanup_replaces_mismatched_newer_publication(
@pytest.mark.asyncio
[email protected]("public_dns")
async def test_failed_navigation_invalidates_inflight_publication(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv(_FLAG, "1")
page = _page()
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index 578b40d29..cede514f6 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -9023,6 +9023,7 @@ async def test_navigate_records_name_the_host_and_no_other_tool_does() -> None:
@pytest.mark.asyncio
[email protected]("public_dns")
async def test_a_url_the_record_cannot_parse_redacts_it_and_never_aborts_the_run() -> None:
# The record helper is evaluated to build the kwargs BEFORE the `taskv3 tool handler raised` call
# is entered, so anything it raises escapes that except block, the per-call try AND the batch loop:
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index 2fa166cfe..3791699ae 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -1872,6 +1872,7 @@ async def test_navigate_refuses_a_url_carrying_a_resolved_credential_off_site()
@pytest.mark.asyncio
[email protected]("unresolvable_dns")
async def test_file_upload_from_a_local_path_carrying_the_username_is_not_refused(tmp_path: Path) -> None:
# The tool takes "a local path or URL", and a file downloaded earlier in the run is routinely named
# after the account. A path names no site, so reading it releases nothing and must not be refused.
@@ -2345,6 +2346,7 @@ async def test_a_url_argument_never_carries_a_totp_placeholder(
@pytest.mark.asyncio
[email protected]("public_dns")
async def test_navigate_to_a_url_that_merely_spells_a_vault_marker_goes_through(
monkeypatch: pytest.MonkeyPatch,
) -> None:
diff --git a/tests/unit/workflow/test_http_request_block.py b/tests/unit/workflow/test_http_request_block.py
index cdeffeb72..8553e4ca9 100644
--- a/tests/unit/workflow/test_http_request_block.py
+++ b/tests/unit/workflow/test_http_request_block.py
@@ -770,6 +770,7 @@ class TestHttpRequestBlockCredentialSiteConfinement:
requested.assert_not_called()
@pytest.mark.asyncio
+ @pytest.mark.usefixtures("public_dns")
async def test_execute_holds_a_same_site_file_fetch_to_the_credential_site(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
@@ -797,6 +798,7 @@ class TestHttpRequestBlockCredentialSiteConfinement:
assert authorize("https://collector.example.net/collect") is False
@pytest.mark.asyncio
+ @pytest.mark.usefixtures("public_dns")
async def test_execute_confines_only_the_file_entry_that_references_the_credential(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
@@ -827,6 +829,7 @@ class TestHttpRequestBlockCredentialSiteConfinement:
assert authorize("https://collector.example.net/x") is False
@pytest.mark.asyncio
+ @pytest.mark.usefixtures("public_dns")
async def test_execute_renders_a_templated_file_field_name_and_keeps_its_entry_confined(
self, monkeypatch: pytest.MonkeyPatch
) -> None: