AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(backend/copilot): close the open text part before any event that clears the frontend's active parts (#14762)
Reinier van der Leer27d48c2f72c6
diff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.pyindex 21ba36dcd6..1fae4c59c2 100644--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py@@ -475,10 +475,7 @@ class SDKResponseAdapter:# Close the current step after tool results — the next# AssistantMessage will open a new step for the continuation.- if self.step_open:- self._end_reasoning_if_open(responses)- responses.append(StreamFinishStep())- self.step_open = False+ self._finish_step(responses)# Narrate the gap between "tool returned" and "model emits its# next chunk". Usually sub-second, but with large tool outputs@@ -505,9 +502,7 @@ class SDKResponseAdapter:# content; with subtype=error the service layer never persists# a marker so the chat history just stops mid-task).if self._should_surface_empty_completion(sdk_message, had_orphan_tool_use):- if self.step_open:- responses.append(StreamFinishStep())- self.step_open = False+ self._finish_step(responses)responses.append(StreamError(errorText="The model returned an empty response.",@@ -555,11 +550,8 @@ class SDKResponseAdapter:# placeholder.if not self.thinking_only_reprompted:self.pending_thinking_only_reprompt = True- self._end_text_if_open(responses)- self._end_reasoning_if_open(responses)- if self.step_open:- responses.append(StreamFinishStep())- self.step_open = False+ self.end_open_blocks(responses)+ self._finish_step(responses)return responses# UserMessage (tool_result) closed the last step, so we must# open a fresh one before emitting any text — the AI SDK v5@@ -587,12 +579,9 @@ class SDKResponseAdapter:delta=fallback_text,))- self._end_text_if_open(responses)- self._end_reasoning_if_open(responses)+ self.end_open_blocks(responses)# Close the step before finishing.- if self.step_open:- responses.append(StreamFinishStep())- self.step_open = False+ self._finish_step(responses)if sdk_message.subtype == "success":responses.append(StreamFinish())@@ -791,6 +780,25 @@ class SDKResponseAdapter:responses.append(StreamReasoningEnd(id=self.reasoning_block_id))self.has_ended_reasoning = True+ def end_open_blocks(self, responses: list[StreamBaseResponse]) -> None:+ """End any open text and reasoning block.++ Runs before every event that clears the frontend's active parts —+ the adapter's own ``StreamFinishStep`` and the ones the service emits+ (compaction rows). An end that arrives after ``finish-step`` has+ nothing to close and fails the whole turn in the AI SDK.+ """+ self._end_text_if_open(responses)+ self._end_reasoning_if_open(responses)++ def _finish_step(self, responses: list[StreamBaseResponse]) -> None:+ """Close the open step, ending any open block first."""+ if not self.step_open:+ return+ self.end_open_blocks(responses)+ responses.append(StreamFinishStep())+ self.step_open = False+# ------------------------------------------------------------------# Partial-message streaming (CHAT_SDK_INCLUDE_PARTIAL_MESSAGES)# ------------------------------------------------------------------@@ -1096,9 +1104,7 @@ class SDKResponseAdapter:# the fallback synthesis if the model then produced no text.self._text_since_last_tool_result = Falseself._any_tool_results_seen = True- if self.step_open:- responses.append(StreamFinishStep())- self.step_open = False+ self._finish_step(responses)def _extract_tool_output(content: str | list[dict[str, str]] | None) -> str:diff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.pyindex 2eb1b7a608..d549452b27 100644--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py@@ -23,6 +23,7 @@ from backend.copilot.response_model import (StreamHeartbeat,StreamReasoningDelta,StreamReasoningEnd,+ StreamReasoningStart,StreamStart,StreamStartStep,StreamStatus,@@ -2272,3 +2273,109 @@ def test_error_max_turns_surfaces_specific_error():err = next((r for r in results if isinstance(r, StreamError)), None)assert err is not Noneassert err.code == "max_turns_exhausted"+++# -- Every finish-step closes the blocks it would strand -----------------------+++def _assert_blocks_end_before_finish_step(events: list[StreamBaseResponse]) -> None:+ """The AI SDK drops active text/reasoning parts on ``finish-step``; an+ end arriving after that fails the turn. Walk the wire order and check+ every start has its end before the next StreamFinishStep."""+ open_ids: set[str] = set()+ for i, ev in enumerate(events):+ if isinstance(ev, (StreamTextStart, StreamReasoningStart)):+ open_ids.add(ev.id)+ elif isinstance(ev, (StreamTextEnd, StreamReasoningEnd)):+ assert ev.id in open_ids, f"event {i}: end for unopened block {ev.id}"+ open_ids.discard(ev.id)+ elif isinstance(ev, StreamFinishStep):+ assert not open_ids, f"event {i}: finish-step with open blocks {open_ids}"+ assert not open_ids, f"stream ended with open blocks {open_ids}"+++def test_late_tool_result_after_text_ends_text_before_finish_step():+ """Replay of Dev session c68992f9 at 08:25:12Z on 2026-09-21.++ The CLI ran ``TaskOutput`` internally and delivered its tool_result late.+ The next AssistantMessage (text only) flushed the orphan and opened a+ text block; the late UserMessage then closed the step. That finish-step+ must be preceded by the text-end, or the frontend rejects the text-end+ the next tool call emits with "text-end for missing text part".+ """+ adapter = _adapter()+ adapter.convert_message(SystemMessage(subtype="init", data={}))+ adapter.convert_message(+ AssistantMessage(+ content=[ToolUseBlock(id="task-1", name="TaskOutput", input={})],+ model="test",+ )+ )+ events: list[StreamBaseResponse] = []+ events += adapter.convert_message(+ AssistantMessage(content=[TextBlock(text="The task finished.")], model="test")+ )+ events += adapter.convert_message(+ UserMessage(content=[ToolResultBlock(tool_use_id="task-1", content="late")])+ )+ events += adapter.convert_message(+ AssistantMessage(+ content=[ToolUseBlock(id="bash-1", name="bash_exec", input={})],+ model="test",+ )+ )++ _assert_blocks_end_before_finish_step(events)+ text_end = next(i for i, e in enumerate(events) if isinstance(e, StreamTextEnd))+ step_close = next(+ i+ for i, e in enumerate(events)+ if isinstance(e, StreamFinishStep) and i > text_end - 2+ )+ assert text_end < step_close+++def test_result_message_flush_ends_open_reasoning_before_finish_step():+ """The ResultMessage flush of an orphan tool_use closes the step; a+ reasoning block opened by the partial stream must end before it."""+ adapter = _adapter()+ adapter.convert_message(SystemMessage(subtype="init", data={}))+ adapter.convert_message(+ AssistantMessage(+ content=[ToolUseBlock(id="fetch-1", name="web_fetch", input={})],+ model="test",+ )+ )+ events: list[StreamBaseResponse] = []+ events += adapter.convert_message(_message_start())+ events += adapter.convert_message(+ _stream_event(+ {+ "type": "content_block_start",+ "index": 0,+ "content_block": {"type": "thinking", "thinking": ""},+ }+ )+ )+ events += adapter.convert_message(+ _stream_event(+ {+ "type": "content_block_delta",+ "index": 0,+ "delta": {"type": "thinking_delta", "thinking": "hmm " * 20},+ }+ )+ )+ events += adapter.convert_message(+ ResultMessage(+ subtype="success",+ duration_ms=1,+ duration_api_ms=1,+ is_error=False,+ num_turns=1,+ session_id="session-1",+ result="done",+ )+ )++ _assert_blocks_end_before_finish_step(events)diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.pyindex 1ee3ab8751..c17ef7481f 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py@@ -707,13 +707,10 @@ async def _consume_sdk_until_done(measured, compacted, end_stats = await _measure_sdk_compaction(ctx, state)compact_result = await ctx.compaction.emit_end_if_ready(ctx.session, end_stats)if compact_result.events:- # Compaction events end with StreamFinishStep, which maps to- # Vercel AI SDK's "finish-step" — that clears activeTextParts.- # Close any open text block BEFORE the compaction events so- # the text-end arrives before finish-step, preventing- # "text-end for missing text part" errors on the frontend.+ # Compaction events end with StreamFinishStep; open blocks must+ # close before it (see ``SDKResponseAdapter.end_open_blocks``).pre_close: list[StreamBaseResponse] = []- state.adapter._end_text_if_open(pre_close)+ state.adapter.end_open_blocks(pre_close)# Compaction events bypass the adapter, so sync step state# when a StreamFinishStep is present — otherwise the adapter# will skip StreamStartStep on the next AssistantMessage.@@ -4231,7 +4228,7 @@ async def _run_stream_attempt(ctx.log_prefix,)closing_responses: list[StreamBaseResponse] = []- state.adapter._end_text_if_open(closing_responses)+ state.adapter.end_open_blocks(closing_responses)for r in closing_responses:yield rnotice_block_id = str(uuid.uuid4())@@ -5896,7 +5893,7 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssuesprovider_failure = _provider_failure_for(stream_ctx)cleanup_events: list[StreamBaseResponse] = []if state is not None:- state.adapter._end_text_if_open(cleanup_events)+ state.adapter.end_open_blocks(cleanup_events)cleanup_events.extend(interrupted.finalize(session,