Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(backend): stop reporting a user's cancel as an assistant error (#14689)

Reinier van der Leereb1e8aee30ed
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index 762e182e59..062137888e 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -1452,6 +1452,12 @@ async def reset_copilot_usage(
)
+# A delivered cancel has been measured missing this window while the executor
+# was still tearing the turn down, so timing out here is a normal outcome.
+_CANCEL_CONFIRM_TIMEOUT_SECONDS = 5.0
+_CANCEL_CONFIRM_POLL_INTERVAL_SECONDS = 0.5
+
+
async def _clear_pending_best_effort(session_id: str) -> None:
"""Drop the session's pending buffer, swallowing Redis errors.
@@ -1532,12 +1538,10 @@ async def cancel_session_task(
logger.info(f"[CANCEL] Published cancel for session ...{session_id[-8:]}")
# Poll until the executor confirms the task is no longer running.
- poll_interval = 0.5
- max_wait = 5.0
waited = 0.0
- while waited < max_wait:
- await asyncio.sleep(poll_interval)
- waited += poll_interval
+ while waited < _CANCEL_CONFIRM_TIMEOUT_SECONDS:
+ await asyncio.sleep(_CANCEL_CONFIRM_POLL_INTERVAL_SECONDS)
+ waited += _CANCEL_CONFIRM_POLL_INTERVAL_SECONDS
session_state = await stream_registry.get_session(session_id)
if session_state is None or session_state.status != "running":
logger.info(
@@ -1551,13 +1555,22 @@ async def cancel_session_task(
return CancelSessionResponse(cancelled=True)
logger.warning(
- f"[CANCEL] Session ...{session_id[-8:]} not confirmed after {max_wait}s, force-completing"
+ f"[CANCEL] Session ...{session_id[-8:]} not confirmed after "
+ f"{_CANCEL_CONFIRM_TIMEOUT_SECONDS}s, completing the turn as cancelled"
+ )
+ # The user asked for this stop, so publishing a StreamError would paint
+ # the "assistant encountered an error" banner over their own cancel.
+ await stream_registry.mark_session_completed(
+ session_id,
+ error_message="Operation cancelled",
+ skip_error_publish=True,
)
- await stream_registry.mark_session_completed(session_id, error_message="Cancelled")
# Status is now force-flipped out of "running"; re-clear to drop any
# follow-up that landed during the poll window.
await _clear_pending_best_effort(session_id)
- return CancelSessionResponse(cancelled=True)
+ return CancelSessionResponse(
+ cancelled=True, reason="cancel_published_not_confirmed"
+ )
def _ui_message_stream_headers() -> dict[str, str]:
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
index 6ea7ccd415..2ad4b102e8 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
@@ -3150,6 +3150,59 @@ def test_cancel_session_enqueues_cancel_and_confirms(
mock_enqueue.assert_called_once_with("sess-1")
+def test_cancel_session_timeout_completes_as_cancelled_not_as_an_error(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ """A Stop the executor never confirms is still the user's Stop.
+
+ The force-complete branch used to publish a ``StreamError``, which every
+ live and resumed stream renders as "the assistant encountered an error" --
+ the user's own cancel reported back to them as the assistant failing.
+ ``skip_error_publish`` keeps the status flip (locks released, queued turns
+ promoted) without the error frame, and the ``reason`` tells the caller the
+ turn may still be draining, which is what the frontend's "Stop may take a
+ moment" toast is keyed on.
+ """
+ from backend.copilot.stream_registry import ActiveSession
+
+ _mock_validate_session(mocker)
+ mocker.patch(
+ "backend.copilot.turn_queue.cancel_queued_turn",
+ new=AsyncMock(return_value=False),
+ )
+ running = ActiveSession(
+ session_id="sess-1",
+ user_id=TEST_USER_ID,
+ tool_call_id="chat_stream",
+ tool_name="chat",
+ turn_id="turn-1",
+ status="running",
+ )
+ mock_registry = MagicMock()
+ mock_registry.get_active_session = AsyncMock(return_value=(running, "1-0"))
+ # Never leaves "running": the executor did not confirm inside the window.
+ mock_registry.get_session = AsyncMock(return_value=running)
+ mock_registry.mark_session_completed = AsyncMock(return_value=True)
+ mocker.patch("backend.api.features.chat.routes.stream_registry", mock_registry)
+ mocker.patch(
+ "backend.api.features.chat.routes.enqueue_cancel_task",
+ new_callable=AsyncMock,
+ )
+ mocker.patch.object(chat_routes, "_CANCEL_CONFIRM_TIMEOUT_SECONDS", 0.02)
+ mocker.patch.object(chat_routes, "_CANCEL_CONFIRM_POLL_INTERVAL_SECONDS", 0.01)
+
+ response = client.post("/sessions/sess-1/cancel")
+
+ assert response.status_code == 200
+ assert response.json()["cancelled"] is True
+ mock_registry.mark_session_completed.assert_awaited_once()
+ assert (
+ mock_registry.mark_session_completed.await_args.kwargs.get("skip_error_publish")
+ is True
+ ), "a user cancel must not be published to the stream as an error"
+ assert response.json()["reason"] == "cancel_published_not_confirmed"
+
+
def test_cancel_session_clears_pending_buffer(
mocker: pytest_mock.MockerFixture,
) -> None:
diff --git a/autogpt_platform/backend/backend/copilot/stream_registry.py b/autogpt_platform/backend/backend/copilot/stream_registry.py
index e08ac76501..410813c705 100644
--- a/autogpt_platform/backend/backend/copilot/stream_registry.py
+++ b/autogpt_platform/backend/backend/copilot/stream_registry.py
@@ -901,9 +901,10 @@ async def mark_session_completed(
error_message: If provided, marks as "failed" and publishes a
StreamError before StreamFinish. Otherwise marks as "completed".
skip_error_publish: If True, still marks the session as "failed" but
- does NOT publish a StreamError event. Use this when the error has
- already been published to the stream (e.g. via stream_and_publish)
- to avoid duplicate error delivery to the frontend.
+ does NOT publish a StreamError event. Use this for a user-initiated
+ cancel, which the frontend would otherwise render as "the assistant
+ encountered an error", and when the error has already been
+ published to the stream (e.g. via stream_and_publish).
Returns:
True if session was newly marked completed, False if already completed/failed
diff --git a/autogpt_platform/backend/backend/copilot/stream_registry_test.py b/autogpt_platform/backend/backend/copilot/stream_registry_test.py
index a70b293dbd..cd983d3127 100644
--- a/autogpt_platform/backend/backend/copilot/stream_registry_test.py
+++ b/autogpt_platform/backend/backend/copilot/stream_registry_test.py
@@ -369,6 +369,46 @@ async def test_mark_session_completed_swallows_dispatcher_errors():
assert result is True
+async def test_mark_session_completed_skip_error_publish_emits_no_stream_error():
+ """``skip_error_publish`` is what lets a user-initiated cancel end a turn
+ without the frontend rendering "the assistant encountered an error".
+
+ Both arms run so the suppression is shown to be load-bearing: the same
+ call without the flag publishes the StreamError. The terminal StreamFinish
+ is published either way, so a subscriber still sees the turn end.
+ """
+
+ async def _mark(*, skip_error_publish: bool):
+ publish_mock = AsyncMock()
+ with (
+ patch.object(
+ stream_registry,
+ "get_redis_async",
+ new=AsyncMock(return_value=_FakeRedis({"status": "running"})),
+ ),
+ patch.object(
+ stream_registry,
+ "hash_compare_and_set",
+ new=AsyncMock(return_value=True),
+ ),
+ patch.object(stream_registry, "publish_chunk", new=publish_mock),
+ ):
+ await stream_registry.mark_session_completed(
+ "sess-1",
+ error_message="Operation cancelled",
+ skip_error_publish=skip_error_publish,
+ )
+ return [call.args[1] for call in publish_mock.call_args_list]
+
+ suppressed = await _mark(skip_error_publish=True)
+ assert not any(isinstance(c, stream_registry.StreamError) for c in suppressed)
+ assert any(isinstance(c, stream_registry.StreamFinish) for c in suppressed)
+
+ published = await _mark(skip_error_publish=False)
+ assert any(isinstance(c, stream_registry.StreamError) for c in published)
+
+
@pytest.mark.asyncio
async def test_mark_session_completed_skips_lock_release_when_already_completed():
"""CAS failure = someone else completed the session first; we must not