Skip to content

Automate browser based workflows with AI

SKY-15226 Preserve Copilot timeout model provenance (#8324)

Andrew Neilson8636f1a02b3f
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index f28f3e889..fee60513f 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -2284,6 +2284,17 @@ _TIMEOUT_REPLY_UNVALIDATED = (
"accept it to save (note: it hasn't been verified end-to-end), or discard."
)
_TIMEOUT_REPLY_TESTED = "I ran out of time, but I have a tested draft for you. Accept it to save, or discard."
+_BROWSER_ABLATION_TIMEOUT_REPLY_DEFAULT = "The browser task did not finish before this turn ran out of time."
+_BROWSER_ABLATION_TIMEOUT_REPLY_WITH_ACTIVITY = (
+ f"{_BROWSER_ABLATION_TIMEOUT_REPLY_DEFAULT} I recorded browser activity before the timeout."
+)
+
+
+def _browser_ablation_timeout_reply(tool_activity_count: int) -> str:
+ if tool_activity_count:
+ return _BROWSER_ABLATION_TIMEOUT_REPLY_WITH_ACTIVITY
+ return _BROWSER_ABLATION_TIMEOUT_REPLY_DEFAULT
+
_MAX_TURNS_REPLY_DEFAULT = (
"I've reached the maximum number of steps, and I don't have a draft workflow to hand over. "
@@ -3026,6 +3037,14 @@ def _merge_exit_context(
def _build_timeout_exit_result(ctx: CopilotContext, global_llm_context: str | None) -> AgentResult:
+ if ctx.eval_mode == CopilotEvalMode.BROWSER_ABLATION:
+ return _build_exit_result(
+ ctx,
+ _browser_ablation_timeout_reply(len(ctx.eval_tool_activity)),
+ global_llm_context,
+ terminal_reason="timeout",
+ proposal_disposition="no_proposal",
+ )
return _build_wip_exit_result(
ctx,
global_llm_context,
@@ -3727,6 +3746,9 @@ async def _run_agent_loop_with_surface(
output_guardrails: list[Any],
allow_untested_retry: bool = False,
) -> Any:
+ # No model owns the attempt until setup completes and enforcement is ready to
+ # enter the model loop. This also clears a prior model before fallback setup.
+ ctx.resolved_model = None
from agents import Agent
from agents.mcp import MCPServerManager
@@ -3773,6 +3795,7 @@ async def _run_agent_loop_with_surface(
attempts = 2 if allow_untested_retry else 1
for attempt in range(attempts):
try:
+ ctx.resolved_model = model_name
result = await run_with_enforcement(
agent=agent,
initial_input=initial_input,
@@ -4880,9 +4903,6 @@ async def _run_copilot_turn_impl(
output_guardrails=output_guardrails,
allow_untested_retry=ctx.allow_untested_workflow_draft,
)
- # Recorded only after the attempt returns, so a model that failed and fell back is never
- # reported as the one that produced the turn.
- ctx.resolved_model = attempt_model_name
return attempt
try:
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index c175a358f..7b975f231 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -717,8 +717,8 @@ class AgentResult:
# "0 tokens" so eval cost grading can flag missing telemetry instead of
# silently passing as cheap.
total_tokens: int | None = None
- # Model name the attempt that actually returned ran on (primary or fallback). None when the
- # turn never reached an attempt; telemetry only.
+ # Model name for the terminal attempt (primary or fallback), including an interrupted attempt.
+ # None when the turn never reached an attempt; telemetry only.
resolved_model: str | None = None
# Set when the agent absorbed an asyncio cancellation initiated by an
# explicit user Stop. Lets the route route to a cancel-specific
diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.py
index 4484ff0aa..0d35effca 100644
--- a/skyvern/forge/sdk/schemas/workflow_copilot.py
+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py
@@ -293,7 +293,10 @@ class WorkflowCopilotStreamResponseUpdate(BaseModel):
response_type: ResponseType = Field("REPLY", description="Agent response classification")
resolved_model: str | None = Field(
None,
- description="Model name the attempt that produced this turn ran on (primary or fallback); None when unknown.",
+ description=(
+ "Model name for the terminal attempt (primary or fallback), including an interrupted attempt; "
+ "None when unknown."
+ ),
)
proposal_disposition: ProposalDisposition = Field(
"auto_applicable",
diff --git a/tests/unit/test_copilot_model_telemetry.py b/tests/unit/test_copilot_model_telemetry.py
index fe7a9bf81..fc5bef9b0 100644
--- a/tests/unit/test_copilot_model_telemetry.py
+++ b/tests/unit/test_copilot_model_telemetry.py
@@ -5,7 +5,7 @@ import contextlib
import json
from collections.abc import AsyncIterator, Iterator
from types import SimpleNamespace
-from typing import Any, cast
+from typing import Any, Self, cast
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -22,6 +22,7 @@ from structlog.testing import capture_logs
from skyvern.forge.sdk.copilot import agent as copilot_agent_module
from skyvern.forge.sdk.copilot import model_telemetry as model_telemetry_module
+from skyvern.forge.sdk.copilot.browser_ablation import CopilotEvalMode
from skyvern.forge.sdk.copilot.cache_envelope import CacheableSystemInstructions
from skyvern.forge.sdk.copilot.config import CopilotConfig
from skyvern.forge.sdk.copilot.model_telemetry import (
@@ -1000,7 +1001,7 @@ async def test_the_result_names_the_fallback_model_that_actually_returned(
def __init__(self, servers: object) -> None:
self.active_servers = servers
- async def __aenter__(self) -> FakeMCPServerManager:
+ async def __aenter__(self) -> Self:
return self
async def __aexit__(self, *args: object) -> None:
@@ -1053,3 +1054,154 @@ async def test_the_result_names_the_fallback_model_that_actually_returned(
assert result.resolved_model == "model-SECONDARY"
assert result.resolved_model != "model-PRIMARY"
+
+
+async def test_model_setup_failure_does_not_claim_the_unstarted_model(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class FailingMCPServerManager:
+ def __init__(self, _servers: object) -> None:
+ pass
+
+ async def __aenter__(self) -> Self:
+ raise RuntimeError("setup failed")
+
+ async def __aexit__(self, *args: object) -> None:
+ return None
+
+ def fake_resolve_model_config(
+ _handler: object, *, copilot_config: object = None, llm_key_override: str | None = None
+ ) -> tuple[str, object, str, bool]:
+ del copilot_config, llm_key_override
+ return "model-PRIMARY", object(), "PRIMARY", True
+
+ enforcement = AsyncMock()
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.agent._resolve_live_browser_session_id", AsyncMock(return_value=None)
+ )
+ monkeypatch.setattr("agents.mcp.MCPServerManager", FailingMCPServerManager)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.model_resolver.resolve_model_config", fake_resolve_model_config)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.run_with_enforcement", enforcement)
+
+ result = await copilot_agent_module.run_copilot_agent(
+ stream=MagicMock(send=AsyncMock(return_value=True)),
+ organization_id="org-1",
+ chat_request=SimpleNamespace(
+ message="build it",
+ workflow_id="wf-1",
+ workflow_permanent_id="wfp-1",
+ workflow_copilot_chat_id="chat-1",
+ workflow_run_id=None,
+ workflow_yaml="",
+ browser_session_id=None,
+ product_action=None,
+ ),
+ chat_history=[],
+ global_llm_context=None,
+ llm_api_handler=SimpleNamespace(llm_key="PRIMARY"),
+ raw_secret_safety_handler=AsyncMock(
+ return_value={"version": "1", "state": "clean", "handling": "none", "citations": []}
+ ),
+ api_key="sk-test",
+ config=CopilotConfig(),
+ )
+
+ assert result.resolved_model is None
+ enforcement.assert_not_awaited()
+
+
+ ("fallback_enabled", "expected_model"),
+ [
+ pytest.param(False, "model-PRIMARY", id="primary"),
+ pytest.param(True, "model-SECONDARY", id="fallback"),
+ ],
+)
+async def test_browser_ablation_timeout_reports_active_model_and_browser_work(
+ monkeypatch: pytest.MonkeyPatch,
+ fallback_enabled: bool,
+ expected_model: str,
+) -> None:
+ class FakeRateLimitError(Exception):
+ pass
+
+ FakeRateLimitError.__module__ = "openai"
+
+ class FakeMCPServerManager:
+ def __init__(self, servers: object) -> None:
+ self.active_servers = servers
+
+ async def __aenter__(self) -> Self:
+ return self
+
+ async def __aexit__(self, *args: object) -> None:
+ return None
+
+ def fake_resolve_model_config(
+ _handler: object, *, copilot_config: object = None, llm_key_override: str | None = None
+ ) -> tuple[str, object, str, bool]:
+ del copilot_config
+ key = llm_key_override or "PRIMARY"
+ return f"model-{key}", object(), key, True
+
+ attempt_count = 0
+
+ async def timeout_after_browser_activity(**kwargs: object) -> None:
+ nonlocal attempt_count
+ attempt_count += 1
+ if fallback_enabled and attempt_count == 1:
+ raise FakeRateLimitError("rate limit")
+ ctx = cast(copilot_agent_module.CopilotContext, kwargs["ctx"])
+ ctx.copilot_total_timeout_exceeded = True
+ ctx.eval_tool_activity = [{"tool_name": "navigate_browser", "success": True}]
+ raise asyncio.CancelledError
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.agent._resolve_live_browser_session_id", AsyncMock(return_value=None)
+ )
+ monkeypatch.setattr("agents.mcp.MCPServerManager", FakeMCPServerManager)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.model_resolver.resolve_model_config", fake_resolve_model_config)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.mcp_adapter.SkyvernOverlayMCPServer.list_tools",
+ AsyncMock(return_value=[]),
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.enforcement.run_with_enforcement",
+ AsyncMock(side_effect=timeout_after_browser_activity),
+ )
+
+ result = await copilot_agent_module.run_copilot_agent(
+ stream=MagicMock(send=AsyncMock(return_value=True)),
+ organization_id="org-1",
+ chat_request=SimpleNamespace(
+ message="research it",
+ workflow_id="wf-1",
+ workflow_permanent_id="wfp-1",
+ workflow_copilot_chat_id="chat-1",
+ workflow_run_id=None,
+ workflow_yaml="",
+ browser_session_id=None,
+ product_action=None,
+ ),
+ chat_history=[],
+ global_llm_context=None,
+ llm_api_handler=SimpleNamespace(llm_key="PRIMARY"),
+ raw_secret_safety_handler=AsyncMock(
+ return_value={"version": "1", "state": "clean", "handling": "none", "citations": []}
+ ),
+ api_key="sk-test",
+ config=CopilotConfig(fallback_llm_key="SECONDARY" if fallback_enabled else None),
+ eval_mode=CopilotEvalMode.BROWSER_ABLATION,
+ )
+
+ assert result.resolved_model == expected_model
+ assert result.user_response == copilot_agent_module._BROWSER_ABLATION_TIMEOUT_REPLY_WITH_ACTIVITY
+ assert "workflow" not in result.user_response.lower()
+ assert "draft" not in result.user_response.lower()
+ assert result.terminal_envelope is not None
+ assert result.terminal_envelope["terminal_cause"] == "deadline_expired"
+ assert result.browser_ablation_metadata is not None
+ assert result.browser_ablation_metadata["eval_mode"] == "browser_ablation"
+ assert result.browser_ablation_metadata["tool_activity"] == [{"tool_name": "navigate_browser", "success": True}]
diff --git a/tests/unit/test_copilot_timeout_wip.py b/tests/unit/test_copilot_timeout_wip.py
index 0ce67ef86..e2a01bdcc 100644
--- a/tests/unit/test_copilot_timeout_wip.py
+++ b/tests/unit/test_copilot_timeout_wip.py
@@ -8,6 +8,8 @@ import pytest
import yaml
from skyvern.forge.sdk.copilot.agent import (
+ _BROWSER_ABLATION_TIMEOUT_REPLY_DEFAULT,
+ _BROWSER_ABLATION_TIMEOUT_REPLY_WITH_ACTIVITY,
_CANCEL_REPLY_DEFAULT,
_CANCEL_REPLY_TESTED,
_CANCEL_REPLY_UNVALIDATED,
@@ -25,6 +27,7 @@ from skyvern.forge.sdk.copilot.agent import (
_build_timeout_exit_result,
_build_unexpected_error_exit_result,
)
+from skyvern.forge.sdk.copilot.browser_ablation import CopilotEvalMode
from skyvern.forge.sdk.copilot.completion_verification import CompletionVerificationResult, CriterionVerdict
from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (
DiagnosisInput,
@@ -312,6 +315,32 @@ def test_capacity_exit_state_disposition(
class TestBuildTimeoutExitResult:
+ def test_browser_ablation_timeout_without_activity_describes_only_the_browser_task(self) -> None:
+ ctx, _ = _state_ctx("no_workflow")
+ ctx.eval_mode = CopilotEvalMode.BROWSER_ABLATION
+ ctx.eval_tool_activity = []
+ ctx.copilot_total_timeout_exceeded = True
+
+ result = _build_timeout_exit_result(ctx, global_llm_context=None)
+
+ assert result.user_response == _BROWSER_ABLATION_TIMEOUT_REPLY_DEFAULT
+ assert "browser task did not finish" in result.user_response.lower()
+ assert "workflow" not in result.user_response.lower()
+ assert "draft" not in result.user_response.lower()
+
+ @pytest.mark.parametrize("state_kind", ["no_workflow", "untested", "passing_test"])
+ def test_browser_ablation_timeout_uses_browser_work_for_every_draft_state(self, state_kind: str) -> None:
+ ctx, _ = _state_ctx(state_kind)
+ ctx.eval_mode = CopilotEvalMode.BROWSER_ABLATION
+ ctx.eval_tool_activity = [{"tool_name": "navigate_browser", "success": True}]
+ ctx.copilot_total_timeout_exceeded = True
+
+ result = _build_timeout_exit_result(ctx, global_llm_context=None)
+
+ assert result.user_response == _BROWSER_ABLATION_TIMEOUT_REPLY_WITH_ACTIVITY
+ assert "workflow" not in result.user_response.lower()
+ assert "draft" not in result.user_response.lower()
+
def test_missing_yaml_drops_untested_proposal(self) -> None:
wf = MagicMock(name="wf")
ctx = _ctx(last_workflow=wf, last_workflow_yaml=None, last_test_ok=None)
diff --git a/tests/unit/test_workflow_copilot_route.py b/tests/unit/test_workflow_copilot_route.py
index bd166559d..b0202fbd7 100644
--- a/tests/unit/test_workflow_copilot_route.py
+++ b/tests/unit/test_workflow_copilot_route.py
@@ -228,7 +228,7 @@ async def test_finalise_normal_turn_finalizes_terminal_envelope_without_auto_acc
@pytest.mark.asyncio
-async def test_finalise_normal_turn_emits_selected_only_browser_ablation_metadata(
+async def test_browser_ablation_timeout_response_preserves_model_terminal_cause_and_activity(
monkeypatch: pytest.MonkeyPatch,
) -> None:
chat = SimpleNamespace(
@@ -248,11 +248,28 @@ async def test_finalise_normal_turn_emits_selected_only_browser_ablation_metadat
"tool_activity": [{"tool_name": "navigate_browser", "success": True}],
"screenshot_frames": [{"capture_id": "frame-1", "image_b64": "encoded"}],
}
+ envelope = assemble_terminal_envelope(
+ response_type="REPLY",
+ verified=False,
+ workflow_applied=False,
+ proposal_disposition="no_proposal",
+ run_outcomes=[],
+ blocker_reason=None,
+ halt_kind=None,
+ attempted=None,
+ workflow_mutated=False,
+ workflow_attempted=False,
+ terminal_cause="deadline_expired",
+ )
+ assert envelope is not None
agent_result = AgentResult(
- user_response="done",
+ user_response=agent_module._BROWSER_ABLATION_TIMEOUT_REPLY_WITH_ACTIVITY,
updated_workflow=None,
global_llm_context=None,
response_type="REPLY",
+ resolved_model="azure/gpt-5.6-terra",
+ proposal_disposition="no_proposal",
+ terminal_envelope=envelope.model_dump(mode="json"),
browser_ablation_metadata=metadata,
)
setup_new_copilot_mocks(monkeypatch, chat, original_workflow, agent_result)
@@ -269,6 +286,10 @@ async def test_finalise_normal_turn_emits_selected_only_browser_ablation_metadat
response_frame = stream.send.await_args.args[0]
assert isinstance(response_frame, WorkflowCopilotBrowserAblationResponseUpdate)
+ assert response_frame.resolved_model == "azure/gpt-5.6-terra"
+ assert response_frame.message == agent_module._BROWSER_ABLATION_TIMEOUT_REPLY_WITH_ACTIVITY
+ assert response_frame.terminal_envelope is not None
+ assert response_frame.terminal_envelope["terminal_cause"] == "deadline_expired"
for key, value in metadata.items():
assert getattr(response_frame, key) == value