Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Stop the older Copilot turn when a new turn starts in the same chat (SKY-18319) (#8955)
Andrew Neilson29271c42d39a
diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.pyindex 74daaa786..bd21ef751 100644--- a/skyvern/forge/sdk/routes/workflow_copilot.py+++ b/skyvern/forge/sdk/routes/workflow_copilot.py@@ -762,6 +762,36 @@ async def _watch_for_cancel(return+async def _stop_older_live_turns(+ cache: BaseCache,+ organization_id: str,+ chat: WorkflowCopilotChat,+ turn_id: str,+ own_cancel_token: str | None,+) -> None:+ # ponytail: the markers come from the chat load, so a turn saved after this request loaded the chat is not seen.+ # Returning the other markers from start_copilot_turn's locked read would close that window.+ for entry in chat.pending_turns.values():+ if (+ entry.turn_id == turn_id+ or not entry.cancel_token+ or entry.cancel_token == own_cancel_token+ or entry.recovering_at is not None+ ):+ continue+ key = _copilot_cancel_key(organization_id, entry.cancel_token)+ with contained_effect("copilot older-turn stop", workflow_copilot_chat_id=chat.workflow_copilot_chat_id):+ # A Stop click may already have written its gesture; keep it.+ if not await cache.get(key):+ await cache.set(key, "superseded", ex=COPILOT_CANCEL_TTL)+ LOG.info(+ "copilot_turn_superseded",+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ turn_id=turn_id,+ superseded_turn_id=entry.turn_id,+ )++RouteExit = Literal["completed", "error", "cancelled", "duplicate", "refused"]@@ -3040,6 +3070,10 @@ async def _new_copilot_chat_post(# This ordering closes the race where Stop could otherwise persist the unscreened# request while starting the turn.cache = getattr(app, "CACHE", None)+ if cache is not None:+ await _stop_older_live_turns(+ cache, organization.organization_id, chat, turn_id, chat_request.cancel_token+ )if chat_request.cancel_token and cache is not None:handler_task = asyncio.current_task()if handler_task is not None:diff --git a/tests/unit/copilot_route_test_support.py b/tests/unit/copilot_route_test_support.pyindex f3da0a810..fb8047f2b 100644--- a/tests/unit/copilot_route_test_support.py+++ b/tests/unit/copilot_route_test_support.py@@ -119,6 +119,8 @@ def setup_new_copilot_mocks(agent_result.proposal_workflow_run_id = Noneif not hasattr(chat, "workflow_permanent_id"):chat.workflow_permanent_id = getattr(original_workflow, "workflow_permanent_id", "wpid-1")+ if not hasattr(chat, "pending_turns"):+ chat.pending_turns = {}if not hasattr(original_workflow, "modified_at"):original_workflow.modified_at = datetime(2026, 4, 14, tzinfo=timezone.utc)if not hasattr(original_workflow, "title"):diff --git a/tests/unit/test_workflow_copilot_cancel.py b/tests/unit/test_workflow_copilot_cancel.pyindex c45d2b09e..6153fd1ff 100644--- a/tests/unit/test_workflow_copilot_cancel.py+++ b/tests/unit/test_workflow_copilot_cancel.py@@ -61,6 +61,7 @@ from skyvern.forge.sdk.routes.workflow_copilot import ()from skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind, TurnOutcomefrom skyvern.forge.sdk.schemas.workflow_copilot import (+ CopilotPendingTurn,WorkflowCopilotCancelRequest,WorkflowCopilotChat,WorkflowCopilotChatRequest,@@ -279,6 +280,7 @@ async def _drive_cancel_route(agent_result: SimpleNamespace,keep_pending_proposal: bool = False,user_cancel: bool = True,+ cancel_token: str = "tok_abc",) -> tuple[AsyncMock, SimpleNamespace, list[Any]]:"""Run a single chat-post + handler turn and return (restore_mock, workflow_params, sent_payloads)."""captured = install_fake_create(monkeypatch)@@ -295,7 +297,9 @@ async def _drive_cancel_route(organization = SimpleNamespace(organization_id="org-1")response = await workflow_copilot_chat_post(- request, _make_chat_request(keep_pending_proposal=keep_pending_proposal), organization+ request,+ _make_chat_request(cancel_token=cancel_token, keep_pending_proposal=keep_pending_proposal),+ organization,)assert response is captured["sentinel"]@@ -1282,6 +1286,33 @@ async def test_watcher_reports_the_gesture_the_cancel_named() -> None:assert handler_task.cancelled() or handler_task.cancelling()+async def test_a_new_turn_stops_the_turn_still_running_in_its_chat(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.forge.sdk.routes.workflow_copilot.COPILOT_CANCEL_POLL_SECONDS", 0.01)+ cache = _FakeCache()+ monkeypatch.setattr(app._inst, "CACHE", cache, raising=False)+ chat = _make_chat(auto_accept=False)+ chat.pending_turns = {+ "turn-a": CopilotPendingTurn(turn_id="turn-a", started_at=datetime.now(timezone.utc), cancel_token="tok-a")+ }+ older_handler = asyncio.create_task(asyncio.sleep(60))+ observed: list[bool] = [False]+ older_watcher = asyncio.create_task(_watch_for_cancel(cache, "org-1", "tok-a", older_handler, observed))+ agent_result = AgentResult(+ user_response="Done.", updated_workflow=None, global_llm_context=None, workflow_yaml=None, turn_outcome=None+ )++ await _drive_cancel_route(+ monkeypatch, chat, _make_original_workflow(), agent_result, user_cancel=False, cancel_token="tok-b"+ )++ await asyncio.wait_for(older_watcher, timeout=2.0)+ with pytest.raises(asyncio.CancelledError):+ await older_handler+ assert observed[0] is True+ assert _copilot_cancel_key("org-1", "tok-b") not in cache.store++# ---------------------------------------------------------------------------# Operational cancel disambiguation# ---------------------------------------------------------------------------@@ -1300,6 +1331,7 @@ async def test_a_cancel_after_the_agent_built_its_context_writes_one_row_with_itorganization_id="org-1",proposed_workflow=None,auto_accept=False,+ pending_turns={},)original_workflow = fake_workflow(workflow_id="wf-canonical",