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.
feat(backend/copilot): id every stream entry, checkpoint every persist, and resume a turn from a cursor (#15084)
Reinier van der Leer0560947a067b
diff --git a/.github/scripts/backend-allowed-skips.json b/.github/scripts/backend-allowed-skips.jsonindex 3ff481c369..0c5c103051 100644--- a/.github/scripts/backend-allowed-skips.json+++ b/.github/scripts/backend-allowed-skips.json@@ -115,7 +115,6 @@"backend.copilot.service_test.test_sdk_resume_multi_turn","backend.copilot.stream_drift.drift_causes_test.test_a_dispatch_does_not_take_over_a_running_turns_meta","backend.copilot.stream_drift.drift_causes_test.test_a_reply_that_failed_to_persist_ends_the_turn_in_error",- "backend.copilot.stream_drift.drift_causes_test.test_a_resume_of_a_long_running_turn_replays_whole_blocks","backend.copilot.stream_drift.drift_causes_test.test_a_silent_turn_keeps_publishing_within_the_stream_ttl","backend.copilot.stream_drift.drift_causes_test.test_a_turn_the_executor_drops_is_not_left_running","backend.copilot.stream_drift.drift_causes_test.test_a_turn_whose_executor_died_is_not_reported_running",diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 6ea9d865ce..cff8380fa0 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -26,11 +26,12 @@ repos:description: Detects high entropy strings that are likely to be passwords.args: ["--baseline", ".secrets.baseline"]files: ^autogpt_platform/- # The style eval's baseline is generated and holds sha256 content- # hashes of the assembled prompts, which read as high-entropy hex.+ # The style eval's baseline and the recorded copilot streams are+ # generated and hold sha256 content hashes (of the assembled prompts,+ # and the checkpoints' row digests), which read as high-entropy hex.# .env.default files are deliberately NOT excluded: they are public, so# a working value committed to one is a published secret (SECRT-2611).- exclude: (pnpm-lock\.yaml|copilot/eval/style/baseline\.json|frontend/public/autogpt-characters/manifest\.json|experts/avatar_references/manifest\.json)$+ exclude: (pnpm-lock\.yaml|copilot/eval/style/baseline\.json|test/fixtures/copilot_stream/.*\.jsonl|frontend/public/autogpt-characters/manifest\.json|experts/avatar_references/manifest\.json)$- repo: https://github.com/gitleaks/gitleaksrev: v8.24.3diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex 3b1a2e06ee..2d845b09c6 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -4,12 +4,12 @@ import asyncioimport loggingfrom collections.abc import AsyncGeneratorfrom datetime import datetime, timezone-from typing import Annotated, Any+from typing import Annotated, Any, Literalfrom uuid import uuid4from autogpt_libs import authfrom fastapi import APIRouter, HTTPException, Query, Response, Security-from fastapi.responses import StreamingResponse+from fastapi.responses import JSONResponse, StreamingResponsefrom pydantic import BaseModel, ConfigDict, Field, field_validatorfrom backend.api.features.experts import experts_db@@ -419,6 +419,8 @@ class ActiveStreamInfo(BaseModel):# turns show honest "time since turn started" instead of the misleading# "time since this mount resumed the SSE".started_at: str | None = None+ # The turn's last checkpoint: seed from its rows, resume the stream after it.+ checkpoint: stream_registry.TurnCheckpoint | None = Noneclass SessionDetailResponse(BaseModel):@@ -1266,6 +1268,7 @@ async def get_session(turn_id=active_session.turn_id,last_message_id=last_message_id,started_at=active_session.created_at.isoformat(),+ checkpoint=active_session.checkpoint,)elif page.session.chat_status == CHAT_STATUS_RUNNING:# DB says running but Redis has no live stream — either the@@ -2090,7 +2093,8 @@ async def stream_chat_post()while True:try:- chunk = await asyncio.wait_for(subscriber_queue.get(), timeout=10.0)+ entry = await asyncio.wait_for(subscriber_queue.get(), timeout=10.0)+ _, chunk = entrychunks_yielded += 1if not first_chunk_yielded:@@ -2108,7 +2112,7 @@ async def stream_chat_post(},)- yield chunk.to_sse()+ yield stream_registry.sse_frame(entry)if isinstance(chunk, StreamFinish):total_time = time_module.perf_counter() - event_gen_start@@ -2258,27 +2262,56 @@ async def get_pending_messages()+class StreamResumeRefusal(BaseModel):+ """Why a resume at a cursor cannot be served from the stream."""++ reason: Literal["trimmed", "expired"]+ # For "trimmed": seed from the DB rows up to here, then resume after it.+ checkpoint: stream_registry.TurnCheckpoint | None = None++@router.get("/sessions/{session_id}/stream",+ responses={+ 409: {"model": StreamResumeRefusal, "description": "Cursor was trimmed"},+ 410: {"model": StreamResumeRefusal, "description": "Stream expired"},+ },)async def resume_session_stream(session_id: str,+ turn: str | None = Query(+ default=None, description="Turn to read; with it, only its stored entries"+ ),+ after: str = Query(+ default="0-0",+ pattern=r"^\d+-\d+$",+ description="Stream entry id the client last applied",+ ),last_chunk_id: str | None = Query(default=None, include_in_schema=False),user_id: str = Security(auth.get_user_id),):"""- Resume an active stream for a session.+ Resume a session's stream.- Called by the AI SDK's ``useChat(resume: true)`` on page load.- Checks for an active (in-progress) task on the session and either replays- the full SSE stream or returns 204 No Content if nothing is running.+ With ``turn``, serves exactly that turn's stored entries after ``after``+ (``0-0`` for all of them) and then its live ones: 409 when entries after+ the cursor were trimmed, 410 when the stream is gone. Every entry frame+ carries ``id: <turn>:<entry>``.- 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.+ Without ``turn``, replays the active turn from ``0-0``, or returns 204+ when nothing is running: the AI SDK's parser cannot continue a block it+ did not see start."""- import asyncio+ if turn is not None:+ try:+ subscriber_queue = await stream_registry.subscribe_to_turn(+ session_id, user_id, turn, after+ )+ except stream_registry.TurnStreamTrimmed as trimmed:+ return _resume_refusal(409, "trimmed", trimmed.checkpoint)+ except stream_registry.TurnStreamGone:+ return _resume_refusal(410, "expired")+ return _resume_response(session_id, subscriber_queue, cursor=True)active_session, _latest_backend_id = await stream_registry.get_active_session(session_id, user_id@@ -2301,6 +2334,26 @@ async def resume_session_stream(if subscriber_queue is None:return Response(status_code=204)+ return _resume_response(session_id, subscriber_queue, cursor=False)+++def _resume_refusal(+ status_code: int,+ reason: Literal["trimmed", "expired"],+ checkpoint: stream_registry.TurnCheckpoint | None = None,+) -> JSONResponse:+ body = StreamResumeRefusal(reason=reason, checkpoint=checkpoint)+ return JSONResponse(status_code=status_code, content=body.model_dump())+++def _resume_response(+ session_id: str,+ subscriber_queue: "asyncio.Queue[stream_registry.StreamEntry]",+ *,+ cursor: bool,+) -> StreamingResponse:+ """Stream the queue as SSE. A ``cursor`` read writes no made-up frame: a+ stream that stops without the turn's finish just ends the response."""async def event_generator() -> AsyncGenerator[str, None]:chunk_count = 0@@ -2308,24 +2361,29 @@ async def resume_session_stream(try:while True:try:- chunk = await asyncio.wait_for(subscriber_queue.get(), timeout=10.0)- if chunk_count < 3:- logger.info(- "Resume stream chunk",- extra={- "session_id": session_id,- "chunk_type": str(chunk.type),- },- )- if not first_chunk_type:- first_chunk_type = str(chunk.type)- chunk_count += 1- yield chunk.to_sse()-- if isinstance(chunk, StreamFinish):- break+ entry = await asyncio.wait_for(subscriber_queue.get(), timeout=10.0)except asyncio.TimeoutError:yield StreamHeartbeat().to_sse()+ continue+ frame_id, chunk = entry+ if (+ cursor+ and frame_id is None+ and not isinstance(chunk, StreamHeartbeat)+ ):+ break+ if chunk_count < 3:+ logger.info(+ "Resume stream chunk",+ extra={"session_id": session_id, "chunk_type": str(chunk.type)},+ )+ if not first_chunk_type:+ first_chunk_type = str(chunk.type)+ chunk_count += 1+ yield stream_registry.sse_frame(entry)++ if isinstance(chunk, StreamFinish):+ breakexcept GeneratorExit:passexcept Exception as e:@@ -2337,7 +2395,7 @@ async def resume_session_stream()except Exception as unsub_err:logger.error(- f"Error unsubscribing from session {active_session.session_id}: {unsub_err}",+ f"Error unsubscribing from session {session_id}: {unsub_err}",exc_info=True,)logger.info(diff --git a/autogpt_platform/backend/backend/api/features/chat/stream_resume_test.py b/autogpt_platform/backend/backend/api/features/chat/stream_resume_test.pynew file mode 100644index 0000000000..c113d2a7b6--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/chat/stream_resume_test.py@@ -0,0 +1,127 @@+"""``GET /sessions/{id}/stream?turn&after`` over the recorded turns, on real Redis.++Each recorded turn is stored back into Redis as a finished turn of a session+the test user owns; the route must serve exactly its committed frames.+"""++import json+import uuid++import fastapi+import pytest+from autogpt_libs.auth.jwt_utils import get_jwt_payload+from httpx import ASGITransport, AsyncClient++from backend.api.features.chat import routes as chat_routes+from backend.copilot import stream_registry+from backend.copilot.stream_drift.recording import RecordedTurn, load_fixture+from backend.data import redis_client+from backend.util.testing import is_tcp_port_reachable++pytestmark = pytest.mark.skipif(+ not is_tcp_port_reachable(redis_client.HOST, redis_client.PORT),+ reason="no local Redis reachable; the stream registry needs one to run",+)++RECORDED_TURNS = ["dummy-text-turn", "baseline-tool-turn", "sdk-late-tool-result"]+DONE = "data: [DONE]\n\n"++app = fastapi.FastAPI()+app.include_router(chat_routes.router)++[email protected](autouse=True)+def auth(mock_jwt_user):+ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]+ yield+ app.dependency_overrides.clear()+++async def stored(test_user_id):+ """Store a recorded turn as a finished turn; returns its session and turn."""+ keys: list[str] = []++ async def store(turn: RecordedTurn) -> tuple[str, str]:+ session_id, turn_id = f"resume-{uuid.uuid4().hex}", str(uuid.uuid4())+ await stream_registry.create_session(+ session_id, test_user_id, "", "", turn_id=turn_id+ )+ redis = await redis_client.get_redis_async()+ stream_key = stream_registry._get_turn_stream_key(turn_id)+ for entry in turn.entries:+ await redis.xadd(+ stream_key, {"data": json.dumps(entry["data"])}, id=entry["id"]+ )+ meta_key = stream_registry.get_session_meta_key(session_id)+ await redis.hset(meta_key, "status", "completed")+ keys.extend([meta_key, stream_key, stream_registry._get_turn_meta_key(turn_id)])+ return session_id, turn_id++ yield store+ redis = await redis_client.get_redis_async()+ for key in keys:+ await redis.delete(key)++[email protected]("name", RECORDED_TURNS)+async def test_a_cursor_read_serves_exactly_the_recorded_frames_after_it(name, stored):+ turn = load_fixture(name)+ session_id, turn_id = await stored(turn)+ ids = [entry["id"] for entry in turn.entries]++ for position, after in enumerate(["0-0", *ids[:-1]]):+ response = await _get_stream(session_id, turn=turn_id, after=after)++ assert response.status_code == 200+ assert response.text == _frames(turn, turn_id, ids[position:]) + DONE+++async def test_a_cursor_before_the_trim_is_answered_with_the_checkpoint(stored):+ turn = load_fixture("baseline-tool-turn")+ [checkpoint] = [e for e in turn.entries if e["data"]["type"] == "data-checkpoint"]+ session_id, turn_id = await stored(turn)+ redis = await redis_client.get_redis_async()+ stream_key = stream_registry._get_turn_stream_key(turn_id)+ await redis.xtrim(stream_key, minid=checkpoint["id"], approximate=False)++ trimmed = await _get_stream(session_id, turn=turn_id, after="3-0")+ resumed = await _get_stream(session_id, turn=turn_id, after=checkpoint["id"])++ assert trimmed.status_code == 409+ assert trimmed.json() == {+ "reason": "trimmed",+ "checkpoint": {+ "entry_id": checkpoint["id"],+ "rows": checkpoint["data"]["rows"],+ "sequence": checkpoint["data"]["sequence"],+ },+ }+ ids = [entry["id"] for entry in turn.entries]+ after = ids[ids.index(checkpoint["id"]) + 1 :]+ assert resumed.text == _frames(turn, turn_id, after) + DONE+++async def test_a_stream_that_is_gone_is_answered_410(stored):+ session_id, _ = await stored(load_fixture("dummy-text-turn"))++ response = await _get_stream(session_id, turn=str(uuid.uuid4()), after="0-0")++ assert response.status_code == 410+ assert response.json() == {"reason": "expired", "checkpoint": None}+++async def _get_stream(session_id: str, **params: str):+ async with AsyncClient(+ transport=ASGITransport(app=app), base_url="http://test"+ ) as client:+ return await client.get(f"/sessions/{session_id}/stream", params=params)+++def _frames(turn: RecordedTurn, turn_id: str, ids: list[str]) -> str:+ wanted = set(ids)+ return "".join(+ frame["sse"].replace("id: drift-turn:", f"id: {turn_id}:")+ for frame in turn.frames+ if frame["id"] in wanted+ )diff --git a/autogpt_platform/backend/backend/copilot/baseline/reasoning.py b/autogpt_platform/backend/backend/copilot/baseline/reasoning.pyindex cc9fe2de5c..3f865ede93 100644--- a/autogpt_platform/backend/backend/copilot/baseline/reasoning.py+++ b/autogpt_platform/backend/backend/copilot/baseline/reasoning.py@@ -317,12 +317,6 @@ class BaselineReasoningEmitter:fresh ``ChatMessage(role="reasoning")`` is appended and mutatedin-place as further deltas arrive; :meth:`close` drops the referencebut leaves the appended row intact.-- ``render_in_ui=False`` suppresses only the live wire events- (``StreamReasoning*``); the ``role='reasoning'`` persistence row is- still appended so ``convertChatSessionToUiMessages.ts`` can hydrate- the reasoning bubble on reload. The state machine advances- identically either way."""def __init__(@@ -331,7 +325,6 @@ class BaselineReasoningEmitter:*,coalesce_min_chars: int = _COALESCE_MIN_CHARS,coalesce_max_interval_ms: float = _COALESCE_MAX_INTERVAL_MS,- render_in_ui: bool = True,) -> None:self._block_id: str = str(uuid.uuid4())self._open: bool = False@@ -343,7 +336,6 @@ class BaselineReasoningEmitter:self._coalesce_max_interval_ms = coalesce_max_interval_msself._pending_delta: str = ""self._last_flush_monotonic: float = 0.0- self._render_in_ui = render_in_ui@propertydef is_open(self) -> bool:@@ -375,9 +367,8 @@ class BaselineReasoningEmitter:# syscalls off the hot path without changing semantics.now = time.monotonic()if not self._open:- if self._render_in_ui:- events.append(StreamReasoningStart(id=self._block_id))- events.append(StreamReasoningDelta(id=self._block_id, delta=text))+ events.append(StreamReasoningStart(id=self._block_id))+ events.append(StreamReasoningDelta(id=self._block_id, delta=text))self._open = Trueself._last_flush_monotonic = nowif self._session_messages is not None:@@ -390,10 +381,9 @@ class BaselineReasoningEmitter:self._pending_delta += textif self._should_flush_pending(now):- if self._render_in_ui:- events.append(- StreamReasoningDelta(id=self._block_id, delta=self._pending_delta)- )+ events.append(+ StreamReasoningDelta(id=self._block_id, delta=self._pending_delta)+ )self._pending_delta = ""self._last_flush_monotonic = nowreturn events@@ -426,12 +416,11 @@ class BaselineReasoningEmitter:if not self._open:return []events: list[StreamBaseResponse] = []- if self._render_in_ui:- if self._pending_delta:- events.append(- StreamReasoningDelta(id=self._block_id, delta=self._pending_delta)- )- events.append(StreamReasoningEnd(id=self._block_id))+ if self._pending_delta:+ events.append(+ StreamReasoningDelta(id=self._block_id, delta=self._pending_delta)+ )+ events.append(StreamReasoningEnd(id=self._block_id))self._pending_delta = ""self._open = Falseself._block_id = str(uuid.uuid4())diff --git a/autogpt_platform/backend/backend/copilot/baseline/reasoning_test.py b/autogpt_platform/backend/backend/copilot/baseline/reasoning_test.pyindex e7aeb10e97..158e2eff19 100644--- a/autogpt_platform/backend/backend/copilot/baseline/reasoning_test.py+++ b/autogpt_platform/backend/backend/copilot/baseline/reasoning_test.py@@ -516,66 +516,6 @@ class TestReasoningPersistence:# Nothing else to assert — just proves None session is supported.-class TestBaselineReasoningEmitterRenderFlag:- """``render_in_ui=False`` must silence ``StreamReasoning*`` wire events- AND drop persistence of ``role="reasoning"`` rows — the operator hides- the collapse on both the live wire and on reload. Persistence is tied- to the wire events because the frontend's hydration path unconditionally- re-renders persisted reasoning rows; keeping them would make the flag a- no-op post-reload. These tests pin the contract in both directions so- future refactors can't flip only one half."""-- def test_render_off_suppresses_start_and_delta(self):- emitter = BaselineReasoningEmitter(render_in_ui=False)- events = emitter.on_delta(_delta(reasoning="hidden"))- # No wire events, but state advanced (is_open == True) so close()- # below has something to rotate.- assert events == []- assert emitter.is_open is True-- def test_render_off_suppresses_close_end(self):- emitter = BaselineReasoningEmitter(render_in_ui=False)- emitter.on_delta(_delta(reasoning="hidden"))- events = emitter.close()- assert events == []- assert emitter.is_open is False-- def test_render_off_still_persists(self):- """Persistence is decoupled from the render flag — session- transcript always keeps the ``role="reasoning"`` row so audit- and ``--resume``-equivalent replay never lose thinking text.- The frontend gates rendering separately."""- session: list[ChatMessage] = []- emitter = BaselineReasoningEmitter(session, render_in_ui=False)-- emitter.on_delta(_delta(reasoning="part one "))- emitter.on_delta(_delta(reasoning="part two"))- emitter.close()-- assert len(session) == 1- assert session[0].role == "reasoning"- assert session[0].content == "part one part two"-- def test_render_off_rotates_block_id_between_sessions(self):- """Even with wire events silenced the block id must rotate on close,- otherwise a hypothetical mid-session flip would reuse a stale id."""- emitter = BaselineReasoningEmitter(render_in_ui=False)- emitter.on_delta(_delta(reasoning="first"))- first_block_id = emitter._block_id- emitter.close()- emitter.on_delta(_delta(reasoning="second"))- assert emitter._block_id != first_block_id-- def test_render_on_is_default(self):- """Defaulting to True preserves backward compat — existing callers- that don't pass the kwarg keep emitting wire events as before."""- emitter = BaselineReasoningEmitter()- events = emitter.on_delta(_delta(reasoning="hello"))- assert len(events) == 2- assert isinstance(events[0], StreamReasoningStart)- assert isinstance(events[1], StreamReasoningDelta)--class TestClaude5FamilyThinking:"""Claude 5 removed ``budget_tokens`` — both thinking fragments muststay off (the documented adaptive default serves), while 4.x keepsdiff --git a/autogpt_platform/backend/backend/copilot/baseline/service.py b/autogpt_platform/backend/backend/copilot/baseline/service.pyindex 5cc7a98dfa..fe44f3ea9e 100644--- a/autogpt_platform/backend/backend/copilot/baseline/service.py+++ b/autogpt_platform/backend/backend/copilot/baseline/service.py@@ -75,10 +75,12 @@ from backend.copilot.moonshot import is_moonshot_modelfrom backend.copilot.pending_message_helpers import (combine_pending_with_current,drain_pending_safe,+ drained_rows_entry,persist_pending_as_user_rows,persist_session_safe,)from backend.copilot.pending_messages import (+ PendingMessage,drain_pending_messages,format_pending_as_user_message,)@@ -96,6 +98,7 @@ from backend.copilot.provider_failure import classify as classify_provider_failufrom backend.copilot.rate_limit import build_budget_ctxfrom backend.copilot.response_model import (StreamBaseResponse,+ StreamCheckpoint,StreamError,StreamFinish,StreamFinishStep,@@ -123,6 +126,7 @@ from backend.copilot.service import (strip_user_context_tags,)from backend.copilot.session_cleanup import prune_orphan_tool_calls+from backend.copilot.stream_checkpoint import turn_checkpointfrom backend.copilot.thinking_stripper import ThinkingStripper as _ThinkingStripperfrom backend.copilot.token_tracking import (_extract_cache_creation_tokens,@@ -562,13 +566,7 @@ class _BaselineStreamState:# frontend's ``convertChatSessionToUiMessages`` relies on these# rows to render the Reasoning collapse after the AI SDK's# stream-end hydrate swaps in the DB-backed message list.- # ``render_in_ui`` is sourced from ``config.render_reasoning_in_ui``- # so the operator can silence the reasoning collapse globally- # without dropping the persisted audit trail.- self.reasoning_emitter = BaselineReasoningEmitter(- self.session_messages,- render_in_ui=config.render_reasoning_in_ui,- )+ self.reasoning_emitter = BaselineReasoningEmitter(self.session_messages)def _emit(state: "_BaselineStreamState", event: StreamBaseResponse) -> None:@@ -1792,6 +1790,10 @@ async def stream_chat_completion_baseline(# Capture count *before* the pending drain so is_first_turn and the# transcript staleness check are not skewed by queued messages._pre_drain_msg_count = len(session.messages)+ # The stream's rows start after the message that triggered it; the rows+ # appended before the turn's first yield are announced once it opens.+ turn_start = _pre_drain_msg_count+ opening_entries: list[StreamBaseResponse] = []# Drain any messages the user queued via POST /messages/pending# while this session was idle (or during a previous turn whose@@ -2130,6 +2132,7 @@ async def stream_chat_completion_baseline(log_prefix="[Baseline]",)if persisted_ok:+ opening_entries.append(drained_rows_entry(drained_at_start_pending))message = combine_pending_with_current(drained_at_start_pending,message,@@ -2361,6 +2364,7 @@ async def stream_chat_completion_baseline(if held_results and await persist_pending_as_user_rows(session, transcript_builder, held_results, log_prefix="[Baseline]"):+ opening_entries.append(drained_rows_entry(held_results))openai_messages.extend(format_pending_as_user_message(pm) for pm in held_results)@@ -2391,6 +2395,11 @@ async def stream_chat_completion_baseline(),)+ # Queued, not yielded: the loop below yields them inside the try whose+ # finally pauses the sandbox.+ for opening in opening_entries:+ _emit(state, opening)+# Bind extracted module-level callbacks to this request's state/session# using functools.partial so they satisfy the Protocol signatures._bound_llm_caller = partial(_baseline_llm_caller, state=state)@@ -2403,6 +2412,7 @@ async def stream_chat_completion_baseline(# and be lost on the final persist. Wrap in a 1-element holder and read# the current binding lazily so the executor always sees the latest session._session_holder: list[ChatSession] = [session]+ final_checkpoint: StreamCheckpoint | None = Noneasync def _bound_tool_executor(tool_call: LLMToolCall, tools: Sequence[Any]@@ -2588,6 +2598,10 @@ async def stream_chat_completion_baseline(formatted_by_pm = {id(pm): format_pending_as_user_message(pm) for pm in pending}++ def _formatted(pm: PendingMessage) -> str:+ return formatted_by_pm[id(pm)]["content"]+_openai_anchor = len(openai_messages)for pm in pending:openai_messages.append(formatted_by_pm[id(pm)])@@ -2595,14 +2609,18 @@ async def stream_chat_completion_baseline(def _trim_openai_on_rollback(_session_anchor: int) -> None:del openai_messages[_openai_anchor:]- await persist_pending_as_user_rows(+ if await persist_pending_as_user_rows(current_session,transcript_builder,pending,log_prefix="[Baseline]",- content_of=lambda pm: formatted_by_pm[id(pm)]["content"],+ content_of=_formatted,on_rollback=_trim_openai_on_rollback,- )+ ):+ _emit(state, drained_rows_entry(pending, _formatted))+ checkpoint = turn_checkpoint(current_session.messages, turn_start)+ if checkpoint is not None:+ _emit(state, checkpoint)finally:# Always post the sentinel so the outer consumer exits — even if# ``tool_call_loop`` raised. ``_baseline_llm_caller``'s own@@ -2903,6 +2921,7 @@ async def stream_chat_completion_baseline()try:await upsert_chat_session(session)+ final_checkpoint = turn_checkpoint(session.messages, turn_start)except Exception as persist_err:logger.error("[Baseline] Failed to persist session: %s", persist_err)@@ -2957,6 +2976,8 @@ async def stream_chat_completion_baseline(# aclose() — doing so raises RuntimeError on client disconnect.# On GeneratorExit the client is already gone, so unreachable yields# are harmless; on normal completion they reach the SSE stream.+ if final_checkpoint is not None:+ yield final_checkpointif state.turn_prompt_tokens > 0 or state.turn_completion_tokens > 0:# Report uncached prompt tokens to match what was billed — both# cache_read and cache_creation are excluded so the threediff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend.pyindex fe0ca48d7d..74ecd4c59f 100644--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py@@ -544,7 +544,7 @@ class BotBackend:try:while True:try:- chunk = await asyncio.wait_for(+ _, chunk = await asyncio.wait_for(queue.get(), timeout=STREAM_CHUNK_TIMEOUT_SECONDS)except asyncio.TimeoutError:diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.pyindex c99ce5d9b2..15b2cce824 100644--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py@@ -162,9 +162,9 @@ class TestStreamChat:queue: asyncio.Queue = asyncio.Queue()# Same block id — a continuous text stream, no separator inserted.- await queue.put(StreamTextDelta(id="1", delta="Hello "))- await queue.put(StreamTextDelta(id="1", delta="world"))- await queue.put(StreamFinish())+ await queue.put((None, StreamTextDelta(id="1", delta="Hello ")))+ await queue.put((None, StreamTextDelta(id="1", delta="world")))+ await queue.put((None, StreamFinish()))captured_session_ids: list[str] = []@@ -203,9 +203,9 @@ class TestStreamChat:api._client.start_chat_turn = AsyncMock(return_value=handle)queue: asyncio.Queue = asyncio.Queue()- await queue.put(StreamTextDelta(id="1", delta="first thought."))- await queue.put(StreamTextDelta(id="2", delta="second thought."))- await queue.put(StreamFinish())+ await queue.put((None, StreamTextDelta(id="1", delta="first thought.")))+ await queue.put((None, StreamTextDelta(id="2", delta="second thought.")))+ await queue.put((None, StreamFinish()))with (patch(@@ -233,7 +233,7 @@ class TestStreamChat:api._client.start_chat_turn = AsyncMock(return_value=handle)queue: asyncio.Queue = asyncio.Queue()- await queue.put(StreamError(errorText="executor crashed"))+ await queue.put((None, StreamError(errorText="executor crashed")))with (patch(@@ -261,14 +261,17 @@ class TestStreamChat:queue: asyncio.Queue = asyncio.Queue()await queue.put(- StreamToolOutputAvailable(- toolCallId="tool-1",- toolName="connect_integration",- output='{"type":"setup_requirements","message":"Connect GitHub"}',+ (+ None,+ StreamToolOutputAvailable(+ toolCallId="tool-1",+ toolName="connect_integration",+ output='{"type":"setup_requirements","message":"Connect GitHub"}',+ ),))- await queue.put(StreamTextDelta(id="1", delta="After setup"))- await queue.put(StreamFinish())+ await queue.put((None, StreamTextDelta(id="1", delta="After setup")))+ await queue.put((None, StreamFinish()))setup_calls: list[tuple[str, dict, str | None]] = []@@ -310,13 +313,16 @@ class TestStreamChat:queue: asyncio.Queue = asyncio.Queue()await queue.put(- StreamToolOutputAvailable(- toolCallId="tool-1",- toolName="connect_integration",- output='{"type":"setup_requirements","message":"Connect Goo',+ (+ None,+ StreamToolOutputAvailable(+ toolCallId="tool-1",+ toolName="connect_integration",+ output='{"type":"setup_requirements","message":"Connect Goo',+ ),))- await queue.put(StreamFinish())+ await queue.put((None, StreamFinish()))setup_calls: list[tuple[str, dict, str | None]] = []dropped_calls: list[tuple[str, str | None]] = []@@ -365,20 +371,23 @@ class TestStreamChat:]queue: asyncio.Queue = asyncio.Queue()await queue.put(- StreamToolOutputAvailable(- toolCallId="tool-1",- toolName="ask_question",- output=json.dumps(- {- "type": "agent_builder_clarification_needed",- "message": "Which region?",- "questions": questions,- }+ (+ None,+ StreamToolOutputAvailable(+ toolCallId="tool-1",+ toolName="ask_question",+ output=json.dumps(+ {+ "type": "agent_builder_clarification_needed",+ "message": "Which region?",+ "questions": questions,+ }+ ),),))- await queue.put(StreamTextDelta(id="1", delta="After question"))- await queue.put(StreamFinish())+ await queue.put((None, StreamTextDelta(id="1", delta="After question")))+ await queue.put((None, StreamFinish()))clarification_calls: list[tuple[str, dict, str | None]] = []@@ -446,7 +455,7 @@ class TestStreamChat:),StreamFinish(),):- await queue.put(chunk)+ await queue.put((None, chunk))cards: list[tuple[str, str]] = []async def on_approval(session_id: str, review_id: str) -> None:diff --git a/autogpt_platform/backend/backend/copilot/config.py b/autogpt_platform/backend/backend/copilot/config.pyindex f1a6080c10..c912672e00 100644--- a/autogpt_platform/backend/backend/copilot/config.py+++ b/autogpt_platform/backend/backend/copilot/config.py@@ -358,10 +358,6 @@ class ChatConfig(BaseSettings):description="TTL in seconds for stream lock (2 minutes). Short timeout allows ""reconnection after refresh/crash without long waits.",)- stream_max_length: int = Field(- default=10000,- description="Maximum number of messages to store per stream",- )# Redis key prefixes for stream registrysession_meta_prefix: str = Field(@@ -590,19 +586,11 @@ class ChatConfig(BaseSettings):"``claude_agent_thinking_effort`` for adaptive control — the SDK ""ignores ``max_thinking_tokens`` for those models.",)- render_reasoning_in_ui: bool = Field(- default=True,- description="Render reasoning as live UI parts "- "(``StreamReasoning*`` wire events). False suppresses the live "- "wire events only; ``role='reasoning'`` rows are always persisted "- "so the reasoning bubble hydrates on reload. Tokens are billed "- "upstream regardless.",- )stream_replay_count: int = Field(default=200,ge=1,le=10000,- description="Max Redis stream entries replayed on SSE reconnect.",+ description="Redis stream entries read per replay batch on SSE reconnect.",)claude_agent_thinking_effort: Literal["low", "medium", "high", "max"] | None = (# TODO: add xhigh when SDK support catches updiff --git a/autogpt_platform/backend/backend/copilot/config_test.py b/autogpt_platform/backend/backend/copilot/config_test.pyindex 4310a70b5f..fab17f18f4 100644--- a/autogpt_platform/backend/backend/copilot/config_test.py+++ b/autogpt_platform/backend/backend/copilot/config_test.py@@ -42,7 +42,6 @@ _ENV_VARS_TO_CLEAR = ("CHAT_CLAUDE_AGENT_FALLBACK_MODEL","CHAT_TITLE_MODEL","CHAT_SIMULATION_MODEL",- "CHAT_RENDER_REASONING_IN_UI","CHAT_STREAM_REPLAY_COUNT",)@@ -735,27 +734,10 @@ class TestLocalTransport:assert cfg.effective_transport == "local"-class TestRenderReasoningInUi:- """``render_reasoning_in_ui`` gates reasoning wire events globally."""-- def test_defaults_to_true(self):- """Default must stay True — flipping it silences the reasoning- collapse for every user, which is an opt-in operator decision."""- cfg = ChatConfig()- assert cfg.render_reasoning_in_ui is True-- def test_env_override_false(self, monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setenv("CHAT_RENDER_REASONING_IN_UI", "false")- cfg = ChatConfig()- assert cfg.render_reasoning_in_ui is False--class TestStreamReplayCount:- """``stream_replay_count`` caps the SSE reconnect replay batch size."""+ """``stream_replay_count`` is the SSE reconnect replay batch size."""def test_default_is_200(self):- """200 covers a full Kimi turn after coalescing (~150 events) while- bounding the replay storm from 1000+ chunks."""cfg = ChatConfig()assert cfg.stream_replay_count == 200diff --git a/autogpt_platform/backend/backend/copilot/pending_message_helpers.py b/autogpt_platform/backend/backend/copilot/pending_message_helpers.pyindex f08239e005..197698c760 100644--- a/autogpt_platform/backend/backend/copilot/pending_message_helpers.py+++ b/autogpt_platform/backend/backend/copilot/pending_message_helpers.py@@ -29,6 +29,10 @@ from backend.copilot.pending_messages import (push_pending_message,push_pending_message_if_session_running,)+from backend.copilot.response_model import (+ StreamPendingDrained,+ StreamPendingDrainedMessage,+)from backend.copilot.stream_registry import get_session as get_active_session_metafrom backend.copilot.stream_registry import get_session_meta_keyfrom backend.data.db_accessors import chat_db@@ -552,3 +556,18 @@ async def persist_pending_as_user_rows(len(pending),)return True+++def drained_rows_entry(+ pending: list[PendingMessage],+ content_of: Callable[[PendingMessage], str] = lambda pm: pm.content,+) -> StreamPendingDrained:+ """The stream entry for the user rows ``persist_pending_as_user_rows``+ landed: one message per row, with the row's own content."""+ return StreamPendingDrained(+ drainedCount=len(pending),+ messages=[+ StreamPendingDrainedMessage(id=pm.id, content=content_of(pm))+ for pm in pending+ ],+ )diff --git a/autogpt_platform/backend/backend/copilot/pending_messages.py b/autogpt_platform/backend/backend/copilot/pending_messages.pyindex 4064aec6b9..e6e0274ef8 100644--- a/autogpt_platform/backend/backend/copilot/pending_messages.py+++ b/autogpt_platform/backend/backend/copilot/pending_messages.py@@ -29,11 +29,6 @@ from typing import Any, castfrom pydantic import BaseModel, Field, ValidationError-from backend.copilot.response_model import (- StreamPendingDrained,- StreamPendingDrainedMessage,-)-from backend.copilot.stream_registry import get_session, publish_chunkfrom backend.data.redis_client import get_redis_asyncfrom backend.data.redis_helpers import capped_rpush, capped_rpush_if_hash_field@@ -227,50 +222,9 @@ async def drain_pending_messages(session_id: str) -> list[PendingMessage]:len(messages),session_id,)- await _notify_pending_drained(session_id, messages)return messages-async def _notify_pending_drained(- session_id: str, drained: list[PendingMessage]-) -> None:- """Emit a ``data-pending-drained`` hint onto the session's live SSE- stream so the frontend promotes its queued chips to bubbles right away- instead of waiting for its backstop poll.-- Best-effort by design: the frontend re-reads the authoritative buffer- count on the hint (and keeps a slow poll as a safety net), so a failed- or dropped emit only delays the chip→bubble swap — it never loses data.- The active turn is looked up from the session so the chunk lands on the- correct per-turn Redis stream.-- The hint also carries the drained text so the client can render the- follow-up bubble exactly where the backend injected it, between the- tool chain that ran before the drain and the work that follows it.- """- try:- active = await get_session(session_id)- if active is None or not active.turn_id:- return- await publish_chunk(- active.turn_id,- StreamPendingDrained(- drainedCount=len(drained),- messages=[- StreamPendingDrainedMessage(id=m.id, content=m.content)- for m in drained- ],- ),- session_id=session_id,- )- except Exception:- logger.debug(- "pending_messages: drain hint emit failed for session=%s",- session_id,- exc_info=True,- )--async def peek_pending_count(session_id: str) -> int:"""Return the current buffer length without consuming it."""redis = await get_redis_async()diff --git a/autogpt_platform/backend/backend/copilot/pending_messages_test.py b/autogpt_platform/backend/backend/copilot/pending_messages_test.pyindex a90f8fba91..16f03f1f97 100644--- a/autogpt_platform/backend/backend/copilot/pending_messages_test.py+++ b/autogpt_platform/backend/backend/copilot/pending_messages_test.py@@ -8,7 +8,6 @@ and pull in the full app startup).import asyncioimport jsonfrom typing import Any-from unittest.mock import AsyncMockimport pytest@@ -161,16 +160,6 @@ def fake_redis(monkeypatch: pytest.MonkeyPatch) -> _FakeRedis:return redismonkeypatch.setattr(pm_module, "get_redis_async", _get_redis_async)-- # Isolate the mid-turn drain hint: by default there's no live turn, so- # ``drain_pending_messages`` must not reach the real stream registry.- # Stub the lookup to "no active turn" so the emit is a no-op; the- # dedicated emit tests below override these to assert the SSE hint.- async def _no_active_session(_session_id: str) -> None:- return None-- monkeypatch.setattr(pm_module, "get_session", _no_active_session)- monkeypatch.setattr(pm_module, "publish_chunk", AsyncMock())return redis@@ -241,81 +230,6 @@ async def test_drain_defaults_id_for_legacy_entries(fake_redis: _FakeRedis) -> Nassert drained[0].id-# ── Mid-turn drain SSE hint ─────────────────────────────────────────---async def test_drain_emits_pending_drained_hint(- fake_redis: _FakeRedis, monkeypatch: pytest.MonkeyPatch-) -> None:- """A mid-turn drain pushes a ``data-pending-drained`` hint onto the- active turn's stream so the client promotes chips immediately instead- of waiting for its backstop poll."""- from backend.copilot.response_model import StreamPendingDrained- from backend.copilot.stream_registry import ActiveSession-- queued = PendingMessage(content="hi")- await push_pending_message("sessHint", queued)-- active = ActiveSession(- session_id="sessHint",- user_id="u1",- tool_call_id="chat_stream",- tool_name="chat",- turn_id="turn-xyz",- status="running",- )-- async def _get_session(_session_id: str) -> ActiveSession:- return active-- publish = AsyncMock()- monkeypatch.setattr(pm_module, "get_session", _get_session)- monkeypatch.setattr(pm_module, "publish_chunk", publish)-- drained = await drain_pending_messages("sessHint")- assert len(drained) == 1-- publish.assert_awaited_once()- args, kwargs = publish.call_args- assert args[0] == "turn-xyz"- assert isinstance(args[1], StreamPendingDrained)- assert args[1].drainedCount == 1- # The hint carries the drained text + a stable id so the client can render- # the follow-up bubble at the drain point instead of guessing its content.- assert [(m.id, m.content) for m in args[1].messages] == [(queued.id, "hi")]- assert kwargs["session_id"] == "sessHint"---async def test_drain_empty_does_not_emit_hint(- fake_redis: _FakeRedis, monkeypatch: pytest.MonkeyPatch-) -> None:- """No drain → no hint: an empty buffer must not emit a stream chunk."""- publish = AsyncMock()- monkeypatch.setattr(pm_module, "publish_chunk", publish)-- assert await drain_pending_messages("emptySess") == []- publish.assert_not_awaited()---async def test_drain_hint_failure_does_not_break_drain(- fake_redis: _FakeRedis, monkeypatch: pytest.MonkeyPatch-) -> None:- """The hint is best-effort: a stream-registry hiccup while emitting it- must not lose the drained messages."""- await push_pending_message("sessBoom", PendingMessage(content="hi"))-- async def _boom(_session_id: str) -> None:- raise RuntimeError("registry down")-- monkeypatch.setattr(pm_module, "get_session", _boom)-- drained = await drain_pending_messages("sessBoom")- assert [m.content for m in drained] == ["hi"]--# ── Buffer cap ──────────────────────────────────────────────────────diff --git a/autogpt_platform/backend/backend/copilot/response_model.py b/autogpt_platform/backend/backend/copilot/response_model.pyindex 3bad4d3bf4..d8ff148563 100644--- a/autogpt_platform/backend/backend/copilot/response_model.py+++ b/autogpt_platform/backend/backend/copilot/response_model.py@@ -68,6 +68,7 @@ class ResponseType(str, Enum):# ``context_compaction`` tool row's JSON output.COMPACTION = "data-compaction"PROVIDER_FAILURE = "data-provider-failure"+ CHECKPOINT = "data-checkpoint"class StreamBaseResponse(BaseModel):@@ -520,3 +521,30 @@ class StreamPendingDrained(StreamBaseResponse):},}return f"data: {json.dumps(data)}\n\n"+++class StreamCheckpoint(StreamBaseResponse):+ """The turn's first ``rows`` rows are persisted, starting at DB ``sequence``.++ Published only after a successful persist with no block open and no tool+ call pending, so the stream after it is self-contained. ``digest`` is+ ``stream_checkpoint.rows_digest`` over those rows. Transient: the AI SDK+ hands it to ``onData`` and stores nothing.+ """++ type: ResponseType = ResponseType.CHECKPOINT+ rows: int+ sequence: int+ digest: str++ def to_sse(self) -> str:+ data = {+ "type": self.type.value,+ "data": {+ "rows": self.rows,+ "sequence": self.sequence,+ "digest": self.digest,+ },+ "transient": True,+ }+ return f"data: {json.dumps(data)}\n\n"diff --git a/autogpt_platform/backend/backend/copilot/sdk/dummy.py b/autogpt_platform/backend/backend/copilot/sdk/dummy.pyindex d66982a643..4624ee2632 100644--- a/autogpt_platform/backend/backend/copilot/sdk/dummy.py+++ b/autogpt_platform/backend/backend/copilot/sdk/dummy.py@@ -28,6 +28,7 @@ from ..constants import (from ..model import ChatMessage, ChatSession, get_chat_session, upsert_chat_sessionfrom ..response_model import (StreamBaseResponse,+ StreamCheckpoint,StreamError,StreamFinish,StreamFinishStep,@@ -37,6 +38,7 @@ from ..response_model import (StreamTextEnd,StreamTextStart,)+from ..stream_checkpoint import turn_checkpointlogger = logging.getLogger(__name__)@@ -151,9 +153,14 @@ async def stream_chat_completion_dummy(yield StreamTextEnd(id=text_block_id)# Persist the assistant reply so it survives page refresh+ checkpoint: StreamCheckpoint | None = Noneif session:+ turn_start = len(session.messages)session.messages.append(ChatMessage(role="assistant", content=dummy_response))await _safe_upsert(session)+ checkpoint = turn_checkpoint(session.messages, turn_start)yield StreamFinishStep()+ if checkpoint is not None:+ yield checkpointyield StreamFinish()diff --git a/autogpt_platform/backend/backend/copilot/sdk/p0_guardrails_test.py b/autogpt_platform/backend/backend/copilot/sdk/p0_guardrails_test.pyindex 9a139ac1fc..cd8de1c1da 100644--- a/autogpt_platform/backend/backend/copilot/sdk/p0_guardrails_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/p0_guardrails_test.py@@ -730,16 +730,11 @@ class TestDoTransientBackoff:mock_sleep.assert_called_once_with(7)async def test_replaces_adapter_with_new_instance(self):- """state.adapter is replaced with a new SDKResponseAdapter after yield,- and ``render_reasoning_in_ui`` is threaded from the SDK service config- (not hardcoded) so ``CHAT_RENDER_REASONING_IN_UI=false`` at runtime- flips the reconstruction consistently with the rest of the path."""+ """state.adapter is replaced with a new SDKResponseAdapter after yield."""from unittest.mock import AsyncMock, MagicMock, patchfrom backend.copilot.sdk.service import _do_transient_backoff- cfg = _make_config(render_reasoning_in_ui=False)-original_adapter = MagicMock()state = MagicMock()state.adapter = original_adapter@@ -747,7 +742,6 @@ class TestDoTransientBackoff:with (patch("asyncio.sleep", new=AsyncMock()),- patch(f"{_SVC}.config", cfg),patch("backend.copilot.sdk.service.SDKResponseAdapter") as mock_cls,):new_adapter = MagicMock()@@ -755,11 +749,7 @@ class TestDoTransientBackoff:async for _ in _do_transient_backoff(3, state, "msg-1", "sess-1"):pass- mock_cls.assert_called_once_with(- message_id="msg-1",- session_id="sess-1",- render_reasoning_in_ui=False,- )+ mock_cls.assert_called_once_with(message_id="msg-1", session_id="sess-1")assert state.adapter is new_adapterasync def test_resets_usage_after_yield(self):diff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.pyindex 3d03a1ec63..070270af49 100644--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py@@ -82,8 +82,6 @@ class SDKResponseAdapter:self,message_id: str | None = None,session_id: str | None = None,- *,- render_reasoning_in_ui: bool = True,):self.message_id = message_id or str(uuid.uuid4())self.session_id = session_id@@ -93,7 +91,6 @@ class SDKResponseAdapter:self.reasoning_block_id = str(uuid.uuid4())self.has_started_reasoning = Falseself.has_ended_reasoning = True- self.render_reasoning_in_ui = render_reasoning_in_ui# Service layer forwards this from the prior adapter on a retry-recreate# so the empty-completion guard doesn't false-fire on a benign empty# trailing ResultMessage when the prior attempt already streamed content.@@ -314,17 +311,6 @@ class SDKResponseAdapter:# thinking-only left the UI stuck on "Thought for Xs"# with nothing rendered until a page refresh.#- # When ``render_reasoning_in_ui=False`` the three- # reasoning helpers below (and the append) no-op, so- # the frontend sees a text-only stream AND no- # ``ChatMessage(role='reasoning')`` row is persisted- # (the row is only created by ``_dispatch_response``- # when ``StreamReasoningStart`` arrives, which is- # suppressed here). Persistence of the thinking text- # into the SDK transcript via- # ``_format_sdk_content_blocks`` is unaffected — that- # feeds ``--resume`` continuity, not the UI.- ## Flush any pending coalesce buffer to the wire BEFORE# computing the tail — otherwise a summary that# arrives between the last partial delta and the@@ -748,11 +734,7 @@ class SDKResponseAdapter:Each ``ThinkingBlock`` the SDK emits gets its own streaming blockso the frontend can render a new ``Reasoning`` part per LLM turn- (rather than concatenating across the whole session). Events- are emitted unconditionally — the caller filters them out of the- SSE wire when ``render_reasoning_in_ui=False`` but still feeds- them through ``_dispatch_response`` so the session transcript- keeps a ``role='reasoning'`` row.+ (rather than concatenating across the whole session)."""if not self.has_started_reasoning or self.has_ended_reasoning:if self.has_ended_reasoning:diff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.pyindex 47a1a4d3c6..9520c04162 100644--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py@@ -390,41 +390,10 @@ def test_empty_thinking_block_is_ignored():assert [type(r).__name__ for r in results] == ["StreamStartStep"]-def test_render_reasoning_in_ui_false_still_emits_adapter_events():- """With the persist/render decoupling the adapter is flag-agnostic:- it always emits ``StreamReasoning*`` so the session transcript keeps a- durable reasoning record. Wire-level suppression when- ``render_reasoning_in_ui=False`` happens at the SDK service yield- boundary, not here — see- ``backend/copilot/sdk/service.py::_filter_reasoning_events``.- """- adapter = SDKResponseAdapter(- message_id="m",- session_id="s",- render_reasoning_in_ui=False,- )- msg = AssistantMessage(- content=[ThinkingBlock(thinking="plan", signature="sig")],- model="test",- )- results = adapter.convert_message(msg)- types = [type(r).__name__ for r in results]- assert "StreamReasoningStart" in types- assert "StreamReasoningDelta" in types---def test_render_reasoning_off_text_after_thinking_still_closes_reasoning():- """Adapter still emits a ``StreamReasoningEnd`` when text follows a- thinking block — decoupled from the render flag. The service layer- drops the reasoning events at yield time; the adapter's structural- open/close pairing must not depend on the flag or downstream filters- would see orphan reasoning starts on the persisted transcript.- """- adapter = SDKResponseAdapter(- message_id="m",- session_id="s",- render_reasoning_in_ui=False,- )+def test_text_after_thinking_closes_reasoning():+ """Text following a thinking block closes the reasoning block first, so+ the transcript never holds an orphan reasoning start."""+ adapter = SDKResponseAdapter(message_id="m", session_id="s")adapter.convert_message(AssistantMessage(content=[ThinkingBlock(thinking="warming up", signature="sig")],diff --git a/autogpt_platform/backend/backend/copilot/sdk/retry_scenarios_test.py b/autogpt_platform/backend/backend/copilot/sdk/retry_scenarios_test.pyindex 4385388ce0..9d1d555f5a 100644--- a/autogpt_platform/backend/backend/copilot/sdk/retry_scenarios_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/retry_scenarios_test.py@@ -34,14 +34,18 @@ from claude_agent_sdk import ResultMessagefrom backend.copilot.constants import COMPACTION_TOOL_NAMEfrom backend.copilot.model import ChatMessage, ChatSessionfrom backend.copilot.response_model import (+ StreamCheckpoint,StreamCompactionProgress,StreamError,+ StreamTextEnd,StreamToolInputAvailable,StreamToolInputStart,StreamToolOutputAvailable,)from backend.copilot.sdk.compaction import CompactionStatsfrom backend.copilot.sdk.service import _RestoreResult, stream_chat_completion_sdk+from backend.copilot.stream_checkpoint import turn_checkpoint+from backend.copilot.stream_drift.recording import saving_intofrom backend.copilot.transcript import (TranscriptDownload,_flatten_assistant_content,@@ -2515,3 +2519,95 @@ class TestPreQueryCompactionRowTiming:opened, _closed = self._compaction_marks(timeline)assert opened == []+++class TestTurnEndCheckpoint:+ """The turn-end persist in the engine's ``finally`` is followed by a+ checkpoint only when it landed."""++ async def test_the_turn_end_persist_is_followed_by_its_checkpoint(self):+ saves: list[ChatSession] = []++ events = await self._run(AsyncMock(side_effect=saving_into(saves)))++ checkpoints = [e for e in events if isinstance(e, StreamCheckpoint)]+ assert checkpoints == [turn_checkpoint(saves[-1].messages, self._TURN_START)]+ assert checkpoints[0].rows == 1+ last_text_end = max(+ i for i, e in enumerate(events) if isinstance(e, StreamTextEnd)+ )+ assert events.index(checkpoints[0]) > last_text_end++ async def test_a_failed_turn_end_persist_publishes_no_checkpoint(self):+ events = await self._run(AsyncMock(side_effect=ConnectionError("db down")))++ assert not any(isinstance(e, StreamCheckpoint) for e in events)++ # A later turn: a first one runs setup that calls other services.+ _HISTORY = [+ ChatMessage(role="user", content="earlier"),+ ChatMessage(role="assistant", content="earlier answer"),+ ChatMessage(role="user", content="hello"),+ ]+ _TURN_START = len(_HISTORY)++ async def _run(self, upsert: AsyncMock) -> list:+ from claude_agent_sdk import AssistantMessage, SystemMessage, TextBlock++ session = ChatSession(+ session_id="test-session-id",+ user_id="test-user",+ title="Greeting",+ usage=[],+ started_at=datetime.now(UTC),+ updated_at=datetime.now(UTC),+ messages=[m.model_copy() for m in self._HISTORY],+ )++ async def _receive():+ yield SystemMessage(subtype="init", data={})+ yield AssistantMessage(content=[TextBlock(text="Hi there.")], model="t")+ yield ResultMessage(+ subtype="success",+ result="Hi there.",+ duration_ms=100,+ duration_api_ms=50,+ is_error=False,+ num_turns=1,+ session_id="test-session-id",+ )++ client = MagicMock(receive_response=_receive, query=AsyncMock())+ client_cm = AsyncMock()+ client_cm.__aenter__.return_value = client+ patches = [+ (target, kwargs)+ for target, kwargs in _make_sdk_patches(+ session,+ original_transcript=_build_transcript([("user", "hi")]),+ compacted_transcript=None,+ client_side_effect=lambda *a, **kw: client_cm,+ )+ if target != f"{_SVC}.upsert_chat_session"+ ]+ events = []+ with contextlib.ExitStack() as stack:+ for target, kwargs in patches:+ stack.enter_context(patch(target, **kwargs))+ stack.enter_context(patch(f"{_SVC}.upsert_chat_session", new=upsert))+ # The skill-drift notice reads the workspace over RPC.+ stack.enter_context(+ patch(+ f"{_SVC}._maybe_prepend_skills_update",+ new=AsyncMock(side_effect=lambda *args: args[-1]),+ )+ )+ async for event in stream_chat_completion_sdk(+ session_id="test-session-id",+ message="hello",+ is_user_message=True,+ user_id="test-user",+ session=session,+ ):+ events.append(event)+ return eventsdiff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.pyindex 8d12649e0a..14b851af5b 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py@@ -116,11 +116,13 @@ from ..model import (from ..pending_message_helpers import (combine_pending_with_current,drain_pending_safe,+ drained_rows_entry,pending_texts_from,persist_pending_as_user_rows,persist_session_safe,)from ..pending_messages import (+ PendingMessage,drain_pending_for_persist,push_pending_message,)@@ -145,12 +147,14 @@ from ..rate_limit import ()from ..response_model import (StreamBaseResponse,+ StreamCheckpoint,StreamCompactionProgress,StreamError,StreamFinish,StreamProviderFailure,StreamFinishStep,StreamHeartbeat,+ StreamPendingDrained,StreamReasoningDelta,StreamReasoningEnd,StreamReasoningStart,@@ -179,6 +183,7 @@ from ..service import (inject_user_context,strip_user_context_tags,)+from ..stream_checkpoint import turn_checkpointfrom ..thinking_stripper import ThinkingStripperfrom ..token_tracking import persist_and_record_usagefrom ..tools import (@@ -808,18 +813,6 @@ async def _consume_sdk_until_done(skip_strip=response is tail_delta,)if dispatched is not None:- # Persistence (via _dispatch_response) always runs so the- # session transcript keeps role='reasoning' rows; the- # wire is gated so UI can suppress rendering.- if not state.adapter.render_reasoning_in_ui and isinstance(- dispatched,- (- StreamReasoningStart,- StreamReasoningDelta,- StreamReasoningEnd,- ),- ):- continue# The envelope goes out just ahead of the error it explains,# so a client acting on it has it in hand before the turn is# reported failed. Same contract as the baseline path.@@ -864,6 +857,7 @@ async def _consume_sdk_until_done(# watermark excludes them and the next turn's# detect_gap picks them up as gap-fill.state.midturn_user_rows += len(followup_drained)+ yield drained_rows_entry(followup_drained)# Append assistant entry AFTER convert_message so that# any stashed tool results from the previous turn are@@ -905,6 +899,7 @@ async def _consume_sdk_until_done(loop_state.msgs_since_flush >= _FLUSH_MESSAGE_THRESHOLDor (now - loop_state.last_flush_time) >= _FLUSH_INTERVAL_SECONDS):+ checkpoint = Nonetry:await asyncio.shield(upsert_chat_session(ctx.session))logger.debug(@@ -914,6 +909,7 @@ async def _consume_sdk_until_done(loop_state.msgs_since_flush,now - loop_state.last_flush_time,)+ checkpoint = turn_checkpoint(ctx.session.messages, ctx.turn_start)except Exception as flush_err:logger.warning("%s Intermediate flush failed: %s",@@ -922,6 +918,8 @@ async def _consume_sdk_until_done()loop_state.last_flush_time = nowloop_state.msgs_since_flush = 0+ if checkpoint is not None:+ yield checkpoint# --- Building-mode switch (enter_agent_building_mode) ---# Restart the attempt with the guide in the system prompt.@@ -1014,10 +1012,13 @@ def _intermediate_flush_blocked(has_unsealed_assistant = (acc.has_appended_assistant and not acc.accumulated_tool_calls)- has_open_block = (adapter.has_started_text and not adapter.has_ended_text) or (+ return has_pending_tools or has_unsealed_assistant or _has_open_block(adapter)+++def _has_open_block(adapter: SDKResponseAdapter) -> bool:+ return (adapter.has_started_text and not adapter.has_ended_text) or (adapter.has_started_reasoning and not adapter.has_ended_reasoning)- return has_pending_tools or has_unsealed_assistant or has_open_blockdef _hidden_short_names_for_permissions(@@ -1174,6 +1175,8 @@ _OUTER_LOOP_YIELDS_ERROR_CODES: frozenset[str] = frozenset(# ``None`` when ``events_yielded > 0``._EPHEMERAL_EVENT_TYPES = (StreamHeartbeat,+ StreamCheckpoint,+ StreamPendingDrained,StreamToolDisplayAvailable,# Compaction UI events are cosmetic and must not block retry — they're# emitted before the SDK query on compacted attempts.@@ -1493,6 +1496,8 @@ class _StreamContext:# text, and the gateway holds the last point at which it was typed.codex_gateway: "CodexAnthropicGateway | None" = Nonetool_display: SDKToolDisplayBridge | None = None+ # Index in ``session.messages`` of the stream's first row, for checkpoints.+ turn_start: int = 0# Per-retry token budgets for the no-transcript (use_resume=False) path.@@ -1877,7 +1882,6 @@ async def _apply_building_mode_restart(state.adapter = SDKResponseAdapter(message_id=message_id,session_id=session_id,- render_reasoning_in_ui=config.render_reasoning_in_ui,)state.adapter.thinking_only_reprompted = state.thinking_only_repromptedif prior_adapter.emitted_real_content_to_wire:@@ -2504,7 +2508,6 @@ async def _do_transient_backoff(state.adapter = SDKResponseAdapter(message_id=message_id,session_id=session_id,- render_reasoning_in_ui=config.render_reasoning_in_ui,)state.usage.reset()@@ -3854,7 +3857,20 @@ def _dispatch_response(if isinstance(response, StreamReasoningStart):acc.reasoning_response = ChatMessage(role="reasoning", content="")- ctx.session.messages.append(acc.reasoning_response)+ messages = ctx.session.messages+ # The post-tool placeholder pre-created for this message's text goes+ # after its thinking, in the order the wire carries them.+ placeholder = acc.assistant_response+ if (+ messages+ and messages[-1] is placeholder+ and placeholder.sequence is None+ and not placeholder.content+ and not placeholder.tool_calls+ ):+ messages.insert(len(messages) - 1, acc.reasoning_response)+ else:+ messages.append(acc.reasoning_response)elif isinstance(response, StreamReasoningDelta):if acc.reasoning_response is not None:@@ -3905,6 +3921,12 @@ def _dispatch_response()elif isinstance(response, StreamToolInputAvailable):+ # A new assistant row opens after tool results, for a call as for text.+ if acc.has_tool_results and acc.has_appended_assistant:+ acc.assistant_response = ChatMessage(role="assistant", content="")+ acc.accumulated_tool_calls = []+ acc.has_appended_assistant = False+ acc.has_tool_results = Falseacc.accumulated_tool_calls.append({"id": response.toolCallId,@@ -4682,6 +4704,8 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssuesteam_id: str | None = None,credential_lease: CredentialLease | CodexCredentialLease | None = None,message_metadata: dict[str, Any] | None = None,+ turn_start: int | None = None,+ continued_pending: list[PendingMessage] | None = None,**_kwargs: Any,) -> AsyncGenerator[StreamBaseResponse, None]:# Pyright's complexity heuristic bails on this ~1500 LoC function (retry@@ -4773,10 +4797,24 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssuesif is_user_message and message and message.strip():await clear_pending_question(session)- _user_message_appended = maybe_append_user_message(- session, message, is_user_message, message_metadata- )- if _user_message_appended and is_user_message:+ continued_entry: StreamPendingDrained | None = None+ if continued_pending:+ # An auto-continue call streams into the turn it continues: its user+ # rows are the drained messages, one each, as a turn-start drain's are.+ if not await persist_pending_as_user_rows(+ session,+ None,+ continued_pending,+ log_prefix=f"[SDK][{session_id[:12]}]",+ ):+ return # rolled back and re-queued for the next turn+ continued_entry = drained_rows_entry(continued_pending)+ _user_message_appended = False+ else:+ _user_message_appended = maybe_append_user_message(+ session, message, is_user_message, message_metadata+ )+ if (_user_message_appended or continued_entry) and is_user_message:track_user_message(user_id=user_id,session_id=session_id,@@ -4818,6 +4856,10 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssuesf"in-memory append rolled back")+ # The stream's rows start after the message that triggered it.+ if turn_start is None:+ turn_start = len(session.messages)+# Generate title for new sessions (first user message)if is_user_message and not session.title:user_messages = [m for m in session.messages if m.role == "user"]@@ -4916,6 +4958,7 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssues# the loop (post-stream upload guards, finally-block bookkeeping) sees a# bound name even when the loop never enters its happy path.ended_with_stream_error = False+ final_checkpoint: StreamCheckpoint | None = None# Make sure there is no more code between the lock acquisition and try-block.try:@@ -5085,6 +5128,8 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssuesrestore_context_messages = _restore.context_messagesyield StreamStart(messageId=message_id, sessionId=session_id)+ if continued_entry is not None:+ yield continued_entryset_execution_context(user_id,@@ -5349,7 +5394,6 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssuesadapter = SDKResponseAdapter(message_id=message_id,session_id=session_id,- render_reasoning_in_ui=config.render_reasoning_in_ui,)# Propagate user_id/session_id as OTEL context attributes so the@@ -5546,6 +5590,7 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssueslog_prefix=log_prefix,)if persisted_ok:+ yield drained_rows_entry(pending_messages)current_message = combine_pending_with_current(pending_messages,current_message,@@ -5660,6 +5705,7 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssueslock=lock,codex_gateway=codex_gateway,tool_display=tool_display_bridge,+ turn_start=turn_start,)# ---------------------------------------------------------------@@ -5829,7 +5875,6 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssuesstate.adapter = SDKResponseAdapter(message_id=message_id,session_id=session_id,- render_reasoning_in_ui=config.render_reasoning_in_ui,)# Carry the per-turn re-prompt cap forward so a transient# retry mid-turn does not unlock another re-prompt round.@@ -6446,6 +6491,10 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssueslog_prefix,len(session.messages),)+ if turn_start is not None and not (+ state is not None and _has_open_block(state.adapter)+ ):+ final_checkpoint = turn_checkpoint(session.messages, turn_start)except Exception as persist_err:logger.error("%s Failed to persist session in finally: %s",@@ -6612,6 +6661,11 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssuesturn_error,)+ # Yielded here, not in ``finally``: an async generator cannot yield while+ # it is being closed, and a closed turn has nobody left to read it.+ if final_checkpoint is not None:+ yield final_checkpoint+# -------------------------------------------------------------------------# Auto-continue: drain any messages the user queued AFTER the turn-start# drain window and process them as a new turn automatically.@@ -6680,6 +6734,8 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssuesorganization_id=organization_id,team_id=team_id,credential_lease=credential_lease,+ turn_start=turn_start,+ continued_pending=_auto_pending_messages,):if _first_auto_event:_first_auto_event = Falsediff --git a/autogpt_platform/backend/backend/copilot/sdk/session_waiter.py b/autogpt_platform/backend/backend/copilot/sdk/session_waiter.pyindex b071e0c906..139e96e690 100644--- a/autogpt_platform/backend/backend/copilot/sdk/session_waiter.py+++ b/autogpt_platform/backend/backend/copilot/sdk/session_waiter.py@@ -109,7 +109,7 @@ async def wait_for_session_result(remaining = deadline - loop.time()if remaining <= 0:break- event = await asyncio.wait_for(queue.get(), timeout=remaining)+ _, event = await asyncio.wait_for(queue.get(), timeout=remaining)process_event(event, acc)if isinstance(event, StreamFinish):outcome = "completed"diff --git a/autogpt_platform/backend/backend/copilot/stream_checkpoint.py b/autogpt_platform/backend/backend/copilot/stream_checkpoint.pynew file mode 100644index 0000000000..9f87779f46--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/stream_checkpoint.py@@ -0,0 +1,59 @@+"""The checkpoint an engine publishes once its turn's rows so far are persisted."""++import hashlib+import json+from collections.abc import Sequence+from typing import Any++from backend.copilot.model import ChatMessage+from backend.copilot.response_model import StreamCheckpoint+++def turn_checkpoint(+ messages: Sequence[ChatMessage], turn_start: int+) -> StreamCheckpoint | None:+ """The checkpoint for ``messages[turn_start:]``, or None unless all of them landed.++ A row without a sequence failed to persist, a row still flagged+ ``tool_calls_pending_save`` holds tool calls its back-fill has not written,+ and a gap in the sequences means the DB rows from the first one are not+ these rows.+ """+ rows = messages[turn_start:]+ sequences = [row.sequence for row in rows if row.sequence is not None]+ if (+ not rows+ or len(sequences) != len(rows)+ or any(row.tool_calls_pending_save for row in rows)+ ):+ return None+ first = sequences[0]+ if sequences != list(range(first, first + len(rows))):+ return None+ return StreamCheckpoint(rows=len(rows), sequence=first, digest=rows_digest(rows))+++def rows_digest(rows: Sequence[ChatMessage]) -> str:+ """SHA-256 of the rows' compact JSON, which ``JSON.stringify`` reproduces."""+ return canonical_digest(canonical_rows(rows))+++def canonical_rows(rows: Sequence[ChatMessage]) -> list[list[Any]]:+ """Per row: role, content (a tool row's tool_call_id) and the ordered+ (id, name) tool calls; tool inputs and outputs serialise differently in JS."""+ return [+ [+ row.role,+ (row.tool_call_id if row.role == "tool" else row.content) or "",+ [+ [call.get("id", ""), call.get("function", {}).get("name", "")]+ for call in row.tool_calls or []+ ],+ ]+ for row in rows+ ]+++def canonical_digest(canonical: list[list[Any]]) -> str:+ text = json.dumps(canonical, ensure_ascii=False, separators=(",", ":"))+ return hashlib.sha256(text.encode("utf-8", "surrogatepass")).hexdigest()diff --git a/autogpt_platform/backend/backend/copilot/stream_checkpoint_test.py b/autogpt_platform/backend/backend/copilot/stream_checkpoint_test.pynew file mode 100644index 0000000000..3d88c2a2d8--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/stream_checkpoint_test.py@@ -0,0 +1,25 @@+from backend.copilot.model import ChatMessage+from backend.copilot.stream_checkpoint import rows_digest, turn_checkpoint+++def test_a_checkpoint_waits_for_the_tool_call_back_fill():+ rows = [+ ChatMessage(role="user", content="Go", sequence=0),+ ChatMessage(+ role="assistant",+ content="",+ sequence=1,+ tool_calls=[{"id": "c1", "function": {"name": "bash_exec"}}],+ tool_calls_pending_save=True,+ ),+ ChatMessage(role="tool", content="ok", tool_call_id="c1", sequence=2),+ ]++ held = turn_checkpoint(rows, 1)+ rows[1].tool_calls_pending_save = False+ landed = turn_checkpoint(rows, 1)++ assert held is None+ assert landed is not None+ assert (landed.rows, landed.sequence) == (2, 1)+ assert landed.digest == rows_digest(rows[1:])diff --git a/autogpt_platform/backend/backend/copilot/stream_drift/checkpoints_test.py b/autogpt_platform/backend/backend/copilot/stream_drift/checkpoints_test.pynew file mode 100644index 0000000000..fff3313ee8--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/stream_drift/checkpoints_test.py@@ -0,0 +1,221 @@+"""A checkpoint follows a persist that landed, never with a block open.++Both engines run their real persist paths with the DB swapped for+``saving_into``; the timeline interleaves each save with the events around it,+so a checkpoint must equal the one the latest save before it describes.+"""++import uuid+from collections.abc import AsyncGenerator+from unittest.mock import AsyncMock++import pytest+from claude_agent_sdk import (+ AssistantMessage,+ ResultMessage,+ SystemMessage,+ TextBlock,+ ToolResultBlock,+ ToolUseBlock,+ UserMessage,+)++from backend.copilot import pending_message_helpers+from backend.copilot.baseline import service as baseline+from backend.copilot.model import ChatSession+from backend.copilot.pending_messages import PendingMessage+from backend.copilot.response_model import (+ ResponseType,+ StreamBaseResponse,+ StreamCheckpoint,+ StreamToolOutputAvailable,+)+from backend.copilot.sdk import service as sdk+from backend.copilot.stream_checkpoint import turn_checkpoint++from .recording import (+ assert_fold_matches_rows,+ fixture_names,+ load_fixture,+ saving_into,+)+from .scripted import baseline_turn, provider_round, sdk_turn, session_with_prompt++# The prompt is row 0, so every turn's rows start at 1.+TURN_START = 1+++async def test_the_sdk_engine_checkpoints_each_flush_that_landed(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(sdk, "_FLUSH_MESSAGE_THRESHOLD", 1)+ timeline = Timeline()+ monkeypatch.setattr(sdk, "upsert_chat_session", timeline.save)++ await timeline.run(sdk_turn(session_with_prompt("List the files"), _sdk_script()))++ # The flush policy holds every flush but the one after the tool round+ # (assistant row plus tool row); the second checkpoint is the turn end's.+ assert [c.rows for c in timeline.checkpoints()] == [2, 3]+++async def test_the_sdk_engine_publishes_no_checkpoint_for_a_failed_flush(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(sdk, "_FLUSH_MESSAGE_THRESHOLD", 1)+ timeline = Timeline()+ monkeypatch.setattr(+ sdk, "upsert_chat_session", AsyncMock(side_effect=ConnectionError("db down"))+ )++ with pytest.raises(ConnectionError): # the scripted turn-end persist+ await timeline.run(+ sdk_turn(session_with_prompt("List the files"), _sdk_script())+ )++ assert timeline.checkpoints() == []+++async def test_the_baseline_engine_checkpoints_the_tool_round_and_the_turn(+ monkeypatch: pytest.MonkeyPatch, baseline_io: list[ChatSession]+) -> None:+ timeline = Timeline()+ monkeypatch.setattr(baseline, "upsert_chat_session", timeline.save)+ monkeypatch.setattr(pending_message_helpers, "upsert_chat_session", timeline.save)+ _script_baseline_tool_turn(monkeypatch)++ await timeline.run(+ baseline_turn(session_with_prompt("What does example.com say?"), "t")+ )++ # After round one: its assistant and tool rows plus the drained follow-up.+ assert [c.rows for c in timeline.checkpoints()] == [3, 4]+++async def test_the_baseline_engine_publishes_no_checkpoint_for_a_failed_persist(+ monkeypatch: pytest.MonkeyPatch, baseline_io: list[ChatSession]+) -> None:+ timeline = Timeline()+ failing = AsyncMock(side_effect=ConnectionError("db down"))+ monkeypatch.setattr(baseline, "upsert_chat_session", failing)+ monkeypatch.setattr(pending_message_helpers, "upsert_chat_session", failing)+ monkeypatch.setattr(pending_message_helpers, "push_pending_message", AsyncMock())+ _script_baseline_tool_turn(monkeypatch)++ await timeline.run(+ baseline_turn(session_with_prompt("What does example.com say?"), "t")+ )++ assert timeline.checkpoints() == []++[email protected]("name", fixture_names())+def test_every_recorded_turn_folds_to_its_rows(name: str) -> None:+ assert_fold_matches_rows(load_fixture(name))++[email protected]("name", fixture_names())+def test_no_recorded_checkpoint_sits_inside_a_block_or_a_tool_call(name: str) -> None:+ open_parts: set[str] = set()+ checkpoints = 0+ for entry in load_fixture(name).entries:+ chunk = entry["data"]+ _track_open_parts(open_parts, chunk["type"], chunk)+ if chunk["type"] == "data-checkpoint":+ assert not open_parts, f"{entry['id']} checkpoints inside {open_parts}"+ checkpoints += 1+ assert checkpoints+++class Timeline:+ """Saves and published events in the order they happened."""++ def __init__(self) -> None:+ self.saves: list[ChatSession] = []+ self._save = saving_into(self.saves)+ self.log: list[ChatSession | StreamBaseResponse] = []++ async def save(self, session: ChatSession) -> ChatSession:+ saved = await self._save(session)+ self.log.append(self.saves[-1])+ return saved++ async def run(self, engine: AsyncGenerator[StreamBaseResponse, None]) -> None:+ async for event in engine:+ self.log.append(event)++ def checkpoints(self) -> list[StreamCheckpoint]:+ """Every checkpoint, each checked against the save before it and+ against the blocks and tool calls open at that point."""+ last_save: ChatSession | None = None+ open_parts: set[str] = set()+ checkpoints = []+ for item in self.log:+ if isinstance(item, ChatSession):+ last_save = item+ continue+ _track_open_parts(open_parts, item.type.value, item.model_dump())+ if isinstance(item, StreamCheckpoint):+ assert not open_parts, f"checkpoint inside {open_parts}"+ assert last_save is not None, "checkpoint before any save"+ assert item == turn_checkpoint(last_save.messages, TURN_START)+ checkpoints.append(item)+ return checkpoints+++def _track_open_parts(open_parts: set[str], kind: str, chunk: dict) -> None:+ if kind in (ResponseType.TEXT_START, ResponseType.REASONING_START):+ open_parts.add(chunk["id"])+ elif kind in (ResponseType.TEXT_END, ResponseType.REASONING_END):+ open_parts.discard(chunk["id"])+ elif kind == ResponseType.TOOL_INPUT_AVAILABLE:+ open_parts.add(chunk["toolCallId"])+ elif kind == ResponseType.TOOL_OUTPUT_AVAILABLE:+ open_parts.discard(chunk["toolCallId"])+++def _sdk_script() -> list:+ return [+ SystemMessage(subtype="init", data={}),+ AssistantMessage(content=[TextBlock(text="Let me look.")], model="drift"),+ AssistantMessage(+ content=[+ ToolUseBlock(id="bash-1", name="bash_exec", input={"command": "ls"})+ ],+ model="drift",+ ),+ UserMessage(content=[ToolResultBlock(tool_use_id="bash-1", content="a.md")]),+ AssistantMessage(content=[TextBlock(text="There is a.md.")], model="drift"),+ ResultMessage(+ subtype="success",+ duration_ms=100,+ duration_api_ms=50,+ is_error=False,+ num_turns=2,+ session_id="drift",+ ),+ ]+++def _script_baseline_tool_turn(monkeypatch: pytest.MonkeyPatch) -> None:+ rounds = [+ provider_round(+ ["Let me ", "fetch that."],+ tool_call={"id": "call-fetch", "name": "web_fetch", "url": "example.com"},+ ),+ provider_round(["It says ", "Example Domain."]),+ ]+ monkeypatch.setattr(baseline, "call_provider_stream", AsyncMock(side_effect=rounds))++ async def execute(*, tool_call_id: str, **_: object) -> StreamToolOutputAvailable:+ return StreamToolOutputAvailable(+ toolCallId=tool_call_id, toolName="web_fetch", output="Example Domain"+ )++ monkeypatch.setattr(baseline, "execute_tool", AsyncMock(side_effect=execute))+ follow_up = PendingMessage(id=str(uuid.uuid4()), content="and in French?")+ monkeypatch.setattr(+ baseline,+ "drain_pending_messages",+ AsyncMock(side_effect=[[follow_up], [], [], []]),+ )diff --git a/autogpt_platform/backend/backend/copilot/stream_drift/conftest.py b/autogpt_platform/backend/backend/copilot/stream_drift/conftest.pyindex ce666e4bfc..69d59b1737 100644--- a/autogpt_platform/backend/backend/copilot/stream_drift/conftest.py+++ b/autogpt_platform/backend/backend/copilot/stream_drift/conftest.py@@ -6,11 +6,14 @@ from unittest.mock import AsyncMock, MagicMockimport pytestimport pytest_asyncio+from backend.copilot import pending_message_helpersfrom backend.copilot.baseline import service as baselinefrom backend.copilot.context import set_execution_contextfrom backend.copilot.model import ChatSessionfrom backend.copilot.model_router import ResolvedModel+from .recording import saving_into+@pytest_asyncio.fixture(scope="session", loop_scope="session")async def server(): # type: ignore[override]@@ -23,14 +26,21 @@ async def graph_cleanup(): # type: ignore[override]@pytest.fixture-def baseline_io(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[ChatSession]]:- """Every session the baseline engine persists, with its I/O stubbed."""+def baseline_io(+ monkeypatch: pytest.MonkeyPatch, baseline_offline: None+) -> list[ChatSession]:+ """Every session the baseline engine persists, with persistence stubbed too."""persisted: list[ChatSession] = []+ save = AsyncMock(side_effect=saving_into(persisted))+ # The mid-turn persist goes through ``persist_session_safe``.+ monkeypatch.setattr(baseline, "upsert_chat_session", save)+ monkeypatch.setattr(pending_message_helpers, "upsert_chat_session", save)+ return persisted- async def save(session: ChatSession) -> ChatSession:- persisted.append(session.model_copy(deep=True))- return session+def baseline_offline(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:+ """The baseline engine with everything but its persistence stubbed."""monkeypatch.setattr(baseline,"config",@@ -52,8 +62,7 @@ def baseline_io(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[ChatSession]]:}.items():monkeypatch.setattr(baseline, name, AsyncMock(return_value=value))monkeypatch.setattr(baseline, "_get_main_client", MagicMock())- monkeypatch.setattr(baseline, "upsert_chat_session", AsyncMock(side_effect=save))try:- yield persisted+ yieldfinally:set_execution_context(None, None)diff --git a/autogpt_platform/backend/backend/copilot/stream_drift/drift_causes_test.py b/autogpt_platform/backend/backend/copilot/stream_drift/drift_causes_test.pyindex 8e7f5d4c75..f0f7fd89f9 100644--- a/autogpt_platform/backend/backend/copilot/stream_drift/drift_causes_test.py+++ b/autogpt_platform/backend/backend/copilot/stream_drift/drift_causes_test.py@@ -114,27 +114,16 @@ async def test_a_turn_whose_executor_died_is_not_reported_running(@requires_redis- strict=True,- raises=AssertionError,- reason=(- "W5: publish_chunk trims a running turn's stream to stream_max_length, "- "so a resume replays from mid-block and the client's parser throws"- ),-)async def test_a_resume_of_a_long_running_turn_replays_whole_blocks(- monkeypatch: pytest.MonkeyPatch, session_id: str, turn_id: str+ session_id: str, turn_id: str) -> None:- monkeypatch.setattr(- stream_registry,- "config",- stream_registry.config.model_copy(update={"stream_max_length": 20}),- )+ """W5: a running turn's stream used to be capped at 10,000 entries, so a+ resume replayed from mid-block and the client's parser threw."""await stream_registry.create_session(session_id, None, "", "", turn_id=turn_id)for chunk in [StreamStart(messageId="m1"),StreamTextStart(id="t1"),- *(StreamTextDelta(id="t1", delta=f"{i} ") for i in range(300)),+ *(StreamTextDelta(id="t1", delta=f"{i} ") for i in range(_PAST_THE_OLD_CAP)),]:await stream_registry.publish_chunk(turn_id, chunk, session_id=session_id)@@ -142,13 +131,19 @@ async def test_a_resume_of_a_long_running_turn_replays_whole_blocks(if queue is None:pytest.fail("harness: the running turn has no subscribable stream")try:- replay = [queue.get_nowait() for _ in range(queue.qsize())]+ replay = [queue.get_nowait()[1] for _ in range(queue.qsize())]finally:await stream_registry.unsubscribe_from_session(session_id, queue)+ assert len(replay) == _PAST_THE_OLD_CAP + 2assert _orphan_parts(replay) == []+# Past the old 10,000 cap by several of Redis's 100-entry stream nodes, which+# is where an approximate MAXLEN starts trimming.+_PAST_THE_OLD_CAP = 10_500++@pytest.mark.xfail(strict=True,raises=AssertionError,diff --git a/autogpt_platform/backend/backend/copilot/stream_drift/fold.py b/autogpt_platform/backend/backend/copilot/stream_drift/fold.pynew file mode 100644index 0000000000..285df769ee--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/stream_drift/fold.py@@ -0,0 +1,39 @@+"""The rows a turn's stream folds to, by the design's row rules.++A reference for the fixture checks, in the canonical shape of+``stream_checkpoint.canonical_rows``: at every checkpoint, and at the end, the+fold of the entries so far must equal the rows the backend persisted.+"""++from collections.abc import Iterable+from typing import Any+++def fold_rows(chunks: Iterable[dict[str, Any]]) -> list[list[Any]]:+ rows: list[list[Any]] = []+ assistant: int | None = None # the row text and tool calls land in+ blocks: dict[str, int] = {}+ for chunk in chunks:+ kind = chunk["type"]+ if kind == "text-start":+ if assistant is None:+ rows.append(["assistant", "", []])+ assistant = len(rows) - 1+ blocks[chunk["id"]] = assistant+ elif kind == "reasoning-start":+ rows.append(["reasoning", "", []])+ blocks[chunk["id"]] = len(rows) - 1+ elif kind in ("text-delta", "reasoning-delta"):+ rows[blocks[chunk["id"]]][1] += chunk["delta"]+ elif kind == "tool-input-available":+ if assistant is None:+ rows.append(["assistant", "", []])+ assistant = len(rows) - 1+ rows[assistant][2].append([chunk["toolCallId"], chunk["toolName"]])+ elif kind == "tool-output-available":+ rows.append(["tool", chunk["toolCallId"], []])+ assistant = None+ elif kind == "data-pending-drained":+ rows.extend(["user", m["content"], []] for m in chunk["messages"])+ assistant = None+ return rowsdiff --git a/autogpt_platform/backend/backend/copilot/stream_drift/recorded_turns_test.py b/autogpt_platform/backend/backend/copilot/stream_drift/recorded_turns_test.pyindex ab80246ab0..f45dd8bd2b 100644--- a/autogpt_platform/backend/backend/copilot/stream_drift/recorded_turns_test.py+++ b/autogpt_platform/backend/backend/copilot/stream_drift/recorded_turns_test.py@@ -1,8 +1,9 @@"""The recorded turns the frontend drift suite replays still match the pipeline.-Each test drives an engine through the real registry and Redis, then compares-what it stored, served and persisted with the committed fixture. A red here-means the sender changed; re-record and rerun the frontend suite.+Each test drives an engine through the real registry, Redis and Postgres,+then compares what it stored, served and persisted with the committed fixture.+A red here means the sender changed; re-record (see ``recording.py``) and rerun+the frontend suite."""import uuid@@ -14,20 +15,25 @@ from claude_agent_sdk import (ResultMessage,SystemMessage,TextBlock,+ ThinkingBlock,ToolResultBlock,ToolUseBlock,UserMessage,)+from prisma.models import Userfrom backend.copilot.baseline import service as baseline-from backend.copilot.model import ChatSession+from backend.copilot.model import ChatMessage+from backend.copilot.pending_messages import PendingMessagefrom backend.copilot.response_model import StreamToolOutputAvailablefrom backend.copilot.sdk import dummy-from backend.data import redis_client+from backend.copilot.sdk import service as sdk+from backend.data import db, redis_client+from backend.data.user import get_or_create_userfrom backend.util.testing import is_tcp_port_reachable-from .recording import check_fixture, record_turn-from .scripted import baseline_turn, provider_round, sdk_turn, session_with_prompt+from .recording import check_fixture, persisted_session, record_turn+from .scripted import baseline_turn, provider_round, sdk_service_turn, sdk_turnpytestmark = pytest.mark.skipif(not is_tcp_port_reachable(redis_client.HOST, redis_client.PORT),@@ -35,32 +41,34 @@ pytestmark = pytest.mark.skipif()-async def test_dummy_text_turn(monkeypatch: pytest.MonkeyPatch) -> None:- session = session_with_prompt("Count to three")- persisted: list[ChatSession] = []+async def user_id():+ """A user of its own, removed with its sessions after the test."""+ await db.connect()+ user_id = str(uuid.uuid4())+ await get_or_create_user({"sub": user_id, "email": f"{user_id}@drift.invalid"})+ yield user_id+ await User.prisma().delete_many(where={"id": user_id})- async def save(saved: ChatSession) -> ChatSession:- persisted.append(saved.model_copy(deep=True))- return saved- monkeypatch.setattr(dummy, "upsert_chat_session", save)+async def test_dummy_text_turn(user_id: str) -> None:+ session = await persisted_session(user_id, "Count to three")recorded = await record_turn(dummy.stream_chat_completion_dummy(session.session_id, message="Count to three", session=session),- session_id=session.session_id,+ session=session,turn_id=str(uuid.uuid4()),- persisted=lambda: persisted[-1].messages,)check_fixture("dummy-text-turn", recorded)async def test_baseline_tool_turn(- monkeypatch: pytest.MonkeyPatch, baseline_io: list[ChatSession]+ monkeypatch: pytest.MonkeyPatch, baseline_offline: None, user_id: str) -> None:- session = session_with_prompt("What does example.com say?")+ session = await persisted_session(user_id, "What does example.com say?")rounds = [provider_round(["Let me ", "fetch that ", "page."],@@ -81,18 +89,15 @@ async def test_baseline_tool_turn(turn_id = str(uuid.uuid4())recorded = await record_turn(- baseline_turn(session, turn_id),- session_id=session.session_id,- turn_id=turn_id,- persisted=lambda: baseline_io[-1].messages,+ baseline_turn(session, turn_id), session=session, turn_id=turn_id)check_fixture("baseline-tool-turn", recorded)-async def test_sdk_late_tool_result_turn() -> None:+async def test_sdk_late_tool_result_turn(user_id: str) -> None:"""Dev session c68992f9's order: a tool result lands after the next text."""- session = session_with_prompt("Check the task and list the files")+ session = await persisted_session(user_id, "Check the task and list the files")messages = [SystemMessage(subtype="init", data={}),AssistantMessage(@@ -124,10 +129,211 @@ async def test_sdk_late_tool_result_turn() -> None:]recorded = await record_turn(- sdk_turn(session, messages),- session_id=session.session_id,- turn_id=str(uuid.uuid4()),- persisted=lambda: session.messages,+ sdk_turn(session, messages), session=session, turn_id=str(uuid.uuid4()))check_fixture("sdk-late-tool-result", recorded)+++async def test_baseline_drain_turn(+ monkeypatch: pytest.MonkeyPatch, baseline_offline: None, user_id: str+) -> None:+ """Follow-ups drained at turn start and between rounds, with reasoning."""+ session = await persisted_session(user_id, "Summarise example.com")+ rounds = [+ provider_round(+ ["Fetching it."],+ reasoning=["The user wants ", "a summary."],+ tool_call={"id": "call-fetch", "name": "web_fetch", "url": "example.com"},+ ),+ provider_round(["It is a placeholder page."], reasoning=["Short answer."]),+ ]+ monkeypatch.setattr(baseline, "call_provider_stream", AsyncMock(side_effect=rounds))++ async def execute(*, tool_call_id: str, **_: object) -> StreamToolOutputAvailable:+ return StreamToolOutputAvailable(+ toolCallId=tool_call_id, toolName="web_fetch", output="Example Domain"+ )++ monkeypatch.setattr(baseline, "execute_tool", AsyncMock(side_effect=execute))+ monkeypatch.setattr(+ baseline,+ "drain_pending_safe",+ AsyncMock(return_value=[PendingMessage(content="Keep it short.")]),+ )+ monkeypatch.setattr(+ baseline,+ "drain_pending_messages",+ AsyncMock(side_effect=[[PendingMessage(content="In French, please.")], []]),+ )+ turn_id = str(uuid.uuid4())++ recorded = await record_turn(+ baseline_turn(session, turn_id), session=session, turn_id=turn_id+ )++ check_fixture("baseline-drain-turn", recorded)+++async def test_sdk_reasoning_turn(+ monkeypatch: pytest.MonkeyPatch, user_id: str+) -> None:+ """Thinking before each reply, and a follow-up drained after a tool call."""+ session = await persisted_session(user_id, "What is in the repo?")+ follow_up = [PendingMessage(content="Only count markdown files.")]+ monkeypatch.setattr(+ sdk, "drain_pending_for_persist", AsyncMock(side_effect=[follow_up, []])+ )+ messages = [+ SystemMessage(subtype="init", data={}),+ AssistantMessage(+ content=[+ ThinkingBlock(thinking="List the files first.", signature="s"),+ ToolUseBlock(id="bash-1", name="bash_exec", input={"command": "ls"}),+ ],+ model="drift",+ ),+ UserMessage(+ content=[ToolResultBlock(tool_use_id="bash-1", content="a.md b.py")]+ ),+ AssistantMessage(+ content=[+ ThinkingBlock(thinking="One markdown file.", signature="s"),+ TextBlock(text="There is one markdown file: a.md."),+ ],+ model="drift",+ ),+ ResultMessage(+ subtype="success",+ duration_ms=100,+ duration_api_ms=50,+ is_error=False,+ num_turns=2,+ session_id="drift",+ ),+ ]++ recorded = await record_turn(+ sdk_turn(session, messages), session=session, turn_id=str(uuid.uuid4())+ )++ check_fixture("sdk-reasoning-turn", recorded)+++async def test_sdk_auto_continue_turn(user_id: str) -> None:+ """Two follow-ups queued after the last drain continue the same turn."""+ session = await persisted_session(+ user_id,+ "Draft the release note.",+ history=[+ ChatMessage(role="user", content="Hi"),+ ChatMessage(role="assistant", content="Hello! What can I do?"),+ ],+ )+ queued = [+ PendingMessage(content="Mention the new export."),+ PendingMessage(content="And keep it to one line."),+ ]++ turn_id = str(uuid.uuid4())++ recorded = await record_turn(+ sdk_service_turn(+ session,+ turn_id,+ [_reply("Release 1.2 adds sharing."), _reply("Release 1.2 adds export.")],+ queued_after_first=queued,+ ),+ session=session,+ turn_id=turn_id,+ )++ check_fixture("sdk-auto-continue-turn", recorded)+++def _reply(text: str) -> list:+ return [+ SystemMessage(subtype="init", data={}),+ AssistantMessage(content=[TextBlock(text=text)], model="drift"),+ ResultMessage(+ subtype="success",+ result=text,+ duration_ms=100,+ duration_api_ms=50,+ is_error=False,+ num_turns=1,+ session_id="drift",+ ),+ ]+++async def test_baseline_consecutive_tools_turn(+ monkeypatch: pytest.MonkeyPatch, baseline_offline: None, user_id: str+) -> None:+ """A tool call right after a tool result, with no text between them."""+ session = await persisted_session(user_id, "Compare example.com and example.org")+ rounds = [+ provider_round(+ [], tool_call={"id": "call-com", "name": "web_fetch", "url": "example.com"}+ ),+ provider_round(+ [], tool_call={"id": "call-org", "name": "web_fetch", "url": "example.org"}+ ),+ provider_round(["Both are placeholder pages."]),+ ]+ monkeypatch.setattr(baseline, "call_provider_stream", AsyncMock(side_effect=rounds))++ async def execute(*, tool_call_id: str, **_: object) -> StreamToolOutputAvailable:+ return StreamToolOutputAvailable(+ toolCallId=tool_call_id, toolName="web_fetch", output="Example Domain"+ )++ monkeypatch.setattr(baseline, "execute_tool", AsyncMock(side_effect=execute))+ turn_id = str(uuid.uuid4())++ recorded = await record_turn(+ baseline_turn(session, turn_id), session=session, turn_id=turn_id+ )++ check_fixture("baseline-consecutive-tools-turn", recorded)+++async def test_sdk_consecutive_tools_turn(user_id: str) -> None:+ """A tool call right after a tool result, with no text between them."""+ session = await persisted_session(user_id, "Count the files, then the lines")+ messages = [+ SystemMessage(subtype="init", data={}),+ AssistantMessage(+ content=[+ ToolUseBlock(id="bash-1", name="bash_exec", input={"command": "ls"})+ ],+ model="drift",+ ),+ UserMessage(content=[ToolResultBlock(tool_use_id="bash-1", content="a.md")]),+ AssistantMessage(+ content=[+ ToolUseBlock(+ id="bash-2", name="bash_exec", input={"command": "wc a.md"}+ )+ ],+ model="drift",+ ),+ UserMessage(content=[ToolResultBlock(tool_use_id="bash-2", content="3 a.md")]),+ AssistantMessage(+ content=[TextBlock(text="One file, three lines.")], model="drift"+ ),+ ResultMessage(+ subtype="success",+ duration_ms=100,+ duration_api_ms=50,+ is_error=False,+ num_turns=3,+ session_id="drift",+ ),+ ]++ recorded = await record_turn(+ sdk_turn(session, messages), session=session, turn_id=str(uuid.uuid4())+ )++ check_fixture("sdk-consecutive-tools-turn", recorded)diff --git a/autogpt_platform/backend/backend/copilot/stream_drift/recording.py b/autogpt_platform/backend/backend/copilot/stream_drift/recording.pyindex ccbe9ece67..e25a4ae8db 100644--- a/autogpt_platform/backend/backend/copilot/stream_drift/recording.py+++ b/autogpt_platform/backend/backend/copilot/stream_drift/recording.py@@ -2,19 +2,23 @@A recorded turn is three files under ``test/fixtures/copilot_stream/<name>/``:-- ``entries.jsonl``: the turn's Redis stream in XRANGE order, ``{id, data}``- per line with ``data`` parsed from the stored JSON;-- ``frames.jsonl``: the SSE frame the resume route writes for each entry;-- ``rows.json``: the rows the session GET returns once the turn persisted.+- ``entries.jsonl``: the turn's whole Redis stream in XRANGE order, before+ completion trims it, ``{id, data}`` per line with ``data`` parsed from the+ stored JSON;+- ``frames.jsonl``: the SSE frame the stream routes write for each entry;+- ``rows.json``: the rows the session GET reads back from Postgres once the+ turn persisted.Backend tests check the pipeline still records these files; the frontend drift-suite replays them. Set ``RECORD_COPILOT_STREAM_FIXTURES=1`` to rewrite them.+suite replays them. To rewrite them, run ``recorded_turns_test.py`` with+``RECORD_COPILOT_STREAM_FIXTURES=1`` and ``DATABASE_URL``/``DIRECT_URL`` on a+throwaway Postgres migrated from the branch (``prisma migrate deploy``)."""import jsonimport osimport re-from collections.abc import AsyncGenerator, Callable, Sequence+from collections.abc import AsyncGenerator, Awaitable, Callable, Sequencefrom pathlib import Pathfrom typing import Anyfrom unittest.mock import AsyncMock, patch@@ -23,12 +27,17 @@ import orjsonfrom fastapi.encoders import jsonable_encoderfrom pydantic import BaseModel+from backend.api.features.chat.routes import _strip_injected_contextfrom backend.copilot import stream_registry-from backend.copilot.model import ChatMessage+from backend.copilot.db import get_chat_messages_paginated+from backend.copilot.model import ChatMessage, ChatSession, upsert_chat_sessionfrom backend.copilot.response_model import StreamBaseResponse, StreamError, StreamStatus+from backend.copilot.stream_checkpoint import canonical_digest, canonical_rowsfrom backend.copilot.stream_heartbeat import wrap_stream_with_heartbeatfrom backend.data.redis_client import get_redis_async+from .fold import fold_rows+FIXTURE_ROOT = (Path(__file__).resolve().parents[3] / "test" / "fixtures" / "copilot_stream")@@ -49,11 +58,12 @@ class RecordedTurn(BaseModel):async def record_turn(engine: AsyncGenerator[StreamBaseResponse, None],*,- session_id: str,+ session: ChatSession,turn_id: str,- persisted: Callable[[], Sequence[ChatMessage]],) -> RecordedTurn:- """Run ``engine`` through the route's and the executor's publishing path."""+ """Run ``engine`` through the route's and the executor's publishing path,+ then read the turn's rows back from the database."""+ session_id = session.session_idawait stream_registry.create_session(session_id, None, "", "", turn_id=turn_id)for status in ("Message received…", "Setting up your environment…"):await stream_registry.publish_chunk(@@ -74,64 +84,92 @@ async def record_turn(finally:await published.aclose()+ entries = await read_turn_entries(turn_id)with patch.object(stream_registry.chat_db(), "set_turn_duration", new=AsyncMock(), create=True):await stream_registry.mark_session_completed(session_id, error_message=error, turn_id=turn_id)- entries = await read_turn_entries(turn_id)+ entries += await read_turn_entries(turn_id, after=entries[-1]["id"])redis = await get_redis_async()await redis.delete(stream_registry._get_turn_stream_key(turn_id))+ await redis.delete(stream_registry._get_turn_meta_key(turn_id))await redis.delete(stream_registry.get_session_meta_key(session_id))- return canonical(- RecordedTurn(- entries=entries,- frames=frames_for(entries),- rows=[jsonable_encoder(message.model_dump()) for message in persisted()],- ),- session_id=session_id,- turn_id=turn_id,+ entries, rows = canonical(+ entries, await persisted_rows(session), session_id=session_id, turn_id=turn_id)+ return RecordedTurn(entries=entries, frames=frames_for(entries), rows=rows)+++async def persisted_session(+ user_id: str, prompt: str, *, history: Sequence[ChatMessage] = ()+) -> ChatSession:+ """A session whose prompt is already persisted, as the POST route leaves it."""+ session = ChatSession.new(user_id, dry_run=False)+ session.messages.extend([*history, ChatMessage(role="user", content=prompt)])+ await upsert_chat_session(session)+ return session+++async def persisted_rows(session: ChatSession) -> list[dict[str, Any]]:+ """The session's rows as ``GET /sessions/{id}`` returns them."""+ page = await get_chat_messages_paginated(+ session.session_id, limit=200, user_id=session.user_id+ )+ assert page is not None, "the session was never persisted"+ return [+ jsonable_encoder(_strip_injected_context(message.model_dump()))+ for message in page.messages+ ]-async def read_turn_entries(turn_id: str) -> list[dict[str, Any]]:+async def read_turn_entries(turn_id: str, after: str = "0-0") -> list[dict[str, Any]]:redis = await get_redis_async()key = stream_registry._get_turn_stream_key(turn_id)- [(_, entries)] = stream_registry._stream_entries([(key, await redis.xrange(key))])+ raw = await redis.xrange(key, min=f"({after}" if after != "0-0" else "-")+ [(_, entries)] = stream_registry._stream_entries([(key, raw)])return [{"id": entry_id, "data": orjson.loads(fields["data"])}for entry_id, fields in entries]-def frames_for(entries: Sequence[dict[str, Any]]) -> list[dict[str, Any]]:- """The frames the resume route writes, one per entry it can rebuild."""+def frames_for(+ entries: Sequence[dict[str, Any]], turn_id: str = CANONICAL_TURN_ID+) -> list[dict[str, Any]]:+ """The frames the stream routes write, one per entry they can rebuild."""frames = []for entry in entries:chunk = stream_registry._reconstruct_chunk(entry["data"])if chunk is not None:- frames.append({"id": entry["id"], "sse": chunk.to_sse()})+ sse = stream_registry.sse_frame((f"{turn_id}:{entry['id']}", chunk))+ frames.append({"id": entry["id"], "sse": sse})return frames-def canonical(turn: RecordedTurn, *, session_id: str, turn_id: str) -> RecordedTurn:+def canonical(+ entries: list[dict[str, Any]],+ rows: list[dict[str, Any]],+ *,+ session_id: str,+ turn_id: str,+) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:"""Replace every value that differs between two recordings of one turn."""- entry_ids = {entry["id"]: f"{i + 1}-0" for i, entry in enumerate(turn.entries)}- rows = [+ entry_ids = {entry["id"]: f"{i + 1}-0" for i, entry in enumerate(entries)}+ numbered = [{**row,"id": f"row-{sequence}","sequence": sequence,"created_at": f"2026-09-30T00:00:{sequence:02d}Z",}- for sequence, row in enumerate(turn.rows)+ for sequence, row in enumerate(rows)]text = json.dumps({- "entries": [{**e, "id": entry_ids[e["id"]]} for e in turn.entries],- "frames": [{**f, "id": entry_ids[f["id"]]} for f in turn.frames],- "rows": rows,+ "entries": [{**e, "id": entry_ids[e["id"]]} for e in entries],+ "rows": numbered,})text = text.replace(session_id, CANONICAL_SESSION_ID)@@ -143,7 +181,52 @@ def canonical(turn: RecordedTurn, *, session_id: str, turn_id: str) -> RecordedT),text,)- return RecordedTurn.model_validate_json(text)+ parsed = json.loads(text)+ return parsed["entries"], parsed["rows"]+++def saving_into(+ saves: list[ChatSession],+) -> Callable[[ChatSession], Awaitable[ChatSession]]:+ """A stand-in for ``upsert_chat_session`` that numbers new rows the way+ the DB does, then keeps a copy of what it saved."""++ async def save(session: ChatSession) -> ChatSession:+ numbered = [m.sequence for m in session.messages if m.sequence is not None]+ next_sequence = max(numbered, default=-1) + 1+ for message in session.messages:+ if message.sequence is None:+ message.sequence = next_sequence+ next_sequence += 1+ saves.append(session.model_copy(deep=True))+ return session++ return save+++def assert_fold_matches_rows(turn: RecordedTurn) -> None:+ """At every checkpoint the fold of the entries before it is the persisted+ turn rows it names, and at the end the fold is every persisted turn row."""+ chunks = [entry["data"] for entry in turn.entries]+ checkpoints = [+ i for i, chunk in enumerate(chunks) if chunk["type"] == "data-checkpoint"+ ]+ assert checkpoints, "the turn published no checkpoint"+ starts = {chunks[i]["sequence"] for i in checkpoints}+ assert len(starts) == 1, f"checkpoints name different first rows: {starts}"+ [start] = starts+ for i in checkpoints:+ folded = fold_rows(chunks[:i])+ assert (len(folded), canonical_digest(folded)) == (+ chunks[i]["rows"],+ chunks[i]["digest"],+ ), f"checkpoint {turn.entries[i]['id']} does not match the fold {folded}"+ persisted = canonical_rows([ChatMessage.model_validate(r) for r in turn.rows])+ assert fold_rows(chunks) == persisted[start:]+++def fixture_names() -> list[str]:+ return sorted(path.name for path in FIXTURE_ROOT.iterdir() if path.is_dir())def load_fixture(name: str) -> RecordedTurn:@@ -156,7 +239,9 @@ def load_fixture(name: str) -> RecordedTurn:def check_fixture(name: str, recorded: RecordedTurn) -> None:- """Fail when the pipeline no longer records the committed fixture."""+ """Fail when the recorded stream does not fold to its rows, or the+ pipeline no longer records the committed fixture."""+ assert_fold_matches_rows(recorded)if os.environ.get(RECORD_ENV):_write_fixture(name, recorded)returndiff --git a/autogpt_platform/backend/backend/copilot/stream_drift/scripted.py b/autogpt_platform/backend/backend/copilot/stream_drift/scripted.pyindex 97cf520df1..9a3dddc9e6 100644--- a/autogpt_platform/backend/backend/copilot/stream_drift/scripted.py+++ b/autogpt_platform/backend/backend/copilot/stream_drift/scripted.py@@ -1,18 +1,24 @@"""Copilot engines driven by a script instead of a model, for the drift suite."""+import contextlib+import tempfile+import timeimport uuidfrom collections.abc import AsyncGeneratorfrom typing import Any-from unittest.mock import AsyncMock, MagicMock+from unittest.mock import AsyncMock, MagicMock, patchfrom claude_agent_sdk import Messagefrom openai.types.chat import ChatCompletionChunkfrom backend.copilot.baseline import service as baselinefrom backend.copilot.model import ChatMessage, ChatSession+from backend.copilot.pending_messages import PendingMessagefrom backend.copilot.response_model import StreamBaseResponse, StreamStart+from backend.copilot.sdk import service as sdk+from backend.copilot.sdk.compaction import CompactionTrackerfrom backend.copilot.sdk.response_adapter import SDKResponseAdapter-from backend.copilot.sdk.service import _dispatch_response, _StreamAccumulator+from backend.copilot.stream_checkpoint import turn_checkpointfrom backend.copilot.tree import root_envelope@@ -29,7 +35,7 @@ async def baseline_turn("""The baseline engine; its provider and I/O come from the ``baseline_io`` fixture."""async for event in baseline.stream_chat_completion_baseline(session.session_id,- user_id="drift-user",+ user_id=session.user_id,session=session,is_user_message=False,envelope=root_envelope(turn_id, session_id=session.session_id),@@ -38,10 +44,15 @@ async def baseline_turn(def provider_round(- deltas: list[str], *, tool_call: dict[str, str] | None = None+ deltas: list[str],+ *,+ tool_call: dict[str, str] | None = None,+ reasoning: list[str] | None = None,) -> MagicMock:- """One scripted OpenAI-compatible response: text deltas, then a tool call."""- chunks = [_chunk({"content": delta}) for delta in deltas]+ """One scripted OpenAI-compatible response: reasoning deltas, text+ deltas, then a tool call."""+ chunks = [_chunk({"reasoning": delta}) for delta in reasoning or []]+ chunks += [_chunk({"content": delta}) for delta in deltas]if tool_call:chunks.append(_chunk(@@ -72,22 +83,142 @@ def provider_round(async def sdk_turn(session: ChatSession, messages: list[Message]) -> AsyncGenerator[StreamBaseResponse, None]:- """The SDK engine's own adapter and row builder over a scripted CLI."""+ """The SDK engine's consume loop, flushes included, over a scripted CLI;+ then the turn-end persist and checkpoint of its ``finally``.++ Persistence goes through ``sdk.upsert_chat_session``; patch it to record.+ """message_id = str(uuid.uuid4())- adapter = SDKResponseAdapter(message_id=message_id, session_id=session.session_id)- acc = _StreamAccumulator(+ turn_start = len(session.messages)+ ctx = sdk._StreamContext(+ session=session,+ session_id=session.session_id,+ log_prefix="[drift]",+ sdk_cwd="/tmp/drift",+ current_message="",+ file_ids=None,+ message_id=message_id,+ attachments=MagicMock(image_blocks=[]),+ compaction=CompactionTracker(),+ lock=MagicMock(refresh=AsyncMock()),+ turn_start=turn_start,+ )+ state = sdk._RetryState(+ options=MagicMock(),+ query_message="",+ compaction_stats=None,+ use_resume=False,+ resume_file=None,+ transcript_msg_count=0,+ adapter=SDKResponseAdapter(+ message_id=message_id, session_id=session.session_id+ ),+ transcript_builder=MagicMock(),+ usage=sdk._TokenUsage(),+ )+ acc = sdk._StreamAccumulator(assistant_response=ChatMessage(role="assistant", content=""),accumulated_tool_calls=[],)- ctx = MagicMock(session=session, log_prefix="[drift]")+ now = time.monotonic()+ loop_state = sdk._SDKLoopState(last_real_msg_time=now, last_flush_time=now)++ async def scripted_cli(*_: Any, **__: Any) -> AsyncGenerator[Message, None]:+ for message in messages:+ yield message+yield StreamStart(messageId=message_id, sessionId=session.session_id)- for message in messages:- for response in adapter.convert_message(message):- dispatched = _dispatch_response(- response, acc, ctx, MagicMock(), False, "[drift]"- )- if dispatched is not None:- yield dispatched+ with patch.object(sdk, "_iter_sdk_messages", scripted_cli):+ async for event in sdk._consume_sdk_until_done(+ MagicMock(), ctx, state, acc, loop_state+ ):+ yield event+ await sdk.upsert_chat_session(session)+ checkpoint = turn_checkpoint(session.messages, turn_start)+ if checkpoint is not None:+ yield checkpoint+++async def sdk_service_turn(+ session: ChatSession,+ turn_id: str,+ queries: list[list[Message]],+ *,+ queued_after_first: list[PendingMessage],+) -> AsyncGenerator[StreamBaseResponse, None]:+ """The whole SDK engine over a scripted CLI, one list of messages per+ query, with ``queued_after_first`` arriving while the first one runs:+ its turn-end persist and auto-continue included. Only what reaches+ beyond the process (CLI, sandbox, RPC services, billing) is stubbed."""+ scripted = iter(queries)++ def cli(*_: Any, **__: Any) -> AsyncMock:+ messages = next(scripted)++ async def receive() -> AsyncGenerator[Message, None]:+ for message in messages:+ yield message++ client = MagicMock(receive_response=receive, query=AsyncMock())+ connection = AsyncMock()+ connection.__aenter__.return_value = client+ return connection++ def lock(*_: Any, owner_id: str = "", **__: Any) -> MagicMock:+ return MagicMock(+ try_acquire=AsyncMock(return_value=owner_id),+ refresh=AsyncMock(),+ release=AsyncMock(),+ )++ stubs: dict[str, Any] = {+ "ClaudeSDKClient": MagicMock(side_effect=cli),+ "AsyncClusterLock": MagicMock(side_effect=lock),+ "_make_sdk_cwd": MagicMock(return_value=tempfile.mkdtemp()),+ "propagate_attributes": MagicMock(),+ "_build_system_prompt": AsyncMock(return_value=("System prompt", None)),+ "download_transcript": AsyncMock(return_value=None),+ "upload_transcript": AsyncMock(),+ "create_copilot_mcp_server": MagicMock(),+ "create_security_hooks": MagicMock(),+ "get_copilot_tool_names": MagicMock(return_value=[]),+ "get_sdk_disallowed_tools": MagicMock(return_value=[]),+ "build_sdk_env": MagicMock(return_value={}),+ "_resolve_sdk_model": MagicMock(return_value=None),+ "set_execution_context": MagicMock(),+ "get_user_tier": AsyncMock(return_value=None),+ "_resolve_dynamic_max_budget_usd": AsyncMock(return_value=100.0),+ "drain_pending_safe": AsyncMock(+ side_effect=[[], queued_after_first] + [[]] * len(queries)+ ),+ "resolve_answered": AsyncMock(return_value=[]),+ "build_session_context": AsyncMock(return_value=""),+ "build_skills_context": AsyncMock(return_value=""),+ "_maybe_prepend_skills_update": AsyncMock(side_effect=lambda *a: a[-1]),+ "build_turn_budget_block": AsyncMock(return_value=""),+ "persist_and_record_usage": AsyncMock(),+ "clear_pending_question": AsyncMock(),+ "config": sdk.config.model_copy(+ update={+ "use_claude_code_subscription": False,+ "use_e2b_sandbox": False,+ "claude_agent_fallback_model": None,+ "claude_agent_max_transient_retries": 1,+ }+ ),+ }+ with contextlib.ExitStack() as stack:+ for name, value in stubs.items():+ stack.enter_context(patch.object(sdk, name, value))+ async for event in sdk.stream_chat_completion_sdk(+ session_id=session.session_id,+ message=session.messages[-1].content,+ is_user_message=True,+ user_id=session.user_id,+ session=session,+ envelope=root_envelope(turn_id, session_id=session.session_id),+ ):+ yield eventdef _chunk(diff --git a/autogpt_platform/backend/backend/copilot/stream_registry.py b/autogpt_platform/backend/backend/copilot/stream_registry.pyindex 0221447f42..0f533b9f9d 100644--- a/autogpt_platform/backend/backend/copilot/stream_registry.py+++ b/autogpt_platform/backend/backend/copilot/stream_registry.py@@ -23,7 +23,8 @@ from datetime import datetime, timezonefrom typing import Any, Literalimport orjson-from redis.exceptions import RedisError+from pydantic import BaseModel, ValidationError+from redis.exceptions import RedisError, ResponseErrorfrom backend.api.model import CopilotCompletionPayloadfrom backend.copilot.active_turns import release_turn_slot@@ -43,6 +44,7 @@ from .executor.utils import COPILOT_CONSUMER_TIMEOUT_SECONDS, get_session_lock_kfrom .response_model import (ResponseType,StreamBaseResponse,+ StreamCheckpoint,StreamCompactionProgress,StreamError,StreamFinish,@@ -75,6 +77,9 @@ config = ChatConfig()_notification_bus = AsyncRedisNotificationEventBus()StreamEntries = list[tuple[str, list[tuple[str, dict[str, str]]]]]+StreamEntry = tuple[str | None, StreamBaseResponse]+"""A chunk and its SSE id ``<turn_id>:<entry_id>``; None for one the registry+made up (a heartbeat, or the end of a stream that stopped without a finish)."""def _as_text(value: bytes | str | None) -> str:@@ -120,6 +125,26 @@ _listener_sessions: dict[int, tuple[str, asyncio.Task]] = {}QUEUE_PUT_TIMEOUT = 5.0+class TurnCheckpoint(BaseModel):+ """Where a turn's last ``data-checkpoint`` sits in its stream."""++ entry_id: str+ rows: int+ sequence: int+++class TurnStreamGone(Exception):+ """The turn's stream expired, or the turn is not this user's session's."""+++class TurnStreamTrimmed(Exception):+ """Entries after the cursor were trimmed away; resume from ``checkpoint``."""++ def __init__(self, checkpoint: TurnCheckpoint | None):+ super().__init__("entries after the cursor were trimmed")+ self.checkpoint = checkpoint++@dataclassclass ActiveSession:"""Represents an active streaming session (metadata only, no in-memory queues)."""@@ -133,6 +158,7 @@ class ActiveSession:status: Literal["running", "completed", "failed"] = "running"created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))asyncio_task: asyncio.Task | None = None+ checkpoint: TurnCheckpoint | None = Nonedef _get_session_meta_key(session_id: str) -> str:@@ -156,6 +182,15 @@ def _get_turn_stream_key(turn_id: str) -> str:return f"{config.turn_stream_prefix}{turn_id}"+def _get_turn_meta_key(turn_id: str) -> str:+ """The turn's own hash: its ``session_id`` and last ``checkpoint``.++ Per turn rather than in the session meta, which the next turn overwrites+ while this turn's stream is still readable.+ """+ return f"{config.turn_stream_prefix}{turn_id}:meta"++def _parse_session_meta(meta: dict[Any, Any], session_id: str = "") -> ActiveSession:"""Parse a raw Redis hash into a typed ActiveSession.@@ -262,6 +297,8 @@ async def create_session()await redis.expire(meta_key, config.stream_ttl)+ if turn_id:+ await _write_turn_meta(redis, turn_id, "session_id", session_id)total_time = (time.perf_counter() - start_time) * 1000logger.info(@@ -339,15 +376,19 @@ async def publish_chunk(redis = await get_redis_async()stream_key = _get_turn_stream_key(turn_id)- # Write to Redis Stream for persistence and real-time delivery+ # Never trimmed while the turn runs: a resume must find whole blocks.+ # ``mark_session_completed`` trims it to the last checkpoint.xadd_start = time.perf_counter()- raw_id = await redis.xadd(- stream_key,- {"data": chunk_json},- maxlen=config.stream_max_length,- )+ raw_id = await redis.xadd(stream_key, {"data": chunk_json})xadd_time = (time.perf_counter() - xadd_start) * 1000message_id = raw_id if isinstance(raw_id, str) else raw_id.decode()+ if isinstance(chunk, StreamCheckpoint):+ record = TurnCheckpoint(+ entry_id=message_id, rows=chunk.rows, sequence=chunk.sequence+ )+ await _write_turn_meta(+ redis, turn_id, "checkpoint", record.model_dump_json()+ )# Set TTL on stream to match session metadata TTLawait redis.expire(stream_key, config.stream_ttl)@@ -367,6 +408,7 @@ async def publish_chunk(meta_key = _get_session_meta_key(session_id)await redis.expire(meta_key, config.stream_ttl)await redis.expire(stream_key, config.stream_ttl)+ await redis.expire(_get_turn_meta_key(turn_id), config.stream_ttl)_meta_ttl_refresh_at[session_id] = nowtotal_time = (time.perf_counter() - start_time) * 1000@@ -405,6 +447,12 @@ async def publish_chunk(return message_id+async def _write_turn_meta(redis: Any, turn_id: str, field: str, value: str) -> None:+ key = _get_turn_meta_key(turn_id)+ await redis.hset(key, field, value)+ await redis.expire(key, config.stream_ttl)++async def stream_and_publish(session_id: str,turn_id: str,@@ -467,186 +515,206 @@ async def subscribe_to_session(session_id: str,user_id: str | None,last_message_id: str = "0-0",-) -> asyncio.Queue[StreamBaseResponse] | None:- """Subscribe to a session's stream with replay of missed messages.-- This is fully stateless - uses Redis Stream for replay and pub/sub for live updates.-- Args:- session_id: Session ID to subscribe to- user_id: User ID for ownership validation- last_message_id: Last Redis Stream message ID received ("0-0" for full replay)+) -> asyncio.Queue[StreamEntry] | None:+ """Subscribe to the session's current turn, replaying every stored entry+ after ``last_message_id`` and then following the live ones.- Returns:- An asyncio Queue that will receive stream chunks, or None if session not found- or user doesn't have access+ Returns None if the session is not found or the user does not own it. A+ turn that is no longer running ends with a made-up ``StreamFinish`` unless+ its stored tail holds the real one."""start_time = time.perf_counter()-- # Build log metadatalog_meta = {"component": "StreamRegistry", "session_id": session_id}if user_id:log_meta["user_id"] = user_id- logger.info(- f"[TIMING] subscribe_to_session STARTED, session={session_id}, user={user_id}, last_msg={last_message_id}",- extra={"json_fields": {**log_meta, "last_message_id": last_message_id}},- )-- redis_start = time.perf_counter()redis = await get_redis_async()- meta_key = _get_session_meta_key(session_id)- meta: dict[Any, Any] = await redis.hgetall(meta_key) # type: ignore[misc]- hgetall_time = (time.perf_counter() - redis_start) * 1000- logger.info(- f"[TIMING] Redis hgetall took {hgetall_time:.1f}ms",- extra={"json_fields": {**log_meta, "duration_ms": hgetall_time}},- )-- # RACE CONDITION FIX: If session not found, retry with backoff.- # Duplicate requests skip create_session and subscribe immediately; the- # original request's create_session (a Redis hset) may not have completed- # yet. 3 × 100ms gives a 300ms window which covers DB-write latency on the- # original request before the hset even starts.- if not meta:- _max_retries = 3- _retry_delay = 0.1 # 100ms per attempt- for attempt in range(_max_retries):- logger.warning(- f"[TIMING] Session not found (attempt {attempt + 1}/{_max_retries}), "- f"retrying after {int(_retry_delay * 1000)}ms",- extra={"json_fields": {**log_meta, "attempt": attempt + 1}},- )- await asyncio.sleep(_retry_delay)- meta = await redis.hgetall(meta_key) # type: ignore[misc]- if meta:- logger.info(- f"[TIMING] Session found after {attempt + 1} retries",- extra={"json_fields": {**log_meta, "attempts": attempt + 1}},- )- break- else:- elapsed = (time.perf_counter() - start_time) * 1000- logger.info(- f"[TIMING] Session still not found in Redis after {_max_retries} retries "- f"({elapsed:.1f}ms total)",- extra={- "json_fields": {- **log_meta,- "elapsed_ms": elapsed,- "reason": "session_not_found_after_retry",- }- },- )- return None-- # Note: Redis client uses decode_responses=True, so keys are strings- session_status = meta.get("status", "")- session_user_id = meta.get("user_id", "") or None- log_meta["session_id"] = meta.get("session_id", "")-- # Validate ownership - if session has an owner, requester must match- if session_user_id:- if user_id != session_user_id:- logger.warning(- f"[TIMING] Access denied: user {user_id} tried to access session owned by {session_user_id}",- extra={- "json_fields": {- **log_meta,- "session_owner": session_user_id,- "reason": "access_denied",- }- },- )- return None+ meta = await _read_meta_with_retry(redis, session_id, log_meta)+ if not meta or not _owned_by(meta, user_id, log_meta):+ return Nonesession = _parse_session_meta(meta, session_id)- subscriber_queue: asyncio.Queue[StreamBaseResponse] = asyncio.Queue()- stream_key = _get_turn_stream_key(session.turn_id)+ queue: asyncio.Queue[StreamEntry] = asyncio.Queue()+ last_id, finished = await _replay(redis, session.turn_id, last_message_id, queue)+ if session.status == "running":+ _start_listener(session_id, queue, last_id, log_meta, session.turn_id)+ elif not finished:+ queue.put_nowait((None, StreamFinish()))- # Replay batch capped by ``stream_replay_count``.- xread_start = time.perf_counter()- messages = await redis.xread(- {stream_key: last_message_id}, block=None, count=config.stream_replay_count- )- xread_time = (time.perf_counter() - xread_start) * 1000+ total_time = (time.perf_counter() - start_time) * 1000logger.info(- f"[TIMING] Redis xread (replay) took {xread_time:.1f}ms, status={session_status}",- extra={- "json_fields": {- **log_meta,- "duration_ms": xread_time,- "session_status": session_status,- }- },+ f"[TIMING] subscribe_to_session COMPLETED in {total_time:.1f}ms; "+ f"session={session_id}, status={session.status}, "+ f"n_messages_replayed={queue.qsize()}, last_id={last_id}",+ extra={"json_fields": {**log_meta, "total_time_ms": total_time}},)+ return queue- replayed_count = 0- replay_last_id = last_message_id- for _stream_name, stream_messages in _stream_entries(messages):- for msg_id, msg_data in stream_messages:- replay_last_id = msg_id- # Note: Redis client uses decode_responses=True, so keys are strings- if "data" in msg_data:- try:- chunk_data = orjson.loads(msg_data["data"])- chunk = _reconstruct_chunk(chunk_data)- if chunk:- await subscriber_queue.put(chunk)- replayed_count += 1- except Exception as e:- logger.warning(f"Failed to replay message: {e}")- logger.info(- f"[TIMING] Replayed {replayed_count} messages, last_id={replay_last_id}",- extra={- "json_fields": {- **log_meta,- "n_messages_replayed": replayed_count,- "replay_last_id": replay_last_id,- }- },- )+async def subscribe_to_turn(+ session_id: str,+ user_id: str | None,+ turn_id: str,+ after: str,+) -> asyncio.Queue[StreamEntry]:+ """Every stored entry of ``turn_id`` after the cursor ``after``, then its+ live ones while it runs.++ Nothing is made up: when the stream stops without the turn's real finish+ the queue ends with ``(None, StreamFinish())``, an end marker only.+ Raises ``TurnStreamGone`` or ``TurnStreamTrimmed``.+ """+ log_meta = {"component": "StreamRegistry", "session_id": session_id}+ redis: Any = await get_redis_async()+ meta = await redis.hgetall(_get_session_meta_key(session_id))+ if not meta or not _owned_by(meta, user_id, log_meta):+ raise TurnStreamGone()+ active = _parse_session_meta(meta, session_id)+ if active.turn_id != turn_id:+ turn_meta = await redis.hgetall(_get_turn_meta_key(turn_id))+ if turn_meta.get("session_id") != session_id:+ raise TurnStreamGone()+ running = active.turn_id == turn_id and active.status == "running"- # Step 2: If session is still running, start stream listener for live updates- if session_status == "running":- logger.info(- "[TIMING] Session still running, starting _stream_listener",- extra={"json_fields": {**log_meta, "session_status": session_status}},- )- listener_task = asyncio.create_task(- _stream_listener(- session_id, subscriber_queue, replay_last_id, log_meta, session.turn_id- )+ try:+ info = await redis.xinfo_stream(_get_turn_stream_key(turn_id))+ except ResponseError:+ if not running:+ raise TurnStreamGone()+ info = None+ # Only whole prefixes are ever trimmed, so the gap is everything before+ # the first entry; that entry is the checkpoint the trim kept.+ if info and info["entries-added"] > info["length"] and info["first-entry"]:+ first_id, first_fields = info["first-entry"]+ if _stream_id(after) < _stream_id(first_id):+ raise TurnStreamTrimmed(_as_checkpoint(first_id, first_fields))++ queue: asyncio.Queue[StreamEntry] = asyncio.Queue()+ last_id, finished = await _replay(redis, turn_id, after, queue)+ if not finished:+ # Also for a turn already marked done: its finish lands just after.+ _start_listener(session_id, queue, last_id, log_meta, turn_id)+ return queue+++def sse_frame(entry: StreamEntry) -> str:+ """The SSE frame for a queued entry, with its id on the data line.++ A comment frame (heartbeat, usage) gets no id: SSE parsers drop the id of+ a frame that carries no data.+ """+ frame_id, chunk = entry+ sse = chunk.to_sse()+ if frame_id is None or not sse.startswith("data:"):+ return sse+ return f"id: {frame_id}\n{sse}"+++async def _read_meta_with_retry(+ redis: Any, session_id: str, log_meta: dict[str, Any]+) -> dict[Any, Any]:+ # A duplicate request can subscribe before the original request's+ # create_session hset lands; 3 × 100 ms covers that window.+ meta_key = _get_session_meta_key(session_id)+ meta: dict[Any, Any] = await redis.hgetall(meta_key)+ for attempt in range(3):+ if meta:+ return meta+ logger.warning(+ f"[TIMING] Session not found (attempt {attempt + 1}/3), retrying after 100ms",+ extra={"json_fields": {**log_meta, "attempt": attempt + 1}},)- # Track listener task for cleanup on unsubscribe- _listener_sessions[id(subscriber_queue)] = (session_id, listener_task)- else:- # Session is completed/failed - add finish marker+ await asyncio.sleep(0.1)+ meta = await redis.hgetall(meta_key)+ if not meta:logger.info(- f"[TIMING] Session already {session_status}, adding StreamFinish",- extra={"json_fields": {**log_meta, "session_status": session_status}},+ "[TIMING] Session still not found in Redis after 3 retries",+ extra={+ "json_fields": {**log_meta, "reason": "session_not_found_after_retry"}+ },)- await subscriber_queue.put(StreamFinish())+ return meta- total_time = (time.perf_counter() - start_time) * 1000- logger.info(- f"[TIMING] subscribe_to_session COMPLETED in {total_time:.1f}ms; session={session_id}, "- f"n_messages_replayed={replayed_count}",- extra={- "json_fields": {- **log_meta,- "total_time_ms": total_time,- "n_messages_replayed": replayed_count,- }- },++def _owned_by(+ meta: dict[Any, Any], user_id: str | None, log_meta: dict[str, Any]+) -> bool:+ owner = meta.get("user_id", "") or None+ if owner and owner != user_id:+ logger.warning(+ f"[TIMING] Access denied: user {user_id} tried to access session owned by {owner}",+ extra={"json_fields": {**log_meta, "reason": "access_denied"}},+ )+ return False+ return True+++async def _replay(+ redis: Any, turn_id: str, after: str, queue: asyncio.Queue[StreamEntry]+) -> tuple[str, bool]:+ """Queue every stored entry after ``after``, in batches of+ ``stream_replay_count``; returns the last id and whether the turn's+ finish was among them."""+ stream_key = _get_turn_stream_key(turn_id)+ last_id, finished = after, False+ while True:+ batch = [+ entry+ for _, entries in _stream_entries(+ await redis.xread(+ {stream_key: last_id}, count=config.stream_replay_count+ )+ )+ for entry in entries+ ]+ for entry_id, fields in batch:+ last_id = entry_id+ chunk = _chunk_from_fields(fields)+ if chunk is not None:+ queue.put_nowait((f"{turn_id}:{entry_id}", chunk))+ finished = finished or isinstance(chunk, StreamFinish)+ if len(batch) < config.stream_replay_count:+ return last_id, finished+++def _start_listener(+ session_id: str,+ queue: asyncio.Queue[StreamEntry],+ last_id: str,+ log_meta: dict[str, Any],+ turn_id: str,+) -> None:+ listener_task = asyncio.create_task(+ _stream_listener(session_id, queue, last_id, log_meta, turn_id))- return subscriber_queue+ _listener_sessions[id(queue)] = (session_id, listener_task)+++def _chunk_from_fields(fields: dict[str, str]) -> StreamBaseResponse | None:+ if "data" not in fields:+ return None+ try:+ return _reconstruct_chunk(orjson.loads(fields["data"]))+ except orjson.JSONDecodeError as e:+ logger.warning(f"Failed to decode stream entry: {e}")+ return None+++def _as_checkpoint(entry_id: str, fields: dict[str, str]) -> TurnCheckpoint | None:+ chunk = _chunk_from_fields(fields)+ if not isinstance(chunk, StreamCheckpoint):+ return None+ return TurnCheckpoint(entry_id=entry_id, rows=chunk.rows, sequence=chunk.sequence)+++def _stream_id(entry_id: str) -> tuple[int, int]:+ ms, _, seq = entry_id.partition("-")+ return int(ms), int(seq or 0)async def _stream_listener(session_id: str,- subscriber_queue: asyncio.Queue[StreamBaseResponse],+ subscriber_queue: asyncio.Queue[StreamEntry],last_replayed_id: str,log_meta: dict | None = None,turn_id: str = "",@@ -682,7 +750,7 @@ async def _stream_listener(xread_count = 0try:- redis = await get_redis_async()+ redis: Any = await get_redis_async()stream_key = _get_turn_stream_key(turn_id)current_id = last_replayed_id@@ -725,14 +793,16 @@ async def _stream_listener()if not entries:- # Timeout - check if session is still running+ # Timeout - stop once the meta is gone (TTL), not running, or+ # names a later turn.meta_key = _get_session_meta_key(session_id)- status = await redis.hget(meta_key, "status") # type: ignore[misc]- # Stop if session metadata is gone (TTL expired) or status is not "running"- if status != "running":+ status, meta_turn_id = await redis.hmget(+ meta_key, ["status", "turn_id"]+ )+ if status != "running" or (meta_turn_id and meta_turn_id != turn_id):try:await asyncio.wait_for(- subscriber_queue.put(StreamFinish()),+ subscriber_queue.put((None, StreamFinish())),timeout=QUEUE_PUT_TIMEOUT,)except asyncio.TimeoutError:@@ -744,7 +814,7 @@ async def _stream_listener(# This prevents frontend timeout (12s) during long-running operationstry:await asyncio.wait_for(- subscriber_queue.put(StreamHeartbeat()),+ subscriber_queue.put((None, StreamHeartbeat())),timeout=QUEUE_PUT_TIMEOUT,)except asyncio.TimeoutError:@@ -757,16 +827,14 @@ async def _stream_listener(for msg_id, msg_data in stream_messages:current_id = msg_id- if "data" not in msg_data:- continue-try:- chunk_data = orjson.loads(msg_data["data"])- chunk = _reconstruct_chunk(chunk_data)+ chunk = _chunk_from_fields(msg_data)if chunk:try:await asyncio.wait_for(- subscriber_queue.put(chunk),+ subscriber_queue.put(+ (f"{turn_id}:{msg_id}", chunk)+ ),timeout=QUEUE_PUT_TIMEOUT,)# Update last delivered ID on successful delivery@@ -806,7 +874,7 @@ async def _stream_listener("recovery_hint": f"Reconnect with last_message_id={last_delivered_id}",},)- subscriber_queue.put_nowait(overflow_error)+ subscriber_queue.put_nowait((None, overflow_error))except asyncio.QueueFull:# Queue is completely stuck, nothing more we can dologger.error(@@ -857,7 +925,7 @@ async def _stream_listener(# On error, send finish to unblock subscribertry:await asyncio.wait_for(- subscriber_queue.put(StreamFinish()),+ subscriber_queue.put((None, StreamFinish())),timeout=QUEUE_PUT_TIMEOUT,)except (asyncio.TimeoutError, asyncio.QueueFull):@@ -1038,6 +1106,7 @@ async def mark_session_completed(f"Failed to publish StreamFinish for session {session_id}: {e}. ""The _stream_listener will detect completion via status polling.")+ await _trim_to_last_checkpoint(redis, turn_id)# Clean up local session reference if exists_local_sessions.pop(session_id, None)@@ -1067,6 +1136,36 @@ async def mark_session_completed(return True+async def _trim_to_last_checkpoint(redis: Any, turn_id: str) -> None:+ """Drop a finished turn's entries before its last checkpoint.++ The tail from a checkpoint is self-contained, so a late resume either+ finds its cursor or gets that checkpoint to seed from.+ """+ try:+ await redis.expire(_get_turn_meta_key(turn_id), config.stream_ttl)+ checkpoint = await _read_checkpoint(redis, turn_id)+ if checkpoint is not None:+ await redis.xtrim(+ _get_turn_stream_key(turn_id),+ minid=checkpoint.entry_id,+ approximate=False,+ )+ except RedisError as e:+ logger.warning(f"Failed to trim the stream of turn {turn_id}: {e}")+++async def _read_checkpoint(redis: Any, turn_id: str) -> TurnCheckpoint | None:+ raw = await redis.hget(_get_turn_meta_key(turn_id), "checkpoint")+ if not raw:+ return None+ try:+ return TurnCheckpoint.model_validate_json(raw)+ except ValidationError:+ logger.warning(f"Unreadable checkpoint for turn {turn_id}: {raw!r}")+ return None++async def get_session(session_id: str) -> ActiveSession | None:"""Get a session by its ID from Redis.@@ -1177,6 +1276,7 @@ async def get_active_session(logger.warning(f"Failed to parse created_at: {e}")session = _parse_session_meta(meta, session_id)+ session.checkpoint = await _read_checkpoint(redis, session.turn_id)logger.info(f"[SESSION_LOOKUP] Found running session {session_id[:8]}..., turn_id={session.turn_id[:8]}")@@ -1223,6 +1323,7 @@ CHUNK_TYPE_TO_CLASS: dict[str, type[StreamBaseResponse]] = {ResponseType.MODE_CHANGED.value: StreamModeChanged,ResponseType.PROVIDER_FAILURE.value: StreamProviderFailure,ResponseType.COMPACTION.value: StreamCompactionProgress,+ ResponseType.CHECKPOINT.value: StreamCheckpoint,}@@ -1263,7 +1364,7 @@ async def set_session_asyncio_task(session_id: str, asyncio_task: asyncio.Task)async def unsubscribe_from_session(session_id: str,- subscriber_queue: asyncio.Queue[StreamBaseResponse],+ subscriber_queue: asyncio.Queue[StreamEntry],) -> None:"""Clean up when a subscriber disconnects.diff --git a/autogpt_platform/backend/backend/copilot/stream_registry_resume_test.py b/autogpt_platform/backend/backend/copilot/stream_registry_resume_test.pynew file mode 100644index 0000000000..24c5e2943e--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/stream_registry_resume_test.py@@ -0,0 +1,249 @@+"""Entry ids, checkpoints and the cursor read, against a real Redis stream."""++import asyncio+import uuid+from unittest.mock import AsyncMock, patch++import pytest++from backend.copilot import stream_registry+from backend.copilot.response_model import (+ StreamBaseResponse,+ StreamCheckpoint,+ StreamFinish,+ StreamHeartbeat,+ StreamStart,+ StreamTextDelta,+ StreamTextEnd,+ StreamTextStart,+ StreamUsage,+)+from backend.data import redis_client+from backend.util.testing import is_tcp_port_reachable++pytestmark = pytest.mark.skipif(+ not is_tcp_port_reachable(redis_client.HOST, redis_client.PORT),+ reason="no local Redis reachable; the stream registry needs one to run",+)+++async def turn():+ """A running turn of its own session, with every key removed after."""+ session_id, turn_id = f"resume-{uuid.uuid4().hex}", str(uuid.uuid4())+ await stream_registry.create_session(session_id, None, "", "", turn_id=turn_id)+ turn_ids = [turn_id]+ yield session_id, turn_id, turn_ids+ redis = await redis_client.get_redis_async()+ await redis.delete(stream_registry.get_session_meta_key(session_id))+ for key_turn in turn_ids:+ await redis.delete(stream_registry._get_turn_stream_key(key_turn))+ await redis.delete(stream_registry._get_turn_meta_key(key_turn))+++async def test_every_entry_frame_carries_its_turn_and_entry_id(turn):+ session_id, turn_id, _ = turn+ ids = await _publish(+ session_id,+ turn_id,+ [+ StreamStart(messageId="m1"),+ StreamUsage(prompt_tokens=1, completion_tokens=1, total_tokens=2),+ ],+ )++ queue = await stream_registry.subscribe_to_session(session_id, None, "0-0")+ assert queue is not None+ try:+ start, usage = queue.get_nowait(), queue.get_nowait()+ finally:+ await stream_registry.unsubscribe_from_session(session_id, queue)++ assert stream_registry.sse_frame(start).startswith(+ f"id: {turn_id}:{ids[0]}\ndata: "+ )+ # A comment frame's id would be dropped by the client's parser.+ assert stream_registry.sse_frame(usage).startswith(": usage ")+ assert stream_registry.sse_frame((None, StreamHeartbeat())) == ": heartbeat\n\n"+++async def test_a_checkpoint_is_exposed_on_the_active_stream(turn):+ session_id, turn_id, _ = turn+ [entry_id] = await _publish(+ session_id, turn_id, [StreamCheckpoint(rows=3, sequence=7, digest="d")]+ )++ active, _ = await stream_registry.get_active_session(session_id)++ assert active is not None+ assert active.checkpoint == stream_registry.TurnCheckpoint(+ entry_id=entry_id, rows=3, sequence=7+ )+++async def test_a_cursor_read_serves_exactly_the_entries_after_the_cursor(turn):+ session_id, turn_id, _ = turn+ ids = await _publish(session_id, turn_id, _text_turn())+ await _complete(session_id, turn_id)++ for position, cursor in enumerate(["0-0", *ids]):+ queue = await stream_registry.subscribe_to_turn(+ session_id, None, turn_id, cursor+ )+ *tail, (finish_id, finish) = await _drain(session_id, queue)++ assert [frame_id for frame_id, _ in tail] == [+ f"{turn_id}:{entry_id}" for entry_id in ids[position:]+ ]+ assert isinstance(finish, StreamFinish)+ assert finish_id is not None and finish_id.startswith(f"{turn_id}:")+++async def test_a_finished_turns_tail_ends_with_its_stored_finish(turn):+ session_id, turn_id, _ = turn+ await _publish(session_id, turn_id, _text_turn())+ await _complete(session_id, turn_id)++ queue = await stream_registry.subscribe_to_turn(session_id, None, turn_id, "0-0")+ served = await _drain(session_id, queue)++ frame_id, last = served[-1]+ assert isinstance(last, StreamFinish) and frame_id is not None+ assert all(frame_id is not None for frame_id, _ in served)+++async def test_completion_trims_to_the_last_checkpoint(turn):+ session_id, turn_id, _ = turn+ ids = await _publish(+ session_id,+ turn_id,+ [+ *_text_turn(),+ StreamCheckpoint(rows=1, sequence=4, digest="d"),+ StreamTextStart(id="t2"),+ StreamTextEnd(id="t2"),+ ],+ )+ checkpoint_id = ids[len(_text_turn())]+ await _complete(session_id, turn_id)++ with pytest.raises(stream_registry.TurnStreamTrimmed) as trimmed:+ await stream_registry.subscribe_to_turn(session_id, None, turn_id, ids[1])+ queue = await stream_registry.subscribe_to_turn(+ session_id, None, turn_id, checkpoint_id+ )+ served = await _drain(session_id, queue)++ assert trimmed.value.checkpoint == stream_registry.TurnCheckpoint(+ entry_id=checkpoint_id, rows=1, sequence=4+ )+ assert [type(chunk) for _, chunk in served] == [+ StreamTextStart,+ StreamTextEnd,+ StreamFinish,+ ]+++async def test_an_expired_stream_is_gone(turn):+ session_id, turn_id, _ = turn+ await _publish(session_id, turn_id, _text_turn())+ await _complete(session_id, turn_id)+ redis = await redis_client.get_redis_async()+ await redis.delete(stream_registry._get_turn_stream_key(turn_id))++ with pytest.raises(stream_registry.TurnStreamGone):+ await stream_registry.subscribe_to_turn(session_id, None, turn_id, "0-0")+++async def test_a_finished_turn_is_served_after_the_next_one_starts(turn):+ session_id, turn_id, turn_ids = turn+ ids = await _publish(session_id, turn_id, _text_turn())+ await _complete(session_id, turn_id)+ turn_ids.append(next_turn := str(uuid.uuid4()))+ await stream_registry.create_session(session_id, None, "", "", turn_id=next_turn)++ queue = await stream_registry.subscribe_to_turn(session_id, None, turn_id, ids[0])+ served = await _drain(session_id, queue)++ assert isinstance(served[-1][1], StreamFinish)+ assert len(served) == len(ids) # everything after the first, plus the finish+++async def test_another_sessions_turn_is_refused(turn):+ session_id, turn_id, _ = turn+ await _publish(session_id, turn_id, _text_turn())+ await _complete(session_id, turn_id)+ other = f"resume-{uuid.uuid4().hex}"+ await stream_registry.create_session(other, None, "", "", turn_id="elsewhere")+ try:+ with pytest.raises(stream_registry.TurnStreamGone):+ await stream_registry.subscribe_to_turn(other, None, turn_id, "0-0")+ finally:+ redis = await redis_client.get_redis_async()+ await redis.delete(stream_registry.get_session_meta_key(other))+ await redis.delete(stream_registry._get_turn_meta_key("elsewhere"))+++async def test_a_finished_turns_replay_is_not_capped(turn):+ """W9: a finished turn's replay stopped at 200 entries and made up a finish."""+ session_id, turn_id, _ = turn+ deltas = [StreamTextDelta(id="t1", delta=f"{i} ") for i in range(450)]+ await _publish(+ session_id,+ turn_id,+ [+ StreamStart(messageId="m1"),+ StreamTextStart(id="t1"),+ *deltas,+ StreamTextEnd(id="t1"),+ ],+ )+ await _complete(session_id, turn_id)++ queue = await stream_registry.subscribe_to_session(session_id, None, "0-0")+ assert queue is not None+ served = await _drain(session_id, queue)++ assert len(served) == len(deltas) + 4+ assert all(frame_id is not None for frame_id, _ in served)+++def _text_turn() -> list[StreamBaseResponse]:+ return [+ StreamStart(messageId="m1"),+ StreamTextStart(id="t1"),+ StreamTextDelta(id="t1", delta="Hello "),+ StreamTextDelta(id="t1", delta="there."),+ StreamTextEnd(id="t1"),+ ]+++async def _publish(+ session_id: str, turn_id: str, chunks: list[StreamBaseResponse]+) -> list[str]:+ return [+ await stream_registry.publish_chunk(turn_id, chunk, session_id=session_id)+ for chunk in chunks+ ]+++async def _complete(session_id: str, turn_id: str) -> None:+ with patch.object(+ stream_registry.chat_db(), "set_turn_duration", new=AsyncMock(), create=True+ ):+ await stream_registry.mark_session_completed(session_id, turn_id=turn_id)+++async def _drain(session_id, queue) -> list[stream_registry.StreamEntry]:+ """Everything the queue serves up to the turn's finish or the end marker."""+ served = []+ try:+ while True:+ frame_id, chunk = await asyncio.wait_for(queue.get(), timeout=10)+ if isinstance(chunk, StreamHeartbeat):+ continue+ served.append((frame_id, chunk))+ if isinstance(chunk, StreamFinish):+ return served+ finally:+ await stream_registry.unsubscribe_from_session(session_id, queue)diff --git a/autogpt_platform/backend/backend/copilot/stream_registry_test.py b/autogpt_platform/backend/backend/copilot/stream_registry_test.pyindex 4265563c45..5afeefcec4 100644--- a/autogpt_platform/backend/backend/copilot/stream_registry_test.py+++ b/autogpt_platform/backend/backend/copilot/stream_registry_test.py@@ -256,6 +256,9 @@ class _FakeRedis:self._meta = dict(meta)self.deleted_keys: list[str] = []self.delete = AsyncMock(side_effect=self._record_delete)+ self.expire = AsyncMock()+ # No turn has a checkpoint, so completion trims nothing.+ self.hget = AsyncMock(return_value=None)async def _record_delete(self, *keys: str):self.deleted_keys.extend(keys)@@ -568,11 +571,12 @@ async def test_subscribe_to_session_replays_chunks_without_cursor_parts():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)+ assert [(frame_id, type(chunk)) for frame_id, chunk in delivered] == [+ ("turn-1:9999-0", StreamTextStart),+ ("turn-1:9999-1", StreamTextDelta),+ ("turn-1:9999-2", StreamTextEnd),+ (None, stream_registry.StreamFinish),+ ]def test_reconstruct_chunk_round_trips_pending_drained():diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-consecutive-tools-turn/entries.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-consecutive-tools-turn/entries.jsonlnew file mode 100644index 0000000000..302031303c--- /dev/null+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-consecutive-tools-turn/entries.jsonl@@ -0,0 +1,21 @@+{"id": "1-0", "data": {"type": "data-status", "message": "Message received…"}}+{"id": "2-0", "data": {"type": "data-status", "message": "Setting up your environment…"}}+{"id": "3-0", "data": {"type": "start", "messageId": "00000000-0000-4000-8000-000000000001", "sessionId": "drift-session"}}+{"id": "4-0", "data": {"type": "start-step"}}+{"id": "5-0", "data": {"type": "finish-step"}}+{"id": "6-0", "data": {"type": "tool-input-start", "toolCallId": "call-com", "toolName": "web_fetch"}}+{"id": "7-0", "data": {"type": "tool-input-available", "toolCallId": "call-com", "toolName": "web_fetch", "input": {"url": "example.com"}}}+{"id": "8-0", "data": {"type": "tool-output-available", "toolCallId": "call-com", "output": "Example Domain", "toolName": "web_fetch", "success": true}}+{"id": "9-0", "data": {"type": "start-step"}}+{"id": "10-0", "data": {"type": "finish-step"}}+{"id": "11-0", "data": {"type": "tool-input-start", "toolCallId": "call-org", "toolName": "web_fetch"}}+{"id": "12-0", "data": {"type": "tool-input-available", "toolCallId": "call-org", "toolName": "web_fetch", "input": {"url": "example.org"}}}+{"id": "13-0", "data": {"type": "tool-output-available", "toolCallId": "call-org", "output": "Example Domain", "toolName": "web_fetch", "success": true}}+{"id": "14-0", "data": {"type": "start-step"}}+{"id": "15-0", "data": {"type": "text-start", "id": "00000000-0000-4000-8000-000000000002"}}+{"id": "16-0", "data": {"type": "text-delta", "id": "00000000-0000-4000-8000-000000000002", "delta": "Both are placeholder pages."}}+{"id": "17-0", "data": {"type": "text-end", "id": "00000000-0000-4000-8000-000000000002"}}+{"id": "18-0", "data": {"type": "finish-step"}}+{"id": "19-0", "data": {"type": "data-checkpoint", "rows": 5, "sequence": 1, "digest": "646196442fc73b104d32dd605434c4a374d76ac2c1de8ade42243ee1638e5e3c"}}+{"id": "20-0", "data": {"type": "usage", "prompt_tokens": 300, "completion_tokens": 60, "total_tokens": 360, "cache_read_tokens": 0, "cache_creation_tokens": 0}}+{"id": "21-0", "data": {"type": "finish"}}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-consecutive-tools-turn/frames.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-consecutive-tools-turn/frames.jsonlnew file mode 100644index 0000000000..257c6b37d3--- /dev/null+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-consecutive-tools-turn/frames.jsonl@@ -0,0 +1,21 @@+{"id": "1-0", "sse": "id: drift-turn:1-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Message received\\u2026\"}}\n\n"}+{"id": "2-0", "sse": "id: drift-turn:2-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Setting up your environment\\u2026\"}}\n\n"}+{"id": "3-0", "sse": "id: drift-turn:3-0\ndata: {\"type\": \"start\", \"messageId\": \"00000000-0000-4000-8000-000000000001\"}\n\n"}+{"id": "4-0", "sse": "id: drift-turn:4-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "5-0", "sse": "id: drift-turn:5-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "6-0", "sse": "id: drift-turn:6-0\ndata: {\"type\":\"tool-input-start\",\"toolCallId\":\"call-com\",\"toolName\":\"web_fetch\"}\n\n"}+{"id": "7-0", "sse": "id: drift-turn:7-0\ndata: {\"type\":\"tool-input-available\",\"toolCallId\":\"call-com\",\"toolName\":\"web_fetch\",\"input\":{\"url\":\"example.com\"}}\n\n"}+{"id": "8-0", "sse": "id: drift-turn:8-0\ndata: {\"type\": \"tool-output-available\", \"toolCallId\": \"call-com\", \"output\": \"Example Domain\"}\n\n"}+{"id": "9-0", "sse": "id: drift-turn:9-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "10-0", "sse": "id: drift-turn:10-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "11-0", "sse": "id: drift-turn:11-0\ndata: {\"type\":\"tool-input-start\",\"toolCallId\":\"call-org\",\"toolName\":\"web_fetch\"}\n\n"}+{"id": "12-0", "sse": "id: drift-turn:12-0\ndata: {\"type\":\"tool-input-available\",\"toolCallId\":\"call-org\",\"toolName\":\"web_fetch\",\"input\":{\"url\":\"example.org\"}}\n\n"}+{"id": "13-0", "sse": "id: drift-turn:13-0\ndata: {\"type\": \"tool-output-available\", \"toolCallId\": \"call-org\", \"output\": \"Example Domain\"}\n\n"}+{"id": "14-0", "sse": "id: drift-turn:14-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "15-0", "sse": "id: drift-turn:15-0\ndata: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}+{"id": "16-0", "sse": "id: drift-turn:16-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"Both are placeholder pages.\"}\n\n"}+{"id": "17-0", "sse": "id: drift-turn:17-0\ndata: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}+{"id": "18-0", "sse": "id: drift-turn:18-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "19-0", "sse": "id: drift-turn:19-0\ndata: {\"type\": \"data-checkpoint\", \"data\": {\"rows\": 5, \"sequence\": 1, \"digest\": \"646196442fc73b104d32dd605434c4a374d76ac2c1de8ade42243ee1638e5e3c\"}, \"transient\": true}\n\n"}+{"id": "20-0", "sse": ": usage {\"type\":\"usage\",\"promptTokens\":300,\"completionTokens\":60,\"totalTokens\":360,\"cacheReadTokens\":0,\"cacheCreationTokens\":0}\n\n"}+{"id": "21-0", "sse": "id: drift-turn:21-0\ndata: {\"type\":\"finish\"}\n\n"}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-consecutive-tools-turn/rows.json b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-consecutive-tools-turn/rows.jsonnew file mode 100644index 0000000000..20bdf6bd69--- /dev/null+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-consecutive-tools-turn/rows.json@@ -0,0 +1,128 @@+[+ {+ "id": "row-0",+ "role": "user",+ "content": "Compare example.com and example.org",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 0,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:00Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-1",+ "role": "assistant",+ "content": "",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": [+ {+ "id": "call-com",+ "type": "function",+ "function": {+ "name": "web_fetch",+ "arguments": "{\"url\": \"example.com\"}"+ }+ }+ ],+ "function_call": null,+ "sequence": 1,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:01Z",+ "model": "anthropic/claude-sonnet-4-6",+ "llm_auth_provider": "platform",+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-2",+ "role": "tool",+ "content": "Example Domain",+ "name": null,+ "tool_call_id": "call-com",+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 2,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:02Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-3",+ "role": "assistant",+ "content": "",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": [+ {+ "id": "call-org",+ "type": "function",+ "function": {+ "name": "web_fetch",+ "arguments": "{\"url\": \"example.org\"}"+ }+ }+ ],+ "function_call": null,+ "sequence": 3,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:03Z",+ "model": "anthropic/claude-sonnet-4-6",+ "llm_auth_provider": "platform",+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-4",+ "role": "tool",+ "content": "Example Domain",+ "name": null,+ "tool_call_id": "call-org",+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 4,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:04Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-5",+ "role": "assistant",+ "content": "Both are placeholder pages.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 5,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:05Z",+ "model": "anthropic/claude-sonnet-4-6",+ "llm_auth_provider": "platform",+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ }+]diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-drain-turn/entries.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-drain-turn/entries.jsonlnew file mode 100644index 0000000000..1f881af369--- /dev/null+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-drain-turn/entries.jsonl@@ -0,0 +1,29 @@+{"id": "1-0", "data": {"type": "data-status", "message": "Message received…"}}+{"id": "2-0", "data": {"type": "data-status", "message": "Setting up your environment…"}}+{"id": "3-0", "data": {"type": "start", "messageId": "00000000-0000-4000-8000-000000000001", "sessionId": "drift-session"}}+{"id": "4-0", "data": {"type": "data-pending-drained", "drainedCount": 1, "messages": [{"id": "00000000-0000-4000-8000-000000000002", "content": "Keep it short."}]}}+{"id": "5-0", "data": {"type": "start-step"}}+{"id": "6-0", "data": {"type": "reasoning-start", "id": "00000000-0000-4000-8000-000000000003"}}+{"id": "7-0", "data": {"type": "reasoning-delta", "id": "00000000-0000-4000-8000-000000000003", "delta": "The user wants "}}+{"id": "8-0", "data": {"type": "reasoning-delta", "id": "00000000-0000-4000-8000-000000000003", "delta": "a summary."}}+{"id": "9-0", "data": {"type": "reasoning-end", "id": "00000000-0000-4000-8000-000000000003"}}+{"id": "10-0", "data": {"type": "text-start", "id": "00000000-0000-4000-8000-000000000004"}}+{"id": "11-0", "data": {"type": "text-delta", "id": "00000000-0000-4000-8000-000000000004", "delta": "Fetching it."}}+{"id": "12-0", "data": {"type": "text-end", "id": "00000000-0000-4000-8000-000000000004"}}+{"id": "13-0", "data": {"type": "finish-step"}}+{"id": "14-0", "data": {"type": "tool-input-start", "toolCallId": "call-fetch", "toolName": "web_fetch"}}+{"id": "15-0", "data": {"type": "tool-input-available", "toolCallId": "call-fetch", "toolName": "web_fetch", "input": {"url": "example.com"}}}+{"id": "16-0", "data": {"type": "tool-output-available", "toolCallId": "call-fetch", "output": "Example Domain", "toolName": "web_fetch", "success": true}}+{"id": "17-0", "data": {"type": "data-pending-drained", "drainedCount": 1, "messages": [{"id": "00000000-0000-4000-8000-000000000005", "content": "In French, please."}]}}+{"id": "18-0", "data": {"type": "data-checkpoint", "rows": 5, "sequence": 1, "digest": "630cc061bcb09f33a99719db8a07e65f79152226f69db47702f7a59ea02b17be"}}+{"id": "19-0", "data": {"type": "start-step"}}+{"id": "20-0", "data": {"type": "reasoning-start", "id": "00000000-0000-4000-8000-000000000006"}}+{"id": "21-0", "data": {"type": "reasoning-delta", "id": "00000000-0000-4000-8000-000000000006", "delta": "Short answer."}}+{"id": "22-0", "data": {"type": "reasoning-end", "id": "00000000-0000-4000-8000-000000000006"}}+{"id": "23-0", "data": {"type": "text-start", "id": "00000000-0000-4000-8000-000000000007"}}+{"id": "24-0", "data": {"type": "text-delta", "id": "00000000-0000-4000-8000-000000000007", "delta": "It is a placeholder page."}}+{"id": "25-0", "data": {"type": "text-end", "id": "00000000-0000-4000-8000-000000000007"}}+{"id": "26-0", "data": {"type": "finish-step"}}+{"id": "27-0", "data": {"type": "data-checkpoint", "rows": 7, "sequence": 1, "digest": "3d5d2ab2fec9709ebf4df2930a8d04ed2277a6a0401a6b0b62ad5faaf9ac2c21"}}+{"id": "28-0", "data": {"type": "usage", "prompt_tokens": 200, "completion_tokens": 40, "total_tokens": 240, "cache_read_tokens": 0, "cache_creation_tokens": 0}}+{"id": "29-0", "data": {"type": "finish"}}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-drain-turn/frames.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-drain-turn/frames.jsonlnew file mode 100644index 0000000000..87e67cc12d--- /dev/null+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-drain-turn/frames.jsonl@@ -0,0 +1,29 @@+{"id": "1-0", "sse": "id: drift-turn:1-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Message received\\u2026\"}}\n\n"}+{"id": "2-0", "sse": "id: drift-turn:2-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Setting up your environment\\u2026\"}}\n\n"}+{"id": "3-0", "sse": "id: drift-turn:3-0\ndata: {\"type\": \"start\", \"messageId\": \"00000000-0000-4000-8000-000000000001\"}\n\n"}+{"id": "4-0", "sse": "id: drift-turn:4-0\ndata: {\"type\": \"data-pending-drained\", \"data\": {\"drainedCount\": 1, \"messages\": [{\"id\": \"00000000-0000-4000-8000-000000000002\", \"content\": \"Keep it short.\"}]}}\n\n"}+{"id": "5-0", "sse": "id: drift-turn:5-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "6-0", "sse": "id: drift-turn:6-0\ndata: {\"type\":\"reasoning-start\",\"id\":\"00000000-0000-4000-8000-000000000003\"}\n\n"}+{"id": "7-0", "sse": "id: drift-turn:7-0\ndata: {\"type\":\"reasoning-delta\",\"id\":\"00000000-0000-4000-8000-000000000003\",\"delta\":\"The user wants \"}\n\n"}+{"id": "8-0", "sse": "id: drift-turn:8-0\ndata: {\"type\":\"reasoning-delta\",\"id\":\"00000000-0000-4000-8000-000000000003\",\"delta\":\"a summary.\"}\n\n"}+{"id": "9-0", "sse": "id: drift-turn:9-0\ndata: {\"type\":\"reasoning-end\",\"id\":\"00000000-0000-4000-8000-000000000003\"}\n\n"}+{"id": "10-0", "sse": "id: drift-turn:10-0\ndata: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000004\"}\n\n"}+{"id": "11-0", "sse": "id: drift-turn:11-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000004\",\"delta\":\"Fetching it.\"}\n\n"}+{"id": "12-0", "sse": "id: drift-turn:12-0\ndata: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000004\"}\n\n"}+{"id": "13-0", "sse": "id: drift-turn:13-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "14-0", "sse": "id: drift-turn:14-0\ndata: {\"type\":\"tool-input-start\",\"toolCallId\":\"call-fetch\",\"toolName\":\"web_fetch\"}\n\n"}+{"id": "15-0", "sse": "id: drift-turn:15-0\ndata: {\"type\":\"tool-input-available\",\"toolCallId\":\"call-fetch\",\"toolName\":\"web_fetch\",\"input\":{\"url\":\"example.com\"}}\n\n"}+{"id": "16-0", "sse": "id: drift-turn:16-0\ndata: {\"type\": \"tool-output-available\", \"toolCallId\": \"call-fetch\", \"output\": \"Example Domain\"}\n\n"}+{"id": "17-0", "sse": "id: drift-turn:17-0\ndata: {\"type\": \"data-pending-drained\", \"data\": {\"drainedCount\": 1, \"messages\": [{\"id\": \"00000000-0000-4000-8000-000000000005\", \"content\": \"In French, please.\"}]}}\n\n"}+{"id": "18-0", "sse": "id: drift-turn:18-0\ndata: {\"type\": \"data-checkpoint\", \"data\": {\"rows\": 5, \"sequence\": 1, \"digest\": \"630cc061bcb09f33a99719db8a07e65f79152226f69db47702f7a59ea02b17be\"}, \"transient\": true}\n\n"}+{"id": "19-0", "sse": "id: drift-turn:19-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "20-0", "sse": "id: drift-turn:20-0\ndata: {\"type\":\"reasoning-start\",\"id\":\"00000000-0000-4000-8000-000000000006\"}\n\n"}+{"id": "21-0", "sse": "id: drift-turn:21-0\ndata: {\"type\":\"reasoning-delta\",\"id\":\"00000000-0000-4000-8000-000000000006\",\"delta\":\"Short answer.\"}\n\n"}+{"id": "22-0", "sse": "id: drift-turn:22-0\ndata: {\"type\":\"reasoning-end\",\"id\":\"00000000-0000-4000-8000-000000000006\"}\n\n"}+{"id": "23-0", "sse": "id: drift-turn:23-0\ndata: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000007\"}\n\n"}+{"id": "24-0", "sse": "id: drift-turn:24-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000007\",\"delta\":\"It is a placeholder page.\"}\n\n"}+{"id": "25-0", "sse": "id: drift-turn:25-0\ndata: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000007\"}\n\n"}+{"id": "26-0", "sse": "id: drift-turn:26-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "27-0", "sse": "id: drift-turn:27-0\ndata: {\"type\": \"data-checkpoint\", \"data\": {\"rows\": 7, \"sequence\": 1, \"digest\": \"3d5d2ab2fec9709ebf4df2930a8d04ed2277a6a0401a6b0b62ad5faaf9ac2c21\"}, \"transient\": true}\n\n"}+{"id": "28-0", "sse": ": usage {\"type\":\"usage\",\"promptTokens\":200,\"completionTokens\":40,\"totalTokens\":240,\"cacheReadTokens\":0,\"cacheCreationTokens\":0}\n\n"}+{"id": "29-0", "sse": "id: drift-turn:29-0\ndata: {\"type\":\"finish\"}\n\n"}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-drain-turn/rows.json b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-drain-turn/rows.jsonnew file mode 100644index 0000000000..4913c443e2--- /dev/null+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-drain-turn/rows.json@@ -0,0 +1,155 @@+[+ {+ "id": "row-0",+ "role": "user",+ "content": "Summarise example.com",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 0,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:00Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-1",+ "role": "user",+ "content": "Keep it short.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 1,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:01Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-2",+ "role": "reasoning",+ "content": "The user wants a summary.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 2,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:02Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-3",+ "role": "assistant",+ "content": "Fetching it.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": [+ {+ "id": "call-fetch",+ "type": "function",+ "function": {+ "name": "web_fetch",+ "arguments": "{\"url\": \"example.com\"}"+ }+ }+ ],+ "function_call": null,+ "sequence": 3,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:03Z",+ "model": "anthropic/claude-sonnet-4-6",+ "llm_auth_provider": "platform",+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-4",+ "role": "tool",+ "content": "Example Domain",+ "name": null,+ "tool_call_id": "call-fetch",+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 4,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:04Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-5",+ "role": "user",+ "content": "In French, please.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 5,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:05Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-6",+ "role": "reasoning",+ "content": "Short answer.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 6,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:06Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-7",+ "role": "assistant",+ "content": "It is a placeholder page.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 7,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:07Z",+ "model": "anthropic/claude-sonnet-4-6",+ "llm_auth_provider": "platform",+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ }+]diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-tool-turn/entries.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-tool-turn/entries.jsonlindex 1b3d1a3733..a3787f5cdb 100644--- a/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-tool-turn/entries.jsonl+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-tool-turn/entries.jsonl@@ -17,5 +17,6 @@{"id": "17-0", "data": {"type": "text-delta", "id": "00000000-0000-4000-8000-000000000003", "delta": "Example Domain."}}{"id": "18-0", "data": {"type": "text-end", "id": "00000000-0000-4000-8000-000000000003"}}{"id": "19-0", "data": {"type": "finish-step"}}-{"id": "20-0", "data": {"type": "usage", "prompt_tokens": 200, "completion_tokens": 40, "total_tokens": 240, "cache_read_tokens": 0, "cache_creation_tokens": 0}}-{"id": "21-0", "data": {"type": "finish"}}+{"id": "20-0", "data": {"type": "data-checkpoint", "rows": 3, "sequence": 1, "digest": "6a90701268140af70592a86f2bad0894e0a3a74acbcf38c65e449021d177b974"}}+{"id": "21-0", "data": {"type": "usage", "prompt_tokens": 200, "completion_tokens": 40, "total_tokens": 240, "cache_read_tokens": 0, "cache_creation_tokens": 0}}+{"id": "22-0", "data": {"type": "finish"}}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-tool-turn/frames.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-tool-turn/frames.jsonlindex 559c50c55f..9403f40df6 100644--- a/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-tool-turn/frames.jsonl+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-tool-turn/frames.jsonl@@ -1,21 +1,22 @@-{"id": "1-0", "sse": "data: {\"type\": \"data-status\", \"data\": {\"message\": \"Message received\\u2026\"}}\n\n"}-{"id": "2-0", "sse": "data: {\"type\": \"data-status\", \"data\": {\"message\": \"Setting up your environment\\u2026\"}}\n\n"}-{"id": "3-0", "sse": "data: {\"type\": \"start\", \"messageId\": \"00000000-0000-4000-8000-000000000001\"}\n\n"}-{"id": "4-0", "sse": "data: {\"type\":\"start-step\"}\n\n"}-{"id": "5-0", "sse": "data: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}-{"id": "6-0", "sse": "data: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"Let me \"}\n\n"}-{"id": "7-0", "sse": "data: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"fetch that \"}\n\n"}-{"id": "8-0", "sse": "data: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"page.\"}\n\n"}-{"id": "9-0", "sse": "data: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}-{"id": "10-0", "sse": "data: {\"type\":\"finish-step\"}\n\n"}-{"id": "11-0", "sse": "data: {\"type\":\"tool-input-start\",\"toolCallId\":\"call-fetch\",\"toolName\":\"web_fetch\"}\n\n"}-{"id": "12-0", "sse": "data: {\"type\":\"tool-input-available\",\"toolCallId\":\"call-fetch\",\"toolName\":\"web_fetch\",\"input\":{\"url\":\"example.com\"}}\n\n"}-{"id": "13-0", "sse": "data: {\"type\": \"tool-output-available\", \"toolCallId\": \"call-fetch\", \"output\": \"<h1>Example Domain</h1>\"}\n\n"}-{"id": "14-0", "sse": "data: {\"type\":\"start-step\"}\n\n"}-{"id": "15-0", "sse": "data: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000003\"}\n\n"}-{"id": "16-0", "sse": "data: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000003\",\"delta\":\"It says \"}\n\n"}-{"id": "17-0", "sse": "data: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000003\",\"delta\":\"Example Domain.\"}\n\n"}-{"id": "18-0", "sse": "data: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000003\"}\n\n"}-{"id": "19-0", "sse": "data: {\"type\":\"finish-step\"}\n\n"}-{"id": "20-0", "sse": ": usage {\"type\":\"usage\",\"promptTokens\":200,\"completionTokens\":40,\"totalTokens\":240,\"cacheReadTokens\":0,\"cacheCreationTokens\":0}\n\n"}-{"id": "21-0", "sse": "data: {\"type\":\"finish\"}\n\n"}+{"id": "1-0", "sse": "id: drift-turn:1-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Message received\\u2026\"}}\n\n"}+{"id": "2-0", "sse": "id: drift-turn:2-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Setting up your environment\\u2026\"}}\n\n"}+{"id": "3-0", "sse": "id: drift-turn:3-0\ndata: {\"type\": \"start\", \"messageId\": \"00000000-0000-4000-8000-000000000001\"}\n\n"}+{"id": "4-0", "sse": "id: drift-turn:4-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "5-0", "sse": "id: drift-turn:5-0\ndata: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}+{"id": "6-0", "sse": "id: drift-turn:6-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"Let me \"}\n\n"}+{"id": "7-0", "sse": "id: drift-turn:7-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"fetch that \"}\n\n"}+{"id": "8-0", "sse": "id: drift-turn:8-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"page.\"}\n\n"}+{"id": "9-0", "sse": "id: drift-turn:9-0\ndata: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}+{"id": "10-0", "sse": "id: drift-turn:10-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "11-0", "sse": "id: drift-turn:11-0\ndata: {\"type\":\"tool-input-start\",\"toolCallId\":\"call-fetch\",\"toolName\":\"web_fetch\"}\n\n"}+{"id": "12-0", "sse": "id: drift-turn:12-0\ndata: {\"type\":\"tool-input-available\",\"toolCallId\":\"call-fetch\",\"toolName\":\"web_fetch\",\"input\":{\"url\":\"example.com\"}}\n\n"}+{"id": "13-0", "sse": "id: drift-turn:13-0\ndata: {\"type\": \"tool-output-available\", \"toolCallId\": \"call-fetch\", \"output\": \"<h1>Example Domain</h1>\"}\n\n"}+{"id": "14-0", "sse": "id: drift-turn:14-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "15-0", "sse": "id: drift-turn:15-0\ndata: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000003\"}\n\n"}+{"id": "16-0", "sse": "id: drift-turn:16-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000003\",\"delta\":\"It says \"}\n\n"}+{"id": "17-0", "sse": "id: drift-turn:17-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000003\",\"delta\":\"Example Domain.\"}\n\n"}+{"id": "18-0", "sse": "id: drift-turn:18-0\ndata: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000003\"}\n\n"}+{"id": "19-0", "sse": "id: drift-turn:19-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "20-0", "sse": "id: drift-turn:20-0\ndata: {\"type\": \"data-checkpoint\", \"data\": {\"rows\": 3, \"sequence\": 1, \"digest\": \"6a90701268140af70592a86f2bad0894e0a3a74acbcf38c65e449021d177b974\"}, \"transient\": true}\n\n"}+{"id": "21-0", "sse": ": usage {\"type\":\"usage\",\"promptTokens\":200,\"completionTokens\":40,\"totalTokens\":240,\"cacheReadTokens\":0,\"cacheCreationTokens\":0}\n\n"}+{"id": "22-0", "sse": "id: drift-turn:22-0\ndata: {\"type\":\"finish\"}\n\n"}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-tool-turn/rows.json b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-tool-turn/rows.jsonindex b2212ee6a0..8a16a72993 100644--- a/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-tool-turn/rows.json+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/baseline-tool-turn/rows.json@@ -14,7 +14,7 @@"model": null,"llm_auth_provider": null,"llm_credential_id": null,- "session_id": null,+ "session_id": "drift-session","metadata": null},{@@ -41,7 +41,7 @@"model": "anthropic/claude-sonnet-4-6","llm_auth_provider": "platform","llm_credential_id": null,- "session_id": null,+ "session_id": "drift-session","metadata": null},{@@ -59,7 +59,7 @@"model": null,"llm_auth_provider": null,"llm_credential_id": null,- "session_id": null,+ "session_id": "drift-session","metadata": null},{@@ -77,7 +77,7 @@"model": "anthropic/claude-sonnet-4-6","llm_auth_provider": "platform","llm_credential_id": null,- "session_id": null,+ "session_id": "drift-session","metadata": null}]diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/dummy-text-turn/entries.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/dummy-text-turn/entries.jsonlindex 4b07d73dc2..0ba6db4eaf 100644--- a/autogpt_platform/backend/test/fixtures/copilot_stream/dummy-text-turn/entries.jsonl+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/dummy-text-turn/entries.jsonl@@ -12,4 +12,5 @@{"id": "12-0", "data": {"type": "text-delta", "id": "00000000-0000-4000-8000-000000000002", "delta": "done!"}}{"id": "13-0", "data": {"type": "text-end", "id": "00000000-0000-4000-8000-000000000002"}}{"id": "14-0", "data": {"type": "finish-step"}}-{"id": "15-0", "data": {"type": "finish"}}+{"id": "15-0", "data": {"type": "data-checkpoint", "rows": 1, "sequence": 1, "digest": "27775965ee2a9b702875c6a0c7a615d3f8bb40120c172d509b9882eab852b439"}}+{"id": "16-0", "data": {"type": "finish"}}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/dummy-text-turn/frames.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/dummy-text-turn/frames.jsonlindex 0d3da38e56..6c3574eb1d 100644--- a/autogpt_platform/backend/test/fixtures/copilot_stream/dummy-text-turn/frames.jsonl+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/dummy-text-turn/frames.jsonl@@ -1,15 +1,16 @@-{"id": "1-0", "sse": "data: {\"type\": \"data-status\", \"data\": {\"message\": \"Message received\\u2026\"}}\n\n"}-{"id": "2-0", "sse": "data: {\"type\": \"data-status\", \"data\": {\"message\": \"Setting up your environment\\u2026\"}}\n\n"}-{"id": "3-0", "sse": "data: {\"type\": \"start\", \"messageId\": \"00000000-0000-4000-8000-000000000001\"}\n\n"}-{"id": "4-0", "sse": "data: {\"type\":\"start-step\"}\n\n"}-{"id": "5-0", "sse": "data: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}-{"id": "6-0", "sse": "data: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"I \"}\n\n"}-{"id": "7-0", "sse": "data: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"counted: \"}\n\n"}-{"id": "8-0", "sse": "data: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"1... \"}\n\n"}-{"id": "9-0", "sse": "data: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"2... \"}\n\n"}-{"id": "10-0", "sse": "data: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"3. \"}\n\n"}-{"id": "11-0", "sse": "data: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"All \"}\n\n"}-{"id": "12-0", "sse": "data: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"done!\"}\n\n"}-{"id": "13-0", "sse": "data: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}-{"id": "14-0", "sse": "data: {\"type\":\"finish-step\"}\n\n"}-{"id": "15-0", "sse": "data: {\"type\":\"finish\"}\n\n"}+{"id": "1-0", "sse": "id: drift-turn:1-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Message received\\u2026\"}}\n\n"}+{"id": "2-0", "sse": "id: drift-turn:2-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Setting up your environment\\u2026\"}}\n\n"}+{"id": "3-0", "sse": "id: drift-turn:3-0\ndata: {\"type\": \"start\", \"messageId\": \"00000000-0000-4000-8000-000000000001\"}\n\n"}+{"id": "4-0", "sse": "id: drift-turn:4-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "5-0", "sse": "id: drift-turn:5-0\ndata: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}+{"id": "6-0", "sse": "id: drift-turn:6-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"I \"}\n\n"}+{"id": "7-0", "sse": "id: drift-turn:7-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"counted: \"}\n\n"}+{"id": "8-0", "sse": "id: drift-turn:8-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"1... \"}\n\n"}+{"id": "9-0", "sse": "id: drift-turn:9-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"2... \"}\n\n"}+{"id": "10-0", "sse": "id: drift-turn:10-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"3. \"}\n\n"}+{"id": "11-0", "sse": "id: drift-turn:11-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"All \"}\n\n"}+{"id": "12-0", "sse": "id: drift-turn:12-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"done!\"}\n\n"}+{"id": "13-0", "sse": "id: drift-turn:13-0\ndata: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}+{"id": "14-0", "sse": "id: drift-turn:14-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "15-0", "sse": "id: drift-turn:15-0\ndata: {\"type\": \"data-checkpoint\", \"data\": {\"rows\": 1, \"sequence\": 1, \"digest\": \"27775965ee2a9b702875c6a0c7a615d3f8bb40120c172d509b9882eab852b439\"}, \"transient\": true}\n\n"}+{"id": "16-0", "sse": "id: drift-turn:16-0\ndata: {\"type\":\"finish\"}\n\n"}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/dummy-text-turn/rows.json b/autogpt_platform/backend/test/fixtures/copilot_stream/dummy-text-turn/rows.jsonindex 52d81cbe04..2cf7499e26 100644--- a/autogpt_platform/backend/test/fixtures/copilot_stream/dummy-text-turn/rows.json+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/dummy-text-turn/rows.json@@ -14,7 +14,7 @@"model": null,"llm_auth_provider": null,"llm_credential_id": null,- "session_id": null,+ "session_id": "drift-session","metadata": null},{@@ -32,7 +32,7 @@"model": null,"llm_auth_provider": null,"llm_credential_id": null,- "session_id": null,+ "session_id": "drift-session","metadata": null}]diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-auto-continue-turn/entries.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-auto-continue-turn/entries.jsonlnew file mode 100644index 0000000000..b5c5b06b6b--- /dev/null+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-auto-continue-turn/entries.jsonl@@ -0,0 +1,26 @@+{"id": "1-0", "data": {"type": "data-status", "message": "Message received…"}}+{"id": "2-0", "data": {"type": "data-status", "message": "Setting up your environment…"}}+{"id": "3-0", "data": {"type": "data-status", "message": "Restoring your session…"}}+{"id": "4-0", "data": {"type": "start", "messageId": "00000000-0000-4000-8000-000000000001", "sessionId": "drift-session"}}+{"id": "5-0", "data": {"type": "data-status", "message": "Preparing conversation context…"}}+{"id": "6-0", "data": {"type": "data-status", "message": "Starting the assistant…"}}+{"id": "7-0", "data": {"type": "data-status", "message": "Reading your message…"}}+{"id": "8-0", "data": {"type": "start-step"}}+{"id": "9-0", "data": {"type": "text-start", "id": "00000000-0000-4000-8000-000000000002"}}+{"id": "10-0", "data": {"type": "text-delta", "id": "00000000-0000-4000-8000-000000000002", "delta": "Release 1.2 adds sharing."}}+{"id": "11-0", "data": {"type": "text-end", "id": "00000000-0000-4000-8000-000000000002"}}+{"id": "12-0", "data": {"type": "finish-step"}}+{"id": "13-0", "data": {"type": "data-checkpoint", "rows": 1, "sequence": 3, "digest": "171cf7547b79de2f13e2cbd3830a9773ac270ed1582c197f54309a03334f9490"}}+{"id": "14-0", "data": {"type": "data-status", "message": "Restoring your session…"}}+{"id": "15-0", "data": {"type": "start", "messageId": "00000000-0000-4000-8000-000000000003", "sessionId": "drift-session"}}+{"id": "16-0", "data": {"type": "data-pending-drained", "drainedCount": 2, "messages": [{"id": "00000000-0000-4000-8000-000000000004", "content": "Mention the new export."}, {"id": "00000000-0000-4000-8000-000000000005", "content": "And keep it to one line."}]}}+{"id": "17-0", "data": {"type": "data-status", "message": "Preparing conversation context…"}}+{"id": "18-0", "data": {"type": "data-status", "message": "Starting the assistant…"}}+{"id": "19-0", "data": {"type": "data-status", "message": "Reading your message…"}}+{"id": "20-0", "data": {"type": "start-step"}}+{"id": "21-0", "data": {"type": "text-start", "id": "00000000-0000-4000-8000-000000000006"}}+{"id": "22-0", "data": {"type": "text-delta", "id": "00000000-0000-4000-8000-000000000006", "delta": "Release 1.2 adds export."}}+{"id": "23-0", "data": {"type": "text-end", "id": "00000000-0000-4000-8000-000000000006"}}+{"id": "24-0", "data": {"type": "finish-step"}}+{"id": "25-0", "data": {"type": "data-checkpoint", "rows": 4, "sequence": 3, "digest": "521c7f41fc4422cc340a62705856626b6688e80cfc508568012639a152b8a1ce"}}+{"id": "26-0", "data": {"type": "finish"}}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-auto-continue-turn/frames.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-auto-continue-turn/frames.jsonlnew file mode 100644index 0000000000..9546caa480--- /dev/null+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-auto-continue-turn/frames.jsonl@@ -0,0 +1,26 @@+{"id": "1-0", "sse": "id: drift-turn:1-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Message received\\u2026\"}}\n\n"}+{"id": "2-0", "sse": "id: drift-turn:2-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Setting up your environment\\u2026\"}}\n\n"}+{"id": "3-0", "sse": "id: drift-turn:3-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Restoring your session\\u2026\"}}\n\n"}+{"id": "4-0", "sse": "id: drift-turn:4-0\ndata: {\"type\": \"start\", \"messageId\": \"00000000-0000-4000-8000-000000000001\"}\n\n"}+{"id": "5-0", "sse": "id: drift-turn:5-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Preparing conversation context\\u2026\"}}\n\n"}+{"id": "6-0", "sse": "id: drift-turn:6-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Starting the assistant\\u2026\"}}\n\n"}+{"id": "7-0", "sse": "id: drift-turn:7-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Reading your message\\u2026\"}}\n\n"}+{"id": "8-0", "sse": "id: drift-turn:8-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "9-0", "sse": "id: drift-turn:9-0\ndata: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}+{"id": "10-0", "sse": "id: drift-turn:10-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"Release 1.2 adds sharing.\"}\n\n"}+{"id": "11-0", "sse": "id: drift-turn:11-0\ndata: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}+{"id": "12-0", "sse": "id: drift-turn:12-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "13-0", "sse": "id: drift-turn:13-0\ndata: {\"type\": \"data-checkpoint\", \"data\": {\"rows\": 1, \"sequence\": 3, \"digest\": \"171cf7547b79de2f13e2cbd3830a9773ac270ed1582c197f54309a03334f9490\"}, \"transient\": true}\n\n"}+{"id": "14-0", "sse": "id: drift-turn:14-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Restoring your session\\u2026\"}}\n\n"}+{"id": "15-0", "sse": "id: drift-turn:15-0\ndata: {\"type\": \"start\", \"messageId\": \"00000000-0000-4000-8000-000000000003\"}\n\n"}+{"id": "16-0", "sse": "id: drift-turn:16-0\ndata: {\"type\": \"data-pending-drained\", \"data\": {\"drainedCount\": 2, \"messages\": [{\"id\": \"00000000-0000-4000-8000-000000000004\", \"content\": \"Mention the new export.\"}, {\"id\": \"00000000-0000-4000-8000-000000000005\", \"content\": \"And keep it to one line.\"}]}}\n\n"}+{"id": "17-0", "sse": "id: drift-turn:17-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Preparing conversation context\\u2026\"}}\n\n"}+{"id": "18-0", "sse": "id: drift-turn:18-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Starting the assistant\\u2026\"}}\n\n"}+{"id": "19-0", "sse": "id: drift-turn:19-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Reading your message\\u2026\"}}\n\n"}+{"id": "20-0", "sse": "id: drift-turn:20-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "21-0", "sse": "id: drift-turn:21-0\ndata: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000006\"}\n\n"}+{"id": "22-0", "sse": "id: drift-turn:22-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000006\",\"delta\":\"Release 1.2 adds export.\"}\n\n"}+{"id": "23-0", "sse": "id: drift-turn:23-0\ndata: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000006\"}\n\n"}+{"id": "24-0", "sse": "id: drift-turn:24-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "25-0", "sse": "id: drift-turn:25-0\ndata: {\"type\": \"data-checkpoint\", \"data\": {\"rows\": 4, \"sequence\": 3, \"digest\": \"521c7f41fc4422cc340a62705856626b6688e80cfc508568012639a152b8a1ce\"}, \"transient\": true}\n\n"}+{"id": "26-0", "sse": "id: drift-turn:26-0\ndata: {\"type\":\"finish\"}\n\n"}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-auto-continue-turn/rows.json b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-auto-continue-turn/rows.jsonnew file mode 100644index 0000000000..8f7db779e1--- /dev/null+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-auto-continue-turn/rows.json@@ -0,0 +1,128 @@+[+ {+ "id": "row-0",+ "role": "user",+ "content": "Hi",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 0,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:00Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-1",+ "role": "assistant",+ "content": "Hello! What can I do?",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 1,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:01Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-2",+ "role": "user",+ "content": "Draft the release note.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 2,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:02Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-3",+ "role": "assistant",+ "content": "Release 1.2 adds sharing.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 3,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:03Z",+ "model": "drift",+ "llm_auth_provider": "platform",+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-4",+ "role": "user",+ "content": "Mention the new export.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 4,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:04Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-5",+ "role": "user",+ "content": "And keep it to one line.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 5,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:05Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-6",+ "role": "assistant",+ "content": "Release 1.2 adds export.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 6,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:06Z",+ "model": "drift",+ "llm_auth_provider": "platform",+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ }+]diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-consecutive-tools-turn/entries.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-consecutive-tools-turn/entries.jsonlnew file mode 100644index 0000000000..e883723cd4--- /dev/null+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-consecutive-tools-turn/entries.jsonl@@ -0,0 +1,22 @@+{"id": "1-0", "data": {"type": "data-status", "message": "Message received…"}}+{"id": "2-0", "data": {"type": "data-status", "message": "Setting up your environment…"}}+{"id": "3-0", "data": {"type": "start", "messageId": "00000000-0000-4000-8000-000000000001", "sessionId": "drift-session"}}+{"id": "4-0", "data": {"type": "start-step"}}+{"id": "5-0", "data": {"type": "tool-input-start", "toolCallId": "bash-1", "toolName": "bash_exec"}}+{"id": "6-0", "data": {"type": "tool-input-available", "toolCallId": "bash-1", "toolName": "bash_exec", "input": {"command": "ls"}}}+{"id": "7-0", "data": {"type": "tool-output-available", "toolCallId": "bash-1", "output": "a.md", "toolName": "bash_exec", "success": true}}+{"id": "8-0", "data": {"type": "finish-step"}}+{"id": "9-0", "data": {"type": "data-status", "message": "Analyzing result…"}}+{"id": "10-0", "data": {"type": "start-step"}}+{"id": "11-0", "data": {"type": "tool-input-start", "toolCallId": "bash-2", "toolName": "bash_exec"}}+{"id": "12-0", "data": {"type": "tool-input-available", "toolCallId": "bash-2", "toolName": "bash_exec", "input": {"command": "wc a.md"}}}+{"id": "13-0", "data": {"type": "tool-output-available", "toolCallId": "bash-2", "output": "3 a.md", "toolName": "bash_exec", "success": true}}+{"id": "14-0", "data": {"type": "finish-step"}}+{"id": "15-0", "data": {"type": "data-status", "message": "Analyzing result…"}}+{"id": "16-0", "data": {"type": "start-step"}}+{"id": "17-0", "data": {"type": "text-start", "id": "00000000-0000-4000-8000-000000000002"}}+{"id": "18-0", "data": {"type": "text-delta", "id": "00000000-0000-4000-8000-000000000002", "delta": "One file, three lines."}}+{"id": "19-0", "data": {"type": "text-end", "id": "00000000-0000-4000-8000-000000000002"}}+{"id": "20-0", "data": {"type": "finish-step"}}+{"id": "21-0", "data": {"type": "data-checkpoint", "rows": 5, "sequence": 1, "digest": "3eb6f34443eff2670c7a01b27df87e04347fa85372f65fbff5dd5684eb693fe4"}}+{"id": "22-0", "data": {"type": "finish"}}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-consecutive-tools-turn/frames.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-consecutive-tools-turn/frames.jsonlnew file mode 100644index 0000000000..d91cb814ba--- /dev/null+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-consecutive-tools-turn/frames.jsonl@@ -0,0 +1,22 @@+{"id": "1-0", "sse": "id: drift-turn:1-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Message received\\u2026\"}}\n\n"}+{"id": "2-0", "sse": "id: drift-turn:2-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Setting up your environment\\u2026\"}}\n\n"}+{"id": "3-0", "sse": "id: drift-turn:3-0\ndata: {\"type\": \"start\", \"messageId\": \"00000000-0000-4000-8000-000000000001\"}\n\n"}+{"id": "4-0", "sse": "id: drift-turn:4-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "5-0", "sse": "id: drift-turn:5-0\ndata: {\"type\":\"tool-input-start\",\"toolCallId\":\"bash-1\",\"toolName\":\"bash_exec\"}\n\n"}+{"id": "6-0", "sse": "id: drift-turn:6-0\ndata: {\"type\":\"tool-input-available\",\"toolCallId\":\"bash-1\",\"toolName\":\"bash_exec\",\"input\":{\"command\":\"ls\"}}\n\n"}+{"id": "7-0", "sse": "id: drift-turn:7-0\ndata: {\"type\": \"tool-output-available\", \"toolCallId\": \"bash-1\", \"output\": \"a.md\"}\n\n"}+{"id": "8-0", "sse": "id: drift-turn:8-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "9-0", "sse": "id: drift-turn:9-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Analyzing result\\u2026\"}}\n\n"}+{"id": "10-0", "sse": "id: drift-turn:10-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "11-0", "sse": "id: drift-turn:11-0\ndata: {\"type\":\"tool-input-start\",\"toolCallId\":\"bash-2\",\"toolName\":\"bash_exec\"}\n\n"}+{"id": "12-0", "sse": "id: drift-turn:12-0\ndata: {\"type\":\"tool-input-available\",\"toolCallId\":\"bash-2\",\"toolName\":\"bash_exec\",\"input\":{\"command\":\"wc a.md\"}}\n\n"}+{"id": "13-0", "sse": "id: drift-turn:13-0\ndata: {\"type\": \"tool-output-available\", \"toolCallId\": \"bash-2\", \"output\": \"3 a.md\"}\n\n"}+{"id": "14-0", "sse": "id: drift-turn:14-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "15-0", "sse": "id: drift-turn:15-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Analyzing result\\u2026\"}}\n\n"}+{"id": "16-0", "sse": "id: drift-turn:16-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "17-0", "sse": "id: drift-turn:17-0\ndata: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}+{"id": "18-0", "sse": "id: drift-turn:18-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"One file, three lines.\"}\n\n"}+{"id": "19-0", "sse": "id: drift-turn:19-0\ndata: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}+{"id": "20-0", "sse": "id: drift-turn:20-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "21-0", "sse": "id: drift-turn:21-0\ndata: {\"type\": \"data-checkpoint\", \"data\": {\"rows\": 5, \"sequence\": 1, \"digest\": \"3eb6f34443eff2670c7a01b27df87e04347fa85372f65fbff5dd5684eb693fe4\"}, \"transient\": true}\n\n"}+{"id": "22-0", "sse": "id: drift-turn:22-0\ndata: {\"type\":\"finish\"}\n\n"}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-consecutive-tools-turn/rows.json b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-consecutive-tools-turn/rows.jsonnew file mode 100644index 0000000000..7df8d5cd41--- /dev/null+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-consecutive-tools-turn/rows.json@@ -0,0 +1,128 @@+[+ {+ "id": "row-0",+ "role": "user",+ "content": "Count the files, then the lines",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 0,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:00Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-1",+ "role": "assistant",+ "content": "",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": [+ {+ "id": "bash-1",+ "type": "function",+ "function": {+ "name": "bash_exec",+ "arguments": "{\"command\": \"ls\"}"+ }+ }+ ],+ "function_call": null,+ "sequence": 1,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:01Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-2",+ "role": "tool",+ "content": "a.md",+ "name": "bash_exec",+ "tool_call_id": "bash-1",+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 2,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:02Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-3",+ "role": "assistant",+ "content": "",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": [+ {+ "id": "bash-2",+ "type": "function",+ "function": {+ "name": "bash_exec",+ "arguments": "{\"command\": \"wc a.md\"}"+ }+ }+ ],+ "function_call": null,+ "sequence": 3,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:03Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-4",+ "role": "tool",+ "content": "3 a.md",+ "name": "bash_exec",+ "tool_call_id": "bash-2",+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 4,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:04Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-5",+ "role": "assistant",+ "content": "One file, three lines.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 5,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:05Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ }+]diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-late-tool-result/entries.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-late-tool-result/entries.jsonlindex 8d8b6d23b1..43ceeff7fd 100644--- a/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-late-tool-result/entries.jsonl+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-late-tool-result/entries.jsonl@@ -22,4 +22,5 @@{"id": "22-0", "data": {"type": "text-delta", "id": "00000000-0000-4000-8000-000000000003", "delta": "All done: report.md is ready."}}{"id": "23-0", "data": {"type": "text-end", "id": "00000000-0000-4000-8000-000000000003"}}{"id": "24-0", "data": {"type": "finish-step"}}-{"id": "25-0", "data": {"type": "finish"}}+{"id": "25-0", "data": {"type": "data-checkpoint", "rows": 5, "sequence": 1, "digest": "cc045d23143efbfa3f8a417f0fc6a97c18d55ce2792b263eb7067d9974daeead"}}+{"id": "26-0", "data": {"type": "finish"}}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-late-tool-result/frames.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-late-tool-result/frames.jsonlindex 7eb60c038d..2a8849540b 100644--- a/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-late-tool-result/frames.jsonl+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-late-tool-result/frames.jsonl@@ -1,25 +1,26 @@-{"id": "1-0", "sse": "data: {\"type\": \"data-status\", \"data\": {\"message\": \"Message received\\u2026\"}}\n\n"}-{"id": "2-0", "sse": "data: {\"type\": \"data-status\", \"data\": {\"message\": \"Setting up your environment\\u2026\"}}\n\n"}-{"id": "3-0", "sse": "data: {\"type\": \"start\", \"messageId\": \"00000000-0000-4000-8000-000000000001\"}\n\n"}-{"id": "4-0", "sse": "data: {\"type\":\"start-step\"}\n\n"}-{"id": "5-0", "sse": "data: {\"type\":\"tool-input-start\",\"toolCallId\":\"task-1\",\"toolName\":\"TaskOutput\"}\n\n"}-{"id": "6-0", "sse": "data: {\"type\":\"tool-input-available\",\"toolCallId\":\"task-1\",\"toolName\":\"TaskOutput\",\"input\":{}}\n\n"}-{"id": "7-0", "sse": "data: {\"type\": \"tool-output-available\", \"toolCallId\": \"task-1\", \"output\": \"\"}\n\n"}-{"id": "8-0", "sse": "data: {\"type\":\"finish-step\"}\n\n"}-{"id": "9-0", "sse": "data: {\"type\":\"start-step\"}\n\n"}-{"id": "10-0", "sse": "data: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}-{"id": "11-0", "sse": "data: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"The task finished.\"}\n\n"}-{"id": "12-0", "sse": "data: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}-{"id": "13-0", "sse": "data: {\"type\":\"finish-step\"}\n\n"}-{"id": "14-0", "sse": "data: {\"type\":\"start-step\"}\n\n"}-{"id": "15-0", "sse": "data: {\"type\":\"tool-input-start\",\"toolCallId\":\"bash-1\",\"toolName\":\"bash_exec\"}\n\n"}-{"id": "16-0", "sse": "data: {\"type\":\"tool-input-available\",\"toolCallId\":\"bash-1\",\"toolName\":\"bash_exec\",\"input\":{\"command\":\"ls\"}}\n\n"}-{"id": "17-0", "sse": "data: {\"type\": \"tool-output-available\", \"toolCallId\": \"bash-1\", \"output\": \"report.md\"}\n\n"}-{"id": "18-0", "sse": "data: {\"type\":\"finish-step\"}\n\n"}-{"id": "19-0", "sse": "data: {\"type\": \"data-status\", \"data\": {\"message\": \"Analyzing result\\u2026\"}}\n\n"}-{"id": "20-0", "sse": "data: {\"type\":\"start-step\"}\n\n"}-{"id": "21-0", "sse": "data: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000003\"}\n\n"}-{"id": "22-0", "sse": "data: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000003\",\"delta\":\"All done: report.md is ready.\"}\n\n"}-{"id": "23-0", "sse": "data: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000003\"}\n\n"}-{"id": "24-0", "sse": "data: {\"type\":\"finish-step\"}\n\n"}-{"id": "25-0", "sse": "data: {\"type\":\"finish\"}\n\n"}+{"id": "1-0", "sse": "id: drift-turn:1-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Message received\\u2026\"}}\n\n"}+{"id": "2-0", "sse": "id: drift-turn:2-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Setting up your environment\\u2026\"}}\n\n"}+{"id": "3-0", "sse": "id: drift-turn:3-0\ndata: {\"type\": \"start\", \"messageId\": \"00000000-0000-4000-8000-000000000001\"}\n\n"}+{"id": "4-0", "sse": "id: drift-turn:4-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "5-0", "sse": "id: drift-turn:5-0\ndata: {\"type\":\"tool-input-start\",\"toolCallId\":\"task-1\",\"toolName\":\"TaskOutput\"}\n\n"}+{"id": "6-0", "sse": "id: drift-turn:6-0\ndata: {\"type\":\"tool-input-available\",\"toolCallId\":\"task-1\",\"toolName\":\"TaskOutput\",\"input\":{}}\n\n"}+{"id": "7-0", "sse": "id: drift-turn:7-0\ndata: {\"type\": \"tool-output-available\", \"toolCallId\": \"task-1\", \"output\": \"\"}\n\n"}+{"id": "8-0", "sse": "id: drift-turn:8-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "9-0", "sse": "id: drift-turn:9-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "10-0", "sse": "id: drift-turn:10-0\ndata: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}+{"id": "11-0", "sse": "id: drift-turn:11-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"The task finished.\"}\n\n"}+{"id": "12-0", "sse": "id: drift-turn:12-0\ndata: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}+{"id": "13-0", "sse": "id: drift-turn:13-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "14-0", "sse": "id: drift-turn:14-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "15-0", "sse": "id: drift-turn:15-0\ndata: {\"type\":\"tool-input-start\",\"toolCallId\":\"bash-1\",\"toolName\":\"bash_exec\"}\n\n"}+{"id": "16-0", "sse": "id: drift-turn:16-0\ndata: {\"type\":\"tool-input-available\",\"toolCallId\":\"bash-1\",\"toolName\":\"bash_exec\",\"input\":{\"command\":\"ls\"}}\n\n"}+{"id": "17-0", "sse": "id: drift-turn:17-0\ndata: {\"type\": \"tool-output-available\", \"toolCallId\": \"bash-1\", \"output\": \"report.md\"}\n\n"}+{"id": "18-0", "sse": "id: drift-turn:18-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "19-0", "sse": "id: drift-turn:19-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Analyzing result\\u2026\"}}\n\n"}+{"id": "20-0", "sse": "id: drift-turn:20-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "21-0", "sse": "id: drift-turn:21-0\ndata: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000003\"}\n\n"}+{"id": "22-0", "sse": "id: drift-turn:22-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000003\",\"delta\":\"All done: report.md is ready.\"}\n\n"}+{"id": "23-0", "sse": "id: drift-turn:23-0\ndata: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000003\"}\n\n"}+{"id": "24-0", "sse": "id: drift-turn:24-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "25-0", "sse": "id: drift-turn:25-0\ndata: {\"type\": \"data-checkpoint\", \"data\": {\"rows\": 5, \"sequence\": 1, \"digest\": \"cc045d23143efbfa3f8a417f0fc6a97c18d55ce2792b263eb7067d9974daeead\"}, \"transient\": true}\n\n"}+{"id": "26-0", "sse": "id: drift-turn:26-0\ndata: {\"type\":\"finish\"}\n\n"}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-late-tool-result/rows.json b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-late-tool-result/rows.jsonindex d2b9cb747f..fd86ea29b6 100644--- a/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-late-tool-result/rows.json+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-late-tool-result/rows.json@@ -14,7 +14,7 @@"model": null,"llm_auth_provider": null,"llm_credential_id": null,- "session_id": null,+ "session_id": "drift-session","metadata": null},{@@ -41,7 +41,7 @@"model": null,"llm_auth_provider": null,"llm_credential_id": null,- "session_id": null,+ "session_id": "drift-session","metadata": null},{@@ -59,7 +59,7 @@"model": null,"llm_auth_provider": null,"llm_credential_id": null,- "session_id": null,+ "session_id": "drift-session","metadata": null},{@@ -86,7 +86,7 @@"model": null,"llm_auth_provider": null,"llm_credential_id": null,- "session_id": null,+ "session_id": "drift-session","metadata": null},{@@ -104,7 +104,7 @@"model": null,"llm_auth_provider": null,"llm_credential_id": null,- "session_id": null,+ "session_id": "drift-session","metadata": null},{@@ -122,7 +122,7 @@"model": null,"llm_auth_provider": null,"llm_credential_id": null,- "session_id": null,+ "session_id": "drift-session","metadata": null}]diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-reasoning-turn/entries.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-reasoning-turn/entries.jsonlnew file mode 100644index 0000000000..e5dc6d0e28--- /dev/null+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-reasoning-turn/entries.jsonl@@ -0,0 +1,23 @@+{"id": "1-0", "data": {"type": "data-status", "message": "Message received…"}}+{"id": "2-0", "data": {"type": "data-status", "message": "Setting up your environment…"}}+{"id": "3-0", "data": {"type": "start", "messageId": "00000000-0000-4000-8000-000000000001", "sessionId": "drift-session"}}+{"id": "4-0", "data": {"type": "start-step"}}+{"id": "5-0", "data": {"type": "reasoning-start", "id": "00000000-0000-4000-8000-000000000002"}}+{"id": "6-0", "data": {"type": "reasoning-delta", "id": "00000000-0000-4000-8000-000000000002", "delta": "List the files first."}}+{"id": "7-0", "data": {"type": "reasoning-end", "id": "00000000-0000-4000-8000-000000000002"}}+{"id": "8-0", "data": {"type": "tool-input-start", "toolCallId": "bash-1", "toolName": "bash_exec"}}+{"id": "9-0", "data": {"type": "tool-input-available", "toolCallId": "bash-1", "toolName": "bash_exec", "input": {"command": "ls"}}}+{"id": "10-0", "data": {"type": "tool-output-available", "toolCallId": "bash-1", "output": "a.md b.py", "toolName": "bash_exec", "success": true}}+{"id": "11-0", "data": {"type": "data-pending-drained", "drainedCount": 1, "messages": [{"id": "00000000-0000-4000-8000-000000000003", "content": "Only count markdown files."}]}}+{"id": "12-0", "data": {"type": "finish-step"}}+{"id": "13-0", "data": {"type": "data-status", "message": "Analyzing result…"}}+{"id": "14-0", "data": {"type": "start-step"}}+{"id": "15-0", "data": {"type": "reasoning-start", "id": "00000000-0000-4000-8000-000000000004"}}+{"id": "16-0", "data": {"type": "reasoning-delta", "id": "00000000-0000-4000-8000-000000000004", "delta": "One markdown file."}}+{"id": "17-0", "data": {"type": "reasoning-end", "id": "00000000-0000-4000-8000-000000000004"}}+{"id": "18-0", "data": {"type": "text-start", "id": "00000000-0000-4000-8000-000000000005"}}+{"id": "19-0", "data": {"type": "text-delta", "id": "00000000-0000-4000-8000-000000000005", "delta": "There is one markdown file: a.md."}}+{"id": "20-0", "data": {"type": "text-end", "id": "00000000-0000-4000-8000-000000000005"}}+{"id": "21-0", "data": {"type": "finish-step"}}+{"id": "22-0", "data": {"type": "data-checkpoint", "rows": 6, "sequence": 1, "digest": "1d2b2f0ea8a34fb221dc8adcfb314ed001a23c0ae01c20e54113126f488af85c"}}+{"id": "23-0", "data": {"type": "finish"}}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-reasoning-turn/frames.jsonl b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-reasoning-turn/frames.jsonlnew file mode 100644index 0000000000..b1c7b5b422--- /dev/null+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-reasoning-turn/frames.jsonl@@ -0,0 +1,23 @@+{"id": "1-0", "sse": "id: drift-turn:1-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Message received\\u2026\"}}\n\n"}+{"id": "2-0", "sse": "id: drift-turn:2-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Setting up your environment\\u2026\"}}\n\n"}+{"id": "3-0", "sse": "id: drift-turn:3-0\ndata: {\"type\": \"start\", \"messageId\": \"00000000-0000-4000-8000-000000000001\"}\n\n"}+{"id": "4-0", "sse": "id: drift-turn:4-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "5-0", "sse": "id: drift-turn:5-0\ndata: {\"type\":\"reasoning-start\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}+{"id": "6-0", "sse": "id: drift-turn:6-0\ndata: {\"type\":\"reasoning-delta\",\"id\":\"00000000-0000-4000-8000-000000000002\",\"delta\":\"List the files first.\"}\n\n"}+{"id": "7-0", "sse": "id: drift-turn:7-0\ndata: {\"type\":\"reasoning-end\",\"id\":\"00000000-0000-4000-8000-000000000002\"}\n\n"}+{"id": "8-0", "sse": "id: drift-turn:8-0\ndata: {\"type\":\"tool-input-start\",\"toolCallId\":\"bash-1\",\"toolName\":\"bash_exec\"}\n\n"}+{"id": "9-0", "sse": "id: drift-turn:9-0\ndata: {\"type\":\"tool-input-available\",\"toolCallId\":\"bash-1\",\"toolName\":\"bash_exec\",\"input\":{\"command\":\"ls\"}}\n\n"}+{"id": "10-0", "sse": "id: drift-turn:10-0\ndata: {\"type\": \"tool-output-available\", \"toolCallId\": \"bash-1\", \"output\": \"a.md b.py\"}\n\n"}+{"id": "11-0", "sse": "id: drift-turn:11-0\ndata: {\"type\": \"data-pending-drained\", \"data\": {\"drainedCount\": 1, \"messages\": [{\"id\": \"00000000-0000-4000-8000-000000000003\", \"content\": \"Only count markdown files.\"}]}}\n\n"}+{"id": "12-0", "sse": "id: drift-turn:12-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "13-0", "sse": "id: drift-turn:13-0\ndata: {\"type\": \"data-status\", \"data\": {\"message\": \"Analyzing result\\u2026\"}}\n\n"}+{"id": "14-0", "sse": "id: drift-turn:14-0\ndata: {\"type\":\"start-step\"}\n\n"}+{"id": "15-0", "sse": "id: drift-turn:15-0\ndata: {\"type\":\"reasoning-start\",\"id\":\"00000000-0000-4000-8000-000000000004\"}\n\n"}+{"id": "16-0", "sse": "id: drift-turn:16-0\ndata: {\"type\":\"reasoning-delta\",\"id\":\"00000000-0000-4000-8000-000000000004\",\"delta\":\"One markdown file.\"}\n\n"}+{"id": "17-0", "sse": "id: drift-turn:17-0\ndata: {\"type\":\"reasoning-end\",\"id\":\"00000000-0000-4000-8000-000000000004\"}\n\n"}+{"id": "18-0", "sse": "id: drift-turn:18-0\ndata: {\"type\":\"text-start\",\"id\":\"00000000-0000-4000-8000-000000000005\"}\n\n"}+{"id": "19-0", "sse": "id: drift-turn:19-0\ndata: {\"type\":\"text-delta\",\"id\":\"00000000-0000-4000-8000-000000000005\",\"delta\":\"There is one markdown file: a.md.\"}\n\n"}+{"id": "20-0", "sse": "id: drift-turn:20-0\ndata: {\"type\":\"text-end\",\"id\":\"00000000-0000-4000-8000-000000000005\"}\n\n"}+{"id": "21-0", "sse": "id: drift-turn:21-0\ndata: {\"type\":\"finish-step\"}\n\n"}+{"id": "22-0", "sse": "id: drift-turn:22-0\ndata: {\"type\": \"data-checkpoint\", \"data\": {\"rows\": 6, \"sequence\": 1, \"digest\": \"1d2b2f0ea8a34fb221dc8adcfb314ed001a23c0ae01c20e54113126f488af85c\"}, \"transient\": true}\n\n"}+{"id": "23-0", "sse": "id: drift-turn:23-0\ndata: {\"type\":\"finish\"}\n\n"}diff --git a/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-reasoning-turn/rows.json b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-reasoning-turn/rows.jsonnew file mode 100644index 0000000000..2231798010--- /dev/null+++ b/autogpt_platform/backend/test/fixtures/copilot_stream/sdk-reasoning-turn/rows.json@@ -0,0 +1,137 @@+[+ {+ "id": "row-0",+ "role": "user",+ "content": "What is in the repo?",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 0,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:00Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-1",+ "role": "reasoning",+ "content": "List the files first.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 1,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:01Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-2",+ "role": "assistant",+ "content": "",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": [+ {+ "id": "bash-1",+ "type": "function",+ "function": {+ "name": "bash_exec",+ "arguments": "{\"command\": \"ls\"}"+ }+ }+ ],+ "function_call": null,+ "sequence": 2,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:02Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-3",+ "role": "tool",+ "content": "a.md b.py",+ "name": "bash_exec",+ "tool_call_id": "bash-1",+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 3,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:03Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-4",+ "role": "user",+ "content": "Only count markdown files.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 4,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:04Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-5",+ "role": "reasoning",+ "content": "One markdown file.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 5,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:05Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ },+ {+ "id": "row-6",+ "role": "assistant",+ "content": "There is one markdown file: a.md.",+ "name": null,+ "tool_call_id": null,+ "refusal": null,+ "tool_calls": null,+ "function_call": null,+ "sequence": 6,+ "duration_ms": null,+ "created_at": "2026-09-30T00:00:06Z",+ "model": null,+ "llm_auth_provider": null,+ "llm_credential_id": null,+ "session_id": "drift-session",+ "metadata": null+ }+]diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/backend-sim.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/backend-sim.tsindex a7d8581110..5d3c26f6d9 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/backend-sim.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/backend-sim.ts@@ -248,9 +248,10 @@ export function turnKeepsRunning() {/** The full text of each text block the turn streamed, in order. */export function streamedTextBlocks(turn: RecordedTurn) {const blocks = new Map<string, string>();- for (const { sse } of turn.frames) {- if (!sse.startsWith("data: ")) continue;- const chunk = JSON.parse(sse.slice("data: ".length));+ for (const frame of turn.frames) {+ const data = frameData(frame);+ if (data === null) continue;+ const chunk = JSON.parse(data);if (chunk.type === "text-start") blocks.set(chunk.id, "");if (chunk.type === "text-delta") {blocks.set(chunk.id, (blocks.get(chunk.id) ?? "") + chunk.delta);@@ -260,7 +261,13 @@ export function streamedTextBlocks(turn: RecordedTurn) {}function isFinish(frame: { sse: string }) {- return frame.sse.startsWith('data: {"type":"finish"}');+ return frameData(frame)?.startsWith('{"type":"finish"}') ?? false;+}++/** The JSON on a frame's `data:` line; entry frames lead with an `id:` line. */+function frameData(frame: { sse: string }) {+ const line = frame.sse.split("\n").find((l) => l.startsWith("data: "));+ return line ? line.slice("data: ".length) : null;}function leadingUserRows(rows: Row[]) {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/stream-wire-compat.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/stream-wire-compat.test.tsnew file mode 100644index 0000000000..2fdae460a7--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/stream-wire-compat.test.ts@@ -0,0 +1,57 @@+import {+ parseJsonEventStream,+ readUIMessageStream,+ uiMessageChunkSchema,+ type UIMessage,+ type UIMessageChunk,+} from "ai";+import { describe, expect, it } from "vitest";+import { loadRecordedTurn } from "./backend-sim";++// The backend's resume ids and checkpoints ship before the client reads them,+// so the AI SDK parser the chat runs today must build the same message+// without them.+describe("the recorded turns through the AI SDK's own parser", () => {+ it.each([+ "dummy-text-turn",+ "baseline-tool-turn",+ "sdk-late-tool-result",+ "baseline-drain-turn",+ "sdk-reasoning-turn",+ "sdk-auto-continue-turn",+ "baseline-consecutive-tools-turn",+ "sdk-consecutive-tools-turn",+ ])("%s: entry ids and the checkpoint change nothing", async (name) => {+ const { frames } = loadRecordedTurn(name);+ const bare = frames+ .filter(({ sse }) => !sse.includes('"type": "data-checkpoint"'))+ .map(({ sse }) => sse.replace(/^id: .*\n/, ""));++ expect(bare.length).toBeLessThan(frames.length);+ const dataFrames = frames.filter(({ sse }) => !sse.startsWith(":"));+ expect(dataFrames.every(({ sse }) => sse.startsWith("id: "))).toBe(true);+ expect(await finalMessage(frames.map(({ sse }) => sse))).toEqual(+ await finalMessage(bare),+ );+ });+});++async function finalMessage(sse: string[]) {+ const body = new Response(sse.join("") + "data: [DONE]\n\n").body!;+ const chunks = parseJsonEventStream({+ stream: body,+ schema: uiMessageChunkSchema,+ }).pipeThrough(+ new TransformStream({+ transform(parsed, controller) {+ if (!parsed.success) throw parsed.error;+ controller.enqueue(parsed.value as UIMessageChunk);+ },+ }),+ );+ let last: UIMessage | undefined;+ for await (const message of readUIMessageStream({ stream: chunks })) {+ last = message;+ }+ return last;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/tool-row-render.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/tool-row-render.test.tsnew file mode 100644index 0000000000..a2cbebb307--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/drift/tool-row-render.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from "vitest";+import { convertChatSessionMessagesToUiMessages } from "../../helpers/convertChatSessionToUiMessages";+import { loadRecordedTurn, type Row } from "./backend-sim";++// The SDK engine used to add a tool call that follows a tool result to the+// earlier assistant row; it now opens a row for it, as the baseline always+// did. A reload must draw the same bubble from either shape.+describe("a tool call after a tool result, on reload", () => {+ it("renders the same whether it has its own row or joins the earlier one", () => {+ const rows = loadRecordedTurn("sdk-consecutive-tools-turn").rows;+ const [prompt, firstCall, firstResult, secondCall, ...rest] = rows;+ const joined: Row[] = [+ prompt,+ {+ ...firstCall,+ tool_calls: [+ ...(firstCall.tool_calls as unknown[]),+ ...(secondCall.tool_calls as unknown[]),+ ],+ },+ firstResult,+ ...rest,+ ];++ expect(render(rows)).toEqual(render(joined));+ expect(render(rows).map((message) => message.role)).toEqual([+ "user",+ "assistant",+ ]);+ });+});++function render(rows: Row[]) {+ return convertChatSessionMessagesToUiMessages("drift-session", rows, {+ isComplete: true,+ }).messages.map(({ role, parts }) => ({ role, parts }));+}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 35fccb7398..01ed36ebd4 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -4735,7 +4735,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\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.",+ "description": "Resume a session's stream.\n\nWith ``turn``, serves exactly that turn's stored entries after ``after``\n(``0-0`` for all of them) and then its live ones: 409 when entries after\nthe cursor were trimmed, 410 when the stream is gone. Every entry frame\ncarries ``id: <turn>:<entry>``.\n\nWithout ``turn``, replays the active turn from ``0-0``, or returns 204\nwhen nothing is running: the AI SDK's parser cannot continue a block it\ndid not see start.","operationId": "getV2ResumeSessionStream","security": [{ "HTTPBearerJWT": [] }],"parameters": [@@ -4744,6 +4744,30 @@"in": "path","required": true,"schema": { "type": "string", "title": "Session Id" }+ },+ {+ "name": "turn",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "description": "Turn to read; with it, only its stored entries",+ "title": "Turn"+ },+ "description": "Turn to read; with it, only its stored entries"+ },+ {+ "name": "after",+ "in": "query",+ "required": false,+ "schema": {+ "type": "string",+ "pattern": "^\\d+-\\d+$",+ "description": "Stream entry id the client last applied",+ "default": "0-0",+ "title": "After"+ },+ "description": "Stream entry id the client last applied"}],"responses": {@@ -4754,6 +4778,22 @@"401": {"$ref": "#/components/responses/HTTP401NotAuthenticatedError"},+ "409": {+ "description": "Cursor was trimmed",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/StreamResumeRefusal" }+ }+ }+ },+ "410": {+ "description": "Stream expired",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/StreamResumeRefusal" }+ }+ }+ },"422": {"description": "Validation Error","content": {@@ -17404,6 +17444,12 @@"started_at": {"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Started At"+ },+ "checkpoint": {+ "anyOf": [+ { "$ref": "#/components/schemas/TurnCheckpoint" },+ { "type": "null" }+ ]}},"type": "object",@@ -30593,6 +30639,25 @@"title": "StreamChatRequest","description": "Request model for streaming chat with optional context."},+ "StreamResumeRefusal": {+ "properties": {+ "reason": {+ "type": "string",+ "enum": ["trimmed", "expired"],+ "title": "Reason"+ },+ "checkpoint": {+ "anyOf": [+ { "$ref": "#/components/schemas/TurnCheckpoint" },+ { "type": "null" }+ ]+ }+ },+ "type": "object",+ "required": ["reason"],+ "title": "StreamResumeRefusal",+ "description": "Why a resume at a cursor cannot be served from the stream."+ },"SubmissionStats": {"properties": {"total": { "type": "integer", "title": "Total" },@@ -32039,6 +32104,17 @@"required": ["name", "graph_id", "graph_version", "trigger_config"],"title": "TriggeredPresetSetupRequest"},+ "TurnCheckpoint": {+ "properties": {+ "entry_id": { "type": "string", "title": "Entry Id" },+ "rows": { "type": "integer", "title": "Rows" },+ "sequence": { "type": "integer", "title": "Sequence" }+ },+ "type": "object",+ "required": ["entry_id", "rows", "sequence"],+ "title": "TurnCheckpoint",+ "description": "Where a turn's last ``data-checkpoint`` sits in its stream."+ },"UnderstandingUpdatedResponse": {"properties": {"type": {