Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(copilot): emit the recorded per-run outcome verdict as a typed narrative event (SKY-10873) (#6528)
Andrew Neilsond60296b463e8
diff --git a/docs/changelog.mdx b/docs/changelog.mdxindex 3a7f0bd69..90699c39d 100644--- a/docs/changelog.mdx+++ b/docs/changelog.mdx@@ -44,7 +44,7 @@ keywords:<p className="cl-subtitle">New features, improvements, and fixes in Skyvern</p><a id="week-jun-8-2026"></a>-<Update label="Week of June 8, 2026" description="Editor onboarding, Copilot modes, GCS storage, API docs split, OTP fixes">+<Update label="Week of June 8, 2026" description="Multi-tab agent control, Gemini 3.5 Flash, GCP Vault, bulk agent actions, credential clears, code-block credentials">## New features@@ -52,6 +52,13 @@ keywords:- **GCS Storage Backend** — Added Google Cloud Storage as an artifact storage backend for self-hosted deployments. ([#6442](https://github.com/Skyvern-AI/skyvern/pull/6442))- **Key-Optional Labels and Flexible Tag Filters** — Tags now support key-optional labels, and tag filter queries accept more flexible formats for richer agent organization. ([#6458](https://github.com/Skyvern-AI/skyvern/pull/6458))- **Self-Serve Editor Onboarding** — New users in the workflow editor now see a get-started modal with intent routing and template cards, a 4-stop guided product tour, and smart empty states on the dashboard and runs pages to accelerate time-to-first-automation. ([#6475](https://github.com/Skyvern-AI/skyvern/pull/6475))+- **Multi-Tab Browser Control** — The autonomous agent loop can now open and interact with multiple browser tabs simultaneously, enabling workflows that span across new tab links and pop-ups. ([#6507](https://github.com/Skyvern-AI/skyvern/pull/6507))+- **Gemini 3.5 Flash Model Support** — Added Google Gemini 3.5 Flash as a selectable LLM for agent runs, providing a faster inference option. ([#6505](https://github.com/Skyvern-AI/skyvern/pull/6505))+- **GCP Secret Manager Vault Adapter** — Added Google Cloud Secret Manager as a supported vault backend for storing and retrieving secrets in self-hosted deployments. ([#6488](https://github.com/Skyvern-AI/skyvern/pull/6488))+- **Bulk Actions on Agents List** — You can now select multiple agents at once and apply bulk actions directly from the agents list page. ([#6485](https://github.com/Skyvern-AI/skyvern/pull/6485))+- **Self-Service Credential Clears** — Saved credentials can now be individually cleared from the credentials settings page without deleting and recreating them. ([#6480](https://github.com/Skyvern-AI/skyvern/pull/6480))+- **Per-Run Session Recordings as Artifacts** — Recordings are now clipped to each run's time window and stored as downloadable run-scoped artifacts. ([#6479](https://github.com/Skyvern-AI/skyvern/pull/6479))+- **Credential-Aware Scouting in Code-Block Mode** — The Copilot now uses saved credentials while scouting pages for code-block generation and produces credential-typed code that fills login fields using your stored credentials. ([#6521](https://github.com/Skyvern-AI/skyvern/pull/6521))## Improvements@@ -64,6 +71,10 @@ keywords:- **Block Title Editable from Settings Sidebar** — Workflow block titles can now be edited from the right-hand settings sidebar, without needing to use the inline editor on the canvas. ([#6443](https://github.com/Skyvern-AI/skyvern/pull/6443))- **API Reference Split into Agents and Runs Sections** — The public API reference is now organized into separate Agents and Runs sections for easier navigation. ([#6448](https://github.com/Skyvern-AI/skyvern/pull/6448))- **Label-First Tag Editor and Flexible Tag Filter UI** — The tag editor now accepts standalone labels or `group:label` format in a single input, and the filter bar supports filtering by label, group, or group:label for richer agent organization. ([#6470](https://github.com/Skyvern-AI/skyvern/pull/6470))+- **2FA Field Progressive Disclosure in Login Block** — Two-factor authentication fields in the login workflow block are now collapsed by default and expanded on demand, reducing visual noise for workflows that don't use 2FA. ([#6490](https://github.com/Skyvern-AI/skyvern/pull/6490))+- **Persistent Browser Session Profile Generation Now Opt-In** — Automatic browser profile generation during persistent sessions is now opt-in, giving you explicit control over when profiles are captured. ([#6489](https://github.com/Skyvern-AI/skyvern/pull/6489))+- **Icon-Only Status Pills on Mobile Viewports** — Status badges now render in a compact icon-only format on small screen widths, preventing layout overflow on mobile devices. ([#6481](https://github.com/Skyvern-AI/skyvern/pull/6481))+- **Hardened Webhook Delivery** — Workflow webhook delivery is now more reliable, with improved handling of transient failures and prioritized delivery ordering. ([#6478](https://github.com/Skyvern-AI/skyvern/pull/6478))## Bug fixes@@ -72,6 +83,12 @@ keywords:- Fixed persistent-session screen recordings not appearing in the run view when the recording timestamp fell outside the run's time window. ([#6454](https://github.com/Skyvern-AI/skyvern/pull/6454))- Fixed Copilot inconsistently asking for a URL before running discovery when the user had only named a site without providing one. ([#6473](https://github.com/Skyvern-AI/skyvern/pull/6473))- Fixed Copilot asking for a URL after already successfully navigating to the requested site during discovery. ([#6472](https://github.com/Skyvern-AI/skyvern/pull/6472))+- Fixed self-hosted deployments rejecting requests with "Invalid credentials" (HTTP 403) when the Docker UI injected an API key that the container's server incorrectly filtered out.+- Fixed persistent session recordings not being finalized when the video encoding process outlasted the session's cleanup window. ([#6519](https://github.com/Skyvern-AI/skyvern/pull/6519))+- Fixed the saved credentials status indicator not updating until the page was manually refreshed. ([#6517](https://github.com/Skyvern-AI/skyvern/pull/6517))+- Fixed the workflow run timeline rendering blocks in branch-tree order instead of execution order, producing a confusing step sequence. ([#6515](https://github.com/Skyvern-AI/skyvern/pull/6515))+- Fixed downloaded files inside loop blocks being shared across all iterations instead of scoped to the block that downloaded them. ([#6487](https://github.com/Skyvern-AI/skyvern/pull/6487))+- Fixed session recordings defaulting to an incorrect resolution; recordings now use Playwright's default viewport size. ([#6524](https://github.com/Skyvern-AI/skyvern/pull/6524))</Update>diff --git a/fern/docs/changelog.mdx b/fern/docs/changelog.mdxindex a52115aea..cb578d721 100644--- a/fern/docs/changelog.mdx+++ b/fern/docs/changelog.mdx@@ -29,7 +29,7 @@ mode: custom<h1 className="cl-title">Changelog</h1><p className="cl-subtitle">New features, improvements, and fixes in Skyvern</p>-<Update label="Week of June 8, 2026" description="Editor onboarding, Copilot modes, GCS storage, API docs split, OTP fixes">+<Update label="Week of June 8, 2026" description="Multi-tab agent control, Gemini 3.5 Flash, GCP Vault, bulk agent actions, credential clears, code-block credentials">## New features@@ -37,6 +37,13 @@ mode: custom- **GCS Storage Backend** — Added Google Cloud Storage as an artifact storage backend for self-hosted deployments. ([#6442](https://github.com/Skyvern-AI/skyvern/pull/6442))- **Key-Optional Labels and Flexible Tag Filters** — Tags now support key-optional labels, and tag filter queries accept more flexible formats for richer agent organization. ([#6458](https://github.com/Skyvern-AI/skyvern/pull/6458))- **Self-Serve Editor Onboarding** — New users in the workflow editor now see a get-started modal with intent routing and template cards, a 4-stop guided product tour, and smart empty states on the dashboard and runs pages to accelerate time-to-first-automation. ([#6475](https://github.com/Skyvern-AI/skyvern/pull/6475))+- **Multi-Tab Browser Control** — The autonomous agent loop can now open and interact with multiple browser tabs simultaneously, enabling workflows that span across new tab links and pop-ups. ([#6507](https://github.com/Skyvern-AI/skyvern/pull/6507))+- **Gemini 3.5 Flash Model Support** — Added Google Gemini 3.5 Flash as a selectable LLM for agent runs, providing a faster inference option. ([#6505](https://github.com/Skyvern-AI/skyvern/pull/6505))+- **GCP Secret Manager Vault Adapter** — Added Google Cloud Secret Manager as a supported vault backend for storing and retrieving secrets in self-hosted deployments. ([#6488](https://github.com/Skyvern-AI/skyvern/pull/6488))+- **Bulk Actions on Agents List** — You can now select multiple agents at once and apply bulk actions directly from the agents list page. ([#6485](https://github.com/Skyvern-AI/skyvern/pull/6485))+- **Self-Service Credential Clears** — Saved credentials can now be individually cleared from the credentials settings page without deleting and recreating them. ([#6480](https://github.com/Skyvern-AI/skyvern/pull/6480))+- **Per-Run Session Recordings as Artifacts** — Recordings are now clipped to each run's time window and stored as downloadable run-scoped artifacts. ([#6479](https://github.com/Skyvern-AI/skyvern/pull/6479))+- **Credential-Aware Scouting in Code-Block Mode** — The Copilot now uses saved credentials while scouting pages for code-block generation and produces credential-typed code that fills login fields using your stored credentials. ([#6521](https://github.com/Skyvern-AI/skyvern/pull/6521))## Improvements@@ -49,6 +56,10 @@ mode: custom- **Block Title Editable from Settings Sidebar** — Workflow block titles can now be edited from the right-hand settings sidebar, without needing to use the inline editor on the canvas. ([#6443](https://github.com/Skyvern-AI/skyvern/pull/6443))- **API Reference Split into Agents and Runs Sections** — The public API reference is now organized into separate Agents and Runs sections for easier navigation. ([#6448](https://github.com/Skyvern-AI/skyvern/pull/6448))- **Label-First Tag Editor and Flexible Tag Filter UI** — The tag editor now accepts standalone labels or `group:label` format in a single input, and the filter bar supports filtering by label, group, or group:label for richer agent organization. ([#6470](https://github.com/Skyvern-AI/skyvern/pull/6470))+- **2FA Field Progressive Disclosure in Login Block** — Two-factor authentication fields in the login workflow block are now collapsed by default and expanded on demand, reducing visual noise for workflows that don't use 2FA. ([#6490](https://github.com/Skyvern-AI/skyvern/pull/6490))+- **Persistent Browser Session Profile Generation Now Opt-In** — Automatic browser profile generation during persistent sessions is now opt-in, giving you explicit control over when profiles are captured. ([#6489](https://github.com/Skyvern-AI/skyvern/pull/6489))+- **Icon-Only Status Pills on Mobile Viewports** — Status badges now render in a compact icon-only format on small screen widths, preventing layout overflow on mobile devices. ([#6481](https://github.com/Skyvern-AI/skyvern/pull/6481))+- **Hardened Webhook Delivery** — Workflow webhook delivery is now more reliable, with improved handling of transient failures and prioritized delivery ordering. ([#6478](https://github.com/Skyvern-AI/skyvern/pull/6478))## Bug fixes@@ -57,6 +68,12 @@ mode: custom- Fixed persistent-session screen recordings not appearing in the run view when the recording timestamp fell outside the run's time window. ([#6454](https://github.com/Skyvern-AI/skyvern/pull/6454))- Fixed Copilot inconsistently asking for a URL before running discovery when the user had only named a site without providing one. ([#6473](https://github.com/Skyvern-AI/skyvern/pull/6473))- Fixed Copilot asking for a URL after already successfully navigating to the requested site during discovery. ([#6472](https://github.com/Skyvern-AI/skyvern/pull/6472))+- Fixed self-hosted deployments rejecting requests with "Invalid credentials" (HTTP 403) when the Docker UI injected an API key that the container's server incorrectly filtered out.+- Fixed persistent session recordings not being finalized when the video encoding process outlasted the session's cleanup window. ([#6519](https://github.com/Skyvern-AI/skyvern/pull/6519))+- Fixed the saved credentials status indicator not updating until the page was manually refreshed. ([#6517](https://github.com/Skyvern-AI/skyvern/pull/6517))+- Fixed the workflow run timeline rendering blocks in branch-tree order instead of execution order, producing a confusing step sequence. ([#6515](https://github.com/Skyvern-AI/skyvern/pull/6515))+- Fixed downloaded files inside loop blocks being shared across all iterations instead of scoped to the block that downloaded them. ([#6487](https://github.com/Skyvern-AI/skyvern/pull/6487))+- Fixed session recordings defaulting to an incorrect resolution; recordings now use Playwright's default viewport size. ([#6524](https://github.com/Skyvern-AI/skyvern/pull/6524))</Update>diff --git a/skyvern/cli/core/result.py b/skyvern/cli/core/result.pyindex a81285ee5..0d1094e0f 100644--- a/skyvern/cli/core/result.py+++ b/skyvern/cli/core/result.py@@ -72,6 +72,7 @@ class BrowserContext:mode: strsession_id: str | None = Nonecdp_url: str | None = None+ can_access_localhost: bool | None = Nonedef to_dict(self) -> dict[str, Any]:return {diff --git a/skyvern/cli/core/session_manager.py b/skyvern/cli/core/session_manager.pyindex 20791b887..91d2f8e69 100644--- a/skyvern/cli/core/session_manager.py+++ b/skyvern/cli/core/session_manager.py@@ -12,6 +12,8 @@ from typing import TYPE_CHECKING, Any, AsyncIteratorimport structlog+from skyvern.config import settings+from .api_key_hash import hash_api_key_for_cachefrom .client import get_active_api_key, get_skyvern, has_api_key_overridefrom .result import BrowserContext, ErrorCode, make_error@@ -91,6 +93,10 @@ def unregister_copilot_session(session_id: str) -> None:_copilot_sessions.pop(session_id, None)+def _explicit_cloud_session_can_access_localhost() -> bool:+ return settings.ENV == "local"++def get_current_session() -> SessionState:global _global_session@@ -223,7 +229,11 @@ async def resolve_browser(try:if session_id:browser = await skyvern.connect_to_cloud_browser_session(session_id)- ctx = BrowserContext(mode="cloud_session", session_id=session_id)+ ctx = BrowserContext(+ mode="cloud_session",+ session_id=session_id,+ can_access_localhost=_explicit_cloud_session_can_access_localhost(),+ )set_current_session(SessionState(browser=browser, context=ctx, api_key_hash=active_api_key_hash))return browser, ctx@@ -235,13 +245,17 @@ async def resolve_browser(if local:browser = await skyvern.launch_local_browser(headless=headless)- ctx = BrowserContext(mode="local")+ ctx = BrowserContext(mode="local", can_access_localhost=True)set_current_session(SessionState(browser=browser, context=ctx, api_key_hash=active_api_key_hash))return browser, ctxif create_session:browser = await skyvern.launch_cloud_browser(timeout=timeout)- ctx = BrowserContext(mode="cloud_session", session_id=browser.browser_session_id)+ ctx = BrowserContext(+ mode="cloud_session",+ session_id=browser.browser_session_id,+ can_access_localhost=False,+ )set_current_session(SessionState(browser=browser, context=ctx, api_key_hash=active_api_key_hash))return browser, ctxexcept Exception:diff --git a/skyvern/cli/mcp_tools/browser.py b/skyvern/cli/mcp_tools/browser.pyindex daad841cc..8a3a708e6 100644--- a/skyvern/cli/mcp_tools/browser.py+++ b/skyvern/cli/mcp_tools/browser.py@@ -65,6 +65,10 @@ def _blank_to_none(value: str | None) -> str | None:return value if value is None or value.strip() else None+def _must_reject_localhost_url(ctx: Any, url: str | None) -> bool:+ return bool(url and is_localhost_url(url) and getattr(ctx, "can_access_localhost", None) is False)++_SelectorMode = Annotated[Literal["resilient", "direct"],Field(@@ -111,7 +115,7 @@ async def skyvern_navigate(except BrowserNotAvailableError:return make_result("skyvern_navigate", ok=False, error=no_browser_error())- if ctx.mode == "cloud_session" and is_localhost_url(url):+ if _must_reject_localhost_url(ctx, url):return make_result("skyvern_navigate",ok=False,@@ -1455,7 +1459,7 @@ async def skyvern_run_task(except BrowserNotAvailableError:return make_result("skyvern_run_task", ok=False, error=no_browser_error())- if url and ctx.mode == "cloud_session" and is_localhost_url(url):+ if _must_reject_localhost_url(ctx, url):return make_result("skyvern_run_task",ok=False,diff --git a/skyvern/cli/mcp_tools/session.py b/skyvern/cli/mcp_tools/session.pyindex a842a7116..6ce43e3dc 100644--- a/skyvern/cli/mcp_tools/session.py+++ b/skyvern/cli/mcp_tools/session.py@@ -110,7 +110,11 @@ async def skyvern_browser_session_create(create_kwargs["extensions"] = extensionssession = await skyvern.create_browser_session(**create_kwargs)timer.mark("sdk")- ctx = BrowserContext(mode="cloud_session", session_id=session.browser_session_id)+ ctx = BrowserContext(+ mode="cloud_session",+ session_id=session.browser_session_id,+ can_access_localhost=False,+ )return make_result("skyvern_browser_session_create",browser_context=ctx,@@ -132,9 +136,13 @@ async def skyvern_browser_session_create(timer.mark("sdk")if result.local:- ctx = BrowserContext(mode="local")+ ctx = BrowserContext(mode="local", can_access_localhost=True)else:- ctx = BrowserContext(mode="cloud_session", session_id=result.session_id)+ ctx = BrowserContext(+ mode="cloud_session",+ session_id=result.session_id,+ can_access_localhost=False,+ )set_current_session(SessionState(browser=browser, context=ctx, api_key_hash=_session_api_key_hash()))except ValueError as e:diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex e4704fdef..80a5f4370 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -958,6 +958,8 @@ def _build_narrative_payload(design_activity: list[NarrativeActivityEntry] = narrator_state.design_activity if narrator_state is not None else []block_labels: list[str] = []blocks: list[NarrativeBlock] = []+ recorded_outcome = ctx.last_run_outcome+ outcome_labels = set(ctx.last_run_outcome_block_labels) if recorded_outcome is not None else set()staged = ctx.staged_workflowif staged is not None and getattr(staged, "workflow_definition", None) is not None:for block in staged.workflow_definition.blocks:@@ -971,20 +973,23 @@ def _build_narrative_payload(else:block_type = str(block_type_value or "task")raw_status = ctx.block_state_map.get(label)- blocks.append(- {- "label": label,- "blockType": block_type,- "state": _block_ui_state(- raw_status,- drafted_fallback=ctx.has_staged_proposal,- ),- "lastSeenIteration": 0,- "activity": list(block_activity.get(label, [])),- "startedAt": ctx.block_started_at_map.get(label),- "endedAt": ctx.block_ended_at_map.get(label),- }- )+ block_entry: NarrativeBlock = {+ "label": label,+ "blockType": block_type,+ "state": _block_ui_state(+ raw_status,+ drafted_fallback=ctx.has_staged_proposal,+ ),+ "lastSeenIteration": 0,+ "activity": list(block_activity.get(label, [])),+ "startedAt": ctx.block_started_at_map.get(label),+ "endedAt": ctx.block_ended_at_map.get(label),+ }+ if recorded_outcome is not None and label in outcome_labels:+ block_entry["outcome"] = recorded_outcome.verdict+ if recorded_outcome.display_reason is not None:+ block_entry["outcomeReason"] = recorded_outcome.display_reason+ blocks.append(block_entry)draft: NarrativeDraft | None = ({"blockCount": len(block_labels), "blockLabels": block_labels, "summary": None}if ctx.has_staged_proposaldiff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.pyindex fa238994b..7f3ac5321 100644--- a/skyvern/forge/sdk/copilot/context.py+++ b/skyvern/forge/sdk/copilot/context.py@@ -47,6 +47,8 @@ class NarrativeBlock(TypedDict):activity: list[NarrativeActivityEntry]startedAt: str | NoneendedAt: str | None+ outcome: NotRequired[str]+ outcomeReason: NotRequired[str]# Mirror of the FE TurnNarrativeState; camelCase keys match the wire shape.diff --git a/skyvern/forge/sdk/copilot/run_outcome.py b/skyvern/forge/sdk/copilot/run_outcome.pynew file mode 100644index 000000000..246a525c0--- /dev/null+++ b/skyvern/forge/sdk/copilot/run_outcome.py@@ -0,0 +1,26 @@+"""Typed per-run outcome verdict recorded at the run-result seam; rendering+surfaces consume it instead of re-deriving success from raw block status."""++from __future__ import annotations++from dataclasses import dataclass+from typing import Literal++RunOutcomeVerdict = Literal["evaluating", "demonstrated", "not_demonstrated", "not_evaluated"]+RecordedRunOutcomeVerdict = Literal["demonstrated", "not_demonstrated", "not_evaluated"]+RunOutcomeReasonCode = Literal["blocker_reported", "no_meaningful_output", "outcome_not_demonstrated"]++_DISPLAY_REASON_MAX_CHARS = 160+++@dataclass(frozen=True)+class RecordedRunOutcome:+ verdict: RecordedRunOutcomeVerdict+ reason_code: RunOutcomeReasonCode | None = None+ display_reason: str | None = None+++def run_outcome_display_reason(text: str | None) -> str | None:+ if not isinstance(text, str) or not text.strip():+ return None+ return " ".join(text.split())[:_DISPLAY_REASON_MAX_CHARS]diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex 63b01808c..cd80343e0 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -24,6 +24,7 @@ from skyvern.cli.core.session_manager import (scoped_session,unregister_copilot_session,)+from skyvern.config import settingsfrom skyvern.forge import appfrom skyvern.forge.sdk.copilot.config import BlockAuthoringPolicyfrom skyvern.forge.sdk.copilot.screenshot_utils import ScreenshotEntry@@ -36,6 +37,7 @@ if TYPE_CHECKING:from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignalfrom skyvern.forge.sdk.copilot.completion_verification import CompletionVerificationResultfrom skyvern.forge.sdk.copilot.request_policy import RequestPolicy+ from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcomefrom skyvern.forge.sdk.routes.event_source_stream import EventSourceStreamfrom skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSession@@ -87,6 +89,10 @@ def _browser_context_is_attachable(browser_context: object | None) -> bool:return True+def _copilot_session_can_access_localhost() -> bool:+ return settings.ENV == "local"++def _browser_session_status_is_final(status: str | None) -> bool:return status in _FINAL_BROWSER_SESSION_STATUSES@@ -204,6 +210,10 @@ class AgentContext:last_good_workflow: Any | None = Nonelast_good_workflow_yaml: str | None = Nonelast_run_blocks_workflow_run_id: str | None = None+ last_run_blocks_block_ids: list[str] = field(default_factory=list)+ last_run_blocks_block_labels: list[str] = field(default_factory=list)+ last_run_outcome: RecordedRunOutcome | None = None+ last_run_outcome_block_labels: list[str] = field(default_factory=list)completion_verification_result: CompletionVerificationResult | None = Noneoutcome_verification_trace_snapshot: dict[str, Any] = field(default_factory=dict)composition_page_evidence: dict[str, Any] | None = None@@ -335,7 +345,11 @@ async def mcp_browser_context(ctx: AgentContext) -> AsyncIterator[None]:browser_state.browser_context,browser_session_id=ctx.browser_session_id,)- mcp_ctx = MCPBrowserContext(mode="cloud_session", session_id=ctx.browser_session_id)+ mcp_ctx = MCPBrowserContext(+ mode="cloud_session",+ session_id=ctx.browser_session_id,+ can_access_localhost=_copilot_session_can_access_localhost(),+ )active_key = get_active_api_key()state = SessionState(browser=skyvern_browser,diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.pyindex 73ebaef95..5ea21b90c 100644--- a/skyvern/forge/sdk/copilot/tools/__init__.py+++ b/skyvern/forge/sdk/copilot/tools/__init__.py@@ -86,9 +86,7 @@ from .completion import _build_run_evidence_snapshot as _build_run_evidence_snapfrom .completion import _completion_verification_handler as _completion_verification_handlerfrom .completion import _is_outcome_evidence_candidate as _is_outcome_evidence_candidatefrom .completion import _is_unfinished_run_verification_candidate as _is_unfinished_run_verification_candidate-from .completion import (- _maybe_run_completion_verification,-)+from .completion import _maybe_run_completion_verification as _maybe_run_completion_verificationfrom .completion import (_maybe_run_completion_verification_from_page_observation as _maybe_run_completion_verification_from_page_observation,)@@ -213,9 +211,12 @@ from .run_execution import _progress_marker as _progress_markerfrom .run_execution import _read_progress_sources as _read_progress_sourcesfrom .run_execution import (_record_diagnosis_repair_contract,- _record_run_blocks_result,+)+from .run_execution import _record_run_blocks_result as _record_run_blocks_result+from .run_execution import (_run_blocks_and_collect_debug,_run_blocks_span_data,+ _verify_and_record_run_blocks_result,)from .run_execution import _watchdog_error_message as _watchdog_error_messagefrom .run_execution import _watchdog_exit_allows_terminal_promotion as _watchdog_exit_allows_terminal_promotion@@ -468,8 +469,7 @@ async def run_blocks_tool(block_outputs_to_seed=block_outputs_to_seed,frontier_start_label=frontier_start_label,)- completion_verification = await _maybe_run_completion_verification(copilot_ctx, result, handler_start)- _record_run_blocks_result(copilot_ctx, result, completion_verification=completion_verification)+ completion_verification = await _verify_and_record_run_blocks_result(copilot_ctx, result, handler_start)tool_visible_result = _tool_visible_result_after_completion_verification(copilot_ctx,result,@@ -752,8 +752,7 @@ async def update_and_run_blocks_tool(block_outputs_to_seed=block_outputs_to_seed,frontier_start_label=frontier_start_label,)- completion_verification = await _maybe_run_completion_verification(copilot_ctx, run_result, handler_start)- _record_run_blocks_result(copilot_ctx, run_result, completion_verification=completion_verification)+ completion_verification = await _verify_and_record_run_blocks_result(copilot_ctx, run_result, handler_start)tool_visible_result = _tool_visible_result_after_completion_verification(copilot_ctx,run_result,diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.pyindex de139b906..d953a9144 100644--- a/skyvern/forge/sdk/copilot/tools/run_execution.py+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py@@ -6,7 +6,7 @@ import jsonimport timefrom collections import defaultdictfrom collections.abc import Mapping-from datetime import datetime+from datetime import datetime, timezonefrom typing import Any, Literalfrom urllib.parse import urlparse@@ -43,11 +43,18 @@ from skyvern.forge.sdk.copilot.output_utils import (iter_failure_reasons,truncate_output,)+from skyvern.forge.sdk.copilot.run_outcome import (+ RecordedRunOutcome,+ RunOutcomeReasonCode,+ RunOutcomeVerdict,+ run_outcome_display_reason,+)from skyvern.forge.sdk.copilot.runtime import (AgentContext,ensure_browser_session,)from skyvern.forge.sdk.copilot.tracing_setup import copilot_span+from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotRunOutcomeUpdate, WorkflowCopilotStreamMessageTypefrom skyvern.forge.sdk.settings_manager import SettingsManagerfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRun, WorkflowRunStatusfrom skyvern.schemas.workflows import BlockType@@ -77,6 +84,7 @@ from .blockers import ()from .completion import (_emit_completion_verification_trace,+ _maybe_run_completion_verification,_outcome_failure_warrants_repair,_outcome_unverified_reason,)@@ -621,6 +629,8 @@ async def _run_blocks_and_collect_debug(ctx.last_requested_block_labels = list(block_labels)ctx.last_executed_block_labels = list(labels_to_execute)ctx.last_frontier_start_label = frontier_start_label+ ctx.last_run_blocks_block_ids = []+ ctx.last_run_blocks_block_labels = []# Verified state is NOT invalidated pre-run. On a failed / partial run we# want the prior verified prefix preserved so the next edit can still use@@ -1041,6 +1051,13 @@ async def _run_blocks_and_collect_debug(block_outputs_by_label[block.label] = block.outputresults.append(block_result)+ # Repository returns DESC by created_at; reverse for chronological order.+ run_block_rows = list(reversed(blocks))+ ctx.last_run_blocks_block_ids = list(+ dict.fromkeys(block.workflow_run_block_id for block in run_block_rows if block.workflow_run_block_id)+ )+ ctx.last_run_blocks_block_labels = list(dict.fromkeys(block.label for block in run_block_rows if block.label))+await _attach_action_traces(blocks, results, ctx.organization_id)# final_status is guaranteed set here: every non-success exit returns@@ -1382,7 +1399,9 @@ def _update_verification_evidence_from_run_result(copilot_ctx: AgentContext, resdef _record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any], completion_verification: CompletionVerificationResult | None = None-) -> None:+) -> RecordedRunOutcome | None:+ """Record the run adjudication on ctx; for an ok run, return the typed+ per-run outcome verdict mirroring exactly what was recorded."""run_ok = bool(result.get("ok", False))data = result.get("data")run_id = data.get("workflow_run_id") if isinstance(data, dict) else None@@ -1403,6 +1422,8 @@ def _record_run_blocks_result(if completion_verification is not None and completion_verification.status == "evaluated":copilot_ctx.last_outcome_gate_reason = _outcome_unverified_reason(copilot_ctx, completion_verification)copilot_ctx.last_test_suspicious_success = False+ copilot_ctx.last_run_outcome = None+ copilot_ctx.last_run_outcome_block_labels = []copilot_ctx.suspicious_success_nudge_count = 0copilot_ctx.last_test_anti_bot = Noneprior_budget_flag = copilot_ctx.last_failure_category_top == PER_TOOL_BUDGET_FAILURE_CATEGORY@@ -1481,7 +1502,14 @@ def _record_run_blocks_result(data["failure_categories"] = [anti_bot_category]update_repeated_failure_state(copilot_ctx, result)_update_verification_evidence_from_run_result(copilot_ctx, result)- return+ return _stash_recorded_run_outcome(+ copilot_ctx,+ RecordedRunOutcome(+ verdict="not_demonstrated",+ reason_code="blocker_reported",+ display_reason=run_outcome_display_reason(structured_blocker),+ ),+ )if empty_data_blocks:copilot_ctx.last_test_ok = Nonecopilot_ctx.last_test_suspicious_success = True@@ -1496,7 +1524,14 @@ def _record_run_blocks_result(copilot_ctx.probable_site_block_streak_count = 0update_repeated_failure_state(copilot_ctx, result)_update_verification_evidence_from_run_result(copilot_ctx, result)- return+ return _stash_recorded_run_outcome(+ copilot_ctx,+ RecordedRunOutcome(+ verdict="not_demonstrated",+ reason_code="no_meaningful_output",+ display_reason=run_outcome_display_reason(copilot_ctx.last_test_failure_reason),+ ),+ )copilot_ctx.failed_test_nudge_count = 0copilot_ctx.null_data_streak_count = 0copilot_ctx.probable_site_block_streak_count = 0@@ -1531,7 +1566,7 @@ def _record_run_blocks_result()update_repeated_failure_state(copilot_ctx, result)_update_verification_evidence_from_run_result(copilot_ctx, result)- return+ return _stash_recorded_run_outcome(copilot_ctx, _adjudicated_run_outcome(copilot_ctx, completion_verification))copilot_ctx.last_failed_workflow_yaml = getattr(copilot_ctx, "workflow_yaml", None)copilot_ctx.last_test_non_retriable_nav_error = _detect_non_retriable_nav_error(result)@@ -1554,6 +1589,100 @@ def _record_run_blocks_result(copilot_ctx.last_test_failure_reason = str(result["error"])update_repeated_failure_state(copilot_ctx, result)_update_verification_evidence_from_run_result(copilot_ctx, result)+ return None+++def _stash_recorded_run_outcome(copilot_ctx: Any, outcome: RecordedRunOutcome) -> RecordedRunOutcome:+ copilot_ctx.last_run_outcome = outcome+ copilot_ctx.last_run_outcome_block_labels = list(getattr(copilot_ctx, "last_run_blocks_block_labels", []) or [])+ return outcome+++def _adjudicated_run_outcome(+ copilot_ctx: Any, completion_verification: CompletionVerificationResult | None+) -> RecordedRunOutcome:+ if completion_verification is not None and completion_verification.status == "evaluated":+ if not completion_verification.is_fully_satisfied():+ return RecordedRunOutcome(+ verdict="not_demonstrated",+ reason_code="outcome_not_demonstrated",+ display_reason=run_outcome_display_reason(+ _outcome_unverified_reason(copilot_ctx, completion_verification)+ ),+ )+ if copilot_ctx.last_full_workflow_test_ok:+ return RecordedRunOutcome(verdict="demonstrated")+ return RecordedRunOutcome(verdict="not_evaluated")+ if copilot_ctx.last_test_suspicious_success:+ return RecordedRunOutcome(+ verdict="not_demonstrated",+ reason_code="outcome_not_demonstrated",+ display_reason=run_outcome_display_reason(copilot_ctx.last_test_failure_reason),+ )+ return RecordedRunOutcome(verdict="not_evaluated")+++async def _send_run_outcome_update(+ copilot_ctx: Any,+ result: dict[str, Any],+ *,+ verdict: RunOutcomeVerdict,+ reason_code: RunOutcomeReasonCode | None,+ display_reason: str | None,+) -> None:+ stream = getattr(copilot_ctx, "stream", None)+ if stream is None:+ return+ data = result.get("data")+ run_id = data.get("workflow_run_id") if isinstance(data, dict) else None+ narrator_state = getattr(copilot_ctx, "narrator_state", None)+ iteration = narrator_state.current_iteration if narrator_state is not None else 0+ try:+ await stream.send(+ WorkflowCopilotRunOutcomeUpdate(+ type=WorkflowCopilotStreamMessageType.RUN_OUTCOME,+ workflow_run_id=run_id if isinstance(run_id, str) else "",+ workflow_run_block_ids=list(getattr(copilot_ctx, "last_run_blocks_block_ids", []) or []),+ block_labels=list(getattr(copilot_ctx, "last_run_blocks_block_labels", []) or []),+ verdict=verdict,+ reason_code=reason_code,+ display_reason=display_reason,+ iteration=iteration,+ timestamp=datetime.now(timezone.utc),+ )+ )+ except Exception:+ LOG.debug("copilot run_outcome send failed", exc_info=True)+++async def _verify_and_record_run_blocks_result(+ copilot_ctx: Any, result: dict[str, Any], handler_start: float+) -> CompletionVerificationResult | None:+ """Single producer of run_outcome frames: verify, record, then emit the recorded verdict.+ An ok run gets an "evaluating" hold the moment it enters adjudication and is+ guaranteed a final frame, so completed-row status alone never implies success."""+ run_ok = bool(result.get("ok", False))+ if not run_ok:+ completion_verification = await _maybe_run_completion_verification(copilot_ctx, result, handler_start)+ _record_run_blocks_result(copilot_ctx, result, completion_verification=completion_verification)+ return completion_verification++ await _send_run_outcome_update(copilot_ctx, result, verdict="evaluating", reason_code=None, display_reason=None)+ completion_verification = None+ recorded: RecordedRunOutcome | None = None+ try:+ completion_verification = await _maybe_run_completion_verification(copilot_ctx, result, handler_start)+ recorded = _record_run_blocks_result(copilot_ctx, result, completion_verification=completion_verification)+ finally:+ final = recorded if recorded is not None else RecordedRunOutcome(verdict="not_evaluated")+ await _send_run_outcome_update(+ copilot_ctx,+ result,+ verdict=final.verdict,+ reason_code=final.reason_code,+ display_reason=final.display_reason,+ )+ return completion_verificationdef _record_diagnosis_repair_contract(diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.pyindex d69dbadb2..1da867c38 100644--- a/skyvern/forge/sdk/schemas/workflow_copilot.py+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py@@ -5,6 +5,7 @@ from typing import Any, Literalfrom pydantic import BaseModel, ConfigDict, Fieldfrom skyvern.forge.sdk.copilot.context import ProposalDisposition, ResponseType, TurnNarrativePayload+from skyvern.forge.sdk.copilot.run_outcome import RunOutcomeReasonCode, RunOutcomeVerdictfrom skyvern.forge.sdk.schemas.copilot_turn_outcome import TurnOutcome@@ -138,6 +139,7 @@ class WorkflowCopilotStreamMessageType(StrEnum):CONDENSING = "condensing"NARRATION = "narration"BLOCK_PROGRESS = "block_progress"+ RUN_OUTCOME = "run_outcome"TURN_START = "turn_start"DESIGN_START = "design_start"DESIGN_END = "design_end"@@ -272,6 +274,28 @@ class WorkflowCopilotBlockProgressUpdate(BaseModel):timestamp: datetime = Field(..., description="Server timestamp")+class WorkflowCopilotRunOutcomeUpdate(BaseModel):+ # Emitted once as an "evaluating" hold when an ok run enters adjudication and+ # once with the final recorded verdict; rows render success from this, not raw status.+ type: WorkflowCopilotStreamMessageType = Field(+ WorkflowCopilotStreamMessageType.RUN_OUTCOME, description="Message type"+ )+ workflow_run_id: str = Field(..., description="Workflow run the verdict applies to")+ workflow_run_block_ids: list[str] = Field(+ default_factory=list, description="Run-block ids of the adjudicated run; match the FE per-row keys"+ )+ block_labels: list[str] = Field(+ default_factory=list, description="Block labels of the adjudicated run; key the persisted narrative payload"+ )+ verdict: RunOutcomeVerdict = Field(..., description="Recorded outcome verdict for the run")+ reason_code: RunOutcomeReasonCode | None = Field(+ None, description="Machine-readable cause for a not_demonstrated verdict"+ )+ display_reason: str | None = Field(None, description="Short product-safe reason for user-facing rendering")+ iteration: int = Field(..., description="Agent loop iteration number")+ timestamp: datetime = Field(..., description="Server timestamp")++class WorkflowCopilotTurnStartUpdate(BaseModel):type: WorkflowCopilotStreamMessageType = Field(WorkflowCopilotStreamMessageType.TURN_START, description="Message type"diff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.pyindex 967a87bc7..04601f835 100644--- a/tests/unit/test_copilot_hooks.py+++ b/tests/unit/test_copilot_hooks.py@@ -360,6 +360,7 @@ class TestMCPFailedStepLoopDetection:get_browser_state=AsyncMock(return_value=browser_state),)monkeypatch.setattr(runtime.app, "PERSISTENT_SESSIONS_MANAGER", persistent_session_manager)+ monkeypatch.setattr(runtime.settings, "ENV", "local")runtime_skyvern = MagicMock()monkeypatch.setattr(runtime, "get_skyvern", lambda: runtime_skyvern)@@ -389,11 +390,13 @@ class TestMCPFailedStepLoopDetection:monkeypatch.setattr(session_manager, "get_skyvern", lambda: fallback_skyvern)observed_session_ids: list[str | None] = []+ observed_localhost_access: list[bool | None] = []async def fake_do_screenshot(page: Any, full_page: bool = False, selector: str | None = None) -> Any:del page, full_page, selectorcurrent = session_manager.get_current_session()observed_session_ids.append(current.context.session_id if current.context else None)+ observed_localhost_access.append(current.context.can_access_localhost if current.context else None)assert current.api_key_hash == session_manager._api_key_hash("sk-copilot-org")return SimpleNamespace(data=b"fake-png")@@ -435,6 +438,7 @@ class TestMCPFailedStepLoopDetection:assert parsed["ok"] is Trueassert parsed["data"]["screenshot_base64"]assert observed_session_ids == ["pbs_copilot"]+ assert observed_localhost_access == [True]fallback_skyvern.connect_to_cloud_browser_session.assert_not_awaited()persistent_session_manager.get_browser_state.assert_any_await(session_id="pbs_copilot",diff --git a/tests/unit/test_copilot_run_outcome_event.py b/tests/unit/test_copilot_run_outcome_event.pynew file mode 100644index 000000000..3d07e6c73--- /dev/null+++ b/tests/unit/test_copilot_run_outcome_event.py@@ -0,0 +1,348 @@+"""Per-run outcome verdict carried into the narrative stream and payload.++Fixtures model a public registry site with a search form and expandable+result rows; domains and person names are generic placeholders.+"""++from __future__ import annotations++import inspect+import time+from types import SimpleNamespace+from typing import Any++import pytest++from skyvern.forge.sdk.copilot import tools as copilot_tools+from skyvern.forge.sdk.copilot.agent import _build_narrative_payload+from skyvern.forge.sdk.copilot.completion_verification import CompletionVerificationResult, CriterionVerdict+from skyvern.forge.sdk.copilot.context import CopilotContext+from skyvern.forge.sdk.copilot.request_policy import CompletionCriterion, RequestPolicy+from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome, run_outcome_display_reason+from skyvern.forge.sdk.copilot.tools import run_execution+from skyvern.forge.sdk.copilot.tools.run_execution import (+ _record_run_blocks_result,+ _verify_and_record_run_blocks_result,+)+from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotRunOutcomeUpdate+++class _FakeStream:+ def __init__(self) -> None:+ self.sent: list[Any] = []++ async def send(self, data: Any) -> bool:+ self.sent.append(data)+ return True+++def _code_block(label: str, extracted: Any) -> dict[str, Any]:+ return {"label": label, "block_type": "CODE", "status": "completed", "extracted_data": extracted}+++def _run_result(blocks: list[dict[str, Any]], *, ok: bool = True) -> dict[str, Any]:+ return {+ "ok": ok,+ "data": {+ "workflow_run_id": "wr_test",+ "overall_status": "completed" if ok else "failed",+ "current_url": "https://registry.example.com/search",+ "blocks": blocks,+ },+ }+++def _ctx(blocks: list[dict[str, Any]] | None = None) -> CopilotContext:+ ctx = CopilotContext(+ organization_id="o",+ workflow_id="w",+ workflow_permanent_id="wp",+ workflow_yaml="blocks: []",+ browser_session_id=None,+ stream=_FakeStream(), # type: ignore[arg-type]+ user_message="search the public registry for a person and expand their result rows",+ )+ ctx.request_policy = RequestPolicy(+ completion_criteria=[CompletionCriterion(id="c0", outcome="result rows extracted")]+ )+ labels = [block["label"] for block in (blocks or [])]+ workflow_blocks = [SimpleNamespace(block_type="code", label=label) for label in labels]+ ctx.last_workflow = SimpleNamespace(workflow_definition=SimpleNamespace(blocks=workflow_blocks)) # type: ignore[assignment]+ ctx.last_workflow_yaml = "blocks: []"+ ctx.verified_prefix_labels = labels+ ctx.last_run_blocks_block_ids = [f"wrb_{label}" for label in labels]+ ctx.last_run_blocks_block_labels = labels+ return ctx+++def _blocked_run_result() -> dict[str, Any]:+ return _run_result(+ [+ _code_block("open_registry_search", {"submit_button_enabled": False}),+ _code_block(+ "search_registry_person",+ {+ "anti_bot_blocked": True,+ "blocker": "The search form is gated by a human verification challenge; the search never ran.",+ "has_results": False,+ "records": [],+ },+ ),+ ]+ )+++def _clean_run_result() -> dict[str, Any]:+ return _run_result(+ [+ _code_block(+ "search_registry_person",+ {"result_row_count": 1, "visible_results_evidence": "DOE, JANE - Status: Active"},+ ),+ ]+ )+++def _evaluated(satisfied: bool) -> CompletionVerificationResult:+ verdict = CriterionVerdict(+ criterion_id="c0", satisfied=satisfied, reason_code="evidence_confirms" if satisfied else "no_evidence"+ )+ return CompletionVerificationResult(status="evaluated", criterion_ids=["c0"], verdicts=[verdict])+++def _run_outcome_frames(stream: _FakeStream) -> list[WorkflowCopilotRunOutcomeUpdate]:+ return [frame for frame in stream.sent if isinstance(frame, WorkflowCopilotRunOutcomeUpdate)]+++async def test_blocker_run_emits_hold_then_not_demonstrated() -> None:+ result = _blocked_run_result()+ ctx = _ctx(result["data"]["blocks"])++ await _verify_and_record_run_blocks_result(ctx, result, time.monotonic())++ frames = _run_outcome_frames(ctx.stream) # type: ignore[arg-type]+ assert [frame.verdict for frame in frames] == ["evaluating", "not_demonstrated"]+ final = frames[-1]+ assert final.reason_code == "blocker_reported"+ assert final.workflow_run_id == "wr_test"+ assert final.workflow_run_block_ids == ["wrb_open_registry_search", "wrb_search_registry_person"]+ assert final.block_labels == ["open_registry_search", "search_registry_person"]+ assert final.display_reason is not None and "human verification challenge" in final.display_reason+ assert ctx.last_test_suspicious_success is True+ assert ctx.last_run_outcome == RecordedRunOutcome(+ verdict=final.verdict, reason_code=final.reason_code, display_reason=final.display_reason+ )+ assert ctx.last_run_outcome_block_labels == final.block_labels+++async def test_empty_data_run_emits_no_meaningful_output() -> None:+ result = _run_result([_code_block("search_registry_person", {"records": [], "result_count": 0})])+ ctx = _ctx(result["data"]["blocks"])++ await _verify_and_record_run_blocks_result(ctx, result, time.monotonic())++ frames = _run_outcome_frames(ctx.stream) # type: ignore[arg-type]+ assert [frame.verdict for frame in frames] == ["evaluating", "not_demonstrated"]+ assert frames[-1].reason_code == "no_meaningful_output"+ assert ctx.last_test_suspicious_success is True+++def _terminal_metadata_entry(label: str) -> dict[str, Any]:+ return {+ "block_label": label,+ "declared_goal": "extract result rows for the requested person",+ "claimed_outcomes": [+ {+ "id": "claim:goal",+ "scope": "outcome",+ "text": "result rows extracted",+ "status": "observed_not_verified",+ "covered_criteria": ["criterion:goal_0"],+ }+ ],+ "completion_criteria": [+ {"id": "criterion:goal_0", "text": "result rows extracted", "level": "terminal", "terminal": True}+ ],+ }+++async def test_negative_adjudication_emits_outcome_not_demonstrated(monkeypatch: pytest.MonkeyPatch) -> None:+ result = _clean_run_result()+ ctx = _ctx(result["data"]["blocks"])+ ctx.code_artifact_metadata = {"search_registry_person": _terminal_metadata_entry("search_registry_person")}++ async def _stub_verification(*args: Any, **kwargs: Any) -> CompletionVerificationResult:+ return _evaluated(satisfied=False)++ monkeypatch.setattr(run_execution, "_maybe_run_completion_verification", _stub_verification)+ await _verify_and_record_run_blocks_result(ctx, result, time.monotonic())++ frames = _run_outcome_frames(ctx.stream) # type: ignore[arg-type]+ assert [frame.verdict for frame in frames] == ["evaluating", "not_demonstrated"]+ final = frames[-1]+ assert final.reason_code == "outcome_not_demonstrated"+ assert final.display_reason is not None and "did not demonstrate the goal outcome" in final.display_reason+ assert ctx.last_test_suspicious_success is True+ assert ctx.last_full_workflow_test_ok is False+ assert ctx.last_run_outcome is not None and ctx.last_run_outcome.verdict == "not_demonstrated"+++async def test_mid_build_fall_through_still_emits_not_demonstrated(monkeypatch: pytest.MonkeyPatch) -> None:+ result = _clean_run_result()+ ctx = _ctx(result["data"]["blocks"])++ async def _stub_verification(*args: Any, **kwargs: Any) -> CompletionVerificationResult:+ return _evaluated(satisfied=False)++ monkeypatch.setattr(run_execution, "_maybe_run_completion_verification", _stub_verification)+ await _verify_and_record_run_blocks_result(ctx, result, time.monotonic())++ frames = _run_outcome_frames(ctx.stream) # type: ignore[arg-type]+ assert [frame.verdict for frame in frames] == ["evaluating", "not_demonstrated"]+ assert frames[-1].reason_code == "outcome_not_demonstrated"+ assert ctx.last_test_suspicious_success is False+ assert ctx.last_full_workflow_test_ok is True+++async def test_satisfied_adjudication_emits_demonstrated(monkeypatch: pytest.MonkeyPatch) -> None:+ result = _clean_run_result()+ ctx = _ctx(result["data"]["blocks"])++ async def _stub_verification(*args: Any, **kwargs: Any) -> CompletionVerificationResult:+ return _evaluated(satisfied=True)++ monkeypatch.setattr(run_execution, "_maybe_run_completion_verification", _stub_verification)+ await _verify_and_record_run_blocks_result(ctx, result, time.monotonic())++ frames = _run_outcome_frames(ctx.stream) # type: ignore[arg-type]+ assert [frame.verdict for frame in frames] == ["evaluating", "demonstrated"]+ assert frames[-1].reason_code is None+ assert ctx.last_full_workflow_test_ok is True+++async def test_verification_skipped_emits_not_evaluated(monkeypatch: pytest.MonkeyPatch) -> None:+ result = _clean_run_result()+ ctx = _ctx(result["data"]["blocks"])++ async def _stub_verification(*args: Any, **kwargs: Any) -> None:+ return None++ monkeypatch.setattr(run_execution, "_maybe_run_completion_verification", _stub_verification)+ await _verify_and_record_run_blocks_result(ctx, result, time.monotonic())++ frames = _run_outcome_frames(ctx.stream) # type: ignore[arg-type]+ assert [frame.verdict for frame in frames] == ["evaluating", "not_evaluated"]+ assert ctx.last_test_suspicious_success is False+++async def test_failed_run_emits_no_frames() -> None:+ result = _run_result([], ok=False)+ ctx = _ctx()++ await _verify_and_record_run_blocks_result(ctx, result, time.monotonic())++ assert _run_outcome_frames(ctx.stream) == [] # type: ignore[arg-type]+ assert ctx.last_run_outcome is None+++async def test_evaluating_hold_gets_final_frame_when_recording_raises(monkeypatch: pytest.MonkeyPatch) -> None:+ result = _clean_run_result()+ ctx = _ctx(result["data"]["blocks"])++ def _boom(*args: Any, **kwargs: Any) -> None:+ raise RuntimeError("recording failed")++ monkeypatch.setattr(run_execution, "_record_run_blocks_result", _boom)+ with pytest.raises(RuntimeError, match="recording failed"):+ await _verify_and_record_run_blocks_result(ctx, result, time.monotonic())++ frames = _run_outcome_frames(ctx.stream) # type: ignore[arg-type]+ assert [frame.verdict for frame in frames] == ["evaluating", "not_evaluated"]+++def test_recorder_returns_none_for_failed_run() -> None:+ result = _run_result([], ok=False)+ ctx = _ctx()+ assert _record_run_blocks_result(ctx, result, completion_verification=None) is None+ assert ctx.last_run_outcome is None+++def test_failed_rerun_clears_prior_recorded_outcome() -> None:+ ctx = _ctx()+ ctx.last_run_outcome = RecordedRunOutcome(verdict="not_demonstrated", reason_code="blocker_reported")+ ctx.last_run_outcome_block_labels = ["search_registry_person"]++ _record_run_blocks_result(ctx, _run_result([], ok=False), completion_verification=None)++ assert ctx.last_run_outcome is None+ assert ctx.last_run_outcome_block_labels == []+++def test_both_consumers_route_through_single_producer() -> None:+ source = inspect.getsource(copilot_tools)+ assert source.count("await _verify_and_record_run_blocks_result(") == 2+ assert "_record_run_blocks_result(copilot_ctx, result, completion_verification" not in source+ assert "_record_run_blocks_result(copilot_ctx, run_result, completion_verification" not in source+ assert "await _maybe_run_completion_verification(copilot_ctx" not in source+++def test_display_reason_collapses_whitespace_and_caps_length() -> None:+ assert run_outcome_display_reason(" a\n b ") == "a b"+ long_text = "x" * 500+ capped = run_outcome_display_reason(long_text)+ assert capped is not None and len(capped) == 160+ assert run_outcome_display_reason(" ") is None+ assert run_outcome_display_reason(None) is None+++def _payload_ctx() -> CopilotContext:+ ctx = _ctx()+ workflow_blocks = [+ SimpleNamespace(block_type=None, label="open_registry_search"),+ SimpleNamespace(block_type=None, label="search_registry_person"),+ SimpleNamespace(block_type=None, label="untested_block"),+ ]+ ctx.staged_workflow = SimpleNamespace(workflow_definition=SimpleNamespace(blocks=workflow_blocks)) # type: ignore[assignment]+ ctx.block_state_map = {+ "open_registry_search": "completed",+ "search_registry_person": "completed",+ }+ return ctx+++def test_narrative_payload_stamps_outcome_on_adjudicated_labels() -> None:+ ctx = _payload_ctx()+ ctx.last_run_outcome = RecordedRunOutcome(+ verdict="not_demonstrated",+ reason_code="blocker_reported",+ display_reason="The search form is gated by a human verification challenge.",+ )+ ctx.last_run_outcome_block_labels = ["open_registry_search", "search_registry_person"]++ payload = _build_narrative_payload(ctx, terminal="response", terminal_message="done", narrative_summary=None)++ by_label = {block["label"]: block for block in payload["blocks"]}+ for label in ("open_registry_search", "search_registry_person"):+ assert by_label[label]["state"] == "completed"+ assert by_label[label]["outcome"] == "not_demonstrated"+ assert by_label[label]["outcomeReason"] == "The search form is gated by a human verification challenge."+ assert "outcome" not in by_label["untested_block"]+ assert "outcomeReason" not in by_label["untested_block"]+++def test_narrative_payload_without_recorded_outcome_has_no_outcome_keys() -> None:+ ctx = _payload_ctx()++ payload = _build_narrative_payload(ctx, terminal="response", terminal_message="done", narrative_summary=None)++ for block in payload["blocks"]:+ assert "outcome" not in block+ assert "outcomeReason" not in blockdiff --git a/tests/unit/test_mcp_localhost_guard.py b/tests/unit/test_mcp_localhost_guard.pyindex a81368f68..73f2e2621 100644--- a/tests/unit/test_mcp_localhost_guard.py+++ b/tests/unit/test_mcp_localhost_guard.py@@ -61,7 +61,7 @@ def test_is_localhost_url_handles_garbage_input() -> None:@pytest.mark.asyncioasync def test_navigate_rejects_localhost_on_cloud_session(monkeypatch: pytest.MonkeyPatch) -> None:page = object()- ctx = BrowserContext(mode="cloud_session", session_id="pbs_test")+ ctx = BrowserContext(mode="cloud_session", session_id="pbs_test", can_access_localhost=False)monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))result = await mcp_browser.skyvern_navigate(url="http://localhost:3000")@@ -75,7 +75,7 @@ async def test_navigate_rejects_localhost_on_cloud_session(monkeypatch: pytest.M@pytest.mark.asyncioasync def test_navigate_rejects_127_0_0_1_on_cloud_session(monkeypatch: pytest.MonkeyPatch) -> None:page = object()- ctx = BrowserContext(mode="cloud_session", session_id="pbs_test")+ ctx = BrowserContext(mode="cloud_session", session_id="pbs_test", can_access_localhost=False)monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))result = await mcp_browser.skyvern_navigate(url="http://127.0.0.1:5173/dashboard")@@ -117,6 +117,39 @@ async def test_navigate_allows_localhost_on_cdp_session(monkeypatch: pytest.Monkassert result["ok"] is True+async def test_navigate_attempts_localhost_when_cloud_session_can_access_localhost(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ page = AsyncMock()+ ctx = BrowserContext(mode="cloud_session", session_id="pbs_test", can_access_localhost=True)+ do_navigate = AsyncMock(return_value=AsyncMock(url="http://localhost:3000", title="App"))+ monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))+ monkeypatch.setattr(mcp_browser, "do_navigate", do_navigate)++ result = await mcp_browser.skyvern_navigate(url="http://localhost:3000")++ assert result["ok"] is True+ do_navigate.assert_awaited_once()+++async def test_navigate_unknown_localhost_reachability_reports_real_navigation_error(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ page = AsyncMock()+ ctx = BrowserContext(mode="cloud_session", session_id="pbs_test")+ monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))+ monkeypatch.setattr(mcp_browser, "do_navigate", AsyncMock(side_effect=RuntimeError("connection refused")))++ result = await mcp_browser.skyvern_navigate(url="http://localhost:3000")++ assert result["ok"] is False+ assert result["error"]["code"] == mcp_browser.ErrorCode.ACTION_FAILED+ assert result["error"]["message"] == "connection refused"+ assert result["error"]["message"] != "Cloud browsers cannot reach localhost URLs"++@pytest.mark.asyncioasync def test_navigate_allows_public_url_on_cloud_session(monkeypatch: pytest.MonkeyPatch) -> None:page = AsyncMock()@@ -141,7 +174,7 @@ async def test_navigate_allows_public_url_on_cloud_session(monkeypatch: pytest.M@pytest.mark.asyncioasync def test_run_task_rejects_localhost_on_cloud_session(monkeypatch: pytest.MonkeyPatch) -> None:page = object()- ctx = BrowserContext(mode="cloud_session", session_id="pbs_test")+ ctx = BrowserContext(mode="cloud_session", session_id="pbs_test", can_access_localhost=False)monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))result = await mcp_browser.skyvern_run_task(@@ -155,6 +188,31 @@ async def test_run_task_rejects_localhost_on_cloud_session(monkeypatch: pytest.Massert "skyvern browser serve --tunnel" in result["error"]["hint"]+async def test_run_task_attempts_localhost_when_cloud_session_can_access_localhost(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ page = AsyncMock()+ page.agent = AsyncMock()+ page.agent.run_task = AsyncMock(+ return_value=AsyncMock(+ run_id="r_1",+ status="completed",+ output=None,+ failure_reason=None,+ recording_url=None,+ app_url=None,+ )+ )+ ctx = BrowserContext(mode="cloud_session", session_id="pbs_test", can_access_localhost=True)+ monkeypatch.setattr(mcp_browser, "get_page", AsyncMock(return_value=(page, ctx)))++ result = await mcp_browser.skyvern_run_task(prompt="Extract the page title", url="http://localhost:5173")++ assert result["ok"] is True+ page.agent.run_task.assert_awaited_once()++@pytest.mark.asyncioasync def test_run_task_allows_no_url(monkeypatch: pytest.MonkeyPatch) -> None:"""run_task with url=None should not trigger the localhost guard."""diff --git a/tests/unit/test_mcp_session_lifecycle.py b/tests/unit/test_mcp_session_lifecycle.pyindex a48fb08c2..4eaf19a44 100644--- a/tests/unit/test_mcp_session_lifecycle.py+++ b/tests/unit/test_mcp_session_lifecycle.py@@ -343,6 +343,36 @@ async def test_resolve_browser_does_not_reuse_session_for_different_api_key(fake_skyvern.connect_to_cloud_browser_session.assert_awaited_once_with("pbs_123")+ ("env", "expected_can_access_localhost"),+ [+ ("local", True),+ ("prod", False),+ ],+)+async def test_resolve_browser_classifies_explicit_cloud_session_localhost_reachability(+ monkeypatch: pytest.MonkeyPatch,+ env: str,+ expected_can_access_localhost: bool,+) -> None:+ monkeypatch.setattr(session_manager.settings, "ENV", env)+ replacement_browser = MagicMock()+ fake_skyvern = MagicMock()+ fake_skyvern.connect_to_cloud_browser_session = AsyncMock(return_value=replacement_browser)+ monkeypatch.setattr(session_manager, "get_skyvern", lambda: fake_skyvern)++ browser, ctx = await session_manager.resolve_browser(session_id="pbs_123")++ assert browser is replacement_browser+ assert ctx == BrowserContext(+ mode="cloud_session",+ session_id="pbs_123",+ can_access_localhost=expected_can_access_localhost,+ )+ fake_skyvern.connect_to_cloud_browser_session.assert_awaited_once_with("pbs_123")++@pytest.mark.asyncioasync def test_resolve_browser_does_not_reuse_registered_copilot_session_for_different_api_key_override(monkeypatch: pytest.MonkeyPatch,@@ -762,6 +792,10 @@ async def test_session_create_persists_active_api_key_hash_in_session_state(assert result["ok"] is Truecurrent = mcp_session.get_current_session()assert current.browser is fake_browser- assert current.context == BrowserContext(mode="cloud_session", session_id="pbs_123")+ assert current.context == BrowserContext(+ mode="cloud_session",+ session_id="pbs_123",+ can_access_localhost=False,+ )assert current.api_key_hash == session_manager._api_key_hash("sk_key_create")assert current.api_key_hash != "sk_key_create"