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(copilot): persist reasoning, split steps/reasoning UX, fix mid-turn promote stream stall (#12853)
Zamil Majdy70b591d74fb0
diff --git a/.claude/skills/pr-address/SKILL.md b/.claude/skills/pr-address/SKILL.mdindex cae35a170b..cb730f9ed1 100644--- a/.claude/skills/pr-address/SKILL.md+++ b/.claude/skills/pr-address/SKILL.md@@ -25,6 +25,8 @@ Understand the **Why / What / How** before addressing comments — you need contgh pr view {N} --json body --jq '.body'```+> If GraphQL is rate-limited, `gh pr view` fails. See [GitHub rate limits](#github-rate-limits) for REST fallbacks.+## Fetch comments (all sources)### 1. Inline review threads — GraphQL (primary source of actionable items)@@ -109,12 +111,16 @@ Only after this loop completes (all pages fetched, count confirmed) should you b**Filter to unresolved threads only** — skip any thread where `isResolved: true`. `comments(last: 1)` returns the most recent comment in the thread — act on that; it reflects the reviewer's final ask. Use the thread `id` (Relay global ID) to track threads across polls.+> If GraphQL is rate-limited, see [GitHub rate limits](#github-rate-limits) for the REST fallback (flat comment list — no thread grouping or `isResolved`).+### 2. Top-level reviews — REST (MUST paginate)```bashgh api repos/Significant-Gravitas/AutoGPT/pulls/{N}/reviews --paginate```+> **Already REST — unaffected by GraphQL rate limits or outages. Continue polling reviews normally even when GraphQL is exhausted.**+**CRITICAL — always `--paginate`.** Reviews default to 30 per page. PRs can have 80–170+ reviews (mostly empty resolution events). Without pagination you miss reviews past position 30 — including `autogpt-reviewer`'s structured review which is typically posted after several CI runs and sits well beyond the first page.Two things to extract:@@ -133,6 +139,8 @@ Two things to extract:gh api repos/Significant-Gravitas/AutoGPT/issues/{N}/comments --paginate```+> **Already REST — unaffected by GraphQL rate limits.**+Mostly contains: bot summaries (`coderabbitai[bot]`), CI/conflict detection (`github-actions[bot]`), and author status updates. Scan for non-empty messages from non-bot human reviewers that aren't the PR author — those are the ones that need a response.## For each unaddressed comment@@ -327,18 +335,65 @@ git push5. Restart the polling loop from the top — new commits reset CI status.-## GitHub abuse rate limits+## GitHub rate limits-Two distinct rate limits exist — they have different causes and recovery times:+Three distinct rate limits exist — they have different causes, error shapes, and recovery times:| Error | HTTP code | Cause | Recovery ||---|---|---|---|| `{"code":"abuse"}` | 403 | Secondary rate limit — too many write operations (comments, mutations) in a short window | Wait **2–3 minutes**. 60s is often not enough. |-| `{"message":"API rate limit exceeded"}` | 429 | Primary rate limit — too many API calls per hour | Wait until `X-RateLimit-Reset` header timestamp |+| `{"message":"API rate limit exceeded"}` | 429 | Primary REST rate limit — 5000 calls/hr per user | Wait until `X-RateLimit-Reset` header timestamp |+| `GraphQL: API rate limit already exceeded for user ID ...` | 403 on stderr, `gh` exits 1 | **GraphQL-specific** per-user limit — distinct from REST's 5000/hr and from the abuse secondary limit. Trips faster than REST because point costs per query. | Wait until the GraphQL window resets (typically ~1 hour from the first call in the window). REST still works — use fallbacks below. |**Prevention:** Add `sleep 3` between individual thread reply API calls. When posting >20 replies, increase to `sleep 5`.-**Recovery from secondary rate limit (403):**+### Detection++The `gh` CLI surfaces the GraphQL limit on stderr with the exact string `GraphQL: API rate limit already exceeded for user ID <id>` and exits 1 — any `gh api graphql ...` **or** `gh pr view ...` call fails. Check current quota and reset time via the REST endpoint that reports GraphQL quota (this call is REST and still works whether GraphQL is rate-limited OR fully down):++```bash+gh api rate_limit --jq '.resources.graphql' # { "limit": 5000, "used": 5000, "remaining": 0, "reset": 1729...}+# Human-readable reset:+gh api rate_limit --jq '.resources.graphql.reset' | xargs -I{} date -r {}+```++Retry when `remaining > 0`. If you need to proceed sooner, sleep 2–5 min and probe again — the limit is per user, not per machine, so other concurrent agents under the same token also consume it.++### What keeps working++When GraphQL is unavailable (rate-limited or outage):++- **Keeps working (REST):** top-level reviews fetch, conversation comments fetch, all inline-comment replies, CI status (`gh pr checks`), and the `gh api rate_limit` probe.+- **Degraded:** inline thread list — fall back to flat `/pulls/{N}/comments` REST, which drops thread grouping, `isResolved`, and Relay thread IDs. You still get comment bodies and the `databaseId` as `id`, enough to read and reply.+- **Blocked:** `gh pr view`, the `resolveReviewThread` mutation, and any new `gh api graphql` queries — wait for the quota to reset.++### Fall back to REST++**PR metadata reads** — `gh pr view` uses GraphQL under the hood; use the REST pulls endpoint instead, which returns the full PR object:++```bash+gh api repos/Significant-Gravitas/AutoGPT/pulls/{N} --jq '.body' # == --json body+gh api repos/Significant-Gravitas/AutoGPT/pulls/{N} --jq '.base.ref' # == --json baseRefName+gh api repos/Significant-Gravitas/AutoGPT/pulls/{N} --jq '.mergeable' # == --json mergeable+```++Note: REST `mergeable` returns `true|false|null`; GraphQL returns `MERGEABLE|CONFLICTING|UNKNOWN`. The `null` case maps to `UNKNOWN` — treat it the same (still computing; poll again).++**Inline comments (flat list)** — no thread grouping or `isResolved`, but enough to read and reply:++```bash+gh api repos/Significant-Gravitas/AutoGPT/pulls/{N}/comments --paginate \+ | jq '[.[] | {id, path, line, user: .user.login, body: .body[:200], in_reply_to_id}]'+```++Use this degraded mode to make progress on the fix → reply loop, then return to GraphQL for `resolveReviewThread` once the rate limit resets.++**Replies** — already REST-native (`/pulls/{N}/comments/{ID}/replies`); no change needed, use the same command as the main flow.++**`resolveReviewThread`** — **no REST equivalent**; GitHub does not expose a REST endpoint for thread resolution. Queue the thread IDs needing resolution, wait for the GraphQL limit to reset, then run the resolve mutations in a batch (with `sleep 3` between calls, per the secondary-limit guidance).++### Recovery from secondary rate limit (403 abuse)+1. Stop all API writes immediately2. Wait **2 minutes minimum** (not 60s — secondary limits are stricter)3. Resume with `sleep 3` between each call@@ -397,6 +452,8 @@ gh api graphql -f query='mutation { resolveReviewThread(input: {threadId: "THREA**Never call this mutation before committing the fix.** The orchestrator will verify actual unresolved counts via GraphQL after you output `ORCHESTRATOR:DONE` — false resolutions will be caught and you will be re-briefed.+> `resolveReviewThread` is GraphQL-only — no REST equivalent. If GraphQL is rate-limited, see [GitHub rate limits](#github-rate-limits) for the queue-and-retry flow.+### Verify actual count before outputting ORCHESTRATOR:DONEBefore claiming "0 unresolved threads", always query GitHub directly — don't rely on your own bookkeeping. Paginate all pages — a single `first: 100` query misses threads beyond page 1:diff --git a/autogpt_platform/backend/backend/copilot/baseline/service.py b/autogpt_platform/backend/backend/copilot/baseline/service.pyindex df52f38d22..4c6ad04d60 100644--- a/autogpt_platform/backend/backend/copilot/baseline/service.py+++ b/autogpt_platform/backend/backend/copilot/baseline/service.py@@ -25,7 +25,7 @@ from langfuse import propagate_attributesfrom openai.types.chat import ChatCompletionMessageParam, ChatCompletionToolParamfrom opentelemetry import trace as otel_trace-from backend.copilot.config import CopilotMode+from backend.copilot.config import CopilotLlmModel, CopilotModefrom backend.copilot.context import get_workspace_manager, set_execution_contextfrom backend.copilot.graphiti.config import is_enabled_for_userfrom backend.copilot.model import (@@ -236,17 +236,17 @@ def _filter_tools_by_permissions(]-def _resolve_baseline_model(mode: CopilotMode | None) -> str:- """Pick the model for the baseline path based on the per-request mode.+def _resolve_baseline_model(tier: CopilotLlmModel | None) -> str:+ """Pick the model for the baseline path based on the per-request tier.- Only ``mode='fast'`` downgrades to the cheaper/faster model. Any other- value (including ``None`` and ``'extended_thinking'``) preserves the- default model so that users who never select a mode don't get- silently moved to the cheaper tier.+ The baseline (fast) and SDK (extended thinking) paths now share the+ same tier-based model resolution — only the *path* differs between+ "fast" and "extended_thinking". ``'advanced'`` → Opus;+ ``'standard'`` / ``None`` → the config default (Sonnet)."""- if mode == "fast":- return config.fast_model- return config.model+ from backend.copilot.service import resolve_chat_model++ return resolve_chat_model(tier)@dataclass@@ -928,6 +928,7 @@ async def stream_chat_completion_baseline(permissions: "CopilotPermissions | None" = None,context: dict[str, str] | None = None,mode: CopilotMode | None = None,+ model: CopilotLlmModel | None = None,request_arrival_at: float = 0.0,**_kwargs: Any,) -> AsyncGenerator[StreamBaseResponse, None]:@@ -1012,9 +1013,10 @@ async def stream_chat_completion_baseline(session_id, last_user_msg.sequence, message)- # Select model based on the per-request mode. 'fast' downgrades to- # the cheaper/faster model; everything else keeps the default.- active_model = _resolve_baseline_model(mode)+ # Select model based on the per-request tier toggle (standard / advanced).+ # The path (fast vs extended_thinking) is already decided — we're in the+ # baseline (fast) path; ``mode`` is accepted for logging parity only.+ active_model = _resolve_baseline_model(model)# --- E2B sandbox setup (feature parity with SDK path) ---e2b_sandbox = Nonediff --git a/autogpt_platform/backend/backend/copilot/baseline/transcript_integration_test.py b/autogpt_platform/backend/backend/copilot/baseline/transcript_integration_test.pyindex 4247c76c19..8d6fb50a53 100644--- a/autogpt_platform/backend/backend/copilot/baseline/transcript_integration_test.py+++ b/autogpt_platform/backend/backend/copilot/baseline/transcript_integration_test.py@@ -63,21 +63,21 @@ def _make_session_messages(*roles: str) -> list[ChatMessage]:class TestResolveBaselineModel:- """Model selection honours the per-request mode."""+ """Baseline model resolution honours the per-request tier toggle."""- def test_fast_mode_selects_fast_model(self):- assert _resolve_baseline_model("fast") == config.fast_model+ def test_advanced_tier_selects_advanced_model(self):+ assert _resolve_baseline_model("advanced") == config.advanced_model- def test_extended_thinking_selects_default_model(self):- assert _resolve_baseline_model("extended_thinking") == config.model+ def test_standard_tier_selects_default_model(self):+ assert _resolve_baseline_model("standard") == config.model- def test_none_mode_selects_default_model(self):- """Critical: baseline users without a mode MUST keep the default (opus)."""+ def test_none_tier_selects_default_model(self):+ """Baseline users without a tier MUST keep the default (standard)."""assert _resolve_baseline_model(None) == config.model- def test_default_and_fast_models_same(self):- """SDK defaults currently keep standard and fast on Sonnet 4.6."""- assert config.model == config.fast_model+ def test_standard_and_advanced_models_differ(self):+ """Advanced tier defaults to a different (Opus) model than standard."""+ assert config.model != config.advanced_modelclass TestLoadPriorTranscript:diff --git a/autogpt_platform/backend/backend/copilot/config.py b/autogpt_platform/backend/backend/copilot/config.pyindex 36644de680..ee4c717dbe 100644--- a/autogpt_platform/backend/backend/copilot/config.py+++ b/autogpt_platform/backend/backend/copilot/config.py@@ -17,8 +17,8 @@ from backend.util.clients import OPENROUTER_BASE_URLCopilotMode = Literal["fast", "extended_thinking"]# Per-request model tier set by the frontend model toggle.-# 'standard' uses the global config default (currently Sonnet).-# 'advanced' forces the highest-capability model (currently Opus).+# 'standard' uses ``ChatConfig.model`` (Sonnet by default).+# 'advanced' uses ``ChatConfig.advanced_model`` (Opus by default).# None means no preference — falls through to LD per-user targeting, then config.# Using tier names instead of model names keeps the contract model-agnostic.CopilotLlmModel = Literal["standard", "advanced"]@@ -27,16 +27,21 @@ CopilotLlmModel = Literal["standard", "advanced"]class ChatConfig(BaseSettings):"""Configuration for the chat system."""- # OpenAI API Configuration+ # Chat model tiers — applied orthogonally to the path (fast=baseline vs+ # extended_thinking=SDK). The "fast" vs "extended_thinking" toggle picks+ # which code path runs (no reasoning / heavy SDK); "standard" vs+ # "advanced" picks the model inside that path.model: str = Field(default="anthropic/claude-sonnet-4-6",- description="Default model for extended thinking mode. "- "Uses Sonnet 4.6 as the balanced default. "- "Override via CHAT_MODEL env var if you want a different default.",- )- fast_model: str = Field(- default="anthropic/claude-sonnet-4-6",- description="Model for fast mode (baseline path). Should be faster/cheaper than the default model.",+ description="Model used for the 'standard' tier (Sonnet by default). "+ "Applies to both baseline (fast) and SDK (extended thinking) paths. "+ "Override via CHAT_MODEL env var.",+ )+ advanced_model: str = Field(+ default="anthropic/claude-opus-4-7",+ description="Model used for the 'advanced' tier (Opus by default). "+ "Applies to both baseline (fast) and SDK (extended thinking) paths. "+ "Override via CHAT_ADVANCED_MODEL env var.",)title_model: str = Field(default="openai/gpt-4o-mini",diff --git a/autogpt_platform/backend/backend/copilot/prompting.py b/autogpt_platform/backend/backend/copilot/prompting.pyindex 1274302eee..2f52bd460d 100644--- a/autogpt_platform/backend/backend/copilot/prompting.py+++ b/autogpt_platform/backend/backend/copilot/prompting.py@@ -361,6 +361,16 @@ Every time you see one:Never echo the `<user_follow_up>` tags back. The block holds only the user'swords — the rest of the tool result is the real data.++# Always close the turn with visible text++Every turn MUST end with at least one short user-facing text sentence —+even if it is only "Done." or "I'm stopping here because X." Never end a+turn with only tool calls or only thinking. The user's UI renders text+messages; a turn that emits only thinking blocks or only tool calls shows+up as a frozen screen with no response. If your plan was to stop after+the last tool result, still produce one closing sentence summarising+what happened so the user knows the turn is complete."""diff --git a/autogpt_platform/backend/backend/copilot/response_model.py b/autogpt_platform/backend/backend/copilot/response_model.pyindex df6ef1d5cf..1805b68b07 100644--- a/autogpt_platform/backend/backend/copilot/response_model.py+++ b/autogpt_platform/backend/backend/copilot/response_model.py@@ -34,6 +34,15 @@ class ResponseType(str, Enum):TEXT_DELTA = "text-delta"TEXT_END = "text-end"+ # Reasoning streaming (extended_thinking content blocks). Matches+ # the Vercel AI SDK v5 wire names so the client's ``useChat``+ # transport accumulates these into a ``type: 'reasoning'`` UIMessage+ # part that the ``ReasoningCollapse`` component renders collapsed by+ # default.+ REASONING_START = "reasoning-start"+ REASONING_DELTA = "reasoning-delta"+ REASONING_END = "reasoning-end"+# Tool interactionTOOL_INPUT_START = "tool-input-start"TOOL_INPUT_AVAILABLE = "tool-input-available"@@ -130,6 +139,31 @@ class StreamTextEnd(StreamBaseResponse):id: str = Field(..., description="Text block ID")+# ========== Reasoning Streaming ==========+++class StreamReasoningStart(StreamBaseResponse):+ """Start of a reasoning block (extended_thinking content)."""++ type: ResponseType = ResponseType.REASONING_START+ id: str = Field(..., description="Reasoning block ID")+++class StreamReasoningDelta(StreamBaseResponse):+ """Streaming reasoning content delta."""++ type: ResponseType = ResponseType.REASONING_DELTA+ id: str = Field(..., description="Reasoning block ID")+ delta: str = Field(..., description="Reasoning content delta")+++class StreamReasoningEnd(StreamBaseResponse):+ """End of a reasoning block."""++ type: ResponseType = ResponseType.REASONING_END+ id: str = Field(..., description="Reasoning block ID")++# ========== Tool Interaction ==========diff --git a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.pyindex e43524197a..fbd73d9277 100644--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter.py@@ -28,6 +28,9 @@ from backend.copilot.response_model import (StreamFinish,StreamFinishStep,StreamHeartbeat,+ StreamReasoningDelta,+ StreamReasoningEnd,+ StreamReasoningStart,StreamStart,StreamStartStep,StreamTextDelta,@@ -56,9 +59,21 @@ class SDKResponseAdapter:self.text_block_id = str(uuid.uuid4())self.has_started_text = Falseself.has_ended_text = False+ self.reasoning_block_id = str(uuid.uuid4())+ self.has_started_reasoning = False+ self.has_ended_reasoning = Trueself.current_tool_calls: dict[str, dict[str, str]] = {}self.resolved_tool_calls: set[str] = set()self.step_open = False+ # Track whether any ``TextBlock`` was emitted after the most recent+ # tool_result. Used at ``ResultMessage`` time to detect the+ # "thinking-only final turn" case — when Claude's last LLM call+ # produced only a ``ThinkingBlock`` (no text, no tool_use) the UI+ # hangs on the last tool result with a "Thought for Xs" label and+ # no response text. We synthesize a short closing line in that+ # case so the turn renders as cleanly complete.+ self._text_since_last_tool_result = False+ self._any_tool_results_seen = False@propertydef has_unresolved_tool_calls(self) -> bool:@@ -103,18 +118,43 @@ class SDKResponseAdapter:for block in sdk_message.content:if isinstance(block, TextBlock):if block.text:+ # Reasoning and text are distinct UI parts; close+ # any open reasoning block before opening text so+ # the AI SDK transport doesn't merge them.+ self._end_reasoning_if_open(responses)self._ensure_text_started(responses)responses.append(StreamTextDelta(id=self.text_block_id, delta=block.text))+ self._text_since_last_tool_result = Trueelif isinstance(block, ThinkingBlock):- # Thinking blocks are preserved in the transcript but- # not streamed to the frontend — skip silently.- pass+ # Stream extended_thinking content as a reasoning+ # block. The Vercel AI SDK's ``useChat`` transport+ # recognises ``reasoning-start`` / ``reasoning-delta``+ # / ``reasoning-end`` events and accumulates them into+ # a ``type: 'reasoning'`` UIMessage part the frontend+ # renders via ``ReasoningCollapse`` (collapsed by+ # default). We also persist the text as a+ # ``type: 'thinking'`` part in ``session.messages`` via+ # ``_format_sdk_content_blocks``, so shared / reloaded+ # sessions see the same reasoning. Without streaming+ # it live, extended_thinking turns that end+ # thinking-only left the UI stuck on "Thought for Xs"+ # with nothing rendered until a page refresh.+ if block.thinking:+ self._end_text_if_open(responses)+ self._ensure_reasoning_started(responses)+ responses.append(+ StreamReasoningDelta(+ id=self.reasoning_block_id,+ delta=block.thinking,+ )+ )elif isinstance(block, ToolUseBlock):self._end_text_if_open(responses)+ self._end_reasoning_if_open(responses)# Strip MCP prefix so frontend sees "find_block"# instead of "mcp__copilot__find_block".@@ -210,16 +250,58 @@ class SDKResponseAdapter:resolved_in_blocks.add(parent_id)self.resolved_tool_calls.update(resolved_in_blocks)+ if resolved_in_blocks:+ # A new tool_result just landed — reset the+ # "has the model emitted text since the last tool result?"+ # tracker so the thinking-only-final-turn guard at+ # ``ResultMessage`` time stays accurate.+ self._text_since_last_tool_result = False+ self._any_tool_results_seen = True# 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 = Falseelif isinstance(sdk_message, ResultMessage):self._flush_unresolved_tool_calls(responses)+ # Thinking-only final turn guard: when the model's last LLM+ # call after a tool result produced only a ``ThinkingBlock``+ # (no ``TextBlock``, no ``ToolUseBlock``) the UI has nothing+ # to render after the tool output — it hangs on "Thought for+ # Xs" with no response text. Synthesise a short closing line+ # so the turn visibly completes. Condition: we've seen at+ # least one tool_result AND zero TextBlocks since. The+ # prompt rule (``_USER_FOLLOW_UP_NOTE``'s closing clause)+ # asks the model to always end with text, but we can't rely+ # on it for extended_thinking / edge cases.+ if (+ self._any_tool_results_seen+ and not self._text_since_last_tool_result+ and sdk_message.subtype == "success"+ ):+ # UserMessage (tool_result) closed the last step, so we must+ # open a fresh one before emitting any text — the AI SDK v5+ # transport rejects text-delta chunks that aren't wrapped in+ # start-step / finish-step.+ if not self.step_open:+ responses.append(StreamStartStep())+ self.step_open = True+ # Close any open reasoning block first — text and reasoning+ # must not interleave on the wire (AI SDK v5 maps distinct+ # start/end events to distinct UI parts).+ self._end_reasoning_if_open(responses)+ self._ensure_text_started(responses)+ responses.append(+ StreamTextDelta(+ id=self.text_block_id,+ delta="(Done — no further commentary.)",+ )+ )self._end_text_if_open(responses)+ self._end_reasoning_if_open(responses)# Close the step before finishing.if self.step_open:responses.append(StreamFinishStep())@@ -261,6 +343,26 @@ class SDKResponseAdapter:responses.append(StreamTextEnd(id=self.text_block_id))self.has_ended_text = True+ def _ensure_reasoning_started(self, responses: list[StreamBaseResponse]) -> None:+ """Start (or restart) a reasoning block if needed.++ Each ``ThinkingBlock`` the SDK emits gets its own streaming block+ on the wire so the frontend can render a new ``Reasoning`` part+ per LLM turn (rather than concatenating across the whole session).+ """+ if not self.has_started_reasoning or self.has_ended_reasoning:+ if self.has_ended_reasoning:+ self.reasoning_block_id = str(uuid.uuid4())+ self.has_ended_reasoning = False+ responses.append(StreamReasoningStart(id=self.reasoning_block_id))+ self.has_started_reasoning = True++ def _end_reasoning_if_open(self, responses: list[StreamBaseResponse]) -> None:+ """End the current reasoning block if one is open."""+ if self.has_started_reasoning and not self.has_ended_reasoning:+ responses.append(StreamReasoningEnd(id=self.reasoning_block_id))+ self.has_ended_reasoning = True+def _flush_unresolved_tool_calls(self, responses: list[StreamBaseResponse]) -> None:"""Emit outputs for tool calls that didn't receive a UserMessage result.@@ -335,9 +437,17 @@ class SDKResponseAdapter:tool_id[:12],)- if flushed and self.step_open:- responses.append(StreamFinishStep())- self.step_open = False+ if flushed:+ # Mirror the UserMessage tool_result path: a flushed tool output is+ # still a tool_result as far as the thinking-only-final-turn guard+ # is concerned. Without this, a turn whose ONLY tool outputs come+ # from the flush path (SDK built-ins like WebSearch) would miss+ # the fallback synthesis if the model then produced no text.+ self._text_since_last_tool_result = False+ self._any_tool_results_seen = True+ if self.step_open:+ responses.append(StreamFinishStep())+ self.step_open = Falsedef _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 7eee1c04e8..c93286a3d6 100644--- a/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/response_adapter_test.py@@ -8,6 +8,7 @@ from claude_agent_sdk import (ResultMessage,SystemMessage,TextBlock,+ ThinkingBlock,ToolResultBlock,ToolUseBlock,UserMessage,@@ -19,6 +20,9 @@ from backend.copilot.response_model import (StreamFinish,StreamFinishStep,StreamHeartbeat,+ StreamReasoningDelta,+ StreamReasoningEnd,+ StreamReasoningStart,StreamStart,StreamStartStep,StreamTextDelta,@@ -251,6 +255,200 @@ def test_result_success_emits_finish_step_and_finish():assert isinstance(results[2], StreamFinish)+# -- Reasoning streaming -----------------------------------------------------+++def test_thinking_block_streams_as_reasoning():+ """ThinkingBlock content streams as StreamReasoningDelta so the+ frontend renders it via the ``Reasoning`` part (collapsed by+ default) instead of dropping it silently."""+ adapter = _adapter()+ msg = AssistantMessage(+ content=[+ ThinkingBlock(thinking="planning step 1", signature="sig"),+ ],+ model="test",+ )+ results = adapter.convert_message(msg)+ # Step + ReasoningStart + ReasoningDelta+ types = [type(r).__name__ for r in results]+ assert "StreamReasoningStart" in types+ assert any(+ isinstance(r, StreamReasoningDelta) and r.delta == "planning step 1"+ for r in results+ )+++def test_text_after_thinking_closes_reasoning_and_opens_text():+ """Reasoning and text are distinct UI parts — opening text must+ emit ``ReasoningEnd`` first so the AI SDK transport doesn't merge+ them into the same ``Reasoning`` part."""+ adapter = _adapter()+ adapter.convert_message(+ AssistantMessage(+ content=[ThinkingBlock(thinking="warming up", signature="sig")],+ model="test",+ )+ )+ results = adapter.convert_message(+ AssistantMessage(content=[TextBlock(text="hello")], model="test")+ )+ types = [type(r).__name__ for r in results]+ # ReasoningEnd must come before TextStart+ re_idx = types.index("StreamReasoningEnd")+ ts_idx = types.index("StreamTextStart")+ assert re_idx < ts_idx+++def test_tool_use_after_thinking_closes_reasoning():+ """Opening a tool also closes an open reasoning block."""+ adapter = _adapter()+ adapter.convert_message(+ AssistantMessage(+ content=[ThinkingBlock(thinking="let me search", signature="sig")],+ model="test",+ )+ )+ results = adapter.convert_message(+ AssistantMessage(+ content=[+ ToolUseBlock(id="t1", name=f"{MCP_TOOL_PREFIX}find_block", input={})+ ],+ model="test",+ )+ )+ types = [type(r).__name__ for r in results]+ assert types.index("StreamReasoningEnd") < types.index("StreamToolInputStart")+++def test_empty_thinking_block_is_ignored():+ """A ThinkingBlock with empty content shouldn't emit anything."""+ adapter = _adapter()+ msg = AssistantMessage(+ content=[ThinkingBlock(thinking="", signature="sig")],+ model="test",+ )+ results = adapter.convert_message(msg)+ # Only the StepStart fires — no reasoning events.+ assert [type(r).__name__ for r in results] == ["StreamStartStep"]+++def test_result_success_synthesizes_fallback_text_when_final_turn_is_thinking_only():+ """If the model's last LLM call after a tool_result produced only a+ ThinkingBlock (no TextBlock), the UI would hang on the tool output+ with no response text. The adapter should inject a short closing+ line before ``StreamFinish`` so the turn visibly completes."""+ adapter = _adapter()++ # Tool use + tool_result (simulates the tool round).+ adapter.convert_message(+ AssistantMessage(+ content=[+ ToolUseBlock(id="t1", name=f"{MCP_TOOL_PREFIX}find_block", input={}),+ ],+ model="test",+ )+ )+ adapter.convert_message(+ UserMessage(+ content=[+ ToolResultBlock(tool_use_id="t1", content="result", is_error=False)+ ],+ parent_tool_use_id=None,+ )+ )++ # Model's "final turn" after tool_result is thinking-only. This test+ # simulates the *degenerate* case where the SDK never surfaces an+ # AssistantMessage carrying the ThinkingBlock at all (not even the+ # streamed reasoning events) before ResultMessage — only the tool_result+ # has arrived. The fallback guard should still synthesize closing text.+ msg = ResultMessage(+ subtype="success",+ duration_ms=100,+ duration_api_ms=50,+ is_error=False,+ num_turns=4,+ session_id="s1",+ result="",+ )+ results = adapter.convert_message(msg)++ # Fallback text should be injected before the finish events.+ text_deltas = [r for r in results if isinstance(r, StreamTextDelta)]+ assert len(text_deltas) == 1, "should synthesize exactly one fallback text"+ assert text_deltas[0].delta.strip() # non-empty+ assert isinstance(results[-1], StreamFinish)+++def test_result_success_does_not_synthesize_when_text_already_emitted():+ """Guard: do NOT synthesize when the model DID emit closing text+ after the last tool result — the fallback is only for the silent+ thinking-only case."""+ adapter = _adapter()++ adapter.convert_message(+ AssistantMessage(+ content=[+ ToolUseBlock(id="t1", name=f"{MCP_TOOL_PREFIX}find_block", input={})+ ],+ model="test",+ )+ )+ adapter.convert_message(+ UserMessage(+ content=[+ ToolResultBlock(tool_use_id="t1", content="result", is_error=False)+ ],+ parent_tool_use_id=None,+ )+ )+ # Model responds with actual text after the tool result.+ adapter.convert_message(+ AssistantMessage(content=[TextBlock(text="all done")], model="test")+ )++ msg = ResultMessage(+ subtype="success",+ duration_ms=100,+ duration_api_ms=50,+ is_error=False,+ num_turns=4,+ session_id="s1",+ result="all done",+ )+ results = adapter.convert_message(msg)++ # No fallback — the only TextDelta came from the previous+ # AssistantMessage call, not from ResultMessage's synthesis.+ text_deltas = [r for r in results if isinstance(r, StreamTextDelta)]+ assert text_deltas == []+++def test_result_success_does_not_synthesize_when_no_tools_ran():+ """Guard: no tool_results seen ⇒ no fallback. Pure-text turns with+ no tools legitimately produce text-only responses through normal+ AssistantMessage events; we don't need a fallback there."""+ adapter = _adapter()++ adapter.convert_message(+ AssistantMessage(content=[TextBlock(text="hello")], model="test")+ )++ msg = ResultMessage(+ subtype="success",+ duration_ms=100,+ duration_api_ms=50,+ is_error=False,+ num_turns=1,+ session_id="s1",+ result="hello",+ )+ results = adapter.convert_message(msg)+ text_deltas = [r for r in results if isinstance(r, StreamTextDelta)]+ assert text_deltas == []++def test_result_error_emits_error_and_finish():adapter = _adapter()msg = ResultMessage(@@ -426,6 +624,13 @@ def test_flush_unresolved_at_result_message():"StreamToolInputAvailable","StreamToolOutputAvailable", # flushed with empty output"StreamFinishStep", # step closed by flush+ # Flush marks a tool_result as seen, so the thinking-only-final-turn+ # guard at ResultMessage time synthesizes a closing text delta.+ "StreamStartStep",+ "StreamTextStart",+ "StreamTextDelta",+ "StreamTextEnd",+ "StreamFinishStep","StreamFinish",]# The flushed output should be empty (no stash available)diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.pyindex c27480651f..8fea273b5d 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py@@ -83,6 +83,9 @@ from ..response_model import (StreamFinish,StreamFinishStep,StreamHeartbeat,+ StreamReasoningDelta,+ StreamReasoningEnd,+ StreamReasoningStart,StreamStart,StreamStartStep,StreamStatus,@@ -739,7 +742,7 @@ async def _resolve_model_and_multiplier(sdk_model = _resolve_sdk_model()if model == "advanced":- sdk_model = _normalize_model_name("anthropic/claude-opus-4-6")+ sdk_model = _normalize_model_name(config.advanced_model)logger.info("[SDK] [%s] Per-request model override: advanced (%s)",session_id[:12] if session_id else "?",@@ -1160,7 +1163,14 @@ async def _compress_messages(`compact_transcript` — compresses JSONL transcript entries.`CompactionTracker` — emits UI events for mid-stream compaction."""- messages = filter_compaction_messages(messages)+ # ``role="reasoning"`` rows are persisted for frontend replay only — they+ # aren't valid OpenAI roles and ``compress_context`` would either drop or+ # malform them. Strip here so every caller is covered (``_build_query_message``+ # already filters upstream, but ``_seed_transcript`` and any future caller+ # don't, and centralising the filter avoids per-call-site drift).+ messages = [+ m for m in filter_compaction_messages(messages) if m.role != "reasoning"+ ]if len(messages) < 2:return messages, False@@ -1357,6 +1367,15 @@ async def _build_query_message(# max(0, ...) guards against a theoretical 0-message ceiling (brand-new# session) where -1 would select all-but-last instead of an empty slice.prior = session.messages[: max(0, effective_count - 1)]+ # ``role="reasoning"`` rows are persisted for frontend replay only and are+ # never present in the CLI JSONL (extended_thinking is embedded inside+ # assistant entries). The watermark — ``transcript_msg_count`` — counts+ # non-reasoning rows (see _jsonl_covered upload), so we must filter reasoning+ # out of ``prior`` too; otherwise the ``prior[transcript_msg_count - 1]``+ # watermark-alignment check trips on a reasoning row (instead of the+ # expected assistant) and the gap injection is skipped, dropping real+ # mid-turn user rows from the next LLM query.+ prior = [m for m in prior if m.role != "reasoning"]logger.info("[SDK] [%s] Context path: use_resume=%s, transcript_msg_count=%d,"@@ -1611,6 +1630,12 @@ class _StreamAccumulator:thinking_stripper: ThinkingStripper = dataclass_field(default_factory=ThinkingStripper,)+ # Currently-open reasoning block for this turn. Each StreamReasoningStart+ # creates a new ChatMessage(role="reasoning"), each delta appends to its+ # content, and StreamReasoningEnd clears the reference. Rows are persisted+ # inline with text/tool rows so they survive session reload; the reader+ # filters role="reasoning" out of LLM context.+ reasoning_response: ChatMessage | None = Nonedef _dispatch_response(@@ -1671,7 +1696,20 @@ def _dispatch_response(retryable=(response.code == "transient_api_error"),)- if isinstance(response, StreamTextDelta):+ if isinstance(response, StreamReasoningStart):+ acc.reasoning_response = ChatMessage(role="reasoning", content="")+ ctx.session.messages.append(acc.reasoning_response)++ elif isinstance(response, StreamReasoningDelta):+ if acc.reasoning_response is not None:+ acc.reasoning_response.content = (acc.reasoning_response.content or "") + (+ response.delta or ""+ )++ elif isinstance(response, StreamReasoningEnd):+ acc.reasoning_response = None++ elif isinstance(response, StreamTextDelta):raw_delta = response.delta or ""if skip_strip:# Pre-stripped tail from ThinkingStripper.flush() — bypass process()@@ -3908,7 +3946,16 @@ async def stream_chat_completion_sdk(_midturn_offset = (state.midturn_user_rows if state is not None else 0)- _jsonl_covered = len(session.messages) - _midturn_offset+ # ``role="reasoning"`` rows are persisted to session.messages+ # for frontend replay but never appear in the CLI JSONL+ # (extended_thinking lives embedded in assistant entries, not+ # as standalone rows). Exclude them from the watermark so+ # ``detect_gap`` on the next turn doesn't skip real+ # user/assistant rows. See sentry comment 3106186683.+ _non_reasoning_count = sum(+ 1 for m in session.messages if m.role != "reasoning"+ )+ _jsonl_covered = _non_reasoning_count - _midturn_offsetawait asyncio.shield(upload_transcript(user_id=user_id,diff --git a/autogpt_platform/backend/backend/copilot/service.py b/autogpt_platform/backend/backend/copilot/service.pyindex 135d08a44a..4ce9c285be 100644--- a/autogpt_platform/backend/backend/copilot/service.py+++ b/autogpt_platform/backend/backend/copilot/service.py@@ -26,7 +26,7 @@ from backend.data.understanding import (from backend.util.exceptions import NotAuthorizedError, NotFoundErrorfrom backend.util.settings import AppEnvironment, Settings-from .config import ChatConfig+from .config import ChatConfig, CopilotLlmModelfrom .model import (ChatMessage,ChatSessionInfo,@@ -40,6 +40,21 @@ logger = logging.getLogger(__name__)config = ChatConfig()settings = Settings()++def resolve_chat_model(tier: CopilotLlmModel | None) -> str:+ """Return the configured OpenRouter model string for the given tier.++ Shared by the baseline (fast) and SDK (extended thinking) paths so+ both honor the same standard/advanced env-var configuration. ``None``+ and ``'standard'`` fall through to ``config.model``; ``'advanced'``+ uses ``config.advanced_model``. Keep this flat — if a third tier+ shows up later, extend here and both paths pick it up for free.+ """+ if tier == "advanced":+ return config.advanced_model+ return config.model++_client: LangfuseAsyncOpenAI | None = None_langfuse = Nonediff --git a/autogpt_platform/backend/backend/copilot/stream_registry.py b/autogpt_platform/backend/backend/copilot/stream_registry.pyindex e669e79dd1..111fbef90a 100644--- a/autogpt_platform/backend/backend/copilot/stream_registry.py+++ b/autogpt_platform/backend/backend/copilot/stream_registry.py@@ -43,6 +43,9 @@ from .response_model import (StreamFinish,StreamFinishStep,StreamHeartbeat,+ StreamReasoningDelta,+ StreamReasoningEnd,+ StreamReasoningStart,StreamStart,StreamStartStep,StreamTextDelta,@@ -1062,6 +1065,9 @@ def _reconstruct_chunk(chunk_data: dict) -> StreamBaseResponse | None:ResponseType.TEXT_START.value: StreamTextStart,ResponseType.TEXT_DELTA.value: StreamTextDelta,ResponseType.TEXT_END.value: StreamTextEnd,+ ResponseType.REASONING_START.value: StreamReasoningStart,+ ResponseType.REASONING_DELTA.value: StreamReasoningDelta,+ ResponseType.REASONING_END.value: StreamReasoningEnd,ResponseType.TOOL_INPUT_START.value: StreamToolInputStart,ResponseType.TOOL_INPUT_AVAILABLE.value: StreamToolInputAvailable,ResponseType.TOOL_OUTPUT_AVAILABLE.value: StreamToolOutputAvailable,diff --git a/autogpt_platform/backend/backend/copilot/transcript.py b/autogpt_platform/backend/backend/copilot/transcript.pyindex c4d3de28af..5a46760dfd 100644--- a/autogpt_platform/backend/backend/copilot/transcript.py+++ b/autogpt_platform/backend/backend/copilot/transcript.py@@ -877,6 +877,14 @@ def extract_context_messages("""from .model import ChatMessage as _ChatMessage # runtime import+ # ``role="reasoning"`` rows are persisted for frontend replay of+ # extended_thinking content but are NOT conversation context — the+ # transcript-based --resume path already carries thinking separately,+ # and sending them back to the model as user/assistant turns would be+ # both redundant and malformed. Drop them before any gap detection+ # or transcript comparison so ordering invariants still hold.+ session_messages = [m for m in session_messages if m.role != "reasoning"]+prior = session_messages[:-1]if download is None:diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPendingChips.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPendingChips.test.tsindex b4120f878f..7c62121124 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPendingChips.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPendingChips.test.ts@@ -345,6 +345,25 @@ describe("useCopilotPendingChips", () => {return updated.some((m) => m.id.startsWith("promoted-midturn-"));});expect(promotedCall).toBeDefined();++ // And — crucially — the promoted bubble is inserted BEFORE the+ // trailing streaming assistant, not after. The AI SDK's ``useChat``+ // streams SSE deltas into ``messages[-1]``; if the last message is+ // a user bubble instead of the still-streaming assistant, every+ // subsequent chunk lands in the wrong slot and the UI freezes until+ // a page refresh.+ const streamingUpdater = promotedCall![0] as (+ prev: UIMessage[],+ ) => UIMessage[];+ const priorMessages = [user("u1"), assistant("a1", "streaming...")];+ const afterPromotion = streamingUpdater(priorMessages);+ expect(afterPromotion).toHaveLength(3);+ const lastIdx = afterPromotion.length - 1;+ expect(afterPromotion[lastIdx].role).toBe("assistant");+ expect(afterPromotion[lastIdx].id).toBe("a1");+ expect(afterPromotion[lastIdx - 1].id.startsWith("promoted-midturn-")).toBe(+ true,+ );// And remaining chips cleared.expect(result.current.queuedMessages).toEqual([]);});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsxindex 357f1dfc1f..e3192a19c6 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx@@ -32,7 +32,7 @@ import { CopyButton } from "./components/CopyButton";import { CollapsedToolGroup } from "./components/CollapsedToolGroup";import { MessageAttachments } from "./components/MessageAttachments";import { MessagePartRenderer } from "./components/MessagePartRenderer";-import { ReasoningCollapse } from "./components/ReasoningCollapse";+import { StepsCollapse } from "./components/StepsCollapse";import { ThinkingIndicator } from "./components/ThinkingIndicator";interface Props {@@ -414,9 +414,9 @@ export function ChatMessagesContainer({}>{hasReasoning && reasoningSegments && (- <ReasoningCollapse>+ <StepsCollapse>{renderSegments(reasoningSegments, message.id)}- </ReasoningCollapse>+ </StepsCollapse>)}{responseSegments? renderSegments(diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsxindex 090ab5310e..1e50408661 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx@@ -26,6 +26,7 @@ import {parseSpecialMarkers,resolveWorkspaceUrls,} from "../helpers";+import { ReasoningCollapse } from "./ReasoningCollapse";/*** Custom img component for Streamdown that renders <video> elements@@ -104,6 +105,18 @@ export function MessagePartRenderer({const key = `${messageID}-${partIndex}`;switch (part.type) {+ case "reasoning": {+ const reasoningText =+ "text" in part && typeof part.text === "string" ? part.text : "";+ if (!reasoningText.trim()) return null;+ return (+ <ReasoningCollapse key={key}>+ <pre className="whitespace-pre-wrap text-sm text-zinc-700">+ {reasoningText}+ </pre>+ </ReasoningCollapse>+ );+ }case "text": {const { markerType, markerText, cleanText } = parseSpecialMarkers(part.text,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ReasoningCollapse.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ReasoningCollapse.tsxindex 5590b04b4f..ce2ce37045 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ReasoningCollapse.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ReasoningCollapse.tsx@@ -1,27 +1,38 @@"use client";-import { LightbulbIcon } from "@phosphor-icons/react";-import { Dialog } from "@/components/molecules/Dialog/Dialog";+import { CaretRightIcon, LightbulbIcon } from "@phosphor-icons/react";+import { useState } from "react";interface Props {children: React.ReactNode;}export function ReasoningCollapse({ children }: Props) {+ const [open, setOpen] = useState(false);+return (- <Dialog title="Reasoning">- <Dialog.Trigger>- <button- type="button"- className="flex items-center gap-1 text-xs text-zinc-500 transition-colors hover:text-zinc-700"- >- <LightbulbIcon size={12} weight="bold" />- <span>Show reasoning</span>- </button>- </Dialog.Trigger>- <Dialog.Content>- <div className="space-y-1">{children}</div>- </Dialog.Content>- </Dialog>+ <div className="my-1">+ <button+ type="button"+ onClick={() => setOpen((o) => !o)}+ aria-expanded={open}+ className="flex items-center gap-1 text-xs text-zinc-500 transition-colors hover:text-zinc-700"+ >+ <CaretRightIcon+ size={10}+ weight="bold"+ className={+ "transition-transform duration-150 " + (open ? "rotate-90" : "")+ }+ />+ <LightbulbIcon size={12} weight="bold" />+ <span>{open ? "Hide reasoning" : "Show reasoning"}</span>+ </button>+ {open && (+ <div className="mt-1 space-y-1 border-l-2 border-zinc-200 pl-3">+ {children}+ </div>+ )}+ </div>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/StepsCollapse.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/StepsCollapse.tsxnew file mode 100644index 0000000000..a5460e3f60--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/StepsCollapse.tsx@@ -0,0 +1,27 @@+"use client";++import { ListBulletsIcon } from "@phosphor-icons/react";+import { Dialog } from "@/components/molecules/Dialog/Dialog";++interface Props {+ children: React.ReactNode;+}++export function StepsCollapse({ children }: Props) {+ return (+ <Dialog title="Steps">+ <Dialog.Trigger>+ <button+ type="button"+ className="flex items-center gap-1 text-xs text-zinc-500 transition-colors hover:text-zinc-700"+ >+ <ListBulletsIcon size={12} weight="bold" />+ <span>Show steps</span>+ </button>+ </Dialog.Trigger>+ <Dialog.Content>+ <div className="space-y-1">{children}</div>+ </Dialog.Content>+ </Dialog>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/MessagePartRenderer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/MessagePartRenderer.test.tsxnew file mode 100644index 0000000000..fc51104bd4--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/MessagePartRenderer.test.tsx@@ -0,0 +1,135 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, render, screen } from "@testing-library/react";+import type { UIDataTypes, UIMessage, UITools } from "ai";+import { MessagePartRenderer } from "../MessagePartRenderer";++type Part = UIMessage<unknown, UIDataTypes, UITools>["parts"][number];++vi.mock("../ReasoningCollapse", () => ({+ ReasoningCollapse: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="reasoning-collapse">{children}</div>+ ),+}));++vi.mock("@/components/ai-elements/message", () => ({+ MessageResponse: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="message-response">{children}</div>+ ),+}));++vi.mock("@/components/molecules/ErrorCard/ErrorCard", () => ({+ ErrorCard: () => null,+}));++vi.mock("@/services/feature-flags/use-get-flag", () => ({+ Flag: { ARTIFACTS: "artifacts" },+ useGetFlag: () => false,+}));++vi.mock("@phosphor-icons/react", async (importOriginal) => {+ const actual = (await importOriginal()) as Record<string, unknown>;+ return { ...actual, ExclamationMarkIcon: () => null };+});++const stub = (name: string) => ({ [name]: () => null });+vi.mock("../../ArtifactCard/ArtifactCard", () => stub("ArtifactCard"));+vi.mock("../../../tools/AskQuestion/AskQuestion", () =>+ stub("AskQuestionTool"),+);+vi.mock("../../../tools/ConnectIntegrationTool/ConnectIntegrationTool", () =>+ stub("ConnectIntegrationTool"),+);+vi.mock("../../../tools/CreateAgent/CreateAgent", () =>+ stub("CreateAgentTool"),+);+vi.mock("../../../tools/EditAgent/EditAgent", () => stub("EditAgentTool"));+vi.mock("../../../tools/FeatureRequests/FeatureRequests", () => ({+ CreateFeatureRequestTool: () => null,+ SearchFeatureRequestsTool: () => null,+}));+vi.mock("../../../tools/FindAgents/FindAgents", () => stub("FindAgentsTool"));+vi.mock("../../../tools/FolderTool/FolderTool", () => stub("FolderTool"));+vi.mock("../../../tools/FindBlocks/FindBlocks", () => stub("FindBlocksTool"));+vi.mock("../../../tools/GenericTool/GenericTool", () => stub("GenericTool"));+vi.mock("../../../tools/RunAgent/RunAgent", () => stub("RunAgentTool"));+vi.mock("../../../tools/RunBlock/RunBlock", () => stub("RunBlockTool"));+vi.mock("../../../tools/RunMCPTool/RunMCPTool", () =>+ stub("RunMCPToolComponent"),+);+vi.mock("../../../tools/SearchDocs/SearchDocs", () => stub("SearchDocsTool"));+vi.mock("../../../tools/ViewAgentOutput/ViewAgentOutput", () =>+ stub("ViewAgentOutputTool"),+);++describe("MessagePartRenderer reasoning branch", () => {+ afterEach(() => {+ cleanup();+ });++ it("renders a ReasoningCollapse wrapping a <pre> with the reasoning text", () => {+ const part = {+ type: "reasoning",+ text: "step-by-step plan",+ state: "done",+ } as unknown as Part;++ render(<MessagePartRenderer part={part} messageID="m1" partIndex={0} />);++ const collapse = screen.getByTestId("reasoning-collapse");+ expect(collapse).toBeDefined();+ const pre = collapse.querySelector("pre");+ expect(pre).not.toBeNull();+ expect(pre?.textContent).toBe("step-by-step plan");+ });++ it("returns null when the reasoning text is whitespace-only", () => {+ const part = {+ type: "reasoning",+ text: " \n ",+ state: "done",+ } as unknown as Part;++ const { container } = render(+ <MessagePartRenderer part={part} messageID="m1" partIndex={0} />,+ );+ expect(container.firstChild).toBeNull();+ expect(screen.queryByTestId("reasoning-collapse")).toBeNull();+ });++ it("returns null when the reasoning part has no text key", () => {+ const part = { type: "reasoning", state: "done" } as unknown as Part;++ const { container } = render(+ <MessagePartRenderer part={part} messageID="m1" partIndex={0} />,+ );+ expect(container.firstChild).toBeNull();+ expect(screen.queryByTestId("reasoning-collapse")).toBeNull();+ });++ it("returns null when the reasoning part's text is not a string", () => {+ const part = {+ type: "reasoning",+ text: 42,+ state: "done",+ } as unknown as Part;++ const { container } = render(+ <MessagePartRenderer part={part} messageID="m1" partIndex={0} />,+ );+ expect(container.firstChild).toBeNull();+ expect(screen.queryByTestId("reasoning-collapse")).toBeNull();+ });++ it("renders reasoning content when it contains non-whitespace surrounded by whitespace", () => {+ const part = {+ type: "reasoning",+ text: " reasoning-with-pad ",+ state: "done",+ } as unknown as Part;++ render(<MessagePartRenderer part={part} messageID="m2" partIndex={3} />);++ const pre = screen.getByTestId("reasoning-collapse").querySelector("pre");+ expect(pre?.textContent).toBe(" reasoning-with-pad ");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ReasoningCollapse.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ReasoningCollapse.test.tsxnew file mode 100644index 0000000000..5dac2d0541--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ReasoningCollapse.test.tsx@@ -0,0 +1,74 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { ReasoningCollapse } from "../ReasoningCollapse";++vi.mock("@phosphor-icons/react", () => ({+ CaretRightIcon: ({ className }: { className?: string }) => (+ <span data-testid="caret" className={className} />+ ),+ LightbulbIcon: () => <span data-testid="lightbulb" />,+}));++describe("ReasoningCollapse", () => {+ afterEach(() => {+ cleanup();+ });++ it("starts collapsed with 'Show reasoning' and no children in the DOM", () => {+ render(+ <ReasoningCollapse>+ <div data-testid="reasoning-body">secret thoughts</div>+ </ReasoningCollapse>,+ );++ expect(screen.getByText("Show reasoning")).toBeDefined();+ expect(screen.queryByTestId("reasoning-body")).toBeNull();+ const trigger = screen.getByRole("button");+ expect(trigger.getAttribute("aria-expanded")).toBe("false");+ });++ it("expands on click: toggles label and reveals children", () => {+ render(+ <ReasoningCollapse>+ <div data-testid="reasoning-body">secret thoughts</div>+ </ReasoningCollapse>,+ );++ const trigger = screen.getByRole("button");+ fireEvent.click(trigger);++ expect(screen.getByText("Hide reasoning")).toBeDefined();+ expect(screen.getByTestId("reasoning-body")).toBeDefined();+ expect(trigger.getAttribute("aria-expanded")).toBe("true");+ });++ it("collapses again on a second click", () => {+ render(+ <ReasoningCollapse>+ <div data-testid="reasoning-body">secret thoughts</div>+ </ReasoningCollapse>,+ );++ const trigger = screen.getByRole("button");+ fireEvent.click(trigger);+ fireEvent.click(trigger);++ expect(screen.getByText("Show reasoning")).toBeDefined();+ expect(screen.queryByTestId("reasoning-body")).toBeNull();+ expect(trigger.getAttribute("aria-expanded")).toBe("false");+ });++ it("applies the rotate-90 caret class only when expanded", () => {+ render(+ <ReasoningCollapse>+ <div>body</div>+ </ReasoningCollapse>,+ );++ const caret = screen.getByTestId("caret");+ expect(caret.className).not.toContain("rotate-90");++ fireEvent.click(screen.getByRole("button"));+ expect(screen.getByTestId("caret").className).toContain("rotate-90");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/StepsCollapse.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/StepsCollapse.test.tsxnew file mode 100644index 0000000000..a7e42c42e7--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/StepsCollapse.test.tsx@@ -0,0 +1,74 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { StepsCollapse } from "../StepsCollapse";++vi.mock("@phosphor-icons/react", () => ({+ ListBulletsIcon: () => <span data-testid="list-icon" />,+}));++vi.mock("@/components/molecules/Dialog/Dialog", async () => {+ const { createContext, useContext, useState } = await import("react");++ const Ctx = createContext<{+ open: boolean;+ setOpen: (v: boolean) => void;+ }>({ open: false, setOpen: () => {} });++ function Dialog({ children }: { children: React.ReactNode }) {+ const [open, setOpen] = useState(false);+ return <Ctx.Provider value={{ open, setOpen }}>{children}</Ctx.Provider>;+ }+ Dialog.Trigger = function Trigger({+ children,+ }: {+ children: React.ReactNode;+ }) {+ const ctx = useContext(Ctx);+ return (+ <span data-testid="dialog-trigger" onClick={() => ctx.setOpen(true)}>+ {children}+ </span>+ );+ };+ Dialog.Content = function Content({+ children,+ }: {+ children: React.ReactNode;+ }) {+ const ctx = useContext(Ctx);+ if (!ctx.open) return null;+ return <div data-testid="dialog-content">{children}</div>;+ };+ return { Dialog };+});++describe("StepsCollapse", () => {+ afterEach(() => {+ cleanup();+ });++ it("renders the 'Show steps' trigger button without opening the dialog", () => {+ render(+ <StepsCollapse>+ <div data-testid="step-body">step content</div>+ </StepsCollapse>,+ );++ expect(screen.getByText("Show steps")).toBeDefined();+ expect(screen.queryByTestId("dialog-content")).toBeNull();+ });++ it("opens the dialog and renders children on trigger click", () => {+ render(+ <StepsCollapse>+ <div data-testid="step-body">step content</div>+ </StepsCollapse>,+ );++ fireEvent.click(screen.getByTestId("dialog-trigger"));++ expect(screen.getByTestId("dialog-content")).toBeDefined();+ expect(screen.getByTestId("step-body")).toBeDefined();+ expect(screen.getByText("step content")).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.test.tsindex 831894d57b..82b132fc66 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.test.ts@@ -1,5 +1,10 @@import { describe, expect, it } from "vitest";-import { extractWorkspaceArtifacts, filePartToArtifactRef } from "./helpers";+import {+ extractWorkspaceArtifacts,+ filePartToArtifactRef,+ splitReasoningAndResponse,+ type MessagePart,+} from "./helpers";describe("extractWorkspaceArtifacts", () => {it("extracts a single workspace:// link with its markdown title", () => {@@ -101,3 +106,41 @@ describe("filePartToArtifactRef", () => {expect(overridden?.origin).toBe("agent");});});++describe("splitReasoningAndResponse", () => {+ const reasoning: MessagePart = {+ type: "reasoning",+ text: "thinking...",+ state: "done",+ } as unknown as MessagePart;+ const text: MessagePart = {+ type: "text",+ text: "final answer",+ state: "done",+ } as unknown as MessagePart;+ const tool: MessagePart = {+ type: "tool-run_block",+ toolCallId: "t1",+ state: "output-available",+ input: {},+ output: "ok",+ } as unknown as MessagePart;++ it("returns empty reasoning when there are no tool parts", () => {+ const out = splitReasoningAndResponse([reasoning, text]);+ expect(out.reasoning).toEqual([]);+ expect(out.response).toEqual([reasoning, text]);+ });++ it("keeps reasoning inside the reasoning group when tools precede the text", () => {+ const out = splitReasoningAndResponse([reasoning, tool, text]);+ expect(out.reasoning).toEqual([reasoning, tool]);+ expect(out.response).toEqual([text]);+ });++ it("splits tools into reasoning and text into response when no reasoning is present", () => {+ const out = splitReasoningAndResponse([tool, text]);+ expect(out.reasoning).toEqual([tool]);+ expect(out.response).toEqual([text]);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.tsindex e03dfaa26c..145e9eb329 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts@@ -150,6 +150,9 @@ export function splitReasoningAndResponse(parts: MessagePart[]): {if (isInteractiveToolPart(part)) {pinnedParts.push(part);} else {+ // Reasoning / thinking parts stay inside the outer "Show steps" modal+ // alongside the tool-use timeline — their own inline accordion handles+ // expansion inside the modal so there's no visual collision.reasoning.push(part);}}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.tsindex 33b2879cc9..102246c6d6 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts@@ -56,4 +56,162 @@ describe("convertChatSessionMessagesToUiMessages", () => {expect(result.messages).toHaveLength(1);expect(result.messages[0].role).toBe("user");});++ it("attaches a reasoning row between user/assistant to the surrounding assistant bubble", () => {+ const result = convertChatSessionMessagesToUiMessages(+ SESSION_ID,+ [+ { role: "user", content: "hi", sequence: 0 },+ { role: "reasoning", content: "thinking deeply", sequence: 1 },+ { role: "assistant", content: "hello back", sequence: 2 },+ ],+ { isComplete: true },+ );++ expect(result.messages).toHaveLength(2);+ expect(result.messages[0].role).toBe("user");+ const assistant = result.messages[1];+ expect(assistant.role).toBe("assistant");+ expect(assistant.parts).toHaveLength(2);+ expect(assistant.parts[0]).toMatchObject({+ type: "reasoning",+ text: "thinking deeply",+ state: "done",+ });+ expect(assistant.parts[1]).toMatchObject({+ type: "text",+ text: "hello back",+ });+ });++ it("merges separate reasoning and assistant DB rows into one UIMessage with reasoning first", () => {+ const result = convertChatSessionMessagesToUiMessages(+ SESSION_ID,+ [+ { role: "reasoning", content: "plan", sequence: 0 },+ { role: "assistant", content: "answer", sequence: 1 },+ ],+ { isComplete: true },+ );++ expect(result.messages).toHaveLength(1);+ expect(result.messages[0].role).toBe("assistant");+ expect(result.messages[0].parts.map((p) => p.type)).toEqual([+ "reasoning",+ "text",+ ]);+ });++ it("includes every reasoning row when multiple are present in the same turn", () => {+ const result = convertChatSessionMessagesToUiMessages(+ SESSION_ID,+ [+ { role: "reasoning", content: "step one", sequence: 0 },+ { role: "reasoning", content: "step two", sequence: 1 },+ { role: "assistant", content: "done", sequence: 2 },+ ],+ { isComplete: true },+ );++ expect(result.messages).toHaveLength(1);+ const parts = result.messages[0].parts;+ const reasoningParts = parts.filter((p) => p.type === "reasoning");+ expect(reasoningParts).toHaveLength(2);+ expect(reasoningParts[0]).toMatchObject({ text: "step one" });+ expect(reasoningParts[1]).toMatchObject({ text: "step two" });+ });++ it("skips reasoning rows with empty content so no reasoning part is emitted", () => {+ const result = convertChatSessionMessagesToUiMessages(+ SESSION_ID,+ [+ { role: "reasoning", content: "", sequence: 0 },+ { role: "assistant", content: "answer", sequence: 1 },+ ],+ { isComplete: true },+ );++ expect(result.messages).toHaveLength(1);+ const parts = result.messages[0].parts;+ expect(parts.some((p) => p.type === "reasoning")).toBe(false);+ expect(parts[0]).toMatchObject({ type: "text", text: "answer" });+ });++ it("captures duration_ms from the following assistant row on the merged bubble", () => {+ const result = convertChatSessionMessagesToUiMessages(+ SESSION_ID,+ [+ { role: "reasoning", content: "ponder", sequence: 0 },+ { role: "assistant", content: "reply", sequence: 1, duration_ms: 750 },+ ],+ { isComplete: true },+ );++ expect(result.messages).toHaveLength(1);+ const mergedId = result.messages[0].id;+ expect(result.durations.get(mergedId)).toBe(750);+ });++ it("falls back to idx-based ids when sequence is null so sequence-less rows don't collide", () => {+ const result = convertChatSessionMessagesToUiMessages(+ SESSION_ID,+ [+ { role: "user", content: "first" },+ { role: "assistant", content: "reply one" },+ { role: "user", content: "second" },+ ],+ { isComplete: true },+ );++ expect(result.messages).toHaveLength(3);+ const ids = result.messages.map((m) => m.id);+ expect(new Set(ids).size).toBe(3);+ for (const id of ids) {+ expect(id.startsWith(`${SESSION_ID}-idx-`)).toBe(true);+ }+ });++ it("uses sequence-based id when sequence is present and idx-based otherwise in the same list", () => {+ const result = convertChatSessionMessagesToUiMessages(+ SESSION_ID,+ [+ { role: "user", content: "seq-ed", sequence: 7 },+ { role: "assistant", content: "no-seq reply" },+ ],+ { isComplete: true },+ );++ expect(result.messages).toHaveLength(2);+ expect(result.messages[0].id).toBe(`${SESSION_ID}-seq-7`);+ expect(result.messages[1].id).toBe(`${SESSION_ID}-idx-1`);+ });++ it("skips role values that are neither user, assistant, tool, nor reasoning", () => {+ const result = convertChatSessionMessagesToUiMessages(+ SESSION_ID,+ [+ { role: "system", content: "ignored", sequence: 0 },+ { role: "assistant", content: "kept", sequence: 1 },+ ],+ { isComplete: true },+ );++ expect(result.messages).toHaveLength(1);+ expect(result.messages[0].role).toBe("assistant");+ });++ it("captures duration_ms directly on a standalone assistant row (non-merged branch)", () => {+ const result = convertChatSessionMessagesToUiMessages(+ SESSION_ID,+ [+ { role: "user", content: "hi", sequence: 0 },+ { role: "assistant", content: "reply", sequence: 1, duration_ms: 123 },+ ],+ { isComplete: true },+ );++ expect(result.messages).toHaveLength(2);+ const assistantId = result.messages[1].id;+ expect(result.durations.get(assistantId)).toBe(123);+ });});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.tsindex 10b0ad52c1..3eeadbfcd7 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts@@ -189,14 +189,32 @@ export function convertChatSessionMessagesToUiMessages(const uiMessages: UIMessage<unknown, UIDataTypes, UITools>[] = [];const durations = new Map<string, number>();- messages.forEach((msg) => {+ messages.forEach((msg, idx) => {if (msg.role === "tool") return;- if (msg.role !== "user" && msg.role !== "assistant") return;+ if (+ msg.role !== "user" &&+ msg.role !== "assistant" &&+ msg.role !== "reasoning"+ )+ return;++ // Role=="reasoning" rows carry extended_thinking content. Treat them as+ // contributing a reasoning part to the surrounding assistant bubble —+ // the consecutive-assistant merge below then folds them into the same+ // UIMessage as the text that follows.+ const uiRole: "user" | "assistant" =+ msg.role === "reasoning" ? "assistant" : msg.role;const parts: UIMessage<unknown, UIDataTypes, UITools>["parts"] = [];if (typeof msg.content === "string" && msg.content.trim()) {- if (msg.role === "user") {+ if (msg.role === "reasoning") {+ parts.push({+ type: "reasoning",+ text: msg.content,+ state: "done",+ } as UIMessage<unknown, UIDataTypes, UITools>["parts"][number]);+ } else if (msg.role === "user") {const { cleanText, fileParts } = extractFileParts(msg.content);if (cleanText) {parts.push({ type: "text", text: cleanText, state: "done" });@@ -209,7 +227,7 @@ export function convertChatSessionMessagesToUiMessages(}}- if (msg.role === "assistant" && Array.isArray(msg.tool_calls)) {+ if (uiRole === "assistant" && Array.isArray(msg.tool_calls)) {for (const rawToolCall of msg.tool_calls) {if (!rawToolCall || typeof rawToolCall !== "object") continue;const toolCall = rawToolCall as {@@ -260,10 +278,10 @@ export function convertChatSessionMessagesToUiMessages(}if (parts.length === 0) return;- // Merge consecutive assistant messages into a single UIMessage- // to avoid split bubbles on page reload.+ // Merge consecutive assistant messages (including reasoning rows) into a+ // single UIMessage to avoid split bubbles on page reload.const prevUI = uiMessages[uiMessages.length - 1];- if (msg.role === "assistant" && prevUI && prevUI.role === "assistant") {+ if (uiRole === "assistant" && prevUI && prevUI.role === "assistant") {prevUI.parts.push(...parts);// Capture duration on merged message (last assistant msg wins)if (msg.duration_ms != null) {@@ -272,14 +290,19 @@ export function convertChatSessionMessagesToUiMessages(return;}- const msgId = `${sessionId}-seq-${msg.sequence}`;+ // Fall back to the loop index when sequence is unexpectedly absent so+ // multiple sequence-less messages don't collide on the same React key.+ const msgId =+ msg.sequence != null+ ? `${sessionId}-seq-${msg.sequence}`+ : `${sessionId}-idx-${idx}`;uiMessages.push({id: msgId,- role: msg.role,+ role: uiRole,parts,});- if (msg.role === "assistant" && msg.duration_ms != null) {+ if (uiRole === "assistant" && msg.duration_ms != null) {durations.set(msgId, msg.duration_ms);}});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.tsindex 7778623693..3a7641010b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPendingChips.ts@@ -277,9 +277,32 @@ async function pollBackendAndPromote(const drained = localChips.slice(0, drainedCount);const remaining = localChips.slice(drainedCount);- setMessages((prev) => [- ...prev,- makePromotedUserBubble(drained, "midturn", crypto.randomUUID()),- ]);+ // Splice the promoted bubble at ``len-1`` so the trailing streaming+ // assistant stays at ``messages[-1]``. AI SDK's ``useChat`` streams+ // every SSE text/tool delta into the last message; pushing the user+ // bubble onto the tail makes ``[-1]`` the user bubble and every+ // subsequent chunk lands in the wrong slot (silently) until a page+ // refresh. Inserting before the assistant keeps the stream flowing.+ //+ // The one tradeoff: during streaming the promoted bubble clusters+ // just above the current streaming assistant — which is earlier in+ // the chronological order than the DB-canonical spot (between the+ // tool result it rode in on and the continuing assistant). AI SDK's+ // single-message-per-turn model can't represent that mid-turn split+ // client-side. ``useHydrateOnStreamEnd`` replaces the in-memory+ // messages with the DB-canonical order once the stream ends, so the+ // bubble snaps to the correct position.+ setMessages((prev) => {+ const bubble = makePromotedUserBubble(+ drained,+ "midturn",+ crypto.randomUUID(),+ );+ const lastIdx = prev.length - 1;+ if (lastIdx >= 0 && prev[lastIdx].role === "assistant") {+ return [...prev.slice(0, lastIdx), bubble, prev[lastIdx]];+ }+ return [...prev, bubble];+ });setQueuedMessages(remaining);}