Skip to content

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

fix(backend/copilot): persist visible marker when SDK turn ends with empty content / error (#13052)

Zamil Majdy6bda1ced58d1
diff --git a/autogpt_platform/backend/backend/copilot/constants.py b/autogpt_platform/backend/backend/copilot/constants.py
index 20b0eff09e..643df99758 100644
--- a/autogpt_platform/backend/backend/copilot/constants.py
+++ b/autogpt_platform/backend/backend/copilot/constants.py
@@ -20,6 +20,13 @@ STOPPED_BY_USER_MARKER = f"{COPILOT_SYSTEM_PREFIX} Execution stopped by user"
# ``asyncio.CancelledError`` and never reaches this branch.
STREAM_INCOMPLETE_MARKER = f"{COPILOT_SYSTEM_PREFIX} Reached the per-query spend limit or the assistant ended without a final response. Send a follow-up message to continue from here."
+# SECRT-2333: surfaced when the SDK turn ends with ``ended_with_stream_error``
+# (subtype=error ResultMessage, idle timeout, transient retries exhausted,
+# circuit breaker) and no marker row has been persisted yet. Without this,
+# the on-wire StreamError dies with the SSE connection and a chat reload sees
+# the history just stopping mid-task.
+STREAM_ERROR_MARKER = f"{COPILOT_SYSTEM_PREFIX} The assistant ran into an error and stopped. Send a follow-up message to retry."
+
# Prefix for all synthetic IDs generated by CoPilot block execution.
# Used to distinguish CoPilot-generated records from real graph execution records
# in PendingHumanReview and other tables.
diff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py
index 35bba66573..2e7a30d848 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py
@@ -108,6 +108,18 @@ class SDKResponseAdapter:
# answer into thinking, so we promote it to text rather than show
# the bare placeholder.
self._last_thinking_content = ""
+ # SECRT-2333: True when the most recent ``AssistantMessage`` carried
+ # zero content blocks (``content == []``). Combined with the
+ # orphan-tool_use snapshot at ResultMessage time, lets the empty-
+ # completion guard fire when the model planned a tool call, the tool
+ # never executed, and the model then returned no further content.
+ self._last_assistant_had_empty_content = False
+ # SECRT-2333: True if the turn ever invoked ``flush_unresolved_tool_calls``
+ # against a non-empty pending-tool set (i.e. a ``tool_use`` block was
+ # registered without a matching ``UserMessage`` tool_result, and we
+ # had to synthesise the result). Distinct from ``_any_tool_results_seen``
+ # which also flips on real UserMessage tool_results.
+ self._any_orphan_flush_seen = False
# --- Partial-message streaming state (CHAT_SDK_INCLUDE_PARTIAL_MESSAGES)
# When ``include_partial_messages=True`` is set on
# ``ClaudeAgentOptions``, the CLI emits raw Anthropic streaming
@@ -173,6 +185,10 @@ class SDKResponseAdapter:
self._handle_stream_event(sdk_message, responses)
elif isinstance(sdk_message, AssistantMessage):
+ # Track empty-content AssistantMessages separately from the
+ # tool-only check below — ``all([])`` is True so an empty
+ # ``content`` list reads as "tool-only" but produced no events.
+ self._last_assistant_had_empty_content = not sdk_message.content
# Flush any SDK built-in tool calls that didn't get a UserMessage
# result (e.g. WebSearch, Read handled internally by the CLI).
# BUT skip flush when this AssistantMessage is a parallel tool
@@ -404,11 +420,22 @@ class SDKResponseAdapter:
responses.append(StreamStatus(message="Analyzing result\u2026"))
elif isinstance(sdk_message, ResultMessage):
+ # Snapshot orphan-tool_use state BEFORE flush — flush adds those
+ # tool_use IDs to ``resolved_tool_calls`` (with empty/stashed
+ # output), so by the time ``_is_empty_completion`` runs the
+ # "tool_use without tool_result" signal is gone.
+ had_orphan_tool_use = self.has_unresolved_tool_calls
self.flush_unresolved_tool_calls(responses)
- # SECRT-2252: surface ghost-finished sessions as errors instead of silent finishes.
- if sdk_message.subtype == "success" and self._is_empty_completion(
- sdk_message
- ):
+ # SECRT-2252 / SECRT-2333: surface ghost-finished sessions as
+ # errors instead of silent finishes. Two failure modes:
+ # 1) success ResultMessage with empty result and zero output_tokens
+ # (the original SECRT-2252 ghost-finish case)
+ # 2) AssistantMessage emitted ``content: []`` after a ``tool_use``
+ # whose tool never executed (SECRT-2333 — model planned a tool
+ # call, the tool failed to run, then the model returned empty
+ # 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
@@ -425,9 +452,12 @@ class SDKResponseAdapter:
# marker.
responses.append(StreamFinish())
logger.warning(
- "[SDK] [%s] Empty-success ResultMessage detected — "
- "emitting stream error instead of silent finish",
+ "[SDK] [%s] Empty completion detected (subtype=%s, "
+ "orphan_tool_use=%s) — emitting stream error instead "
+ "of silent finish",
(self.session_id or "?")[:12],
+ sdk_message.subtype,
+ had_orphan_tool_use,
)
return responses
# Thinking-only final turn guard: when the model's last LLM
@@ -516,6 +546,46 @@ class SDKResponseAdapter:
return responses
+ def _should_surface_empty_completion(
+ self,
+ msg: ResultMessage,
+ had_orphan_tool_use_at_result: bool,
+ ) -> bool:
+ """True when the turn ended with no user-visible content the wire
+ can render.
+
+ Two failure modes:
+
+ * **Ghost-finished success** (SECRT-2252): a ``subtype="success"``
+ ResultMessage whose ``result`` is empty, ``output_tokens == 0``,
+ and nothing was emitted this turn — the SDK silently ended a turn
+ with no answer. ``_is_empty_completion`` covers this.
+ * **Orphan tool_use + empty AssistantMessage** (SECRT-2333): the
+ model emitted a ``tool_use`` block whose tool never produced a
+ ``tool_result`` (tool failed to execute, or the SDK skipped it),
+ then returned an AssistantMessage with ``content: []`` and a
+ ResultMessage with ``subtype="error"``. Without surfacing this as
+ a stream error, ``_dispatch_response`` never appends an error
+ marker (the StreamFinish from the success branch flips
+ ``acc.stream_completed=True``) and the chat history just stops
+ mid-task on reload.
+
+ ``had_orphan_tool_use_at_result`` is the snapshot taken just
+ before the ResultMessage's pre-flush call; ``_any_orphan_flush_seen``
+ covers the equivalent case where an interleaving AssistantMessage
+ (with non-tool content) triggered an earlier orphan flush — so by
+ the time the ResultMessage lands, ``current_tool_calls`` looks
+ fully resolved even though the actual tool_results were synthetic.
+ """
+ if msg.subtype == "success" and self._is_empty_completion(msg):
+ return True
+ had_orphan_tool_use = (
+ had_orphan_tool_use_at_result or self._any_orphan_flush_seen
+ )
+ if had_orphan_tool_use and self._last_assistant_had_empty_content:
+ return True
+ return False
+
def _is_empty_completion(self, msg: ResultMessage) -> bool:
"""True when a success ResultMessage carries no content at all.
@@ -835,6 +905,7 @@ class SDKResponseAdapter:
len(unresolved),
", ".join(f"{name}({tid[:12]})" for tid, name in unresolved),
)
+ self._any_orphan_flush_seen = True
flushed = False
for tool_id, tool_name in unresolved:
diff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py
index 3281b388e4..5c3bacbc44 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py
@@ -874,6 +874,105 @@ def test_result_error_emits_error_and_finish():
assert isinstance(results[1], StreamFinish)
+def test_result_orphan_tool_use_then_empty_assistant_emits_empty_completion():
+ """SECRT-2333: a turn that emits tool_use blocks whose tool never runs,
+ then an AssistantMessage with empty content, then a ResultMessage with
+ ``subtype='error'`` must surface as an ``empty_completion`` StreamError —
+ even when subtype is "error" (langsmith ``is_error=true`` case).
+ Without this guard the chat history just stops mid-task because the
+ empty AssistantMessage produces no events and the StreamError emitted
+ by the subtype=error branch is racy on the wire."""
+ adapter = _adapter()
+ adapter.convert_message(SystemMessage(subtype="init", data={}))
+ # Step 1: model emits 4 ToolUseBlocks (parallel browser_act calls).
+ adapter.convert_message(
+ AssistantMessage(
+ content=[
+ ToolUseBlock(
+ id=f"t{i}",
+ name=f"{MCP_TOOL_PREFIX}browser_act",
+ input={"action": "click", "selector": f"e{i}"},
+ )
+ for i in range(4)
+ ],
+ model="test",
+ )
+ )
+ # Step 2: tool never executes (no UserMessage tool_result). Model
+ # emits a thinking-only AssistantMessage trying to plan the next click.
+ adapter.convert_message(
+ AssistantMessage(
+ content=[ThinkingBlock(thinking="Planning click on e113", signature="")],
+ model="test",
+ )
+ )
+ # Step 3: model returns an AssistantMessage with empty content.
+ adapter.convert_message(AssistantMessage(content=[], model="test"))
+ # Step 4: ResultMessage with subtype="error".
+ msg = ResultMessage(
+ subtype="error",
+ duration_ms=100,
+ duration_api_ms=50,
+ is_error=True,
+ num_turns=3,
+ session_id="s1",
+ result="model returned empty content",
+ usage={"output_tokens": 0},
+ )
+ results = adapter.convert_message(msg)
+ types = [type(r).__name__ for r in results]
+ # The empty-completion guard must beat the subtype=error branch so the
+ # service-layer post-stream flow can flip ``acc.stream_completed=True``
+ # via the paired StreamFinish and the dispatched StreamError persists
+ # an error marker.
+ assert "StreamError" in types, types
+ err = next(r for r in results if isinstance(r, StreamError))
+ assert err.code == "empty_completion", err.code
+ # StreamFinish is required so ``acc.stream_completed`` flips True and
+ # the post-stream branch doesn't append a second STREAM_INCOMPLETE_MARKER.
+ assert "StreamFinish" in types, types
+
+
+def test_result_orphan_tool_use_with_thinking_only_assistant_does_not_fire():
+ """The orphan-tool-use guard must NOT fire when the final AssistantMessage
+ carried any content (e.g. just a ThinkingBlock). Without this guard the
+ thinking-only-final-turn re-prompt would never get a chance to run."""
+ adapter = _adapter()
+ adapter.convert_message(SystemMessage(subtype="init", data={}))
+ adapter.convert_message(
+ AssistantMessage(
+ content=[
+ ToolUseBlock(
+ id="t1",
+ name=f"{MCP_TOOL_PREFIX}browser_act",
+ input={},
+ )
+ ],
+ model="test",
+ )
+ )
+ # The most recent AssistantMessage has thinking — NOT empty content.
+ adapter.convert_message(
+ AssistantMessage(
+ content=[ThinkingBlock(thinking="hmm", signature="")],
+ model="test",
+ )
+ )
+ msg = ResultMessage(
+ subtype="success",
+ duration_ms=100,
+ duration_api_ms=50,
+ is_error=False,
+ num_turns=2,
+ session_id="s1",
+ result="hmm",
+ usage={"output_tokens": 5},
+ )
+ results = adapter.convert_message(msg)
+ err_codes = [r.code for r in results if isinstance(r, StreamError)]
+ assert "empty_completion" not in err_codes, err_codes
+
+
# -- Text after tools (new block ID) ----------------------------------------
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.py
index f8478aa021..51e86c1fd5 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py
@@ -51,6 +51,7 @@ from ..constants import (
COPILOT_ERROR_PREFIX,
COPILOT_RETRYABLE_ERROR_PREFIX,
FRIENDLY_TRANSIENT_MSG,
+ STREAM_ERROR_MARKER,
STREAM_INCOMPLETE_MARKER,
STREAM_LOCK_PREFIX,
is_transient_api_error,
@@ -1347,6 +1348,25 @@ def _is_error_marker(msg: ChatMessage) -> bool:
)
+def _has_trailing_marker(session: ChatSession | None) -> bool:
+ """True when the session's last message is a copilot system/error marker.
+
+ Used to guard against double-persisting markers when multiple guards
+ (StreamError dispatch, post-stream STREAM_ERROR_MARKER append, retry-loop
+ ``_append_error_marker``) fire on the same turn.
+ """
+ if session is None or not session.messages:
+ return False
+ last = session.messages[-1]
+ if last.role != "assistant" or not last.content:
+ return False
+ return (
+ _is_error_marker(last)
+ or last.content == STREAM_INCOMPLETE_MARKER
+ or last.content == STREAM_ERROR_MARKER
+ )
+
+
@dataclass
class _InterruptedAttempt:
"""Captured state of a failed SDK attempt, carried across the retry loop.
@@ -1382,10 +1402,15 @@ class _InterruptedAttempt:
Trailing error markers appended inside ``_run_stream_attempt`` (idle
timeout, circuit breaker) are stripped: re-attaching them would make
the post-loop restore replay a stale marker before adding its own,
- leaving duplicate error bubbles.
+ leaving duplicate error bubbles. ``STREAM_ERROR_MARKER`` is treated
+ the same way — the post-loop ``finalize`` calls
+ ``_append_error_marker`` which writes a fresh COPILOT_*_PREFIX row
+ with the final display message.
"""
tail = list(session.messages[pre_attempt_msg_count:])
- while tail and _is_error_marker(tail[-1]):
+ while tail and (
+ _is_error_marker(tail[-1]) or tail[-1].content == STREAM_ERROR_MARKER
+ ):
tail.pop()
self.partial = tail
session.messages = session.messages[:pre_attempt_msg_count]
@@ -3382,6 +3407,19 @@ async def _run_stream_attempt(
) and not acc.has_appended_assistant:
ctx.session.messages.append(acc.assistant_response)
+ # SECRT-2333: persist a visible-marker ChatMessage when the turn ended
+ # with ``ended_with_stream_error=True`` and no prior marker is on the
+ # tail. The on-wire StreamError dies with the SSE connection (client
+ # disconnect, network) — this row keeps the chat history honest on
+ # reload, even if the outer retry loop's ``interrupted.finalize`` later
+ # appends its own COPILOT_ERROR_PREFIX entry on the post-rollback
+ # restore. The capture/restore cycle pops trailing error markers
+ # before re-attaching, so this row is never double-rendered.
+ if loop_state.ended_with_stream_error and not _has_trailing_marker(ctx.session):
+ ctx.session.messages.append(
+ ChatMessage(role="assistant", content=STREAM_ERROR_MARKER)
+ )
+
# Raise so the outer retry loop can rollback session messages.
# already_yielded=False for transient_api_error: StreamError was NOT
# sent to the client yet (the outer loop does it when retries are
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service_test.py b/autogpt_platform/backend/backend/copilot/sdk/service_test.py
index aaa1b790e4..af0d7ebac0 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service_test.py
@@ -2051,3 +2051,101 @@ class TestStreamEndedWithoutResultMessage:
contents = [m.content for m in assistant_msgs]
assert STREAM_INCOMPLETE_MARKER in contents
assert STOPPED_BY_USER_MARKER not in contents
+
+ @pytest.mark.asyncio
+ async def test_ended_with_stream_error_persists_stream_error_marker(self):
+ """SECRT-2333: when the SDK turn ends with
+ ``loop_state.ended_with_stream_error=True`` (idle timeout, transient
+ retries exhausted, breaker, subtype=error) and no marker is on the
+ tail yet, the post-stream branch must persist a STREAM_ERROR_MARKER
+ ChatMessage so chat reload sees a clear "stopped on error" entry —
+ even when the on-wire StreamError is dropped (client disconnect)."""
+ from backend.copilot.constants import STREAM_ERROR_MARKER
+ from backend.copilot.sdk.service import _HandledStreamError, _run_stream_attempt
+
+ ctx = self._ctx()
+ state = self._state()
+
+ async def fake_consume(_client, _ctx, _state, _acc, loop_state):
+ loop_state.stream_error_msg = "Idle timeout"
+ loop_state.stream_error_code = "idle_timeout"
+ loop_state.ended_with_stream_error = True
+ if False:
+ yield None # pragma: no cover (make this an async generator)
+
+ fake_client = MagicMock()
+ fake_client.query = AsyncMock()
+ fake_sdk_client = MagicMock()
+ fake_sdk_client.__aenter__ = AsyncMock(return_value=fake_client)
+ fake_sdk_client.__aexit__ = AsyncMock(return_value=False)
+
+ with (
+ patch(
+ "backend.copilot.sdk.service.ClaudeSDKClient",
+ return_value=fake_sdk_client,
+ ),
+ patch(
+ "backend.copilot.sdk.service._consume_sdk_until_done",
+ new=fake_consume,
+ ),
+ pytest.raises(_HandledStreamError),
+ ):
+ async for _ev in _run_stream_attempt(ctx, state):
+ pass
+
+ contents = [m.content for m in ctx.session.messages]
+ assert STREAM_ERROR_MARKER in contents, contents
+
+ @pytest.mark.asyncio
+ async def test_ended_with_stream_error_skips_marker_when_one_exists(self):
+ """When the inner branch (idle timeout, breaker) already appended an
+ ``_append_error_marker`` row, the post-stream branch must NOT add a
+ second STREAM_ERROR_MARKER on top — that would render two error
+ bubbles on reload."""
+ from backend.copilot.constants import (
+ COPILOT_RETRYABLE_ERROR_PREFIX,
+ STREAM_ERROR_MARKER,
+ )
+ from backend.copilot.model import ChatMessage
+ from backend.copilot.sdk.service import _HandledStreamError, _run_stream_attempt
+
+ ctx = self._ctx()
+ state = self._state()
+
+ async def fake_consume(_client, _ctx, _state, _acc, loop_state):
+ # Mirror the idle-timeout branch: it calls ``_append_error_marker``
+ # before flipping the flag.
+ _ctx.session.messages.append(
+ ChatMessage(
+ role="assistant",
+ content=f"{COPILOT_RETRYABLE_ERROR_PREFIX} Idle timeout",
+ )
+ )
+ loop_state.stream_error_msg = "Idle timeout"
+ loop_state.stream_error_code = "idle_timeout"
+ loop_state.ended_with_stream_error = True
+ if False:
+ yield None # pragma: no cover
+
+ fake_client = MagicMock()
+ fake_client.query = AsyncMock()
+ fake_sdk_client = MagicMock()
+ fake_sdk_client.__aenter__ = AsyncMock(return_value=fake_client)
+ fake_sdk_client.__aexit__ = AsyncMock(return_value=False)
+
+ with (
+ patch(
+ "backend.copilot.sdk.service.ClaudeSDKClient",
+ return_value=fake_sdk_client,
+ ),
+ patch(
+ "backend.copilot.sdk.service._consume_sdk_until_done",
+ new=fake_consume,
+ ),
+ pytest.raises(_HandledStreamError),
+ ):
+ async for _ev in _run_stream_attempt(ctx, state):
+ pass
+
+ contents = [m.content for m in ctx.session.messages]
+ assert STREAM_ERROR_MARKER not in contents, contents
diff --git a/autogpt_platform/backend/backend/copilot/sdk/session_persistence_test.py b/autogpt_platform/backend/backend/copilot/sdk/session_persistence_test.py
index e2bdea902d..16c242acd2 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/session_persistence_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/session_persistence_test.py
@@ -19,7 +19,11 @@ from __future__ import annotations
from datetime import datetime, timezone
from unittest.mock import MagicMock
-from backend.copilot.constants import STOPPED_BY_USER_MARKER, STREAM_INCOMPLETE_MARKER
+from backend.copilot.constants import (
+ STOPPED_BY_USER_MARKER,
+ STREAM_ERROR_MARKER,
+ STREAM_INCOMPLETE_MARKER,
+)
from backend.copilot.model import ChatMessage, ChatSession
from backend.copilot.response_model import StreamStartStep, StreamTextDelta
from backend.copilot.sdk.service import _dispatch_response, _StreamAccumulator
@@ -293,6 +297,43 @@ class TestPruneOrphanToolCalls:
assert len(messages) == 1
assert messages[-1].role == "user"
+ def test_stop_strips_stream_error_marker_and_orphan(self) -> None:
+ """SECRT-2333: ``STREAM_ERROR_MARKER`` is the post-stream marker
+ appended when ``ended_with_stream_error=True``. Like the other
+ synthetic notices, it must be stripped on the next turn so it
+ doesn't leak into the ``--resume`` transcript and confuse the
+ model."""
+ messages: list[ChatMessage] = [
+ ChatMessage(role="user", content="do something"),
+ ChatMessage(
+ role="assistant",
+ content="",
+ tool_calls=[self._tool_call("tc_abc")],
+ ),
+ ChatMessage(role="assistant", content=STREAM_ERROR_MARKER),
+ ]
+
+ removed = prune_orphan_tool_calls(messages)
+
+ assert removed == 2
+ assert len(messages) == 1
+ assert messages[-1].role == "user"
+
+ def test_stream_error_marker_alone_is_stripped(self) -> None:
+ """A trailing STREAM_ERROR_MARKER without an orphan tool_use is
+ still stripped — the marker is a one-shot user-facing notice, not
+ history the next turn should resume from."""
+ messages: list[ChatMessage] = [
+ ChatMessage(role="user", content="do something"),
+ ChatMessage(role="assistant", content=STREAM_ERROR_MARKER),
+ ]
+
+ removed = prune_orphan_tool_calls(messages)
+
+ assert removed == 1
+ assert len(messages) == 1
+ assert messages[-1].role == "user"
+
def test_completed_tool_call_is_preserved(self) -> None:
"""An assistant row whose tool_calls are all resolved is a healthy
trailing state and must not be popped."""
diff --git a/autogpt_platform/backend/backend/copilot/session_cleanup.py b/autogpt_platform/backend/backend/copilot/session_cleanup.py
index dbc6ac6f3a..7c4f0f438d 100644
--- a/autogpt_platform/backend/backend/copilot/session_cleanup.py
+++ b/autogpt_platform/backend/backend/copilot/session_cleanup.py
@@ -7,7 +7,11 @@ start every new turn from a well-formed message list.
import logging
-from backend.copilot.constants import STOPPED_BY_USER_MARKER, STREAM_INCOMPLETE_MARKER
+from backend.copilot.constants import (
+ STOPPED_BY_USER_MARKER,
+ STREAM_ERROR_MARKER,
+ STREAM_INCOMPLETE_MARKER,
+)
from backend.copilot.model import ChatMessage
logger = logging.getLogger(__name__)
@@ -26,10 +30,10 @@ def prune_orphan_tool_calls(
``tool_use`` with no paired ``tool_result`` and the SDK raises a
generic error.
- Also strips trailing ``STOPPED_BY_USER_MARKER`` and
- ``STREAM_INCOMPLETE_MARKER`` assistant rows so the next turn's
- transcript starts clean — these synthetic notices must not leak into
- the next ``--resume`` turn's history.
+ Also strips trailing ``STOPPED_BY_USER_MARKER``,
+ ``STREAM_INCOMPLETE_MARKER``, and ``STREAM_ERROR_MARKER`` assistant rows
+ so the next turn's transcript starts clean — these synthetic notices
+ must not leak into the next ``--resume`` turn's history.
If *log_prefix* is given, emits an INFO log with the prefix whenever
something was actually popped so the turn-start cleanup is visible.
@@ -51,6 +55,7 @@ def prune_orphan_tool_calls(
if msg.role == "assistant" and msg.content in (
STOPPED_BY_USER_MARKER,
STREAM_INCOMPLETE_MARKER,
+ STREAM_ERROR_MARKER,
):
cut_index = i
continue