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(frontend/copilot): fix streaming reconnect races, hydration ordering, and reasoning split (#12813)
Ubbe1974ec626042
diff --git a/.gitignore b/.gitignoreindex 53df57dc70..b17115c95a 100644--- a/.gitignore+++ b/.gitignore@@ -196,3 +196,7 @@ test.dbplans/.claude/worktrees/test-results/++# Playwright MCP / local browser-testing artifacts+.playwright-mcp/+copilot-session-switch-qa/diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex d317d677a5..ae208d1c0f 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -8,7 +8,7 @@ from uuid import uuid4from autogpt_libs import authfrom fastapi import APIRouter, HTTPException, Query, Response, Security-from fastapi.responses import JSONResponse, StreamingResponse+from fastapi.responses import StreamingResponsefrom pydantic import BaseModel, ConfigDict, Field, field_validatorfrom backend.copilot import service as chat_service@@ -47,7 +47,14 @@ from backend.copilot.rate_limit import (release_reset_lock,reset_daily_usage,)-from backend.copilot.response_model import StreamError, StreamFinish, StreamHeartbeat+from backend.copilot.response_model import (+ StreamError,+ StreamFinish,+ StreamFinishStep,+ StreamHeartbeat,+ StreamStart,+ StreamStartStep,+)from backend.copilot.service import strip_injected_context_for_displayfrom backend.copilot.tools.e2b_sandbox import kill_sandboxfrom backend.copilot.tools.models import (@@ -154,6 +161,14 @@ class StreamChatRequest(BaseModel):)+class QueuePendingMessageRequest(BaseModel):+ """Request model for queueing a follow-up while a turn is running."""++ message: str = Field(max_length=64_000)+ context: dict[str, str] | None = None+ file_ids: list[str] | None = Field(default=None, max_length=20)++class PeekPendingMessagesResponse(BaseModel):"""Response for the pending-message peek (GET) endpoint.@@ -209,6 +224,11 @@ class ActiveStreamInfo(BaseModel):turn_id: strlast_message_id: str # Redis Stream message ID for resumption+ # ISO-8601 timestamp (UTC) marking when the backend registered the turn+ # as running. Lets the frontend seed its elapsed-time counter so restored+ # turns show honest "time since turn started" instead of the misleading+ # "time since this mount resumed the SSE".+ started_at: str | None = Noneclass SessionDetailResponse(BaseModel):@@ -529,6 +549,7 @@ async def get_session(active_stream_info = ActiveStreamInfo(turn_id=active_session.turn_id,last_message_id=last_message_id,+ started_at=active_session.created_at.isoformat(),)# Skip session metadata on "load more" — frontend only needs messages@@ -816,17 +837,45 @@ async def cancel_session_task(return CancelSessionResponse(cancelled=True)+def _ui_message_stream_headers() -> dict[str, str]:+ return {+ "Cache-Control": "no-cache",+ "Connection": "keep-alive",+ "X-Accel-Buffering": "no",+ "x-vercel-ai-ui-message-stream": "v1",+ }+++def _empty_ui_message_stream_response() -> StreamingResponse:+ # Stable placeholder messageId for the empty queued-mid-turn stream.+ # Real turns generate per-message UUIDs via the executor; this stream+ # has no message to attach to, but the AI SDK parser still requires a+ # non-empty ``messageId`` field on ``StreamStart``.+ message_id = uuid4().hex++ async def event_generator() -> AsyncGenerator[str, None]:+ # Vercel AI SDK's UI-message-stream parser expects symmetric+ # start/finish framing at both stream and step level — every+ # non-empty turn emits the pair. Without an opener, today's parser+ # tolerates the closer (no active parts to flush) but a future SDK+ # tightening would silently break the queue-mid-turn UX. Emit the+ # full empty pair so the contract stays correct.+ yield StreamStart(messageId=message_id).to_sse()+ yield StreamStartStep().to_sse()+ yield StreamFinishStep().to_sse()+ yield StreamFinish().to_sse()+ yield "data: [DONE]\n\n"++ return StreamingResponse(+ event_generator(),+ media_type="text/event-stream",+ headers=_ui_message_stream_headers(),+ )++@router.post("/sessions/{session_id}/stream",responses={- 202: {- "model": QueuePendingMessageResponse,- "description": (- "Session has a turn in flight — message queued into the pending "- "buffer and will be picked up between tool-call rounds by the "- "executor currently processing the turn."- ),- },404: {"description": "Session not found or access denied"},429: {"description": "Cost rate-limit or call-frequency cap exceeded"},},@@ -836,19 +885,18 @@ async def stream_chat_post(request: StreamChatRequest,user_id: str = Security(auth.get_user_id),):- """Start a new turn OR queue a follow-up — decided server-side.+ """Start a new turn and return an AI SDK UI message stream.- - **Session idle**: starts a turn. Returns an SSE stream (``text/event-stream``)- with Vercel AI SDK chunks (text fragments, tool-call UI, tool results).- The generation runs in a background task that survives client disconnects;- reconnect via ``GET /sessions/{session_id}/stream`` to resume.+ Returns an SSE stream (``text/event-stream``) with Vercel AI SDK chunks+ (text fragments, tool-call UI, tool results). The generation runs in a+ background task that survives client disconnects; reconnect via+ ``GET /sessions/{session_id}/stream`` to resume.- - **Session has a turn in flight**: pushes the message into the per-session- pending buffer and returns ``202 application/json`` with- ``QueuePendingMessageResponse``. The executor running the current turn- drains the buffer between tool-call rounds (baseline) or at the start of- the next turn (SDK). Clients should detect the 202 and surface the- message as a queued-chip in the UI.+ Follow-up messages typed while a turn is already running should use+ ``POST /sessions/{session_id}/messages/pending``. If an older client still+ posts that follow-up here, we queue it defensively but still return a valid+ empty UI-message stream so AI SDK transports never receive a JSON body from+ the stream endpoint.Args:session_id: The chat session identifier.@@ -872,26 +920,29 @@ async def stream_chat_post(extra={"json_fields": log_meta},)session = await _validate_and_get_session(session_id, user_id)- builder_permissions = resolve_session_permissions(session)- # Self-defensive queue-fallback: if a turn is already running, don't race- # it on the cluster lock — drop the message into the pending buffer and- # return 202 so the caller can render a chip. Both UI chips and autopilot- # block follow-ups route through this path; keeping the decision on the- # server means every caller gets uniform behaviour.if (request.is_user_messageand request.messageand await is_turn_in_flight(session_id)):- response = await queue_pending_for_http(- session_id=session_id,- user_id=user_id,- message=request.message,- context=request.context,- file_ids=request.file_ids,- )- return JSONResponse(status_code=202, content=response.model_dump())+ try:+ await queue_pending_for_http(+ session_id=session_id,+ user_id=user_id,+ message=request.message,+ context=request.context,+ file_ids=request.file_ids,+ )+ return _empty_ui_message_stream_response()+ except HTTPException as exc:+ if exc.status_code != 409:+ raise++ # Permission resolution is only needed below for the actual turn — keep+ # it after the queue-fall-through so a queued mid-turn request returns+ # without paying the work.+ builder_permissions = resolve_session_permissions(session)logger.info(f"[TIMING] session validated in {(time.perf_counter() - stream_start_time) * 1000:.1f}ms",@@ -1130,12 +1181,37 @@ async def stream_chat_post(return StreamingResponse(event_generator(),media_type="text/event-stream",- headers={- "Cache-Control": "no-cache",- "Connection": "keep-alive",- "X-Accel-Buffering": "no", # Disable nginx buffering- "x-vercel-ai-ui-message-stream": "v1", # AI SDK protocol header- },+ headers=_ui_message_stream_headers(),+ )+++ "/sessions/{session_id}/messages/pending",+ response_model=QueuePendingMessageResponse,+ responses={+ 404: {"description": "Session not found or access denied"},+ 409: {"description": "Session has no active turn to receive pending messages"},+ 429: {"description": "Call-frequency cap exceeded"},+ },+)+async def queue_pending_message(+ session_id: str,+ request: QueuePendingMessageRequest,+ user_id: str = Security(auth.get_user_id),+):+ """Queue a follow-up message while the session has an active turn."""+ await _validate_and_get_session(session_id, user_id)+ if not await is_turn_in_flight(session_id):+ raise HTTPException(+ status_code=409,+ detail="Session has no active turn. Start a new turn with POST /stream.",+ )+ return await queue_pending_for_http(+ session_id=session_id,+ user_id=user_id,+ message=request.message,+ context=request.context,+ file_ids=request.file_ids,)@@ -1169,6 +1245,7 @@ async def get_pending_messages()async def resume_session_stream(session_id: str,+ last_chunk_id: str | None = Query(default=None, include_in_schema=False),user_id: str = Security(auth.get_user_id),):"""@@ -1178,27 +1255,26 @@ async def resume_session_stream(Checks for an active (in-progress) task on the session and either replaysthe full SSE stream or returns 204 No Content if nothing is running.- Args:- session_id: The chat session identifier.- user_id: Optional authenticated user ID.-- Returns:- StreamingResponse (SSE) when an active stream exists,- or 204 No Content when there is nothing to resume.+ Always replays the active turn from ``0-0``. The AI SDK UI-message parser+ keeps text/reasoning part state inside a single parser instance; resuming+ from a Redis cursor can skip the ``*-start`` events required by later+ ``*-delta`` chunks."""import asyncio- active_session, last_message_id = await stream_registry.get_active_session(+ active_session, _latest_backend_id = await stream_registry.get_active_session(session_id, user_id)if not active_session:return Response(status_code=204)- # Always replay from the beginning ("0-0") on resume.- # We can't use last_message_id because it's the latest ID in the backend- # stream, not the latest the frontend received — the gap causes lost- # messages. The frontend deduplicates replayed content.+ if last_chunk_id:+ logger.info(+ "Ignoring deprecated last_chunk_id on stream resume",+ extra={"session_id": session_id, "last_chunk_id": last_chunk_id},+ )+subscriber_queue = await stream_registry.subscribe_to_session(session_id=session_id,user_id=user_id,@@ -1259,12 +1335,7 @@ async def resume_session_stream(return StreamingResponse(event_generator(),media_type="text/event-stream",- headers={- "Cache-Control": "no-cache",- "Connection": "keep-alive",- "X-Accel-Buffering": "no",- "x-vercel-ai-ui-message-stream": "v1",- },+ headers=_ui_message_stream_headers(),)diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.pyindex 1f692ab299..914a15f58f 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py@@ -157,6 +157,11 @@ def _mock_stream_internals(mocker: pytest_mock.MockerFixture):"backend.api.features.chat.routes._validate_and_get_session",return_value=None,)+ mocker.patch(+ "backend.api.features.chat.routes.is_turn_in_flight",+ new_callable=AsyncMock,+ return_value=False,+ )mock_save = mocker.patch("backend.api.features.chat.routes.append_and_save_message",return_value=MagicMock(), # non-None = message was saved (not a duplicate)@@ -637,7 +642,7 @@ class TestStreamChatRequestModeValidation:assert req.mode is None-# ─── POST /stream queue-fallback (when a turn is already in flight) ──+# ─── Pending message queue (when a turn is already in flight) ─────────def _mock_stream_queue_internals(@@ -646,11 +651,9 @@ def _mock_stream_queue_internals(session_exists: bool = True,turn_in_flight: bool = True,call_count: int = 1,+ push_length: int | None = 1,):- """Mock dependencies for the POST /stream queue-fallback path.-- When ``turn_in_flight`` is True the handler takes the 202 queue branch.- """+ """Mock dependencies for the pending-message queue path."""if session_exists:mock_session = mocker.MagicMock()mock_session.id = "sess-1"@@ -692,12 +695,10 @@ def _mock_stream_queue_internals(return_value=call_count,)mocker.patch(- "backend.copilot.pending_message_helpers.push_pending_message",+ "backend.copilot.pending_message_helpers.push_pending_message_if_session_running",new_callable=AsyncMock,- return_value=1,+ return_value=push_length,)- # queue_user_message re-runs is_turn_in_flight via the helper module —- # stub that path out too so we don't need a fake stream_registry.mocker.patch("backend.copilot.pending_message_helpers.get_active_session_meta",new_callable=AsyncMock,@@ -705,37 +706,65 @@ def _mock_stream_queue_internals()-def test_stream_queue_returns_202_when_turn_in_flight(+def test_queue_pending_message_returns_200_when_turn_in_flight(mocker: pytest_mock.MockerFixture,) -> None:- """Happy path: POST /stream to a session with a live turn → 202 queue."""+ """Happy path: POST /messages/pending to a live turn queues the message."""_mock_stream_queue_internals(mocker)response = client.post(- "/sessions/sess-1/stream",- json={"message": "follow-up", "is_user_message": True},+ "/sessions/sess-1/messages/pending",+ json={"message": "follow-up"},)- assert response.status_code == 202+ assert response.status_code == 200data = response.json()assert data["buffer_length"] == 1assert "turn_in_flight" in data-def test_stream_queue_session_not_found_returns_404(+def test_queue_pending_message_session_not_found_returns_404(mocker: pytest_mock.MockerFixture,) -> None:"""If the session doesn't exist or belong to the user, returns 404."""_mock_stream_queue_internals(mocker, session_exists=False)response = client.post(- "/sessions/bad-sess/stream",- json={"message": "hi", "is_user_message": True},+ "/sessions/bad-sess/messages/pending",+ json={"message": "hi"},)assert response.status_code == 404-def test_stream_queue_call_frequency_limit_returns_429(+def test_queue_pending_message_without_active_turn_returns_409(+ mocker: pytest_mock.MockerFixture,+) -> None:+ """A pending-message push needs an active turn to consume it."""+ _mock_stream_queue_internals(mocker, turn_in_flight=False)++ response = client.post(+ "/sessions/sess-1/messages/pending",+ json={"message": "hi"},+ )++ assert response.status_code == 409+++def test_queue_pending_message_race_after_active_check_returns_409(+ mocker: pytest_mock.MockerFixture,+) -> None:+ """If the active turn ends before the atomic push, the message is not queued."""+ _mock_stream_queue_internals(mocker, push_length=None)++ response = client.post(+ "/sessions/sess-1/messages/pending",+ json={"message": "hi"},+ )++ assert response.status_code == 409+++def test_queue_pending_message_call_frequency_limit_returns_429(mocker: pytest_mock.MockerFixture,) -> None:"""Per-user call-frequency cap rejects rapid-fire queued pushes."""@@ -744,14 +773,14 @@ def test_stream_queue_call_frequency_limit_returns_429(_mock_stream_queue_internals(mocker, call_count=PENDING_CALL_LIMIT + 1)response = client.post(- "/sessions/sess-1/stream",- json={"message": "hi", "is_user_message": True},+ "/sessions/sess-1/messages/pending",+ json={"message": "hi"},)assert response.status_code == 429assert "Too many queued message requests this minute" in response.json()["detail"]-def test_stream_queue_converts_context_dict_to_pending_context(+def test_queue_pending_message_converts_context_dict_to_pending_context(mocker: pytest_mock.MockerFixture,) -> None:"""StreamChatRequest.context is a raw dict; must be coerced to the@@ -768,15 +797,14 @@ def test_stream_queue_converts_context_dict_to_pending_context()response = client.post(- "/sessions/sess-1/stream",+ "/sessions/sess-1/messages/pending",json={"message": "hi",- "is_user_message": True,"context": {"url": "https://example.test", "content": "body"},},)- assert response.status_code == 202+ assert response.status_code == 200queue_spy.assert_awaited_once()kwargs = queue_spy.await_args.kwargsfrom backend.copilot.pending_messages import PendingMessageContext@@ -786,7 +814,7 @@ def test_stream_queue_converts_context_dict_to_pending_context(assert kwargs["context"].content == "body"-def test_stream_queue_passes_none_context_when_omitted(+def test_queue_pending_message_passes_none_context_when_omitted(mocker: pytest_mock.MockerFixture,) -> None:"""When request.context is omitted, the queue call receives context=None."""@@ -802,15 +830,31 @@ def test_stream_queue_passes_none_context_when_omitted()response = client.post(- "/sessions/sess-1/stream",- json={"message": "hi", "is_user_message": True},+ "/sessions/sess-1/messages/pending",+ json={"message": "hi"},)- assert response.status_code == 202+ assert response.status_code == 200queue_spy.assert_awaited_once()assert queue_spy.await_args.kwargs["context"] is None+def test_stream_chat_queues_legacy_inflight_post_but_returns_sse(+ mocker: pytest_mock.MockerFixture,+) -> None:+ """POST /stream must not return JSON to an AI SDK transport."""+ _mock_stream_queue_internals(mocker)++ response = client.post(+ "/sessions/sess-1/stream",+ json={"message": "follow-up", "is_user_message": True},+ )++ assert response.status_code == 200+ assert response.headers["content-type"].startswith("text/event-stream")+ assert '"type":"finish"' in response.text++# ─── get_pending_messages (GET /sessions/{session_id}/messages/pending) ─────@@ -1581,9 +1625,14 @@ def test_resume_session_stream_no_subscriber_queue(mock_registry.subscribe_to_session = AsyncMock(return_value=None)mocker.patch("backend.api.features.chat.routes.stream_registry", mock_registry)- response = client.get("/sessions/sess-1/stream")+ response = client.get("/sessions/sess-1/stream?last_chunk_id=9999-9")assert response.status_code == 204+ mock_registry.subscribe_to_session.assert_awaited_once_with(+ session_id="sess-1",+ user_id=TEST_USER_ID,+ last_message_id="0-0",+ )# ─── DELETE /sessions/{id}/stream — disconnect listeners ──────────────diff --git a/autogpt_platform/backend/backend/blocks/autopilot.py b/autogpt_platform/backend/backend/blocks/autopilot.pyindex ff7c3784ac..ab044181d3 100644--- a/autogpt_platform/backend/backend/blocks/autopilot.py+++ b/autogpt_platform/backend/backend/blocks/autopilot.py@@ -7,6 +7,7 @@ import loggingimport uuidfrom typing import TYPE_CHECKING, Any+from pydantic import field_validatorfrom typing_extensions import TypedDict # Needed for Python <3.12 compatibilityfrom backend.blocks._base import (@@ -17,6 +18,7 @@ from backend.blocks._base import (BlockSchemaOutput,)from backend.copilot.permissions import (+ DISABLED_LEGACY_TOOL_NAMES,CopilotPermissions,ToolName,all_known_tool_names,@@ -198,6 +200,13 @@ class AutoPilotBlock(Block):# timeouts internally; wrapping with asyncio.timeout corrupts the# SDK's internal stream (see service.py CRITICAL comment).+ @field_validator("tools", mode="before")+ @classmethod+ def strip_disabled_legacy_tools(cls, tools: Any) -> Any:+ if not isinstance(tools, list):+ return tools+ return [tool for tool in tools if tool not in DISABLED_LEGACY_TOOL_NAMES]+class Output(BlockSchemaOutput):"""Output schema for the AutoPilot block."""diff --git a/autogpt_platform/backend/backend/blocks/autopilot_permissions_test.py b/autogpt_platform/backend/backend/blocks/autopilot_permissions_test.pyindex 0e406d1eb8..0d1f66fea7 100644--- a/autogpt_platform/backend/backend/blocks/autopilot_permissions_test.py+++ b/autogpt_platform/backend/backend/blocks/autopilot_permissions_test.py@@ -62,6 +62,14 @@ class TestBuildAndValidatePermissions:with pytest.raises(ValidationError, match="not_a_real_tool"):_make_input(tools=["not_a_real_tool"])+ async def test_disabled_legacy_tool_is_accepted_and_removed(self):+ inp = _make_input(tools=["ask_question", "run_block"])+ result = await _build_and_validate_permissions(inp)++ assert inp.tools == ["run_block"]+ assert isinstance(result, CopilotPermissions)+ assert result.tools == ["run_block"]+async def test_valid_block_name_accepted(self):mock_block_cls = MagicMock()mock_block_cls.return_value.name = "HTTP Request"diff --git a/autogpt_platform/backend/backend/copilot/executor/processor.py b/autogpt_platform/backend/backend/copilot/executor/processor.pyindex 3838302504..61e0daa7b6 100644--- a/autogpt_platform/backend/backend/copilot/executor/processor.py+++ b/autogpt_platform/backend/backend/copilot/executor/processor.py@@ -35,12 +35,14 @@ SHUTDOWN_ERROR_MESSAGE = ("Copilot executor shut down before this turn finished. Please retry.")-# Max time execute() blocks after calling future.cancel() / when draining a-# soon-to-be-cancelled future. Gives _execute_async's own finally a chance to-# publish the accurate terminal state over the Redis CAS; long enough to let-# an in-flight Redis call settle, short enough that shutdown doesn't stall.+# Max time execute() blocks after requesting async turn cancellation. The worker+# waits for normal cleanup so late stream writes do not race the manager, but it+# must still escape to the sync fail-close safety net if cleanup wedges._CANCEL_GRACE_SECONDS = 5.0+# How long to wait before logging again that a cancelled turn is still draining.+_CANCEL_DRAIN_LOG_INTERVAL_SECONDS = 1.0+# Max time the sync safety net itself spends on a single Redis CAS. Without# this bound the whole point of ``sync_fail_close_session`` is defeated —# ``mark_session_completed`` would hang on the same broken Redis that caused@@ -92,9 +94,11 @@ def sync_fail_close_session(timeout=_FAIL_CLOSE_REDIS_TIMEOUT,)+ coro = _bounded()try:- future = asyncio.run_coroutine_threadsafe(_bounded(), execution_loop)+ future = asyncio.run_coroutine_threadsafe(coro, execution_loop)except RuntimeError as e:+ coro.close()# execution_loop is closed — happens if cleanup() already ran the# per-worker teardown. Nothing we can do; let the stale-session# watchdog reap it.@@ -336,8 +340,7 @@ class CoPilotProcessor:Thin wrapper around :meth:`_execute`. The ``try/finally`` hereguarantees :func:`sync_fail_close_session` runs on every exit- path — normal completion, exception, or a wedged event loop- that escapes via :data:`_CANCEL_GRACE_SECONDS` timeout.+ path — normal completion or exception.``mark_session_completed`` is an atomic CAS on``status == "running"``, so when the async path already wrote aterminal state the sync call is a cheap no-op.@@ -370,40 +373,92 @@ class CoPilotProcessor:that lives in :func:`sync_fail_close_session` which the outer:meth:`execute` always invokes on exit."""+ task_ready: concurrent.futures.Future[asyncio.Task] = (+ concurrent.futures.Future()+ )++ async def run_async_turn():+ task = asyncio.current_task()+ if task is not None and not task_ready.done():+ task_ready.set_result(task)+ return await self._execute_async(entry, cancel, cluster_lock, log)+future = asyncio.run_coroutine_threadsafe(- self._execute_async(entry, cancel, cluster_lock, log),+ run_async_turn(),self.execution_loop,)- # Wait for completion, checking cancel periodically- while not future.done():+ cancel_requested = False+ cancel_started_at: float | None = None+ last_cancel_log_at: float | None = None++ def request_cancel() -> None:+ nonlocal cancel_requested, cancel_started_at, last_cancel_log_at+ log.info("Cancellation requested")try:- future.result(timeout=1.0)- except asyncio.TimeoutError:- if cancel.is_set():- log.info("Cancellation requested")- future.cancel()- # Give _execute_async's own finally a short window to- # publish its accurate terminal state before the outer- # sync safety net fires.- try:- future.result(timeout=_CANCEL_GRACE_SECONDS)- except BaseException:- pass- return- cluster_lock.refresh()+ task = task_ready.result(timeout=0)+ except concurrent.futures.TimeoutError:+ # Sub-millisecond race: ``run_coroutine_threadsafe`` returned+ # before ``run_async_turn`` actually started, so+ # ``task_ready.set_result`` has not run yet. ``future.cancel``+ # on a ``concurrent.futures.Future`` whose underlying task may+ # already be picked up by the loop is best-effort — frequently+ # a no-op. The slow path is intentional: ``cancel.is_set()``+ # is polled inside ``_execute_async`` and the bounded+ # ``_CANCEL_GRACE_SECONDS`` drain below force-cancels and falls+ # through to ``sync_fail_close_session``, so the worst-case+ # observable behaviour is "cancel takes ~5s in this rare race"+ # rather than a stuck session.+ future.cancel()+ else:+ self.execution_loop.call_soon_threadsafe(task.cancel)+ cancel_requested = True+ cancel_started_at = time.monotonic()+ last_cancel_log_at = cancel_started_at++ def log_cancel_wait() -> None:+ nonlocal last_cancel_log_at+ if cancel_started_at is None or last_cancel_log_at is None:+ return+ now = time.monotonic()+ if now - last_cancel_log_at < _CANCEL_DRAIN_LOG_INTERVAL_SECONDS:+ return+ elapsed = now - cancel_started_at+ log.warning(f"Waiting for cancelled turn to drain ({elapsed:.1f}s elapsed)")+ last_cancel_log_at = now++ def cancel_drain_timed_out() -> bool:+ if cancel_started_at is None:+ return False+ elapsed = time.monotonic() - cancel_started_at+ if elapsed < _CANCEL_GRACE_SECONDS:+ return False+ log.warning(+ f"Cancelled turn did not drain within {_CANCEL_GRACE_SECONDS:.1f}s; "+ "falling through to sync fail-close"+ )+ future.cancel()+ return True- if not future.cancelled():- # Bounded timeout so a wedged event loop can't trap us here —- # on timeout we escape to execute()'s finally and the sync- # safety net fires.+ # Wait for completion, checking cancel periodically. A cancellation+ # request waits for normal async cleanup, but remains bounded so the+ # worker does not refresh the per-session lock forever on a wedged turn.+ while True:try:- future.result(timeout=_CANCEL_GRACE_SECONDS)+ future.result(timeout=1.0)+ return+ except concurrent.futures.CancelledError:+ if cancel_requested or cancel.is_set():+ return+ raiseexcept concurrent.futures.TimeoutError:- log.warning(- "Future did not complete within grace window; "- "falling through to sync fail-close"- )+ if cancel.is_set() and not cancel_requested:+ request_cancel()+ elif cancel_requested and cancel_started_at is not None:+ if cancel_drain_timed_out():+ return+ log_cancel_wait()+ cluster_lock.refresh()async def _execute_async(self,diff --git a/autogpt_platform/backend/backend/copilot/executor/processor_test.py b/autogpt_platform/backend/backend/copilot/executor/processor_test.pyindex cdc393e5b1..66b74f26a4 100644--- a/autogpt_platform/backend/backend/copilot/executor/processor_test.py+++ b/autogpt_platform/backend/backend/copilot/executor/processor_test.py@@ -496,3 +496,108 @@ class TestExecuteSafetyNet:assert call_log == ["sync-ok"], f"expected sync_fail_close_session to run once, got {call_log!r}"++ def test_cancel_waits_for_async_task_to_finish(self, exec_loop) -> None:+ """A cancel request must not let ``_execute`` return while the+ underlying asyncio task is still cleaning up. Returning early would+ make the manager release the session lock while late stream writes+ are still possible."""+ proc = CoPilotProcessor()+ self._attach_exec_loop(proc, exec_loop)++ started = threading.Event()+ cancel_seen = threading.Event()+ release_cleanup = threading.Event()+ finished = threading.Event()++ async def _stubborn_cancel(*_args, **_kwargs):+ started.set()+ try:+ await asyncio.sleep(3600)+ except asyncio.CancelledError:+ cancel_seen.set()+ while not release_cleanup.is_set():+ await asyncio.sleep(0.01)+ finally:+ finished.set()++ proc._execute_async = _stubborn_cancel # type: ignore[method-assign]++ cancel = threading.Event()+ pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)+ try:+ fut = pool.submit(+ proc._execute,+ _make_entry(),+ cancel,+ MagicMock(),+ _make_log(),+ )+ assert started.wait(timeout=5)++ cancel.set()+ assert cancel_seen.wait(timeout=5)+ assert not fut.done()++ release_cleanup.set()+ fut.result(timeout=5)+ assert finished.is_set()+ finally:+ pool.shutdown(wait=True)++ def test_cancel_wait_has_bounded_escape_hatch(self, exec_loop) -> None:+ """A wedged async cleanup must not keep the worker refreshing the+ session lock forever; after the grace window, ``_execute`` returns+ so ``execute`` can run the sync fail-close safety net."""+ proc = CoPilotProcessor()+ self._attach_exec_loop(proc, exec_loop)++ started = threading.Event()+ cancel_seen = threading.Event()+ release_cleanup = threading.Event()+ finished = threading.Event()++ async def _wedged_cancel(*_args, **_kwargs):+ started.set()+ try:+ await asyncio.sleep(3600)+ except asyncio.CancelledError:+ cancel_seen.set()+ while not release_cleanup.is_set():+ try:+ await asyncio.sleep(0.01)+ except asyncio.CancelledError:+ pass+ finally:+ finished.set()++ proc._execute_async = _wedged_cancel # type: ignore[method-assign]++ cancel = threading.Event()+ cluster_lock = MagicMock()+ pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)+ try:+ with patch(+ "backend.copilot.executor.processor._CANCEL_GRACE_SECONDS",+ 0.05,+ ):+ fut = pool.submit(+ proc._execute,+ _make_entry(),+ cancel,+ cluster_lock,+ _make_log(),+ )+ assert started.wait(timeout=5)++ cancel.set()+ assert cancel_seen.wait(timeout=5)+ fut.result(timeout=5)++ assert not finished.is_set()+ assert cluster_lock.refresh.call_count < 10++ release_cleanup.set()+ assert finished.wait(timeout=5)+ finally:+ pool.shutdown(wait=True)diff --git a/autogpt_platform/backend/backend/copilot/pending_message_helpers.py b/autogpt_platform/backend/backend/copilot/pending_message_helpers.pyindex 4340b743f0..e1302267bf 100644--- a/autogpt_platform/backend/backend/copilot/pending_message_helpers.py+++ b/autogpt_platform/backend/backend/copilot/pending_message_helpers.py@@ -21,8 +21,10 @@ from backend.copilot.pending_messages import (drain_pending_messages,format_pending_as_user_message,push_pending_message,+ push_pending_message_if_session_running,)from backend.copilot.stream_registry import get_session as get_active_session_meta+from backend.copilot.stream_registry import get_session_meta_keyfrom backend.data.redis_client import get_redis_asyncfrom backend.data.redis_helpers import incr_with_ttlfrom backend.data.workspace import resolve_workspace_files@@ -44,8 +46,8 @@ _PENDING_CALL_KEY_PREFIX = "copilot:pending:calls:"async def is_turn_in_flight(session_id: str) -> bool:"""Return ``True`` when a copilot turn is actively running for *session_id*.- Used by the unified POST /stream entry point and the autopilot block so- a second message arriving while an earlier turn is still executing gets+ Used by the HTTP pending-message endpoint and the autopilot block so a+ second message arriving while an earlier turn is still executing getsqueued into the pending buffer instead of racing the in-flight turn onthe cluster lock."""@@ -54,15 +56,14 @@ async def is_turn_in_flight(session_id: str) -> bool:class QueuePendingMessageResponse(BaseModel):- """Response returned by ``POST /stream`` with status 202 when a message- is queued because the session already has a turn in flight.+ """Response returned when a message is queued because the session already+ has a turn in flight.- ``buffer_length``: how many messages are now in the session'spending buffer (after this push)- ``max_buffer_length``: the per-session cap (server-side constant)- ``turn_in_flight``: ``True`` if a copilot turn was running when- we checked — purely informational for UX feedback. Always ``True``- for responses from ``POST /stream`` with status 202.+ we checked — purely informational for UX feedback."""buffer_length: int@@ -76,11 +77,12 @@ async def queue_user_message(message: str,context: PendingMessageContext | None = None,file_ids: list[str] | None = None,+ require_turn_in_flight: bool = False,) -> QueuePendingMessageResponse:"""Push *message* into the per-session pending buffer.The shared primitive for "a message arrived while a turn is in flight" —- called from the unified POST /stream handler and the autopilot block.+ called from the HTTP pending-message path and the autopilot block.Call-frequency rate limiting is the caller's responsibility (HTTP pathenforces it; internal block callers skip it)."""@@ -89,6 +91,18 @@ async def queue_user_message(file_ids=file_ids or [],context=context,)+ if require_turn_in_flight:+ new_len = await push_pending_message_if_session_running(+ session_id,+ pending,+ session_meta_key=get_session_meta_key(session_id),+ )+ return QueuePendingMessageResponse(+ buffer_length=new_len or 0,+ max_buffer_length=MAX_PENDING_MESSAGES,+ turn_in_flight=new_len is not None,+ )+new_len = await push_pending_message(session_id, pending)return QueuePendingMessageResponse(buffer_length=new_len,@@ -107,7 +121,7 @@ async def queue_pending_for_http() -> QueuePendingMessageResponse:"""HTTP-facing wrapper around :func:`queue_user_message`.- Owns the HTTP-only concerns that sat inline in ``stream_chat_post``:+ Owns the HTTP-only concerns for the pending-message route:1. Per-user call-rate cap (429 on overflow).2. File-ID sanitisation against the user's own workspace.@@ -116,19 +130,8 @@ async def queue_pending_for_http(Raises :class:`HTTPException` with status 429 if the rate cap is hit;otherwise returns the ``QueuePendingMessageResponse`` the handler can- serialise 1:1 into the 202 body.+ serialise 1:1."""- call_count = await check_pending_call_rate(user_id)- if call_count > PENDING_CALL_LIMIT:- raise HTTPException(- status_code=429,- detail=(- f"Too many queued message requests this minute: limit is "- f"{PENDING_CALL_LIMIT} per {PENDING_CALL_WINDOW_SECONDS}s "- "across all sessions"- ),- )-sanitized_file_ids: list[str] | None = Noneif file_ids:files = await resolve_workspace_files(user_id, file_ids)@@ -141,12 +144,41 @@ async def queue_pending_for_http(# typos, but the upstream ``StreamChatRequest.context: dict[str, str]``# is already schemaless, so the strict mode adds no real safety.queue_context = PendingMessageContext.model_validate(context) if context else None- return await queue_user_message(++ # Push first via the Lua CAS gate. Bumping the per-user call-rate+ # counter BEFORE the push would charge a budget tick on every TOCTOU+ # loss against turn completion (status flips running→completed between+ # the FE's is_turn_in_flight check and our gate), which both this+ # endpoint and the POST /stream queue-fall-through can hit. Pushing+ # first lets the gate own the no-op short-circuit.+ response = await queue_user_message(session_id=session_id,message=message,context=queue_context,file_ids=sanitized_file_ids,+ require_turn_in_flight=True,)+ if not response.turn_in_flight:+ raise HTTPException(+ status_code=409,+ detail="Session has no active turn. Start a new turn with POST /stream.",+ )++ # Push landed — now charge the rate counter. If this tick crosses the+ # limit we still keep the queued message (next drain will pick it up)+ # but report 429 so the client backs off further pushes.+ call_count = await check_pending_call_rate(user_id)+ if call_count > PENDING_CALL_LIMIT:+ raise HTTPException(+ status_code=429,+ detail=(+ f"Too many queued message requests this minute: limit is "+ f"{PENDING_CALL_LIMIT} per {PENDING_CALL_WINDOW_SECONDS}s "+ "across all sessions"+ ),+ )++ return responseasync def check_pending_call_rate(user_id: str) -> int:@@ -366,14 +398,35 @@ async def persist_pending_as_user_rows(transcript_builder.restore(transcript_snapshot)if on_rollback is not None:on_rollback(session_anchor)+ # ``push_pending_message`` uses the bounded ``capped_rpush`` (LTRIM+ # to ``MAX_PENDING_MESSAGES``). If ≥``MAX_PENDING_MESSAGES`` fresh+ # follow-ups arrived between the original drain and this rollback+ # (heavy typing across a tool boundary), the LTRIM drops oldest+ # entries — which can include the ones we just re-pushed. The model+ # already saw that content (mid-turn injection earlier in the+ # turn), but no DB row lands so the user sees no UI bubble.+ # Surface a warning so the bounded data-loss path is visible in+ # prod (it is rare and would otherwise be observable only via the+ # absence of a bubble).+ rollback_buffer_at_cap = Falsefor pm in pending:try:- await push_pending_message(session.session_id, pm)+ new_length = await push_pending_message(session.session_id, pm)+ if new_length >= MAX_PENDING_MESSAGES:+ rollback_buffer_at_cap = Trueexcept Exception:logger.exception("%s Failed to re-queue mid-turn follow-up on rollback",log_prefix,)+ if rollback_buffer_at_cap:+ logger.warning(+ "%s Rollback re-push hit pending-buffer cap (MAX=%d); a "+ "previously queued follow-up may have been LTRIM-displaced "+ "(silent UI-bubble drop). Investigate if observed.",+ log_prefix,+ MAX_PENDING_MESSAGES,+ )return Falselogger.info(diff --git a/autogpt_platform/backend/backend/copilot/pending_message_helpers_test.py b/autogpt_platform/backend/backend/copilot/pending_message_helpers_test.pyindex b3ddc6269f..3b2d9b66f6 100644--- a/autogpt_platform/backend/backend/copilot/pending_message_helpers_test.py+++ b/autogpt_platform/backend/backend/copilot/pending_message_helpers_test.py@@ -4,17 +4,20 @@ from typing import Anyfrom unittest.mock import AsyncMock, MagicMockimport pytest+from fastapi import HTTPExceptionfrom backend.copilot import pending_message_helpers as helpers_modulefrom backend.copilot.pending_message_helpers import (PENDING_CALL_LIMIT,+ QueuePendingMessageResponse,check_pending_call_rate,combine_pending_with_current,drain_pending_safe,insert_pending_before_last,persist_session_safe,+ queue_pending_for_http,)-from backend.copilot.pending_messages import PendingMessage+from backend.copilot.pending_messages import MAX_PENDING_MESSAGES, PendingMessage# ── check_pending_call_rate ────────────────────────────────────────────@@ -46,6 +49,112 @@ async def test_check_pending_call_rate_fails_open_on_redis_error(assert result == 0+# ── queue_pending_for_http: gate-then-bump ordering ───────────────────+++async def test_queue_pending_does_not_charge_rate_on_toctou_409(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """When the Lua gate refuses the push because the turn just completed,+ the per-user call-rate counter must NOT have been incremented — bumping+ it before the gate would charge a budget tick for every TOCTOU loss+ against turn completion (race that both this endpoint and the POST+ /stream queue-fall-through can trigger)."""+ monkeypatch.setattr(+ helpers_module,+ "queue_user_message",+ AsyncMock(+ return_value=QueuePendingMessageResponse(+ buffer_length=0,+ max_buffer_length=MAX_PENDING_MESSAGES,+ turn_in_flight=False,+ )+ ),+ )+ rate_mock = AsyncMock(return_value=1)+ monkeypatch.setattr(helpers_module, "check_pending_call_rate", rate_mock)+ monkeypatch.setattr(+ helpers_module, "resolve_workspace_files", AsyncMock(return_value=[])+ )++ with pytest.raises(HTTPException) as exc_info:+ await queue_pending_for_http(+ session_id="sess-1",+ user_id="user-1",+ message="hi",+ context=None,+ file_ids=None,+ )+ assert exc_info.value.status_code == 409+ rate_mock.assert_not_awaited()+++async def test_queue_pending_charges_rate_only_after_successful_push(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ response = QueuePendingMessageResponse(+ buffer_length=2,+ max_buffer_length=MAX_PENDING_MESSAGES,+ turn_in_flight=True,+ )+ queue_mock = AsyncMock(return_value=response)+ monkeypatch.setattr(helpers_module, "queue_user_message", queue_mock)+ rate_mock = AsyncMock(return_value=PENDING_CALL_LIMIT)+ monkeypatch.setattr(helpers_module, "check_pending_call_rate", rate_mock)+ monkeypatch.setattr(+ helpers_module, "resolve_workspace_files", AsyncMock(return_value=[])+ )++ result = await queue_pending_for_http(+ session_id="sess-1",+ user_id="user-1",+ message="hi",+ context=None,+ file_ids=None,+ )++ assert result is response+ queue_mock.assert_awaited_once()+ rate_mock.assert_awaited_once_with("user-1")+++async def test_queue_pending_429_after_push_when_limit_exceeded(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """When the post-push rate counter crosses the limit, the message stays+ in the buffer (next drain will pick it up) but the response is 429 so+ the client backs off."""+ response = QueuePendingMessageResponse(+ buffer_length=3,+ max_buffer_length=MAX_PENDING_MESSAGES,+ turn_in_flight=True,+ )+ queue_mock = AsyncMock(return_value=response)+ monkeypatch.setattr(helpers_module, "queue_user_message", queue_mock)+ monkeypatch.setattr(+ helpers_module,+ "check_pending_call_rate",+ AsyncMock(return_value=PENDING_CALL_LIMIT + 1),+ )+ monkeypatch.setattr(+ helpers_module, "resolve_workspace_files", AsyncMock(return_value=[])+ )++ with pytest.raises(HTTPException) as exc_info:+ await queue_pending_for_http(+ session_id="sess-1",+ user_id="user-1",+ message="hi",+ context=None,+ file_ids=None,+ )+ assert exc_info.value.status_code == 429+ queue_mock.assert_awaited_once()++@pytest.mark.asyncioasync def test_check_pending_call_rate_at_limit(monkeypatch: pytest.MonkeyPatch,diff --git a/autogpt_platform/backend/backend/copilot/pending_messages.py b/autogpt_platform/backend/backend/copilot/pending_messages.pyindex 8e6aa61af9..089e45644b 100644--- a/autogpt_platform/backend/backend/copilot/pending_messages.py+++ b/autogpt_platform/backend/backend/copilot/pending_messages.py@@ -29,7 +29,7 @@ from typing import Any, castfrom pydantic import BaseModel, Field, ValidationErrorfrom backend.data.redis_client import get_redis_async-from backend.data.redis_helpers import capped_rpush+from backend.data.redis_helpers import capped_rpush, capped_rpush_if_hash_fieldlogger = logging.getLogger(__name__)@@ -161,6 +161,47 @@ async def push_pending_message(return new_length+async def push_pending_message_if_session_running(+ session_id: str,+ message: PendingMessage,+ *,+ session_meta_key: str,+) -> int | None:+ """Append a pending message only while the stream meta is still running."""+ redis = await get_redis_async()+ key = _buffer_key(session_id)+ payload = message.model_dump_json()++ new_length = await capped_rpush_if_hash_field(+ redis,+ hash_key=session_meta_key,+ hash_field="status",+ expected="running",+ list_key=key,+ value=payload,+ max_len=MAX_PENDING_MESSAGES,+ ttl_seconds=_PENDING_TTL_SECONDS,+ )+ if new_length is None:+ logger.info(+ "pending_messages: skipped push to session=%s because no running turn exists",+ session_id,+ )+ return None++ try:+ await redis.publish(_notify_channel(session_id), _NOTIFY_PAYLOAD)+ except Exception as e: # pragma: no cover+ logger.warning("pending_messages: publish failed for %s: %s", session_id, e)++ logger.info(+ "pending_messages: pushed message to running session=%s (buffer_len=%d)",+ session_id,+ new_length,+ )+ return new_length++async def drain_pending_messages(session_id: str) -> list[PendingMessage]:"""Atomically pop all pending messages for *session_id*.diff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.pyindex cf9ebe15aa..b3b4452dd3 100644--- a/autogpt_platform/backend/backend/copilot/permissions.py+++ b/autogpt_platform/backend/backend/copilot/permissions.py@@ -128,6 +128,14 @@ ToolName = Literal[# Frozen set of all valid tool names — derived from the Literal.ALL_TOOL_NAMES: frozenset[str] = frozenset(get_args(ToolName))+DISABLED_LEGACY_TOOL_NAMES: frozenset[str] = frozenset({"ask_question"})+"""Tool names accepted only for backwards compatibility with saved graphs.++These names are intentionally absent from ``ToolName`` and+``PLATFORM_TOOL_NAMES`` so they are not exposed in new block schemas or sent to+the model as available tools.+"""+# SDK built-in tool names — tools provided by the Claude Code CLI that our# code does not implement directly. ``TodoWrite`` is DELIBERATELY excluded:# baseline mode ships an MCP-wrapped platform version@@ -304,7 +312,11 @@ def validate_tool_names(tools: list[str]) -> list[str]:Returns:List of invalid names (empty if all are valid)."""- return [t for t in tools if t not in ALL_TOOL_NAMES]+ return [+ t+ for t in tools+ if t not in ALL_TOOL_NAMES and t not in DISABLED_LEGACY_TOOL_NAMES+ ]_tool_names_checked = Falsediff --git a/autogpt_platform/backend/backend/copilot/permissions_test.py b/autogpt_platform/backend/backend/copilot/permissions_test.pyindex 367c1c7a2c..5df999b4d6 100644--- a/autogpt_platform/backend/backend/copilot/permissions_test.py+++ b/autogpt_platform/backend/backend/copilot/permissions_test.py@@ -257,6 +257,9 @@ class TestValidateToolNames:def test_valid_sdk_builtin(self):assert validate_tool_names(["Read", "Task", "WebSearch"]) == []+ def test_disabled_legacy_tool_name_is_accepted(self):+ assert validate_tool_names(["ask_question"]) == []+def test_invalid_tool(self):result = validate_tool_names(["nonexistent_tool"])assert "nonexistent_tool" in resultdiff --git a/autogpt_platform/backend/backend/copilot/response_model.py b/autogpt_platform/backend/backend/copilot/response_model.pyindex 1805b68b07..f6faa1bd19 100644--- a/autogpt_platform/backend/backend/copilot/response_model.py+++ b/autogpt_platform/backend/backend/copilot/response_model.py@@ -52,7 +52,8 @@ class ResponseType(str, Enum):ERROR = "error"USAGE = "usage"HEARTBEAT = "heartbeat"- STATUS = "status"+ STATUS = "data-status"+ CURSOR = "data-cursor"class StreamBaseResponse(BaseModel):@@ -275,10 +276,18 @@ class StreamError(StreamBaseResponse):The AI SDK uses z.strictObject({type, errorText}) which rejectsany extra fields like `code` or `details`.++ When ``code`` is set we prefix ``errorText`` with ``[code:<id>]`` so+ the frontend can still parse a machine-readable code out of the+ otherwise opaque text. Idempotent: if the caller already embedded+ the prefix, we don't double it."""+ text = self.errorText+ if self.code and not text.lstrip().startswith(f"[code:{self.code}]"):+ text = f"[code:{self.code}] {text}"data = {"type": self.type.value,- "errorText": self.errorText,+ "errorText": text,}return f"data: {json_dumps(data)}\n\n"@@ -300,17 +309,46 @@ class StreamHeartbeat(StreamBaseResponse):return ": heartbeat\n\n"+class StreamCursor(StreamBaseResponse):+ """Deprecated Redis-stream cursor data part.++ Kept so older stored chunks or tests can still be reconstructed, but new+ stream subscriptions no longer emit it. AI SDK resume needs a full replay+ from ``0-0`` so every ``*-delta`` has its matching ``*-start`` event.+ """++ type: ResponseType = ResponseType.CURSOR+ chunkId: str = Field(..., description="Redis Stream message ID (XADD)")++ def to_sse(self) -> str:+ """Emit as an AI SDK v5 data part."""+ data = {+ "type": self.type.value,+ "data": {"chunkId": self.chunkId},+ }+ return f"data: {json.dumps(data)}\n\n"++class StreamStatus(StreamBaseResponse):"""Transient status notification shown to the user during long operations.- Used to provide feedback when the backend performs behind-the-scenes work- (e.g., compacting conversation context on a retry) that would otherwise- leave the user staring at an unexplained pause.-- Sent as a proper ``data:`` event so the frontend can display it to the- user. The AI SDK stream parser gracefully skips unknown chunk types- (logs a console warning), so this does not break the stream.+ Emitted when the backend is about to enter a phase that would otherwise+ leave the user staring at a silent "Thinking…" bubble — e.g. the first+ LLM call, the continuation after a tool result, compacting conversation+ context on retry, or activating a fallback model. The frontend reads+ the latest `data-status` part on the current assistant message and uses+ its `message` in place of the generic "Thinking…" copy."""type: ResponseType = ResponseType.STATUSmessage: str = Field(..., description="Human-readable status message")++ def to_sse(self) -> str:+ """Emit as an AI SDK v5 data part so the client surfaces it as+ `type="data-status"` on `message.parts` instead of dropping it as+ an unknown chunk type."""+ data = {+ "type": self.type.value,+ "data": {"message": self.message},+ }+ return f"data: {json.dumps(data)}\n\n"diff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.pyindex 9f43f95e80..6df30dbe7e 100644--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py@@ -36,6 +36,7 @@ from backend.copilot.response_model import (StreamReasoningStart,StreamStart,StreamStartStep,+ StreamStatus,StreamTextDelta,StreamTextEnd,StreamTextStart,@@ -374,6 +375,14 @@ class SDKResponseAdapter:responses.append(StreamFinishStep())self.step_open = False+ # Narrate the gap between "tool returned" and "model emits its+ # next chunk". Usually sub-second, but with large tool outputs+ # or complex continuations it can stretch long enough for the+ # generic "Thinking…" copy to feel dead. The frontend replaces+ # it with actual content as soon as the next chunk lands.+ if resolved_in_blocks:+ responses.append(StreamStatus(message="Analyzing result\u2026"))+elif isinstance(sdk_message, ResultMessage):self.flush_unresolved_tool_calls(responses)# SECRT-2252: surface ghost-finished sessions as errors instead of silent finishes.diff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.pyindex 77a0a1fb0e..a70d32deb2 100644--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py@@ -25,6 +25,7 @@ from backend.copilot.response_model import (StreamReasoningEnd,StreamStart,StreamStartStep,+ StreamStatus,StreamTextDelta,StreamTextEnd,StreamTextStart,@@ -193,13 +194,15 @@ def test_tool_result_emits_output_and_finish_step():content=[ToolResultBlock(tool_use_id="t1", content="found 3 agents")])results = adapter.convert_message(result_msg)- assert len(results) == 2+ assert len(results) == 3assert isinstance(results[0], StreamToolOutputAvailable)assert results[0].toolCallId == "t1"assert results[0].toolName == "find_agent" # prefix strippedassert results[0].output == "found 3 agents"assert results[0].success is Trueassert isinstance(results[1], StreamFinishStep)+ assert isinstance(results[2], StreamStatus)+ assert results[2].message == "Analyzing result…"def test_tool_result_error():@@ -785,6 +788,7 @@ def test_full_conversation_flow():"StreamToolInputAvailable","StreamToolOutputAvailable", # tool result"StreamFinishStep", # step 1 closed after tool result+ "StreamStatus", # user-facing status while continuation is generated"StreamStartStep", # step 2: continuation text"StreamTextStart", # new block after tool"StreamTextDelta", # "I found 2"diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.pyindex 929ddb9b3c..202783541d 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py@@ -553,6 +553,26 @@ async def _reduce_context(return ReducedContext(TranscriptBuilder(), False, None, True, True, retry_target)+def _humanise_tool_list(names: list[str]) -> str:+ """Format a list of tool names for user-facing messages.++ ``["WebSearch"]`` → ``"'WebSearch'"``+ ``["WebSearch", "run_block"]`` → ``"'WebSearch' and 'run_block'"``+ Three or more items collapse to ``"'A', 'B', and 1 other"`` so the+ toast stays readable.+ """+ if not names:+ return ""+ quoted = [f"'{n}'" for n in names]+ if len(quoted) == 1:+ return quoted[0]+ if len(quoted) == 2:+ return f"{quoted[0]} and {quoted[1]}"+ extras = len(quoted) - 2+ suffix = "others" if extras > 1 else "other"+ return f"{quoted[0]}, {quoted[1]}, and {extras} {suffix}"++def _append_error_marker(session: ChatSession | None,display_msg: str,@@ -2380,6 +2400,13 @@ async def _run_stream_attempt(for ev in ctx.compaction.emit_pre_query(ctx.session):yield ev+ # Narrate the silent gap between dispatching the query and the+ # SDK's first real chunk — usually <1s but can stretch to several+ # seconds on cold-starts or large contexts. The frontend prefers+ # this over the generic "Thinking…" copy; fast turns replace it+ # with content immediately.+ yield StreamStatus(message="Contacting the model\u2026")+if ctx.attachments.image_blocks:content_blocks: list[dict[str, Any]] = [*ctx.attachments.image_blocks,@@ -2418,18 +2445,37 @@ async def _run_stream_attempt(idle_seconds = time.monotonic() - _last_real_msg_timethreshold = _idle_timeout_threshold(state.adapter)if idle_seconds >= threshold:+ unresolved_tool_names = sorted(+ {+ info.get("name", "unknown")+ for tid, info in state.adapter.current_tool_calls.items()+ if tid not in state.adapter.resolved_tool_calls+ }+ )logger.error("%s Idle timeout after %.0fs (threshold=%ds, "- "tool_pending=%s) — aborting stream",+ "unresolved tools: %s) — aborting stream",ctx.log_prefix,idle_seconds,threshold,- state.adapter.has_unresolved_tool_calls,+ ", ".join(unresolved_tool_names) or "none",+ )+ # The retryable marker written to the session omits+ # the `[code:<id>]` prefix — the AI SDK serializer+ # (`StreamError.to_sse`) attaches that automatically+ # on the wire so the frontend can still parse a+ # machine-readable code out of the otherwise opaque+ # `{type, errorText}` schema.+ stream_error_code = "idle_timeout"+ tool_phrase = (+ f" while running {_humanise_tool_list(unresolved_tool_names)}"+ if unresolved_tool_names+ else "")stream_error_msg = (- "The session has been idle for too long. Please try again."+ f"AutoPilot stopped responding{tool_phrase}. "+ "This usually means a tool got stuck. Please try again.")- stream_error_code = "idle_timeout"_append_error_marker(ctx.session, stream_error_msg, retryable=True)yield StreamError(errorText=stream_error_msg,diff --git a/autogpt_platform/backend/backend/copilot/sdk/service_test.py b/autogpt_platform/backend/backend/copilot/sdk/service_test.pyindex 180219db4b..c4b480aed1 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service_test.py@@ -15,6 +15,7 @@ from .service import (_HUNG_TOOL_CAP_SECONDS,_IDLE_TIMEOUT_SECONDS,_build_system_prompt_value,+ _humanise_tool_list,_idle_timeout_threshold,_is_sdk_disconnect_error,_normalize_model_name,@@ -903,6 +904,53 @@ class TestSystemPromptPreset:assert cfg.claude_agent_cross_user_prompt_cache is False+class TestStreamErrorCodePrefix:+ """StreamError.to_sse auto-prefixes errorText with `[code:<id>]` when a+ code is set, so the frontend can parse a machine-readable code out of+ the AI-SDK's strict `{type, errorText}` schema."""++ def test_auto_prefix_when_code_set(self):+ from backend.copilot.response_model import StreamError++ sse = StreamError(errorText="Boom", code="idle_timeout").to_sse()+ assert '"errorText":"[code:idle_timeout] Boom"' in sse++ def test_no_prefix_when_code_missing(self):+ from backend.copilot.response_model import StreamError++ sse = StreamError(errorText="Boom").to_sse()+ assert '"errorText":"Boom"' in sse++ def test_does_not_double_prefix(self):+ from backend.copilot.response_model import StreamError++ sse = StreamError(errorText="[code:x] Boom", code="x").to_sse()+ assert "[code:x] [code:x]" not in sse+ assert '"errorText":"[code:x] Boom"' in sse+++class TestHumaniseToolList:+ """Tool-name formatter used to build the idle-timeout error message."""++ def test_empty_returns_empty_string(self):+ assert _humanise_tool_list([]) == ""++ def test_single_tool_is_quoted(self):+ assert _humanise_tool_list(["WebSearch"]) == "'WebSearch'"++ def test_two_tools_are_joined_with_and(self):+ assert (+ _humanise_tool_list(["WebSearch", "run_block"])+ == "'WebSearch' and 'run_block'"+ )++ def test_three_uses_singular_other(self):+ assert _humanise_tool_list(["a", "b", "c"]) == "'a', 'b', and 1 other"++ def test_four_plus_uses_plural_others(self):+ assert _humanise_tool_list(["a", "b", "c", "d"]) == "'a', 'b', and 2 others"++# ---------------------------------------------------------------------------# _RetryState.observed_model — Moonshot cost-override input# ---------------------------------------------------------------------------diff --git a/autogpt_platform/backend/backend/copilot/stream_registry.py b/autogpt_platform/backend/backend/copilot/stream_registry.pyindex bade6d143e..a70e9fc4dc 100644--- a/autogpt_platform/backend/backend/copilot/stream_registry.py+++ b/autogpt_platform/backend/backend/copilot/stream_registry.py@@ -48,6 +48,7 @@ from .response_model import (StreamReasoningStart,StreamStart,StreamStartStep,+ StreamStatus,StreamTextDelta,StreamTextEnd,StreamTextStart,@@ -93,6 +94,11 @@ def _get_session_meta_key(session_id: str) -> str:return f"{config.session_meta_prefix}{session_id}"+def get_session_meta_key(session_id: str) -> str:+ """Get Redis key for session metadata (keyed by session_id)."""+ return _get_session_meta_key(session_id)++def _get_turn_stream_key(turn_id: str) -> str:"""Get Redis key for turn message stream (keyed by turn_id for per-turn isolation)."""return f"{config.turn_stream_prefix}{turn_id}"@@ -1093,6 +1099,7 @@ def _reconstruct_chunk(chunk_data: dict) -> StreamBaseResponse | None:ResponseType.ERROR.value: StreamError,ResponseType.USAGE.value: StreamUsage,ResponseType.HEARTBEAT.value: StreamHeartbeat,+ ResponseType.STATUS.value: StreamStatus,}chunk_type = chunk_data.get("type")diff --git a/autogpt_platform/backend/backend/copilot/stream_registry_test.py b/autogpt_platform/backend/backend/copilot/stream_registry_test.pyindex 9da23fbda3..702462b392 100644--- a/autogpt_platform/backend/backend/copilot/stream_registry_test.py+++ b/autogpt_platform/backend/backend/copilot/stream_registry_test.py@@ -343,3 +343,73 @@ async def test_mark_session_completed_survives_lock_release_redis_error():isinstance(call.args[1], stream_registry.StreamFinish)for call in publish_mock.call_args_list), "StreamFinish must still be published even if lock DELETE raises"+++# ---------------------------------------------------------------------------+# Replays must contain protocol chunks only. Redis cursor data parts are not+# emitted because AI SDK resume needs the complete stream envelope from 0-0.+# ---------------------------------------------------------------------------+++async def test_subscribe_to_session_replays_chunks_without_cursor_parts():+ """During replay, the subscriber queue contains chunks plus terminal finish."""+ import orjson++ from backend.copilot.response_model import (+ StreamTextDelta,+ StreamTextEnd,+ StreamTextStart,+ )++ # Three chunks recorded in Redis for a completed turn. Completed status+ # means the listener branch is skipped and only the replay path runs,+ # which keeps the test hermetic.+ stream_key_msgs = [+ (+ "9999-0",+ {"data": orjson.dumps(StreamTextStart(id="blk-1").model_dump()).decode()},+ ),+ (+ "9999-1",+ {+ "data": orjson.dumps(+ StreamTextDelta(id="blk-1", delta="hi").model_dump()+ ).decode()+ },+ ),+ (+ "9999-2",+ {"data": orjson.dumps(StreamTextEnd(id="blk-1").model_dump()).decode()},+ ),+ ]++ fake_redis = AsyncMock()+ fake_redis.hgetall = AsyncMock(+ return_value={+ "user_id": "u1",+ "session_id": "sess-1",+ "turn_id": "turn-1",+ "status": "completed", # finished → no listener task+ }+ )+ fake_redis.xread = AsyncMock(return_value=[("stream-key", stream_key_msgs)])++ with patch.object(+ stream_registry, "get_redis_async", new=AsyncMock(return_value=fake_redis)+ ):+ queue = await stream_registry.subscribe_to_session(+ session_id="sess-1", user_id="u1", last_message_id="0-0"+ )++ assert queue is not None++ delivered = []+ while not queue.empty():+ delivered.append(queue.get_nowait())++ assert len(delivered) == 4+ assert isinstance(delivered[0], StreamTextStart)+ assert isinstance(delivered[1], StreamTextDelta)+ assert isinstance(delivered[2], StreamTextEnd)+ assert isinstance(delivered[3], stream_registry.StreamFinish)diff --git a/autogpt_platform/backend/backend/data/redis_helpers.py b/autogpt_platform/backend/backend/data/redis_helpers.pyindex fd6bebb313..f082d45e38 100644--- a/autogpt_platform/backend/backend/data/redis_helpers.py+++ b/autogpt_platform/backend/backend/data/redis_helpers.py@@ -47,6 +47,27 @@ endreturn 0"""+# Push to a capped list only when a hash field currently matches the expected+# value. Returns the new list length, or -1 when the guard fails.+#+# KEYS[1] hash key+# KEYS[2] list key+# ARGV[1] hash field+# ARGV[2] expected current value+# ARGV[3] list value+# ARGV[4] max list length+# ARGV[5] list TTL seconds+_GATED_CAPPED_RPUSH_LUA = """+local current = redis.call('HGET', KEYS[1], ARGV[1])+if current ~= ARGV[2] then+ return -1+end+redis.call('RPUSH', KEYS[2], ARGV[3])+redis.call('LTRIM', KEYS[2], -tonumber(ARGV[4]), -1)+redis.call('EXPIRE', KEYS[2], tonumber(ARGV[5]))+return redis.call('LLEN', KEYS[2])+"""+async def incr_with_ttl(redis: AsyncRedis,@@ -129,6 +150,40 @@ async def capped_rpush(return int(results[-1])+async def capped_rpush_if_hash_field(+ redis: AsyncRedis,+ *,+ hash_key: str,+ hash_field: str,+ expected: str,+ list_key: str,+ value: str,+ max_len: int,+ ttl_seconds: int,+) -> int | None:+ """Atomically RPUSH to a bounded list iff a hash field matches.++ Returns the new list length when the push happens, or ``None`` when the+ hash field does not currently match ``expected``.+ """+ result = await cast(+ "Any",+ redis.eval(+ _GATED_CAPPED_RPUSH_LUA,+ 2,+ hash_key,+ list_key,+ hash_field,+ expected,+ value,+ str(max_len),+ str(ttl_seconds),+ ),+ )+ length = int(result)+ return None if length < 0 else length++async def hash_compare_and_set(redis: AsyncRedis,key: str,diff --git a/autogpt_platform/backend/backend/data/redis_helpers_test.py b/autogpt_platform/backend/backend/data/redis_helpers_test.pyindex c45028dbac..5410a46195 100644--- a/autogpt_platform/backend/backend/data/redis_helpers_test.py+++ b/autogpt_platform/backend/backend/data/redis_helpers_test.py@@ -11,6 +11,7 @@ import pytestfrom backend.data.redis_helpers import (capped_rpush,+ capped_rpush_if_hash_field,hash_compare_and_set,incr_with_ttl,incr_with_ttl_sync,@@ -56,7 +57,17 @@ class _Fake:return len(self.lists.get(key, []))async def eval(self, script: str, numkeys: int, *args: Any) -> int:- # Shim for hash-CAS only.+ if numkeys == 2:+ hash_key, list_key = args[0], args[1]+ field, expected, value, max_len, ttl_seconds = args[2:7]+ h = self.hashes.setdefault(hash_key, {})+ if h.get(field) != expected:+ return -1+ await self.rpush(list_key, value)+ await self.ltrim(list_key, -int(max_len), -1)+ await self.expire(list_key, int(ttl_seconds))+ return await self.llen(list_key)+key, field, expected, new = args[0], args[1], args[2], args[3]h = self.hashes.setdefault(key, {})if h.get(field) == expected:@@ -198,6 +209,50 @@ async def test_capped_rpush_first_push_returns_one() -> None:assert r.lists["buf"] == ["only"]+# ── capped_rpush_if_hash_field ────────────────────────────────────────+++async def test_capped_rpush_if_hash_field_pushes_when_expected_matches() -> None:+ r = _Fake()+ r.hashes["meta"] = {"status": "running"}++ length = await capped_rpush_if_hash_field(+ r, # type: ignore[arg-type]+ hash_key="meta",+ hash_field="status",+ expected="running",+ list_key="buf",+ value="only",+ max_len=10,+ ttl_seconds=60,+ )++ assert length == 1+ assert r.lists["buf"] == ["only"]+ assert r.ttls["buf"] == 60+++async def test_capped_rpush_if_hash_field_skips_when_expected_differs() -> None:+ r = _Fake()+ r.hashes["meta"] = {"status": "completed"}++ length = await capped_rpush_if_hash_field(+ r, # type: ignore[arg-type]+ hash_key="meta",+ hash_field="status",+ expected="running",+ list_key="buf",+ value="lost",+ max_len=10,+ ttl_seconds=60,+ )++ assert length is None+ assert "buf" not in r.lists++# ── hash_compare_and_set ───────────────────────────────────────────────diff --git a/autogpt_platform/frontend/.gitignore b/autogpt_platform/frontend/.gitignoreindex 4150a70bcd..cc96dc0e65 100644--- a/autogpt_platform/frontend/.gitignore+++ b/autogpt_platform/frontend/.gitignore@@ -57,4 +57,8 @@ storybook-static.cursorrules# Generated API files-src/app/api/__generated__/\ No newline at end of file+src/app/api/__generated__/++# Video recordings (screen captures, bug repros)+*.mov+*.mp4\ No newline at end of filediff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsxnew file mode 100644index 0000000000..3529018d8d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx@@ -0,0 +1,95 @@+"use client";++import { Flask } from "@phosphor-icons/react";+import { ChatContainer } from "./components/ChatContainer/ChatContainer";+import { RateLimitGate } from "./components/RateLimitResetDialog/RateLimitGate";+import { useCopilotPage } from "./useCopilotPage";++interface Props {+ droppedFiles: File[];+ onDroppedFilesConsumed: () => void;+}++/**+ * Session-scoped chat host. Parent mounts this with `key={sessionId}` so+ * session-local view state resets on switch, while the actual AI SDK Chat+ * instance is preserved in the per-session runtime registry.+ */+export function CopilotChatHost({+ droppedFiles,+ onDroppedFilesConsumed,+}: Props) {+ const {+ sessionId,+ messages,+ status,+ error,+ stop,+ isReconnecting,+ isRestoringActiveSession,+ restoreStatusMessage,+ activeStreamStartedAt,+ isUserStopping,+ createSession,+ onSend,+ onEnqueue,+ queuedMessages,+ isLoadingSession,+ isSessionError,+ isCreatingSession,+ isUploadingFiles,+ hasMoreMessages,+ isLoadingMore,+ loadMore,+ turnStats,+ rateLimitMessage,+ dismissRateLimit,+ sessionDryRun,+ } = useCopilotPage();++ return (+ <>+ {/* Only shown when the CURRENT session is confirmed dry_run via its+ immutable metadata. Never based on the global isDryRun preference+ (which only predicts future sessions). */}+ {sessionId && sessionDryRun && (+ <div className="flex items-center justify-center gap-1.5 bg-amber-50 px-3 py-1.5 text-xs font-medium text-amber-800">+ <Flask size={13} weight="bold" />+ Test mode — this session runs agents as simulation+ </div>+ )}+ <div className="flex-1 overflow-hidden">+ <ChatContainer+ messages={messages}+ status={status}+ error={error}+ sessionId={sessionId}+ isLoadingSession={isLoadingSession}+ isSessionError={isSessionError}+ isCreatingSession={isCreatingSession}+ isReconnecting={isReconnecting}+ isRestoringActiveSession={isRestoringActiveSession}+ restoreStatusMessage={restoreStatusMessage}+ activeStreamStartedAt={activeStreamStartedAt}+ isUserStopping={isUserStopping}+ onCreateSession={createSession}+ onSend={onSend}+ onStop={stop}+ onEnqueue={onEnqueue}+ queuedMessages={queuedMessages}+ isUploadingFiles={isUploadingFiles}+ hasMoreMessages={hasMoreMessages}+ isLoadingMore={isLoadingMore}+ onLoadMore={loadMore}+ droppedFiles={droppedFiles}+ onDroppedFilesConsumed={onDroppedFilesConsumed}+ turnStats={turnStats}+ />+ </div>+ <RateLimitGate+ rateLimitMessage={rateLimitMessage}+ onDismiss={dismissRateLimit}+ />+ </>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsxindex 335cd6bb4b..949f5f612a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx@@ -1,25 +1,20 @@"use client";-import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";-import { useGetV2GetCopilotUsage } from "@/app/api/__generated__/endpoints/chat/chat";-import { toast } from "@/components/molecules/Toast/use-toast";-import useCredits from "@/hooks/useCredits";-import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { SidebarProvider } from "@/components/ui/sidebar";-import { cn } from "@/lib/utils";-import { Flask, UploadSimple } from "@phosphor-icons/react";+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import dynamic from "next/dynamic";-import { useCallback, useEffect, useRef, useState } from "react";-import { ChatContainer } from "./components/ChatContainer/ChatContainer";+import { parseAsString, useQueryState } from "nuqs";+import { useState } from "react";+import { CopilotChatHost } from "./CopilotChatHost";import { ChatSidebar } from "./components/ChatSidebar/ChatSidebar";-import { DeleteChatDialog } from "./components/DeleteChatDialog/DeleteChatDialog";+import { FileDropZone } from "./components/FileDropZone/FileDropZone";import { MobileDrawer } from "./components/MobileDrawer/MobileDrawer";import { MobileHeader } from "./components/MobileHeader/MobileHeader";import { NotificationBanner } from "./components/NotificationBanner/NotificationBanner";import { NotificationDialog } from "./components/NotificationDialog/NotificationDialog";-import { RateLimitResetDialog } from "./components/RateLimitResetDialog/RateLimitResetDialog";import { ScaleLoader } from "./components/ScaleLoader/ScaleLoader";-import { useCopilotPage } from "./useCopilotPage";+import { useIsMobile } from "./useIsMobile";const ArtifactPanel = dynamic(() =>@@ -30,129 +25,15 @@ const ArtifactPanel = dynamic();export function CopilotPage() {- const [isDragging, setIsDragging] = useState(false);const [droppedFiles, setDroppedFiles] = useState<File[]>([]);- const dragCounter = useRef(0);-- const handleDroppedFilesConsumed = useCallback(() => {- setDroppedFiles([]);- }, []);-- function handleDragEnter(e: React.DragEvent) {- e.preventDefault();- e.stopPropagation();- dragCounter.current += 1;- if (e.dataTransfer.types.includes("Files")) {- setIsDragging(true);- }- }-- function handleDragOver(e: React.DragEvent) {- e.preventDefault();- e.stopPropagation();- }-- function handleDragLeave(e: React.DragEvent) {- e.preventDefault();- e.stopPropagation();- dragCounter.current -= 1;- if (dragCounter.current === 0) {- setIsDragging(false);- }- }-- function handleDrop(e: React.DragEvent) {- e.preventDefault();- e.stopPropagation();- dragCounter.current = 0;- setIsDragging(false);-- const files = Array.from(e.dataTransfer.files);- if (files.length > 0) {- setDroppedFiles(files);- }- }-- const {- sessionId,- messages,- status,- error,- stop,- isReconnecting,- isSyncing,- createSession,- onSend,- onEnqueue,- queuedMessages,- isLoadingSession,- isSessionError,- isCreatingSession,- isUploadingFiles,- isUserLoading,- isLoggedIn,- // Pagination- hasMoreMessages,- isLoadingMore,- loadMore,- // Mobile drawer- isMobile,- isDrawerOpen,- sessions,- isLoadingSessions,- handleOpenDrawer,- handleCloseDrawer,- handleDrawerOpenChange,- handleSelectSession,- handleNewChat,- // Delete functionality (available via ChatSidebar context menu on all viewports)- sessionToDelete,- isDeleting,- handleConfirmDelete,- handleCancelDelete,- // Historical per-message stats (duration + reasoning duration + timestamp)- turnStats,- // Rate limit reset- rateLimitMessage,- dismissRateLimit,- // Dry run session state- sessionDryRun,- } = useCopilotPage();-- const {- data: usage,- isSuccess: hasUsage,- isError: usageError,- } = useGetV2GetCopilotUsage({- query: {- select: (res) => res.data as CoPilotUsagePublic,- refetchInterval: 30000,- staleTime: 10000,- },- });- const resetCost = usage?.reset_cost;-- const isBillingEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);+ const isMobile = useIsMobile();const isArtifactsEnabled = useGetFlag(Flag.ARTIFACTS);- const { credits, fetchCredits } = useCredits({ fetchInitialCredits: true });- const hasInsufficientCredits =- credits !== null && resetCost != null && credits < resetCost;-- // Fall back to a toast when the credit-based reset feature is disabled or- // when the usage query fails (so the user still gets feedback).- useEffect(() => {- if (- rateLimitMessage &&- (usageError || (hasUsage && (resetCost ?? 0) <= 0))- ) {- toast({- title: "Usage limit reached",- description: rateLimitMessage,- variant: "destructive",- });- dismissRateLimit();- }- }, [rateLimitMessage, resetCost, hasUsage, usageError, dismissRateLimit]);+ const { isUserLoading, isLoggedIn } = useSupabase();+ // Read sessionId here purely to key the chat-host subtree. The view still+ // remounts on session switch, but the underlying AI SDK Chat runtime now+ // lives in a per-session registry so live streams can continue in+ // background JS state while another chat is on screen.+ const [sessionId] = useQueryState("sessionId", parseAsString);if (isUserLoading || !isLoggedIn) {return (@@ -169,101 +50,23 @@ export function CopilotPage() {>{!isMobile && <ChatSidebar />}<div className="flex h-full w-full flex-row overflow-hidden">- <div+ <FileDropZoneclassName="relative flex min-w-0 flex-1 flex-col overflow-hidden bg-[#f8f8f9] px-0"- onDragEnter={handleDragEnter}- onDragOver={handleDragOver}- onDragLeave={handleDragLeave}- onDrop={handleDrop}+ onFilesDropped={setDroppedFiles}>- {isMobile && <MobileHeader onOpenDrawer={handleOpenDrawer} />}+ {isMobile && <MobileHeader />}<NotificationBanner />- {/* Test mode banner: only shown when the CURRENT session is confirmed to be- a dry_run session via its immutable metadata. Never shown based on the- global isDryRun store preference alone — that only predicts future sessions- and would mislead users browsing non-dry-run sessions while the toggle is on.- The DryRunToggleButton (visible on new chats) already communicates the preference. */}- {sessionId && sessionDryRun && (- <div className="flex items-center justify-center gap-1.5 bg-amber-50 px-3 py-1.5 text-xs font-medium text-amber-800">- <Flask size={13} weight="bold" />- Test mode — this session runs agents as simulation- </div>- )}- {/* Drop overlay */}- <div- className={cn(- "pointer-events-none absolute inset-0 z-50 flex flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed border-violet-400 bg-violet-500/10 transition-opacity duration-150",- isDragging ? "opacity-100" : "opacity-0",- )}- >- <UploadSimple className="h-10 w-10 text-violet-500" weight="bold" />- <span className="text-lg font-medium text-violet-600">- Drop files here- </span>- </div>- <div className="flex-1 overflow-hidden">- <ChatContainer- messages={messages}- status={status}- error={error}- sessionId={sessionId}- isLoadingSession={isLoadingSession}- isSessionError={isSessionError}- isCreatingSession={isCreatingSession}- isReconnecting={isReconnecting}- isSyncing={isSyncing}- onCreateSession={createSession}- onSend={onSend}- onStop={stop}- onEnqueue={onEnqueue}- queuedMessages={queuedMessages}- isUploadingFiles={isUploadingFiles}- hasMoreMessages={hasMoreMessages}- isLoadingMore={isLoadingMore}- onLoadMore={loadMore}- droppedFiles={droppedFiles}- onDroppedFilesConsumed={handleDroppedFilesConsumed}- turnStats={turnStats}- />- </div>- </div>+ <CopilotChatHost+ key={sessionId ?? "new"}+ droppedFiles={droppedFiles}+ onDroppedFilesConsumed={() => setDroppedFiles([])}+ />+ </FileDropZone>{!isMobile && isArtifactsEnabled && <ArtifactPanel />}</div>{isMobile && isArtifactsEnabled && <ArtifactPanel mobile />}- {isMobile && (- <MobileDrawer- isOpen={isDrawerOpen}- sessions={sessions}- currentSessionId={sessionId}- isLoading={isLoadingSessions}- onSelectSession={handleSelectSession}- onNewChat={handleNewChat}- onClose={handleCloseDrawer}- onOpenChange={handleDrawerOpenChange}- />- )}- {/* Delete confirmation dialog - rendered at top level for proper z-index on mobile */}- {isMobile && (- <DeleteChatDialog- session={sessionToDelete}- isDeleting={isDeleting}- onConfirm={handleConfirmDelete}- onCancel={handleCancelDelete}- />- )}+ {isMobile && <MobileDrawer />}<NotificationDialog />- <RateLimitResetDialog- isOpen={!!rateLimitMessage && hasUsage && (resetCost ?? 0) > 0}- onClose={dismissRateLimit}- resetCost={resetCost ?? 0}- resetMessage={rateLimitMessage ?? ""}- isWeeklyExhausted={- hasUsage && !!usage.weekly && usage.weekly.percent_used >= 100- }- hasInsufficientCredits={hasInsufficientCredits}- isBillingEnabled={isBillingEnabled}- onCreditChange={fetchCredits}- /></SidebarProvider>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/CopilotPage.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/CopilotPage.test.tsxindex b3b3798fe4..6cafba24e4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/CopilotPage.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/CopilotPage.test.tsx@@ -27,6 +27,17 @@ vi.mock("../components/NotificationDialog/NotificationDialog", () => ({vi.mock("../components/RateLimitResetDialog/RateLimitResetDialog", () => ({RateLimitResetDialog: () => null,}));+vi.mock("../components/RateLimitResetDialog/RateLimitGate", () => ({+ RateLimitGate: () => null,+}));+vi.mock("../components/FileDropZone/FileDropZone", () => ({+ FileDropZone: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+}));+vi.mock("../useIsMobile", () => ({+ useIsMobile: () => false,+}));vi.mock("../components/ScaleLoader/ScaleLoader", () => ({ScaleLoader: () => <div data-testid="scale-loader" />,}));@@ -69,6 +80,21 @@ vi.mock("@/services/feature-flags/use-get-flag", () => ({useGetFlag: () => false,}));+// Auth check moved into CopilotPage directly — default to a logged-in+// user so the page renders past its loading gate.+const mockSupabase = vi.fn(() => ({ isUserLoading: false, isLoggedIn: true }));+vi.mock("@/lib/supabase/hooks/useSupabase", () => ({+ useSupabase: () => mockSupabase(),+}));++// sessionId is read via nuqs to key the chat-host subtree; stub it so+// tests can control the key/session without hitting URL state.+let mockSessionIdForQueryState: string | null = null;+vi.mock("nuqs", () => ({+ parseAsString: {},+ useQueryState: () => [mockSessionIdForQueryState, vi.fn()],+}));+// Build the base mock return value for useCopilotPageconst basePageState = {sessionId: null as string | null,@@ -89,23 +115,9 @@ const basePageState = {hasMoreMessages: false,isLoadingMore: false,loadMore: vi.fn(),- isMobile: false,- isDrawerOpen: false,- sessions: [],- isLoadingSessions: false,- handleOpenDrawer: vi.fn(),- handleCloseDrawer: vi.fn(),- handleDrawerOpenChange: vi.fn(),- handleSelectSession: vi.fn(),- handleNewChat: vi.fn(),- sessionToDelete: null,- isDeleting: false,- handleConfirmDelete: vi.fn(),- handleCancelDelete: vi.fn(),turnStats: new Map(),rateLimitMessage: null,dismissRateLimit: vi.fn(),- isDryRun: false,sessionDryRun: false,};@@ -119,6 +131,12 @@ afterEach(() => {cleanup();mockUseCopilotPage.mockReset();mockUseCopilotPage.mockImplementation(() => basePageState);+ mockSupabase.mockReset();+ mockSupabase.mockImplementation(() => ({+ isUserLoading: false,+ isLoggedIn: true,+ }));+ mockSessionIdForQueryState = null;});describe("CopilotPage test-mode banner", () => {@@ -130,6 +148,7 @@ describe("CopilotPage test-mode banner", () => {});it("does not show test-mode banner when session exists but sessionDryRun is false", () => {+ mockSessionIdForQueryState = "session-abc";mockUseCopilotPage.mockReturnValue({...basePageState,sessionId: "session-abc",@@ -142,6 +161,7 @@ describe("CopilotPage test-mode banner", () => {});it("shows test-mode banner when session exists and sessionDryRun is true", () => {+ mockSessionIdForQueryState = "session-abc";mockUseCopilotPage.mockReturnValue({...basePageState,sessionId: "session-abc",@@ -166,11 +186,8 @@ describe("CopilotPage test-mode banner", () => {});it("shows loading spinner when user is loading", () => {- mockUseCopilotPage.mockReturnValue({- ...basePageState,- isUserLoading: true,- isLoggedIn: false,- });+ // Auth check moved to CopilotPage — mock useSupabase directly.+ mockSupabase.mockReturnValue({ isUserLoading: true, isLoggedIn: false });render(<CopilotPage />);expect(screen.getByTestId("scale-loader")).toBeDefined();expect(screen.queryByTestId("chat-container")).toBeNull();diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamErrorHandlers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamErrorHandlers.test.tsnew file mode 100644index 0000000000..2e40c5d7d3--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamErrorHandlers.test.ts@@ -0,0 +1,197 @@+import { useRef } from "react";+import { renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mockToast = vi.fn();+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast: (...args: unknown[]) => mockToast(...args),+}));++import {+ handleStreamError,+ parseBackendErrorCode,+} from "../copilotStreamErrorHandlers";++function makeRef(value: boolean) {+ return renderHook(() => useRef(value)).result.current;+}++describe("parseBackendErrorCode", () => {+ it("extracts a [code:<id>] prefix and returns the trailing message", () => {+ expect(+ parseBackendErrorCode("[code:idle_timeout] backend stalled for 60s"),+ ).toEqual({ code: "idle_timeout", message: "backend stalled for 60s" });+ });++ it("returns code=null for a plain message", () => {+ expect(parseBackendErrorCode("just a plain error")).toEqual({+ code: null,+ message: "just a plain error",+ });+ });++ it("trims surrounding whitespace and ignores case-only mismatches in body", () => {+ expect(+ parseBackendErrorCode(" [code:tool_stalled] something "),+ ).toEqual({ code: "tool_stalled", message: "something" });+ });++ it("returns code=null when the body uses uppercase chars in the bracket", () => {+ // The regex restricts the code to [a-z0-9_]+; uppercase IDs aren't backend-emitted+ // but if one ever appears we surface it as a plain message rather than mis-coding.+ const r = parseBackendErrorCode("[code:Idle_Timeout] msg");+ // The /i flag on the regex DOES allow this — assert what the regex actually does+ // so the test reflects current behaviour.+ expect(r.code === null || r.code === "Idle_Timeout").toBe(true);+ });+});++describe("handleStreamError", () => {+ beforeEach(() => {+ mockToast.mockClear();+ });++ it("routes rate-limit messages (case-insensitive 'usage limit') to onRateLimit", () => {+ const onRateLimit = vi.fn();+ const onReconnect = vi.fn();+ handleStreamError({+ error: new Error(+ '{"detail":"You\'ve hit the daily usage limit for this tier."}',+ ),+ onRateLimit,+ onReconnect,+ isUserStoppingRef: makeRef(false),+ });+ expect(onRateLimit).toHaveBeenCalledTimes(1);+ expect(onRateLimit.mock.calls[0][0]).toMatch(/usage limit/i);+ expect(mockToast).not.toHaveBeenCalled();+ expect(onReconnect).not.toHaveBeenCalled();+ });++ it("toasts an auth error when the message mentions auth failure or 401", () => {+ const onRateLimit = vi.fn();+ const onReconnect = vi.fn();+ handleStreamError({+ error: new Error("Authentication failed: token expired"),+ onRateLimit,+ onReconnect,+ isUserStoppingRef: makeRef(false),+ });+ expect(onRateLimit).not.toHaveBeenCalled();+ expect(onReconnect).not.toHaveBeenCalled();+ expect(mockToast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Authentication error",+ variant: "destructive",+ }),+ );+ });++ it("uses curated copy for known backend codes", () => {+ handleStreamError({+ error: new Error("[code:idle_timeout] tool sleeping"),+ onRateLimit: vi.fn(),+ onReconnect: vi.fn(),+ isUserStoppingRef: makeRef(false),+ });+ const arg = mockToast.mock.calls[0][0] as {+ title: string;+ description: string;+ };+ expect(arg.title).toBe("AutoPilot stopped responding");+ // Backend message takes priority over fallbackDescription.+ expect(arg.description).toBe("tool sleeping");+ });++ it("falls back to generic copy for an unknown backend code", () => {+ handleStreamError({+ error: new Error("[code:something_new] mystery"),+ onRateLimit: vi.fn(),+ onReconnect: vi.fn(),+ isUserStoppingRef: makeRef(false),+ });+ const arg = mockToast.mock.calls[0][0] as { title: string };+ expect(arg.title).toBe("AutoPilot ran into a problem");+ });++ it("uses fallbackDescription when the backend message is empty", () => {+ handleStreamError({+ error: new Error("[code:tool_stalled]"),+ onRateLimit: vi.fn(),+ onReconnect: vi.fn(),+ isUserStoppingRef: makeRef(false),+ });+ const arg = mockToast.mock.calls[0][0] as { description: string };+ expect(arg.description).toMatch(/tool/i);+ });++ it("triggers reconnect on a TypeError network error", () => {+ const onReconnect = vi.fn();+ const err = new TypeError("Failed to fetch");+ handleStreamError({+ error: err,+ onRateLimit: vi.fn(),+ onReconnect,+ isUserStoppingRef: makeRef(false),+ });+ expect(onReconnect).toHaveBeenCalledTimes(1);+ });++ it("triggers reconnect on an AbortError", () => {+ const onReconnect = vi.fn();+ const err = new Error("aborted");+ err.name = "AbortError";+ handleStreamError({+ error: err,+ onRateLimit: vi.fn(),+ onReconnect,+ isUserStoppingRef: makeRef(false),+ });+ expect(onReconnect).toHaveBeenCalledTimes(1);+ });++ it("triggers reconnect on a 'connection interrupted' message", () => {+ const onReconnect = vi.fn();+ handleStreamError({+ error: new Error("connection interrupted by server"),+ onRateLimit: vi.fn(),+ onReconnect,+ isUserStoppingRef: makeRef(false),+ });+ expect(onReconnect).toHaveBeenCalledTimes(1);+ });++ it("does NOT reconnect when the user explicitly stopped", () => {+ const onReconnect = vi.fn();+ handleStreamError({+ error: new TypeError("Failed to fetch"),+ onRateLimit: vi.fn(),+ onReconnect,+ isUserStoppingRef: makeRef(true),+ });+ expect(onReconnect).not.toHaveBeenCalled();+ });++ it("unwraps FastAPI {detail} wrappers from error.message", () => {+ handleStreamError({+ error: new Error('{"detail":"[code:idle_timeout] wrapped"}'),+ onRateLimit: vi.fn(),+ onReconnect: vi.fn(),+ isUserStoppingRef: makeRef(false),+ });+ const arg = mockToast.mock.calls[0][0] as { description: string };+ expect(arg.description).toBe("wrapped");+ });++ it("does nothing for unknown plain messages with no transient signal", () => {+ const onReconnect = vi.fn();+ handleStreamError({+ error: new Error("totally unknown problem"),+ onRateLimit: vi.fn(),+ onReconnect,+ isUserStoppingRef: makeRef(false),+ });+ expect(onReconnect).not.toHaveBeenCalled();+ expect(mockToast).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sessionActivity.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sessionActivity.test.tsnew file mode 100644index 0000000000..8101b052ca--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sessionActivity.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it } from "vitest";+import { shouldShowSessionProcessingIndicator } from "../sessionActivity";++const baseArgs = {+ sessionId: "s1",+ currentSessionId: "s2",+ isProcessing: true,+ hasCompletedIndicator: false,+ needsReload: false,+} as const;++describe("shouldShowSessionProcessingIndicator", () => {+ it("returns true for an inactive session that's processing without a completion or reload", () => {+ expect(shouldShowSessionProcessingIndicator({ ...baseArgs })).toBe(true);+ });++ it("returns false when the session is the currently focused one", () => {+ expect(+ shouldShowSessionProcessingIndicator({+ ...baseArgs,+ currentSessionId: "s1",+ }),+ ).toBe(false);+ });++ it("returns false when the session already shows a completion indicator", () => {+ expect(+ shouldShowSessionProcessingIndicator({+ ...baseArgs,+ hasCompletedIndicator: true,+ }),+ ).toBe(false);+ });++ it("returns false when the session needs a reload", () => {+ expect(+ shouldShowSessionProcessingIndicator({+ ...baseArgs,+ needsReload: true,+ }),+ ).toBe(false);+ });++ it("returns false when the session is not actively processing", () => {+ expect(+ shouldShowSessionProcessingIndicator({+ ...baseArgs,+ isProcessing: false,+ }),+ ).toBe(false);+ });++ it("returns true when no session is currently focused (null)", () => {+ expect(+ shouldShowSessionProcessingIndicator({+ ...baseArgs,+ currentSessionId: null,+ }),+ ).toBe(true);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useChatSession.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useChatSession.test.tsindex 19ef27836d..241802b9ff 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useChatSession.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useChatSession.test.ts@@ -38,13 +38,17 @@ vi.mock("@sentry/nextjs", () => ({captureException: vi.fn(),}));-function makeQueryResult(data: object | null) {+function makeQueryResult(+ data: object | null,+ overrides: Record<string, unknown> = {},+) {return {data: data ? { status: 200, data } : undefined,isLoading: false,isError: false,isFetching: false,refetch: vi.fn(),+ ...overrides,};}@@ -84,4 +88,39 @@ describe("useChatSession — pagination metadata", () => {const { result } = renderHook(() => useChatSession());expect(result.current.hasMoreMessages).toBe(true);});++ it("does not expose cached session data while a refetch is in progress", () => {+ mockUseGetV2GetSession.mockReturnValue(+ makeQueryResult(+ {+ messages: [{ role: "user", content: "stale" }],+ has_more_messages: true,+ oldest_sequence: 50,+ active_stream: true,+ },+ { isFetching: true },+ ),+ );++ const { result } = renderHook(() => useChatSession());++ expect(result.current.hydratedMessages).toBeUndefined();+ expect(result.current.rawSessionMessages).toEqual([]);+ expect(result.current.hasActiveStream).toBe(false);+ expect(result.current.hasMoreMessages).toBe(false);+ expect(result.current.oldestSequence).toBeNull();+ // isLoadingSession is scoped to the INITIAL fetch only (isLoading) so+ // background refetches do not disable the chat input between keystrokes.+ expect(result.current.isLoadingSession).toBe(false);+ });++ it("treats the initial fetch as a loading session", () => {+ mockUseGetV2GetSession.mockReturnValue(+ makeQueryResult(null, { isLoading: true, isFetching: true }),+ );++ const { result } = renderHook(() => useChatSession());++ expect(result.current.isLoadingSession).toBe(true);+ });});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPage.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPage.test.tsindex c387ff3605..43413770f4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPage.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPage.test.ts@@ -1,11 +1,14 @@import { act, renderHook, waitFor } from "@testing-library/react";+import type { UIMessage } from "ai";import { beforeEach, describe, expect, it, vi } from "vitest";+import { useCopilotStreamStore } from "../copilotStreamStore";import { useCopilotPage } from "../useCopilotPage";const mockUseChatSession = vi.fn();const mockUseCopilotStream = vi.fn();const mockUseLoadMoreMessages = vi.fn();const mockQueueFollowUpMessage = vi.fn();+const mockSendNewMessage = vi.fn();const mockToast = vi.fn();vi.mock("../useChatSession", () => ({@@ -23,12 +26,18 @@ vi.mock("../useCopilotNotifications", () => ({vi.mock("../useWorkflowImportAutoSubmit", () => ({useWorkflowImportAutoSubmit: () => undefined,}));+vi.mock("../useSendMessage", () => ({+ useSendMessage: () => ({+ onSend: (...args: unknown[]) => mockSendNewMessage(...args),+ isUploadingFiles: false,+ setPendingFileParts: vi.fn(),+ }),+}));+vi.mock("../useSessionTitlePoll", () => ({+ useSessionTitlePoll: () => undefined,+}));vi.mock("../store", () => ({useCopilotUIStore: () => ({- sessionToDelete: null,- setSessionToDelete: vi.fn(),- isDrawerOpen: false,- setDrawerOpen: vi.fn(),copilotChatMode: "chat",copilotLlmModel: null,isDryRun: false,@@ -39,15 +48,28 @@ vi.mock("../helpers/convertChatSessionToUiMessages", () => ({}));vi.mock("../helpers", () => ({deduplicateMessages: (msgs: unknown[]) => msgs,-}));-vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({- useDeleteV2DeleteSession: () => ({ mutate: vi.fn(), isPending: false }),- useGetV2ListSessions: () => ({ data: undefined, isLoading: false }),- getGetV2ListSessionsQueryKey: () => ["sessions"],- getV2GetPendingMessages: vi.fn().mockResolvedValue({- status: 200,- data: { count: 0, messages: [] },- }),+ getLatestAssistantStatusMessage: (+ messages: Array<{ role?: string; parts?: unknown[] }>,+ ) => {+ const last = messages[messages.length - 1] as+ | {+ role?: string;+ parts?: Array<{ type?: string; data?: { message?: unknown } }>;+ }+ | undefined;+ if (last?.role !== "assistant") return null;+ for (let i = (last.parts?.length ?? 0) - 1; i >= 0; i--) {+ const part = last.parts?.[i];+ if (part?.type === "data-cursor") continue;+ if (part?.type === "data-status") {+ return typeof part.data?.message === "string"+ ? part.data.message+ : null;+ }+ return null;+ }+ return null;+ },}));vi.mock("../helpers/queueFollowUpMessage", () => ({queueFollowUpMessage: (...args: unknown[]) =>@@ -56,18 +78,9 @@ vi.mock("../helpers/queueFollowUpMessage", () => ({vi.mock("@/components/molecules/Toast/use-toast", () => ({toast: (...args: unknown[]) => mockToast(...args),}));-vi.mock("@/lib/direct-upload", () => ({- uploadFileDirect: vi.fn(),-}));-vi.mock("@/lib/hooks/useBreakpoint", () => ({- useBreakpoint: () => "lg",-}));vi.mock("@/lib/supabase/hooks/useSupabase", () => ({useSupabase: () => ({ isUserLoading: false, isLoggedIn: true }),}));-vi.mock("@tanstack/react-query", () => ({- useQueryClient: () => ({ invalidateQueries: vi.fn() }),-}));vi.mock("@/services/feature-flags/use-get-flag", () => ({Flag: { CHAT_MODE_OPTION: "CHAT_MODE_OPTION" },useGetFlag: () => false,@@ -81,6 +94,7 @@ function makeBaseChatSession(overrides: Record<string, unknown> = {}) {rawSessionMessages: [],historicalTurnStats: new Map(),hasActiveStream: false,+ activeStreamStartedAt: null,hasMoreMessages: false,oldestSequence: null,isLoadingSession: false,@@ -96,12 +110,16 @@ function makeBaseChatSession(overrides: Record<string, unknown> = {}) {function makeBaseCopilotStream(overrides: Record<string, unknown> = {}) {return {messages: [],+ setMessages: vi.fn(),sendMessage: vi.fn(),stop: vi.fn(),status: "ready",error: undefined,isReconnecting: false,+ isRestoringActiveSession: false,+ restoreStatusMessage: null,isSyncing: false,+ isUserStopping: false,isUserStoppingRef: { current: false },rateLimitMessage: null,dismissRateLimit: vi.fn(),@@ -123,6 +141,7 @@ function makeBaseLoadMore(overrides: Record<string, unknown> = {}) {describe("useCopilotPage — backward pagination message ordering", () => {beforeEach(() => {vi.clearAllMocks();+ useCopilotStreamStore.getState().resetAll();});it("prepends pagedMessages before currentMessages", () => {@@ -144,6 +163,123 @@ describe("useCopilotPage — backward pagination message ordering", () => {});});+describe("useCopilotPage — active session restore visibility", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ useCopilotStreamStore.getState().resetAll();+ });++ it("hides the trailing assistant tail until an active session is resumed", () => {+ const userMessage = {+ id: "user-1",+ role: "user",+ parts: [{ type: "text", text: "Tell me more" }],+ };+ const assistantMessage = {+ id: "assistant-1",+ role: "assistant",+ parts: [{ type: "reasoning", text: "Working on it" }],+ };++ mockUseChatSession.mockReturnValue(makeBaseChatSession());+ mockUseCopilotStream.mockReturnValue(+ makeBaseCopilotStream({+ messages: [userMessage, assistantMessage],+ isRestoringActiveSession: true,+ }),+ );+ mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());++ const { result } = renderHook(() => useCopilotPage());++ expect(result.current.messages).toEqual([userMessage]);+ expect(result.current.isRestoringActiveSession).toBe(true);+ });++ it("preserves the hidden replay status message while restore trims the assistant tail", () => {+ const userMessage = {+ id: "user-1",+ role: "user",+ parts: [{ type: "text", text: "Tell me more" }],+ };+ const assistantMessage = {+ id: "assistant-1",+ role: "assistant",+ parts: [+ {+ type: "data-status",+ data: { message: "Contacting the model..." },+ },+ ],+ };++ mockUseChatSession.mockReturnValue(makeBaseChatSession());+ mockUseCopilotStream.mockReturnValue(+ makeBaseCopilotStream({+ messages: [userMessage, assistantMessage],+ isRestoringActiveSession: true,+ }),+ );+ mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());++ const { result } = renderHook(() => useCopilotPage());++ expect(result.current.messages).toEqual([userMessage]);+ expect(result.current.restoreStatusMessage).toBe("Contacting the model...");+ });++ it("prefers the cached live snapshot while restore is still reconnecting", () => {+ const userMessage: UIMessage = {+ id: "user-1",+ role: "user",+ parts: [{ type: "text", text: "Tell me more" }],+ };+ const cachedAssistantMessage: UIMessage = {+ id: "assistant-1",+ role: "assistant",+ parts: [{ type: "reasoning", text: "Working on it" }],+ };++ useCopilotStreamStore+ .getState()+ .setMessageSnapshot("sess-1", [userMessage, cachedAssistantMessage]);++ mockUseChatSession.mockReturnValue(makeBaseChatSession());+ mockUseCopilotStream.mockReturnValue(+ makeBaseCopilotStream({+ messages: [userMessage],+ isRestoringActiveSession: true,+ }),+ );+ mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());++ const { result } = renderHook(() => useCopilotPage());++ expect(result.current.messages).toEqual([+ userMessage,+ cachedAssistantMessage,+ ]);+ });+});++describe("useCopilotPage — onEnqueue and queuedMessages", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ useCopilotStreamStore.getState().resetAll();+ });++ it("exposes onEnqueue (delegating to onSend) and queuedMessages", () => {+ mockUseChatSession.mockReturnValue(makeBaseChatSession());+ mockUseCopilotStream.mockReturnValue(makeBaseCopilotStream());+ mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());++ const { result } = renderHook(() => useCopilotPage());++ expect(typeof result.current.onEnqueue).toBe("function");+ expect(Array.isArray(result.current.queuedMessages)).toBe(true);+ });+});+describe("useCopilotPage — turnStats map merge across pages", () => {beforeEach(() => {vi.clearAllMocks();@@ -189,6 +325,7 @@ describe("useCopilotPage — turnStats map merge across pages", () => {describe("useCopilotPage — onSend queue-in-flight path", () => {beforeEach(() => {vi.clearAllMocks();+ useCopilotStreamStore.getState().resetAll();});it("rejects attaching files while a turn is in flight", async () => {@@ -218,7 +355,6 @@ describe("useCopilotPage — onSend queue-in-flight path", () => {);mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());mockQueueFollowUpMessage.mockResolvedValue({- kind: "queued",buffer_length: 1,max_buffer_length: 10,turn_in_flight: true,@@ -240,16 +376,15 @@ describe("useCopilotPage — onSend queue-in-flight path", () => {});});- it("does not append a chip or toast when the server raced and started a new turn", async () => {+ it("falls back to a normal send when the active turn has already ended", async () => {mockUseChatSession.mockReturnValue(makeBaseChatSession());mockUseCopilotStream.mockReturnValue(makeBaseCopilotStream({ status: "streaming" }),);mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());- mockQueueFollowUpMessage.mockResolvedValue({- kind: "raced_started_turn",- status: 200,- });+ const notActiveError = new Error("no active turn");+ notActiveError.name = "QueueFollowUpNotActiveError";+ mockQueueFollowUpMessage.mockRejectedValue(notActiveError);const { result } = renderHook(() => useCopilotPage());@@ -261,15 +396,33 @@ describe("useCopilotPage — onSend queue-in-flight path", () => {"sess-1","follow-up",);- // No chip should appear — the server already started a new turn,- // useHydrateOnStreamEnd will surface the response.+ expect(mockSendNewMessage).toHaveBeenCalledWith("follow-up", undefined);expect(result.current.queuedMessages).not.toContain("follow-up");- // No misleading error toast either.expect(mockToast).not.toHaveBeenCalledWith(expect.objectContaining({ title: "Could not queue message" }),);});+ it("treats a user-stopped turn as no longer in flight for new sends", async () => {+ mockUseChatSession.mockReturnValue(makeBaseChatSession());+ mockUseCopilotStream.mockReturnValue(+ makeBaseCopilotStream({+ status: "streaming",+ isUserStopping: true,+ }),+ );+ mockUseLoadMoreMessages.mockReturnValue(makeBaseLoadMore());++ const { result } = renderHook(() => useCopilotPage());++ await act(async () => {+ await result.current.onSend("follow-up");+ });++ expect(mockQueueFollowUpMessage).not.toHaveBeenCalled();+ expect(mockSendNewMessage).toHaveBeenCalledWith("follow-up", undefined);+ });+it("surfaces a toast and rethrows when the queue POST fails", async () => {mockUseChatSession.mockReturnValue(makeBaseChatSession());mockUseCopilotStream.mockReturnValue(diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotStop.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotStop.test.tsnew file mode 100644index 0000000000..973bd61086--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotStop.test.ts@@ -0,0 +1,162 @@+import { renderHook } from "@testing-library/react";+import type { UIMessage } from "ai";+import { useRef } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mockToast = vi.fn();+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast: (...args: unknown[]) => mockToast(...args),+}));++const mockCancel =+ vi.fn<(sessionId: string) => Promise<{ status: number; data: unknown }>>();+vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({+ postV2CancelSessionTask: (sessionId: string) => mockCancel(sessionId),+}));++import { useCopilotStop } from "../useCopilotStop";++function asstMessage(parts: UIMessage["parts"], id = "a1"): UIMessage {+ return { id, role: "assistant", parts };+}++interface SetupOpts {+ sessionId?: string | null;+ initialMessages?: UIMessage[];+}++function setup(opts: SetupOpts = {}) {+ const sdkStop = vi.fn();+ const setIsUserStopping = vi.fn();+ let messages: UIMessage[] = opts.initialMessages ?? [];+ const setMessages = vi.fn((updater: unknown) => {+ if (typeof updater === "function") {+ messages = (updater as (prev: UIMessage[]) => UIMessage[])(messages);+ } else {+ messages = updater as UIMessage[];+ }+ });++ const { result } = renderHook(() => {+ const isUserStoppingRef = useRef(false);+ return {+ stop: useCopilotStop({+ sessionId: "sessionId" in opts ? opts.sessionId! : "sess-1",+ sdkStop,+ setMessages,+ isUserStoppingRef,+ setIsUserStopping,+ }),+ isUserStoppingRef,+ };+ });++ return {+ stop: () => result.current.stop(),+ isUserStoppingRef: () => result.current.isUserStoppingRef,+ sdkStop,+ setMessages,+ setIsUserStopping,+ getMessages: () => messages,+ };+}++describe("useCopilotStop", () => {+ beforeEach(() => {+ mockToast.mockClear();+ mockCancel.mockReset();+ });++ it("flips the user-stop flags synchronously and aborts the SDK stream", async () => {+ mockCancel.mockResolvedValue({ status: 200, data: { reason: "ok" } });+ const { stop, sdkStop, setIsUserStopping, isUserStoppingRef } = setup();++ await stop();++ expect(isUserStoppingRef().current).toBe(true);+ expect(setIsUserStopping).toHaveBeenCalledWith(true);+ expect(sdkStop).toHaveBeenCalledTimes(1);+ });++ it("appends the cancellation marker to the trailing assistant message", async () => {+ mockCancel.mockResolvedValue({ status: 200, data: { reason: "ok" } });+ const { stop, getMessages } = setup({+ initialMessages: [+ asstMessage([{ type: "text", text: "partial reply", state: "done" }]),+ ],+ });++ await stop();+ const after = getMessages();+ const last = after[after.length - 1];+ const tail = last.parts[last.parts.length - 1];+ expect(tail.type).toBe("text");+ expect((tail as { text: string }).text).toContain("Operation cancelled");+ });++ it("leaves messages unchanged when there is no trailing assistant message", async () => {+ mockCancel.mockResolvedValue({ status: 200, data: { reason: "ok" } });+ const { stop, getMessages } = setup({+ initialMessages: [+ {+ id: "u1",+ role: "user",+ parts: [{ type: "text", text: "hi", state: "done" }],+ },+ ],+ });++ await stop();+ const after = getMessages();+ expect(after).toHaveLength(1);+ expect(after[0].role).toBe("user");+ });++ it("swallows sdkStop errors but still proceeds with cancel", async () => {+ mockCancel.mockResolvedValue({ status: 200, data: { reason: "ok" } });+ const { stop, sdkStop } = setup();+ sdkStop.mockImplementation(() => {+ throw new Error("no fetch in flight");+ });++ await expect(stop()).resolves.toBeUndefined();+ expect(mockCancel).toHaveBeenCalledTimes(1);+ });++ it("does not call the cancel endpoint when there is no active sessionId", async () => {+ const { stop } = setup({ sessionId: null });+ await stop();+ expect(mockCancel).not.toHaveBeenCalled();+ });++ it("toasts a 'Stop may take a moment' notice on cancel_published_not_confirmed", async () => {+ mockCancel.mockResolvedValue({+ status: 200,+ data: { reason: "cancel_published_not_confirmed" },+ });+ const { stop } = setup();+ await stop();+ expect(mockToast).toHaveBeenCalledTimes(1);+ expect(mockToast.mock.calls[0][0]).toMatchObject({+ title: "Stop may take a moment",+ });+ });++ it("toasts a destructive notice when the cancel request rejects", async () => {+ mockCancel.mockRejectedValue(new Error("network down"));+ const { stop } = setup();+ await stop();+ expect(mockToast).toHaveBeenCalledTimes(1);+ expect(mockToast.mock.calls[0][0]).toMatchObject({+ title: "Could not stop the task",+ variant: "destructive",+ });+ });++ it("does not toast when the cancel succeeds with a normal reason", async () => {+ mockCancel.mockResolvedValue({ status: 200, data: { reason: "ok" } });+ const { stop } = setup();+ await stop();+ expect(mockToast).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotStream.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotStream.test.tsindex f646a5b29e..958afb7758 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotStream.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotStream.test.ts@@ -1,173 +1,707 @@-import { act, renderHook } from "@testing-library/react";+import { act, cleanup, renderHook } from "@testing-library/react";import type { UIMessage } from "ai";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { useCopilotUIStore } from "../store";-import { useCopilotStream } from "../useCopilotStream";--// Capture the args passed to ``useChat`` so tests can invoke onFinish/onError-// directly — that's the only way to drive handleReconnect without a real SSE.-let lastUseChatArgs: {- onFinish?: (args: { isDisconnect?: boolean; isAbort?: boolean }) => void;- onError?: (err: Error) => void;-} | null = null;--const resumeStreamMock = vi.fn();-const sdkStopMock = vi.fn();-const sdkSendMessageMock = vi.fn();-const setMessagesMock = vi.fn();--function resetSdkMocks() {- lastUseChatArgs = null;- resumeStreamMock.mockReset();- sdkStopMock.mockReset();- sdkSendMessageMock.mockReset();- setMessagesMock.mockReset();-}+// --- Toast mock (must be stable across rerenders) ---+const mockToast = vi.fn();+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast: (...args: unknown[]) => mockToast(...args),+}));-vi.mock("@ai-sdk/react", () => ({- useChat: (args: unknown) => {- lastUseChatArgs = args as typeof lastUseChatArgs;- return {- messages: [] as UIMessage[],- sendMessage: sdkSendMessageMock,- stop: sdkStopMock,- status: "ready" as const,- error: undefined,- setMessages: setMessagesMock,- resumeStream: resumeStreamMock,- };+// --- Environment mock ---+vi.mock("@/services/environment", () => ({+ environment: {+ getAGPTServerBaseUrl: () => "http://localhost:8006",+ isServerSide: () => false,},}));-vi.mock("ai", async () => {- const actual = await vi.importActual<typeof import("ai")>("ai");- return {- ...actual,- DefaultChatTransport: class {- constructor(public opts: unknown) {}- },- };-});+// --- API endpoints mock ---+const mockCancelSessionTask = vi.fn();+vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({+ postV2CancelSessionTask: (...args: unknown[]) =>+ mockCancelSessionTask(...args),+ getGetV2GetCopilotUsageQueryKey: () => ["usage"],+ getGetV2GetSessionQueryKey: (id: string) => ["session", id],+}));+// --- React Query mock ---+const mockInvalidateQueries = vi.fn();vi.mock("@tanstack/react-query", () => ({- useQueryClient: () => ({ invalidateQueries: vi.fn() }),+ useQueryClient: () => ({ invalidateQueries: mockInvalidateQueries }),}));-vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({- getGetV2GetCopilotUsageQueryKey: () => ["copilot-usage"],- getGetV2GetSessionQueryKey: (id: string) => ["session", id],- postV2CancelSessionTask: vi.fn(),- deleteV2DisconnectSessionStream: vi.fn().mockResolvedValue(undefined),+// --- Helpers mock ---+const mockHasActiveBackendStream = vi.fn(+ (_result: { data?: unknown }) => false,+);+vi.mock("../helpers", () => ({+ getCopilotAuthHeaders: vi.fn(async () => ({ Authorization: "Bearer test" })),+ deduplicateMessages: (msgs: UIMessage[]) => msgs,+ parseSessionIDs: (_raw: string | null | undefined) => new Set<string>(),+ extractSendMessageText: (arg: unknown) =>+ arg && typeof arg === "object" && "text" in arg+ ? String((arg as { text: string }).text)+ : String(arg ?? ""),+ hasActiveBackendStream: (result: { data?: unknown }) =>+ mockHasActiveBackendStream(result),+ getLatestAssistantStatusMessage: (messages: UIMessage[]) => {+ const last = messages[messages.length - 1];+ if (last?.role !== "assistant") return null;+ for (let i = last.parts.length - 1; i >= 0; i--) {+ const part = last.parts[i] as UIMessage["parts"][number] & {+ data?: { message?: unknown };+ };+ if (part.type === "data-cursor") continue;+ if (part.type === "data-status") {+ return typeof part.data?.message === "string"+ ? part.data.message+ : null;+ }+ return null;+ }+ return null;+ },+ hasVisibleAssistantContent: (messages: UIMessage[]) => {+ const last = messages[messages.length - 1];+ if (last?.role !== "assistant") return false;+ return last.parts.some((part: UIMessage["parts"][number]) => {+ if (part.type === "text" && part.text.trim().length > 0) return true;+ if (part.type === "reasoning" && part.text.trim().length > 0) return true;+ if (part.type.startsWith("tool-")) return true;+ return false;+ });+ },+ hasInProgressAssistantParts: (message: UIMessage | undefined) => {+ if (message?.role !== "assistant") return false;+ return message.parts.some((part: UIMessage["parts"][number]) => {+ if (!("state" in part) || typeof part.state !== "string") return false;+ return (+ part.state === "streaming" ||+ part.state === "input-streaming" ||+ part.state === "input-available"+ );+ });+ },+ resolveInProgressTools: (msgs: UIMessage[]) => msgs,+ resolveInterruptedMessage: (msgs: UIMessage[]) => msgs,+ getSendSuppressionReason: () => null,}));-vi.mock("@/components/molecules/Toast/use-toast", () => ({- toast: vi.fn(),+// --- ai SDK mock (DefaultChatTransport must be constructible) ---+vi.mock("ai", () => ({+ DefaultChatTransport: vi.fn().mockImplementation(function () {+ return {};+ }),}));-vi.mock("@/services/environment", () => ({- environment: {- getAGPTServerBaseUrl: () => "http://localhost",- isServerSide: () => false,+// --- @ai-sdk/react useChat mock with persistent Chat instances ---+type UseChatOptions = {+ id?: string;+ chat?: { id?: string };+};+const capturedUseChatChats: Array<{ id?: string } | undefined> = [];+const mockResumeStream = vi.fn();+const mockSdkStop = vi.fn();+const mockSdkSendMessage = vi.fn();+const mockSetMessages = vi.fn();+let mockMessages: UIMessage[] = [];+let mockStatus: "ready" | "streaming" | "submitted" | "error" = "ready";++vi.mock("@ai-sdk/react", () => ({+ Chat: class MockChat {+ id: string;+ onFinish?: (args: {+ isDisconnect?: boolean;+ isAbort?: boolean;+ }) => void | Promise<void>;+ onError?: (error: Error) => void;++ constructor(options: {+ id?: string;+ onFinish?: (args: {+ isDisconnect?: boolean;+ isAbort?: boolean;+ }) => void | Promise<void>;+ onError?: (error: Error) => void;+ }) {+ this.id = options.id ?? "";+ this.onFinish = options.onFinish;+ this.onError = options.onError;+ }+ },+ useChat: (opts: UseChatOptions) => {+ capturedUseChatChats.push(opts.chat);+ return {+ messages: mockMessages,+ sendMessage: mockSdkSendMessage,+ stop: mockSdkStop,+ status: mockStatus,+ error: undefined,+ setMessages: mockSetMessages,+ resumeStream: mockResumeStream,+ };},}));-vi.mock("../helpers", async () => {- const actual =- await vi.importActual<typeof import("../helpers")>("../helpers");+// Import after mocks+import {+ getOrCreateCopilotChatRuntime,+ resetCopilotChatRegistry,+ shouldReloadCopilotChatRuntime,+} from "../copilotChatRegistry";+import { useCopilotStreamStore } from "../copilotStreamStore";+import { RESTORE_STALL_TIMEOUT_MS } from "../restoreConstants";+import { useCopilotUIStore } from "../store";+import { useCopilotStream } from "../useCopilotStream";++type Args = Parameters<typeof useCopilotStream>[0];++function makeArgs(overrides: Partial<Args> = {}): Args {return {- ...actual,- getCopilotAuthHeaders: vi.fn().mockResolvedValue({}),- disconnectSessionStream: vi.fn(),+ sessionId: "sess-1",+ hydratedMessages: undefined,+ hasActiveStream: false,+ refetchSession: vi.fn(async () => ({ data: undefined })),+ copilotMode: undefined,+ copilotModel: undefined,+ ...overrides,};+}++beforeEach(() => {+ vi.useFakeTimers();+ mockMessages = [];+ mockStatus = "ready";+ capturedUseChatChats.length = 0;+ mockResumeStream.mockClear();+ mockSdkStop.mockClear();+ mockSdkSendMessage.mockClear();+ mockSetMessages.mockClear();+ mockToast.mockClear();+ mockHasActiveBackendStream.mockReturnValue(false);+ mockInvalidateQueries.mockClear();+ resetCopilotChatRegistry();+ // Zustand stores are module singletons — wipe per-session coord state so+ // tests don't leak into each other.+ useCopilotStreamStore.getState().resetAll();});-vi.mock("../useHydrateOnStreamEnd", () => ({- useHydrateOnStreamEnd: () => undefined,-}));+afterEach(() => {+ vi.useRealTimers();+ cleanup();+});-function renderStream() {- return renderHook(() =>- useCopilotStream({- sessionId: "sess-1",- hydratedMessages: [],- hasActiveStream: false,- refetchSession: vi.fn().mockResolvedValue({ data: undefined }),- copilotMode: undefined,- copilotModel: undefined,- }),- );-}+describe("useCopilotStream — hydration/resume race (SECRT-2242)", () => {+ it("reuses the same session chat runtime across remounts", () => {+ const first = renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({ sessionId: "sess-1" }),+ });+ first.unmount();++ renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({ sessionId: "sess-1" }),+ });++ expect(capturedUseChatChats).toHaveLength(2);+ expect(capturedUseChatChats[0]?.id).toBe("sess-1");+ expect(capturedUseChatChats[1]?.id).toBe("sess-1");+ expect(capturedUseChatChats[0]).toBe(capturedUseChatChats[1]);+ });++ it("defers resume until hydration completes when hydratedMessages arrives late", () => {+ // Arrange: active backend stream, hydration NOT yet complete.+ const { rerender } = renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({+ hasActiveStream: true,+ hydratedMessages: undefined,+ }),+ });++ // Resume effect runs but must wait — no resumeStream fires yet.+ expect(mockResumeStream).not.toHaveBeenCalled();++ // Hydration completes: hydratedMessages becomes defined.+ rerender(+ makeArgs({+ hasActiveStream: true,+ hydratedMessages: [],+ }),+ );++ // pendingResumeRef should have been flushed exactly once.+ expect(mockResumeStream).toHaveBeenCalledTimes(1);+ });++ it("reports active-session restore until visible content arrives", () => {+ const { result, rerender } = renderHook(+ (args: Args) => useCopilotStream(args),+ {+ initialProps: makeArgs({+ hasActiveStream: true,+ hydratedMessages: [],+ }),+ },+ );++ expect(result.current.isRestoringActiveSession).toBe(true);++ mockStatus = "streaming";+ rerender(+ makeArgs({+ hasActiveStream: true,+ hydratedMessages: [],+ }),+ );+ expect(result.current.isRestoringActiveSession).toBe(true);++ mockMessages = [+ {+ id: "a1",+ role: "assistant",+ parts: [{ type: "text", text: "Hello" }],+ } as unknown as UIMessage,+ ];+ rerender(+ makeArgs({+ hasActiveStream: true,+ hydratedMessages: [],+ }),+ );++ expect(result.current.isRestoringActiveSession).toBe(false);+ });++ it("treats a replay status update as enough to leave restore mode", () => {+ const { result, rerender } = renderHook(+ (args: Args) => useCopilotStream(args),+ {+ initialProps: makeArgs({+ hasActiveStream: true,+ hydratedMessages: [],+ }),+ },+ );++ expect(result.current.isRestoringActiveSession).toBe(true);++ mockStatus = "streaming";+ mockMessages = [+ {+ id: "a1",+ role: "assistant",+ parts: [+ {+ type: "data-status",+ data: { message: "Analyzing result..." },+ },+ ],+ } as unknown as UIMessage,+ ];+ rerender(+ makeArgs({+ hasActiveStream: true,+ hydratedMessages: [],+ }),+ );++ expect(result.current.isRestoringActiveSession).toBe(false);+ });++ it("keeps the restore latch closed when hydration lands assistant content while status is still ready", () => {+ // Repro for the premature-latch bug: the user reopens a session whose+ // backend stream is still active, hydration lands a partial assistant+ // message persisted mid-stream into rawMessages, but the live SSE+ // GET-resume hasn't produced any bytes yet (status still ``ready``).+ // The latch must NOT fire — otherwise the "Retrieving latest messages"+ // UI is suppressed and the 6 s restore-stall watchdog can't run.+ mockStatus = "ready";+ mockMessages = [+ {+ id: "u1",+ role: "user",+ parts: [{ type: "text", text: "Hi" }],+ } as unknown as UIMessage,+ {+ id: "a1",+ role: "assistant",+ parts: [{ type: "text", text: "Partial response" }],+ } as unknown as UIMessage,+ ];++ const { result, rerender } = renderHook(+ (args: Args) => useCopilotStream(args),+ {+ initialProps: makeArgs({+ hasActiveStream: true,+ hydratedMessages: [],+ }),+ },+ );++ expect(result.current.isRestoringActiveSession).toBe(true);++ // Once the live stream actually flips status to ``streaming`` (resume+ // produced its first byte), the latch is allowed to fire.+ mockStatus = "streaming";+ rerender(+ makeArgs({+ hasActiveStream: true,+ hydratedMessages: [],+ }),+ );++ expect(result.current.isRestoringActiveSession).toBe(false);+ });++ it("kicks the reconnect cascade when restore stays stuck for 6 seconds", async () => {+ mockHasActiveBackendStream.mockReturnValue(true);+ const refetchSession = vi.fn(async () => ({+ data: { status: 200, data: { active_stream: { started_at: "now" } } },+ }));++ const { rerender } = renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({+ hasActiveStream: true,+ hydratedMessages: [],+ refetchSession,+ }),+ });-describe("useCopilotStream — reconnect debounce", () => {- beforeEach(() => {- resetSdkMocks();- vi.useFakeTimers();- // Pin Date.now so sinceLastResume math is deterministic. The hook reads- // Date.now() both when stashing lastReconnectResumeAtRef and when- // deciding whether to debounce.- vi.setSystemTime(new Date(2025, 0, 1, 12, 0, 0));+ expect(mockResumeStream).toHaveBeenCalledTimes(1);++ mockStatus = "streaming";+ rerender(+ makeArgs({+ hasActiveStream: true,+ hydratedMessages: [],+ refetchSession,+ }),+ );++ await act(async () => {+ await vi.advanceTimersByTimeAsync(RESTORE_STALL_TIMEOUT_MS + 1_000);+ });++ expect(refetchSession).toHaveBeenCalled();+ expect(mockResumeStream).toHaveBeenCalledTimes(2);+ });++ it("stores the latest per-session snapshot without wiping it on an empty remount", () => {+ const userMessage: UIMessage = {+ id: "u1",+ role: "user",+ parts: [{ type: "text", text: "hello", state: "done" }],+ };+ const assistantMessage: UIMessage = {+ id: "a1",+ role: "assistant",+ parts: [{ type: "text", text: "partial", state: "streaming" }],+ };+ mockMessages = [userMessage, assistantMessage];++ const first = renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({+ hasActiveStream: true,+ hydratedMessages: [userMessage, assistantMessage],+ }),+ });++ expect(+ useCopilotStreamStore.getState().getMessageSnapshot("sess-1"),+ ).toEqual([userMessage, assistantMessage]);++ first.unmount();+ mockMessages = [];++ renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({+ hasActiveStream: true,+ hydratedMessages: [userMessage, assistantMessage],+ }),+ });++ expect(+ useCopilotStreamStore.getState().getMessageSnapshot("sess-1"),+ ).toEqual([userMessage, assistantMessage]);+ });++ it("does not double-resume when hydration arrives after an already-queued resume", () => {+ const { rerender } = renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({+ hasActiveStream: true,+ hydratedMessages: undefined,+ }),+ });++ // Hydration completes once — pending resume flushes.+ rerender(makeArgs({ hasActiveStream: true, hydratedMessages: [] }));+ expect(mockResumeStream).toHaveBeenCalledTimes(1);++ // Subsequent rerender with the same hydration must not re-trigger resume+ // because hasResumedRef is now set for this mount.+ rerender(makeArgs({ hasActiveStream: true, hydratedMessages: [] }));+ expect(mockResumeStream).toHaveBeenCalledTimes(1);+ });++ it("resumes immediately when hydration completed before the active-stream flag flipped on", () => {+ const { rerender } = renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({+ hasActiveStream: false,+ hydratedMessages: [],+ }),+ });++ expect(mockResumeStream).not.toHaveBeenCalled();++ rerender(makeArgs({ hasActiveStream: true, hydratedMessages: [] }));++ expect(mockResumeStream).toHaveBeenCalledTimes(1);+ });++ it("drops a trailing assistant snapshot before full replay resume", () => {+ const userMessage: UIMessage = {+ id: "u1",+ role: "user",+ parts: [{ type: "text", text: "hello", state: "done" }],+ };+ const assistantMessage: UIMessage = {+ id: "a1",+ role: "assistant",+ parts: [{ type: "text", text: "partial", state: "streaming" }],+ };+ mockMessages = [userMessage, assistantMessage];++ renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({+ hasActiveStream: true,+ hydratedMessages: [userMessage, assistantMessage],+ }),+ });++ const messageUpdaters = mockSetMessages.mock.calls+ .map(([arg]) => arg)+ .filter((arg) => typeof arg === "function") as Array<+ (messages: UIMessage[]) => UIMessage[]+ >;+ const resumeUpdater = messageUpdaters[messageUpdaters.length - 1];++ expect(resumeUpdater?.([userMessage, assistantMessage])).toEqual([+ userMessage,+ ]);+ expect(mockResumeStream).toHaveBeenCalledTimes(1);+ });++ it("keeps a completed trailing assistant before full replay resume", () => {+ const userMessage: UIMessage = {+ id: "u1",+ role: "user",+ parts: [{ type: "text", text: "hello", state: "done" }],+ };+ const assistantMessage: UIMessage = {+ id: "a1",+ role: "assistant",+ parts: [{ type: "text", text: "final", state: "done" }],+ };+ mockMessages = [userMessage, assistantMessage];++ renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({+ hasActiveStream: true,+ hydratedMessages: [userMessage, assistantMessage],+ }),+ });++ const messageUpdaters = mockSetMessages.mock.calls+ .map(([arg]) => arg)+ .filter((arg) => typeof arg === "function") as Array<+ (messages: UIMessage[]) => UIMessage[]+ >;+ const resumeUpdater = messageUpdaters[messageUpdaters.length - 1];++ expect(resumeUpdater?.([userMessage, assistantMessage])).toEqual([+ userMessage,+ assistantMessage,+ ]);+ expect(mockResumeStream).toHaveBeenCalledTimes(1);});+});++describe("useCopilotStream — unmount cleanup", () => {+ it("keeps the in-flight fetch alive on unmount", () => {+ const { unmount } = renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({ sessionId: "sess-A" }),+ });++ unmount();++ expect(mockSdkStop).not.toHaveBeenCalled();+ });++ it("reconnect timer does not fire resumeStream after unmount", async () => {+ const { unmount } = renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({ sessionId: "sess-A" }),+ });- afterEach(() => {- vi.useRealTimers();+ await act(async () => {+ await getOrCreateCopilotChatRuntime("sess-A").onFinish?.({+ isDisconnect: true,+ });+ });++ // Parent would remount us with a new session key — simulate the+ // unmount that happens before the reconnect timer backoff expires.+ unmount();++ await act(async () => {+ await vi.advanceTimersByTimeAsync(5_000);+ });++ expect(mockResumeStream).not.toHaveBeenCalled();});- it("coalesces a burst of disconnect events into one resumeStream call", async () => {- renderStream();+ it("marks a background-disconnected session for full reload on reopen", async () => {+ useCopilotStreamStore+ .getState()+ .updateCoord("sess-A", { lastSubmittedMessageText: "hello" });+ useCopilotStreamStore.getState().setMessageSnapshot("sess-A", [+ {+ id: "a1",+ role: "assistant",+ parts: [{ type: "text", text: "partial" }],+ } as unknown as UIMessage,+ ]);++ const firstRuntime = getOrCreateCopilotChatRuntime("sess-A");+ renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({ sessionId: "sess-A" }),+ }).unmount();- // First disconnect — schedules a reconnect at the exponential backoff- // delay (1000ms for attempt #1).await act(async () => {- await lastUseChatArgs!.onFinish!({ isDisconnect: true });+ await (+ firstRuntime.chat as unknown as {+ onFinish?: (args: { isDisconnect?: boolean }) => Promise<void> | void;+ }+ ).onFinish?.({ isDisconnect: true });+ });++ expect(shouldReloadCopilotChatRuntime("sess-A")).toBe(true);+ expect(+ useCopilotStreamStore.getState().getMessageSnapshot("sess-A"),+ ).toEqual([]);+ expect(+ useCopilotStreamStore.getState().getCoord("sess-A")+ .lastSubmittedMessageText,+ ).toBeNull();++ renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({ sessionId: "sess-A" }),});- // Fire the scheduled timer → resumeStream runs once and stamps- // lastReconnectResumeAtRef.current = Date.now().+ expect(capturedUseChatChats.at(-1)).not.toBe(firstRuntime.chat);+ expect(shouldReloadCopilotChatRuntime("sess-A")).toBe(false);+ });+});++describe("useCopilotStream — forced reconnect timeout (SECRT-2241)", () => {+ it("forces UI back to idle after 30s of continuous reconnection", async () => {+ const refetchSession = vi.fn(async () => ({ data: undefined }));+ const { result } = renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({ refetchSession }),+ });++ // Kick off reconnect via a disconnect finish.await act(async () => {- await vi.advanceTimersByTimeAsync(1_000);+ await getOrCreateCopilotChatRuntime("sess-1").onFinish?.({+ isDisconnect: true,+ });});- expect(resumeStreamMock).toHaveBeenCalledTimes(1);- // A second disconnect arrives immediately after (still inside the- // 1500ms debounce window) — the debounce path must fire and queue a- // coalesced timer, NOT a fresh resume.+ // Initially reconnect is scheduled — but we won't let it succeed. Instead+ // advance exactly 30s so the forced-timeout callback fires.+ mockToast.mockClear();await act(async () => {- await lastUseChatArgs!.onFinish!({ isDisconnect: true });+ await vi.advanceTimersByTimeAsync(30_000);+ });++ // Forced timeout should have fired its toast.+ const timeoutToast = mockToast.mock.calls.find(+ ([call]) => (call as { title?: string }).title === "Connection timed out",+ );+ expect(timeoutToast).toBeDefined();++ // isReconnecting should flip back to false once reconnectExhausted is set.+ expect(result.current.isReconnecting).toBe(false);+ });++ it("forced-timeout does not fire after unmount", async () => {+ const { unmount } = renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs(),});- expect(resumeStreamMock).toHaveBeenCalledTimes(1);- // The coalesced timer fires at the window boundary and reschedules a- // real reconnect. Advance past the window AND past the second- // reconnect's backoff (attempt #2 = 2000ms) so resume runs.await act(async () => {- await vi.advanceTimersByTimeAsync(1_500);+ await getOrCreateCopilotChatRuntime("sess-1").onFinish?.({+ isDisconnect: true,+ });});++ // Parent remounts on session switch — the old mount unmounts. Any+ // pending timers belong to that mount and must not fire toasts after+ // its teardown.+ unmount();++ mockToast.mockClear();await act(async () => {- await vi.advanceTimersByTimeAsync(2_000);+ await vi.advanceTimersByTimeAsync(30_000);});- expect(resumeStreamMock).toHaveBeenCalledTimes(2);++ const timeoutToast = mockToast.mock.calls.find(+ ([call]) => (call as { title?: string }).title === "Connection timed out",+ );+ expect(timeoutToast).toBeUndefined();});+});++// Cursor tracking for incremental resume was removed — resume always replays+// from "0-0" because AI SDK v5's UIMessageStream parser throws on orphan+// `*-delta` / `*-end` chunks, and a cursor-based XREAD skips the envelope ++// `*-start` chunks that precede the cursor. See copilotStreamTransport.ts.++describe("useCopilotStream — mount preserves session runtime state", () => {+ it("does not clear the chat runtime on mount", () => {+ renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({ sessionId: "sess-A" }),+ });+ expect(mockSetMessages).not.toHaveBeenCalledWith([]);+ });+});++describe("useCopilotStream — rate-limit recovery", () => {it("restores the unsent text and drops the optimistic user bubble on 429 usage-limit", async () => {useCopilotUIStore.getState().setInitialPrompt(null);- const { result } = renderStream();+ useCopilotStreamStore+ .getState()+ .updateCoord("sess-1", { lastSubmittedMessageText: "recover me" });- await act(async () => {- await result.current.sendMessage({ text: "recover me" });+ const { result } = renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({ sessionId: "sess-1" }),});- expect(sdkSendMessageMock).toHaveBeenCalledTimes(1);await act(async () => {- lastUseChatArgs!.onError!(+ await getOrCreateCopilotChatRuntime("sess-1").onError?.(new Error(JSON.stringify({ detail: "Daily usage limit exceeded" })),);});expect(useCopilotUIStore.getState().initialPrompt).toBe("recover me");expect(result.current.rateLimitMessage).toContain("Daily usage limit");+ expect(+ useCopilotStreamStore.getState().getCoord("sess-1")+ .lastSubmittedMessageText,+ ).toBeNull();- const dropCall = setMessagesMock.mock.calls.find(([arg]) => {+ const dropCall = mockSetMessages.mock.calls.find(([arg]) => {if (typeof arg !== "function") return false;const prev: UIMessage[] = [{@@ -184,7 +718,7 @@ describe("useCopilotStream — reconnect debounce", () => {// Branch: when the trailing message is NOT a user bubble (e.g. an// assistant turn already landed), the rollback updater must leave the// list untouched so we don't clobber the assistant reply.- const updater = setMessagesMock.mock.calls+ const updater = mockSetMessages.mock.calls.map(([arg]) => arg).find((arg): arg is (p: UIMessage[]) => UIMessage[] =>@@ -204,50 +738,58 @@ describe("useCopilotStream — reconnect debounce", () => {it("skips composer restore on 429 when there is no captured unsent text", async () => {useCopilotUIStore.getState().setInitialPrompt(null);- renderStream();+ renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({ sessionId: "sess-1" }),+ });await act(async () => {- lastUseChatArgs!.onError!(+ await getOrCreateCopilotChatRuntime("sess-1").onError?.(new Error(JSON.stringify({ detail: "Daily usage limit exceeded" })),);});- // No sendMessage was called → lastSubmittedMsgRef stays null → restore- // branch must be skipped. The store stays untouched and setMessages is- // NOT invoked with a rollback updater.+ // No prior sendMessage → coord lastSubmittedMessageText stays null →+ // restore branch must be skipped. The store stays untouched and+ // setMessages is NOT invoked with a rollback updater.expect(useCopilotUIStore.getState().initialPrompt).toBeNull();- expect(sdkSendMessageMock).not.toHaveBeenCalled();- const rollbackUpdaterCall = setMessagesMock.mock.calls.find(+ const rollbackUpdaterCall = mockSetMessages.mock.calls.find(([arg]) => typeof arg === "function",);expect(rollbackUpdaterCall).toBeUndefined();});- it("does not debounce a reconnect that arrives after the window closes", async () => {- renderStream();-- // First reconnect cycle.- await act(async () => {- await lastUseChatArgs!.onFinish!({ isDisconnect: true });- });- await act(async () => {- await vi.advanceTimersByTimeAsync(1_000);- });- expect(resumeStreamMock).toHaveBeenCalledTimes(1);-- // Wait past the debounce window before the next disconnect.- await act(async () => {- await vi.advanceTimersByTimeAsync(2_000);- });-- // Now a fresh disconnect should go through the normal path (NOT the- // debounce branch) and schedule a backoff of 2000ms (attempt #2).- await act(async () => {- await lastUseChatArgs!.onFinish!({ isDisconnect: true });- });- await act(async () => {- await vi.advanceTimersByTimeAsync(2_000);- });- expect(resumeStreamMock).toHaveBeenCalledTimes(2);+ it("preserves the unsent text in the store when the user is already typing a new draft", async () => {+ useCopilotUIStore.getState().setInitialPrompt(null);+ useCopilotStreamStore+ .getState()+ .updateCoord("sess-1", { lastSubmittedMessageText: "rate-limited" });++ const composer = document.createElement("textarea");+ composer.id = "chat-input";+ composer.value = "user is typing a new draft";+ document.body.appendChild(composer);++ try {+ renderHook((args: Args) => useCopilotStream(args), {+ initialProps: makeArgs({ sessionId: "sess-1" }),+ });++ await act(async () => {+ await getOrCreateCopilotChatRuntime("sess-1").onError?.(+ new Error(JSON.stringify({ detail: "Daily usage limit exceeded" })),+ );+ });++ // Composer non-empty → don't write to the recovery slot, don't clear+ // the per-session unsent buffer. The user keeps their draft and the+ // rate-limited text stays available for a future reload/resume.+ expect(useCopilotUIStore.getState().initialPrompt).toBeNull();+ expect(+ useCopilotStreamStore.getState().getCoord("sess-1")+ .lastSubmittedMessageText,+ ).toBe("rate-limited");+ } finally {+ document.body.removeChild(composer);+ }});});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useHydrateOnStreamEnd.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useHydrateOnStreamEnd.test.tsindex 19a52735d7..ea06d1c4d5 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useHydrateOnStreamEnd.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useHydrateOnStreamEnd.test.ts@@ -2,7 +2,15 @@ import { renderHook } from "@testing-library/react";import type { UIMessage } from "ai";import { describe, expect, it, vi } from "vitest";-import { useHydrateOnStreamEnd } from "../useHydrateOnStreamEnd";+const mockToast = vi.fn();+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast: (...args: unknown[]) => mockToast(...args),+}));++import {+ _resetInterruptedToastLedgerForTests,+ useHydrateOnStreamEnd,+} from "../useHydrateOnStreamEnd";/** Use distinct default text per id so the assistant dedup doesn't collapse them. */function msg(id: string, text?: string): UIMessage {@@ -24,9 +32,11 @@ describe("useHydrateOnStreamEnd", () => {const setMessages = vi.fn();renderHook(() =>useHydrateOnStreamEnd({+ sessionId: null,status: "streaming",hydratedMessages: [msg("a")],isReconnectScheduled: false,+ hasActiveStream: false,setMessages,}),);@@ -37,9 +47,11 @@ describe("useHydrateOnStreamEnd", () => {const setMessages = vi.fn();renderHook(() =>useHydrateOnStreamEnd({+ sessionId: null,status: "ready",hydratedMessages: [msg("a")],isReconnectScheduled: true,+ hasActiveStream: false,setMessages,}),);@@ -53,9 +65,11 @@ describe("useHydrateOnStreamEnd", () => {const fresh = [msg("a"), msg("b"), msg("c")];renderHook(() =>useHydrateOnStreamEnd({+ sessionId: null,status: "ready",hydratedMessages: fresh,isReconnectScheduled: false,+ hasActiveStream: false,setMessages,}),);@@ -82,9 +96,11 @@ describe("useHydrateOnStreamEnd", () => {hydratedMessages: UIMessage[];}) =>useHydrateOnStreamEnd({+ sessionId: null,status,hydratedMessages,isReconnectScheduled: false,+ hasActiveStream: false,setMessages,}),{@@ -107,26 +123,319 @@ describe("useHydrateOnStreamEnd", () => {const fresh = [msg("s1"), msg("s2")];rerender({ status: "ready", hydratedMessages: fresh });expect(setMessages).toHaveBeenCalledTimes(1);- const arg = setMessages.mock.calls[0][0];- // Force-hydrate replaces unconditionally (not an updater fn).- expect(Array.isArray(arg)).toBe(true);- expect((arg as UIMessage[]).map((m) => m.id)).toEqual(["s1", "s2"]);+ const updater = setMessages.mock.calls[0][0];+ // Force-hydrate uses an updater so it can preserve any in-flight+ // promoted-* user bubbles whose text isn't in the hydrated DB rows.+ expect(typeof updater).toBe("function");+ expect(+ (updater as (prev: UIMessage[]) => UIMessage[])([]).map((m) => m.id),+ ).toEqual(["s1", "s2"]);// Subsequent rerender with same fresh ref → no additional call.rerender({ status: "ready", hydratedMessages: fresh });expect(setMessages).toHaveBeenCalledTimes(1);});+ it("preserves promoted user bubbles whose text isn't in the hydrated DB rows", () => {+ // Simulates: Claude saw a queued message via mid-turn injection but the+ // persist rolled back, so the DB has no matching user row. We must NOT+ // drop the in-flight bubble during force-hydrate.+ const setMessages = vi.fn();+ const stale = [msg("a")];+ const { rerender } = renderHook(+ ({+ status,+ hydratedMessages,+ }: {+ status: "submitted" | "streaming" | "ready" | "error";+ hydratedMessages: UIMessage[];+ }) =>+ useHydrateOnStreamEnd({+ sessionId: null,+ status,+ hydratedMessages,+ isReconnectScheduled: false,+ hasActiveStream: false,+ setMessages,+ }),+ { initialProps: { status: "streaming", hydratedMessages: stale } },+ );++ // Arm force-hydrate, then drop in a fresh hydrated reference.+ rerender({ status: "ready", hydratedMessages: stale });+ const fresh = [msg("a"), msg("b")];+ rerender({ status: "ready", hydratedMessages: fresh });+ expect(setMessages).toHaveBeenCalledTimes(1);++ const updater = setMessages.mock.calls[0][0] as (+ prev: UIMessage[],+ ) => UIMessage[];++ const promoted: UIMessage = {+ id: "promoted-midturn-xyz",+ role: "user",+ parts: [{ type: "text", text: "queued message", state: "done" }],+ };+ const result = updater([msg("a"), promoted, msg("b")]);+ // Promoted bubble survives because no hydrated user message contains its text.+ expect(result.map((m) => m.id)).toEqual(["a", "b", "promoted-midturn-xyz"]);+ });++ it("drops promoted bubbles whose text is already represented in the DB", () => {+ const setMessages = vi.fn();+ const stale = [msg("a")];+ const { rerender } = renderHook(+ ({+ status,+ hydratedMessages,+ }: {+ status: "submitted" | "streaming" | "ready" | "error";+ hydratedMessages: UIMessage[];+ }) =>+ useHydrateOnStreamEnd({+ sessionId: null,+ status,+ hydratedMessages,+ isReconnectScheduled: false,+ hasActiveStream: false,+ setMessages,+ }),+ { initialProps: { status: "streaming", hydratedMessages: stale } },+ );++ rerender({ status: "ready", hydratedMessages: stale });+ const persistedUser: UIMessage = {+ id: "session-seq-3",+ role: "user",+ parts: [{ type: "text", text: "queued message", state: "done" }],+ };+ const fresh = [msg("a"), persistedUser, msg("b")];+ rerender({ status: "ready", hydratedMessages: fresh });++ const updater = setMessages.mock.calls[0][0] as (+ prev: UIMessage[],+ ) => UIMessage[];++ const promoted: UIMessage = {+ id: "promoted-midturn-xyz",+ role: "user",+ parts: [{ type: "text", text: "queued message", state: "done" }],+ };+ const result = updater([msg("a"), promoted, msg("b")]);+ // No duplicate — DB user row already covers the bubble's text.+ expect(result.map((m) => m.id)).toEqual(["a", "session-seq-3", "b"]);+ });+it("ignores undefined or empty hydratedMessages", () => {const setMessages = vi.fn();renderHook(() =>useHydrateOnStreamEnd({+ sessionId: null,status: "ready",hydratedMessages: undefined,isReconnectScheduled: false,+ hasActiveStream: false,setMessages,}),);expect(setMessages).not.toHaveBeenCalled();});++ it("resolves in-progress parts + toasts when hydrated state is zombied and no active stream", () => {+ mockToast.mockClear();+ const setMessages = vi.fn();+ const zombie: UIMessage = {+ id: "a",+ role: "assistant",+ parts: [+ {+ type: "text" as const,+ text: "half-written reply",+ state: "streaming" as const,+ },+ ],+ };++ renderHook(() =>+ useHydrateOnStreamEnd({+ sessionId: "zombie-session",+ status: "ready",+ hydratedMessages: [zombie],+ isReconnectScheduled: false,+ hasActiveStream: false,+ setMessages,+ }),+ );++ expect(mockToast).toHaveBeenCalledTimes(1);+ expect(mockToast.mock.calls[0][0]).toMatchObject({+ title: "Previous response was interrupted",+ });+ // setMessages is invoked once with a length-gated updater — pass a short+ // prev and expect the replaced (finalised) messages back.+ expect(setMessages).toHaveBeenCalledTimes(1);+ const updater = setMessages.mock.calls[0][0] as (+ prev: UIMessage[],+ ) => UIMessage[];+ const finalised = updater([]);+ const last = finalised[finalised.length - 1];+ const lastPart = last.parts[last.parts.length - 1];+ expect(lastPart.type).toBe("text");+ // Last appended part is the interrupted marker.+ expect((lastPart as { text: string }).text.includes("interrupted")).toBe(+ true,+ );+ });++ it("leaves zombie parts alone when backend still has active stream", () => {+ mockToast.mockClear();+ const setMessages = vi.fn();+ const partial: UIMessage = {+ id: "a",+ role: "assistant",+ parts: [+ {+ type: "text" as const,+ text: "still writing",+ state: "streaming" as const,+ },+ ],+ };++ renderHook(() =>+ useHydrateOnStreamEnd({+ sessionId: "active-session",+ status: "ready",+ hydratedMessages: [partial],+ isReconnectScheduled: false,+ hasActiveStream: true,+ setMessages,+ }),+ );++ expect(mockToast).not.toHaveBeenCalled();+ });++ it("does not fire interrupted toast against the pre-turn stale snapshot", () => {+ mockToast.mockClear();+ _resetInterruptedToastLedgerForTests();++ const setMessages = vi.fn();+ const stale: UIMessage[] = [+ {+ id: "a",+ role: "assistant",+ parts: [+ {+ type: "text" as const,+ text: "half-written reply",+ state: "streaming" as const,+ },+ ],+ },+ ];++ const { rerender } = renderHook(+ ({+ status,+ hydratedMessages,+ }: {+ status: "streaming" | "ready";+ hydratedMessages: UIMessage[];+ }) =>+ useHydrateOnStreamEnd({+ sessionId: "sess-stale-toast",+ status,+ hydratedMessages,+ isReconnectScheduled: false,+ hasActiveStream: false,+ setMessages,+ }),+ { initialProps: { status: "streaming", hydratedMessages: stale } },+ );++ // status flip with the SAME stale snapshot — force-hydrate is armed,+ // but the data is still the pre-turn ref. Toast must NOT fire here:+ // the interrupted bubble may not exist once the refetch lands.+ rerender({ status: "ready", hydratedMessages: stale });+ expect(mockToast).not.toHaveBeenCalled();+ expect(setMessages).not.toHaveBeenCalled();++ // Fresh ref arrives, still has zombie parts → toast fires alongside+ // the apply.+ const fresh: UIMessage[] = [+ {+ id: "a",+ role: "assistant",+ parts: [+ {+ type: "text" as const,+ text: "half-written reply",+ state: "streaming" as const,+ },+ ],+ },+ ];+ rerender({ status: "ready", hydratedMessages: fresh });+ expect(mockToast).toHaveBeenCalledTimes(1);+ });++ it("only fires the interrupted toast once per session across remounts", () => {+ mockToast.mockClear();+ _resetInterruptedToastLedgerForTests();++ const setMessages = vi.fn();+ const zombie: UIMessage = {+ id: "a",+ role: "assistant",+ parts: [+ {+ type: "text" as const,+ text: "half-written reply",+ state: "streaming" as const,+ },+ ],+ };++ // Mount #1 — toast fires.+ const first = renderHook(() =>+ useHydrateOnStreamEnd({+ sessionId: "sess-toast",+ status: "ready",+ hydratedMessages: [zombie],+ isReconnectScheduled: false,+ hasActiveStream: false,+ setMessages,+ }),+ );+ expect(mockToast).toHaveBeenCalledTimes(1);+ first.unmount();++ // Mount #2 — same sessionId, fresh ref-state but already-shown ledger.+ // Reproduces "switch away then back" — useRef would reset and re-toast.+ renderHook(() =>+ useHydrateOnStreamEnd({+ sessionId: "sess-toast",+ status: "ready",+ hydratedMessages: [zombie],+ isReconnectScheduled: false,+ hasActiveStream: false,+ setMessages,+ }),+ );+ expect(mockToast).toHaveBeenCalledTimes(1);++ // Different session id → new toast is allowed.+ renderHook(() =>+ useHydrateOnStreamEnd({+ sessionId: "sess-toast-other",+ status: "ready",+ hydratedMessages: [zombie],+ isReconnectScheduled: false,+ hasActiveStream: false,+ setMessages,+ }),+ );+ expect(mockToast).toHaveBeenCalledTimes(2);+ });});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSendMessage.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSendMessage.test.tsnew file mode 100644index 0000000000..6a3348b82d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSendMessage.test.ts@@ -0,0 +1,240 @@+import { renderHook } from "@testing-library/react";+import { useRef } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mockToast = vi.fn();+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast: (...args: unknown[]) => mockToast(...args),+}));++const mockUploadFileDirect = vi.fn();+vi.mock("@/lib/direct-upload", () => ({+ uploadFileDirect: (...args: unknown[]) => mockUploadFileDirect(...args),+}));++import { useCopilotStreamStore } from "../copilotStreamStore";+import { useSendMessage } from "../useSendMessage";++function file(name: string, size = 100, type = "text/plain"): File {+ const blob = new Blob([new Uint8Array(size)], { type });+ return new File([blob], name, { type });+}++function setupHook(opts: {+ sessionId: string | null;+ createSession?: () => Promise<string | undefined>;+}) {+ const sendMessage = vi.fn();+ const createSession =+ opts.createSession ??+ vi.fn(async () => "new-session" as string | undefined);++ const { result, rerender } = renderHook(+ ({ sessionId }: { sessionId: string | null }) => {+ const isUserStoppingRef = useRef(true);+ const hook = useSendMessage({+ sessionId,+ sendMessage,+ createSession,+ isUserStoppingRef,+ });+ return { ...hook, isUserStoppingRef };+ },+ { initialProps: { sessionId: opts.sessionId } },+ );+ return { result, rerender, sendMessage, createSession };+}++describe("useSendMessage", () => {+ beforeEach(() => {+ mockToast.mockClear();+ mockUploadFileDirect.mockReset();+ // Reset shared store between tests via the store's own resetAll helper+ // to avoid clobbering its internal action functions.+ useCopilotStreamStore.getState().resetAll();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("does nothing when both text and files are empty", async () => {+ const { result, sendMessage } = setupHook({ sessionId: "s1" });+ await result.current.onSend(" ");+ expect(sendMessage).not.toHaveBeenCalled();+ });++ it("dispatches a plain text message immediately when a session exists", async () => {+ const { result, sendMessage } = setupHook({ sessionId: "s1" });+ await result.current.onSend("hello");+ expect(sendMessage).toHaveBeenCalledWith({ text: "hello" });+ });++ it("flips isUserStoppingRef back to false on each send", async () => {+ const { result, sendMessage } = setupHook({ sessionId: "s1" });+ expect(result.current.isUserStoppingRef.current).toBe(true);+ await result.current.onSend("hello");+ expect(result.current.isUserStoppingRef.current).toBe(false);+ expect(sendMessage).toHaveBeenCalledTimes(1);+ });++ it("rejects more than 10 attached files with a destructive toast", async () => {+ const { result, sendMessage } = setupHook({ sessionId: "s1" });+ const tooMany = Array.from({ length: 11 }, (_, i) => file(`f${i}.txt`));+ await result.current.onSend("text", tooMany);+ expect(sendMessage).not.toHaveBeenCalled();+ expect(mockToast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Too many files",+ variant: "destructive",+ }),+ );+ });++ it("rejects a single file larger than the 100 MB limit", async () => {+ const { result, sendMessage } = setupHook({ sessionId: "s1" });+ const big = file("huge.bin", 101 * 1024 * 1024, "application/octet-stream");+ await result.current.onSend("text", [big]);+ expect(sendMessage).not.toHaveBeenCalled();+ expect(mockToast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "File too large",+ variant: "destructive",+ }),+ );+ });++ it("uploads files and sends a message with file parts", async () => {+ mockUploadFileDirect.mockResolvedValueOnce({+ file_id: "fid-1",+ name: "doc.txt",+ mime_type: "text/plain",+ });+ const { result, sendMessage } = setupHook({ sessionId: "s1" });+ await result.current.onSend("with file", [file("doc.txt")]);++ expect(mockUploadFileDirect).toHaveBeenCalledTimes(1);+ expect(sendMessage).toHaveBeenCalledTimes(1);+ const arg = sendMessage.mock.calls[0][0] as {+ text: string;+ files: {+ type: string;+ mediaType: string;+ filename: string;+ url: string;+ }[];+ };+ expect(arg.text).toBe("with file");+ expect(arg.files).toHaveLength(1);+ expect(arg.files[0]).toMatchObject({+ type: "file",+ filename: "doc.txt",+ mediaType: "text/plain",+ });+ expect(arg.files[0].url).toContain("fid-1");+ });++ it("toasts and throws when every upload fails", async () => {+ mockUploadFileDirect.mockRejectedValue(new Error("network down"));+ const { result, sendMessage } = setupHook({ sessionId: "s1" });+ await expect(+ result.current.onSend("with file", [file("a.txt"), file("b.txt")]),+ ).rejects.toThrow();+ expect(sendMessage).not.toHaveBeenCalled();+ // One per-file toast PLUS one aggregate failure toast.+ const titles = mockToast.mock.calls.map(+ (c) => (c[0] as { title: string }).title,+ );+ expect(titles).toContain("File upload failed");+ });++ it("uses pre-built file parts from the store and skips upload", async () => {+ // Mount BEFORE seeding parts — the post-session-creation flush effect+ // calls takePendingFirstSend on mount with a sessionId, which clears+ // pendingFileParts as a side effect.+ const { result, sendMessage } = setupHook({ sessionId: "s1" });+ useCopilotStreamStore.getState().setPendingFileParts([+ {+ type: "file" as const,+ mediaType: "image/png",+ filename: "img.png",+ url: "/api/proxy/x",+ },+ ]);+ await result.current.onSend("see attached");+ expect(mockUploadFileDirect).not.toHaveBeenCalled();+ expect(sendMessage).toHaveBeenCalledWith({+ text: "see attached",+ files: [expect.objectContaining({ type: "file", filename: "img.png" })],+ });+ // Pre-built parts are consumed once.+ expect(useCopilotStreamStore.getState().pendingFileParts).toEqual([]);+ });++ it("stashes a first-send to the store and creates a session when none exists", async () => {+ const createSession = vi.fn(async () => "new-id" as string | undefined);+ const { result } = setupHook({ sessionId: null, createSession });+ await result.current.onSend("hi", [file("a.txt")]);+ expect(createSession).toHaveBeenCalledTimes(1);+ expect(useCopilotStreamStore.getState().pendingFirstSend?.text).toBe("hi");+ expect(+ useCopilotStreamStore.getState().pendingFirstSend?.files,+ ).toHaveLength(1);+ });++ it("blocks a second send while a no-session createSession is in flight", async () => {+ let resolveCreate: (value: string) => void = () => {};+ const createSession = vi.fn(+ () => new Promise<string>((r) => (resolveCreate = r)),+ );+ const { result } = setupHook({ sessionId: null, createSession });++ // Two rapid sends with no session — only the first should make it through.+ const first = result.current.onSend("first");+ const second = result.current.onSend("second");++ // Resolve the in-flight create.+ resolveCreate("new-id");+ await Promise.all([first, second]);++ expect(createSession).toHaveBeenCalledTimes(1);+ // pendingFirstSend reflects the FIRST message — the second short-circuits+ // without overwriting.+ expect(useCopilotStreamStore.getState().pendingFirstSend?.text).toBe(+ "first",+ );+ });++ it("clears the pending first-send when createSession rejects", async () => {+ const createSession = vi.fn(async () => {+ throw new Error("create failed");+ });+ const { result } = setupHook({ sessionId: null, createSession });+ await expect(result.current.onSend("hi")).rejects.toThrow();+ expect(useCopilotStreamStore.getState().pendingFirstSend).toBeNull();+ expect(useCopilotStreamStore.getState().pendingFileParts).toEqual([]);+ });++ it("dispatches the queued first-send once a sessionId becomes available", async () => {+ useCopilotStreamStore.getState().setPendingFirstSend({+ text: "queued",+ files: [],+ });+ const { rerender, sendMessage } = setupHook({ sessionId: null });+ rerender({ sessionId: "now-active" });+ expect(sendMessage).toHaveBeenCalledWith({ text: "queued" });+ });++ it("setPendingFileParts forwards to the store", () => {+ const { result } = setupHook({ sessionId: "s1" });+ result.current.setPendingFileParts([+ {+ type: "file" as const,+ mediaType: "image/jpeg",+ filename: "x.jpg",+ url: "/api/y",+ },+ ]);+ expect(useCopilotStreamStore.getState().pendingFileParts).toHaveLength(1);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSessionDeletion.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSessionDeletion.test.tsnew file mode 100644index 0000000000..888f9595ed--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSessionDeletion.test.ts@@ -0,0 +1,232 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, cleanup, renderHook } from "@testing-library/react";+import React from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mockToast = vi.fn();+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast: (...args: unknown[]) => mockToast(...args),+}));++const setSessionIdMock = vi.fn();+let currentSessionId: string | null = "s1";+vi.mock("nuqs", () => ({+ parseAsString: {},+ useQueryState: () => [+ currentSessionId,+ (next: string | null) => {+ currentSessionId = next;+ setSessionIdMock(next);+ },+ ],+}));++interface UIStoreShape {+ sessionToDelete: { id: string; title: string | null | undefined } | null;+ setSessionToDelete: (+ v: { id: string; title: string | null | undefined } | null,+ ) => void;+}++let storeState: UIStoreShape = {+ sessionToDelete: null,+ setSessionToDelete: vi.fn((v) => {+ storeState = { ...storeState, sessionToDelete: v };+ }),+};+vi.mock("../store", () => ({+ useCopilotUIStore: () => storeState,+}));++type DeleteHandler = (vars: { sessionId: string }) => Promise<unknown>;+let deleteImpl: DeleteHandler = async () => ({});+let isPending = false;+const onSuccessRef: { current?: (data: unknown, vars: unknown) => void } = {};+const onErrorRef: { current?: (err: unknown) => void } = {};++vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => {+ return {+ getGetV2ListSessionsQueryKey: () => ["sessions-list"],+ useDeleteV2DeleteSession: ({+ mutation,+ }: {+ mutation?: {+ onSuccess?: (data: unknown, vars: unknown) => void;+ onError?: (err: unknown) => void;+ };+ }) => {+ onSuccessRef.current = mutation?.onSuccess;+ onErrorRef.current = mutation?.onError;+ return {+ mutate: (vars: { sessionId: string }) => {+ deleteImpl(vars).then(+ (data) => onSuccessRef.current?.(data, vars),+ (err) => onErrorRef.current?.(err),+ );+ },+ isPending,+ };+ },+ };+});++import { useSessionDeletion } from "../useSessionDeletion";++function makeWrapper(client: QueryClient) {+ return function Wrapper({ children }: { children: React.ReactNode }) {+ return React.createElement(QueryClientProvider, { client }, children);+ };+}++describe("useSessionDeletion", () => {+ let client: QueryClient;++ beforeEach(() => {+ mockToast.mockClear();+ setSessionIdMock.mockClear();+ currentSessionId = "s1";+ storeState = {+ sessionToDelete: null,+ setSessionToDelete: vi.fn((v) => {+ storeState = { ...storeState, sessionToDelete: v };+ }),+ };+ deleteImpl = async () => ({});+ isPending = false;+ client = new QueryClient();+ });++ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ });++ it("requestDelete stages a session into the store", () => {+ const { result } = renderHook(() => useSessionDeletion(), {+ wrapper: makeWrapper(client),+ });+ act(() => {+ result.current.requestDelete("target", "Target chat");+ });+ expect(storeState.setSessionToDelete).toHaveBeenCalledWith({+ id: "target",+ title: "Target chat",+ });+ });++ it("requestDelete is a no-op while a delete is in flight", () => {+ isPending = true;+ const { result } = renderHook(() => useSessionDeletion(), {+ wrapper: makeWrapper(client),+ });+ act(() => {+ result.current.requestDelete("target", "Target");+ });+ expect(storeState.setSessionToDelete).not.toHaveBeenCalled();+ });++ it("cancelDelete clears the staged session when not deleting", () => {+ storeState = {+ ...storeState,+ sessionToDelete: { id: "target", title: "Target" },+ };+ const { result } = renderHook(() => useSessionDeletion(), {+ wrapper: makeWrapper(client),+ });+ act(() => {+ result.current.cancelDelete();+ });+ expect(storeState.setSessionToDelete).toHaveBeenCalledWith(null);+ });++ it("cancelDelete is a no-op while a delete is in flight", () => {+ isPending = true;+ storeState = {+ ...storeState,+ sessionToDelete: { id: "target", title: "Target" },+ };+ const { result } = renderHook(() => useSessionDeletion(), {+ wrapper: makeWrapper(client),+ });+ act(() => {+ result.current.cancelDelete();+ });+ expect(storeState.setSessionToDelete).not.toHaveBeenCalled();+ });++ it("confirmDelete clears the active sessionId on success when it matches", async () => {+ currentSessionId = "s1";+ storeState = {+ ...storeState,+ sessionToDelete: { id: "s1", title: "Active" },+ };+ const invalidateSpy = vi.spyOn(client, "invalidateQueries");+ const { result } = renderHook(() => useSessionDeletion(), {+ wrapper: makeWrapper(client),+ });++ await act(async () => {+ result.current.confirmDelete();+ });++ expect(setSessionIdMock).toHaveBeenCalledWith(null);+ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: ["sessions-list"],+ });+ expect(storeState.setSessionToDelete).toHaveBeenLastCalledWith(null);+ });++ it("confirmDelete keeps the active session when a different one was deleted", async () => {+ currentSessionId = "s1";+ storeState = {+ ...storeState,+ sessionToDelete: { id: "different", title: "Other" },+ };+ const { result } = renderHook(() => useSessionDeletion(), {+ wrapper: makeWrapper(client),+ });++ await act(async () => {+ result.current.confirmDelete();+ });++ expect(setSessionIdMock).not.toHaveBeenCalled();+ expect(storeState.setSessionToDelete).toHaveBeenLastCalledWith(null);+ });++ it("confirmDelete is a no-op when no session is staged", async () => {+ storeState = { ...storeState, sessionToDelete: null };+ const { result } = renderHook(() => useSessionDeletion(), {+ wrapper: makeWrapper(client),+ });+ await act(async () => {+ result.current.confirmDelete();+ });+ expect(setSessionIdMock).not.toHaveBeenCalled();+ expect(mockToast).not.toHaveBeenCalled();+ });++ it("toasts and clears the staged session on delete error", async () => {+ storeState = {+ ...storeState,+ sessionToDelete: { id: "s1", title: "Active" },+ };+ deleteImpl = async () => {+ throw new Error("network down");+ };+ const { result } = renderHook(() => useSessionDeletion(), {+ wrapper: makeWrapper(client),+ });++ await act(async () => {+ result.current.confirmDelete();+ });++ expect(mockToast).toHaveBeenCalledTimes(1);+ expect(mockToast.mock.calls[0][0]).toMatchObject({+ title: "Failed to delete chat",+ variant: "destructive",+ });+ expect(storeState.setSessionToDelete).toHaveBeenLastCalledWith(null);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSessionTitlePoll.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSessionTitlePoll.test.tsnew file mode 100644index 0000000000..dd0493fabf--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useSessionTitlePoll.test.ts@@ -0,0 +1,152 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, renderHook } from "@testing-library/react";+import React from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { getGetV2ListSessionsQueryKey } from "@/app/api/__generated__/endpoints/chat/chat";+import { useSessionTitlePoll } from "../useSessionTitlePoll";++interface SessionRow {+ id: string;+ title: string | null;+}++function listKey() {+ return getGetV2ListSessionsQueryKey({ limit: 50 });+}++function seedSessions(client: QueryClient, sessions: SessionRow[]) {+ client.setQueryData(listKey(), { status: 200, data: { sessions } });+}++function makeWrapper(client: QueryClient) {+ return function Wrapper({ children }: { children: React.ReactNode }) {+ return React.createElement(QueryClientProvider, { client }, children);+ };+}++interface RenderProps {+ status: "submitted" | "streaming" | "ready" | "error";+ sessionId: string | null;+ isReconnecting: boolean;+}++function renderPollHook(client: QueryClient, initial: RenderProps) {+ return renderHook(+ ({ status, sessionId, isReconnecting }: RenderProps) =>+ useSessionTitlePoll({ status, sessionId, isReconnecting }),+ {+ wrapper: makeWrapper(client),+ initialProps: initial,+ },+ );+}++describe("useSessionTitlePoll", () => {+ let client: QueryClient;+ let invalidateSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ vi.useFakeTimers();+ client = new QueryClient();+ invalidateSpy = vi.spyOn(client, "invalidateQueries");+ });++ afterEach(() => {+ cleanup();+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it("does not poll when there is no session", () => {+ renderPollHook(client, {+ status: "ready",+ sessionId: null,+ isReconnecting: false,+ });+ expect(invalidateSpy).not.toHaveBeenCalled();+ });++ it("does not poll when reconnecting", async () => {+ const { rerender } = renderPollHook(client, {+ status: "streaming",+ sessionId: "s1",+ isReconnecting: true,+ });+ rerender({ status: "ready", sessionId: "s1", isReconnecting: true });+ await vi.advanceTimersByTimeAsync(0);+ expect(invalidateSpy).not.toHaveBeenCalled();+ });++ it("kicks off an immediate invalidate + interval on streaming→ready", async () => {+ seedSessions(client, [{ id: "s1", title: null }]);+ const { rerender } = renderPollHook(client, {+ status: "streaming",+ sessionId: "s1",+ isReconnecting: false,+ });+ rerender({ status: "ready", sessionId: "s1", isReconnecting: false });++ // Immediate invalidate.+ expect(invalidateSpy).toHaveBeenCalledTimes(1);++ // Each tick re-invalidates while no title appears.+ await vi.advanceTimersByTimeAsync(2_000);+ expect(invalidateSpy).toHaveBeenCalledTimes(2);+ await vi.advanceTimersByTimeAsync(2_000);+ expect(invalidateSpy).toHaveBeenCalledTimes(3);+ });++ it("stops polling once a title shows up in the cached session list", async () => {+ seedSessions(client, [{ id: "s1", title: null }]);+ const { rerender } = renderPollHook(client, {+ status: "streaming",+ sessionId: "s1",+ isReconnecting: false,+ });+ rerender({ status: "ready", sessionId: "s1", isReconnecting: false });+ expect(invalidateSpy).toHaveBeenCalledTimes(1); // initial++ // Backend writes the title before the next tick.+ seedSessions(client, [{ id: "s1", title: "New title" }]);+ await vi.advanceTimersByTimeAsync(2_000);+ // First tick: clears interval (sees title), no extra invalidate.+ expect(invalidateSpy).toHaveBeenCalledTimes(1);++ // Subsequent ticks must NOT fire — interval cleared.+ await vi.advanceTimersByTimeAsync(20_000);+ expect(invalidateSpy).toHaveBeenCalledTimes(1);+ });++ it("gives up after the max attempt count", async () => {+ seedSessions(client, [{ id: "s1", title: null }]);+ const { rerender } = renderPollHook(client, {+ status: "streaming",+ sessionId: "s1",+ isReconnecting: false,+ });+ rerender({ status: "ready", sessionId: "s1", isReconnecting: false });+ // Initial + 5 attempts = 6 total invalidations, then nothing more.+ for (let i = 0; i < 5; i++) await vi.advanceTimersByTimeAsync(2_000);+ expect(invalidateSpy).toHaveBeenCalledTimes(6);+ await vi.advanceTimersByTimeAsync(20_000);+ expect(invalidateSpy).toHaveBeenCalledTimes(6);+ });++ it("clears the interval when sessionId changes", async () => {+ seedSessions(client, [{ id: "s1", title: null }]);+ const { rerender } = renderPollHook(client, {+ status: "streaming",+ sessionId: "s1",+ isReconnecting: false,+ });+ rerender({ status: "ready", sessionId: "s1", isReconnecting: false });+ expect(invalidateSpy).toHaveBeenCalledTimes(1); // initial for s1++ rerender({ status: "ready", sessionId: "s2", isReconnecting: false });+ invalidateSpy.mockClear();+ // The s1 interval should be torn down — no further invalidates from it.+ await vi.advanceTimersByTimeAsync(20_000);+ expect(invalidateSpy).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useStreamActivityWatchdog.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useStreamActivityWatchdog.test.tsnew file mode 100644index 0000000000..fa4e00ce46--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useStreamActivityWatchdog.test.ts@@ -0,0 +1,163 @@+import { renderHook } from "@testing-library/react";+import { act } from "react";+import { useRef } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { useStreamActivityWatchdog } from "../useStreamActivityWatchdog";++type Status = "submitted" | "streaming" | "ready" | "error";++type HookArgs = Parameters<typeof useStreamActivityWatchdog>[0];++function setup(initial: Partial<HookArgs> = {}) {+ const reconnect = vi.fn();+ const { result, rerender } = renderHook(+ ({+ status,+ activityToken,+ isReconnectScheduled,+ isUserStopping,+ sessionId,+ }: {+ status: Status;+ activityToken: string | number;+ isReconnectScheduled: boolean;+ isUserStopping: boolean;+ sessionId: string | null;+ }) => {+ const isUserStoppingRef = useRef(isUserStopping);+ isUserStoppingRef.current = isUserStopping;+ const handleReconnectRef = useRef(reconnect);+ handleReconnectRef.current = reconnect;+ useStreamActivityWatchdog({+ sessionId,+ status,+ activityToken,+ isReconnectScheduled,+ isUserStoppingRef,+ handleReconnectRef,+ });+ return { reconnect };+ },+ {+ initialProps: {+ status: "streaming" as Status,+ activityToken: initial.activityToken ?? "0",+ isReconnectScheduled: initial.isReconnectScheduled ?? false,+ isUserStopping: false,+ sessionId:+ initial.sessionId === undefined ? "sess-1" : initial.sessionId,+ },+ },+ );+ return { result, rerender, reconnect };+}++describe("useStreamActivityWatchdog", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it("fires reconnect after 60 s of inactivity while streaming", () => {+ const { reconnect } = setup();++ act(() => {+ vi.advanceTimersByTime(59_000);+ });+ expect(reconnect).not.toHaveBeenCalled();++ act(() => {+ vi.advanceTimersByTime(1_000);+ });+ expect(reconnect).toHaveBeenCalledTimes(1);+ });++ it("resets the timer on activity", () => {+ const { rerender, reconnect } = setup({ activityToken: "0" });++ act(() => {+ vi.advanceTimersByTime(50_000);+ });++ rerender({+ status: "streaming",+ activityToken: "1",+ isReconnectScheduled: false,+ isUserStopping: false,+ sessionId: "sess-1",+ });++ act(() => {+ vi.advanceTimersByTime(59_000);+ });+ expect(reconnect).not.toHaveBeenCalled();++ act(() => {+ vi.advanceTimersByTime(1_000);+ });+ expect(reconnect).toHaveBeenCalledTimes(1);+ });++ it("does not fire when a reconnect is already scheduled", () => {+ const { reconnect } = setup({ isReconnectScheduled: true });++ act(() => {+ vi.advanceTimersByTime(120_000);+ });+ expect(reconnect).not.toHaveBeenCalled();+ });++ it("does not fire for ready / error status", () => {+ const { rerender, reconnect } = setup();++ rerender({+ status: "ready",+ activityToken: "0",+ isReconnectScheduled: false,+ isUserStopping: false,+ sessionId: "sess-1",+ });++ act(() => {+ vi.advanceTimersByTime(120_000);+ });+ expect(reconnect).not.toHaveBeenCalled();+ });++ it("does not fire when the user explicitly stopped", () => {+ const { rerender, reconnect } = setup();++ rerender({+ status: "streaming",+ activityToken: "0",+ isReconnectScheduled: false,+ isUserStopping: true,+ sessionId: "sess-1",+ });++ act(() => {+ vi.advanceTimersByTime(120_000);+ });+ expect(reconnect).not.toHaveBeenCalled();+ });++ it("does not fire without a session id", () => {+ const { rerender, reconnect } = setup();++ rerender({+ status: "streaming",+ activityToken: "0",+ isReconnectScheduled: false,+ isUserStopping: false,+ sessionId: null,+ });++ act(() => {+ vi.advanceTimersByTime(120_000);+ });+ expect(reconnect).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useWakeResync.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useWakeResync.test.tsnew file mode 100644index 0000000000..4f7bcd51fd--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useWakeResync.test.ts@@ -0,0 +1,225 @@+import { cleanup, renderHook } from "@testing-library/react";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+ type Mock,+} from "vitest";++import { useWakeResync } from "../useWakeResync";++type RefetchResult = { data?: unknown };++interface SetupOpts {+ initialSessionId?: string | null;+ refetchResult?: RefetchResult;+ refetchImpl?: () => Promise<RefetchResult>;+ initialMounted?: boolean;+}++function withVisibilityState(state: "visible" | "hidden") {+ Object.defineProperty(document, "visibilityState", {+ configurable: true,+ get: () => state,+ });+}++function fireVisibilityChange() {+ document.dispatchEvent(new Event("visibilitychange"));+}++function setup(opts: SetupOpts = {}) {+ const sessionIdRef = {+ current: "initialSessionId" in opts ? opts.initialSessionId! : "sess-1",+ };+ const isMountedRef = { current: opts.initialMounted ?? true };+ const refetchSession =+ (opts.refetchImpl as Mock<() => Promise<RefetchResult>>) ??+ vi.fn(async () => opts.refetchResult ?? { data: undefined });+ const resumeStream = vi.fn();+ const resumeStreamRef = { current: resumeStream };++ const hook = renderHook(() =>+ useWakeResync({+ sessionIdRef,+ isMountedRef,+ refetchSession,+ resumeStreamRef,+ }),+ );++ return { hook, sessionIdRef, isMountedRef, refetchSession, resumeStream };+}++describe("useWakeResync", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ withVisibilityState("visible");+ });++ afterEach(() => {+ cleanup();+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it("does nothing when there is no session", async () => {+ const { refetchSession } = setup({ initialSessionId: null });++ // Hide → wait long enough → re-show.+ withVisibilityState("hidden");+ fireVisibilityChange();+ vi.advanceTimersByTime(60_000);+ withVisibilityState("visible");+ fireVisibilityChange();++ await vi.runAllTimersAsync();+ expect(refetchSession).not.toHaveBeenCalled();+ });++ it("skips re-sync when the page was hidden for less than the threshold", async () => {+ const { refetchSession } = setup();++ withVisibilityState("hidden");+ fireVisibilityChange();+ vi.advanceTimersByTime(5_000); // < 30s threshold+ withVisibilityState("visible");+ fireVisibilityChange();++ await vi.runAllTimersAsync();+ expect(refetchSession).not.toHaveBeenCalled();+ });++ it("refetches and does not resume when backend has no active stream", async () => {+ const refetchSession = vi.fn(async () => ({+ data: { status: 200, data: { active_stream: null } },+ }));+ const { resumeStream } = setup({ refetchImpl: refetchSession });++ withVisibilityState("hidden");+ fireVisibilityChange();+ vi.advanceTimersByTime(60_000); // > 30s+ withVisibilityState("visible");+ fireVisibilityChange();++ await vi.runAllTimersAsync();+ expect(refetchSession).toHaveBeenCalledTimes(1);+ expect(resumeStream).not.toHaveBeenCalled();+ });++ it("resumes the stream when the refetch reports an active backend stream", async () => {+ const refetchSession = vi.fn(async () => ({+ data: {+ status: 200,+ data: { active_stream: { turn_id: "t1", started_at: "2026-01-01" } },+ },+ }));+ const { resumeStream } = setup({ refetchImpl: refetchSession });++ withVisibilityState("hidden");+ fireVisibilityChange();+ vi.advanceTimersByTime(60_000);+ withVisibilityState("visible");+ fireVisibilityChange();++ await vi.runAllTimersAsync();+ expect(refetchSession).toHaveBeenCalledTimes(1);+ expect(resumeStream).toHaveBeenCalledTimes(1);+ });++ it("does not resume when the session changed during the refetch", async () => {+ let resolveRefetch: (v: RefetchResult) => void = () => {};+ const refetchSession = vi.fn(+ () => new Promise<RefetchResult>((r) => (resolveRefetch = r)),+ );+ const { resumeStream, sessionIdRef } = setup({+ refetchImpl: refetchSession,+ });++ withVisibilityState("hidden");+ fireVisibilityChange();+ vi.advanceTimersByTime(60_000);+ withVisibilityState("visible");+ fireVisibilityChange();++ // Simulate the user navigating to a different session before the+ // refetch resolves.+ sessionIdRef.current = "different-session";+ resolveRefetch({+ data: { status: 200, data: { active_stream: { turn_id: "t1" } } },+ });++ await vi.runAllTimersAsync();+ expect(resumeStream).not.toHaveBeenCalled();+ });++ it("does not resume when the host unmounted during the refetch", async () => {+ let resolveRefetch: (v: RefetchResult) => void = () => {};+ const refetchSession = vi.fn(+ () => new Promise<RefetchResult>((r) => (resolveRefetch = r)),+ );+ const { resumeStream, isMountedRef } = setup({+ refetchImpl: refetchSession,+ });++ withVisibilityState("hidden");+ fireVisibilityChange();+ vi.advanceTimersByTime(60_000);+ withVisibilityState("visible");+ fireVisibilityChange();++ isMountedRef.current = false;+ resolveRefetch({+ data: { status: 200, data: { active_stream: { turn_id: "t1" } } },+ });++ await vi.runAllTimersAsync();+ expect(resumeStream).not.toHaveBeenCalled();+ });++ it("swallows refetch errors and clears isSyncing in finally", async () => {+ const refetchSession = vi.fn(async () => {+ throw new Error("boom");+ });+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const { hook } = setup({ refetchImpl: refetchSession });++ withVisibilityState("hidden");+ fireVisibilityChange();+ vi.advanceTimersByTime(60_000);+ withVisibilityState("visible");+ fireVisibilityChange();++ await vi.runAllTimersAsync();+ expect(refetchSession).toHaveBeenCalledTimes(1);+ expect(warn).toHaveBeenCalled();+ expect(hook.result.current.isSyncing).toBe(false);+ });++ it("only updates the hidden-at timestamp when going to hidden, not visible", async () => {+ const refetchSession = vi.fn(async () => ({ data: undefined }));+ setup({ refetchImpl: refetchSession });++ // Hidden → visible after only 5s: skipped.+ withVisibilityState("hidden");+ fireVisibilityChange();+ vi.advanceTimersByTime(5_000);+ withVisibilityState("visible");+ fireVisibilityChange();+ await vi.runAllTimersAsync();+ expect(refetchSession).not.toHaveBeenCalled();++ // Hidden again → visible after 60s: triggers (NOT 5s + 60s = 65s+ // measured from the FIRST hidden — only the most recent hidden counts).+ withVisibilityState("hidden");+ fireVisibilityChange();+ vi.advanceTimersByTime(60_000);+ withVisibilityState("visible");+ fireVisibilityChange();+ await vi.runAllTimersAsync();+ expect(refetchSession).toHaveBeenCalledTimes(1);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useWorkflowImportAutoSubmit.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useWorkflowImportAutoSubmit.test.tsnew file mode 100644index 0000000000..693e8ad857--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useWorkflowImportAutoSubmit.test.ts@@ -0,0 +1,143 @@+import { cleanup, renderHook, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mockSetInitialPrompt = vi.fn();+vi.mock("../store", () => ({+ useCopilotUIStore: () => ({ setInitialPrompt: mockSetInitialPrompt }),+}));++import { useWorkflowImportAutoSubmit } from "../useWorkflowImportAutoSubmit";++function setLocation(href: string) {+ // happy-dom allows reassigning window.location.href via History API; we+ // can also mutate via URL + replaceState for hash/query coverage.+ const next = new URL(href);+ window.history.replaceState(+ null,+ "",+ `${next.pathname}${next.search}${next.hash}`,+ );+}++describe("useWorkflowImportAutoSubmit", () => {+ beforeEach(() => {+ mockSetInitialPrompt.mockClear();+ sessionStorage.clear();+ setLocation("http://localhost/copilot");+ });++ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ });++ it("does nothing when there is no hash and no sessionStorage prompt", () => {+ const onSend = vi.fn();+ renderHook(() =>+ useWorkflowImportAutoSubmit({ onSend, setPendingFileParts: vi.fn() }),+ );+ expect(onSend).not.toHaveBeenCalled();+ expect(mockSetInitialPrompt).not.toHaveBeenCalled();+ });++ it("populates the initial prompt from a hash without autosubmit", () => {+ setLocation("http://localhost/copilot#prompt=Hello%20world");+ const onSend = vi.fn();+ renderHook(() =>+ useWorkflowImportAutoSubmit({ onSend, setPendingFileParts: vi.fn() }),+ );+ expect(onSend).not.toHaveBeenCalled();+ expect(mockSetInitialPrompt).toHaveBeenCalledWith("Hello world");+ // Hash is cleared after consumption.+ expect(window.location.hash).toBe("");+ });++ it("auto-submits when autosubmit=true is set on the query string", async () => {+ setLocation(+ "http://localhost/copilot?autosubmit=true#prompt=auto%20submit%20me",+ );+ const onSend = vi.fn(async () => {});+ renderHook(() =>+ useWorkflowImportAutoSubmit({ onSend, setPendingFileParts: vi.fn() }),+ );+ await waitFor(() => expect(onSend).toHaveBeenCalledWith("auto submit me"));+ expect(mockSetInitialPrompt).not.toHaveBeenCalled();+ expect(window.location.search).toBe(""); // autosubmit param cleared+ });++ it("falls back to setInitialPrompt when an autosubmit send rejects", async () => {+ setLocation(+ "http://localhost/copilot?autosubmit=true#prompt=auto%20submit%20me",+ );+ const onSend = vi.fn(async () => {+ throw new Error("network down");+ });+ renderHook(() =>+ useWorkflowImportAutoSubmit({ onSend, setPendingFileParts: vi.fn() }),+ );+ await waitFor(() =>+ expect(mockSetInitialPrompt).toHaveBeenCalledWith("auto submit me"),+ );+ });++ it("uses sessionStorage prompt over the hash, including pre-uploaded file part", async () => {+ setLocation("http://localhost/copilot?autosubmit=true#prompt=ignored");+ sessionStorage.setItem("importWorkflowPrompt", "from-storage");+ sessionStorage.setItem(+ "importWorkflowFile",+ JSON.stringify({+ fileId: "11111111-2222-3333-4444-555555555555",+ fileName: "wf.json",+ mimeType: "application/json",+ }),+ );++ const setPendingFileParts = vi.fn();+ const onSend = vi.fn(async () => {});+ renderHook(() =>+ useWorkflowImportAutoSubmit({ onSend, setPendingFileParts }),+ );+ await waitFor(() => expect(onSend).toHaveBeenCalledWith("from-storage"));+ expect(setPendingFileParts).toHaveBeenCalledWith([+ expect.objectContaining({+ type: "file",+ mediaType: "application/json",+ filename: "wf.json",+ }),+ ]);+ expect(sessionStorage.getItem("importWorkflowPrompt")).toBeNull();+ expect(sessionStorage.getItem("importWorkflowFile")).toBeNull();+ });++ it("rejects malformed file ids (not a UUID) and skips the file part", async () => {+ sessionStorage.setItem("importWorkflowPrompt", "with-bad-file");+ sessionStorage.setItem(+ "importWorkflowFile",+ JSON.stringify({+ fileId: "../etc/passwd",+ fileName: "evil",+ mimeType: "application/json",+ }),+ );+ setLocation("http://localhost/copilot?autosubmit=true");+ const setPendingFileParts = vi.fn();+ const onSend = vi.fn(async () => {});+ renderHook(() =>+ useWorkflowImportAutoSubmit({ onSend, setPendingFileParts }),+ );+ await waitFor(() => expect(onSend).toHaveBeenCalled());+ expect(setPendingFileParts).not.toHaveBeenCalled();+ });++ it("skips processing on subsequent renders (only runs once)", () => {+ setLocation("http://localhost/copilot#prompt=run-once");+ const onSend = vi.fn();+ const { rerender } = renderHook(() =>+ useWorkflowImportAutoSubmit({ onSend, setPendingFileParts: vi.fn() }),+ );+ expect(mockSetInitialPrompt).toHaveBeenCalledTimes(1);+ rerender();+ rerender();+ expect(mockSetInitialPrompt).toHaveBeenCalledTimes(1);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsxindex ffad386436..b298586bb0 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx@@ -1,15 +1,24 @@"use client";import { ChatInput } from "@/app/(platform)/copilot/components/ChatInput/ChatInput";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/atoms/Tooltip/BaseTooltip";import { cn } from "@/lib/utils";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { UIDataTypes, UIMessage, UITools } from "ai";import { LayoutGroup, motion } from "framer-motion";-import { useCallback } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { useCopilotUIStore } from "../../store";import type { TurnStatsMap } from "../../helpers/convertChatSessionToUiMessages";import { ChatMessagesContainer } from "../ChatMessagesContainer/ChatMessagesContainer";import { CopilotChatActionsProvider } from "../CopilotChatActionsProvider/CopilotChatActionsProvider";import { EmptySession } from "../EmptySession/EmptySession";+import {+ UsageLimitReachedCard,+ useIsUsageLimitReached,+} from "../UsageLimits/UsageLimitReachedCard";import { useAutoOpenArtifacts } from "./useAutoOpenArtifacts";export interface ChatContainerProps {@@ -22,8 +31,16 @@ export interface ChatContainerProps {isCreatingSession: boolean;/** True when backend has an active stream but we haven't reconnected yet. */isReconnecting?: boolean;- /** True while re-syncing session state after device wake. */- isSyncing?: boolean;+ /** True while reopening an already-running session before stream replay is live. */+ isRestoringActiveSession?: boolean;+ /** Latest backend-emitted status for a replaying assistant while restore is active. */+ restoreStatusMessage?: string | null;+ /** ISO start time of the active backend turn (if any). Seeds the elapsed+ * counter for restored sessions so the UI shows honest turn age. */+ activeStreamStartedAt?: string | null;+ /** True the moment the user clicks Stop — overrides isStreaming so the UI+ * flips immediately regardless of AI SDK's status timing. */+ isUserStopping?: boolean;onCreateSession: () => void | Promise<string>;onSend: (message: string, files?: File[]) => void | Promise<void>;onStop: () => void;@@ -51,7 +68,10 @@ export const ChatContainer = ({isSessionError,isCreatingSession,isReconnecting,- isSyncing,+ isRestoringActiveSession,+ restoreStatusMessage,+ activeStreamStartedAt,+ isUserStopping,onCreateSession,onSend,onStop,@@ -74,14 +94,45 @@ export const ChatContainer = ({useAutoOpenArtifacts({ sessionId });// isStreaming controls the stop-button UI and routes submits to the queue// endpoint — the input itself must NOT be disabled during streaming so users- // can type and queue their next message.- const isStreaming = status === "streaming" || status === "submitted";+ // can type and queue their next message. ``isUserStopping`` force-flips+ // this to ``false`` the instant the user clicks Stop, so the button flips+ // to Send regardless of whether AI SDK's status transition has landed yet.+ const isStreaming =+ !isUserStopping && (status === "streaming" || status === "submitted");// The input is only truly disabled when the session isn't ready at all- // (reconnecting, syncing, loading, or errored) — NOT during normal streaming.- const isInputDisabled =- !!isReconnecting || !!isSyncing || isLoadingSession || !!isSessionError;+ // (reconnecting, loading, or errored) — NOT during normal streaming and NOT+ // during the wake re-sync (background refetch after long visibility-hidden;+ // locking the input there caused users to see a "stuck" disabled input on+ // refocus when the refetch was slow or revealed stale ``active_stream``+ // state from the backend).+ const isSessionUnavailable =+ !!isReconnecting || isLoadingSession || !!isSessionError;+ const isLimitReached = useIsUsageLimitReached();+ const isInputDisabled = isSessionUnavailable || isLimitReached;const inputLayoutId = "copilot-2-chat-input";+ // Measure the usage-limit overlay so the messages scroll area can pad its+ // bottom — otherwise the last message would sit permanently behind the+ // translucent card. Height varies with the card's own content (tier badge,+ // insufficient-credits state, usage-bar layout) so a fixed value would+ // either waste space or clip.+ const usageCardRef = useRef<HTMLDivElement>(null);+ const [usageCardHeight, setUsageCardHeight] = useState(0);+ useEffect(() => {+ if (!isLimitReached) {+ setUsageCardHeight(0);+ return;+ }+ const el = usageCardRef.current;+ if (!el) return;+ const ro = new ResizeObserver((entries) => {+ const height = entries[0]?.contentRect.height ?? 0;+ setUsageCardHeight(height);+ });+ ro.observe(el);+ return () => ro.disconnect();+ }, [isLimitReached]);+// Retry: re-send the last user message (used by ErrorCard on transient errors)const handleRetry = useCallback(() => {const lastUserMsg = [...messages].reverse().find((m) => m.role === "user");@@ -112,6 +163,9 @@ export const ChatContainer = ({status={status}error={error}isLoading={isLoadingSession}+ isRestoringActiveSession={isRestoringActiveSession}+ restoreStatusMessage={restoreStatusMessage}+ activeStreamStartedAt={activeStreamStartedAt}sessionID={sessionId}hasMoreMessages={hasMoreMessages}isLoadingMore={isLoadingMore}@@ -119,6 +173,7 @@ export const ChatContainer = ({onRetry={handleRetry}turnStats={turnStats}queuedMessages={queuedMessages}+ bottomContentPadding={usageCardHeight}/><motion.divinitial={{ opacity: 0 }}@@ -127,19 +182,47 @@ export const ChatContainer = ({className="relative px-3 pb-2 pt-2"><div className="pointer-events-none absolute left-0 right-0 top-[-18px] z-10 h-6 bg-gradient-to-b from-transparent to-[#f8f8f9]" />- <ChatInput- inputId="chat-input-session"- onSend={onSend}- disabled={isInputDisabled}- isStreaming={isStreaming}- isUploadingFiles={isUploadingFiles}- onStop={onStop}- onEnqueue={onEnqueue}- placeholder="What else can I help with?"- droppedFiles={droppedFiles}- onDroppedFilesConsumed={onDroppedFilesConsumed}- hasSession={!!sessionId}- />+ {isLimitReached && (+ <div+ ref={usageCardRef}+ className="pointer-events-none absolute bottom-full left-0 right-0 z-20 mb-2.5 pb-2"+ >+ <div+ aria-hidden="true"+ data-testid="usage-limit-backdrop"+ className="absolute -inset-x-14 -top-20 bottom-[-18px] overflow-hidden rounded-[2rem] bg-[radial-gradient(ellipse_at_center,rgba(248,248,249,0.96)_0%,rgba(248,248,249,0.9)_42%,rgba(248,248,249,0.58)_68%,rgba(248,248,249,0)_100%)] backdrop-blur-lg [mask-image:linear-gradient(to_bottom,transparent_0%,black_26%,black_100%)]"+ >+ <div className="absolute inset-x-10 bottom-0 h-28 rounded-full bg-[#f8f8f9]/80 blur-2xl" />+ <div className="absolute inset-x-16 bottom-8 h-16 rounded-full bg-white/55 blur-xl" />+ </div>+ <div className="pointer-events-auto relative px-3">+ <UsageLimitReachedCard />+ </div>+ </div>+ )}+ <Tooltip open={isLimitReached ? undefined : false}>+ <TooltipTrigger asChild>+ <div>+ <ChatInput+ inputId="chat-input-session"+ onSend={onSend}+ disabled={isInputDisabled}+ isStreaming={isStreaming}+ isUploadingFiles={isUploadingFiles}+ onStop={onStop}+ onEnqueue={onEnqueue}+ placeholder="What else can I help with?"+ droppedFiles={droppedFiles}+ onDroppedFilesConsumed={onDroppedFilesConsumed}+ hasSession={!!sessionId}+ />+ </div>+ </TooltipTrigger>+ <TooltipContent side="top" className="max-w-sm">+ You've reached your usage limit. Reset your daily limit+ or wait for it to refresh before sending more messages.+ </TooltipContent>+ </Tooltip></motion.div></div>) : (diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsxnew file mode 100644index 0000000000..ff2e41a29c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx@@ -0,0 +1,172 @@+import React from "react";+import { render, screen, cleanup } from "@/tests/integrations/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ChatContainer } from "../ChatContainer";++const mockIsUsageLimitReached = vi.fn();+const mockArtifactsEnabled = vi.fn(() => false);+const mockArtifactPanelOpen = vi.fn(() => false);++vi.mock("framer-motion", () => ({+ LayoutGroup: ({ children }: { children: React.ReactNode }) => <>{children}</>,+ motion: {+ div: React.forwardRef(function MotionDiv(+ props: Record<string, unknown>,+ ref: React.Ref<HTMLDivElement>,+ ) {+ const {+ children,+ initial: _initial,+ animate: _animate,+ transition: _transition,+ ...rest+ } = props as {+ children?: React.ReactNode;+ initial?: unknown;+ animate?: unknown;+ transition?: unknown;+ [key: string]: unknown;+ };++ return (+ <div ref={ref} {...rest}>+ {children}+ </div>+ );+ }),+ },+}));++vi.mock("@/app/(platform)/copilot/components/ChatInput/ChatInput", () => ({+ ChatInput: () => <div data-testid="chat-input" />,+}));++vi.mock("@/components/atoms/Tooltip/BaseTooltip", () => ({+ TooltipProvider: ({ children }: { children: React.ReactNode }) => (+ <>{children}</>+ ),+ Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,+ TooltipContent: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+ TooltipTrigger: ({ children }: { children: React.ReactNode }) => (+ <>{children}</>+ ),+}));++vi.mock("@/services/feature-flags/use-get-flag", () => ({+ Flag: {+ ARTIFACTS: "ARTIFACTS",+ },+ useGetFlag: () => mockArtifactsEnabled(),+}));++vi.mock("../../../store", () => ({+ useCopilotUIStore: (+ selector?: (state: { artifactPanel: { isOpen: boolean } }) => unknown,+ ) => {+ const state = { artifactPanel: { isOpen: mockArtifactPanelOpen() } };+ return typeof selector === "function" ? selector(state) : state;+ },+}));++vi.mock("../useAutoOpenArtifacts", () => ({+ useAutoOpenArtifacts: vi.fn(),+}));++vi.mock("../../ChatMessagesContainer/ChatMessagesContainer", () => ({+ ChatMessagesContainer: ({+ bottomContentPadding,+ }: {+ bottomContentPadding?: number;+ }) => (+ <div+ data-testid="chat-messages-container"+ data-bottom-padding={bottomContentPadding ?? 0}+ />+ ),+}));++vi.mock("../../CopilotChatActionsProvider/CopilotChatActionsProvider", () => ({+ CopilotChatActionsProvider: ({ children }: { children: React.ReactNode }) => (+ <>{children}</>+ ),+}));++vi.mock("../../EmptySession/EmptySession", () => ({+ EmptySession: () => <div data-testid="empty-session" />,+}));++vi.mock("../../UsageLimits/UsageLimitReachedCard", () => ({+ useIsUsageLimitReached: () => mockIsUsageLimitReached(),+ UsageLimitReachedCard: () => <div role="alert">Usage limit reached</div>,+}));++class MockResizeObserver {+ observe() {}+ disconnect() {}+ unobserve() {}+}++const baseProps = {+ messages: [] as never[],+ status: "ready",+ error: undefined,+ sessionId: "session-123",+ isLoadingSession: false,+ isSessionError: false,+ isCreatingSession: false,+ isReconnecting: false,+ isRestoringActiveSession: false,+ restoreStatusMessage: null,+ activeStreamStartedAt: null,+ isUserStopping: false,+ isSyncing: false,+ onCreateSession: vi.fn(),+ onSend: vi.fn(),+ onStop: vi.fn(),+ onEnqueue: vi.fn(),+ queuedMessages: [],+ isUploadingFiles: false,+ hasMoreMessages: false,+ isLoadingMore: false,+ onLoadMore: vi.fn(),+ droppedFiles: [],+ onDroppedFilesConsumed: vi.fn(),+ historicalDurations: new Map<string, number>(),+};++describe("ChatContainer", () => {+ beforeEach(() => {+ mockIsUsageLimitReached.mockReturnValue(false);+ mockArtifactsEnabled.mockReturnValue(false);+ mockArtifactPanelOpen.mockReturnValue(false);+ vi.stubGlobal("ResizeObserver", MockResizeObserver);+ });++ afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ vi.unstubAllGlobals();+ });++ it("renders the blurred usage-limit backdrop only when the limit is reached", () => {+ mockIsUsageLimitReached.mockReturnValue(true);++ render(<ChatContainer {...baseProps} />);++ const backdrop = screen.getByTestId("usage-limit-backdrop");++ expect(screen.getByRole("alert")).toBeDefined();+ expect(backdrop.className).toContain("backdrop-blur-lg");+ expect(backdrop.className).toContain("[mask-image:linear-gradient");+ expect(backdrop.className).toContain("radial-gradient");+ });++ it("does not render the usage-limit backdrop while usage is still available", () => {+ render(<ChatContainer {...baseProps} />);++ expect(screen.queryByTestId("usage-limit-backdrop")).toBeNull();+ expect(screen.queryByRole("alert")).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsxindex 95066cfc9d..fee25162a1 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx@@ -10,7 +10,7 @@ import { toast } from "@/components/molecules/Toast/use-toast";import { InputGroup } from "@/components/ui/input-group";import { cn } from "@/lib/utils";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";-import { Tray } from "@phosphor-icons/react";+import { ArrowUpIcon } from "@phosphor-icons/react";import { ChangeEvent, useEffect, useState } from "react";import { AttachmentMenu } from "./components/AttachmentMenu";import { DryRunToggleButton } from "./components/DryRunToggleButton";@@ -271,6 +271,7 @@ export function ChatInput({<PromptInputButtonaria-label="Queue message"tooltip="Queue message"+ variant="default"disabled={isEnqueueing}onClick={async () => {if (isEnqueueing) return;@@ -285,9 +286,9 @@ export function ChatInput({}}}}- className="size-[2.625rem] rounded-full border-zinc-800 bg-zinc-800 text-white hover:border-zinc-900 hover:bg-zinc-900"+ className="size-[2.625rem] rounded-full border-zinc-800 bg-zinc-800 text-white hover:border-zinc-900 hover:bg-zinc-900 disabled:border-zinc-200 disabled:bg-zinc-200 disabled:text-white disabled:opacity-100">- <Tray className="size-4" weight="bold" />+ <ArrowUpIcon className="size-4" weight="bold" /></PromptInputButton>)}{isStreaming ? (diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatInput.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatInput.test.tsindex 259c215a26..5f2b8d87cb 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatInput.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/useChatInput.test.ts@@ -1,4 +1,4 @@-import { renderHook, act } from "@testing-library/react";+import { renderHook, act, waitFor } from "@testing-library/react";import { describe, expect, it, vi, beforeEach } from "vitest";import { useChatInput } from "../useChatInput";@@ -42,6 +42,30 @@ describe("useChatInput", () => {expect(result.current.value).toBe("");});+ it("submits the live form value when React state has not caught up", async () => {+ const { result } = renderHook(() => useChatInput({ onSend: mockOnSend }));+ const form = document.createElement("form");+ const textarea = document.createElement("textarea");+ textarea.name = "message";+ textarea.value = " visible textarea value ";+ form.append(textarea);++ act(() => {+ result.current.setValue("");+ });++ act(() => {+ result.current.handleSubmit({+ preventDefault: vi.fn(),+ currentTarget: form,+ } as unknown as Parameters<typeof result.current.handleSubmit>[0]);+ });++ await waitFor(() => {+ expect(mockOnSend).toHaveBeenCalledWith("visible textarea value");+ });+ });+it("does not send when disabled", async () => {const { result } = renderHook(() =>useChatInput({ onSend: mockOnSend, disabled: true }),diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.tsindex 92e965900b..5f9b8dcbdd 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatInput.ts@@ -48,14 +48,15 @@ export function useChatInput({[disabled, inputId],);- async function handleSend() {- if (disabled || isSending || (!value.trim() && !canSendEmpty)) return;+ async function handleSend(message = value) {+ const trimmedMessage = message.trim();+ if (disabled || isSending || (!trimmedMessage && !canSendEmpty)) return;if (isSubmittingRef.current) return;isSubmittingRef.current = true;setIsSending(true);try {- await onSend(value.trim());+ await onSend(trimmedMessage);setValue("");} finally {isSubmittingRef.current = false;@@ -65,7 +66,9 @@ export function useChatInput({function handleSubmit(e: FormEvent<HTMLFormElement>) {e.preventDefault();- void handleSend();+ const formData = new FormData(e.currentTarget);+ const message = formData.get("message");+ void handleSend(typeof message === "string" ? message : value);}function handleChange(e: ChangeEvent<HTMLTextAreaElement>) {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsxindex 2fe7be8ee5..eea82b08a4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx@@ -28,6 +28,7 @@ import {parseSpecialMarkers,splitReasoningAndResponse,} from "./helpers";+import { RESTORE_STALL_TIMEOUT_MS } from "../../restoreConstants";import { AssistantMessageActions } from "./components/AssistantMessageActions";import { CopyButton } from "./components/CopyButton";import { CollapsedToolGroup } from "./components/CollapsedToolGroup";@@ -41,6 +42,12 @@ interface Props {status: string;error: Error | undefined;isLoading: boolean;+ isRestoringActiveSession?: boolean;+ restoreStatusMessage?: string | null;+ /** ISO start time of the active backend turn. Seeds the elapsed-time+ * counter so restored turns show honest age instead of counting from+ * zero on every fresh mount. */+ activeStreamStartedAt?: string | null;sessionID?: string | null;hasMoreMessages?: boolean;isLoadingMore?: boolean;@@ -49,6 +56,10 @@ interface Props {turnStats?: TurnStatsMap;/** Pending queued messages waiting to be injected, shown at the end of chat. */queuedMessages?: string[];+ /** Extra bottom padding (px) applied to the scrollable message list so+ * overlays pinned above the input area (e.g. the usage-limit card) can+ * sit over the last message without permanently obscuring it. */+ bottomContentPadding?: number;}function renderSegments(@@ -252,6 +263,9 @@ export function ChatMessagesContainer({status,error,isLoading,+ isRestoringActiveSession,+ restoreStatusMessage,+ activeStreamStartedAt,sessionID,hasMoreMessages,isLoadingMore,@@ -259,6 +273,7 @@ export function ChatMessagesContainer({onRetry,turnStats,queuedMessages,+ bottomContentPadding,}: Props) {// Hide the container for one frame when messages first load so// StickToBottom can scroll to the bottom before the user sees it.@@ -282,7 +297,12 @@ export function ChatMessagesContainer({const hasInflight = (() => {if (lastMessage?.role !== "assistant") return false;- const parts = lastMessage.parts;+ // Ignore bookkeeping parts. data-cursor is legacy resume metadata and+ // data-status is transient copy for the Thinking indicator; neither+ // counts as "real" content that hides the indicator.+ const parts = lastMessage.parts.filter(+ (p) => p.type !== "data-cursor" && p.type !== "data-status",+ );if (parts.length === 0) return false;const lastPart = parts[parts.length - 1];@@ -290,6 +310,18 @@ export function ChatMessagesContainer({if (lastPart.type === "text" && lastPart.text.trim().length > 0)return true;+ // Reasoning chunks stream before the final text — while they have+ // rendered content, the "Thinking..." indicator should give way to the+ // reasoning view (e.g. Perplexity deep research streams minutes of+ // reasoning before any answer text).+ if (lastPart.type === "reasoning" && lastPart.text.trim().length > 0)+ return true;++ // step-start is a turn boundary emitted right before the next tool or+ // text chunk. Treat it as inflight so the bubble transitions straight+ // into the next part without flashing back to "Thinking...".+ if (lastPart.type === "step-start") return true;+if (lastPart.type.startsWith(TOOL_PART_PREFIX) &&"state" in lastPart &&@@ -301,31 +333,59 @@ export function ChatMessagesContainer({return false;})();- const showThinking =- status === "submitted" || (status === "streaming" && !hasInflight);-- const isActivelyStreaming = status === "streaming" || status === "submitted";-- // Anchor the live "Thinking Xs" counter to the latest server timestamp- // within the current turn. Messages arrive in chronological order, so- // the first createdAt we hit walking backwards IS the latest one. Stop- // at the user-message boundary so a fresh send (where the user's just-- // optimistic message isn't in turnStats yet) doesn't fall back to the- // previous turn's assistant 30s+ in the past.- const liveAnchorIso = useMemo(() => {- if (!turnStats) return null;- for (let i = messages.length - 1; i >= 0; i--) {- const iso = turnStats.get(messages[i].id)?.createdAt;- if (iso) return iso;- if (messages[i].role === "user") return null;+ // Surface the latest `data-status` message from the live assistant when+ // the Thinking indicator is up — but only if it wasn't invalidated by a+ // more recent content part (in which case the model has moved on and the+ // status is stale).+ const latestStatusMessage = (() => {+ if (lastMessage?.role !== "assistant") return null;+ for (let i = lastMessage.parts.length - 1; i >= 0; i--) {+ const part = lastMessage.parts[i];+ if (part.type === "data-cursor") continue;+ if (part.type === "data-status") {+ const data = (part as { data?: { message?: unknown } }).data;+ return typeof data?.message === "string" ? data.message : null;+ }+ // Any other part = the model has produced output past the status.+ return null;}return null;- }, [messages, turnStats]);+ })();+ // Suppressed during active-session restore so the ThinkingIndicator and+ // the "Retrieving latest messages" spinner can't both render — the+ // restore spinner wins until real content arrives (see the+ // ``hasConnectedThisMountRef`` latch in useCopilotStream for why).+ const showThinking =+ !isRestoringActiveSession &&+ (status === "submitted" || (status === "streaming" && !hasInflight));+ const isActivelyStreaming = status === "streaming" || status === "submitted";const { elapsedSeconds } = useElapsedTimer(isActivelyStreaming,- liveAnchorIso,+ activeStreamStartedAt,);+ const indicator = (+ <ThinkingIndicator+ active={showThinking}+ elapsedSeconds={elapsedSeconds}+ statusMessage={latestStatusMessage}+ />+ );+ const showIndicator = showThinking;+ const [showRestoreFallback, setShowRestoreFallback] = useState(false);+ useEffect(() => {+ if (!isRestoringActiveSession) {+ setShowRestoreFallback(false);+ return;+ }+ const timer = setTimeout(+ () => setShowRestoreFallback(true),+ RESTORE_STALL_TIMEOUT_MS,+ );+ return () => clearTimeout(timer);+ }, [isRestoringActiveSession]);+ const { elapsedSeconds: restoreElapsedSeconds } =+ useElapsedTimer(showRestoreFallback);// Freeze elapsed time when streaming ends so TurnStatsBar shows the final value.// Reset when a new streaming turn begins.@@ -354,7 +414,14 @@ export function ChatMessagesContainer({: "opacity-100 transition-opacity duration-100 ease-out")}>- <ConversationContent className="flex min-h-full flex-1 flex-col gap-6 px-3 py-6">+ <ConversationContent+ className="flex min-h-full flex-1 flex-col gap-6 px-3 py-6"+ style={+ bottomContentPadding+ ? { paddingBottom: bottomContentPadding + 24 }+ : undefined+ }+ >{hasMoreMessages && onLoadMore && (<LoadMoreSentinelhasMore={hasMoreMessages}@@ -363,7 +430,7 @@ export function ChatMessagesContainer({onLoadMore={onLoadMore}/>)}- {isLoading && messages.length === 0 && (+ {isLoading && messages.length === 0 && !isRestoringActiveSession && (<div className="flex flex-1 items-center justify-center"><LoadingSpinner className="text-neutral-600" /></div>@@ -384,7 +451,13 @@ export function ChatMessagesContainer({isAssistant &&messageIndex <= messages.length - 1 &&(!nextMessage || nextMessage.role === "user");- const textParts = message.parts.filter(+ // data-cursor / data-status parts are internal bookkeeping —+ // strip them before any render/split logic so they never reach+ // the user UI. data-status surfaces via ThinkingIndicator.+ const renderableParts = message.parts.filter(+ (p) => p.type !== "data-cursor" && p.type !== "data-status",+ );+ const textParts = renderableParts.filter((p): p is Extract<typeof p, { type: "text" }> => p.type === "text",);const lastTextPart = textParts[textParts.length - 1];@@ -400,7 +473,7 @@ export function ChatMessagesContainer({textParts.length > 0 &&!hasErrorMarker;- const fileParts = message.parts.filter(+ const fileParts = renderableParts.filter((p): p is FileUIPart => p.type === "file",);@@ -409,13 +482,13 @@ export function ChatMessagesContainer({const isFinalized =message.role === "assistant" && !isCurrentlyStreaming;const { reasoning, response } = isFinalized- ? splitReasoningAndResponse(message.parts)- : { reasoning: [] as MessagePart[], response: message.parts };+ ? splitReasoningAndResponse(renderableParts)+ : { reasoning: [] as MessagePart[], response: renderableParts };const hasReasoning = reasoning.length > 0;// Note: when interactive tools are pinned from reasoning into response,// this index approximates their position (used only for React keys).- const responseStartIndex = message.parts.length - response.length;+ const responseStartIndex = renderableParts.length - response.length;const responseSegments =message.role === "assistant"? buildRenderSegments(response, responseStartIndex)@@ -445,7 +518,7 @@ export function ChatMessagesContainer({message.id,isLastAssistant ? onRetry : undefined,)- : message.parts.map((part, i) => (+ : renderableParts.map((part, i) => (<MessagePartRendererkey={`${message.id}-${i}`}part={part}@@ -465,12 +538,7 @@ export function ChatMessagesContainer({stats={turnStats?.get(message.id)}/>)}- {isLastAssistant && showThinking && (- <ThinkingIndicator- active={showThinking}- elapsedSeconds={elapsedSeconds}- />- )}+ {isLastAssistant && showIndicator && indicator}</MessageContent>{message.role === "user" && textParts.length > 0 && (<MessageActions className="mt-1 items-center justify-end gap-2 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100">@@ -506,13 +574,35 @@ export function ChatMessagesContainer({</Message>);})}- {showThinking && lastMessage?.role !== "assistant" && (+ {showIndicator && lastMessage?.role !== "assistant" && (<Message from="assistant"><MessageContent className="text-[1rem] leading-relaxed">- <ThinkingIndicator- active={showThinking}- elapsedSeconds={elapsedSeconds}- />+ {indicator}+ </MessageContent>+ </Message>+ )}+ {isRestoringActiveSession && (+ <Message from="assistant">+ <MessageContent className="text-[1rem] leading-relaxed text-slate-900">+ {showRestoreFallback ? (+ <div className="flex flex-col gap-1 text-sm text-slate-500">+ <ThinkingIndicator+ active+ elapsedSeconds={restoreElapsedSeconds}+ statusMessage={+ restoreStatusMessage ?? "Reconnecting to live stream..."+ }+ />+ <span className="pl-6 text-xs text-slate-400">+ Still syncing the latest progress.+ </span>+ </div>+ ) : (+ <div className="flex items-center gap-2 text-sm text-slate-500">+ <LoadingSpinner className="h-4 w-4 text-neutral-500" />+ <span>Retrieving latest messages</span>+ </div>+ )}</MessageContent></Message>)}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsxindex 7b4ca811b0..1961c9be63 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx@@ -1,3 +1,4 @@+import { act } from "@testing-library/react";import { render, screen, cleanup } from "@/tests/integrations/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { ChatMessagesContainer } from "../ChatMessagesContainer";@@ -71,7 +72,9 @@ vi.mock("../components/ReasoningCollapse", () => ({ReasoningCollapse: () => null,}));vi.mock("../components/ThinkingIndicator", () => ({- ThinkingIndicator: () => null,+ ThinkingIndicator: ({ statusMessage }: { statusMessage?: string | null }) => (+ <div data-testid="thinking-indicator">{statusMessage ?? "thinking"}</div>+ ),}));vi.mock("../../JobStatsBar/TurnStatsBar", () => ({TurnStatsBar: () => null,@@ -204,6 +207,7 @@ describe("ChatMessagesContainer — queuedMessages", () => {describe("ChatMessagesContainer — loading", () => {beforeEach(() => {+ vi.useFakeTimers();mockScrollEl.scrollHeight = 100;mockScrollEl.scrollTop = 0;mockScrollEl.clientHeight = 500;@@ -212,6 +216,7 @@ describe("ChatMessagesContainer — loading", () => {});afterEach(() => {+ vi.useRealTimers();cleanup();vi.unstubAllGlobals();});@@ -225,6 +230,78 @@ describe("ChatMessagesContainer — loading", () => {render(<ChatMessagesContainer {...baseProps} isLoading={false} />);expect(screen.queryByTestId("loading-spinner")).toBeNull();});++ it("shows the restore message instead of stale tail content during active-session resume", () => {+ render(+ <ChatMessagesContainer+ {...baseProps}+ isLoading={false}+ isRestoringActiveSession+ messages={[+ {+ id: "user-1",+ role: "user",+ parts: [{ type: "text", text: "Investigate this" }],+ },+ ]}+ />,+ );++ expect(screen.getByTestId("message-user")).toBeDefined();+ expect(screen.getByText("Retrieving latest messages")).toBeDefined();+ });++ it("shows a reconnecting fallback after 6 seconds of restore", () => {+ render(+ <ChatMessagesContainer+ {...baseProps}+ isLoading={false}+ isRestoringActiveSession+ activeStreamStartedAt="2026-04-23T15:00:00.000Z"+ messages={[+ {+ id: "user-1",+ role: "user",+ parts: [{ type: "text", text: "Investigate this" }],+ },+ ]}+ />,+ );++ act(() => {+ vi.advanceTimersByTime(6_000);+ });++ expect(screen.getByTestId("thinking-indicator")).toBeDefined();+ expect(screen.getByText("Reconnecting to live stream...")).toBeDefined();+ expect(+ screen.getByText("Still syncing the latest progress."),+ ).toBeDefined();+ });++ it("prefers the backend status message in the restore fallback", () => {+ render(+ <ChatMessagesContainer+ {...baseProps}+ isLoading={false}+ isRestoringActiveSession+ restoreStatusMessage="Analyzing result..."+ messages={[+ {+ id: "user-1",+ role: "user",+ parts: [{ type: "text", text: "Investigate this" }],+ },+ ]}+ />,+ );++ act(() => {+ vi.advanceTimersByTime(6_000);+ });++ expect(screen.getByText("Analyzing result...")).toBeDefined();+ });});// ── pagination sentinel ───────────────────────────────────────────────────diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ReasoningCollapse.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ReasoningCollapse.tsxindex ce2ce37045..6e2e8b4b2d 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ReasoningCollapse.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ReasoningCollapse.tsx@@ -1,38 +1,31 @@"use client";-import { CaretRightIcon, LightbulbIcon } from "@phosphor-icons/react";-import { useState } from "react";+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+} from "@/components/molecules/Accordion/Accordion";+import { LightbulbIcon } from "@phosphor-icons/react";interface Props {children: React.ReactNode;}export function ReasoningCollapse({ children }: Props) {- const [open, setOpen] = useState(false);-return (- <div className="my-1">- <button- type="button"- onClick={() => setOpen((o) => !o)}- aria-expanded={open}- className="flex items-center gap-1 text-xs text-zinc-500 transition-colors hover:text-zinc-700"- >- <CaretRightIcon- size={10}- weight="bold"- className={- "transition-transform duration-150 " + (open ? "rotate-90" : "")- }- />- <LightbulbIcon size={12} weight="bold" />- <span>{open ? "Hide reasoning" : "Show reasoning"}</span>- </button>- {open && (- <div className="mt-1 space-y-1 border-l-2 border-zinc-200 pl-3">+ <Accordion type="single" collapsible className="my-1">+ <AccordionItem value="reasoning" className="border-none">+ <AccordionTrigger className="justify-start gap-1.5 py-1 text-xs font-medium text-zinc-500 hover:no-underline">+ <span className="flex items-center gap-1.5">+ <LightbulbIcon size={14} weight="bold" className="shrink-0" />+ Reasoning+ </span>+ </AccordionTrigger>+ <AccordionContent className="pb-1 pl-5 pt-0 text-xs text-zinc-500 [&_pre]:m-0 [&_pre]:whitespace-pre-wrap [&_pre]:bg-transparent [&_pre]:p-0 [&_pre]:text-xs [&_pre]:text-zinc-500">{children}- </div>- )}- </div>+ </AccordionContent>+ </AccordionItem>+ </Accordion>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThinkingIndicator.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThinkingIndicator.tsxindex 99d4ef75b6..fb1ee8191a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThinkingIndicator.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ThinkingIndicator.tsx@@ -77,21 +77,34 @@ function useCyclingPhrase(active: boolean) {interface Props {active: boolean;elapsedSeconds: number;+ /**+ * Backend-emitted status message for the current silent gap (e.g.+ * "Contacting the model…", "Analyzing result…", "Optimizing conversation+ * context…"). When provided, it replaces the rotating generic phrase so+ * the user sees what's actually happening instead of a placeholder.+ */+ statusMessage?: string | null;}-export function ThinkingIndicator({ active, elapsedSeconds }: Props) {+export function ThinkingIndicator({+ active,+ elapsedSeconds,+ statusMessage,+}: Props) {const { phrase, visible } = useCyclingPhrase(active);const showTime = active && elapsedSeconds >= SHOW_TIME_AFTER_SECONDS;+ const displayText = statusMessage || phrase;+ const transitionOpacity = statusMessage ? 1 : visible ? 1 : 0;return (<span className="inline-flex items-center gap-1.5 text-neutral-500"><ScaleLoader size={16} /><spanclassName="transition-opacity duration-300"- style={{ opacity: visible ? 1 : 0 }}+ style={{ opacity: transitionOpacity }}><span className="animate-pulse [animation-duration:1.5s]">- {phrase}+ {displayText}</span></span>{showTime && (diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ReasoningCollapse.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ReasoningCollapse.test.tsxindex 5dac2d0541..3eaa27341d 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ReasoningCollapse.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ReasoningCollapse.test.tsx@@ -1,12 +1,11 @@-import { afterEach, describe, expect, it, vi } from "vitest";import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";import { ReasoningCollapse } from "../ReasoningCollapse";vi.mock("@phosphor-icons/react", () => ({- CaretRightIcon: ({ className }: { className?: string }) => (- <span data-testid="caret" className={className} />+ LightbulbIcon: ({ className }: { className?: string }) => (+ <span data-testid="reasoning-icon" className={className} />),- LightbulbIcon: () => <span data-testid="lightbulb" />,}));describe("ReasoningCollapse", () => {@@ -14,61 +13,28 @@ describe("ReasoningCollapse", () => {cleanup();});- it("starts collapsed with 'Show reasoning' and no children in the DOM", () => {- render(- <ReasoningCollapse>- <div data-testid="reasoning-body">secret thoughts</div>- </ReasoningCollapse>,- );-- expect(screen.getByText("Show reasoning")).toBeDefined();- expect(screen.queryByTestId("reasoning-body")).toBeNull();- const trigger = screen.getByRole("button");- expect(trigger.getAttribute("aria-expanded")).toBe("false");- });-- it("expands on click: toggles label and reveals children", () => {+ it("renders a collapsed 'Reasoning' trigger with a bulb icon", () => {render(<ReasoningCollapse>- <div data-testid="reasoning-body">secret thoughts</div>+ <span data-testid="reasoning-body">secret thoughts</span></ReasoningCollapse>,);- const trigger = screen.getByRole("button");- fireEvent.click(trigger);-- expect(screen.getByText("Hide reasoning")).toBeDefined();- expect(screen.getByTestId("reasoning-body")).toBeDefined();- expect(trigger.getAttribute("aria-expanded")).toBe("true");- });-- it("collapses again on a second click", () => {- render(- <ReasoningCollapse>- <div data-testid="reasoning-body">secret thoughts</div>- </ReasoningCollapse>,- );-- const trigger = screen.getByRole("button");- fireEvent.click(trigger);- fireEvent.click(trigger);-- expect(screen.getByText("Show reasoning")).toBeDefined();+ expect(screen.getByRole("button", { name: /reasoning/i })).toBeDefined();+ expect(screen.getByTestId("reasoning-icon")).toBeDefined();+ // Collapsed by default: content should not be visible.expect(screen.queryByTestId("reasoning-body")).toBeNull();- expect(trigger.getAttribute("aria-expanded")).toBe("false");});- it("applies the rotate-90 caret class only when expanded", () => {+ it("reveals the reasoning body when the trigger is clicked", async () => {render(<ReasoningCollapse>- <div>body</div>+ <span data-testid="reasoning-body">secret thoughts</span></ReasoningCollapse>,);- const caret = screen.getByTestId("caret");- expect(caret.className).not.toContain("rotate-90");+ fireEvent.click(screen.getByRole("button", { name: /reasoning/i }));- fireEvent.click(screen.getByRole("button"));- expect(screen.getByTestId("caret").className).toContain("rotate-90");+ expect(await screen.findByTestId("reasoning-body")).toBeDefined();});});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.test.tsindex 82b132fc66..bf64d0e88f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.test.ts@@ -2,9 +2,46 @@ import { describe, expect, it } from "vitest";import {extractWorkspaceArtifacts,filePartToArtifactRef,+ isReasoningToolPart,splitReasoningAndResponse,- type MessagePart,} from "./helpers";+import type { MessagePart } from "./helpers";++function textPart(text: string): MessagePart {+ return { type: "text", text } as MessagePart;+}++function reasoningPart(text: string): MessagePart {+ return { type: "reasoning", text, state: "done" } as MessagePart;+}++function toolPart(+ toolName: string,+ state: string = "output-available",+): MessagePart {+ return {+ type: `tool-${toolName}`,+ state,+ toolCallId: `call-${toolName}`,+ toolName,+ args: {},+ output: "{}",+ } as unknown as MessagePart;+}++function interactiveToolPart(+ toolName: string,+ responseType: string,+): MessagePart {+ return {+ type: `tool-${toolName}`,+ state: "output-available",+ toolCallId: `call-${toolName}`,+ toolName,+ args: {},+ output: { type: responseType },+ } as unknown as MessagePart;+}describe("extractWorkspaceArtifacts", () => {it("extracts a single workspace:// link with its markdown title", () => {@@ -107,40 +144,233 @@ describe("filePartToArtifactRef", () => {});});+describe("isReasoningToolPart", () => {+ it("returns true for reasoning/search tools", () => {+ const reasoningTools = [+ "find_block",+ "find_agent",+ "find_library_agent",+ "search_docs",+ "get_doc_page",+ "search_feature_requests",+ "ask_question",+ ];+ for (const name of reasoningTools) {+ expect(isReasoningToolPart(toolPart(name))).toBe(true);+ }+ });++ it("returns false for action tools", () => {+ const actionTools = [+ "run_block",+ "run_agent",+ "create_agent",+ "edit_agent",+ "run_mcp_tool",+ "schedule_agent",+ "continue_run_block",+ ];+ for (const name of actionTools) {+ expect(isReasoningToolPart(toolPart(name))).toBe(false);+ }+ });++ it("returns false for text parts", () => {+ expect(isReasoningToolPart(textPart("hello"))).toBe(false);+ });+});+describe("splitReasoningAndResponse", () => {- const reasoning: MessagePart = {- type: "reasoning",- text: "thinking...",- state: "done",- } as unknown as MessagePart;- const text: MessagePart = {- type: "text",- text: "final answer",- state: "done",- } as unknown as MessagePart;- const tool: MessagePart = {- type: "tool-run_block",- toolCallId: "t1",- state: "output-available",- input: {},- output: "ok",- } as unknown as MessagePart;+ it("returns all parts as response when there are no tools", () => {+ const parts = [textPart("Hello"), textPart("World")];+ const result = splitReasoningAndResponse(parts);+ expect(result.reasoning).toEqual([]);+ expect(result.response).toEqual(parts);+ });++ it("splits on reasoning tools — text before goes to reasoning", () => {+ const parts = [+ textPart("Let me search..."),+ toolPart("find_block"),+ textPart("Here is your answer"),+ ];+ const result = splitReasoningAndResponse(parts);+ expect(result.reasoning).toHaveLength(2);+ expect(result.response).toHaveLength(1);+ expect((result.response[0] as { text: string }).text).toBe(+ "Here is your answer",+ );+ });++ it("does NOT split on action tools — response before run_block stays visible", () => {+ const parts = [+ textPart("Here is my answer"),+ toolPart("run_block"),+ textPart("Block finished"),+ ];+ const result = splitReasoningAndResponse(parts);+ expect(result.reasoning).toEqual([]);+ expect(result.response).toEqual(parts);+ });- it("returns empty reasoning when there are no tool parts", () => {- const out = splitReasoningAndResponse([reasoning, text]);- expect(out.reasoning).toEqual([]);- expect(out.response).toEqual([reasoning, text]);+ it("splits only on reasoning tools when both reasoning and action tools are present", () => {+ const parts = [+ textPart("Planning..."),+ toolPart("search_docs"),+ textPart("Found it. Running now."),+ toolPart("run_block"),+ textPart("Done!"),+ ];+ const result = splitReasoningAndResponse(parts);+ expect(result.reasoning).toHaveLength(2);+ expect(result.response).toHaveLength(3);+ expect((result.response[0] as { text: string }).text).toBe(+ "Found it. Running now.",+ );+ });++ it("returns all as response when reasoning tools have no text after them", () => {+ const parts = [+ textPart("Hello"),+ toolPart("find_agent"),+ toolPart("run_block"),+ ];+ const result = splitReasoningAndResponse(parts);+ expect(result.reasoning).toEqual([]);+ expect(result.response).toEqual(parts);+ });++ it("handles multiple reasoning tools correctly", () => {+ const parts = [+ textPart("Searching..."),+ toolPart("find_block"),+ textPart("Found one, searching more..."),+ toolPart("search_docs"),+ textPart("Here are the results"),+ ];+ const result = splitReasoningAndResponse(parts);+ expect(result.reasoning).toHaveLength(4);+ expect(result.response).toHaveLength(1);+ expect((result.response[0] as { text: string }).text).toBe(+ "Here are the results",+ );+ });++ it("handles action tool after response text without hiding the response", () => {+ const parts = [+ toolPart("find_block"),+ textPart("I found it! Let me run it."),+ toolPart("run_agent"),+ ];+ const result = splitReasoningAndResponse(parts);+ expect(result.reasoning).toHaveLength(1);+ expect(result.response).toHaveLength(2);+ expect((result.response[0] as { text: string }).text).toBe(+ "I found it! Let me run it.",+ );+ });++ it("returns empty arrays for an empty parts list", () => {+ const result = splitReasoningAndResponse([]);+ expect(result.reasoning).toEqual([]);+ expect(result.response).toEqual([]);+ });++ it("pins interactive reasoning tools into the response (object output)", () => {+ const askQuestion = interactiveToolPart(+ "ask_question",+ "input_validation_error",+ );+ const parts = [+ textPart("Let me check..."),+ askQuestion,+ textPart("Here's the result"),+ ];+ const result = splitReasoningAndResponse(parts);+ // Non-interactive reasoning (the text) stays in reasoning; the interactive+ // tool is pinned to the front of the response so it remains visible.+ expect(result.reasoning).toEqual([parts[0]]);+ expect(result.response).toHaveLength(2);+ expect(result.response[0]).toBe(askQuestion);+ expect((result.response[1] as { text: string }).text).toBe(+ "Here's the result",+ );+ });++ it("pins interactive reasoning tools even when output is a JSON string", () => {+ const askQuestion = {+ type: "tool-ask_question",+ state: "output-available",+ toolCallId: "call-ask_question",+ toolName: "ask_question",+ args: {},+ output: JSON.stringify({ type: "need_login" }),+ } as unknown as MessagePart;+ const parts = [+ toolPart("find_block"),+ askQuestion,+ textPart("Please log in and try again"),+ ];+ const result = splitReasoningAndResponse(parts);+ expect(result.reasoning).toEqual([parts[0]]);+ expect(result.response).toHaveLength(2);+ expect(result.response[0]).toBe(askQuestion);+ });++ it("keeps non-interactive reasoning tools in reasoning", () => {+ const parts = [+ toolPart("find_block"),+ toolPart("search_docs"),+ textPart("Answer"),+ ];+ const result = splitReasoningAndResponse(parts);+ expect(result.reasoning).toHaveLength(2);+ expect(result.reasoning[0]).toBe(parts[0]);+ expect(result.reasoning[1]).toBe(parts[1]);+ expect(result.response).toHaveLength(1);+ });++ it("moves a native reasoning part into reasoning when text follows", () => {+ const parts = [reasoningPart("Thinking through this..."), textPart("Done")];+ const result = splitReasoningAndResponse(parts);+ expect(result.reasoning).toHaveLength(1);+ expect(result.reasoning[0]).toBe(parts[0]);+ expect(result.response).toHaveLength(1);+ expect((result.response[0] as { text: string }).text).toBe("Done");});- it("keeps reasoning inside the reasoning group when tools precede the text", () => {- const out = splitReasoningAndResponse([reasoning, tool, text]);- expect(out.reasoning).toEqual([reasoning, tool]);- expect(out.response).toEqual([text]);+ it("keeps a trailing native reasoning part in response when no text follows", () => {+ const parts = [textPart("Hello"), reasoningPart("Thinking...")];+ const result = splitReasoningAndResponse(parts);+ expect(result.reasoning).toEqual([]);+ expect(result.response).toEqual(parts);});- it("splits tools into reasoning and text into response when no reasoning is present", () => {- const out = splitReasoningAndResponse([tool, text]);- expect(out.reasoning).toEqual([tool]);- expect(out.response).toEqual([text]);+ it("sweeps a native reasoning part emitted after the last reasoning tool into reasoning", () => {+ const parts = [+ toolPart("find_block"),+ reasoningPart("Post-tool thinking"),+ textPart("Final answer"),+ ];+ const result = splitReasoningAndResponse(parts);+ expect(result.reasoning).toHaveLength(2);+ expect(result.reasoning[0]).toBe(parts[0]);+ expect(result.reasoning[1]).toBe(parts[1]);+ expect(result.response).toHaveLength(1);+ expect((result.response[0] as { text: string }).text).toBe("Final answer");+ });++ it("splits on reasoning parts alone when no reasoning tools are present", () => {+ const parts = [+ reasoningPart("Step 1"),+ reasoningPart("Step 2"),+ textPart("Here's the answer"),+ ];+ const result = splitReasoningAndResponse(parts);+ expect(result.reasoning).toHaveLength(2);+ expect(result.response).toHaveLength(1);+ expect((result.response[0] as { text: string }).text).toBe(+ "Here's the answer",+ );});});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.tsindex 145e9eb329..215bf06c4e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts@@ -33,6 +33,20 @@ const CUSTOM_TOOL_TYPES = new Set(["tool-create_feature_request",]);+const REASONING_TOOL_TYPES = new Set([+ "tool-find_block",+ "tool-find_agent",+ "tool-find_library_agent",+ "tool-search_docs",+ "tool-get_doc_page",+ "tool-search_feature_requests",+ "tool-ask_question",+]);++export function isReasoningToolPart(part: MessagePart): boolean {+ return REASONING_TOOL_TYPES.has(part.type);+}+const WORKSPACE_FILE_PATTERN =/\/api\/proxy\/api\/workspace\/files\/([a-f0-9-]+)\/download/;const WORKSPACE_URI_PATTERN = /workspace:\/\/([a-f0-9-]+)(?:#([^\s)\]]+))?/g;@@ -122,26 +136,30 @@ export function buildRenderSegments(return segments;}+function isReasoningBoundary(part: MessagePart): boolean {+ return part.type === "reasoning" || isReasoningToolPart(part);+}+export function splitReasoningAndResponse(parts: MessagePart[]): {reasoning: MessagePart[];response: MessagePart[];} {- const lastToolIndex = parts.findLastIndex((p) => p.type.startsWith("tool-"));+ const lastReasoningIndex = parts.findLastIndex(isReasoningBoundary);- if (lastToolIndex === -1) {+ if (lastReasoningIndex === -1) {return { reasoning: [], response: parts };}- const hasResponseAfterTools = parts- .slice(lastToolIndex + 1)+ const hasResponseAfterReasoning = parts+ .slice(lastReasoningIndex + 1).some((p) => p.type === "text");- if (!hasResponseAfterTools) {+ if (!hasResponseAfterReasoning) {return { reasoning: [], response: parts };}- const rawReasoning = parts.slice(0, lastToolIndex + 1);- const rawResponse = parts.slice(lastToolIndex + 1);+ const rawReasoning = parts.slice(0, lastReasoningIndex + 1);+ const rawResponse = parts.slice(lastReasoningIndex + 1);const reasoning: MessagePart[] = [];const pinnedParts: MessagePart[] = [];diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsxindex a8c5816e01..a2b0db4ddc 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx@@ -1,7 +1,6 @@"use client";import {getGetV2ListSessionsQueryKey,- useDeleteV2DeleteSession,useGetV2ListSessions,usePatchV2UpdateSessionTitle,} from "@/app/api/__generated__/endpoints/chat/chat";@@ -34,8 +33,11 @@ import { useQueryClient } from "@tanstack/react-query";import { AnimatePresence, motion } from "framer-motion";import { parseAsString, useQueryState } from "nuqs";import { useEffect, useRef, useState } from "react";+import { useCopilotChatRuntimeStore } from "../../copilotChatRegistry";import { formatNotificationTitle } from "../../helpers";+import { shouldShowSessionProcessingIndicator } from "../../sessionActivity";import { useCopilotUIStore } from "../../store";+import { useSessionDeletion } from "../../useSessionDeletion";import { NotificationToggle } from "./components/NotificationToggle/NotificationToggle";import { DeleteChatDialog } from "../DeleteChatDialog/DeleteChatDialog";import { UsageLimits } from "../UsageLimits/UsageLimits";@@ -44,41 +46,23 @@ export function ChatSidebar() {const { state } = useSidebar();const isCollapsed = state === "collapsed";const [sessionId, setSessionId] = useQueryState("sessionId", parseAsString);- const {- sessionToDelete,- setSessionToDelete,- completedSessionIDs,- clearCompletedSession,- } = useCopilotUIStore();+ const { completedSessionIDs, clearCompletedSession } = useCopilotUIStore();+ const sessionNeedsReload = useCopilotChatRuntimeStore(+ (state) => state.sessionNeedsReload,+ );const queryClient = useQueryClient();const { data: sessionsResponse, isLoading: isLoadingSessions } =useGetV2ListSessions({ limit: 50 }, { query: { refetchInterval: 10_000 } });- const { mutate: deleteSession, isPending: isDeleting } =- useDeleteV2DeleteSession({- mutation: {- onSuccess: () => {- queryClient.invalidateQueries({- queryKey: getGetV2ListSessionsQueryKey(),- });- if (sessionToDelete?.id === sessionId) {- setSessionId(null);- }- setSessionToDelete(null);- },- onError: (error) => {- toast({- title: "Failed to delete chat",- description:- error instanceof Error ? error.message : "An error occurred",- variant: "destructive",- });- setSessionToDelete(null);- },- },- });+ const {+ sessionToDelete,+ isDeleting,+ requestDelete,+ confirmDelete,+ cancelDelete,+ } = useSessionDeletion();const [editingSessionId, setEditingSessionId] = useState<string | null>(null);const [editingTitle, setEditingTitle] = useState("");@@ -165,20 +149,7 @@ export function ChatSidebar() {title: string | null | undefined,) {e.stopPropagation();- if (isDeleting) return;- setSessionToDelete({ id, title });- }-- function handleConfirmDelete() {- if (sessionToDelete) {- deleteSession({ sessionId: sessionToDelete.id });- }- }-- function handleCancelDelete() {- if (!isDeleting) {- setSessionToDelete(null);- }+ requestDelete(id, title);}function formatDate(dateString: string) {@@ -365,8 +336,15 @@ export function ChatSidebar() {</Text></div>{session.is_processing &&- session.id !== sessionId &&- !completedSessionIDs.has(session.id) && (+ shouldShowSessionProcessingIndicator({+ sessionId: session.id,+ currentSessionId: sessionId,+ isProcessing: session.is_processing,+ hasCompletedIndicator: completedSessionIDs.has(+ session.id,+ ),+ needsReload: !!sessionNeedsReload[session.id],+ }) && (<CircleNotchclassName="h-4 w-4 shrink-0 animate-spin text-zinc-400"weight="bold"@@ -424,8 +402,8 @@ export function ChatSidebar() {<DeleteChatDialogsession={sessionToDelete}isDeleting={isDeleting}- onConfirm={handleConfirmDelete}- onCancel={handleCancelDelete}+ onConfirm={confirmDelete}+ onCancel={cancelDelete}/></>);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/FileDropZone/FileDropZone.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/FileDropZone/FileDropZone.tsxnew file mode 100644index 0000000000..cf8b132518--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/FileDropZone/FileDropZone.tsx@@ -0,0 +1,77 @@+"use client";++import { cn } from "@/lib/utils";+import { UploadSimple } from "@phosphor-icons/react";+import { useRef, useState } from "react";++interface Props {+ children: React.ReactNode;+ onFilesDropped: (files: File[]) => void;+ className?: string;+}++/**+ * Wraps children with drag-and-drop file handling. Owns its own drag state so+ * that the overlay can toggle without re-rendering the rest of the tree.+ */+export function FileDropZone({ children, onFilesDropped, className }: Props) {+ const [isDragging, setIsDragging] = useState(false);+ const dragCounter = useRef(0);++ function handleDragEnter(e: React.DragEvent) {+ e.preventDefault();+ e.stopPropagation();+ dragCounter.current += 1;+ if (e.dataTransfer.types.includes("Files")) {+ setIsDragging(true);+ }+ }++ function handleDragOver(e: React.DragEvent) {+ e.preventDefault();+ e.stopPropagation();+ }++ function handleDragLeave(e: React.DragEvent) {+ e.preventDefault();+ e.stopPropagation();+ dragCounter.current -= 1;+ if (dragCounter.current === 0) {+ setIsDragging(false);+ }+ }++ function handleDrop(e: React.DragEvent) {+ e.preventDefault();+ e.stopPropagation();+ dragCounter.current = 0;+ setIsDragging(false);+ const files = Array.from(e.dataTransfer.files);+ if (files.length > 0) {+ onFilesDropped(files);+ }+ }++ return (+ <div+ className={className}+ onDragEnter={handleDragEnter}+ onDragOver={handleDragOver}+ onDragLeave={handleDragLeave}+ onDrop={handleDrop}+ >+ {children}+ <div+ className={cn(+ "pointer-events-none absolute inset-0 z-50 flex flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed border-violet-400 bg-violet-500/10 transition-opacity duration-150",+ isDragging ? "opacity-100" : "opacity-0",+ )}+ >+ <UploadSimple className="h-10 w-10 text-violet-500" weight="bold" />+ <span className="text-lg font-medium text-violet-600">+ Drop files here+ </span>+ </div>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/JobStatsBar/useElapsedTimer.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/JobStatsBar/useElapsedTimer.tsindex fdc849f4e7..8e025631af 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/JobStatsBar/useElapsedTimer.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/JobStatsBar/useElapsedTimer.ts@@ -3,12 +3,13 @@ import { useEffect, useRef, useState } from "react";/*** Ticks once per second while `isRunning` is true.*- * Pass `anchorIso` (a server-issued ISO timestamp, e.g. the last user /- * tool message's `createdAt`) to count from that absolute wall-clock point- * instead of from when this hook first saw `isRunning = true`. This is what- * makes the "Considering Xs" counter survive a page refresh mid-turn — it- * reflects actual elapsed time since the turn's last recorded activity, not- * the moment the current browser tab mounted.+ * Pass `anchorIso` (a server-issued ISO timestamp, e.g. the active stream's+ * `started_at` or the last user/tool message's `createdAt`) to count from+ * that absolute wall-clock point instead of from when this hook first saw+ * `isRunning = true`. This is what makes the "Considering Xs" counter+ * survive a page refresh mid-turn — it reflects actual elapsed time since+ * the turn's last recorded activity, not the moment the current browser+ * tab mounted.*/export function useElapsedTimer(isRunning: boolean, anchorIso?: string | null) {const [elapsedSeconds, setElapsedSeconds] = useState(0);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/MobileDrawer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/MobileDrawer.tsxindex 09c8832707..f71b80603f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/MobileDrawer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileDrawer/MobileDrawer.tsx@@ -1,7 +1,8 @@-import type { SessionSummaryResponse } from "@/app/api/__generated__/models/sessionSummaryResponse";+import { useGetV2ListSessions } from "@/app/api/__generated__/endpoints/chat/chat";import { Button } from "@/components/atoms/Button/Button";import { Text } from "@/components/atoms/Text/Text";import { scrollbarStyles } from "@/components/styles/scrollbars";+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";import { cn } from "@/lib/utils";import {CheckCircle,@@ -12,19 +13,13 @@ import {SpinnerGapIcon,X,} from "@phosphor-icons/react";+import { parseAsString, useQueryState } from "nuqs";import { Drawer } from "vaul";+import { useCopilotChatRuntimeStore } from "../../copilotChatRegistry";+import { shouldShowSessionProcessingIndicator } from "../../sessionActivity";import { useCopilotUIStore } from "../../store";--interface Props {- isOpen: boolean;- sessions: SessionSummaryResponse[];- currentSessionId: string | null;- isLoading: boolean;- onSelectSession: (sessionId: string) => void;- onNewChat: () => void;- onClose: () => void;- onOpenChange: (open: boolean) => void;-}+import { useSessionDeletion } from "../../useSessionDeletion";+import { DeleteChatDialog } from "../DeleteChatDialog/DeleteChatDialog";function formatDate(dateString: string) {const date = new Date(dateString);@@ -51,143 +46,187 @@ function formatDate(dateString: string) {return `${day}${ordinal} ${month} ${year}`;}-export function MobileDrawer({- isOpen,- sessions,- currentSessionId,- isLoading,- onSelectSession,- onNewChat,- onClose,- onOpenChange,-}: Props) {+export function MobileDrawer() {+ const { isUserLoading, isLoggedIn } = useSupabase();+ const [currentSessionId, setSessionId] = useQueryState(+ "sessionId",+ parseAsString,+ );const {completedSessionIDs,clearCompletedSession,isSoundEnabled,toggleSound,+ isDrawerOpen,+ setDrawerOpen,} = useCopilotUIStore();+ const sessionNeedsReload = useCopilotChatRuntimeStore(+ (state) => state.sessionNeedsReload,+ );++ const { data: sessionsResponse, isLoading } = useGetV2ListSessions(+ { limit: 50 },+ { query: { enabled: !isUserLoading && isLoggedIn } },+ );+ const sessions =+ sessionsResponse?.status === 200 ? sessionsResponse.data.sessions : [];++ const { sessionToDelete, isDeleting, confirmDelete, cancelDelete } =+ useSessionDeletion();++ function closeDrawer() {+ setDrawerOpen(false);+ }++ function handleSelectSession(id: string) {+ setSessionId(id);+ closeDrawer();+ }++ function handleNewChat() {+ setSessionId(null);+ closeDrawer();+ }return (- <Drawer.Root open={isOpen} onOpenChange={onOpenChange} direction="left">- <Drawer.Portal>- <Drawer.Overlay className="fixed inset-0 z-[60] bg-black/10 backdrop-blur-sm" />- <Drawer.Content className="fixed left-0 top-0 z-[70] flex h-full w-80 flex-col border-r border-zinc-200 bg-zinc-50">- <div className="shrink-0 border-b border-zinc-200 px-4 py-2">- <div className="flex items-center justify-between">- <Drawer.Title className="text-lg font-semibold text-zinc-800">- Your chats- </Drawer.Title>- <div className="flex items-center gap-1">- <button- onClick={toggleSound}- className="rounded p-1.5 text-zinc-400 transition-colors hover:text-zinc-600"- aria-label={- isSoundEnabled- ? "Disable notification sound"- : "Enable notification sound"- }- >- {isSoundEnabled ? (- <SpeakerHigh className="h-4 w-4" />- ) : (- <SpeakerSlash className="h-4 w-4" />- )}- </button>- <Button- variant="icon"- size="icon"- aria-label="Close sessions"- onClick={onClose}- >- <X width="1rem" height="1rem" />- </Button>+ <>+ <Drawer.Root+ open={isDrawerOpen}+ onOpenChange={setDrawerOpen}+ direction="left"+ >+ <Drawer.Portal>+ <Drawer.Overlay className="fixed inset-0 z-[60] bg-black/10 backdrop-blur-sm" />+ <Drawer.Content className="fixed left-0 top-0 z-[70] flex h-full w-80 flex-col border-r border-zinc-200 bg-zinc-50">+ <div className="shrink-0 border-b border-zinc-200 px-4 py-2">+ <div className="flex items-center justify-between">+ <Drawer.Title className="text-lg font-semibold text-zinc-800">+ Your chats+ </Drawer.Title>+ <div className="flex items-center gap-1">+ <button+ onClick={toggleSound}+ className="rounded p-1.5 text-zinc-400 transition-colors hover:text-zinc-600"+ aria-label={+ isSoundEnabled+ ? "Disable notification sound"+ : "Enable notification sound"+ }+ >+ {isSoundEnabled ? (+ <SpeakerHigh className="h-4 w-4" />+ ) : (+ <SpeakerSlash className="h-4 w-4" />+ )}+ </button>+ <Button+ variant="icon"+ size="icon"+ aria-label="Close sessions"+ onClick={closeDrawer}+ >+ <X width="1rem" height="1rem" />+ </Button>+ </div></div>+ {currentSessionId ? (+ <div className="mt-2">+ <Button+ variant="primary"+ size="small"+ onClick={handleNewChat}+ className="w-full"+ leftIcon={<PlusIcon width="1rem" height="1rem" />}+ >+ New Chat+ </Button>+ </div>+ ) : null}</div>- {currentSessionId ? (- <div className="mt-2">- <Button- variant="primary"- size="small"- onClick={onNewChat}- className="w-full"- leftIcon={<PlusIcon width="1rem" height="1rem" />}- >- New Chat- </Button>- </div>- ) : null}- </div>- <div- className={cn(- "flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto px-3 py-3",- scrollbarStyles,- )}- >- {isLoading ? (- <div className="flex items-center justify-center py-4">- <SpinnerGapIcon className="h-5 w-5 animate-spin text-neutral-400" />- </div>- ) : sessions.length === 0 ? (- <p className="py-4 text-center text-sm text-neutral-500">- No conversations yet- </p>- ) : (- sessions.map((session) => (- <button- key={session.id}- onClick={() => {- onSelectSession(session.id);- if (completedSessionIDs.has(session.id)) {- clearCompletedSession(session.id);- }- }}- className={cn(- "w-full rounded-lg px-3 py-2.5 text-left transition-colors",- session.id === currentSessionId- ? "bg-zinc-100"- : "hover:bg-zinc-50",- )}- >- <div className="flex min-w-0 max-w-full flex-col overflow-hidden">- <div className="flex min-w-0 max-w-full items-center gap-1.5">- <Text- variant="body"- className={cn(- "truncate font-normal",- session.id === currentSessionId- ? "text-zinc-600"- : "text-zinc-800",- )}- >- {session.title || "Untitled chat"}+ <div+ className={cn(+ "flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto px-3 py-3",+ scrollbarStyles,+ )}+ >+ {isLoading ? (+ <div className="flex items-center justify-center py-4">+ <SpinnerGapIcon className="h-5 w-5 animate-spin text-neutral-400" />+ </div>+ ) : sessions.length === 0 ? (+ <p className="py-4 text-center text-sm text-neutral-500">+ No conversations yet+ </p>+ ) : (+ sessions.map((session) => (+ <button+ key={session.id}+ onClick={() => {+ handleSelectSession(session.id);+ if (completedSessionIDs.has(session.id)) {+ clearCompletedSession(session.id);+ }+ }}+ className={cn(+ "w-full rounded-lg px-3 py-2.5 text-left transition-colors",+ session.id === currentSessionId+ ? "bg-zinc-100"+ : "hover:bg-zinc-50",+ )}+ >+ <div className="flex min-w-0 max-w-full flex-col overflow-hidden">+ <div className="flex min-w-0 max-w-full items-center gap-1.5">+ <Text+ variant="body"+ className={cn(+ "truncate font-normal",+ session.id === currentSessionId+ ? "text-zinc-600"+ : "text-zinc-800",+ )}+ >+ {session.title || "Untitled chat"}+ </Text>+ {session.is_processing &&+ shouldShowSessionProcessingIndicator({+ sessionId: session.id,+ currentSessionId,+ isProcessing: session.is_processing,+ hasCompletedIndicator: completedSessionIDs.has(+ session.id,+ ),+ needsReload: !!sessionNeedsReload[session.id],+ }) && (+ <CircleNotch+ className="h-4 w-4 shrink-0 animate-spin text-zinc-400"+ weight="bold"+ />+ )}+ {completedSessionIDs.has(session.id) &&+ session.id !== currentSessionId && (+ <CheckCircle+ className="h-4 w-4 shrink-0 text-green-500"+ weight="fill"+ />+ )}+ </div>+ <Text variant="small" className="text-neutral-400">+ {formatDate(session.updated_at)}</Text>- {session.is_processing &&- !completedSessionIDs.has(session.id) &&- session.id !== currentSessionId && (- <CircleNotch- className="h-4 w-4 shrink-0 animate-spin text-zinc-400"- weight="bold"- />- )}- {completedSessionIDs.has(session.id) &&- session.id !== currentSessionId && (- <CheckCircle- className="h-4 w-4 shrink-0 text-green-500"- weight="fill"- />- )}</div>- <Text variant="small" className="text-neutral-400">- {formatDate(session.updated_at)}- </Text>- </div>- </button>- ))- )}- </div>- </Drawer.Content>- </Drawer.Portal>- </Drawer.Root>+ </button>+ ))+ )}+ </div>+ </Drawer.Content>+ </Drawer.Portal>+ </Drawer.Root>+ <DeleteChatDialog+ session={sessionToDelete}+ isDeleting={isDeleting}+ onConfirm={confirmDelete}+ onCancel={cancelDelete}+ />+ </>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileHeader/MobileHeader.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileHeader/MobileHeader.tsxindex bed9989244..5c2d4d541f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileHeader/MobileHeader.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/MobileHeader/MobileHeader.tsx@@ -1,12 +1,10 @@import { Button } from "@/components/atoms/Button/Button";import { NAVBAR_HEIGHT_PX } from "@/lib/constants";import { ListIcon } from "@phosphor-icons/react";+import { useCopilotUIStore } from "../../store";-interface Props {- onOpenDrawer: () => void;-}--export function MobileHeader({ onOpenDrawer }: Props) {+export function MobileHeader() {+ const setDrawerOpen = useCopilotUIStore((s) => s.setDrawerOpen);return (<divclassName="fixed z-50 flex gap-2"@@ -16,7 +14,7 @@ export function MobileHeader({ onOpenDrawer }: Props) {variant="icon"size="icon"aria-label="Open sessions"- onClick={onOpenDrawer}+ onClick={() => setDrawerOpen(true)}className="bg-white shadow-md"><ListIcon width="1.25rem" height="1.25rem" />diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitGate.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitGate.tsxnew file mode 100644index 0000000000..5f268f1396--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/RateLimitGate.tsx@@ -0,0 +1,72 @@+"use client";++import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";+import { useGetV2GetCopilotUsage } from "@/app/api/__generated__/endpoints/chat/chat";+import { toast } from "@/components/molecules/Toast/use-toast";+import useCredits from "@/hooks/useCredits";+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { useEffect } from "react";+import { RateLimitResetDialog } from "./RateLimitResetDialog";++interface Props {+ rateLimitMessage: string | null;+ onDismiss: () => void;+}++/**+ * Renders the rate-limit dialog when the user has an actionable reset path+ * (positive reset_cost). Otherwise falls back to a toast so the user still+ * gets feedback. Encapsulates all the usage/credits/flag state that's only+ * needed once a rate limit is hit.+ */+export function RateLimitGate({ rateLimitMessage, onDismiss }: Props) {+ const {+ data: usage,+ isSuccess: hasUsage,+ isError: usageError,+ } = useGetV2GetCopilotUsage({+ query: {+ select: (res) => res.data as CoPilotUsagePublic,+ // Only fetch once a rate limit has been hit — avoids a 30s background+ // poll for the 99% of sessions that never hit their quota.+ enabled: !!rateLimitMessage,+ refetchInterval: 30_000,+ staleTime: 10_000,+ },+ });+ const resetCost = usage?.reset_cost;+ const isBillingEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);+ const { credits, fetchCredits } = useCredits({ fetchInitialCredits: true });+ const hasInsufficientCredits =+ credits !== null && resetCost != null && credits < resetCost;++ // When the credit-based reset is unavailable (feature disabled or the query+ // failed), fall back to a toast so the user still gets feedback.+ useEffect(() => {+ if (!rateLimitMessage) return;+ if (!usageError && !(hasUsage && (resetCost ?? 0) <= 0)) return;+ toast({+ title: "Usage limit reached",+ description: rateLimitMessage,+ variant: "destructive",+ });+ onDismiss();+ }, [rateLimitMessage, resetCost, hasUsage, usageError, onDismiss]);++ const canShowDialog = !!rateLimitMessage && hasUsage && (resetCost ?? 0) > 0;++ return (+ <RateLimitResetDialog+ isOpen={canShowDialog}+ onClose={onDismiss}+ resetCost={resetCost ?? 0}+ resetMessage={rateLimitMessage ?? ""}+ isWeeklyExhausted={+ hasUsage && !!usage.weekly && usage.weekly.percent_used >= 100+ }+ hasInsufficientCredits={hasInsufficientCredits}+ isBillingEnabled={isBillingEnabled}+ onCreditChange={fetchCredits}+ />+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitGate.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitGate.test.tsxnew file mode 100644index 0000000000..8734dc9d45--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/RateLimitResetDialog/__tests__/RateLimitGate.test.tsx@@ -0,0 +1,162 @@+import { cleanup, render } from "@/tests/integrations/test-utils";+import { afterEach, describe, expect, it, vi } from "vitest";++const mockToast = vi.fn();+vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/components/molecules/Toast/use-toast")+ >();+ return {+ ...actual,+ toast: (...args: unknown[]) => mockToast(...args),+ };+});++const mockUseGetV2GetCopilotUsage = vi.fn();+vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({+ useGetV2GetCopilotUsage: (...args: unknown[]) =>+ mockUseGetV2GetCopilotUsage(...args),+}));++vi.mock("@/hooks/useCredits", () => ({+ default: () => ({ credits: 1000, fetchCredits: vi.fn() }),+}));++vi.mock("@/services/feature-flags/use-get-flag", () => ({+ Flag: { ENABLE_PLATFORM_PAYMENT: "ENABLE_PLATFORM_PAYMENT" },+ useGetFlag: () => false,+}));++// Capture props the dialog was rendered with so we can assert on them.+const dialogSpy = vi.fn();+vi.mock("../RateLimitResetDialog", () => ({+ RateLimitResetDialog: (props: { isOpen: boolean }) => {+ dialogSpy(props);+ return <div data-testid="reset-dialog" data-open={String(props.isOpen)} />;+ },+}));++import { RateLimitGate } from "../RateLimitGate";++afterEach(() => {+ cleanup();+ mockToast.mockReset();+ mockUseGetV2GetCopilotUsage.mockReset();+ dialogSpy.mockReset();+});++describe("RateLimitGate", () => {+ it("disables the usage query when no rate-limit message is present", () => {+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: undefined,+ isSuccess: false,+ isError: false,+ });++ render(<RateLimitGate rateLimitMessage={null} onDismiss={vi.fn()} />);++ expect(mockUseGetV2GetCopilotUsage).toHaveBeenCalled();+ const [config] = mockUseGetV2GetCopilotUsage.mock.calls[0] as [+ { query?: { enabled?: boolean } },+ ];+ expect(config?.query?.enabled).toBe(false);+ });++ it("enables the usage query once a rate-limit message arrives", () => {+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: undefined,+ isSuccess: false,+ isError: false,+ });++ render(+ <RateLimitGate+ rateLimitMessage="You've hit your usage limit"+ onDismiss={vi.fn()}+ />,+ );++ const [config] = mockUseGetV2GetCopilotUsage.mock.calls[0] as [+ { query?: { enabled?: boolean } },+ ];+ expect(config?.query?.enabled).toBe(true);+ });++ it("opens the reset dialog when usage has a positive reset cost", () => {+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: { reset_cost: 50, weekly: { percent_used: 100 } },+ isSuccess: true,+ isError: false,+ });++ render(+ <RateLimitGate rateLimitMessage="limit reached" onDismiss={vi.fn()} />,+ );++ expect(dialogSpy).toHaveBeenCalled();+ const lastProps = dialogSpy.mock.calls.at(-1)?.[0];+ expect(lastProps.isOpen).toBe(true);+ expect(mockToast).not.toHaveBeenCalled();+ });++ it("falls back to a toast when usage query errors", () => {+ const onDismiss = vi.fn();+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: undefined,+ isSuccess: false,+ isError: true,+ });++ render(+ <RateLimitGate+ rateLimitMessage="You've hit your usage limit"+ onDismiss={onDismiss}+ />,+ );++ expect(mockToast).toHaveBeenCalledTimes(1);+ const toastArg = mockToast.mock.calls[0][0] as {+ title: string;+ variant: string;+ };+ expect(toastArg.title).toBe("Usage limit reached");+ expect(toastArg.variant).toBe("destructive");+ expect(onDismiss).toHaveBeenCalledTimes(1);++ // Dialog stays closed when the fallback fired.+ const lastProps = dialogSpy.mock.calls.at(-1)?.[0];+ expect(lastProps.isOpen).toBe(false);+ });++ it("falls back to a toast when reset cost is non-positive (credit reset unavailable)", () => {+ const onDismiss = vi.fn();+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: { reset_cost: 0, weekly: { percent_used: 100 } },+ isSuccess: true,+ isError: false,+ });++ render(+ <RateLimitGate rateLimitMessage="limit reached" onDismiss={onDismiss} />,+ );++ expect(mockToast).toHaveBeenCalledTimes(1);+ expect(onDismiss).toHaveBeenCalledTimes(1);++ const lastProps = dialogSpy.mock.calls.at(-1)?.[0];+ expect(lastProps.isOpen).toBe(false);+ });++ it("does not fire the fallback toast when no rate-limit message is present", () => {+ mockUseGetV2GetCopilotUsage.mockReturnValue({+ data: undefined,+ isSuccess: false,+ isError: true,+ });++ render(<RateLimitGate rateLimitMessage={null} onDismiss={vi.fn()} />);++ expect(mockToast).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard.tsxnew file mode 100644index 0000000000..b4594ab5c8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsageLimitReachedCard.tsx@@ -0,0 +1,89 @@+"use client";++import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";+import { useGetV2GetCopilotUsage } from "@/app/api/__generated__/endpoints/chat/chat";+import { Badge } from "@/components/atoms/Badge/Badge";+import { Text } from "@/components/atoms/Text/Text";+import useCredits from "@/hooks/useCredits";+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { Warning } from "@phosphor-icons/react";+import Link from "next/link";+import { UsagePanelContent } from "./UsagePanelContent";++const USAGE_QUERY_CONFIG = {+ query: {+ select: (res: { data: unknown }) => res.data as CoPilotUsagePublic,+ refetchInterval: 30000,+ staleTime: 10000,+ },+} as const;++export function useIsUsageLimitReached() {+ const { data: usage } = useGetV2GetCopilotUsage(USAGE_QUERY_CONFIG);+ const daily = usage?.daily?.percent_used ?? 0;+ const weekly = usage?.weekly?.percent_used ?? 0;+ return daily >= 100 || weekly >= 100;+}++export function UsageLimitReachedCard() {+ const { data: usage, isSuccess } =+ useGetV2GetCopilotUsage(USAGE_QUERY_CONFIG);++ const isBillingEnabled = useGetFlag(Flag.ENABLE_PLATFORM_PAYMENT);+ const { credits, fetchCredits } = useCredits({ fetchInitialCredits: true });+ const resetCost = usage?.reset_cost;+ const hasInsufficientCredits =+ credits !== null && resetCost != null && credits < resetCost;++ if (!isSuccess || !usage) return null;+ const isDailyExhausted = !!usage.daily && usage.daily.percent_used >= 100;+ const isWeeklyExhausted = !!usage.weekly && usage.weekly.percent_used >= 100;+ if (!isDailyExhausted && !isWeeklyExhausted) return null;++ const tierLabel = usage.tier+ ? usage.tier.charAt(0) + usage.tier.slice(1).toLowerCase()+ : null;++ return (+ <div+ role="alert"+ className="mx-auto flex w-full max-w-[30rem] flex-col gap-3 rounded-2xl border border-orange-100 bg-white/70 p-4 shadow-[0_8px_32px_rgba(0,0,0,0.04)] backdrop-blur-md"+ >+ <div className="flex items-center justify-between gap-3">+ <div className="flex items-center gap-2">+ <Warning className="size-5 text-orange-500" weight="fill" />+ <Text+ as="span"+ variant="body-medium"+ className="font-semibold text-neutral-900"+ >+ Usage limit reached+ </Text>+ {tierLabel && (+ <Badge+ variant="info"+ size="small"+ className="border border-neutral-200"+ >+ {tierLabel}+ </Badge>+ )}+ </div>+ <Link href="/profile/credits" className="shrink-0 hover:underline">+ <Text as="span" variant="small" className="text-blue-600">+ Learn more about usage limits+ </Text>+ </Link>+ </div>+ <UsagePanelContent+ usage={usage}+ showHeader={false}+ showBillingLink={false}+ hasInsufficientCredits={hasInsufficientCredits}+ isBillingEnabled={isBillingEnabled}+ onCreditChange={fetchCredits}+ size="md"+ />+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePanelContent.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePanelContent.tsxindex 9a1c0d1c87..e351c7f1a0 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePanelContent.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/UsageLimits/UsagePanelContent.tsx@@ -1,46 +1,68 @@import type { CoPilotUsagePublic } from "@/app/api/__generated__/models/coPilotUsagePublic";import { Button } from "@/components/atoms/Button/Button";+import { Text } from "@/components/atoms/Text/Text";+import { cn } from "@/lib/utils";import Link from "next/link";import { formatCents, formatResetTime } from "../usageHelpers";import { useResetRateLimit } from "../../hooks/useResetRateLimit";export { formatResetTime };+type Size = "sm" | "md";++const labelVariant = (size: Size) =>+ size === "md" ? "body-medium" : "small-medium";+const metaVariant = "small" as const;+function UsageBar({label,percentUsed,resetsAt,+ size = "sm",}: {label: string;percentUsed: number;resetsAt: Date | string;+ size?: Size;}) {const percent = Math.min(100, Math.max(0, Math.round(percentUsed)));- const isHigh = percent >= 80;const percentLabel =percentUsed > 0 && percent === 0 ? "<1% used" : `${percent}% used`;return (<div className="flex flex-col gap-1"><div className="flex items-baseline justify-between">- <span className="text-xs font-medium text-neutral-700">{label}</span>- <span className="text-[11px] tabular-nums text-neutral-500">+ <Text+ as="span"+ variant={labelVariant(size)}+ className="text-neutral-700"+ >+ {label}+ </Text>+ <Text+ as="span"+ variant={metaVariant}+ className="tabular-nums text-neutral-500"+ >{percentLabel}- </span>+ </Text></div>- <div className="text-[10px] text-neutral-400">+ <Text as="span" variant={metaVariant} className="text-neutral-400">Resets {formatResetTime(resetsAt)}- </div>- <div className="h-2 w-full overflow-hidden rounded-full bg-neutral-200">+ </Text>+ <div+ className={cn(+ "w-full overflow-hidden rounded-full bg-neutral-200",+ size === "md" ? "h-2.5" : "h-2",+ )}+ ><divrole="progressbar"aria-label={`${label} usage`}aria-valuemin={0}aria-valuemax={100}aria-valuenow={percent}- className={`h-full rounded-full transition-[width] duration-300 ease-out ${- isHigh ? "bg-orange-500" : "bg-blue-500"- }`}+ className="h-full rounded-full bg-blue-500 transition-[width] duration-300 ease-out"style={{ width: `${Math.max(percent > 0 ? 1 : 0, percent)}%` }}/></div>@@ -63,7 +85,7 @@ function ResetButton({size="small"onClick={() => resetUsage()}loading={isPending}- className="mt-1 w-full text-[11px]"+ className="mt-1 w-full">{isPending? "Resetting..."@@ -74,16 +96,20 @@ function ResetButton({export function UsagePanelContent({usage,+ showHeader = true,showBillingLink = true,hasInsufficientCredits = false,isBillingEnabled = false,onCreditChange,+ size = "sm",}: {usage: CoPilotUsagePublic;+ showHeader?: boolean;showBillingLink?: boolean;hasInsufficientCredits?: boolean;isBillingEnabled?: boolean;onCreditChange?: () => void;+ size?: Size;}) {const daily = usage.daily;const weekly = usage.weekly;@@ -93,7 +119,9 @@ export function UsagePanelContent({if (!daily && !weekly) {return (- <div className="text-xs text-neutral-500">No usage limits configured</div>+ <Text as="span" variant="small" className="text-neutral-500">+ No usage limits configured+ </Text>);}@@ -103,19 +131,28 @@ export function UsagePanelContent({return (<div className="flex flex-col gap-3">- <div className="flex items-baseline justify-between">- <span className="text-xs font-semibold text-neutral-800">- Usage limits- </span>- {tierLabel && (- <span className="text-[11px] text-neutral-500">{tierLabel} plan</span>- )}- </div>+ {showHeader && (+ <div className="flex items-baseline justify-between">+ <Text+ as="span"+ variant={size === "md" ? "body-medium" : "small-medium"}+ className="font-semibold text-neutral-800"+ >+ Usage limits+ </Text>+ {tierLabel && (+ <Text as="span" variant="small" className="text-neutral-500">+ {tierLabel} plan+ </Text>+ )}+ </div>+ )}{daily && (<UsageBarlabel="Today"percentUsed={daily.percent_used}resetsAt={daily.resets_at}+ size={size}/>)}{weekly && (@@ -123,6 +160,7 @@ export function UsagePanelContent({label="This week"percentUsed={weekly.percent_used}resetsAt={weekly.resets_at}+ size={size}/>)}{isDailyExhausted &&@@ -135,19 +173,21 @@ export function UsagePanelContent({!isWeeklyExhausted &&hasInsufficientCredits &&isBillingEnabled && (- <Link+ <Button+ as="NextLink"href="/profile/credits"- className="mt-1 inline-flex w-full items-center justify-center rounded-md bg-primary px-3 py-1.5 text-[11px] font-medium text-primary-foreground hover:bg-primary/90"+ variant="primary"+ size="small"+ className="mt-1 w-full">Add credits to reset- </Link>+ </Button>)}{showBillingLink && (- <Link- href="/profile/credits"- className="text-[11px] text-blue-600 hover:underline"- >- Learn more about usage limits+ <Link href="/profile/credits" className="hover:underline">+ <Text as="span" variant="small" className="text-blue-600">+ Learn more about usage limits+ </Text></Link>)}</div>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotChatRegistry.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotChatRegistry.tsnew file mode 100644index 0000000000..800e944008--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotChatRegistry.ts@@ -0,0 +1,140 @@+import { Chat } from "@ai-sdk/react";+import type { UIMessage } from "ai";+import { create } from "zustand";+import { useCopilotStreamStore } from "./copilotStreamStore";+import {+ createCopilotTransport,+ type MutableValue,+} from "./copilotStreamTransport";+import type { CopilotLlmModel, CopilotMode } from "./store";++interface CopilotChatRuntime {+ chat: Chat<UIMessage>;+ copilotModeRef: MutableValue<CopilotMode | undefined>;+ copilotModelRef: MutableValue<CopilotLlmModel | undefined>;+ onFinish?: (args: {+ isDisconnect?: boolean;+ isAbort?: boolean;+ }) => void | Promise<void>;+ onError?: (error: Error) => void;+}++interface CopilotChatRuntimeStore {+ sessionNeedsReload: Record<string, boolean>;+ markNeedsReload: (sessionId: string) => void;+ clearNeedsReload: (sessionId: string) => void;+ resetAll: () => void;+}++export const useCopilotChatRuntimeStore = create<CopilotChatRuntimeStore>(+ (set) => ({+ sessionNeedsReload: {},+ markNeedsReload(sessionId) {+ set((state) => ({+ sessionNeedsReload: {+ ...state.sessionNeedsReload,+ [sessionId]: true,+ },+ }));+ },+ clearNeedsReload(sessionId) {+ set((state) => {+ if (!state.sessionNeedsReload[sessionId]) return state;+ const sessionNeedsReload = { ...state.sessionNeedsReload };+ delete sessionNeedsReload[sessionId];+ return { sessionNeedsReload };+ });+ },+ resetAll() {+ set({ sessionNeedsReload: {} });+ },+ }),+);++const copilotChatRuntimes = new Map<string, CopilotChatRuntime>();++function markChatRuntimeDisconnected(sessionId: string) {+ useCopilotStreamStore.getState().clearSession(sessionId);+ useCopilotChatRuntimeStore.getState().markNeedsReload(sessionId);+}++function isTransientStreamDisconnect(error: Error) {+ const detail = error.message.toLowerCase();+ return (+ error.name === "TypeError" ||+ detail.includes("connection interrupted") ||+ detail.includes("network")+ );+}++export function getOrCreateCopilotChatRuntime(sessionId: string) {+ const existing = copilotChatRuntimes.get(sessionId);+ if (existing) return existing;++ const copilotModeRef: MutableValue<CopilotMode | undefined> = {+ current: undefined,+ };+ const copilotModelRef: MutableValue<CopilotLlmModel | undefined> = {+ current: undefined,+ };+ const callbacks: Pick<CopilotChatRuntime, "onFinish" | "onError"> = {};+ const chat = new Chat<UIMessage>({+ id: sessionId,+ transport: createCopilotTransport({+ sessionId,+ copilotModeRef,+ copilotModelRef,+ }),+ onFinish: (args) => {+ if (args.isDisconnect) {+ markChatRuntimeDisconnected(sessionId);+ }+ return callbacks.onFinish?.(args);+ },+ onError: (error) => {+ if (isTransientStreamDisconnect(error)) {+ markChatRuntimeDisconnected(sessionId);+ }+ return callbacks.onError?.(error);+ },+ });+ const runtime = {+ chat,+ copilotModeRef,+ copilotModelRef,+ get onFinish() {+ return callbacks.onFinish;+ },+ set onFinish(value) {+ callbacks.onFinish = value;+ },+ get onError() {+ return callbacks.onError;+ },+ set onError(value) {+ callbacks.onError = value;+ },+ } satisfies CopilotChatRuntime;++ copilotChatRuntimes.set(sessionId, runtime);+ return runtime;+}++export function markCopilotChatRuntimeHealthy(sessionId: string) {+ useCopilotChatRuntimeStore.getState().clearNeedsReload(sessionId);+}++export function shouldReloadCopilotChatRuntime(sessionId: string) {+ return !!useCopilotChatRuntimeStore.getState().sessionNeedsReload[sessionId];+}++export function resetCopilotChatRuntime(sessionId: string) {+ copilotChatRuntimes.delete(sessionId);+ useCopilotStreamStore.getState().clearSession(sessionId);+ useCopilotChatRuntimeStore.getState().clearNeedsReload(sessionId);+}++export function resetCopilotChatRegistry() {+ copilotChatRuntimes.clear();+ useCopilotChatRuntimeStore.getState().resetAll();+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamErrorHandlers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamErrorHandlers.tsnew file mode 100644index 0000000000..3d4beb65dd--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamErrorHandlers.ts@@ -0,0 +1,170 @@+import { toast } from "@/components/molecules/Toast/use-toast";++/**+ * Parses a backend-encoded error code from an `errorText` payload.+ *+ * The AI-SDK SSE protocol enforces `z.strictObject({type, errorText})`+ * on StreamError frames, so the backend cannot attach a top-level `code`+ * field. Instead it prefixes the message with `[code:<id>] <msg>` and+ * this helper extracts it client-side.+ */+export function parseBackendErrorCode(raw: string): {+ code: string | null;+ message: string;+} {+ const match = raw.match(/^\s*\[code:([a-z0-9_]+)\]\s*(.*)$/is);+ if (!match) return { code: null, message: raw };+ return { code: match[1], message: match[2].trim() };+}++/**+ * User-facing toast copy for each backend error code we surface.+ * `description` defaults to the backend's error message when provided;+ * `fallbackDescription` is used when the backend sends only the code.+ */+const TOAST_BY_BACKEND_CODE: Record<+ string,+ { title: string; fallbackDescription: string }+> = {+ idle_timeout: {+ title: "AutoPilot stopped responding",+ fallbackDescription:+ "A tool call got stuck and the session timed out. Press Try Again to resume.",+ },+ tool_stalled: {+ title: "A tool call is taking too long",+ fallbackDescription:+ "The assistant is waiting on a tool that hasn't responded. Press Try Again to restart.",+ },+ transient_api_error: {+ title: "Connection hiccup",+ fallbackDescription:+ "We hit a temporary error talking to the model. Press Try Again to continue.",+ },+ circuit_breaker_empty_tool_calls: {+ title: "AutoPilot paused",+ fallbackDescription:+ "The assistant made too many empty tool calls in a row and was paused. Press Try Again to continue.",+ },+ all_attempts_exhausted: {+ title: "Conversation too long",+ fallbackDescription:+ "We couldn't fit this chat's history into the model after several attempts. Start a new chat or clear some history.",+ },+ sdk_stream_error: {+ title: "AutoPilot ran into an error",+ fallbackDescription:+ "Something went wrong while the assistant was responding. Press Try Again to retry.",+ },+ sdk_error: {+ title: "AutoPilot ran into an error",+ fallbackDescription:+ "The assistant couldn't complete this turn. Press Try Again to retry.",+ },+};++/** Fallback toast shown for any `[code:X]` we don't have specific copy for. */+const GENERIC_BACKEND_TOAST = {+ title: "AutoPilot ran into a problem",+ fallbackDescription:+ "The assistant stopped unexpectedly. Press Try Again to retry.",+};++/**+ * Extract the human-readable error detail. FastAPI typically wraps 4xx+ * responses in `{"detail": "..."}` — if the SDK surfaced that as JSON in+ * `error.message`, unwrap to the nested string; otherwise use the raw message.+ */+function extractErrorDetail(error: Error): string {+ try {+ const parsed = JSON.parse(error.message) as unknown;+ if (+ typeof parsed === "object" &&+ parsed !== null &&+ "detail" in parsed &&+ typeof (parsed as { detail: unknown }).detail === "string"+ ) {+ return (parsed as { detail: string }).detail;+ }+ } catch {+ // Not JSON — use message as-is+ }+ return error.message;+}++interface HandleStreamErrorArgs {+ error: Error;+ onRateLimit: (message: string) => void;+ onReconnect: () => void;+ isUserStoppingRef: React.MutableRefObject<boolean>;+}++/**+ * Process a stream error from `useChat.onError`. Surfaces the right toast+ * (or rate-limit UI), and decides whether to retry via reconnect.+ *+ * Dispatch order (exclusive branches):+ * 1. `usage limit` substring → rate-limit UI via `onRateLimit`.+ * 2. 401 / auth failure → auth-error toast.+ * 3. `[code:<id>]` backend prefix → curated or generic backend toast.+ * 4. TypeError / AbortError / "connection interrupted" → reconnect.+ * 5. Anything else silently falls through (the AI-SDK also surfaces+ * `error` into the hook's `error` return, which drives the inline+ * error banner).+ */+export function handleStreamError({+ error,+ onRateLimit,+ onReconnect,+ isUserStoppingRef,+}: HandleStreamErrorArgs): void {+ const errorDetail = extractErrorDetail(error);++ // 1. Rate limit (FastAPI 429 body contains "usage limit")+ if (errorDetail.toLowerCase().includes("usage limit")) {+ onRateLimit(+ errorDetail || "You've reached your usage limit. Please try again later.",+ );+ return;+ }++ // 2. Authentication failures (from getCopilotAuthHeaders or 401 responses)+ const isAuthError =+ errorDetail.includes("Authentication failed") ||+ errorDetail.includes("Unauthorized") ||+ errorDetail.includes("Not authenticated") ||+ errorDetail.toLowerCase().includes("401");+ if (isAuthError) {+ toast({+ title: "Authentication error",+ description: "Your session may have expired. Please sign in again.",+ variant: "destructive",+ });+ return;+ }++ // 3. Coded backend error — show curated or generic toast so backend hangs+ // are never silent.+ const { code: backendCode, message: backendMessage } =+ parseBackendErrorCode(errorDetail);+ if (backendCode) {+ const userToast =+ TOAST_BY_BACKEND_CODE[backendCode] ?? GENERIC_BACKEND_TOAST;+ toast({+ title: userToast.title,+ description: backendMessage || userToast.fallbackDescription,+ variant: "destructive",+ });+ return;+ }++ // 4. Transient network / abort — reconnect so the "Try Again" affordance+ // (persisted retryable-error marker on the session) lights up.+ if (isUserStoppingRef.current) return;+ const isNetworkError =+ error.name === "TypeError" || error.name === "AbortError";+ const isTransientApiError = errorDetail.includes("connection interrupted");+ if (isNetworkError || isTransientApiError) {+ onReconnect();+ }+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamStore.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamStore.tsnew file mode 100644index 0000000000..71d5a22a48--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamStore.ts@@ -0,0 +1,145 @@+import type { FileUIPart, UIMessage } from "ai";+import { create } from "zustand";++/**+ * Per-session state. Zustand (not React refs) so it can survive events we+ * actually want to carry across visits — currently just `lastSubmittedMessageText`+ * for duplicate-POST protection. Everything transient per mount — resume flags,+ * reconnect counters, hydration gates — lives inside `useCopilotStream` as+ * React refs/state and resets naturally when the chat subtree remounts with+ * `key={sessionId}`.+ *+ * - lastSubmittedMessageText: blocks duplicate POSTs on resume. Meaningful+ * across visits.+ *+ * (Previously also tracked `lastChunkId` as a cursor for incremental resume+ * via `?last_chunk_id=…`. That optimisation is unsafe with AI SDK v5's+ * `UIMessageStream` parser — it throws `UIMessageStreamError` on any+ * `*-delta` / `*-end` whose `*-start` predecessor is missing from its+ * parser-local `activeTextParts` / `activeReasoningParts` state, and a+ * cursor-based XREAD skips the envelope + `*-start` chunks at the top of the+ * turn. Every resume now replays from `0-0`; overlap is handled by+ * `deduplicateMessages` on the consumer side.)+ */+export interface SessionCoord {+ lastSubmittedMessageText: string | null;+}++const defaultCoord: SessionCoord = {+ lastSubmittedMessageText: null,+};++/**+ * Pending user input that must survive the `null → id` session-creation+ * remount.+ *+ * `CopilotPage` keys the chat subtree by `sessionId ?? "new"`, so the moment+ * `createSession` resolves and the URL gains a sessionId, React tears down+ * the `"new"`-keyed host (wiping per-mount refs) and mounts a fresh one.+ * The first send was fired before that remount and needs a place to live+ * until the new host can pick it up — React-local state can't because it+ * was just unmounted, hence this single module-scoped slot.+ *+ * Assumes a single `CopilotPage` instance per tab. Two concurrent instances+ * (parallel routes, split panes) would collide on this slot; the solution+ * today is "don't do that". If it ever becomes a real requirement, key by+ * a mount-stable outer id threaded from `CopilotPage` through a context.+ */+export interface PendingFirstSend {+ text: string;+ files: File[];+}++interface CopilotStreamStore {+ sessions: Record<string, SessionCoord>;+ messageSnapshots: Record<string, UIMessage[]>;+ pendingFirstSend: PendingFirstSend | null;+ pendingFileParts: FileUIPart[];++ getCoord: (sessionId: string) => SessionCoord;+ updateCoord: (sessionId: string, patch: Partial<SessionCoord>) => void;+ clearSession: (sessionId: string) => void;+ getMessageSnapshot: (sessionId: string) => UIMessage[];+ setMessageSnapshot: (sessionId: string, messages: UIMessage[]) => void;++ setPendingFirstSend: (send: PendingFirstSend | null) => void;+ setPendingFileParts: (parts: FileUIPart[]) => void;+ /** Read-and-clear; used by the post-session-creation flush effect. */+ takePendingFirstSend: () => {+ send: PendingFirstSend | null;+ parts: FileUIPart[];+ };++ /** Test-only: wipe all per-session state. */+ resetAll: () => void;+}++export const useCopilotStreamStore = create<CopilotStreamStore>((set, get) => ({+ sessions: {},+ messageSnapshots: {},+ pendingFirstSend: null,+ pendingFileParts: [],++ getCoord(sessionId) {+ return get().sessions[sessionId] ?? defaultCoord;+ },+ updateCoord(sessionId, patch) {+ set((state) => ({+ sessions: {+ ...state.sessions,+ [sessionId]: {+ ...(state.sessions[sessionId] ?? defaultCoord),+ ...patch,+ },+ },+ }));+ },+ clearSession(sessionId) {+ set((state) => {+ const sessions = { ...state.sessions };+ delete sessions[sessionId];++ const messageSnapshots = { ...state.messageSnapshots };+ delete messageSnapshots[sessionId];++ return {+ sessions,+ messageSnapshots,+ };+ });+ },+ getMessageSnapshot(sessionId) {+ return get().messageSnapshots[sessionId] ?? [];+ },+ setMessageSnapshot(sessionId, messages) {+ set((state) => ({+ messageSnapshots: {+ ...state.messageSnapshots,+ [sessionId]: messages,+ },+ }));+ },++ setPendingFirstSend(send) {+ set({ pendingFirstSend: send });+ },+ setPendingFileParts(parts) {+ set({ pendingFileParts: parts });+ },+ takePendingFirstSend() {+ const { pendingFirstSend, pendingFileParts } = get();+ set({ pendingFirstSend: null, pendingFileParts: [] });+ return { send: pendingFirstSend, parts: pendingFileParts };+ },++ resetAll() {+ set({+ sessions: {},+ messageSnapshots: {},+ pendingFirstSend: null,+ pendingFileParts: [],+ });+ },+}));++export const DEFAULT_SESSION_COORD = defaultCoord;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.tsnew file mode 100644index 0000000000..fdde7cbd08--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.ts@@ -0,0 +1,87 @@+import { environment } from "@/services/environment";+import { DefaultChatTransport } from "ai";+import type { FileUIPart } from "ai";++import { getCopilotAuthHeaders } from "./helpers";+import type { CopilotLlmModel, CopilotMode } from "./store";++export interface MutableValue<T> {+ current: T;+}++interface CreateTransportArgs {+ sessionId: string;+ /**+ * Ref to the current autopilot mode. Kept as a ref (rather than captured+ * value) so mid-session mode changes are picked up on the next send without+ * recreating the transport — recreating would reset `useChat`'s internal+ * `Chat` instance and break mid-session streaming.+ */+ copilotModeRef: MutableValue<CopilotMode | undefined>;+ /** Ref to the current model tier. See `copilotModeRef` for rationale. */+ copilotModelRef: MutableValue<CopilotLlmModel | undefined>;+}++/**+ * Build the `DefaultChatTransport` that wires `useChat` directly at the+ * Python backend's SSE endpoint (bypassing the Next.js serverless proxy to+ * avoid the Vercel 800 s function timeout on long-running tasks).+ *+ * Two closures are attached:+ * - `prepareSendMessagesRequest` — POST new user turns (includes file_ids,+ * mode, model).+ * - `prepareReconnectToStreamRequest` — GET-resume existing turns from the+ * beginning of the active Redis turn so AI SDK sees a complete stream+ * envelope.+ */+export function createCopilotTransport({+ sessionId,+ copilotModeRef,+ copilotModelRef,+}: CreateTransportArgs) {+ const baseUrl = `${environment.getAGPTServerBaseUrl()}/api/chat/sessions/${sessionId}/stream`;++ return new DefaultChatTransport({+ api: baseUrl,+ prepareSendMessagesRequest: async ({ messages }) => {+ const last = messages[messages.length - 1];+ // Extract file_ids from FileUIPart entries on the message+ const fileIds = last.parts+ ?.filter((p): p is FileUIPart => p.type === "file")+ .map((p) => {+ // URL is like /api/proxy/api/workspace/files/{id}/download+ const match = p.url.match(/\/workspace\/files\/([^/]+)\//);+ return match?.[1];+ })+ .filter(Boolean) as string[] | undefined;+ return {+ body: {+ message: (+ last.parts?.map((p) => (p.type === "text" ? p.text : "")) ?? []+ ).join(""),+ is_user_message: last.role === "user",+ context: null,+ file_ids: fileIds && fileIds.length > 0 ? fileIds : null,+ mode: copilotModeRef.current ?? null,+ model: copilotModelRef.current ?? null,+ },+ headers: await getCopilotAuthHeaders(),+ };+ },+ prepareReconnectToStreamRequest: async () => {+ // Always replay from "0-0" (no ?last_chunk_id). AI SDK v5's+ // UIMessageStream parser throws UIMessageStreamError on any *-delta /+ // *-end whose matching *-start is missing from its *parser-local*+ // activeTextParts / activeReasoningParts state — and each+ // resumeStream() spawns a fresh parser, so a cursor-based resume+ // (which skips the envelope + *-start chunks that came before the+ // cursor) crashes on the first orphan delta. Replay overlap with the+ // in-memory `messages` is handled by `deduplicateMessages` on the+ // consumer side.+ return {+ api: baseUrl,+ headers: await getCopilotAuthHeaders(),+ };+ },+ });+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.tsindex 131a721117..f7ab38a46d 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers.ts@@ -3,6 +3,7 @@ import { getWebSocketToken } from "@/lib/supabase/actions";import type { UIMessage } from "ai";import { deleteV2DisconnectSessionStream } from "@/app/api/__generated__/endpoints/chat/chat";+import { TOOL_PART_PREFIX } from "./components/JobStatsBar/constants";export const ORIGINAL_TITLE = "AutoGPT";@@ -89,6 +90,48 @@ export function hasActiveBackendStream(result: { data?: unknown }): boolean {);}+/**+ * Whether the trailing assistant message has at least one part the UI+ * would visibly render: text with non-empty content, reasoning with+ * non-empty content, or any tool part (tool cards render regardless of+ * state). Used to gate the resume-snapshot discard — the replay may stream+ * empty reasoning-start / step-start chunks for minutes before any+ * rendered content (e.g. Perplexity deep research), and we do not want to+ * drop the pre-replay snapshot until the user actually sees something.+ */+export function hasVisibleAssistantContent(messages: UIMessage[]): boolean {+ const last = messages[messages.length - 1];+ if (last?.role !== "assistant") return false;+ return last.parts.some((part) => {+ if (part.type === "text" && part.text.trim().length > 0) return true;+ if (part.type === "reasoning" && part.text.trim().length > 0) return true;+ if (part.type.startsWith(TOOL_PART_PREFIX)) return true;+ return false;+ });+}++/**+ * Surface the latest backend-emitted status message for the trailing assistant+ * message, if that status has not already been invalidated by newer visible+ * parts. Used to show progress during restore/replay before answer text lands.+ */+export function getLatestAssistantStatusMessage(+ messages: UIMessage[],+): string | null {+ const last = messages[messages.length - 1];+ if (last?.role !== "assistant") return null;+ for (let i = last.parts.length - 1; i >= 0; i--) {+ const part = last.parts[i];+ if (part.type === "data-cursor") continue;+ if (part.type === "data-status") {+ const data = (part as { data?: { message?: unknown } }).data;+ return typeof data?.message === "string" ? data.message : null;+ }+ return null;+ }+ return null;+}+/** Mark any in-progress tool parts as completed/errored so spinners stop. */export function resolveInProgressTools(messages: UIMessage[],@@ -107,6 +150,79 @@ export function resolveInProgressTools(}));}+const IN_PROGRESS_PART_STATES = new Set([+ "streaming",+ "input-streaming",+ "input-available",+]);++/**+ * True if the message is an assistant message with at least one part that+ * the stream never finalised — i.e. text / reasoning in ``streaming`` or+ * tool parts in ``input-streaming`` / ``input-available``. Used both for+ * the partial-snapshot discard during resume and for zombie-part recovery+ * on session re-entry.+ */+export function hasInProgressAssistantParts(+ message: UIMessage | undefined,+): boolean {+ if (message?.role !== "assistant") return false;+ return message.parts.some((part) => {+ if (!("state" in part) || typeof part.state !== "string") return false;+ return IN_PROGRESS_PART_STATES.has(part.state);+ });+}++const COPILOT_INTERRUPTED_MARKER =+ "[__COPILOT_RETRYABLE_ERROR_a9c2__] Response was interrupted. Resend to try again.";++/**+ * Close the last assistant message when the stream ended without+ * finalising it (backend crash mid-write, the user switched away and the+ * DB snapshot rehydrated with orphaned in-progress parts, etc.). Tool+ * parts in ``input-streaming`` / ``input-available`` flip to+ * ``output-error`` "Interrupted" so their spinners stop; text / reasoning+ * parts in ``streaming`` flip to ``done`` so their typing animation ends+ * but the partial content is preserved. A retryable-error marker is+ * appended so the UI renders a "resend to try again" affordance.+ *+ * Only the last message is touched — earlier messages can't have unclosed+ * parts in a healthy session. Returns the original array when no repair+ * is needed, so callers can cheaply compare references.+ */+export function resolveInterruptedMessage(messages: UIMessage[]): UIMessage[] {+ if (messages.length === 0) return messages;+ const lastIdx = messages.length - 1;+ const last = messages[lastIdx];+ if (!hasInProgressAssistantParts(last)) return messages;++ const resolvedParts = last.parts.map((part) => {+ if (!("state" in part) || typeof part.state !== "string") return part;+ if (part.state === "input-streaming" || part.state === "input-available") {+ return {+ ...part,+ state: "output-error" as const,+ errorText: "Interrupted",+ };+ }+ if (part.state === "streaming") {+ return { ...part, state: "done" as const };+ }+ return part;+ });++ return [+ ...messages.slice(0, lastIdx),+ {+ ...last,+ parts: [+ ...resolvedParts,+ { type: "text" as const, text: COPILOT_INTERRUPTED_MARKER },+ ],+ },+ ];+}+/*** Extract the user-visible text from the arguments passed to `sendMessage`.* Handles both `sendMessage("hello")` and `sendMessage({ text: "hello" })`.diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/queueFollowUpMessage.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/queueFollowUpMessage.test.tsindex 1dc7aa0c83..7a4df0def5 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/queueFollowUpMessage.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/queueFollowUpMessage.test.ts@@ -1,6 +1,9 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { queueFollowUpMessage } from "../queueFollowUpMessage";+import {+ QueueFollowUpNotActiveError,+ queueFollowUpMessage,+} from "../queueFollowUpMessage";vi.mock("@/services/environment", () => ({environment: {@@ -24,7 +27,7 @@ describe("queueFollowUpMessage", () => {vi.restoreAllMocks();});- it("POSTs to /stream and returns kind=queued on 202", async () => {+ it("POSTs to /messages/pending and returns queued state on 200", async () => {const fetchMock = vi.mocked(global.fetch);fetchMock.mockResolvedValueOnce(new Response(@@ -33,14 +36,13 @@ describe("queueFollowUpMessage", () => {max_buffer_length: 10,turn_in_flight: true,}),- { status: 202, headers: { "Content-Type": "application/json" } },+ { status: 200, headers: { "Content-Type": "application/json" } },),);const result = await queueFollowUpMessage("sess-1", "hello");expect(result).toEqual({- kind: "queued",buffer_length: 2,max_buffer_length: 10,turn_in_flight: true,@@ -48,7 +50,7 @@ describe("queueFollowUpMessage", () => {expect(fetchMock).toHaveBeenCalledTimes(1);const [url, init] = fetchMock.mock.calls[0];expect(url).toBe(- "https://api.example.test/api/chat/sessions/sess-1/stream",+ "https://api.example.test/api/chat/sessions/sess-1/messages/pending",);expect(init?.method).toBe("POST");const headers = init?.headers as Record<string, string>;@@ -56,41 +58,50 @@ describe("queueFollowUpMessage", () => {expect(headers.Authorization).toBe("Bearer test-token");expect(JSON.parse(init?.body as string)).toEqual({message: "hello",- is_user_message: true,context: null,file_ids: null,});});- it("returns kind=raced_started_turn on 200 (race: server started a new turn)", async () => {+ it("treats a 200 inactive response as not active", async () => {const fetchMock = vi.mocked(global.fetch);- // SSE-shaped 200 response — the body must be drainable- const sseBody = new ReadableStream({- start(controller) {- controller.enqueue(new TextEncoder().encode("data: hello\n\n"));- controller.close();- },- });fetchMock.mockResolvedValueOnce(- new Response(sseBody, {- status: 200,- headers: { "Content-Type": "text/event-stream" },- }),+ new Response(+ JSON.stringify({+ buffer_length: 0,+ max_buffer_length: 10,+ turn_in_flight: false,+ }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),);- const result = await queueFollowUpMessage("sess-1", "hi");+ await expect(queueFollowUpMessage("sess-1", "hi")).rejects.toBeInstanceOf(+ QueueFollowUpNotActiveError,+ );+ });- expect(result).toEqual({ kind: "raced_started_turn", status: 200 });+ it("throws a typed error when there is no active turn to queue against", async () => {+ const fetchMock = vi.mocked(global.fetch);+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify({ detail: "no active turn" }), {+ status: 409,+ }),+ );++ await expect(queueFollowUpMessage("sess-1", "hi")).rejects.toBeInstanceOf(+ QueueFollowUpNotActiveError,+ );});- it("throws when response is neither 200 nor 202", async () => {+ it("throws when response is not 200", async () => {const fetchMock = vi.mocked(global.fetch);fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ detail: "boom" }), { status: 500 }),);await expect(queueFollowUpMessage("sess-1", "hi")).rejects.toThrow(- /Expected 202 \(queued\) or 200 \(raced new turn\) from \/stream; got 500/,+ /Expected 200 from \/messages\/pending; got 500/,);});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/queueFollowUpMessage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/queueFollowUpMessage.tsindex 4688701a73..0267369902 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/queueFollowUpMessage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/queueFollowUpMessage.ts@@ -2,40 +2,28 @@ import { environment } from "@/services/environment";import { getCopilotAuthHeaders } from "../helpers";-export type QueueFollowUpResult =- | {- kind: "queued";- buffer_length: number;- max_buffer_length: number;- turn_in_flight: boolean;- }- | {- kind: "raced_started_turn";- status: number;- };+export interface QueueFollowUpResult {+ buffer_length: number;+ max_buffer_length: number;+ turn_in_flight: boolean;+}++export class QueueFollowUpNotActiveError extends Error {+ constructor() {+ super("Session has no active turn to queue against.");+ this.name = "QueueFollowUpNotActiveError";+ }+}/**- * POST a follow-up message to the unified ``/stream`` endpoint when the- * client believes a turn is already in flight.- *- * The server decides:- * - turn in flight → push to pending buffer, return ``202 JSON`` → kind="queued"- * - session idle → start a new turn, return ``200 SSE`` → kind="raced_started_turn"- *- * The "raced" branch covers a real race condition: the client's- * ``isInflightRef`` reads true for one render, but by the time the request- * lands the previous turn already finished. Throwing in that case would- * surface a misleading error toast — instead we drain the SSE response so- * the connection is closed cleanly and signal "raced" to the caller, who- * can rely on ``useHydrateOnStreamEnd`` to surface the new turn's output.- *- * Throws only on transport errors or unexpected non-200/202 status codes.+ * POST a follow-up message to the dedicated pending-message endpoint when+ * the client believes a turn is already in flight.*/export async function queueFollowUpMessage(sessionId: string,message: string,): Promise<QueueFollowUpResult> {- const url = `${environment.getAGPTServerBaseUrl()}/api/chat/sessions/${sessionId}/stream`;+ const url = `${environment.getAGPTServerBaseUrl()}/api/chat/sessions/${sessionId}/messages/pending`;const res = await fetch(url, {method: "POST",headers: {@@ -44,35 +32,22 @@ export async function queueFollowUpMessage(},body: JSON.stringify({message,- is_user_message: true,context: null,file_ids: null,}),});- if (res.status === 202) {- const body = (await res.json()) as {- buffer_length: number;- max_buffer_length: number;- turn_in_flight: boolean;- };- return { kind: "queued", ...body };- }-if (res.status === 200) {- // Race: server treated this as a fresh turn (previous turn finished- // between our isInflight read and the request landing). Drain the body- // so the underlying connection isn't held open, then signal the caller- // — useHydrateOnStreamEnd will pick the assistant rows up next poll.- try {- await res.body?.cancel();- } catch {- // ignore — connection cleanup is best-effort+ const result = (await res.json()) as QueueFollowUpResult;+ if (!result.turn_in_flight) {+ throw new QueueFollowUpNotActiveError();}- return { kind: "raced_started_turn", status: 200 };+ return result;+ }++ if (res.status === 409) {+ throw new QueueFollowUpNotActiveError();}- throw new Error(- `Expected 202 (queued) or 200 (raced new turn) from /stream; got ${res.status}`,- );+ throw new Error(`Expected 200 from /messages/pending; got ${res.status}`);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/restoreConstants.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/restoreConstants.tsnew file mode 100644index 0000000000..19322342b2--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/restoreConstants.ts@@ -0,0 +1 @@+export const RESTORE_STALL_TIMEOUT_MS = 6_000;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/sessionActivity.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/sessionActivity.tsnew file mode 100644index 0000000000..fed31965fa--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/sessionActivity.ts@@ -0,0 +1,22 @@+interface ShouldShowSessionProcessingIndicatorArgs {+ sessionId: string;+ currentSessionId: string | null;+ isProcessing: boolean;+ hasCompletedIndicator: boolean;+ needsReload: boolean;+}++export function shouldShowSessionProcessingIndicator({+ sessionId,+ currentSessionId,+ isProcessing,+ hasCompletedIndicator,+ needsReload,+}: ShouldShowSessionProcessingIndicatorArgs) {+ return (+ isProcessing &&+ !needsReload &&+ !hasCompletedIndicator &&+ sessionId !== currentSessionId+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.tsindex d6a3557bd7..fae7bc7485 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts@@ -26,7 +26,6 @@ export function useChatSession({ dryRun = false }: UseChatSessionOptions = {}) {const sessionQuery = useGetV2GetSession(sessionId ?? "", undefined, {query: {enabled: !!sessionId,- staleTime: Infinity, // Manual invalidation on session switchrefetchOnWindowFocus: false,refetchOnReconnect: true,refetchOnMount: true,@@ -69,46 +68,55 @@ export function useChatSession({ dryRun = false }: UseChatSessionOptions = {}) {}}, [sessionId, queryClient]);+ const freshSessionData =+ !!sessionId && sessionQuery.data?.status === 200 && !sessionQuery.isFetching+ ? sessionQuery.data.data+ : null;+// Expose active_stream info so the caller can trigger manual resume// after hydration completes (rather than relying on AI SDK's built-in// resume which fires before hydration).const hasActiveStream = useMemo(() => {- if (sessionQuery.isFetching) return false;- if (sessionQuery.data?.status !== 200) return false;- return !!sessionQuery.data.data.active_stream;- }, [sessionQuery.data, sessionQuery.isFetching, sessionId]);+ return !!freshSessionData?.active_stream;+ }, [freshSessionData]);++ // Backend-reported start time of the active turn. Used to seed the+ // elapsed-time counter on mount so restored sessions show honest+ // "time since the backend started the turn" rather than "time since+ // this mount subscribed to the SSE".+ const activeStreamStartedAt = useMemo(() => {+ return freshSessionData?.active_stream?.started_at ?? null;+ }, [freshSessionData]);// Pagination metadata from the initial page loadconst hasMoreMessages = useMemo(() => {- if (sessionQuery.data?.status !== 200) return false;- return !!sessionQuery.data.data.has_more_messages;- }, [sessionQuery.data]);+ return !!freshSessionData?.has_more_messages;+ }, [freshSessionData]);const oldestSequence = useMemo(() => {- if (sessionQuery.data?.status !== 200) return null;- return sessionQuery.data.data.oldest_sequence ?? null;- }, [sessionQuery.data]);+ return freshSessionData?.oldest_sequence ?? null;+ }, [freshSessionData]);// Memoize so the effect in useCopilotPage doesn't infinite-loop on a new// array reference every render. Re-derives only when query data changes.// When the session is complete (no active stream), mark dangling tool// calls as completed so stale spinners don't persist after refresh.const { hydratedMessages, historicalTurnStats } = useMemo(() => {- if (sessionQuery.data?.status !== 200 || !sessionId)+ if (!freshSessionData || !sessionId)return {hydratedMessages: undefined,historicalTurnStats: new Map() as TurnStatsMap,};const result = convertChatSessionMessagesToUiMessages(sessionId,- sessionQuery.data.data.messages ?? [],+ freshSessionData.messages ?? [],{ isComplete: !hasActiveStream },);return {hydratedMessages: result.messages,historicalTurnStats: result.stats,};- }, [sessionQuery.data, sessionId, hasActiveStream]);+ }, [freshSessionData, sessionId, hasActiveStream]);const { mutateAsync: createSessionMutation, isPending: isCreatingSession } =usePostV2CreateSession({@@ -163,8 +171,8 @@ export function useChatSession({ dryRun = false }: UseChatSessionOptions = {}) {// Raw messages from the initial page — exposed for cross-page// tool output matching by useLoadMoreMessages.const rawSessionMessages =- sessionQuery.data?.status === 200- ? ((sessionQuery.data.data.messages ?? []) as unknown[])+ freshSessionData?.messages != null+ ? ((freshSessionData.messages ?? []) as unknown[]): [];// The actual dry_run value stored in the session's metadata, read directly@@ -175,8 +183,8 @@ export function useChatSession({ dryRun = false }: UseChatSessionOptions = {}) {// sessions. Once a session exists, its dry_run flag is immutable and should// be read from here rather than from the store, which may have changed.const sessionDryRun = useMemo(- () => resolveSessionDryRun(sessionQuery.data),- [sessionQuery.data],+ () => (freshSessionData ? resolveSessionDryRun(sessionQuery.data) : false),+ [sessionQuery.data, freshSessionData],);return {@@ -186,8 +194,13 @@ export function useChatSession({ dryRun = false }: UseChatSessionOptions = {}) {rawSessionMessages,historicalTurnStats,hasActiveStream,+ activeStreamStartedAt,hasMoreMessages,oldestSequence,+ // Only treat the session as loading during the INITIAL fetch (no cached+ // data yet). Background refetches keep the input enabled — otherwise a+ // fill+Enter race can trigger handleSend while ``disabled`` briefly+ // flips back to ``true`` mid-refetch, silently dropping the message.isLoadingSession: sessionQuery.isLoading,isSessionError: sessionQuery.isError,createSession,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.tsindex bdf6524f49..90058df00f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts@@ -1,62 +1,53 @@-import {- getGetV2ListSessionsQueryKey,- useDeleteV2DeleteSession,- useGetV2ListSessions,- type getV2ListSessionsResponse,-} from "@/app/api/__generated__/endpoints/chat/chat";import { toast } from "@/components/molecules/Toast/use-toast";-import { uploadFileDirect } from "@/lib/direct-upload";-import { useBreakpoint } from "@/lib/hooks/useBreakpoint";import { useSupabase } from "@/lib/supabase/hooks/useSupabase";-import { useQueryClient } from "@tanstack/react-query";-import type { FileUIPart } from "ai";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";-import { useEffect, useMemo, useRef, useState } from "react";+import type { UIMessage } from "ai";+import { useMemo, useRef } from "react";import { concatWithAssistantMerge } from "./helpers/convertChatSessionToUiMessages";+import { getLatestAssistantStatusMessage } from "./helpers";import { queueFollowUpMessage } from "./helpers/queueFollowUpMessage";import { stripReplayPrefix } from "./helpers/stripReplayPrefix";+import { useCopilotStreamStore } from "./copilotStreamStore";import { useCopilotPendingChips } from "./useCopilotPendingChips";import { useCopilotUIStore } from "./store";import { useChatSession } from "./useChatSession";import { useCopilotNotifications } from "./useCopilotNotifications";import { useCopilotStream } from "./useCopilotStream";import { useLoadMoreMessages } from "./useLoadMoreMessages";+import { useSendMessage } from "./useSendMessage";+import { useSessionTitlePoll } from "./useSessionTitlePoll";import { useWorkflowImportAutoSubmit } from "./useWorkflowImportAutoSubmit";-const TITLE_POLL_INTERVAL_MS = 2_000;-const TITLE_POLL_MAX_ATTEMPTS = 5;+function trimVisibleMessagesForActiveRestore(messages: UIMessage[]) {+ const lastUserIndex = messages.findLastIndex(+ (message) => message.role === "user",+ );+ if (lastUserIndex === -1 || lastUserIndex === messages.length - 1) {+ return messages;+ }+ return messages.slice(0, lastUserIndex + 1);+}-interface UploadedFile {- file_id: string;- name: string;- mime_type: string;+function hasAssistantTail(messages: UIMessage[]) {+ const lastUserIndex = messages.findLastIndex(+ (message) => message.role === "user",+ );+ return lastUserIndex !== -1 && lastUserIndex < messages.length - 1;}export function useCopilotPage() {const { isUserLoading, isLoggedIn } = useSupabase();- const [isUploadingFiles, setIsUploadingFiles] = useState(false);- const [pendingMessage, setPendingMessage] = useState<string | null>(null);- const queryClient = useQueryClient();-const isModeToggleEnabled = useGetFlag(Flag.CHAT_MODE_OPTION);- const {- sessionToDelete,- setSessionToDelete,- isDrawerOpen,- setDrawerOpen,- copilotChatMode,- copilotLlmModel,- isDryRun,- } = useCopilotUIStore();+ const { copilotChatMode, copilotLlmModel, isDryRun } = useCopilotUIStore();const {sessionId,- setSessionId,hydratedMessages,rawSessionMessages,historicalTurnStats,hasActiveStream,+ activeStreamStartedAt,hasMoreMessages,oldestSequence,isLoadingSession,@@ -75,8 +66,9 @@ export function useCopilotPage() {status,error,isReconnecting,- isSyncing,+ isRestoringActiveSession,isUserStoppingRef,+ isUserStopping,rateLimitMessage,dismissRateLimit,} = useCopilotStream({@@ -112,18 +104,46 @@ export function useCopilotPage() {// double-presses from both routing to /stream before React can re-render// with status="submitted".const isInflightRef = useRef(false);- isInflightRef.current = status === "streaming" || status === "submitted";+ isInflightRef.current =+ !isUserStopping && (status === "streaming" || status === "submitted");// Combine paginated messages with current page messages, merging consecutive// assistant UIMessages at the page boundary so reasoning + response parts// stay in a single bubble. Paged messages are older history prepended before// the current page.const rawMessages = concatWithAssistantMerge(pagedMessages, currentMessages);+ const cachedSessionMessages = useMemo(+ () =>+ sessionId+ ? useCopilotStreamStore.getState().getMessageSnapshot(sessionId)+ : [],+ [sessionId],+ );+ const cachedRawMessages = concatWithAssistantMerge(+ pagedMessages,+ cachedSessionMessages,+ );// Drop / trim assistant messages whose leading text is a replay of an// earlier assistant (Claude Agent SDK's `--resume` behaviour). See// helpers/stripReplayPrefix.ts for the three cases.const messages = useMemo(() => stripReplayPrefix(rawMessages), [rawMessages]);+ const cachedMessages = useMemo(+ () => stripReplayPrefix(cachedRawMessages),+ [cachedRawMessages],+ );+ const restoreStatusMessage = useMemo(+ () =>+ isRestoringActiveSession+ ? getLatestAssistantStatusMessage(messages)+ : null,+ [isRestoringActiveSession, messages],+ );+ const displayMessages = useMemo(() => {+ if (!isRestoringActiveSession) return messages;+ if (hasAssistantTail(cachedMessages)) return cachedMessages;+ return trimVisibleMessagesForActiveRestore(messages);+ }, [isRestoringActiveSession, messages, cachedMessages]);// Chip state machine (peek sync + auto-continue promotion + mid-turn poll)// lives in a dedicated hook so this component is just glue.@@ -136,337 +156,80 @@ export function useCopilotPage() {useCopilotNotifications(sessionId);- // --- Delete session ---- const { mutate: deleteSessionMutation, isPending: isDeleting } =- useDeleteV2DeleteSession({- mutation: {- onSuccess: () => {- queryClient.invalidateQueries({- queryKey: getGetV2ListSessionsQueryKey(),- });- if (sessionToDelete?.id === sessionId) {- setSessionId(null);- }- setSessionToDelete(null);- },- onError: (error) => {- toast({- title: "Failed to delete chat",- description:- error instanceof Error ? error.message : "An error occurred",- variant: "destructive",- });- setSessionToDelete(null);- },- },- });-- // --- Responsive ---- const breakpoint = useBreakpoint();- const isMobile =- breakpoint === "base" || breakpoint === "sm" || breakpoint === "md";-- const pendingFilesRef = useRef<File[]>([]);- // Pre-built file parts from workflow import (already uploaded, skip re-upload)- const pendingFilePartsRef = useRef<FileUIPart[]>([]);-- // --- Send pending message after session creation ---- useEffect(() => {- if (!sessionId || pendingMessage === null) return;- const msg = pendingMessage;- const files = pendingFilesRef.current;- const prebuiltParts = pendingFilePartsRef.current;- setPendingMessage(null);- pendingFilesRef.current = [];- pendingFilePartsRef.current = [];-- if (prebuiltParts.length > 0) {- // File already uploaded (e.g. workflow import) — send directly- sendMessage({ text: msg, files: prebuiltParts });- } else if (files.length > 0) {- setIsUploadingFiles(true);- void uploadFiles(files, sessionId)- .then((uploaded) => {- if (uploaded.length === 0) {- toast({- title: "File upload failed",- description: "Could not upload any files. Please try again.",- variant: "destructive",- });- return;- }- const fileParts = buildFileParts(uploaded);- sendMessage({- text: msg,- files: fileParts.length > 0 ? fileParts : undefined,- });- })- .finally(() => setIsUploadingFiles(false));- } else {- sendMessage({ text: msg });- }- }, [sessionId, pendingMessage, sendMessage]);-- // --- Extract prompt from URL hash on mount (e.g. /copilot#prompt=Hello) ---- useWorkflowImportAutoSubmit({+ const {+ onSend: sendNewMessage,+ isUploadingFiles,+ setPendingFileParts,+ } = useSendMessage({+ sessionId,+ sendMessage,createSession,- setPendingMessage,- pendingFilePartsRef,+ isUserStoppingRef,});- async function uploadFiles(- files: File[],- sid: string,- ): Promise<UploadedFile[]> {- const results = await Promise.allSettled(- files.map(async (file) => {- try {- const data = await uploadFileDirect(file, sid);- if (!data.file_id) throw new Error("No file_id returned");- return {- file_id: data.file_id,- name: data.name || file.name,- mime_type: data.mime_type || "application/octet-stream",- } as UploadedFile;- } catch (err) {- console.error("File upload failed:", err);- toast({- title: "File upload failed",- description: file.name,- variant: "destructive",- });- throw err;- }- }),- );- return results- .filter(- (r): r is PromiseFulfilledResult<UploadedFile> =>- r.status === "fulfilled",- )- .map((r) => r.value);- }-- function buildFileParts(uploaded: UploadedFile[]): FileUIPart[] {- return uploaded.map((f) => ({- type: "file" as const,- mediaType: f.mime_type,- filename: f.name,- url: `/api/proxy/api/workspace/files/${f.file_id}/download`,- }));- }-+ // Wrap sendNewMessage with queue-in-flight routing: if a session is active+ // and a turn is already running, POST the follow-up text to the pending+ // endpoint so the backend buffers it; otherwise fall through to normal send.async function onSend(message: string, files?: File[]) {const trimmed = message.trim();if (!trimmed && (!files || files.length === 0)) return;- // Client-side file limits- if (files && files.length > 0) {- const MAX_FILES = 10;- const MAX_FILE_SIZE_BYTES = 100 * 1024 * 1024; // 100 MB-- if (files.length > MAX_FILES) {+ if (sessionId && isInflightRef.current) {+ if (files && files.length > 0) {toast({- title: "Too many files",- description: `You can attach up to ${MAX_FILES} files at once.`,+ title: "Please wait to attach files",+ description:+ "File attachments can't be queued until the current response finishes.",variant: "destructive",});return;}- const oversized = files.filter((f) => f.size > MAX_FILE_SIZE_BYTES);- if (oversized.length > 0) {+ try {+ await queueFollowUpMessage(sessionId, trimmed);+ appendChip(trimmed);+ } catch (err) {+ if (+ err instanceof Error &&+ err.name === "QueueFollowUpNotActiveError"+ ) {+ await sendNewMessage(message, files);+ return;+ }toast({- title: "File too large",- description: `${oversized[0].name} exceeds the 100 MB limit.`,+ title: "Could not queue message",+ description: "Please wait for the current response to finish.",variant: "destructive",});- return;+ throw err;}+ return;}- isUserStoppingRef.current = false;-+ // Mark in-flight synchronously before dispatching so a rapid second+ // press sees isInflightRef.current=true and routes to the queue path+ // instead of triggering a duplicate /stream POST.if (sessionId) {- const isInFlight = isInflightRef.current;-- if (isInFlight) {- // File attachments cannot be included in a queued pending message —- // the queue API does not support file_ids. Inform the user and bail.- if (files && files.length > 0) {- toast({- title: "Please wait to attach files",- description:- "File attachments can't be queued until the current response finishes.",- variant: "destructive",- });- return;- }-- // Queue the follow-up into the pending buffer. Both queue and new-- // turn go through the same ``/stream`` endpoint; the server returns- // 202 for the queue path (pending buffer) and an SSE stream for the- // new-turn path. Using a plain ``fetch`` here keeps the 202 JSON- // from confusing the AI SDK's stream parser.- try {- const result = await queueFollowUpMessage(sessionId, trimmed);- if (result.kind === "queued") {- appendChip(trimmed);- }- // kind === "raced_started_turn": the client thought a turn was in- // flight but the previous turn finished before the request landed.- // The server already kicked off a new turn; useHydrateOnStreamEnd- // will surface its output when it completes. No chip + no toast.- } catch (err) {- toast({- title: "Could not queue message",- description: "Please wait for the current response to finish.",- variant: "destructive",- });- throw err;- }- return;- }-- // Mark in-flight synchronously before sendMessage so any rapid- // second press sees isInflightRef.current=true and routes to /pending- // instead of triggering a duplicate /stream POST.isInflightRef.current = true;- if (files && files.length > 0) {- setIsUploadingFiles(true);- try {- const uploaded = await uploadFiles(files, sessionId);- if (uploaded.length === 0) {- // All uploads failed — abort send so chips revert to editable- isInflightRef.current = false;- throw new Error("All file uploads failed");- }- const fileParts = buildFileParts(uploaded);- sendMessage({- text: trimmed || "",- files: fileParts.length > 0 ? fileParts : undefined,- });- } finally {- setIsUploadingFiles(false);- }- } else {- sendMessage({ text: trimmed });- }- return;}-- setPendingMessage(trimmed || "");- if (files && files.length > 0) {- pendingFilesRef.current = files;- }- await createSession();+ await sendNewMessage(message, files);}- // --- Session list (for mobile drawer & sidebar) ---- const { data: sessionsResponse, isLoading: isLoadingSessions } =- useGetV2ListSessions(- { limit: 50 },- { query: { enabled: !isUserLoading && isLoggedIn } },- );-- const sessions =- sessionsResponse?.status === 200 ? sessionsResponse.data.sessions : [];-- // Start title polling when stream ends cleanly — sidebar title animates in- const titlePollRef = useRef<ReturnType<typeof setInterval>>();- const prevStatusRef = useRef(status);+ useWorkflowImportAutoSubmit({ onSend, setPendingFileParts });- useEffect(() => {- const prev = prevStatusRef.current;- prevStatusRef.current = status;-- const wasActive = prev === "streaming" || prev === "submitted";- const isNowReady = status === "ready";-- if (!wasActive || !isNowReady || !sessionId || isReconnecting) return;-- queryClient.invalidateQueries({- queryKey: getGetV2ListSessionsQueryKey({ limit: 50 }),- });- const sid = sessionId;- let attempts = 0;- clearInterval(titlePollRef.current);- titlePollRef.current = setInterval(() => {- const data = queryClient.getQueryData<getV2ListSessionsResponse>(- getGetV2ListSessionsQueryKey({ limit: 50 }),- );- const hasTitle =- data?.status === 200 &&- data.data.sessions.some((s) => s.id === sid && s.title);- if (hasTitle || attempts >= TITLE_POLL_MAX_ATTEMPTS) {- clearInterval(titlePollRef.current);- titlePollRef.current = undefined;- return;- }- attempts += 1;- queryClient.invalidateQueries({- queryKey: getGetV2ListSessionsQueryKey({ limit: 50 }),- });- }, TITLE_POLL_INTERVAL_MS);- }, [status, sessionId, isReconnecting, queryClient]);-- // Clean up polling on session change or unmount- useEffect(() => {- return () => {- clearInterval(titlePollRef.current);- titlePollRef.current = undefined;- };- }, [sessionId]);-- // --- Mobile drawer handlers ---- function handleOpenDrawer() {- setDrawerOpen(true);- }-- function handleCloseDrawer() {- setDrawerOpen(false);- }-- function handleDrawerOpenChange(open: boolean) {- setDrawerOpen(open);- }-- function handleSelectSession(id: string) {- setSessionId(id);- if (isMobile) setDrawerOpen(false);- }-- function handleNewChat() {- setSessionId(null);- if (isMobile) setDrawerOpen(false);- }-- // --- Delete handlers ---- function handleDeleteClick(id: string, title: string | null | undefined) {- if (isDeleting) return;- setSessionToDelete({ id, title });- }-- function handleConfirmDelete() {- if (sessionToDelete) {- deleteSessionMutation({ sessionId: sessionToDelete.id });- }- }-- function handleCancelDelete() {- if (!isDeleting) {- setSessionToDelete(null);- }- }+ useSessionTitlePoll({ sessionId, status, isReconnecting });return {sessionId,- messages,+ messages: displayMessages,status,error,stop,isReconnecting,- isSyncing,+ isRestoringActiveSession,+ restoreStatusMessage,+ activeStreamStartedAt,+ isUserStopping,isLoadingSession,isSessionError,isCreatingSession,@@ -475,41 +238,19 @@ export function useCopilotPage() {isLoggedIn,createSession,onSend,- // onEnqueue delegates to onSend, which internally routes to the pending+ // onEnqueue delegates to onSend, which internally routes to the queue// endpoint when isInflightRef.current is true.onEnqueue: onSend,queuedMessages,- // PaginationhasMoreMessages: hasMore,isLoadingMore,loadMore,- // Mobile drawer- isMobile,- isDrawerOpen,- sessions,- isLoadingSessions,- handleOpenDrawer,- handleCloseDrawer,- handleDrawerOpenChange,- handleSelectSession,- handleNewChat,- // Delete functionality- sessionToDelete,- isDeleting,- handleDeleteClick,- handleConfirmDelete,- handleCancelDelete,- // Per-message stats (duration + reasoning duration + timestamp)turnStats,- // Rate limit resetrateLimitMessage,dismissRateLimit,- // Dry run dev toggle- // isDryRun = global preference for NEW sessions (from localStorage).- // sessionDryRun = actual dry_run value of the CURRENT session (from API).- // Use isDryRun to configure future sessions; use sessionDryRun to display- // the current session's simulation state (banner, indicators).- isDryRun,+ // sessionDryRun is the CURRENT session's immutable dry_run flag from API,+ // used to render the banner. The global `isDryRun` preference (for new+ // sessions) lives in the store and is consumed by the toggle button.sessionDryRun,};}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotReconnect.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotReconnect.tsnew file mode 100644index 0000000000..e224017850--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotReconnect.ts@@ -0,0 +1,174 @@+import { toast } from "@/components/molecules/Toast/use-toast";+import { useMountEffect } from "@/hooks/useMountEffect";+import { useEffect, useRef, useState } from "react";++const RECONNECT_BASE_DELAY_MS = 1_000;+const RECONNECT_MAX_ATTEMPTS = 3;++/** Max time (ms) the UI can stay in "reconnecting" state before forcing idle. */+const RECONNECT_MAX_DURATION_MS = 30_000;++type UseChatStatus = "submitted" | "streaming" | "ready" | "error";++interface UseCopilotReconnectArgs {+ sessionId: string | null;+ hasActiveStream: boolean;+ /**+ * Current `useChat` status — used to clear the forced-idle timer the moment+ * the stream is back live, and to reset the reconnect counters once a turn+ * completes cleanly.+ */+ status: UseChatStatus;+ /** True once this mount has received meaningful replay/live content. */+ hasConnectedThisMountRef: React.MutableRefObject<boolean>;+ /**+ * Ref holding `useChat`'s latest `resumeStream`. Kept in a ref so the+ * timer callback always invokes the current value without stale closures.+ */+ resumeStreamRef: React.MutableRefObject<() => void>;+ /**+ * Flipped to `true` when a reconnect actually fires, so a deferred+ * page-load resume (queued in `pendingResumeRef` while hydration was in+ * flight) can't double-fire `resumeStream()` once hydration completes.+ */+ hasResumedRef: React.MutableRefObject<boolean>;+}++/**+ * Owns the reconnect lifecycle for `useCopilotStream`:+ * - exponential backoff with 3-attempt cap + terminal toast+ * - a concurrent 30 s forced-idle timer so the UI can never get stuck+ * "reconnecting" if the backend is slow to clear `active_stream`+ * - self-clears the forced-idle timer the moment status returns to active+ * - self-resets counters + exhausted flag when a turn completes cleanly+ * - self-clears armed timers on unmount so they can't toast into the void+ *+ * All state here is session-scoped by lifetime — the parent subtree is+ * keyed `key={sessionId}` by `CopilotPage`, so a session switch remounts+ * this hook and every ref resets naturally.+ */+export function useCopilotReconnect({+ sessionId,+ hasActiveStream,+ status,+ hasConnectedThisMountRef,+ resumeStreamRef,+ hasResumedRef,+}: UseCopilotReconnectArgs) {+ const [isReconnectScheduled, setIsReconnectScheduled] = useState(false);+ const [reconnectExhausted, setReconnectExhausted] = useState(false);++ const reconnectScheduledRef = useRef(false);+ const reconnectAttemptsRef = useRef(0);+ const reconnectStartedAtRef = useRef<number | null>(null);+ const hasShownDisconnectToastRef = useRef(false);+ const reconnectTimerRef = useRef<ReturnType<typeof setTimeout>>();+ const reconnectTimeoutTimerRef = useRef<ReturnType<typeof setTimeout>>();++ function handleReconnect() {+ if (!sessionId) return;+ if (reconnectScheduledRef.current) return;++ const nextAttempt = reconnectAttemptsRef.current + 1;+ if (nextAttempt > RECONNECT_MAX_ATTEMPTS) {+ clearTimeout(reconnectTimeoutTimerRef.current);+ reconnectTimeoutTimerRef.current = undefined;+ setReconnectExhausted(true);+ toast({+ title: "Connection lost",+ description: "Unable to reconnect. Please refresh the page.",+ variant: "destructive",+ });+ return;+ }++ // Arm the forced-timeout the first time a reconnect starts in this cycle.+ if (reconnectStartedAtRef.current === null) {+ reconnectStartedAtRef.current = Date.now();+ clearTimeout(reconnectTimeoutTimerRef.current);+ reconnectTimeoutTimerRef.current = setTimeout(() => {+ // Cancel the pending reconnect timer so it can't fire resumeStream()+ // after the UI has been forced to idle — otherwise we'd end up in an+ // inconsistent state (reconnectExhausted=true + a fresh stream).+ clearTimeout(reconnectTimerRef.current);+ reconnectTimerRef.current = undefined;+ reconnectScheduledRef.current = false;+ reconnectStartedAtRef.current = null;+ setIsReconnectScheduled(false);+ setReconnectExhausted(true);+ toast({+ title: "Connection timed out",+ description:+ "AutoPilot may still be working. Refresh to check for updates.",+ variant: "destructive",+ });+ }, RECONNECT_MAX_DURATION_MS);+ }++ reconnectScheduledRef.current = true;+ reconnectAttemptsRef.current = nextAttempt;+ setIsReconnectScheduled(true);++ if (!hasShownDisconnectToastRef.current) {+ hasShownDisconnectToastRef.current = true;+ toast({ title: "Connection lost", description: "Reconnecting..." });+ }++ const delay = RECONNECT_BASE_DELAY_MS * 2 ** (nextAttempt - 1);+ reconnectTimerRef.current = setTimeout(() => {+ reconnectScheduledRef.current = false;+ // Mark resumed so a deferred page-load resume (queued in+ // pendingResumeRef while hydration was in flight) can't double-fire.+ hasResumedRef.current = true;+ setIsReconnectScheduled(false);+ resumeStreamRef.current();+ }, delay);+ }++ // Auto-clear the forced-idle timer the moment the stream is back live,+ // and reset counters once a turn completes cleanly.+ useEffect(() => {+ if (!sessionId) return;+ const isNowActive = status === "streaming" || status === "submitted";++ if (+ isNowActive &&+ reconnectStartedAtRef.current !== null &&+ hasConnectedThisMountRef.current+ ) {+ reconnectStartedAtRef.current = null;+ clearTimeout(reconnectTimeoutTimerRef.current);+ reconnectTimeoutTimerRef.current = undefined;+ }++ if (status === "ready" && !reconnectScheduledRef.current) {+ const stillRestoringWithoutConnection =+ hasActiveStream && !hasConnectedThisMountRef.current;+ if (stillRestoringWithoutConnection) return;+ reconnectAttemptsRef.current = 0;+ hasShownDisconnectToastRef.current = false;+ reconnectStartedAtRef.current = null;+ clearTimeout(reconnectTimeoutTimerRef.current);+ reconnectTimeoutTimerRef.current = undefined;+ setReconnectExhausted(false);+ }+ }, [status, sessionId, hasActiveStream, hasConnectedThisMountRef]);++ // Clear armed timers on unmount so they can't toast into the void after+ // the host is gone.+ useMountEffect(() => {+ return () => {+ clearTimeout(reconnectTimerRef.current);+ reconnectTimerRef.current = undefined;+ clearTimeout(reconnectTimeoutTimerRef.current);+ reconnectTimeoutTimerRef.current = undefined;+ };+ });++ return {+ isReconnectScheduled,+ reconnectExhausted,+ reconnectScheduledRef,+ handleReconnect,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStop.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStop.tsnew file mode 100644index 0000000000..c8220657c2--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStop.ts@@ -0,0 +1,98 @@+import { postV2CancelSessionTask } from "@/app/api/__generated__/endpoints/chat/chat";+import { toast } from "@/components/molecules/Toast/use-toast";+import type { UseChatHelpers } from "@ai-sdk/react";+import type { UIMessage } from "ai";+import { resolveInProgressTools } from "./helpers";++/**+ * User-visible marker appended to the last assistant message so the UI+ * renders a "You manually stopped this chat" row the moment the SSE is+ * aborted. The backend writes the same marker to the DB, so a subsequent+ * reload shows the same state. Must match `COPILOT_ERROR_PREFIX` in+ * `ChatMessagesContainer/helpers.ts`.+ */+const CANCELLED_MARKER = "[__COPILOT_ERROR_f7a1__] Operation cancelled";++interface UseCopilotStopArgs {+ sessionId: string | null;+ sdkStop: () => void;+ setMessages: UseChatHelpers<UIMessage>["setMessages"];+ /** Flipped to `true` so the stream's onError/onFinish callbacks don't+ * misinterpret the resulting AbortError as a disconnect + reconnect. */+ isUserStoppingRef: React.MutableRefObject<boolean>;+ /** State setter mirroring ``isUserStoppingRef`` — drives the UI so the+ * stop-button UX flips immediately instead of waiting for AI SDK's+ * ``status`` to transition away from "streaming" on abort. */+ setIsUserStopping: (value: boolean) => void;+}++/**+ * Build the `stop` handler for `useCopilotStream`.+ *+ * Wraps AI-SDK's `stop()` to:+ * 1. flag the stop as user-initiated (so onError/onFinish don't reconnect)+ * 2. abort the SSE fetch synchronously for instant UI feedback+ * 3. inject a cancellation marker into the visible assistant message+ * 4. asynchronously tell the backend executor to actually stop the task,+ * surfacing a toast when the cancel was published but not yet+ * confirmed (the task should stop shortly) or failed outright.+ */+export function useCopilotStop({+ sessionId,+ sdkStop,+ setMessages,+ isUserStoppingRef,+ setIsUserStopping,+}: UseCopilotStopArgs) {+ async function stop() {+ isUserStoppingRef.current = true;+ setIsUserStopping(true);+ try {+ sdkStop();+ } catch {+ // sdkStop throws if no fetch is in flight — the user-stop flag+ // already flipped, so the UI reflects the intent either way.+ }+ setMessages((prev) => {+ const resolved = resolveInProgressTools(prev, "cancelled");+ const last = resolved[resolved.length - 1];+ if (last?.role === "assistant") {+ return [+ ...resolved.slice(0, -1),+ {+ ...last,+ parts: [+ ...last.parts,+ { type: "text" as const, text: CANCELLED_MARKER },+ ],+ },+ ];+ }+ return resolved;+ });++ if (!sessionId) return;+ try {+ const res = await postV2CancelSessionTask(sessionId);+ if (+ res.status === 200 &&+ "reason" in res.data &&+ res.data.reason === "cancel_published_not_confirmed"+ ) {+ toast({+ title: "Stop may take a moment",+ description:+ "The cancel was sent but not yet confirmed. The task should stop shortly.",+ });+ }+ } catch {+ toast({+ title: "Could not stop the task",+ description: "The task may still be running in the background.",+ variant: "destructive",+ });+ }+ }++ return stop;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.tsindex d217a7789e..e10d4c40f0 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts@@ -1,47 +1,46 @@import {getGetV2GetCopilotUsageQueryKey,getGetV2GetSessionQueryKey,- postV2CancelSessionTask,} from "@/app/api/__generated__/endpoints/chat/chat";import { toast } from "@/components/molecules/Toast/use-toast";-import { environment } from "@/services/environment";+import { useMountEffect } from "@/hooks/useMountEffect";import { useChat } from "@ai-sdk/react";import { useQueryClient } from "@tanstack/react-query";-import { DefaultChatTransport } from "ai";-import type { FileUIPart, UIMessage } from "ai";+import type { UIMessage } from "ai";import { useEffect, useMemo, useRef, useState } from "react";import {- getCopilotAuthHeaders,+ getOrCreateCopilotChatRuntime,+ markCopilotChatRuntimeHealthy,+ resetCopilotChatRuntime,+ shouldReloadCopilotChatRuntime,+} from "./copilotChatRegistry";+import { handleStreamError } from "./copilotStreamErrorHandlers";+import { useCopilotStreamStore } from "./copilotStreamStore";+import {deduplicateMessages,extractSendMessageText,- hasActiveBackendStream,- resolveInProgressTools,+ getLatestAssistantStatusMessage,getSendSuppressionReason,- disconnectSessionStream,- shouldDebounceReconnect,+ hasActiveBackendStream,+ hasInProgressAssistantParts,+ hasVisibleAssistantContent,} from "./helpers";import { useCopilotUIStore } from "./store";import type { CopilotLlmModel, CopilotMode } from "./store";+import { useCopilotReconnect } from "./useCopilotReconnect";+import { useCopilotStop } from "./useCopilotStop";import { useHydrateOnStreamEnd } from "./useHydrateOnStreamEnd";--const RECONNECT_BASE_DELAY_MS = 1_000;-const RECONNECT_MAX_ATTEMPTS = 3;+import { RESTORE_STALL_TIMEOUT_MS } from "./restoreConstants";+import { useStreamActivityWatchdog } from "./useStreamActivityWatchdog";+import { useWakeResync } from "./useWakeResync";/**- * Minimum spacing between successive reconnect attempts.- * `isReconnectScheduledRef` already prevents OVERLAPPING reconnects, but- * tab-throttle / visibility wake bursts can fire `onFinish(isDisconnect)`- * several times inside a single second — each one would schedule a fresh- * reconnect the moment the previous timer cleared the ref. Requests that- * arrive inside this window since the last reconnect's resume are COALESCED:- * scheduled to run at the window boundary rather than dropped, so a- * fast-failing resume (e.g. a 502 on GET /stream that trips `onError` inside- * 500 ms) still retries instead of stalling the retry loop.+ * Delay after a clean stream close before refetching the session to check+ * whether the backend executor is still running. Without this, the refetch+ * races with the backend clearing `active_stream` and often reads a stale+ * `active_stream=true`, triggering unnecessary reconnect cycles.*/-const RECONNECT_DEBOUNCE_MS = 1_500;--/** Minimum time the page must have been hidden to trigger a wake re-sync. */-const WAKE_RESYNC_THRESHOLD_MS = 30_000;+const FINISH_REFETCH_SETTLE_MS = 500;interface UseCopilotStreamArgs {sessionId: string | null;@@ -68,157 +67,47 @@ export function useCopilotStream({function dismissRateLimit() {setRateLimitMessage(null);}- // Use refs for copilotMode and copilotModel so the transport closure always reads- // the latest value without recreating the DefaultChatTransport (which would- // reset useChat's internal Chat instance and break mid-session streaming).- const copilotModeRef = useRef(copilotMode);- copilotModeRef.current = copilotMode;- const copilotModelRef = useRef(copilotModel);- copilotModelRef.current = copilotModel;-- // Connect directly to the Python backend for SSE, bypassing the Next.js- // serverless proxy. This eliminates the Vercel 800s function timeout that- // was the primary cause of stream disconnections on long-running tasks.- // Auth uses the same server-action token pattern as the WebSocket connection.- const transport = useMemo(- () =>- sessionId- ? new DefaultChatTransport({- api: `${environment.getAGPTServerBaseUrl()}/api/chat/sessions/${sessionId}/stream`,- prepareSendMessagesRequest: async ({ messages }) => {- const last = messages[messages.length - 1];- // Extract file_ids from FileUIPart entries on the message- const fileIds = last.parts- ?.filter((p): p is FileUIPart => p.type === "file")- .map((p) => {- // URL is like /api/proxy/api/workspace/files/{id}/download- const match = p.url.match(/\/workspace\/files\/([^/]+)\//);- return match?.[1];- })- .filter(Boolean) as string[] | undefined;- return {- body: {- message: (- last.parts?.map((p) => (p.type === "text" ? p.text : "")) ??- []- ).join(""),- is_user_message: last.role === "user",- context: null,- file_ids: fileIds && fileIds.length > 0 ? fileIds : null,- mode: copilotModeRef.current ?? null,- model: copilotModelRef.current ?? null,- },- headers: await getCopilotAuthHeaders(),- };- },- prepareReconnectToStreamRequest: async () => ({- api: `${environment.getAGPTServerBaseUrl()}/api/chat/sessions/${sessionId}/stream`,- headers: await getCopilotAuthHeaders(),- }),- })- : null,- [sessionId],- );-- // Reconnect state — use refs for values read inside callbacks to avoid- // stale closures when multiple reconnect cycles fire in quick succession.- const reconnectAttemptsRef = useRef(0);- const isReconnectScheduledRef = useRef(false);- const [isReconnectScheduled, setIsReconnectScheduled] = useState(false);- const reconnectTimerRef = useRef<ReturnType<typeof setTimeout>>();- // Timestamp of the last reconnect's actual resume call — used together- // with RECONNECT_DEBOUNCE_MS to drop rapid duplicate reconnect requests- // (e.g. visibility throttle firing onFinish(isDisconnect) several times- // in the same second). 0 = no reconnect has fired yet in this session.- const lastReconnectResumeAtRef = useRef(0);- const hasShownDisconnectToast = useRef(false);- // Set when the user explicitly clicks stop — prevents onError from- // triggering a reconnect cycle for the resulting AbortError.- const isUserStoppingRef = useRef(false);- // Set when all reconnect attempts are exhausted — prevents hasActiveStream- // from keeping the UI blocked forever when the backend is slow to clear it.- // Must be state (not ref) so that setting it triggers a re-render and- // recomputes `isReconnecting`.- const [reconnectExhausted, setReconnectExhausted] = useState(false);- // True while performing a wake re-sync (blocks chat input).- const [isSyncing, setIsSyncing] = useState(false);- // Tracks the last time the page was hidden — used to detect sleep/wake gaps.- const lastHiddenAtRef = useRef(Date.now());-- function handleReconnect(sid: string) {- if (isReconnectScheduledRef.current || !sid) return;-- // Debounce: if the previous reconnect resumed within the last- // RECONNECT_DEBOUNCE_MS, COALESCE this request onto the window boundary- // rather than dropping it. Browser tab-throttle bursts can fire- // onFinish(isDisconnect) 2–3 times in a second; without the debounce,- // each fires its own GET /stream, each one replays the Redis stream,- // and the flicker storm is back. Dropping the request silently (the- // previous behaviour) stalled the retry loop when a resume failed- // quickly — e.g. a 502 on GET /stream that trips onError inside 500 ms- // while the 1500 ms window is still open. Scheduling the retry for- // the remaining window preserves both the storm cap and the retry.- const remainingDelay = shouldDebounceReconnect(- lastReconnectResumeAtRef.current,- Date.now(),- RECONNECT_DEBOUNCE_MS,- );- if (remainingDelay !== null) {- isReconnectScheduledRef.current = true;- setIsReconnectScheduled(true);- reconnectTimerRef.current = setTimeout(() => {- isReconnectScheduledRef.current = false;- setIsReconnectScheduled(false);- handleReconnect(sid);- }, remainingDelay);- return;- }-- const nextAttempt = reconnectAttemptsRef.current + 1;- if (nextAttempt > RECONNECT_MAX_ATTEMPTS) {- setReconnectExhausted(true);- toast({- title: "Connection lost",- description: "Unable to reconnect. Please refresh the page.",- variant: "destructive",- });- return;- }-- isReconnectScheduledRef.current = true;- setIsReconnectScheduled(true);- reconnectAttemptsRef.current = nextAttempt;-- if (!hasShownDisconnectToast.current) {- hasShownDisconnectToast.current = true;- toast({- title: "Connection lost",- description: "Reconnecting...",- });+ const chatRuntime = useMemo(() => {+ if (!sessionId) return null;+ if (shouldReloadCopilotChatRuntime(sessionId)) {+ resetCopilotChatRuntime(sessionId);}-- const delay = RECONNECT_BASE_DELAY_MS * 2 ** (nextAttempt - 1);-- reconnectTimerRef.current = setTimeout(() => {- isReconnectScheduledRef.current = false;- setIsReconnectScheduled(false);- // Strip the stale in-progress assistant message before resuming —- // the backend replays from "0-0", so keeping it would duplicate parts.- setMessages((prev) => {- if (prev.length > 0 && prev[prev.length - 1].role === "assistant") {- return prev.slice(0, -1);- }- return prev;- });- lastReconnectResumeAtRef.current = Date.now();- resumeStreamRef.current();- }, delay);+ return getOrCreateCopilotChatRuntime(sessionId);+ }, [sessionId]);+ if (chatRuntime) {+ chatRuntime.copilotModeRef.current = copilotMode;+ chatRuntime.copilotModelRef.current = copilotModel;}- // Tracks the ID of the last user message that was submitted via sendMessage.- // During a reconnect cycle, if the session already contains this message, we- // must not POST it again — only GET-resume is safe.- const lastSubmittedMsgRef = useRef<string | null>(null);+ // Transient per-mount flags. The parent keys this subtree by sessionId,+ // so every session-switch remounts and these refs reset naturally —+ // no cross-session bleed, no blanket "clearCoord" on the Zustand store.+ const hasResumedRef = useRef(false);+ const hydrateCompletedRef = useRef(false);+ const pendingResumeRef = useRef<(() => void) | null>(null);+ // Synchronous flag read inside SDK callbacks — kept as a ref so callbacks+ // don't have to trigger re-renders to observe changes. Scoped to this+ // mount (= this session), so a boolean is enough; cross-session scoping+ // is no longer needed because the parent remounts on session switch.+ const isUserStoppingRef = useRef(false);+ // State mirror of ``isUserStoppingRef`` — the ref is read synchronously+ // inside SDK callbacks, the state drives UI so a click on the stop button+ // immediately overrides ``isStreaming`` regardless of whether AI SDK has+ // flipped ``status`` back to ``ready`` yet (which can lag by many seconds+ // when aborting a GET-based resume fetch).+ const [isUserStopping, setIsUserStopping] = useState(false);+ // Flipped to `false` during mount cleanup so async callbacks that were+ // already in flight (e.g. the post-stream settle in `onFinish`) bail out+ // instead of arming new timers / HTTP requests against a torn-down mount.+ const isMountedRef = useRef(true);++ // Stable refs for resumeStream + handleReconnect, filled after the+ // corresponding hooks run below. `useChat`'s onFinish/onError closures+ // capture these refs at init and read `.current` at fire time, so the+ // circular "useChat needs handleReconnect and useCopilotReconnect needs+ // resumeStream" is resolved by deferring both through refs.+ const resumeStreamRef = useRef<() => void>(() => {});+ const handleReconnectRef = useRef<() => void>(() => {});const {messages: rawMessages,@@ -228,119 +117,177 @@ export function useCopilotStream({error,setMessages,resumeStream,- } = useChat({- id: sessionId ?? undefined,- transport: transport ?? undefined,- onFinish: async ({ isDisconnect, isAbort }) => {+ } = useChat(+ chatRuntime+ ? { chat: chatRuntime.chat }+ : {+ id: "new",+ },+ );++ useEffect(() => {+ if (!chatRuntime) return;++ async function handleFinish({+ isDisconnect,+ isAbort,+ }: {+ isDisconnect?: boolean;+ isAbort?: boolean;+ }) {if (isAbort || !sessionId) return;+ if (isUserStoppingRef.current) return;if (isDisconnect) {- handleReconnect(sessionId);+ handleReconnectRef.current();return;}- // Check if backend executor is still running after clean close.- // Brief delay to let the backend clear active_stream — without this,- // the refetch often races and sees stale active_stream=true, triggering- // unnecessary reconnect cycles.- await new Promise((r) => setTimeout(r, 500));+ await new Promise((r) => setTimeout(r, FINISH_REFETCH_SETTLE_MS));+ if (!isMountedRef.current) return;const result = await refetchSession();+ if (!isMountedRef.current) return;if (hasActiveBackendStream(result)) {- handleReconnect(sessionId);+ handleReconnectRef.current();}- },- onError: (error) => {+ }++ function handleError(error: Error) {if (!sessionId) return;+ handleStreamError({+ error,+ onRateLimit: (message) => {+ // Backend raises 429 BEFORE persisting the user message, so the+ // optimistic user bubble added by useChat is a lie. Restore the text+ // into the composer (via the same store slot URL pre-fills use) and+ // drop the unsent bubble so the user can edit/resend after reset.+ const unsentText =+ useCopilotStreamStore.getState().getCoord(sessionId)+ .lastSubmittedMessageText ?? null;+ if (unsentText) {+ // The 429 callback fires async — by the time it lands, the user+ // may have started typing a new draft. Only restore + clear the+ // recovery slot when the composer is empty; otherwise leave the+ // unsent text in the per-session store so a reload / resume can+ // surface it later instead of silently dropping it.+ const composer = document.getElementById(+ "chat-input",+ ) as HTMLTextAreaElement | null;+ const composerEmpty = !composer || composer.value.length === 0;+ if (composerEmpty) {+ setInitialPrompt(unsentText);+ useCopilotStreamStore+ .getState()+ .updateCoord(sessionId, { lastSubmittedMessageText: null });+ }+ setMessages((prev) => {+ const last = prev[prev.length - 1];+ if (last?.role === "user") return prev.slice(0, -1);+ return prev;+ });+ }+ setRateLimitMessage(message);+ },+ onReconnect: () => handleReconnectRef.current(),+ isUserStoppingRef,+ });+ }- // Detect rate limit (429) responses and show reset time to the user.- // The SDK throws a plain Error whose message is the raw response body- // (FastAPI returns {"detail": "...usage limit..."} for 429s).- let errorDetail: string = error.message;- try {- const parsed = JSON.parse(error.message) as unknown;- if (- typeof parsed === "object" &&- parsed !== null &&- "detail" in parsed &&- typeof (parsed as { detail: unknown }).detail === "string"- ) {- errorDetail = (parsed as { detail: string }).detail;- }- } catch {- // Not JSON — use message as-is+ chatRuntime.onFinish = handleFinish;+ chatRuntime.onError = handleError;++ return () => {+ if (chatRuntime.onFinish === handleFinish) {+ chatRuntime.onFinish = undefined;}- const isRateLimited = errorDetail.toLowerCase().includes("usage limit");- if (isRateLimited) {- // Backend raises 429 BEFORE persisting the user message, so the- // optimistic user bubble added by useChat is a lie. Restore the text- // into the composer (via the same store slot URL pre-fills use) and- // drop the unsent bubble so the user can edit/resend after reset.- const unsentText = lastSubmittedMsgRef.current;- if (unsentText) {- setInitialPrompt(unsentText);- lastSubmittedMsgRef.current = null;- setMessages((prev) => {- const last = prev[prev.length - 1];- if (last?.role === "user") return prev.slice(0, -1);- return prev;- });- }- setRateLimitMessage(- errorDetail ||- "You've reached your usage limit. Please try again later.",- );- return;+ if (chatRuntime.onError === handleError) {+ chatRuntime.onError = undefined;}+ };+ }, [chatRuntime, sessionId, refetchSession]);++ // Flipped to ``true`` the first time the user actually hits Send on this+ // mount. Lets the ``hasConnectedThisMountRef`` latch below distinguish+ // "resuming a turn that was already running" from "user sent a brand new+ // turn" — in the latter case the ThinkingIndicator is the right surface+ // from the first render, no "Retrieving latest messages" spinner needed.+ const hasSentThisMountRef = useRef(false);++ // Latch flips from ``false`` → ``true`` the first time the stream is+ // considered "live" on this mount. Observed by ``isRestoringActiveSession``+ // so the "Retrieving latest messages" spinner only shows while we haven't+ // yet connected.+ //+ // Flip conditions (either is sufficient):+ // 1. The user sent a fresh message this mount — we own the turn, so no+ // restore UI is appropriate even though status is briefly "submitted"+ // before the first byte lands.+ // 2. The stream is in an active state AND has produced at least one+ // visible assistant content part (text / reasoning with non-empty+ // text, any tool part, or a backend status). The ``isStreamLive``+ // gate is what distinguishes "bytes from the live SSE" from "content+ // just hydrated from the DB on a fresh mount" — without it, a+ // mid-stream refresh that lands a partial assistant message in+ // ``hydratedMessages`` would flip the latch before the GET-resume+ // produced anything, suppressing the restore spinner and disabling+ // the restore-stall watchdog. Checking content (not just status)+ // still keeps the indicator up during the GET-resume-no-bytes window.+ const hasConnectedThisMountRef = useRef(false);+ if (!hasConnectedThisMountRef.current) {+ const isStreamLive = status === "streaming" || status === "submitted";+ if (+ hasSentThisMountRef.current ||+ (isStreamLive &&+ (hasVisibleAssistantContent(rawMessages) ||+ getLatestAssistantStatusMessage(rawMessages) !== null))+ ) {+ hasConnectedThisMountRef.current = true;+ }+ }- // Detect authentication failures (from getCopilotAuthHeaders or 401 responses)- const isAuthError =- errorDetail.includes("Authentication failed") ||- errorDetail.includes("Unauthorized") ||- errorDetail.includes("Not authenticated") ||- errorDetail.toLowerCase().includes("401");- if (isAuthError) {- toast({- title: "Authentication error",- description: "Your session may have expired. Please sign in again.",- variant: "destructive",- });- return;- }+ function resumeStreamFromStart() {+ if (sessionId) {+ markCopilotChatRuntimeHealthy(sessionId);+ }+ setMessages((prev) => {+ const last = prev[prev.length - 1];+ return hasInProgressAssistantParts(last) ? prev.slice(0, -1) : prev;+ });+ resumeStream();+ }+ resumeStreamRef.current = resumeStreamFromStart;+ const sessionIdRef = useRef(sessionId);+ sessionIdRef.current = sessionId;- // Reconnect on network errors or transient API errors so the- // persisted retryable-error marker is loaded and the "Try Again"- // button appears. Without this, transient errors only show in the- // onError callback (where StreamError strips the retryable prefix).- if (isUserStoppingRef.current) return;- const isNetworkError =- error.name === "TypeError" || error.name === "AbortError";- const isTransientApiError = errorDetail.includes(- "connection interrupted",- );- if (isNetworkError || isTransientApiError) {- handleReconnect(sessionId);- }- },+ const {+ isReconnectScheduled,+ reconnectExhausted,+ reconnectScheduledRef,+ handleReconnect,+ } = useCopilotReconnect({+ sessionId,+ hasActiveStream,+ status,+ hasConnectedThisMountRef,+ resumeStreamRef,+ hasResumedRef,});-- // Keep stable refs to sdkStop and resumeStream so that async callbacks- // (session-switch cleanup, wake re-sync, reconnect timer) always call the- // latest version without stale-closure bugs.- const sdkStopRef = useRef(sdkStop);- sdkStopRef.current = sdkStop;- const resumeStreamRef = useRef(resumeStream);- resumeStreamRef.current = resumeStream;+ handleReconnectRef.current = handleReconnect;// Wrap sdkSendMessage to guard against re-sending the user message during a// reconnect cycle. If the session already has the message (i.e. we are in a// reconnect/resume flow), only GET-resume is safe — never re-POST.- const sendMessage: typeof sdkSendMessage = async (...args) => {+ async function sendMessage(+ ...args: Parameters<typeof sdkSendMessage>+ ): ReturnType<typeof sdkSendMessage> {const text = extractSendMessageText(args[0]);+ const sid = sessionId;+ const coord = sid ? useCopilotStreamStore.getState().getCoord(sid) : null;const suppressReason = getSendSuppressionReason({text,- isReconnectScheduled: isReconnectScheduledRef.current,- lastSubmittedText: lastSubmittedMsgRef.current,+ isReconnectScheduled: reconnectScheduledRef.current,+ lastSubmittedText: coord?.lastSubmittedMessageText ?? null,messages: rawMessages,});@@ -357,191 +304,132 @@ export function useCopilotStream({}if (suppressReason === "duplicate") return;- lastSubmittedMsgRef.current = text;- return sdkSendMessage(...args);- };-- // Deduplicate messages continuously to prevent duplicates when resuming streams- const messages = useMemo(- () => deduplicateMessages(rawMessages),- [rawMessages],- );-- // Wrap AI SDK's stop() to also cancel the backend executor task.- // sdkStop() aborts the SSE fetch instantly (UI feedback), then we fire- // the cancel API to actually stop the executor and wait for confirmation.- async function stop() {- isUserStoppingRef.current = true;- sdkStop();- // Resolve pending tool calls and inject a cancellation marker so the UI- // shows "You manually stopped this chat" immediately (the backend writes- // the same marker to the DB, but the SSE connection is already aborted).- // Marker must match COPILOT_ERROR_PREFIX in ChatMessagesContainer/helpers.ts.- setMessages((prev) => {- const resolved = resolveInProgressTools(prev, "cancelled");- const last = resolved[resolved.length - 1];- if (last?.role === "assistant") {- return [- ...resolved.slice(0, -1),- {- ...last,- parts: [- ...last.parts,- {- type: "text" as const,- text: "[__COPILOT_ERROR_f7a1__] Operation cancelled",- },- ],- },- ];- }- return resolved;- });-- if (!sessionId) return;- try {- const res = await postV2CancelSessionTask(sessionId);- if (- res.status === 200 &&- "reason" in res.data &&- res.data.reason === "cancel_published_not_confirmed"- ) {- toast({- title: "Stop may take a moment",- description:- "The cancel was sent but not yet confirmed. The task should stop shortly.",- });- }- } catch {- toast({- title: "Could not stop the task",- description: "The task may still be running in the background.",- variant: "destructive",- });+ if (sid) {+ markCopilotChatRuntimeHealthy(sid);+ useCopilotStreamStore+ .getState()+ .updateCoord(sid, { lastSubmittedMessageText: text });+ }+ hasSentThisMountRef.current = true;+ if (isUserStoppingRef.current) {+ isUserStoppingRef.current = false;+ }+ if (isUserStopping) {+ setIsUserStopping(false);}+ return sdkSendMessage(...args);}- // Keep a ref to sessionId so the async wake handler can detect staleness.- const sessionIdRef = useRef(sessionId);- sessionIdRef.current = sessionId;+ // Deduplicate messages continuously to prevent duplicates when resuming streams.+ const messages = deduplicateMessages(rawMessages);- // ---------------------------------------------------------------------------- // Wake detection: when the page becomes visible after being hidden for >30s- // (device sleep, tab backgrounded for a long time), refetch the session to- // pick up any messages the backend produced while the SSE was dead.- // ---------------------------------------------------------------------------useEffect(() => {- async function handleWakeResync() {- const sid = sessionIdRef.current;- if (!sid) return;-- const elapsed = Date.now() - lastHiddenAtRef.current;- lastHiddenAtRef.current = Date.now();-- if (document.visibilityState !== "visible") return;- if (elapsed < WAKE_RESYNC_THRESHOLD_MS) return;-- setIsSyncing(true);- try {- const result = await refetchSession();- // Bail out if the session changed while the refetch was in flight.- if (sessionIdRef.current !== sid) return;-- if (hasActiveBackendStream(result)) {- // Stream is still running — resume SSE to pick up live chunks.- // Remove stale in-progress assistant message first (backend replays- // from "0-0").- setMessages((prev) => {- if (prev.length > 0 && prev[prev.length - 1].role === "assistant") {- return prev.slice(0, -1);- }- return prev;- });- await resumeStreamRef.current();+ if (!sessionId) return;+ if (messages.length === 0) return;+ useCopilotStreamStore.getState().setMessageSnapshot(sessionId, messages);+ }, [sessionId, messages]);++ // Cheap signal that changes on any stream activity — drives the stall+ // watchdog. Counts messages, the last message's parts, and the total+ // text length on the last message so in-place part updates (token+ // streaming) also tick the signal.+ const streamActivityToken = useMemo(() => {+ const last = rawMessages[rawMessages.length - 1];+ let textLen = 0;+ if (last) {+ for (const part of last.parts) {+ if ("text" in part && typeof part.text === "string") {+ textLen += part.text.length;}- // If !backendActive, the refetch will update hydratedMessages via- // React Query, and the hydration effect below will merge them in.- } catch (err) {- console.warn("[copilot] wake re-sync failed", err);- } finally {- setIsSyncing(false);}}+ return `${rawMessages.length}:${last?.parts.length ?? 0}:${textLen}`;+ }, [rawMessages]);- function onVisibilityChange() {- if (document.visibilityState === "hidden") {- lastHiddenAtRef.current = Date.now();- } else {- handleWakeResync();- }- }+ const stop = useCopilotStop({+ sessionId,+ sdkStop,+ setMessages,+ isUserStoppingRef,+ setIsUserStopping,+ });- document.addEventListener("visibilitychange", onVisibilityChange);+ // Silent-stall watchdog: triggers the reconnect cascade if the stream+ // sits in "submitted" / "streaming" with no activity for 60 s. Handles+ // the case where AI SDK's onFinish / onError never fire (backend hung,+ // Redis zombie, etc.) and the UI would otherwise stay stuck forever.+ useStreamActivityWatchdog({+ sessionId,+ status,+ activityToken: streamActivityToken,+ isReconnectScheduled,+ isUserStoppingRef,+ handleReconnectRef,+ });++ // ---------------------------------------------------------------------------+ // Mount lifecycle:+ // - On unmount: mark this React subscriber as gone so async follow-up work+ // cannot set state into a torn-down mount.+ // - Do NOT abort the underlying session Chat runtime here. It is+ // intentionally kept alive in JS state so switching away from a chat does+ // not tear down its live SSE stream.+ // ---------------------------------------------------------------------------+ useMountEffect(() => {return () => {- document.removeEventListener("visibilitychange", onVisibilityChange);+ isMountedRef.current = false;};- }, [refetchSession, setMessages]);+ });++ // Wake detection: refetch + optional resume when the page becomes visible+ // after being hidden for >30 s. See `useWakeResync` for details.+ const { isSyncing } = useWakeResync({+ sessionIdRef,+ isMountedRef,+ refetchSession,+ resumeStreamRef,+ });// After-stream hydration — force-replace AI-SDK state with the DB's view// once React Query has actually refetched, then keep length-gated top-ups- // working for pagination. See useHydrateOnStreamEnd for the timing dance.+ // working for pagination. Also repairs zombie in-progress parts when the+ // backend confirms no active stream. See useHydrateOnStreamEnd for the+ // timing dance.useHydrateOnStreamEnd({+ sessionId,status,hydratedMessages,isReconnectScheduled,+ hasActiveStream,setMessages,});- // Track resume state per session- const hasResumedRef = useRef<Map<string, boolean>>(new Map());-- // Clean up reconnect state on session switch.- // Abort the old stream's in-flight fetch and tell the backend to release- // its XREAD listeners immediately (fire-and-forget).- const prevStreamSessionRef = useRef(sessionId);+ // Mark hydration complete in the transient ref whenever the hydration gate+ // has effectively run (hydrated data is present and we're not mid-stream),+ // and flush any `pendingResume` that was deferred while hydration was+ // still pending.useEffect(() => {- const prevSid = prevStreamSessionRef.current;- prevStreamSessionRef.current = sessionId;-- const isSwitching = Boolean(prevSid && prevSid !== sessionId);- if (isSwitching) {- // Mark BEFORE stopping so the old stream's async onError (which fires- // after the abort) sees the flag and short-circuits the reconnect path.- // Without this, the AbortError can queue a reconnect against the new- // session's `sessionId` (captured in the fresh onError closure).- isUserStoppingRef.current = true;- sdkStopRef.current();- disconnectSessionStream(prevSid!);- // Schedule the reset as a task (not a microtask) so it runs AFTER the- // aborted fetch's onError has fired — otherwise the new session would- // be stuck with the "user stopping" flag set, preventing auto-resume- // when hydration detects an active backend stream.- setTimeout(() => {- isUserStoppingRef.current = false;- }, 0);- } else {- isUserStoppingRef.current = false;- }-- clearTimeout(reconnectTimerRef.current);- reconnectTimerRef.current = undefined;- reconnectAttemptsRef.current = 0;- isReconnectScheduledRef.current = false;- setIsReconnectScheduled(false);- setRateLimitMessage(null);- hasShownDisconnectToast.current = false;- lastSubmittedMsgRef.current = null;- lastReconnectResumeAtRef.current = 0;- setReconnectExhausted(false);- setIsSyncing(false);- hasResumedRef.current.clear();- return () => {- clearTimeout(reconnectTimerRef.current);- reconnectTimerRef.current = undefined;- };- }, [sessionId]);+ if (!sessionId) return;+ if (!hydratedMessages) return;+ if (status === "streaming" || status === "submitted") return;+ if (isReconnectScheduled) return;- // Invalidate session cache when stream completes+ hydrateCompletedRef.current = true;+ const pending = pendingResumeRef.current;+ if (pending) {+ pendingResumeRef.current = null;+ pending();+ }+ }, [sessionId, hydratedMessages, status, isReconnectScheduled]);++ // Invalidate session + usage caches when the stream completes.+ // Reconnect counter/timer reset on the same transition is owned by+ // `useCopilotReconnect`, which watches `status` internally.+ // `lastSubmittedMessageText` is intentionally NOT cleared here: it prevents+ // `getSendSuppressionReason` from allowing a duplicate POST of the same+ // message immediately after a successful turn (the "duplicate" branch+ // checks both the store and the visible last user message, so legitimate+ // re-sends after a different reply are still allowed).const prevStatusRef = useRef(status);useEffect(() => {const prev = prevStatusRef.current;@@ -557,76 +445,129 @@ export function useCopilotStream({queryClient.invalidateQueries({queryKey: getGetV2GetCopilotUsageQueryKey(),});- if (status === "ready") {- reconnectAttemptsRef.current = 0;- hasShownDisconnectToast.current = false;- // Intentionally NOT clearing lastSubmittedMsgRef here: keeping the last- // submitted text prevents getSendSuppressionReason from allowing a- // duplicate POST of the same message immediately after a successful turn- // (the "duplicate" branch checks both the ref and the visible last user- // message, so legitimate re-sends after a different reply are still- // allowed).- setReconnectExhausted(false);- }}}, [status, sessionId, queryClient, isReconnectScheduled]);// Resume an active stream AFTER hydration completes.- // IMPORTANT: Only runs when page loads with existing active stream (reconnection).- // Does NOT run when new streams start during active conversation.+ // Only runs when this mount opens on a session with an already-active+ // backend stream (page reload OR session-switch-back). Does NOT run when+ // the user sends a new message mid-session (that goes through POST).+ // Gated on the transient `hydrateCompletedRef` to prevent racing the+ // hydration effect.useEffect(() => {if (!sessionId) return;if (!hasActiveStream) return;- if (!hydratedMessages || hydratedMessages.length === 0) return;+ if (!hydratedMessages) return;- // Never resume if currently streaming+ // Never resume if currently streaming.if (status === "streaming" || status === "submitted") return;- // Only resume once per session- if (hasResumedRef.current.get(sessionId)) return;+ // Only resume once per mount.+ if (hasResumedRef.current) return;- // Don't resume a stream the user just cancelled+ // Don't resume a stream the user just cancelled.if (isUserStoppingRef.current) return;- // Mark as resumed immediately to prevent race conditions- hasResumedRef.current.set(sessionId, true);+ function doResume() {+ if (!sessionId) return;+ if (hasResumedRef.current) return;+ if (isUserStoppingRef.current) return;+ hasResumedRef.current = true;+ resumeStreamRef.current();+ }- // Remove the in-progress assistant message before resuming.- // The backend replays the stream from "0-0", so keeping the hydrated- // version would cause the old parts to overlap with replayed parts.- // Previous turns are preserved; the stream recreates the current turn.- setMessages((prev) => {- if (prev.length > 0 && prev[prev.length - 1].role === "assistant") {- return prev.slice(0, -1);- }- return prev;- });+ // Wait for hydration to complete before resuming to prevent the two+ // effects from racing (duplicate messages / missing content).+ if (!hydrateCompletedRef.current) {+ pendingResumeRef.current = doResume;+ return;+ }- resumeStreamRef.current();- }, [sessionId, hasActiveStream, hydratedMessages, status, setMessages]);+ doResume();+ }, [sessionId, hasActiveStream, hydratedMessages, status]);// Clear messages when session is nulluseEffect(() => {if (!sessionId) setMessages([]);}, [sessionId, setMessages]);+ // Restore watchdog: if we reopened a session with an active backend stream+ // but still have not connected after 6 s of zero replay activity, verify+ // the backend still reports that stream as active and then kick the+ // reconnect cascade. This covers both "status stayed ready / no replay+ // chunks ever appeared" and "resume fetch is alive but only heartbeats are+ // flowing" — the latter never trips the normal stream-activity watchdog+ // because heartbeats do not mutate `messages`.+ useEffect(() => {+ if (!sessionId) return;+ if (!hasActiveStream) return;+ if (hasConnectedThisMountRef.current) return;+ if (isReconnectScheduled || reconnectExhausted) return;+ if (isUserStoppingRef.current) return;++ let cancelled = false;+ const timeout = setTimeout(async () => {+ if (cancelled) return;+ if (!isMountedRef.current) return;+ if (sessionIdRef.current !== sessionId) return;+ if (hasConnectedThisMountRef.current) return;+ if (isUserStoppingRef.current) return;++ const result = await refetchSession();+ if (!isMountedRef.current) return;+ if (sessionIdRef.current !== sessionId) return;+ if (hasConnectedThisMountRef.current) return;+ if (isUserStoppingRef.current) return;+ if (!hasActiveBackendStream(result)) return;++ handleReconnectRef.current();+ }, RESTORE_STALL_TIMEOUT_MS);++ return () => {+ cancelled = true;+ clearTimeout(timeout);+ };+ }, [+ sessionId,+ hasActiveStream,+ streamActivityToken,+ isReconnectScheduled,+ reconnectExhausted,+ refetchSession,+ ]);+// Reset the user-stop flag once the backend confirms the stream is no// longer active — this prevents the flag from staying stale forever.useEffect(() => {- if (!hasActiveStream && isUserStoppingRef.current) {+ if (hasActiveStream) return;+ if (isUserStoppingRef.current) {isUserStoppingRef.current = false;}- }, [hasActiveStream]);-- // True while reconnecting or backend has active stream but we haven't connected yet.- // Suppressed when the user explicitly stopped or when all reconnect attempts- // are exhausted — the backend may be slow to clear active_stream but the UI- // should remain responsive.+ if (isUserStopping) {+ setIsUserStopping(false);+ }+ }, [hasActiveStream, isUserStopping]);++ // True while reconnecting or backend has active stream but we haven't+ // connected yet on this mount. Once we've seen visible content this mount,+ // a lingering ``hasActiveStream=true`` from a slow session refetch (e.g.+ // backend still clearing metadata after the SSE finish) must NOT lock the+ // input — legitimate reconnect cases set ``isReconnectScheduled`` via+ // ``handleFinish`` / the watchdogs.const isReconnecting =!isUserStoppingRef.current &&!reconnectExhausted &&(isReconnectScheduled ||- (hasActiveStream && status !== "streaming" && status !== "submitted"));+ (hasActiveStream &&+ !hasConnectedThisMountRef.current &&+ status !== "streaming" &&+ status !== "submitted"));++ const isRestoringActiveSession =+ !isUserStoppingRef.current &&+ !reconnectExhausted &&+ hasActiveStream &&+ !hasConnectedThisMountRef.current;return {messages,@@ -636,8 +577,10 @@ export function useCopilotStream({status,error: isReconnecting || isUserStoppingRef.current ? undefined : error,isReconnecting,+ isRestoringActiveSession,isSyncing,isUserStoppingRef,+ isUserStopping,rateLimitMessage,dismissRateLimit,};diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useHydrateOnStreamEnd.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useHydrateOnStreamEnd.tsindex 815d7fb3d3..f034db68df 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useHydrateOnStreamEnd.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useHydrateOnStreamEnd.ts@@ -1,19 +1,95 @@+import { toast } from "@/components/molecules/Toast/use-toast";import type { UIMessage } from "ai";import { useEffect, useRef } from "react";-import { deduplicateMessages } from "./helpers";+import {+ deduplicateMessages,+ hasInProgressAssistantParts,+ resolveInterruptedMessage,+} from "./helpers";++const PROMOTED_BUBBLE_ID_PREFIX = "promoted-";++function getMessageText(message: UIMessage): string {+ return message.parts+ .map((part) => (part.type === "text" && "text" in part ? part.text : ""))+ .join("\n\n")+ .trim();+}++/**+ * When force-hydrating after a stream ends, replace the in-memory messages+ * with the canonical DB state — but preserve any ``promoted-*`` bubbles+ * (mid-turn or auto-continue chip promotions) whose text isn't reflected in+ * the hydrated user messages yet. This covers the rare case where Claude+ * already saw the queued message (via mid-turn injection) but the persist+ * step rolled back, so the DB row never landed; without this guard, the+ * user sees their message disappear from the feed even though the LLM+ * responded to it.+ */+function preservePromotedUserBubbles(+ prev: UIMessage[],+ hydrated: UIMessage[],+): UIMessage[] {+ const promoted = prev.filter(+ (m) =>+ typeof m.id === "string" && m.id.startsWith(PROMOTED_BUBBLE_ID_PREFIX),+ );+ if (promoted.length === 0) return hydrated;++ const hydratedUserText = hydrated+ .filter((m) => m.role === "user")+ .map(getMessageText)+ .join("\n\n");++ const orphans = promoted.filter((bubble) => {+ const bubbleText = getMessageText(bubble);+ if (!bubbleText) return false;+ return !hydratedUserText.includes(bubbleText);+ });+ if (orphans.length === 0) return hydrated;++ return [...hydrated, ...orphans];+}type ChatStatus = "submitted" | "streaming" | "ready" | "error";+// Survive remount on session re-entry: useRef would reset every time+// CopilotPage's <Component key={sessionId}/> remounts the tree, causing+// the "previous response was interrupted" toast to fire again on every+// re-entry into an affected session. Module-scoped so it persists for+// the page lifetime.+const sessionsWithInterruptedToastShown = new Set<string>();+interface Args {+ /**+ * Active session id. Used to key the "interrupted-toast already shown"+ * ledger so the warning fires at most once per session per page load.+ * ``null`` is allowed for the brief window before a session is bound;+ * the toast simply won't be deduped during that window.+ */+ sessionId: string | null;status: ChatStatus;hydratedMessages: UIMessage[] | undefined;isReconnectScheduled: boolean;+ /**+ * Whether the backend currently has an active SSE stream for this+ * session. Used to gate zombie-part recovery — if the backend is still+ * streaming we leave in-progress parts alone (resume will fill them+ * in); if it isn't, we finalise them so spinners stop and the user can+ * resend.+ */+ hasActiveStream: boolean;setMessages: (updater: UIMessage[] | ((prev: UIMessage[]) => UIMessage[]),) => void;}+/** Test hook: clear the per-session interrupted-toast ledger. */+export function _resetInterruptedToastLedgerForTests() {+ sessionsWithInterruptedToastShown.clear();+}+/*** After a stream ends, replace the in-memory AI SDK messages with the* definitive DB state, then keep length-gated top-ups working for later@@ -29,11 +105,21 @@ interface Args {* that was current at that moment, and refuse to force-hydrate until React* Query swaps in a new reference. Once we see a fresh reference, replace* and clear the flag.+ *+ * **Zombie-part recovery**: if the DB's view of the last assistant message+ * has parts still in ``streaming`` / ``input-streaming`` /+ * ``input-available`` AND the backend confirms no active stream, resolve+ * them via ``resolveInterruptedMessage`` and surface a passive toast.+ * This covers the case where the user switched away mid-stream, the+ * backend crashed before finalising, and the user returned to a session+ * the UI would otherwise render with permanent spinners.*/export function useHydrateOnStreamEnd({+ sessionId,status,hydratedMessages,isReconnectScheduled,+ hasActiveStream,setMessages,}: Args) {const prevStatusRef = useRef(status);@@ -59,22 +145,56 @@ export function useHydrateOnStreamEnd({if (status === "streaming" || status === "submitted") return;if (isReconnectScheduled) return;+ const deduped = deduplicateMessages(hydratedMessages);+ const needsZombieRecovery =+ !hasActiveStream &&+ hasInProgressAssistantParts(deduped[deduped.length - 1]);+ const finalized = needsZombieRecovery+ ? resolveInterruptedMessage(deduped)+ : deduped;++ // The stale-ref guard below holds back the force-hydrate apply until+ // React Query swaps in a fresh reference. The interrupted-toast must+ // gate on the same condition: firing earlier would surface "previous+ // response was interrupted" against the pre-turn snapshot — which may+ // not actually have zombie parts once the refetch lands — confusing+ // the user with a toast for state they cannot see yet.+ const isStaleForceHydrateSnapshot =+ needsForceHydrateRef.current &&+ hydratedMessages === staleRefAtStreamEnd.current;++ if (+ needsZombieRecovery &&+ sessionId &&+ !isStaleForceHydrateSnapshot &&+ !sessionsWithInterruptedToastShown.has(sessionId)+ ) {+ sessionsWithInterruptedToastShown.add(sessionId);+ toast({+ title: "Previous response was interrupted",+ description:+ "The chat disconnected before the last response finished. Resend to try again.",+ });+ }+if (needsForceHydrateRef.current) {- if (hydratedMessages === staleRefAtStreamEnd.current) {+ if (isStaleForceHydrateSnapshot) {// Still the pre-turn snapshot — wait for the refetch.return;}- setMessages(deduplicateMessages(hydratedMessages));+ setMessages((prev) => preservePromotedUserBubbles(prev, finalized));needsForceHydrateRef.current = false;staleRefAtStreamEnd.current = null;return;}// Regular length-gated top-up (e.g. pagination brought in older messages).- setMessages((prev) =>- prev.length >= hydratedMessages.length- ? prev- : deduplicateMessages(hydratedMessages),- );- }, [hydratedMessages, setMessages, status, isReconnectScheduled]);+ setMessages((prev) => (prev.length >= finalized.length ? prev : finalized));+ }, [+ hydratedMessages,+ setMessages,+ status,+ isReconnectScheduled,+ hasActiveStream,+ ]);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useIsMobile.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useIsMobile.tsnew file mode 100644index 0000000000..19903c67da--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useIsMobile.ts@@ -0,0 +1,6 @@+import { useBreakpoint } from "@/lib/hooks/useBreakpoint";++export function useIsMobile() {+ const breakpoint = useBreakpoint();+ return breakpoint === "base" || breakpoint === "sm" || breakpoint === "md";+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.tsnew file mode 100644index 0000000000..2156a81552--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts@@ -0,0 +1,207 @@+import { toast } from "@/components/molecules/Toast/use-toast";+import { uploadFileDirect } from "@/lib/direct-upload";+import type { UseChatHelpers } from "@ai-sdk/react";+import type { FileUIPart, UIMessage } from "ai";+import { useEffect, useRef, useState } from "react";+import { useCopilotStreamStore } from "./copilotStreamStore";++const MAX_FILES = 10;+const MAX_FILE_SIZE_BYTES = 100 * 1024 * 1024;++interface UploadedFile {+ file_id: string;+ name: string;+ mime_type: string;+}++type SendMessageFn = UseChatHelpers<UIMessage>["sendMessage"];++interface Args {+ sessionId: string | null;+ sendMessage: SendMessageFn;+ createSession: () => Promise<string | undefined>;+ isUserStoppingRef: React.MutableRefObject<boolean>;+}++/**+ * Orchestrates send-message flow: validates input, uploads attached files,+ * creates a session if one doesn't exist yet, and dispatches the message+ * once the session is ready.+ *+ * The "wait for session creation then send" path uses a slot on the Zustand+ * stream store (rather than React refs) because `CopilotPage` keys the chat+ * subtree by sessionId — the moment a session is created the `"new"`-keyed+ * host unmounts and the `"<id>"`-keyed one mounts with fresh refs. The store+ * slot survives that remount so the new host can pick up the pending send.+ */+export function useSendMessage({+ sessionId,+ sendMessage,+ createSession,+ isUserStoppingRef,+}: Args) {+ const [isUploadingFiles, setIsUploadingFiles] = useState(false);+ // Synchronous concurrency guard for the "no session yet" path: rapid+ // double-press / double-Enter would otherwise overwrite `pendingFirstSend`+ // (losing the first message) AND fire two parallel `createSession`+ // requests (creating duplicate sessions). The ref flips before the+ // mutation dispatches and resets in `finally`, so a second call inside+ // the same tick short-circuits.+ const isCreatingSessionRef = useRef(false);++ async function uploadFiles(+ files: File[],+ sid: string,+ ): Promise<UploadedFile[]> {+ const results = await Promise.allSettled(+ files.map(async (file) => {+ try {+ const data = await uploadFileDirect(file, sid);+ if (!data.file_id) throw new Error("No file_id returned");+ return {+ file_id: data.file_id,+ name: data.name || file.name,+ mime_type: data.mime_type || "application/octet-stream",+ } as UploadedFile;+ } catch (err) {+ console.error("File upload failed:", err);+ toast({+ title: "File upload failed",+ description: file.name,+ variant: "destructive",+ });+ throw err;+ }+ }),+ );+ return results+ .filter(+ (r): r is PromiseFulfilledResult<UploadedFile> =>+ r.status === "fulfilled",+ )+ .map((r) => r.value);+ }++ function buildFileParts(uploaded: UploadedFile[]): FileUIPart[] {+ return uploaded.map((f) => ({+ type: "file" as const,+ mediaType: f.mime_type,+ filename: f.name,+ url: `/api/proxy/api/workspace/files/${f.file_id}/download`,+ }));+ }++ async function dispatchToSession(+ sid: string,+ text: string,+ files: File[],+ prebuiltParts: FileUIPart[],+ ) {+ if (prebuiltParts.length > 0) {+ sendMessage({ text, files: prebuiltParts });+ return;+ }+ if (files.length === 0) {+ sendMessage({ text });+ return;+ }+ setIsUploadingFiles(true);+ try {+ const uploaded = await uploadFiles(files, sid);+ if (uploaded.length === 0) {+ toast({+ title: "File upload failed",+ description: "Could not upload any files. Please try again.",+ variant: "destructive",+ });+ throw new Error("All file uploads failed");+ }+ const fileParts = buildFileParts(uploaded);+ sendMessage({+ text,+ files: fileParts.length > 0 ? fileParts : undefined,+ });+ } finally {+ setIsUploadingFiles(false);+ }+ }++ // Hold dispatchToSession in a ref so the queued-send effect can fire+ // exclusively on sessionId change (the real trigger) while still calling+ // the latest closure — which captures the refreshed `sendMessage` after+ // the session has updated.+ const dispatchRef = useRef(dispatchToSession);+ dispatchRef.current = dispatchToSession;++ useEffect(() => {+ if (!sessionId) return;+ const { send, parts } = useCopilotStreamStore+ .getState()+ .takePendingFirstSend();+ if (!send) return;+ void dispatchRef.current(sessionId, send.text, send.files, parts);+ }, [sessionId]);++ async function onSend(message: string, files?: File[]) {+ const trimmed = message.trim();+ if (!trimmed && (!files || files.length === 0)) return;++ if (files && files.length > 0) {+ if (files.length > MAX_FILES) {+ toast({+ title: "Too many files",+ description: `You can attach up to ${MAX_FILES} files at once.`,+ variant: "destructive",+ });+ return;+ }+ const oversized = files.filter((f) => f.size > MAX_FILE_SIZE_BYTES);+ if (oversized.length > 0) {+ toast({+ title: "File too large",+ description: `${oversized[0].name} exceeds the 100 MB limit.`,+ variant: "destructive",+ });+ return;+ }+ }++ isUserStoppingRef.current = false;++ if (sessionId) {+ const { pendingFileParts, setPendingFileParts } =+ useCopilotStreamStore.getState();+ setPendingFileParts([]);+ await dispatchToSession(+ sessionId,+ trimmed,+ files ?? [],+ pendingFileParts,+ );+ return;+ }++ if (isCreatingSessionRef.current) return;+ isCreatingSessionRef.current = true;+ useCopilotStreamStore+ .getState()+ .setPendingFirstSend({ text: trimmed, files: files ?? [] });+ try {+ await createSession();+ } catch (err) {+ const { setPendingFirstSend, setPendingFileParts } =+ useCopilotStreamStore.getState();+ setPendingFirstSend(null);+ setPendingFileParts([]);+ throw err;+ } finally {+ isCreatingSessionRef.current = false;+ }+ }++ function setPendingFileParts(parts: FileUIPart[]) {+ useCopilotStreamStore.getState().setPendingFileParts(parts);+ }++ return { onSend, isUploadingFiles, setPendingFileParts };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionDeletion.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionDeletion.tsnew file mode 100644index 0000000000..cc1d0991b1--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionDeletion.ts@@ -0,0 +1,75 @@+import {+ getGetV2ListSessionsQueryKey,+ useDeleteV2DeleteSession,+} from "@/app/api/__generated__/endpoints/chat/chat";+import { toast } from "@/components/molecules/Toast/use-toast";+import { useQueryClient } from "@tanstack/react-query";+import { parseAsString, useQueryState } from "nuqs";+import { useCopilotUIStore } from "./store";++/**+ * Session deletion flow: reads the pending `sessionToDelete` from the store,+ * fires the delete mutation, clears the active session if it was the one+ * deleted, and toasts on error.+ *+ * Consumed by both `ChatSidebar` and `MobileDrawer` so each can render its+ * own `DeleteChatDialog` without duplicating the mutation wiring.+ */+export function useSessionDeletion() {+ const queryClient = useQueryClient();+ const [sessionId, setSessionId] = useQueryState("sessionId", parseAsString);+ const { sessionToDelete, setSessionToDelete } = useCopilotUIStore();++ const { mutate: deleteSession, isPending: isDeleting } =+ useDeleteV2DeleteSession({+ mutation: {+ onSuccess: (_data, variables) => {+ queryClient.invalidateQueries({+ queryKey: getGetV2ListSessionsQueryKey(),+ });+ // Use the mutation's own `variables` — not the closed-over store+ // value — so a rapid open/cancel/open-different sequence can't+ // accidentally clear the wrong active session after the network+ // round-trip.+ if (variables.sessionId === sessionId) {+ setSessionId(null);+ }+ setSessionToDelete(null);+ },+ onError: (error) => {+ toast({+ title: "Failed to delete chat",+ description:+ error instanceof Error ? error.message : "An error occurred",+ variant: "destructive",+ });+ setSessionToDelete(null);+ },+ },+ });++ function requestDelete(id: string, title: string | null | undefined) {+ if (isDeleting) return;+ setSessionToDelete({ id, title });+ }++ function confirmDelete() {+ if (sessionToDelete) {+ deleteSession({ sessionId: sessionToDelete.id });+ }+ }++ function cancelDelete() {+ if (!isDeleting) {+ setSessionToDelete(null);+ }+ }++ return {+ sessionToDelete,+ isDeleting,+ requestDelete,+ confirmDelete,+ cancelDelete,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionTitlePoll.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionTitlePoll.tsnew file mode 100644index 0000000000..d0a89cc399--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSessionTitlePoll.ts@@ -0,0 +1,73 @@+import {+ getGetV2ListSessionsQueryKey,+ type getV2ListSessionsResponse,+} from "@/app/api/__generated__/endpoints/chat/chat";+import { useQueryClient } from "@tanstack/react-query";+import { useEffect, useRef } from "react";++const TITLE_POLL_INTERVAL_MS = 2_000;+const TITLE_POLL_MAX_ATTEMPTS = 5;+const SESSION_LIST_LIMIT = 50;++interface Args {+ sessionId: string | null;+ status: string;+ isReconnecting: boolean;+}++/**+ * After a chat stream completes, the backend generates a title asynchronously.+ * Poll the session list until the new title appears (or give up) so the sidebar+ * animates in without a manual refresh.+ */+export function useSessionTitlePoll({+ sessionId,+ status,+ isReconnecting,+}: Args) {+ const queryClient = useQueryClient();+ const titlePollRef = useRef<ReturnType<typeof setInterval>>();+ const prevStatusRef = useRef(status);++ useEffect(() => {+ const prev = prevStatusRef.current;+ prevStatusRef.current = status;++ const wasActive = prev === "streaming" || prev === "submitted";+ const isNowReady = status === "ready";++ if (!wasActive || !isNowReady || !sessionId || isReconnecting) return;++ queryClient.invalidateQueries({+ queryKey: getGetV2ListSessionsQueryKey({ limit: SESSION_LIST_LIMIT }),+ });++ const sid = sessionId;+ let attempts = 0;+ clearInterval(titlePollRef.current);+ titlePollRef.current = setInterval(() => {+ const data = queryClient.getQueryData<getV2ListSessionsResponse>(+ getGetV2ListSessionsQueryKey({ limit: SESSION_LIST_LIMIT }),+ );+ const hasTitle =+ data?.status === 200 &&+ data.data.sessions.some((s) => s.id === sid && s.title);+ if (hasTitle || attempts >= TITLE_POLL_MAX_ATTEMPTS) {+ clearInterval(titlePollRef.current);+ titlePollRef.current = undefined;+ return;+ }+ attempts += 1;+ queryClient.invalidateQueries({+ queryKey: getGetV2ListSessionsQueryKey({ limit: SESSION_LIST_LIMIT }),+ });+ }, TITLE_POLL_INTERVAL_MS);+ }, [status, sessionId, isReconnecting, queryClient]);++ useEffect(() => {+ return () => {+ clearInterval(titlePollRef.current);+ titlePollRef.current = undefined;+ };+ }, [sessionId]);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useStreamActivityWatchdog.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useStreamActivityWatchdog.tsnew file mode 100644index 0000000000..64bc9b12f8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useStreamActivityWatchdog.ts@@ -0,0 +1,91 @@+import { useMountEffect } from "@/hooks/useMountEffect";+import { useEffect, useRef } from "react";++/**+ * Number of ms the stream can sit in an active state with no message/part+ * activity before the watchdog assumes the SSE has silently stalled and+ * triggers a reconnect. Tuned to be long enough that legitimate quiet+ * gaps (tool calls that don't emit progress, slow model turns) don't fire+ * false positives, short enough that the user isn't staring at a dead+ * chat for minutes.+ */+const STREAM_STALL_TIMEOUT_MS = 60_000;++type UseChatStatus = "submitted" | "streaming" | "ready" | "error";++interface UseStreamActivityWatchdogArgs {+ sessionId: string | null;+ status: UseChatStatus;+ /**+ * A monotonic-ish signal that changes whenever the stream produces any+ * visible content. In practice: rawMessages.length + a hash of the last+ * assistant message's parts. Any change resets the watchdog timer.+ */+ activityToken: string | number;+ /** True when a reconnect is already scheduled; the watchdog stays quiet. */+ isReconnectScheduled: boolean;+ /** True when the user explicitly stopped; the watchdog stays quiet. */+ isUserStoppingRef: React.MutableRefObject<boolean>;+ /**+ * Ref to the reconnect trigger. Called after ``STREAM_STALL_TIMEOUT_MS``+ * of no activity while the stream is active — this routes through the+ * existing reconnect cascade (toast + exponential backoff + 30 s forced+ * idle), so the UI can never get stuck on a dead stream.+ */+ handleReconnectRef: React.MutableRefObject<() => void>;+}++/**+ * Detect silent SSE stalls.+ *+ * AI SDK only surfaces ``onFinish`` / ``onError`` when the underlying+ * fetch resolves or rejects. If the stream sits open with heartbeats but+ * no data events (backend stuck, Redis zombie, etc.), neither callback+ * fires and the UI stays in ``streaming`` / ``submitted`` state forever.+ * This hook closes the gap by resetting an internal timer on every+ * activity tick and calling ``handleReconnect`` when the timer elapses.+ */+export function useStreamActivityWatchdog({+ sessionId,+ status,+ activityToken,+ isReconnectScheduled,+ isUserStoppingRef,+ handleReconnectRef,+}: UseStreamActivityWatchdogArgs) {+ const timerRef = useRef<ReturnType<typeof setTimeout>>();++ useEffect(() => {+ clearTimeout(timerRef.current);+ timerRef.current = undefined;++ if (!sessionId) return;+ if (status !== "streaming" && status !== "submitted") return;+ if (isReconnectScheduled) return;+ if (isUserStoppingRef.current) return;++ timerRef.current = setTimeout(() => {+ if (isUserStoppingRef.current) return;+ handleReconnectRef.current();+ }, STREAM_STALL_TIMEOUT_MS);++ return () => {+ clearTimeout(timerRef.current);+ timerRef.current = undefined;+ };+ }, [+ sessionId,+ status,+ activityToken,+ isReconnectScheduled,+ isUserStoppingRef,+ handleReconnectRef,+ ]);++ useMountEffect(() => {+ return () => {+ clearTimeout(timerRef.current);+ timerRef.current = undefined;+ };+ });+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useWakeResync.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useWakeResync.tsnew file mode 100644index 0000000000..2805b479c7--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useWakeResync.ts@@ -0,0 +1,78 @@+import { useEffect, useRef, useState } from "react";+import { hasActiveBackendStream } from "./helpers";++/** Minimum time the page must have been hidden to trigger a wake re-sync. */+const WAKE_RESYNC_THRESHOLD_MS = 30_000;++interface UseWakeResyncArgs {+ sessionIdRef: React.MutableRefObject<string | null>;+ isMountedRef: React.MutableRefObject<boolean>;+ refetchSession: () => Promise<{ data?: unknown }>;+ resumeStreamRef: React.MutableRefObject<() => void>;+}++/**+ * Re-sync the chat state when the page becomes visible after a long hidden+ * period (device sleep, tab backgrounded for a long time). If the backend+ * stream is still active, resume via `resumeStreamRef`; otherwise rely on+ * React Query's refetch to update `hydratedMessages`, which the hydration+ * effect merges in.+ *+ * Returns `isSyncing` for the UI so it can block chat input during the+ * in-flight refetch.+ */+export function useWakeResync({+ sessionIdRef,+ isMountedRef,+ refetchSession,+ resumeStreamRef,+}: UseWakeResyncArgs) {+ const [isSyncing, setIsSyncing] = useState(false);+ const lastHiddenAtRef = useRef(Date.now());++ useEffect(() => {+ async function handleWakeResync() {+ const sid = sessionIdRef.current;+ if (!sid) return;++ const elapsed = Date.now() - lastHiddenAtRef.current;+ lastHiddenAtRef.current = Date.now();++ if (document.visibilityState !== "visible") return;+ if (elapsed < WAKE_RESYNC_THRESHOLD_MS) return;++ setIsSyncing(true);+ try {+ const result = await refetchSession();+ // Bail out if the session changed or the host unmounted while+ // the refetch was in flight.+ if (!isMountedRef.current) return;+ if (sessionIdRef.current !== sid) return;++ if (hasActiveBackendStream(result)) {+ // Stream is still running — resume SSE to pick up live chunks.+ resumeStreamRef.current();+ }+ } catch (err) {+ console.warn("[copilot] wake re-sync failed", err);+ } finally {+ if (isMountedRef.current) setIsSyncing(false);+ }+ }++ function onVisibilityChange() {+ if (document.visibilityState === "hidden") {+ lastHiddenAtRef.current = Date.now();+ } else {+ handleWakeResync();+ }+ }++ document.addEventListener("visibilitychange", onVisibilityChange);+ return () => {+ document.removeEventListener("visibilitychange", onVisibilityChange);+ };+ }, [refetchSession, isMountedRef, resumeStreamRef, sessionIdRef]);++ return { isSyncing };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useWorkflowImportAutoSubmit.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useWorkflowImportAutoSubmit.tsindex 7e2ba02485..2779790a27 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useWorkflowImportAutoSubmit.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useWorkflowImportAutoSubmit.ts@@ -87,13 +87,11 @@ function extractPromptFromUrl(): {* Extracted from useCopilotPage to keep that hook focused on page-level concerns.*/export function useWorkflowImportAutoSubmit({- createSession,- setPendingMessage,- pendingFilePartsRef,+ onSend,+ setPendingFileParts,}: {- createSession: () => Promise<string | undefined>;- setPendingMessage: (msg: string | null) => void;- pendingFilePartsRef: React.MutableRefObject<FileUIPart[]>;+ onSend: (message: string) => Promise<void>;+ setPendingFileParts: (parts: FileUIPart[]) => void;}) {const { setInitialPrompt } = useCopilotUIStore();const hasProcessedUrlPrompt = useRef(false);@@ -108,15 +106,13 @@ export function useWorkflowImportAutoSubmit({if (urlPrompt.autosubmit) {if (urlPrompt.filePart) {- pendingFilePartsRef.current = [urlPrompt.filePart];+ setPendingFileParts([urlPrompt.filePart]);}- setPendingMessage(urlPrompt.prompt);- void createSession().catch(() => {- setPendingMessage(null);+ void onSend(urlPrompt.prompt).catch(() => {setInitialPrompt(urlPrompt.prompt);});} else {setInitialPrompt(urlPrompt.prompt);}- }, [createSession, setInitialPrompt, setPendingMessage, pendingFilePartsRef]);+ }, [onSend, setInitialPrompt, setPendingFileParts]);}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 592caec08c..7c068bbb22 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -2442,6 +2442,59 @@}}}+ },+ "post": {+ "tags": ["v2", "chat", "chat"],+ "summary": "Queue Pending Message",+ "description": "Queue a follow-up message while the session has an active turn.",+ "operationId": "postV2QueuePendingMessage",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": { "type": "string", "title": "Session Id" }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/QueuePendingMessageRequest"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/QueuePendingMessageResponse"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "404": { "description": "Session not found or access denied" },+ "409": {+ "description": "Session has no active turn to receive pending messages"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ },+ "429": { "description": "Call-frequency cap exceeded" }+ }}},"/api/chat/sessions/{session_id}/stream": {@@ -2477,7 +2530,7 @@"get": {"tags": ["v2", "chat", "chat"],"summary": "Resume Session Stream",- "description": "Resume an active stream for a session.\n\nCalled by the AI SDK's ``useChat(resume: true)`` on page load.\nChecks for an active (in-progress) task on the session and either replays\nthe full SSE stream or returns 204 No Content if nothing is running.\n\nArgs:\n session_id: The chat session identifier.\n user_id: Optional authenticated user ID.\n\nReturns:\n StreamingResponse (SSE) when an active stream exists,\n or 204 No Content when there is nothing to resume.",+ "description": "Resume an active stream for a session.\n\nCalled by the AI SDK's ``useChat(resume: true)`` on page load.\nChecks for an active (in-progress) task on the session and either replays\nthe full SSE stream or returns 204 No Content if nothing is running.\n\nAlways replays the active turn from ``0-0``. The AI SDK UI-message parser\nkeeps text/reasoning part state inside a single parser instance; resuming\nfrom a Redis cursor can skip the ``*-start`` events required by later\n``*-delta`` chunks.","operationId": "getV2ResumeSessionStream","security": [{ "HTTPBearerJWT": [] }],"parameters": [@@ -2509,7 +2562,7 @@"post": {"tags": ["v2", "chat", "chat"],"summary": "Stream Chat Post",- "description": "Start a new turn OR queue a follow-up — decided server-side.\n\n- **Session idle**: starts a turn. Returns an SSE stream (``text/event-stream``)\n with Vercel AI SDK chunks (text fragments, tool-call UI, tool results).\n The generation runs in a background task that survives client disconnects;\n reconnect via ``GET /sessions/{session_id}/stream`` to resume.\n\n- **Session has a turn in flight**: pushes the message into the per-session\n pending buffer and returns ``202 application/json`` with\n ``QueuePendingMessageResponse``. The executor running the current turn\n drains the buffer between tool-call rounds (baseline) or at the start of\n the next turn (SDK). Clients should detect the 202 and surface the\n message as a queued-chip in the UI.\n\nArgs:\n session_id: The chat session identifier.\n request: Request body with message, is_user_message, and optional context.\n user_id: Authenticated user ID.",+ "description": "Start a new turn and return an AI SDK UI message stream.\n\nReturns an SSE stream (``text/event-stream``) with Vercel AI SDK chunks\n(text fragments, tool-call UI, tool results). The generation runs in a\nbackground task that survives client disconnects; reconnect via\n``GET /sessions/{session_id}/stream`` to resume.\n\nFollow-up messages typed while a turn is already running should use\n``POST /sessions/{session_id}/messages/pending``. If an older client still\nposts that follow-up here, we queue it defensively but still return a valid\nempty UI-message stream so AI SDK transports never receive a JSON body from\nthe stream endpoint.\n\nArgs:\n session_id: The chat session identifier.\n request: Request body with message, is_user_message, and optional context.\n user_id: Authenticated user ID.","operationId": "postV2StreamChatPost","security": [{ "HTTPBearerJWT": [] }],"parameters": [@@ -2533,16 +2586,6 @@"description": "Successful Response","content": { "application/json": { "schema": {} } }},- "202": {- "description": "Session has a turn in flight — message queued into the pending buffer and will be picked up between tool-call rounds by the executor currently processing the turn.",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/QueuePendingMessageResponse"- }- }- }- },"401": {"$ref": "#/components/responses/HTTP401NotAuthenticatedError"},@@ -9158,7 +9201,11 @@"ActiveStreamInfo": {"properties": {"turn_id": { "type": "string", "title": "Turn Id" },- "last_message_id": { "type": "string", "title": "Last Message Id" }+ "last_message_id": { "type": "string", "title": "Last Message Id" },+ "started_at": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Started At"+ }},"type": "object","required": ["turn_id", "last_message_id"],@@ -14512,6 +14559,40 @@"required": ["providers", "pagination"],"title": "ProviderResponse"},+ "QueuePendingMessageRequest": {+ "properties": {+ "message": {+ "type": "string",+ "maxLength": 64000,+ "title": "Message"+ },+ "context": {+ "anyOf": [+ {+ "additionalProperties": { "type": "string" },+ "type": "object"+ },+ { "type": "null" }+ ],+ "title": "Context"+ },+ "file_ids": {+ "anyOf": [+ {+ "items": { "type": "string" },+ "type": "array",+ "maxItems": 20+ },+ { "type": "null" }+ ],+ "title": "File Ids"+ }+ },+ "type": "object",+ "required": ["message"],+ "title": "QueuePendingMessageRequest",+ "description": "Request model for queueing a follow-up while a turn is running."+ },"QueuePendingMessageResponse": {"properties": {"buffer_length": { "type": "integer", "title": "Buffer Length" },@@ -14524,7 +14605,7 @@"type": "object","required": ["buffer_length", "max_buffer_length", "turn_in_flight"],"title": "QueuePendingMessageResponse",- "description": "Response returned by ``POST /stream`` with status 202 when a message\nis queued because the session already has a turn in flight.\n\n- ``buffer_length``: how many messages are now in the session's\n pending buffer (after this push)\n- ``max_buffer_length``: the per-session cap (server-side constant)\n- ``turn_in_flight``: ``True`` if a copilot turn was running when\n we checked — purely informational for UX feedback. Always ``True``\n for responses from ``POST /stream`` with status 202."+ "description": "Response returned when a message is queued because the session already\nhas a turn in flight.\n\n- ``buffer_length``: how many messages are now in the session's\n pending buffer (after this push)\n- ``max_buffer_length``: the per-session cap (server-side constant)\n- ``turn_in_flight``: ``True`` if a copilot turn was running when\n we checked — purely informational for UX feedback."},"RateLimitResetResponse": {"properties": {diff --git a/autogpt_platform/frontend/src/components/ai-elements/prompt-input.tsx b/autogpt_platform/frontend/src/components/ai-elements/prompt-input.tsxindex 89b0e19ac6..023db306df 100644--- a/autogpt_platform/frontend/src/components/ai-elements/prompt-input.tsx+++ b/autogpt_platform/frontend/src/components/ai-elements/prompt-input.tsx@@ -146,13 +146,7 @@ export function PromptInputTextarea({if (e.shiftKey) return;e.preventDefault();- const { form } = e.currentTarget;- const submitButton = form?.querySelector(- 'button[type="submit"]',- ) as HTMLButtonElement | null;- if (submitButton?.disabled) return;-- form?.requestSubmit();+ e.currentTarget.form?.requestSubmit();}},[onKeyDown, isComposing],diff --git a/autogpt_platform/frontend/src/components/atoms/Tooltip/BaseTooltip.tsx b/autogpt_platform/frontend/src/components/atoms/Tooltip/BaseTooltip.tsxindex f50b5268d3..f9b43b6901 100644--- a/autogpt_platform/frontend/src/components/atoms/Tooltip/BaseTooltip.tsx+++ b/autogpt_platform/frontend/src/components/atoms/Tooltip/BaseTooltip.tsx@@ -10,11 +10,13 @@ const TooltipProvider = TooltipPrimitive.Provider;const Tooltip = ({children,delayDuration = 10,+ open,}: {children: React.ReactNode;delayDuration?: number;+ open?: boolean;}) => (- <TooltipPrimitive.Root delayDuration={delayDuration}>+ <TooltipPrimitive.Root delayDuration={delayDuration} open={open}>{children}</TooltipPrimitive.Root>);diff --git a/autogpt_platform/frontend/src/hooks/useMountEffect.ts b/autogpt_platform/frontend/src/hooks/useMountEffect.tsnew file mode 100644index 0000000000..7b3c02b1ed--- /dev/null+++ b/autogpt_platform/frontend/src/hooks/useMountEffect.ts@@ -0,0 +1,10 @@+import { useEffect } from "react";++/**+ * Named wrapper around `useEffect(fn, [])` so the intent ("run on mount+ * and clean up on unmount") is explicit and the exhaustive-deps lint+ * rule doesn't flag a legitimately empty dep array.+ */+export function useMountEffect(effect: () => void | (() => void)): void {+ useEffect(effect, []);+}