Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(SKY-12612): batch run-heal-summary endpoint for run-list outcome-risk (#7523)
pedrohsdb7a42e923958f
diff --git a/skyvern/cli/mcp_tools/code_block.py b/skyvern/cli/mcp_tools/code_block.pyindex 9655bfa9e..c7da71556 100644--- a/skyvern/cli/mcp_tools/code_block.py+++ b/skyvern/cli/mcp_tools/code_block.py@@ -20,6 +20,7 @@ from skyvern.forge.sdk.copilot.code_block_security import (from skyvern.forge.sdk.copilot.code_block_synthesis import synthesize_code_blockfrom ._common import ErrorCode, make_error, make_result+from .trajectory import skyvern_trajectory_getdef _serialize_diagnostic(diagnostic: CodeBlockPreflightDiagnostic) -> dict[str, str]:@@ -96,27 +97,70 @@ async def skyvern_code_block_lint(async def skyvern_code_block_synthesize(trajectory_json: Annotated[- str,+ str | None,Field(description=("JSON array of captured interaction objects (the scout trajectory). Each object has ""tool_name plus selector/source_url/role/accessible_name/typed_value/value/key as "- "applicable. This tool does NOT scout a live page - the trajectory is supplied by the caller."+ "applicable. Provide this or session_id, not both.")),- ],+ ] = None,strict_selectors: Annotated[bool,Field(description="Emit only the scout's captured selectors verbatim; drop ambiguous bare selectors"),] = False,+ session_id: Annotated[+ str | None,+ Field(description="Browser session ID (pbs_...) whose captured trajectory to synthesize directly"),+ ] = None,) -> dict[str, Any]:"""Deterministically synthesize a Playwright `code` block from a captured trajectory.- Wraps the copilot's pure synthesize_code_block(): output is byte-identical per trajectory,- with no LLM and no I/O. The trajectory is supplied by the caller - capturing a live trajectory- (the scout) is out of scope for this tool.+ Pass session_id for one-step capture-to-code. Use skyvern_trajectory_get first and pass trajectory_json+ when you need to inspect or trim the capture. Session results include capture_truncated; synthesis remains+ deterministic with no LLM."""action = "skyvern_code_block_synthesize"+ if (trajectory_json is not None) == (session_id is not None):+ return make_result(+ action,+ ok=False,+ error=make_error(+ ErrorCode.INVALID_INPUT,+ "Exactly one trajectory source is required",+ "Provide exactly one of trajectory_json or session_id",+ ),+ )++ capture_truncated: bool | None = None+ if session_id is not None:+ capture = await skyvern_trajectory_get(session_id)+ if capture["data"]["capture_status"] == "not_found":+ return make_result(+ action,+ ok=False,+ error=make_error(+ ErrorCode.INVALID_INPUT,+ "No captured trajectory is available for this session",+ "Capture browser interactions first or provide trajectory_json",+ ),+ )+ if capture["data"]["entry_count"] == 0:+ return make_result(+ action,+ ok=False,+ error=make_error(+ ErrorCode.INVALID_INPUT,+ "Captured trajectory is empty (entries were dropped by storage limits)",+ "Re-capture the interactions or provide trajectory_json",+ details={"capture_truncated": capture["data"]["truncated"]},+ ),+ )+ trajectory_json = capture["data"]["trajectory_json"]+ capture_truncated = capture["data"]["truncated"]++ assert trajectory_json is not Nonetry:trajectory = json.loads(trajectory_json)@@ -166,17 +210,17 @@ async def skyvern_code_block_synthesize(),)- return make_result(- action,- data={- "code": synthesized.code,- "parameters": synthesized.parameters,- "steps": synthesized.steps,- "notes": synthesized.notes,- "emitted_interaction_count": synthesized.diagnostics.emitted_interaction_count,- "truncated": synthesized.diagnostics.truncated,- },- )+ data = {+ "code": synthesized.code,+ "parameters": synthesized.parameters,+ "steps": synthesized.steps,+ "notes": synthesized.notes,+ "emitted_interaction_count": synthesized.diagnostics.emitted_interaction_count,+ "truncated": synthesized.diagnostics.truncated,+ }+ if capture_truncated is not None:+ data["capture_truncated"] = capture_truncated+ return make_result(action, data=data)__all__ = ["skyvern_code_block_lint", "skyvern_code_block_synthesize"]diff --git a/skyvern/forge/sdk/routes/self_heal.py b/skyvern/forge/sdk/routes/self_heal.pyindex 3a8ca37c0..a7b4b2749 100644--- a/skyvern/forge/sdk/routes/self_heal.py+++ b/skyvern/forge/sdk/routes/self_heal.py@@ -12,6 +12,7 @@ from skyvern.schemas.self_heal import (RunHealSummary,WorkflowReliability,summarize_run_heals,+ summarize_runs_heals,)from skyvern.services.self_heal_reliability_service import get_workflow_reliability, get_workflows_reliability@@ -23,6 +24,14 @@ class RunHealEpisodesResponse(BaseModel):summary: RunHealSummary+class RunsHealSummaryRequest(BaseModel):+ workflow_run_ids: list[str] = Field(default_factory=list, max_length=100)+++class RunsHealSummaryResponse(BaseModel):+ summaries: dict[str, RunHealSummary]++class WorkflowsReliabilityRequest(BaseModel):workflow_permanent_ids: list[str] = Field(default_factory=list, max_length=100)@@ -74,6 +83,23 @@ async def get_run_heal_episodes()+@base_router.post(+ "/runs/heal_summary/batch",+ response_model=RunsHealSummaryResponse,+ include_in_schema=False,+)+async def get_runs_heal_summary_route(+ request: RunsHealSummaryRequest,+ organization: Organization = Depends(org_auth_service.get_current_org),+) -> RunsHealSummaryResponse:+ workflow_run_ids = list(dict.fromkeys(request.workflow_run_ids))+ episodes = await app.DATABASE.self_heal.get_heal_episodes_for_runs(+ organization_id=organization.organization_id,+ workflow_run_ids=workflow_run_ids,+ )+ return RunsHealSummaryResponse(summaries=summarize_runs_heals(episodes))++@base_router.get("/workflows/{workflow_permanent_id}/reliability",response_model=WorkflowReliability,diff --git a/skyvern/schemas/self_heal.py b/skyvern/schemas/self_heal.pyindex 77bc95039..93a41bc57 100644--- a/skyvern/schemas/self_heal.py+++ b/skyvern/schemas/self_heal.py@@ -211,6 +211,15 @@ def summarize_run_heals(episodes: list[HealEpisode]) -> RunHealSummary:)+def summarize_runs_heals(episodes: list[HealEpisode]) -> dict[str, RunHealSummary]:+ episodes_by_run: dict[str, list[HealEpisode]] = {}+ for episode in episodes:+ episodes_by_run.setdefault(episode.workflow_run_id, []).append(episode)+ return {+ workflow_run_id: summarize_run_heals(run_episodes) for workflow_run_id, run_episodes in episodes_by_run.items()+ }++def compute_workflow_reliability(runs: list[RunHealGroup]) -> WorkflowReliability:run_flags: list[tuple[bool, bool, bool]] = []for run in runs:diff --git a/tests/unit/forge/sdk/routes/test_self_heal_routes.py b/tests/unit/forge/sdk/routes/test_self_heal_routes.pyindex a4b07f2a3..249f00ae9 100644--- a/tests/unit/forge/sdk/routes/test_self_heal_routes.py+++ b/tests/unit/forge/sdk/routes/test_self_heal_routes.py@@ -245,3 +245,71 @@ def test_get_workflows_reliability_batch_rejects_over_cap(monkeypatch) -> None:assert response.status_code == 422get_reliability_batch.assert_not_awaited()+++def test_get_runs_heal_summary_batch_groups_dedupes_and_summarizes(monkeypatch) -> None:+ client, _, _, _, _ = _build_client(monkeypatch)++ episodes = [+ _episode(+ heal_episode_id="he_1",+ workflow_run_block_id="wrb_1",+ block_label="block_a",+ status=HealStatus.fired_completed,+ workflow_run_id="wr_1",+ ),+ _episode(+ heal_episode_id="he_2",+ workflow_run_block_id="wrb_2",+ block_label="block_b",+ status=HealStatus.fired_unverified,+ workflow_run_id="wr_2",+ output_obligation=OutputObligation.observed,+ ),+ ]++ seen: dict = {}++ async def _for_runs(*, organization_id: str, workflow_run_ids: list[str]) -> list[HealEpisode]:+ seen["organization_id"] = organization_id+ seen["workflow_run_ids"] = workflow_run_ids+ return episodes++ monkeypatch.setattr(forge_app.DATABASE.self_heal, "get_heal_episodes_for_runs", _for_runs)++ response = client.post(+ "/v1/runs/heal_summary/batch",+ json={"workflow_run_ids": ["wr_1", "wr_2", "wr_1"]},+ )++ assert response.status_code == 200+ body = response.json()+ assert set(body.keys()) == {"summaries"}+ assert set(body["summaries"].keys()) == {"wr_1", "wr_2"}+ assert body["summaries"]["wr_1"]["blocks_healed"] == 1+ assert body["summaries"]["wr_1"]["blocks_outcome_risk"] == []+ assert body["summaries"]["wr_2"]["blocks_healed"] == 0+ assert body["summaries"]["wr_2"]["blocks_outcome_risk"] == ["block_b"]+ assert seen["organization_id"] == ORG_ID+ assert seen["workflow_run_ids"] == ["wr_1", "wr_2"]+++def test_get_runs_heal_summary_batch_rejects_over_cap(monkeypatch) -> None:+ client, _, _, _, _ = _build_client(monkeypatch)++ called = False++ async def _for_runs(*, organization_id: str, workflow_run_ids: list[str]) -> list[HealEpisode]:+ nonlocal called+ called = True+ return []++ monkeypatch.setattr(forge_app.DATABASE.self_heal, "get_heal_episodes_for_runs", _for_runs)++ response = client.post(+ "/v1/runs/heal_summary/batch",+ json={"workflow_run_ids": [f"wr_{i}" for i in range(101)]},+ )++ assert response.status_code == 422+ assert called is Falsediff --git a/tests/unit/test_code_block_synthesize_mcp_tool.py b/tests/unit/test_code_block_synthesize_mcp_tool.pyindex 586230f6f..06b07c218 100644--- a/tests/unit/test_code_block_synthesize_mcp_tool.py+++ b/tests/unit/test_code_block_synthesize_mcp_tool.py@@ -6,10 +6,35 @@ OSS-synced: only example.* / RFC-2606 placeholder targets.from __future__ import annotationsimport json+from collections.abc import Iterator+from typing import Anyimport pytest+from skyvern.cli.core import trajectory_store+from skyvern.cli.core.trajectory_store import append_trajectory_entry+from skyvern.cli.mcp_tools import mcp+from skyvern.cli.mcp_tools import trajectory as mcp_trajectoryfrom skyvern.cli.mcp_tools.code_block import skyvern_code_block_synthesize+from skyvern.forge.sdk.copilot.code_block_synthesis import synthesize_code_block++_HASH_A = "principal-a"+_HASH_B = "principal-b"+_SYNTHESIS_FIELDS = ("code", "parameters", "steps", "notes", "emitted_interaction_count", "truncated")+_SOURCE_HINT = "Provide exactly one of trajectory_json or session_id"++[email protected](autouse=True)+def _reset_trajectory_store() -> Iterator[None]:+ trajectory_store._trajectories.clear()+ yield+ trajectory_store._trajectories.clear()+++def active_principal(monkeypatch: pytest.MonkeyPatch) -> str:+ monkeypatch.setattr(mcp_trajectory, "active_api_key_hash", lambda: _HASH_A)+ return _HASH_Adef _fixture_trajectory() -> list[dict]:@@ -32,6 +57,220 @@ def _fixture_trajectory() -> list[dict]:]+def _expected_result(*, ok: bool, data: dict[str, Any] | None = None, error: dict[str, Any] | None = None) -> dict:+ return {+ "ok": ok,+ "action": "skyvern_code_block_synthesize",+ "browser_context": {"mode": "none", "session_id": None, "cdp_url": None},+ "data": data,+ "artifacts": [],+ "timing_ms": {},+ "warnings": [],+ "error": error,+ }+++def _expected_synthesis_data(*, strict_selectors: bool) -> dict[str, Any]:+ # Expected data comes from the pure synthesizer (its own tests own the code bytes);+ # this test locks the wrapper envelope around it.+ synthesized = synthesize_code_block(_fixture_trajectory(), strict_selectors=strict_selectors)+ assert synthesized is not None+ return {+ "code": synthesized.code,+ "parameters": synthesized.parameters,+ "steps": synthesized.steps,+ "notes": synthesized.notes,+ "emitted_interaction_count": synthesized.diagnostics.emitted_interaction_count,+ "truncated": synthesized.diagnostics.truncated,+ }++[email protected]("strict_selectors", [False, True])+async def test_existing_trajectory_json_success_envelope_is_unchanged(strict_selectors: bool) -> None:+ result = await skyvern_code_block_synthesize(+ json.dumps(_fixture_trajectory()),+ strict_selectors=strict_selectors,+ )++ assert result == _expected_result(ok=True, data=_expected_synthesis_data(strict_selectors=strict_selectors))+++async def test_legacy_two_positional_call_still_binds_strict_selectors() -> None:+ positional = await skyvern_code_block_synthesize(json.dumps(_fixture_trajectory()), True)++ assert positional == _expected_result(ok=True, data=_expected_synthesis_data(strict_selectors=True))+++ ("trajectory_json", "message", "hint"),+ [+ (+ "{not valid json",+ "Invalid trajectory JSON: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)",+ "Provide a JSON array of interaction objects",+ ),+ (+ json.dumps({"not": "a list"}),+ "Expected a JSON array, got dict",+ "Provide a JSON array of interaction objects",+ ),+ (+ json.dumps([1]),+ "Expected trajectory item at index 0 to be an object, got int",+ "Provide a JSON array of interaction objects",+ ),+ (+ json.dumps(["click"]),+ "Expected trajectory item at index 0 to be an object, got str",+ "Provide a JSON array of interaction objects",+ ),+ (+ json.dumps([]),+ "Trajectory produced no synthesizable steps",+ "Supply a non-empty trajectory with at least one actionable interaction",+ ),+ ],+)+async def test_existing_trajectory_json_error_envelopes_are_unchanged(+ trajectory_json: str,+ message: str,+ hint: str,+) -> None:+ result = await skyvern_code_block_synthesize(trajectory_json)++ assert result == _expected_result(+ ok=False,+ error={"code": "INVALID_INPUT", "message": message, "hint": hint, "details": {}},+ )+++ ("trajectory_json", "session_id"),+ [+ (None, None),+ (json.dumps(_fixture_trajectory()), "pbs_shortcut"),+ ],+ ids=["neither", "both"],+)+async def test_synthesize_requires_exactly_one_trajectory_source(+ trajectory_json: str | None,+ session_id: str | None,+) -> None:+ result = await skyvern_code_block_synthesize(trajectory_json=trajectory_json, session_id=session_id)++ assert result["ok"] is False+ assert result["error"]["code"] == "INVALID_INPUT"+ assert result["error"]["hint"] == _SOURCE_HINT+++async def test_empty_trajectory_json_is_parsed_instead_of_treated_as_missing() -> None:+ result = await skyvern_code_block_synthesize(trajectory_json="")++ assert result["ok"] is False+ assert result["error"]["code"] == "INVALID_INPUT"+ assert result["error"]["message"].startswith("Invalid trajectory JSON:")+ assert result["error"]["hint"] != _SOURCE_HINT+++async def test_session_shortcut_matches_two_step_synthesis_fields(active_principal: str) -> None:+ for entry in _fixture_trajectory():+ append_trajectory_entry(api_key_hash=active_principal, session_id="pbs_shortcut", entry=entry)++ one_step = await skyvern_code_block_synthesize(session_id="pbs_shortcut")+ capture = await mcp_trajectory.skyvern_trajectory_get("pbs_shortcut")+ two_step = await skyvern_code_block_synthesize(trajectory_json=capture["data"]["trajectory_json"])++ assert capture["data"]["truncated"] is False+ assert one_step["ok"] is True+ assert one_step["data"]["capture_truncated"] is False+ assert {field: one_step["data"][field] for field in _SYNTHESIS_FIELDS} == {+ field: two_step["data"][field] for field in _SYNTHESIS_FIELDS+ }+++async def test_session_shortcut_keeps_capture_and_emission_truncation_independent(+ active_principal: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(trajectory_store, "MAX_ENTRIES", 1)+ append_trajectory_entry(+ api_key_hash=active_principal,+ session_id="pbs_clipped",+ entry={"tool_name": "click", "selector": "#discarded"},+ )+ append_trajectory_entry(+ api_key_hash=active_principal,+ session_id="pbs_clipped",+ entry={"tool_name": "click", "selector": "#retained"},+ )++ result = await skyvern_code_block_synthesize(session_id="pbs_clipped")++ assert result["ok"] is True+ assert result["data"]["capture_truncated"] is True+ assert result["data"]["truncated"] is False+ assert result["data"]["emitted_interaction_count"] == 1+++async def test_session_shortcut_reports_fully_clipped_capture(+ active_principal: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(trajectory_store, "MAX_BYTES", 1)+ append_trajectory_entry(+ api_key_hash=active_principal,+ session_id="pbs_clipped",+ entry={"tool_name": "click", "selector": "#oversized"},+ )++ result = await skyvern_code_block_synthesize(session_id="pbs_clipped")++ assert result["ok"] is False+ assert result["error"]["code"] == "INVALID_INPUT"+ assert result["error"]["details"] == {"capture_truncated": True}+++async def test_session_shortcut_rejects_not_found_capture(active_principal: str) -> None:+ result = await skyvern_code_block_synthesize(session_id="pbs_unknown")++ assert result["ok"] is False+ assert result["error"]["code"] == "INVALID_INPUT"+++async def test_session_shortcut_does_not_disclose_foreign_capture(active_principal: str) -> None:+ append_trajectory_entry(+ api_key_hash=_HASH_B,+ session_id="pbs_foreign",+ entry={"tool_name": "click", "selector": "#private"},+ )++ foreign = await skyvern_code_block_synthesize(session_id="pbs_foreign")+ unknown = await skyvern_code_block_synthesize(session_id="pbs_unknown")++ assert active_principal == _HASH_A+ assert foreign == unknown+++async def test_synthesize_mcp_schema_keeps_both_sources_optional_and_trajectory_first() -> None:+ tools_by_name = {tool.name: tool for tool in await mcp.list_tools()}+ schema = tools_by_name["skyvern_code_block_synthesize"].parameters++ assert list(schema["properties"]) == ["trajectory_json", "strict_selectors", "session_id"]+ assert "trajectory_json" not in schema.get("required", [])+ assert "session_id" not in schema.get("required", [])++@pytest.mark.asyncioasync def test_fixture_trajectory_synthesizes_non_empty_code_block() -> None:result = await skyvern_code_block_synthesize(json.dumps(_fixture_trajectory()))