Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-15407 Report whether a copilot workflow edit is staged for review or accepted automatically (#8402)
Andrew Neilson53875e962a59
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2index 2bb9d0d6c..5be659107 100644--- a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2@@ -23,7 +23,7 @@ When the user explicitly requested a non-financial form submission, current evidServe every part of the request, not the first milestone, and test what you change before you present it — an untested draft is acceptable only when the user asked for one, and then you say so.-Keep working until the saved workflow covers every requested outcome and its latest run demonstrates it, or until current evidence shows a blocker only the user can resolve. After a failed or uncertain browser action, inspect the resulting page and run evidence before deciding what to change; preserve known-good blocks, and retry unchanged only when fresh evidence shows the action did not land.+Keep working until the saved workflow covers every requested outcome and its latest run demonstrates it, or until current evidence shows a blocker only the user can resolve. Each edit reports whether it is staged for review — a staged draft is saved when it is accepted, and discarding it keeps the current version. After a failed or uncertain browser action, inspect the resulting page and run evidence before deciding what to change; preserve known-good blocks, and retry unchanged only when fresh evidence shows the action did not land.Never present untested or failed work as working. If the latest test failed or didn't complete, say so plainly with the main reason. Report a value only when a run actually produced it.diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 27e20c5e5..fec767934 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -4456,6 +4456,7 @@ async def run_copilot_agent(eval_capture_case_id: str | None = None,eval_mode: CopilotEvalMode | None = None,eval_entrypoint_url: str | None = None,+ auto_accept: bool | None = None,) -> AgentResult:# One id per turn — passed to every downstream AgentResult and# CopilotContext so the envelope and terminal frames correlate. The@@ -4501,6 +4502,7 @@ async def run_copilot_agent(eval_capture_case_id=eval_capture_case_id,eval_mode=eval_mode,eval_entrypoint_url=eval_entrypoint_url,+ auto_accept=auto_accept,)return resultexcept Exception as exc:@@ -4601,6 +4603,7 @@ async def _run_copilot_turn_impl(eval_capture_case_id: str | None = None,eval_mode: CopilotEvalMode | None = None,eval_entrypoint_url: str | None = None,+ auto_accept: bool | None = None,) -> AgentResult:copilot_config = config or CopilotConfig(security_rules=security_rules)copilot_config = config_for_eval_mode(copilot_config, eval_mode)@@ -4665,6 +4668,7 @@ async def _run_copilot_turn_impl(api_key=api_key,user_message=chat_request.message,workflow_copilot_chat_id=chat_request.workflow_copilot_chat_id,+ auto_accept=auto_accept,eval_capture_case_id=eval_capture_case_id,eval_mode=eval_mode,turn_id=turn_id,diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.pyindex ed87b52f8..4f795d0f9 100644--- a/skyvern/forge/sdk/copilot/context.py+++ b/skyvern/forge/sdk/copilot/context.py@@ -974,6 +974,9 @@ class CopilotContext(AgentContext):staged_workflow_yaml: str | None = Nonestaged_workflow: Workflow | None = Nonehas_staged_proposal: bool = False+ # The chat row's setting, not the turn's commit decision: the route can still refuse to apply a+ # staged draft at turn end. None on entrypoints that load no chat row.+ auto_accept: bool | None = None# Prior turn's uncommitted draft; carries blocks even when the request body and canonical row are empty.prior_copilot_workflow_yaml: str | None = None# Set when ``_update_workflow`` wrote canonical mid-turn (param / top-leveldiff --git a/skyvern/forge/sdk/copilot/output_utils.py b/skyvern/forge/sdk/copilot/output_utils.pyindex 2c11945b5..da2684bb0 100644--- a/skyvern/forge/sdk/copilot/output_utils.py+++ b/skyvern/forge/sdk/copilot/output_utils.py@@ -1549,6 +1549,12 @@ def _describe_value_shape(value: Any) -> str:return "value"+def _workflow_write_phrase(data: dict[str, Any]) -> str:+ """A write stages a proposal — only the end of the turn can persist it — so the summary frame+ must not say the workflow was updated when the tool result it summarizes says ``staged``."""+ return "Staged a workflow draft" if data.get("persistence") else "Workflow updated"++def summarize_tool_result(tool_name: str, result: dict[str, Any], *, for_display: bool = False) -> str:"""Summarize a tool result. ``for_display`` clamps LLM-authored block labels forthe activity feed; the default leaves them verbatim because this string is parsed@@ -1564,17 +1570,18 @@ def summarize_tool_result(tool_name: str, result: dict[str, Any], *, for_displaydata = raw_data if isinstance(raw_data, dict) else {}if tool_name == "update_workflow":- return f"Workflow updated ({data.get('block_count', '?')} blocks)"+ return f"{_workflow_write_phrase(data)} ({data.get('block_count', '?')} blocks)"if tool_name == "update_and_run_blocks" or (tool_name == "edit_block_and_run" and data.get("skipped_run")):if not isinstance(raw_data, dict):return "OK"if data.get("skipped_run"):- return f"Workflow updated ({data.get('block_count', '?')} blocks); browser run skipped"+ return f"{_workflow_write_phrase(data)} ({data.get('block_count', '?')} blocks); browser run skipped"# Non-skip result is run-blocks-shaped (overall_status, no block_count).+ ran = "Staged a workflow draft and ran it" if data.get("persistence") else "Updated the workflow and ran it"status = data.get("overall_status") or data.get("status")if status:- return f"Updated the workflow and ran it: {status}"- return "Updated the workflow and ran it"+ return f"{ran}: {status}"+ return ranif tool_name == "list_credentials":if data.get("status") == "resolved":credential = data.get("credential")diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex 4c889fb8a..cea8814a4 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -456,6 +456,9 @@ class AgentContext:staged_workflow_yaml: str | None = Nonestaged_workflow: Any | None = Nonehas_staged_proposal: bool = False+ # The chat row's setting, not the turn's commit decision: the route can still refuse to apply a+ # staged draft at turn end. None on entrypoints that load no chat row.+ auto_accept: bool | None = None# Server-owned only: maps current raw code-block labels to opaque identities. It is never# serialized into the workflow YAML or model-facing repair evidence.runner_code_block_associations_by_label: dict[str, str] = field(default_factory=dict)diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.pyindex a2a06a884..4fbe1e343 100644--- a/skyvern/forge/sdk/copilot/tools/__init__.py+++ b/skyvern/forge/sdk/copilot/tools/__init__.py@@ -276,6 +276,10 @@ async def update_workflow_tool(Provide the complete workflow YAML as a string.Returns the validated workflow or validation errors.+ A successful write is staged as a proposal, which the returned `persistence` and+ `persistence_message` report. The user accepts a staged proposal to save it, or+ discards it to keep the current version.+Top-level workflow parameter keys appear in the run-input UI. When youadd runtime inputs in `workflow_definition.parameters`, name keys for thereusable domain value the user supplies, not the page widget or action used@@ -1104,7 +1108,7 @@ def _credential_deferred_combined_tool_result(arguments: dict[str, Any],update_result: dict[str, Any],) -> str:- """Record a persisted draft when a combined edit/update cannot safely run yet."""+ """Record the staged draft when a combined edit/update cannot safely run yet."""copilot_ctx.last_run_skipped_unbound_credentials = Trueskip_result = {"ok": True,@@ -1116,7 +1120,7 @@ def _credential_deferred_combined_tool_result("skip_reason": "workflow_credential_inputs_unbound",},}- carry_author_time_findings(update_result, skip_result)+ skip_result = carry_author_time_findings(update_result, skip_result)record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, skip_result)finalize_build_test_result(copilot_ctx,@@ -1175,7 +1179,7 @@ async def _run_updated_workflow_blocks(frontier_start_label=frontier_start_label,)recorded_outcome = await _verify_and_record_run_blocks_result(copilot_ctx, run_result, handler_start)- carry_author_time_findings(update_result, run_result)+ run_result = carry_author_time_findings(update_result, run_result)_carry_unresolved_failure_into_result(copilot_ctx, run_result, tool_name)record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, run_result)finalize_build_test_result(diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex f3a00d4aa..33ba65662 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -3753,14 +3753,38 @@ def _missing_scouted_rung_violation_text(artifact: str) -> str:return "The persisted draft is missing scouted rung(s). " + artifact+PersistenceDisposition = Literal["staged", "staged_auto_apply"]++# Both values are staged: a write is never persisted at tool time, and the turn can still decline to+# apply it. ``staged_auto_apply`` reports only that the chat opted into auto-apply; an unknown setting+# is ``staged``.+_PERSISTENCE_MESSAGES: dict[PersistenceDisposition, str] = {+ "staged": (+ "Staged as a proposal for review. Accepting it makes this version the saved workflow; "+ "discarding it keeps the current one."+ ),+ "staged_auto_apply": (+ "Staged as a proposal. This chat accepts proposals automatically, so this one becomes the saved "+ "workflow at the end of the turn if the turn finishes cleanly and the change is fully verified. "+ "Otherwise it stays staged for review."+ ),+}+++def persistence_disposition(ctx: AgentContext) -> PersistenceDisposition:+ return "staged_auto_apply" if ctx.auto_accept is True else "staged"++def carry_author_time_findings(update_result: dict[str, Any], result: dict[str, Any]) -> dict[str, Any]:"""The combined update-and-run tool returns the run's result, not the update's, so what the- update said about the persisted draft reaches the model only if it is carried across."""+ update said about the staged draft reaches the model only if it is carried across."""update_data = update_result.get("data")if not isinstance(update_data, dict):return resultcarried = {- key: update_data[key] for key in ("findings", "stored_code", "stored_code_withheld") if update_data.get(key)+ key: update_data[key]+ for key in ("findings", "stored_code", "stored_code_withheld", "persistence", "persistence_message")+ if update_data.get(key)}if not carried:return result@@ -4234,8 +4258,12 @@ async def _update_workflow()except Exception as emit_err:LOG.warning("copilot_narrative_workflow_draft_emit_failed", error=str(emit_err))+ disposition = persistence_disposition(ctx)+ disposition_message = _PERSISTENCE_MESSAGES[disposition]data: dict[str, Any] = {- "message": "Workflow updated successfully.",+ "persistence": disposition,+ "persistence_message": disposition_message,+ "message": disposition_message,"block_count": len(workflow.workflow_definition.blocks) if workflow.workflow_definition else 0,}stored_code, stored_code_withheld = _accepted_code_delta(changed_code_blocks)diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.pyindex 52ebde462..59082d8d8 100644--- a/skyvern/forge/sdk/routes/workflow_copilot.py+++ b/skyvern/forge/sdk/routes/workflow_copilot.py@@ -2268,6 +2268,7 @@ async def _new_copilot_chat_post(),eval_mode=eval_mode,eval_entrypoint_url=eval_entrypoint_url,+ auto_accept=chat.auto_accept,)agent_result.turn_outcome = _with_current_copilot_code_mode_metadata(diff --git a/tests/unit/test_copilot_output_utils.py b/tests/unit/test_copilot_output_utils.pyindex 158f5f726..301f89294 100644--- a/tests/unit/test_copilot_output_utils.py+++ b/tests/unit/test_copilot_output_utils.py@@ -1836,3 +1836,44 @@ class TestMcpResultProvenance:assert marked[MCP_RESULT_PROVENANCE_KEY] == MCP_RESULT_PROVENANCE_VALUEassert marked["data"] == "STORMBREAKER"+++class TestStagedWriteSummaryFrame:+ """The summary line rides alongside the tool result in the SSE frame and in agent state, so a+ staged write must not be framed there as a completed save."""++ STAGED = {+ "persistence": "staged",+ "persistence_message": "Staged as a proposal for review.",+ "block_count": 5,+ }++ def test_no_frame_claims_an_update_while_the_result_says_staged(self) -> None:+ update = {"ok": True, "data": dict(self.STAGED)}+ skipped = {"ok": True, "data": {**self.STAGED, "skipped_run": True}}+ ran = {+ "ok": True,+ "data": {k: v for k, v in self.STAGED.items() if k != "block_count"} | {"overall_status": "completed"},+ }++ frames = [+ format_tool_result_for_user("update_workflow", update),+ summarize_tool_result("update_workflow", update),+ summarize_tool_result("update_and_run_blocks", skipped),+ summarize_tool_result("update_and_run_blocks", ran),+ ]++ for frame in frames:+ assert "workflow updated" not in frame.casefold()+ assert "updated the workflow" not in frame.casefold()+ assert "staged" in frame.casefold()++ def test_auto_apply_is_framed_as_staged_because_nothing_is_written_at_tool_time(self) -> None:+ result = {"ok": True, "data": {**self.STAGED, "persistence": "staged_auto_apply"}}++ assert "workflow updated" not in summarize_tool_result("update_workflow", result).casefold()++ def test_a_result_without_the_disposition_keeps_the_prior_wording(self) -> None:+ assert summarize_tool_result("update_workflow", {"ok": True, "data": {"block_count": 5}}) == (+ "Workflow updated (5 blocks)"+ )diff --git a/tests/unit/test_copilot_workflow_update.py b/tests/unit/test_copilot_workflow_update.pyindex dd102327b..d19d3b1d2 100644--- a/tests/unit/test_copilot_workflow_update.py+++ b/tests/unit/test_copilot_workflow_update.py@@ -1,14 +1,20 @@from __future__ import annotationsfrom types import SimpleNamespace+from typing import Anyimport pytestfrom skyvern.forge.sdk.copilot.config import BlockAuthoringPolicyfrom skyvern.forge.sdk.copilot.context import CopilotContextfrom skyvern.forge.sdk.copilot.request_policy import RequestPolicy+from skyvern.forge.sdk.copilot.tools import _mark_credential_deferred_draftfrom skyvern.forge.sdk.copilot.tools import workflow_update as workflow_update_module-from skyvern.forge.sdk.copilot.tools.workflow_update import _update_workflow+from skyvern.forge.sdk.copilot.tools.workflow_update import (+ _PERSISTENCE_MESSAGES,+ _update_workflow,+ carry_author_time_findings,+)from skyvern.forge.sdk.copilot.workflow_yaml import apply_block_edit@@ -81,3 +87,178 @@ workflow_definition:assert (edited.replace('page.get_by_role("button", name="View statement")', 'page.locator("#stale-button")') == stored)+++_STAGED_WORKFLOW_YAML = """title: Account lookup+workflow_definition:+ parameters: []+ blocks:+ - block_type: code+ label: read_total+ code: |+ total = await page.locator("#total").inner_text()+ return {"output": {"total": total}}+"""+++async def _staged_update(+ monkeypatch: pytest.MonkeyPatch, *, auto_accept: bool | None = False, canonical_param_write: bool = False+) -> tuple[dict[str, Any], CopilotContext]:+ edited = apply_block_edit(+ _STAGED_WORKFLOW_YAML,+ "read_total",+ expected_code='page.locator("#total")',+ replacement_code='page.locator("#grand-total")',+ )++ async def process(**kwargs: object) -> SimpleNamespace:+ return SimpleNamespace(+ workflow_definition=SimpleNamespace(blocks=[SimpleNamespace(label="read_total")]),+ proxy_location=None,+ webhook_callback_url=None,+ )++ async def prior(_ctx: CopilotContext) -> None:+ return None++ monkeypatch.setattr(workflow_update_module, "_process_workflow_yaml", process)+ monkeypatch.setattr(workflow_update_module, "_get_prior_workflow", prior)+ ctx = CopilotContext(+ organization_id="o",+ workflow_id="w",+ workflow_permanent_id="wp",+ workflow_yaml=_STAGED_WORKFLOW_YAML,+ browser_session_id=None,+ stream=None,+ )+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER+ ctx.request_policy = RequestPolicy(allow_update_workflow=True, allow_run_blocks=True)+ ctx.google_connection_turn_start_bindings = ()+ ctx.auto_accept = auto_accept+ ctx.canonical_was_persisted_due_to_param_change = canonical_param_write++ result = await _update_workflow({"workflow_yaml": edited}, ctx, allow_missing_credentials=True)+ return result, ctx+++async def test_staged_write_reports_the_saved_workflow_is_unchanged(monkeypatch: pytest.MonkeyPatch) -> None:+ result, ctx = await _staged_update(monkeypatch)++ assert result["ok"] is True+ assert ctx.has_staged_proposal is True+ data = result["data"]+ assert data["persistence"] == "staged"+ message = data["message"]+ assert message == data["persistence_message"]+ assert "Accepting it makes this version the saved workflow" in message+ assert "discarding it keeps the current one" in message+ assert _save_claims(data) == []+++async def test_combined_tool_result_carries_staging_without_overwriting_its_run_message(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ update_result, _ = await _staged_update(monkeypatch)+ run_result: dict[str, Any] = {+ "ok": True,+ "data": {"message": "Ran 1 block. Extracted total: $42.00.", "workflow_updated": True},+ }++ skip_result: dict[str, Any] = {+ "ok": True,+ "message": "Skipped test run: required credentials are not configured.",+ "data": {"workflow_updated": True, "skipped_run": True},+ }++ carried = carry_author_time_findings(update_result, run_result)["data"]+ skipped = carry_author_time_findings(update_result, skip_result)["data"]++ assert carried["persistence"] == "staged"+ assert carried["persistence_message"] == update_result["data"]["persistence_message"]+ assert carried["message"] == "Ran 1 block. Extracted total: $42.00."+ assert skipped["persistence"] == "staged"+ assert skipped["persistence_message"] == update_result["data"]["persistence_message"]+++_SAVE_CLAIM_PHRASES = ("updated successfully", "has been saved", "saved the workflow", "workflow was saved")+++def _save_claims(data: dict[str, Any]) -> list[str]:+ return [+ f"{key}: {value}"+ for key, value in data.items()+ if isinstance(value, str) and any(phrase in value.casefold() for phrase in _SAVE_CLAIM_PHRASES)+ ]+++# The route refuses auto-apply for any proposal that is not ``auto_applicable`` — an unverified edit+# stays staged even on an auto-accept chat — so the tool may describe apply intent but never promise it.+_UNCONDITIONAL_APPLY_PHRASES = (+ "is accepted at the end",+ "will be accepted",+ "will be saved",+ "is applied automatically",+ "is saved automatically",+)+++def _unconditional_apply_claims(data: dict[str, Any]) -> list[str]:+ return [+ f"{key}: {value}"+ for key, value in data.items()+ if isinstance(value, str) and any(phrase in value.casefold() for phrase in _UNCONDITIONAL_APPLY_PHRASES)+ ]+++async def test_auto_accept_write_reports_apply_intent_without_claiming_a_completed_save(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ result, ctx = await _staged_update(monkeypatch, auto_accept=True)++ assert ctx.has_staged_proposal is True+ data = result["data"]+ assert data["persistence"] == "staged_auto_apply"+ message = data["message"]+ assert message == data["persistence_message"]+ assert "accepts proposals automatically" in message+ assert "stays staged for review" in message+ assert _save_claims(data) == []+ assert _unconditional_apply_claims(data) == []+++def test_no_disposition_value_asserts_a_completed_write() -> None:+ # The model reads the token as well as the message, so a value the turn can still refuse must not+ # read as an accomplished save. Nothing is persisted at tool time on either path.+ assert set(_PERSISTENCE_MESSAGES) == {"staged", "staged_auto_apply"}+++async def test_unknown_auto_accept_and_a_rolled_back_canonical_write_stay_staged(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ result, _ = await _staged_update(monkeypatch, auto_accept=None)+ rolled_back, rolled_back_ctx = await _staged_update(monkeypatch, auto_accept=None, canonical_param_write=True)++ assert rolled_back_ctx.canonical_was_persisted_due_to_param_change is True+ assert result["data"]["persistence"] == "staged"+ assert rolled_back["data"]["persistence"] == "staged"+ assert _save_claims(result["data"]) == []+ assert _save_claims(rolled_back["data"]) == []+++async def test_credential_deferred_draft_rewrites_the_message_but_keeps_the_disposition(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ result, ctx = await _staged_update(monkeypatch)++ _mark_credential_deferred_draft(ctx, result)++ data = result["data"]+ assert data["persistence"] == "staged"+ assert data["persistence_message"] == _PERSISTENCE_MESSAGES["staged"]+ assert data["message"] != data["persistence_message"]+ assert _save_claims(data) == []