From 9cae1bf7a14bddd61f2c9d51555ba97607e4a821 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Tue, 16 Jun 2026 16:40:20 +0200 Subject: [PATCH] refac --- .../components/chat/AssistantMessage.svelte | 157 +++++-------- .../src/lib/components/chat/ChatPanel.svelte | 39 +++- cptr/frontend/src/lib/i18n/locales/en.json | 1 + cptr/utils/ai.py | 141 +++++++----- cptr/utils/chat_task.py | 212 +++++++++++++----- 5 files changed, 327 insertions(+), 223 deletions(-) diff --git a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte index 736add6..51443d9 100644 --- a/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte +++ b/cptr/frontend/src/lib/components/chat/AssistantMessage.svelte @@ -196,11 +196,12 @@ } // ── Consecutive grouping logic ──────────────────────────────── - // Groups consecutive function_call items together, breaking on message items. + // Groups consecutive function_call and reasoning items together, breaking on message items. interface ToolGroup { type: 'tool_group'; calls: any[]; // function_call items + reasoning: any[]; // reasoning items outputs: Map; // call_id → function_call_output } @@ -214,12 +215,7 @@ item: any; } - interface ReasoningItem { - type: 'reasoning_item'; - item: any; - } - - type DisplayItem = ToolGroup | MessageItem | ArtifactItem | ReasoningItem; + type DisplayItem = ToolGroup | MessageItem | ArtifactItem; const outputText = $derived.by((): string => { return (output || []) @@ -249,8 +245,14 @@ } } + const ensureGroup = () => { + if (!currentGroup) { + currentGroup = { type: 'tool_group', calls: [], reasoning: [], outputs: outputMap }; + } + }; + const flushGroup = () => { - if (currentGroup && currentGroup.calls.length > 0) { + if (currentGroup && (currentGroup.calls.length > 0 || currentGroup.reasoning.length > 0)) { items.push(currentGroup); currentGroup = null; } @@ -258,19 +260,17 @@ for (const item of output) { if (item.type === 'function_call') { - if (!currentGroup) { - currentGroup = { type: 'tool_group', calls: [], outputs: outputMap }; - } - currentGroup.calls.push(item); + ensureGroup(); + currentGroup!.calls.push(item); + } else if (item.type === 'reasoning') { + ensureGroup(); + currentGroup!.reasoning.push(item); } else if (item.type === 'message') { flushGroup(); items.push({ type: 'message_item', item }); } else if (item.type === 'artifact') { flushGroup(); items.push({ type: 'artifact_item', item }); - } else if (item.type === 'reasoning') { - // Don't flush group — reasoning precedes tool calls - items.push({ type: 'reasoning_item', item }); } // function_call_output items are handled via outputMap, skip standalone render } @@ -384,44 +384,6 @@ c.text).join('') || ''} /> - {:else if displayItem.type === 'reasoning_item'} - {@const reasoningText = (displayItem.item.summary ?? displayItem.item.content ?? []) - .filter((p) => 'text' in p) - .map((p) => p.text ?? '') - .join('')} - {#if reasoningText} -
- - {#if expandedGroups.has(groupIdx)} -
-
-
{reasoningText}
-
-
- {/if} -
- {/if} {:else if displayItem.type === 'artifact_item'} {@const artifact = displayItem.item} {@const preview = (artifact.content || '') @@ -458,12 +420,19 @@ {:else if displayItem.type === 'tool_group'} {@const calls = displayItem.calls} + {@const reasoning = displayItem.reasoning} {@const outputs = displayItem.outputs} - {@const hasPending = groupHasPending(calls)} - {@const allDone = groupAllDone(calls)} - {@const hasRejected = groupHasRejected(calls)} + {@const isReasoningOnly = calls.length === 0 && reasoning.length > 0} + {@const hasPending = isReasoningOnly ? !done : groupHasPending(calls)} + {@const allDone = isReasoningOnly ? done : groupAllDone(calls)} + {@const hasRejected = isReasoningOnly ? false : groupHasRejected(calls)} {@const isGroupOpen = expandedGroups.has(groupIdx)} {@const hasPendingApproval = calls.some((c: any) => c.status === 'pending')} + {@const reasoningText = reasoning + .flatMap((ri: any) => ri.summary ?? ri.content ?? []) + .filter((p: any) => 'text' in p) + .map((p: any) => p.text ?? '') + .join('')}
@@ -477,7 +446,13 @@ class="flex items-center gap-1.5 text-sm min-w-0 {hasPending ? 'shimmer' : ''}" > - {#if hasPending} + {#if isReasoningOnly} +
+ + + +
+ {:else if hasPending}
- - + +
{:else if hasRejected}
- - + +
{:else}
- - + +
{/if}
- {hasPending ? $t('chat.exploring') : $t('chat.explored')} - {#if groupSummaryText(calls)} - {groupSummaryText(calls)}{done ? $t('chat.edit.thought') : $t('chat.thinking')} + {:else} + {hasPending ? $t('chat.exploring') : $t('chat.explored')} + {#if groupSummaryText(calls)} + {groupSummaryText(calls)} + {/if} {/if}
@@ -598,7 +544,12 @@ {#if isGroupOpen}
- {#each calls as item} + {#if reasoningText} +
+
{reasoningText}
+
+ {/if} + {#each calls as item} {@const args = item.arguments || {}} {@const toolName = item.name} {@const callId = item.call_id || toolName} diff --git a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte index 6c0c7fb..171fdb8 100644 --- a/cptr/frontend/src/lib/components/chat/ChatPanel.svelte +++ b/cptr/frontend/src/lib/components/chat/ChatPanel.svelte @@ -362,7 +362,20 @@ const existing = msg.output || []; const callId = data.output.call_id; const itemType = data.output.type; - if (callId && itemType) { + + if (itemType === 'reasoning') { + // Responses-style reasoning items stream as output item updates. + const itemId = data.output.id; + const existingIdx = itemId + ? existing.findIndex((o: any) => o.type === 'reasoning' && o.id === itemId) + : existing.findIndex((o: any) => o.type === 'reasoning'); + if (existingIdx >= 0) { + existing[existingIdx] = data.output; + msg.output = [...existing]; + } else { + msg.output = [...existing, data.output]; + } + } else if (callId && itemType) { const existingIdx = existing.findIndex( (o: any) => o.type === itemType && o.call_id === callId ); @@ -559,7 +572,11 @@ workspace, chatId, parentId, - { tool_approval_mode: mode, plan_mode: get(planMode), request_params: get(requestParams) }, + { + tool_approval_mode: mode, + plan_mode: get(planMode), + request_params: get(requestParams) + }, undefined, files ); @@ -829,7 +846,11 @@ workspace, chatId, msg.parent_id, - { tool_approval_mode: get(toolApprovalMode), plan_mode: get(planMode), request_params: get(requestParams) } + { + tool_approval_mode: get(toolApprovalMode), + plan_mode: get(planMode), + request_params: get(requestParams) + } ); if (result.user_message && result.assistant_message) { allMessages = [...allMessages, result.user_message, result.assistant_message]; @@ -873,7 +894,11 @@ {#if isLanding}
-
+

@@ -911,9 +936,9 @@ {:else} {#if loading} -
- -
+
+ +
{:else}
diff --git a/cptr/frontend/src/lib/i18n/locales/en.json b/cptr/frontend/src/lib/i18n/locales/en.json index 934112d..e5a3ad7 100644 --- a/cptr/frontend/src/lib/i18n/locales/en.json +++ b/cptr/frontend/src/lib/i18n/locales/en.json @@ -676,6 +676,7 @@ "chat.edit.text": "Text", "chat.edit.thought": "Thought", + "chat.thinking": "Thinking", "chat.edit.tool": "Tool", "chat.edit.item": "Item", diff --git a/cptr/utils/ai.py b/cptr/utils/ai.py index a41c95a..898a57e 100644 --- a/cptr/utils/ai.py +++ b/cptr/utils/ai.py @@ -1,7 +1,7 @@ """Provider streaming and completion functions: raw httpx. Each streaming function takes a ChatCompletionForm + url + key. -All yield normalized events: text_delta, tool_call, usage, done. +All yield normalized events: text_delta, output, tool_call, usage, done. chat_completion() provides a simple non-streaming call for lightweight tasks (title generation, summarization, etc.). @@ -10,6 +10,7 @@ chat_completion() provides a simple non-streaming call for lightweight tasks from __future__ import annotations import asyncio +import copy import json import logging import uuid @@ -28,6 +29,16 @@ from cptr.env import ( logger = logging.getLogger(__name__) +def _reasoning_output_item(text: str = "", *, status: str = "in_progress") -> dict: + """Create a Responses-style reasoning output item.""" + return { + "type": "reasoning", + "id": f"rs_{uuid.uuid4().hex}", + "status": status, + "content": [{"type": "text", "text": text}], + } + + def _openrouter_headers(url: str) -> dict[str, str]: """Return OpenRouter app-info headers when the URL is an OpenRouter endpoint.""" if "openrouter.ai" in url: @@ -169,7 +180,7 @@ def _to_anthropic_messages(messages: list[dict]) -> list[dict]: role = m["role"] if role == "system": continue # system goes in body.system - + content = m.get("content", "") if isinstance(content, list): formatted_content = [] @@ -177,14 +188,16 @@ def _to_anthropic_messages(messages: list[dict]) -> list[dict]: if block.get("type") == "text": formatted_content.append({"type": "text", "text": block.get("text", "")}) elif block.get("type") == "image": - formatted_content.append({ - "type": "image", - "source": { - "type": "base64", - "media_type": block.get("media_type", "image/jpeg"), - "data": block.get("base64", "") + formatted_content.append( + { + "type": "image", + "source": { + "type": "base64", + "media_type": block.get("media_type", "image/jpeg"), + "data": block.get("base64", ""), + }, } - }) + ) content = formatted_content if role == "tool": # tool result → Anthropic tool_result block @@ -196,14 +209,16 @@ def _to_anthropic_messages(messages: list[dict]) -> list[dict]: if block.get("type") == "text": tool_content.append({"type": "text", "text": block.get("text", "")}) elif block.get("type") == "image": - tool_content.append({ - "type": "image", - "source": { - "type": "base64", - "media_type": block.get("media_type", "image/jpeg"), - "data": block.get("base64", ""), + tool_content.append( + { + "type": "image", + "source": { + "type": "base64", + "media_type": block.get("media_type", "image/jpeg"), + "data": block.get("base64", ""), + }, } - }) + ) else: tool_content = content result.append( @@ -286,7 +301,10 @@ async def stream_anthropic( msg_usage = event.get("message", {}).get("usage", {}) if msg_usage: usage_data["input_tokens"] = msg_usage.get("input_tokens", 0) - for cache_key in ("cache_read_input_tokens", "cache_creation_input_tokens"): + for cache_key in ( + "cache_read_input_tokens", + "cache_creation_input_tokens", + ): if msg_usage.get(cache_key): usage_data[cache_key] = msg_usage[cache_key] @@ -345,13 +363,14 @@ async def stream_anthropic( def _reasoning_items_to_content(items: list[dict]) -> str: """Convert Responses API reasoning items to a reasoning_content string. - Reasoning items use the shape: {"type": "reasoning", "content": [{"type": "text", "text": "..."}]}. - We extract the text blocks and join them. + Reasoning items may expose text in content or summary blocks. We extract + those text blocks and join them for Chat Completions-compatible providers. """ texts: list[str] = [] for item in items: - for block in item.get("content", []): - if block.get("type") == "text" and block.get("text"): + blocks = item.get("content") or item.get("summary") or [] + for block in blocks: + if isinstance(block, dict) and block.get("type") == "text" and block.get("text"): texts.append(block["text"]) return "\n".join(texts) @@ -381,10 +400,7 @@ def _to_openai_messages(messages: list[dict], instructions: str) -> list[dict]: formatted_content.append(block) elif block.get("type") == "image": data_uri = f"data:{block.get('media_type', 'image/jpeg')};base64,{block.get('base64', '')}" - formatted_content.append({ - "type": "image_url", - "image_url": {"url": data_uri} - }) + formatted_content.append({"type": "image_url", "image_url": {"url": data_uri}}) new_m = dict(m) new_m["content"] = formatted_content # Convert reasoning_items → reasoning_content for round-tripping @@ -405,8 +421,7 @@ def _to_openai_messages(messages: list[dict], instructions: str) -> list[dict]: # Clean tool_calls: remove fc_id which is Responses-API-only if "tool_calls" in out: out["tool_calls"] = [ - {k: v for k, v in tc.items() if k != "fc_id"} - for tc in out["tool_calls"] + {k: v for k, v in tc.items() if k != "fc_id"} for tc in out["tool_calls"] ] result.append(out) return result @@ -454,10 +469,14 @@ async def stream_openai_completions( logger.info("[stream] openai completions status=%s", resp.status_code) if resp.status_code >= 400: error_body = await resp.aread() - logger.error("[stream] openai completions error body: %s", error_body.decode(errors="replace")) + logger.error( + "[stream] openai completions error body: %s", + error_body.decode(errors="replace"), + ) resp.raise_for_status() tool_calls: dict[int, dict] = {} reasoning_buffer = "" # Accumulate reasoning_content deltas (Kimi, DeepSeek) + reasoning_item: dict | None = None async for line in resp.aiter_lines(): if not line.startswith("data: ") or line == "data: [DONE]": continue @@ -472,6 +491,11 @@ async def stream_openai_completions( # Capture reasoning_content from providers like Kimi / DeepSeek if delta.get("reasoning_content"): reasoning_buffer += delta["reasoning_content"] + if reasoning_item is None: + reasoning_item = _reasoning_output_item() + reasoning_item["content"][0]["text"] = reasoning_buffer + emitted = True + yield {"type": "output", "item": copy.deepcopy(reasoning_item)} for tc in delta.get("tool_calls", []): idx = tc["index"] @@ -485,14 +509,11 @@ async def stream_openai_completions( if choices and choices[0].get("finish_reason") == "tool_calls": # Emit accumulated reasoning before tool calls - if reasoning_buffer: - yield { - "type": "reasoning", - "item": { - "type": "reasoning", - "content": [{"type": "text", "text": reasoning_buffer}], - }, - } + if reasoning_item is not None: + reasoning_item["status"] = "completed" + emitted = True + yield {"type": "output", "item": copy.deepcopy(reasoning_item)} + reasoning_item = None reasoning_buffer = "" for tc in tool_calls.values(): emitted = True @@ -504,6 +525,14 @@ async def stream_openai_completions( } if chunk.get("usage"): + # Emit any remaining reasoning BEFORE usage + # (usage triggers immediate save+return in chat_task) + if reasoning_item is not None: + reasoning_item["status"] = "completed" + emitted = True + yield {"type": "output", "item": copy.deepcopy(reasoning_item)} + reasoning_item = None + reasoning_buffer = "" raw = chunk["usage"] emitted = True yield { @@ -512,15 +541,11 @@ async def stream_openai_completions( "output_tokens": raw.get("completion_tokens", 0), } - # Emit any remaining reasoning (text-only response, no tool calls) - if reasoning_buffer: - yield { - "type": "reasoning", - "item": { - "type": "reasoning", - "content": [{"type": "text", "text": reasoning_buffer}], - }, - } + # Emit any remaining reasoning if no usage event was received + if reasoning_item is not None: + reasoning_item["status"] = "completed" + emitted = True + yield {"type": "output", "item": copy.deepcopy(reasoning_item)} emitted = True yield {"type": "done"} return @@ -544,11 +569,7 @@ def _to_responses_input(messages: list[dict], instructions: str) -> list[dict]: # Pre-collect all tool result call_ids so we can validate function_calls # have matching outputs. This prevents orphaned function_calls (from # crashes, data corruption, etc.) from permanently breaking the chat. - tool_result_ids = { - m.get("tool_call_id", "") - for m in messages - if m.get("role") == "tool" - } + tool_result_ids = {m.get("tool_call_id", "") for m in messages if m.get("role") == "tool"} items = [] for m in messages: @@ -608,13 +629,12 @@ def _to_responses_input(messages: list[dict], instructions: str) -> list[dict]: formatted_content = [] for block in content: if block.get("type") == "text": - formatted_content.append({"type": "input_text", "text": block.get("text", "")}) + formatted_content.append( + {"type": "input_text", "text": block.get("text", "")} + ) elif block.get("type") == "image": data_uri = f"data:{block.get('media_type', 'image/jpeg')};base64,{block.get('base64', '')}" - formatted_content.append({ - "type": "input_image", - "image_url": data_uri - }) + formatted_content.append({"type": "input_image", "image_url": data_uri}) items.append({"type": "message", "role": role, "content": formatted_content}) else: items.append({"type": "message", "role": role, "content": content}) @@ -653,7 +673,8 @@ async def stream_openai_responses( async with httpx.AsyncClient(timeout=_STREAM_TIMEOUT) as client: logger.info( "[stream] openai responses POST %s/responses model=%s input_items=%d types=%s", - url, form_data.model, + url, + form_data.model, len(body.get("input", [])), [i.get("type", i.get("role", "?")) for i in body.get("input", [])], ) @@ -663,7 +684,10 @@ async def stream_openai_responses( logger.info("[stream] openai responses status=%s", resp.status_code) if resp.status_code >= 400: error_body = await resp.aread() - logger.error("[stream] openai responses error body: %s", error_body.decode(errors="replace")) + logger.error( + "[stream] openai responses error body: %s", + error_body.decode(errors="replace"), + ) resp.raise_for_status() async for line in resp.aiter_lines(): if not line.startswith("data: "): @@ -691,8 +715,9 @@ async def stream_openai_responses( } elif item["type"] == "reasoning": # Reasoning items must be round-tripped for reasoning models + emitted = True yield { - "type": "reasoning", + "type": "output", "item": item, } diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 93407ad..4f48e62 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -614,9 +614,7 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic # This is needed to filter out orphaned function_calls # (e.g. from crashes, partial persistence, or data corruption). output_call_ids = { - item["call_id"] - for item in m.output - if item.get("type") == "function_call_output" + item["call_id"] for item in m.output if item.get("type") == "function_call_output" } # ── Group output items into per-iteration turns ── @@ -673,10 +671,7 @@ async def _load_message_history(chat_id: str, message_id: str) -> tuple[list[dic for ti, turn in enumerate(turns): # Filter calls to only those with matching outputs turn_output_ids = {o["call_id"] for o in turn["outputs"]} - matched_calls = [ - tc for tc in turn["calls"] - if tc["id"] in turn_output_ids - ] + matched_calls = [tc for tc in turn["calls"] if tc["id"] in turn_output_ids] if matched_calls: if ti == 0: # First turn: attach to the existing entry @@ -723,9 +718,7 @@ def _sanitize_tool_pairs(messages: list[dict]) -> list[dict]: """ # Collect all tool-result call_ids in the conversation tool_result_ids = { - m["tool_call_id"] - for m in messages - if m.get("role") == "tool" and m.get("tool_call_id") + m["tool_call_id"] for m in messages if m.get("role") == "tool" and m.get("tool_call_id") } # Collect all tool_call ids declared by assistant messages @@ -790,7 +783,10 @@ def _parse_image_data_uri(result: str) -> tuple[str, str] | None: def _append_tool_to_messages( - messages: list[dict], event: dict, result: str, provider: str, + messages: list[dict], + event: dict, + result: str, + provider: str, reasoning_items: list[dict] | None = None, ): """Append a tool call + result to the message history for the next API call.""" @@ -944,6 +940,49 @@ def _scrub_incomplete_items(output_items: list[dict]) -> None: item["status"] = "failed" +def _reasoning_text_len(item: dict) -> int: + """Return displayable reasoning text length for diagnostics.""" + blocks = item.get("summary") or item.get("content") or [] + if not isinstance(blocks, list): + return 0 + return sum(len(block.get("text") or "") for block in blocks if isinstance(block, dict)) + + +def _output_debug_stats(output_items: list[dict] | None) -> tuple[dict[str, int], int, int]: + """Return output type counts plus reasoning count/text length.""" + counts: dict[str, int] = {} + reasoning_count = 0 + reasoning_chars = 0 + for item in output_items or []: + itype = item.get("type", "?") + counts[itype] = counts.get(itype, 0) + 1 + if itype == "reasoning": + reasoning_count += 1 + reasoning_chars += _reasoning_text_len(item) + return counts, reasoning_count, reasoning_chars + + +def _output_item_key(item: dict) -> tuple | None: + """Stable key for Responses-style output item updates.""" + if item.get("id"): + return ("id", item["id"]) + if item.get("type") and item.get("call_id"): + return ("call", item["type"], item["call_id"]) + return None + + +def _upsert_output_item(items: list[dict], item: dict) -> bool: + """Insert or replace a Responses-style output item by id/call_id.""" + key = _output_item_key(item) + if key is not None: + for idx, existing in enumerate(items): + if _output_item_key(existing) == key: + items[idx] = item + return False + items.append(item) + return True + + def _find_safe_split(messages: list[dict], target_keep: int) -> int: """Find a safe split index that doesn't break tool call pairs. @@ -1088,6 +1127,27 @@ async def run_chat_task( """Update in-memory state so API can serve it on refresh.""" _task_state[message_id] = {"content": content, "output": output_items} + async def _save_message(save_reason: str, **kwargs) -> bool: + """Persist a message update and log enough detail to debug skipped saves.""" + saved_output = kwargs.get("output", output_items) + saved_content = kwargs.get("content", content) + counts, reasoning_count, reasoning_chars = _output_debug_stats(saved_output) + logger.info( + "[task %s] db save (%s) begin: done=%s content=%d chars output=%d items reasoning=%d items/%d chars types=%s", + message_id[:8], + save_reason, + kwargs.get("done", ""), + len(saved_content or ""), + len(saved_output or []), + reasoning_count, + reasoning_chars, + counts, + ) + saved = await ChatMessage.update(message_id, **kwargs) + log = logger.info if saved else logger.warning + log("[task %s] db save (%s) result: updated=%s", message_id[:8], save_reason, saved) + return saved + try: provider = connection["provider"] api_key = decrypt_key(connection.get("api_key", ""), _get_jwt_secret()) @@ -1274,7 +1334,8 @@ async def run_chat_task( restart = False pending_calls: list[dict] = [] # Collect tool calls from this response - pending_reasoning: list[dict] = [] # Reasoning items for round-tripping + response_reasoning_items: list[dict] = [] # Pair with tool outputs on the next request + streamed_reasoning_chars = 0 async for event in stream: if event["type"] == "text_delta": @@ -1287,9 +1348,30 @@ async def run_chat_task( # Collect tool call — don't execute yet pending_calls.append(event) - elif event["type"] == "reasoning": - # Collect reasoning items for round-tripping with tool calls - pending_reasoning.append(event["item"]) + elif event["type"] in ("output", "reasoning"): + # Providers stream normalized Responses-style output items. + # "reasoning" is kept temporarily for compatibility with older + # provider adapters. + item = event["item"] + _upsert_output_item(output_items, item) + if item.get("type") == "reasoning": + streamed_reasoning_chars = max( + streamed_reasoning_chars, + _reasoning_text_len(item), + ) + if item.get("status") in (None, "completed"): + _upsert_output_item(response_reasoning_items, item) + logger.info( + "[task %s] output item: type=%s status=%s output=%d items reasoning_chars=%d response_reasoning_items=%d", + message_id[:8], + item.get("type"), + item.get("status"), + len(output_items), + streamed_reasoning_chars, + len(response_reasoning_items), + ) + _sync_state() + await emit(output=item) elif event["type"] == "usage": usage = {k: v for k, v in event.items() if k != "type"} @@ -1303,15 +1385,14 @@ async def run_chat_task( if not pending_calls: # No tool calls — final response, we're done _flush_text() - logger.info( - "[task %s] save (usage): content=%d chars, output=%d items, types=%s", - message_id[:8], - len(content), - len(output_items), - [i.get("type") for i in output_items], - ) - await ChatMessage.update( - message_id, + if streamed_reasoning_chars and not response_reasoning_items: + logger.warning( + "[task %s] reasoning output streamed (%d chars) but no completed reasoning item arrived before usage; DB output may contain only in-progress reasoning", + message_id[:8], + streamed_reasoning_chars, + ) + await _save_message( + "usage", content=content, output=output_items, usage=usage, @@ -1322,11 +1403,36 @@ async def run_chat_task( return elif event["type"] == "done": - # Stream ended without explicit usage - pass + # Stream ended — if usage already triggered a save+return, we won't + # reach here. This is the fallback for providers that don't support + # stream_options.include_usage. + if not pending_calls: + _flush_text() + if streamed_reasoning_chars and not response_reasoning_items: + logger.warning( + "[task %s] reasoning output streamed (%d chars) but no completed reasoning item arrived before done; DB output may contain only in-progress reasoning", + message_id[:8], + streamed_reasoning_chars, + ) + await _save_message( + "done fallback", + content=content, + output=output_items, + usage=last_usage, + done=True, + ) + _task_state.pop(message_id, None) + await _emit_done() + return # ── Process collected tool calls ──────────────────── if pending_calls: + if streamed_reasoning_chars and not response_reasoning_items: + logger.warning( + "[task %s] reasoning output streamed (%d chars) before tool calls but no completed reasoning item arrived; model continuation will not include reasoning items", + message_id[:8], + streamed_reasoning_chars, + ) flushed_item = _flush_text() tool_ctx = { @@ -1352,9 +1458,6 @@ async def run_chat_task( if needs_approval: # First non-auto tool stops the loop for approval tc = needs_approval - # Store reasoning items before function_call for round-tripping - for ri in pending_reasoning: - output_items.append(ri) item = { "type": "function_call", "id": str(uuid.uuid4()), @@ -1365,8 +1468,8 @@ async def run_chat_task( "status": "pending", } output_items.append(item) - await ChatMessage.update( - message_id, + await _save_message( + "pending approval", content=content, output=output_items, done=False, @@ -1378,9 +1481,7 @@ async def run_chat_task( await emit(done=True) return - # All calls are auto-approved — store reasoning + build UI items - for ri in pending_reasoning: - output_items.append(ri) + # All calls are auto-approved — build UI items call_items: list[tuple[dict, dict]] = [] # (event, ui_item) for tc in pending_calls: item = { @@ -1403,8 +1504,12 @@ async def run_chat_task( _sync_state() # Separate delegate_task (concurrent) from others (sequential) - delegate_indices = [i for i, (tc, _) in enumerate(call_items) if tc["name"] == "delegate_task"] - other_indices = [i for i, (tc, _) in enumerate(call_items) if tc["name"] != "delegate_task"] + delegate_indices = [ + i for i, (tc, _) in enumerate(call_items) if tc["name"] == "delegate_task" + ] + other_indices = [ + i for i, (tc, _) in enumerate(call_items) if tc["name"] != "delegate_task" + ] # Execute non-delegate tools sequentially first # Collect results for batch message construction @@ -1443,8 +1548,10 @@ async def run_chat_task( # with their shared reasoning items (required for reasoning model round-tripping) if sequential_results: _append_batch_to_messages( - messages, sequential_results, provider, - reasoning_items=pending_reasoning, + messages, + sequential_results, + provider, + reasoning_items=response_reasoning_items, ) new_messages_since += 1 + len(sequential_results) @@ -1489,30 +1596,25 @@ async def run_chat_task( # Build combined message for all delegate calls if delegate_results: # Only attach reasoning if sequential calls didn't consume it - ri = pending_reasoning if not other_indices else None + ri = response_reasoning_items if not other_indices else None _append_batch_to_messages( - messages, delegate_results, provider, + messages, + delegate_results, + provider, reasoning_items=ri, ) new_messages_since += 1 + len(delegate_results) # Persist after all tool calls - await ChatMessage.update(message_id, content=content, output=output_items) + await _save_message("tool calls complete", content=content, output=output_items) restart = True if not restart: flushed_item = _flush_text() if flushed_item: await emit(output=flushed_item) - logger.info( - "[task %s] save (end): content=%d chars, output=%d items, types=%s", - message_id[:8], - len(content), - len(output_items), - [i.get("type") for i in output_items], - ) - await ChatMessage.update( - message_id, + await _save_message( + "end", content=content, output=output_items, done=True, @@ -1522,8 +1624,8 @@ async def run_chat_task( return # Max iterations reached - await ChatMessage.update( - message_id, + await _save_message( + "max iterations", content=content, output=output_items, done=True, @@ -1535,7 +1637,7 @@ async def run_chat_task( except asyncio.CancelledError: _flush_text() _scrub_incomplete_items(output_items) - await ChatMessage.update(message_id, content=content, output=output_items, done=True) + await _save_message("cancelled", content=content, output=output_items, done=True) _task_state.pop(message_id, None) await _emit_done() except Exception as e: @@ -1563,8 +1665,8 @@ async def run_chat_task( if flushed_item: await emit(output=flushed_item) _scrub_incomplete_items(output_items) - await ChatMessage.update( - message_id, + await _save_message( + "error", content=content, output=output_items, done=True,