Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-10139): preserve proposals on output-policy blocks (#6107)
Andrew Neilson6e098278ec78
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.test.ts b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.test.tsindex 675e1d38a..7f2d78de6 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.test.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.test.ts@@ -33,6 +33,16 @@ describe("shouldAutoApplyWorkflowResponse", () => {},);+ it("does not auto-apply no_proposal responses", () => {+ expect(+ shouldAutoApplyWorkflowResponse(+ response({ proposal_disposition: "no_proposal" }),+ true,+ false,+ ),+ ).toBe(false);+ });+it("uses the enum over legacy booleans when both are present", () => {expect(shouldAutoApplyWorkflowResponse(diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.tsindex d88c3e6bf..033d7730b 100644--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts@@ -5,6 +5,7 @@ import {export type WorkflowCopilotChatSender = "user" | "ai";export type ProposalDisposition =+ | "no_proposal"| "auto_applicable"| "review_untested"| "review_tested";diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 1ef17f2f7..630f57860 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -704,6 +704,13 @@ _RAW_SECRET_LEAK_REFUSAL = ("Store credentials in the Skyvern Credentials UI and reply with the saved credential name or a "f"credential ID beginning with cred_. {RAW_SECRET_REFUSAL_SENTINEL}.")+_SAVED_DRAFT_OUTPUT_POLICY_SUFFIX = " I only blocked the chat reply; the workflow draft is still saved."+++def _with_saved_draft_output_policy_copy(user_response: str) -> str:+ return f"{user_response}{_SAVED_DRAFT_OUTPUT_POLICY_SUFFIX}"++_CANCEL_REPLY_DEFAULT = "Cancelled by user."_CANCEL_REPLY_UNVALIDATED = ("Cancelled. I have a draft workflow you can keep — accept it to save "@@ -1541,44 +1548,63 @@ def _build_output_policy_blocked_result(prior_workflow_yaml: str | None,output_policy_diagnostics: dict[str, Any] | None = None,) -> AgentResult:+ preserved_workflow = ctx.last_workflow if ctx.last_workflow is not None and ctx.last_workflow_yaml else None+ preserved_workflow_yaml = ctx.last_workflow_yaml if preserved_workflow is not None else Nonestructured = StructuredContext.from_json_str(prior_global_llm_context)structured.decisions_made.append("output-policy blocked final output: " + ", ".join(reason.value for reason in verdict.reason_codes))request_policy = ctx.request_policy if isinstance(ctx.request_policy, RequestPolicy) else None+ add_saved_draft_copy = Falseif (request_policy is not Noneand request_policy.clarification_questionand OutputPolicyReason.REQUEST_POLICY_CLARIFICATION_BYPASS in verdict.reason_codes):user_response = request_policy.clarification_question+ add_saved_draft_copy = Trueelif OutputPolicyReason.RAW_SECRET_LEAK in verdict.reason_codes:user_response = _RAW_SECRET_LEAK_REFUSAL+ add_saved_draft_copy = Trueelif OutputPolicyReason.UNAPPROVED_CREDENTIAL_REFERENCE in verdict.reason_codes:user_response = ("I need you to confirm which saved credential should be used before I can continue. ""Please reply with the credential name from the Credentials UI, or adjust the workflow to avoid ""using credentials.")+ add_saved_draft_copy = Trueelif OutputPolicyReason.CREDENTIAL_SCOPE_BROADENED in verdict.reason_codes:user_response = ("The selected credential is not approved for one of the URLs in this workflow. ""Please use a saved credential tested for that URL, update the block URL to match the credential's ""tested site, or adjust the workflow to avoid using credentials.")+ add_saved_draft_copy = True+ elif preserved_workflow is not None:+ user_response = (+ "I could not safely return that chat reply, but the workflow draft is still saved. "+ "Please review the draft or adjust the request and try again."+ )else:- user_response = "I could not safely return that Copilot output. Please adjust the request and try again."+ user_response = "I could not safely return that chat reply. Please adjust the request and try again."+ if preserved_workflow is not None and add_saved_draft_copy:+ user_response = _with_saved_draft_output_policy_copy(user_response)return AgentResult(user_response=user_response,- updated_workflow=None,+ updated_workflow=preserved_workflow,global_llm_context=structured.to_json_str(),response_type="ASK_QUESTION",- workflow_yaml=prior_workflow_yaml or None,+ workflow_yaml=preserved_workflow_yaml or prior_workflow_yaml,workflow_was_persisted=ctx.workflow_persisted,total_tokens=ctx.total_tokens_used,- # Policy blocks invalidate any currently staged proposal. The prior- # YAML is retained for context, but the accept UI should not stay armed.- clear_proposed_workflow=True,+ clear_proposed_workflow=False,+ proposal_disposition=(+ "no_proposal"+ if preserved_workflow is None+ else "review_untested"+ if ctx.last_test_ok is not True+ else "review_tested"+ ),output_policy_diagnostics=output_policy_diagnosticsor build_output_policy_diagnostics(raw_verdict=verdict,diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.pyindex 380bda33d..3e8537009 100644--- a/skyvern/forge/sdk/copilot/context.py+++ b/skyvern/forge/sdk/copilot/context.py@@ -13,7 +13,7 @@ from skyvern.forge.sdk.workflow.models.workflow import WorkflowResponseType = Literal["REPLY", "ASK_QUESTION", "REPLACE_WORKFLOW"]COPILOT_RESPONSE_TYPES: tuple[ResponseType, ...] = get_args(ResponseType)-ProposalDisposition = Literal["auto_applicable", "review_untested", "review_tested"]+ProposalDisposition = Literal["no_proposal", "auto_applicable", "review_untested", "review_tested"]if TYPE_CHECKING:from skyvern.forge.sdk.copilot.diagnosis_repair_contract import DiagnosisRepairContractdiff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.pyindex a08c90a75..69ccb6e07 100644--- a/skyvern/forge/sdk/routes/workflow_copilot.py+++ b/skyvern/forge/sdk/routes/workflow_copilot.py@@ -254,13 +254,17 @@ async def _ensure_terminal_frame(stream: EventSourceStream, already_emitted: boodef _proposal_disposition(agent_result: object | None) -> ProposalDisposition:+ if agent_result is None:+ return "no_proposal"disposition = getattr(agent_result, "proposal_disposition", None)- if disposition in ("auto_applicable", "review_untested", "review_tested"):+ if disposition in ("no_proposal", "auto_applicable", "review_untested", "review_tested"):return dispositionif getattr(agent_result, "unvalidated", False) is True:return "review_untested"if getattr(agent_result, "force_review", False) is True:return "review_tested"+ if getattr(agent_result, "updated_workflow", None) is None:+ return "no_proposal"return "auto_applicable"@@ -305,6 +309,11 @@ def _build_proposed_workflow_data(updated_workflow: Workflow, agent_result: Agenreturn proposed_data+def _output_policy_blocked_final_response(agent_result: AgentResult) -> bool:+ diagnostics = getattr(agent_result, "output_policy_diagnostics", None)+ return isinstance(diagnostics, dict) and diagnostics.get("final_output_policy_allowed") is False++async def _persist_proposed_workflow_state(chat: Any, agent_result: AgentResult, restored: bool) -> None:updated_workflow = agent_result.updated_workflowauto_accept_effective = _effective_auto_accept(chat.auto_accept, agent_result)@@ -321,9 +330,10 @@ async def _persist_proposed_workflow_state(chat: Any, agent_result: AgentResult,# auto-accept toggle.await _clear_proposed_workflow(chat)elif (- auto_accept_effective+ chat.auto_accept is Trueand chat.proposed_workflow is not Noneand chat.proposed_workflow.get("_copilot_unvalidated") is True+ and not _output_policy_blocked_final_response(agent_result)):# The leftover unvalidated proposal is no longer attached to the chat# tail; clear it so reload doesn't resurrect a stale Accept/Reject card.diff --git a/tests/unit/test_copilot_output_policy.py b/tests/unit/test_copilot_output_policy.pyindex e02873f94..9b08f971d 100644--- a/tests/unit/test_copilot_output_policy.py+++ b/tests/unit/test_copilot_output_policy.py@@ -737,13 +737,63 @@ def test_output_policy_credential_block_asks_for_credential_confirmation()assert result.response_type == "ASK_QUESTION"- assert result.clear_proposed_workflow is True+ assert result.clear_proposed_workflow is Falseresponse = result.user_response.lower()for term in expected_terms:assert term in responseassert "I could not safely return" not in result.user_response+def test_output_policy_block_preserves_already_gated_workflow_proposal() -> None:+ ctx = _ctx()+ ctx.last_workflow = SimpleNamespace(name="draft")+ ctx.last_workflow_yaml = "title: Draft"+ ctx.workflow_persisted = True+ ctx.last_test_ok = True++ result = agent_module._build_output_policy_blocked_result(+ ctx,+ OutputPolicyVerdict(+ reason_codes=[OutputPolicyReason.INTERNAL_TOOL_INSTRUCTION_LEAK],+ ),+ prior_global_llm_context="{}",+ prior_workflow_yaml="title: Prior",+ )++ assert result.response_type == "ASK_QUESTION"+ assert result.updated_workflow is ctx.last_workflow+ assert result.workflow_yaml == "title: Draft"+ assert result.workflow_was_persisted is True+ assert result.clear_proposed_workflow is False+ assert result.proposal_disposition == "review_tested"+ response = result.user_response.lower()+ assert "chat reply" in response+ assert "workflow draft" in response+ assert "saved" in response+++def test_output_policy_specific_refusal_preserves_saved_draft_copy() -> None:+ ctx = _ctx()+ ctx.last_workflow = SimpleNamespace(name="draft")+ ctx.last_workflow_yaml = "title: Draft"++ result = agent_module._build_output_policy_blocked_result(+ ctx,+ OutputPolicyVerdict(+ reason_codes=[OutputPolicyReason.RAW_SECRET_LEAK],+ ),+ prior_global_llm_context="{}",+ prior_workflow_yaml="title: Prior",+ )++ assert result.updated_workflow is ctx.last_workflow+ assert result.clear_proposed_workflow is False+ assert result.proposal_disposition == "review_untested"+ assert "raw credentials or secrets" in result.user_response+ assert "chat reply" in result.user_response+ assert "workflow draft is still saved" in result.user_response++def test_scheduling_credential_policy_block_does_not_use_safety_refusal() -> None:scheduling_yaml = """workflow_definition:@@ -1018,7 +1068,8 @@ workflow_definition:assert agent_result.response_type == "ASK_QUESTION"assert agent_result.updated_workflow is None- assert agent_result.clear_proposed_workflow is True+ assert agent_result.clear_proposed_workflow is False+ assert agent_result.proposal_disposition == "no_proposal"process_mock.assert_not_called()@@ -1035,7 +1086,8 @@ def test_translate_to_agent_result_blocks_raw_secret_final_text() -> None:assert agent_result.response_type == "ASK_QUESTION"assert agent_result.updated_workflow is None- assert agent_result.clear_proposed_workflow is True+ assert agent_result.clear_proposed_workflow is False+ assert agent_result.proposal_disposition == "no_proposal"assert "hunter2" not in agent_result.user_responseassert "DO NOT PROVIDE RAW LOGIN/PASSWORD" in agent_result.user_responsediff --git a/tests/unit/test_workflow_copilot_route.py b/tests/unit/test_workflow_copilot_route.pyindex e60bc1abe..c5019d491 100644--- a/tests/unit/test_workflow_copilot_route.py+++ b/tests/unit/test_workflow_copilot_route.py@@ -377,6 +377,63 @@ async def test_proposed_workflow_cleared_on_restore(assert response_frames[0].updated_workflow == expected_payload_workflow+async def test_output_policy_block_preserves_unvalidated_prior_proposal_under_auto_accept(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(settings, "ENABLE_WORKFLOW_COPILOT_V2", True)++ captured = _install_fake_create(monkeypatch)++ chat = SimpleNamespace(+ workflow_copilot_chat_id="chat-1",+ workflow_permanent_id="wpid-1",+ organization_id="org-1",+ proposed_workflow={"workflow_id": "staged", "_copilot_unvalidated": True},+ auto_accept=True,+ )+ original_workflow = SimpleNamespace(+ workflow_id="wf-canonical",+ title="Original",+ description="Original description",+ workflow_definition=None,+ )+ agent_result = SimpleNamespace(+ user_response="I could not safely return that chat reply.",+ updated_workflow=None,+ global_llm_context=None,+ workflow_yaml=None,+ workflow_was_persisted=False,+ clear_proposed_workflow=False,+ unvalidated=False,+ output_policy_diagnostics={+ "final_output_policy_allowed": False,+ "hard_block_reason_codes": ["internal_tool_instruction_leak"],+ },+ )++ _setup_new_copilot_mocks(monkeypatch, chat, original_workflow, agent_result)++ request = MagicMock()+ request.headers = {"x-api-key": "sk-test-key"}+ organization = SimpleNamespace(organization_id="org-1")++ response = await workflow_copilot_chat_post(request, _make_chat_request(), organization)+ assert response is captured["sentinel"]++ stream = MagicMock()+ stream.send = AsyncMock(return_value=True)+ stream.is_disconnected = AsyncMock(return_value=False)++ handler = captured["handler"]+ assert callable(handler)+ await handler(stream)++ update_calls = app.DATABASE.workflow_params.update_workflow_copilot_chat.await_args_list+ clear_calls = [c for c in update_calls if c.kwargs.get("proposed_workflow") is None]+ assert not clear_calls, f"did not expect a clear call, got {update_calls!r}"++@pytest.mark.asyncioasync def test_unvalidated_timeout_wip_overrides_auto_accept(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(settings, "ENABLE_WORKFLOW_COPILOT_V2", True)diff --git a/tests/unit/test_workflow_copilot_route_helpers.py b/tests/unit/test_workflow_copilot_route_helpers.pyindex 156b7aaab..0e815a676 100644--- a/tests/unit/test_workflow_copilot_route_helpers.py+++ b/tests/unit/test_workflow_copilot_route_helpers.py@@ -120,6 +120,22 @@ class TestEffectiveAutoAccept:assert _effective_auto_accept(True, result) is Falseassert _effective_auto_accept(False, result) is False+ def test_no_proposal_disposition_overrides_auto_accept(self) -> None:+ result = MagicMock()+ result.proposal_disposition = "no_proposal"+ result.cancelled = False++ assert _effective_auto_accept(True, result) is False+ assert _effective_auto_accept(False, result) is False++ def test_missing_proposal_disposition_is_no_proposal_without_updated_workflow(self) -> None:+ result = MagicMock(spec=["unvalidated", "force_review", "updated_workflow"])+ result.unvalidated = False+ result.force_review = False+ result.updated_workflow = None++ assert _proposal_disposition(result) == "no_proposal"+def test_legacy_flag_fallback_for_stacked_deploy(self) -> None:result = MagicMock(spec=["unvalidated", "force_review"])result.unvalidated = False@@ -137,8 +153,9 @@ class TestEffectiveAutoAccept:assert _effective_auto_accept(False, validated) is Falseassert _effective_auto_accept(None, validated) is False- def test_no_agent_result_falls_back_to_user_setting(self) -> None:- assert _effective_auto_accept(True, None) is True+ def test_no_agent_result_is_not_auto_applicable(self) -> None:+ assert _proposal_disposition(None) == "no_proposal"+ assert _effective_auto_accept(True, None) is Falseassert _effective_auto_accept(False, None) is False