DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: handle DeepSeek reasoning budget exhaustion (#1331)
Gao Chenkai3192757d452e
diff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yamlindex a129d194c..e5e6eb037 100644--- a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml+++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml@@ -149,6 +149,8 @@ notices:empty_final_response: "I could not produce a useful response from the model output. Please try again or narrow the request."reasoning_only_final_response: "The model produced internal reasoning but no usable answer. Please try again or narrow the request."empty_finish_nudged: "The round produced only internal reasoning; asked the model to continue."+ reasoning_progress: "The model is still reasoning; it has not produced an answer or tool action yet."+ reasoning_budget_exhausted: "The model exhausted its output budget on internal reasoning twice without producing an answer or tool action. Please retry, lower reasoning effort, or split the task into smaller steps."empty:empty_reply: "(empty reply)"diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yamlindex 6be0a2d46..d453bce4f 100644--- a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml+++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml@@ -112,6 +112,8 @@ notices:empty_final_response: "未能从模型输出中得到有效回答。请重试或缩小问题范围。"reasoning_only_final_response: "模型产生了内部推理,但没有可用回答。请重试或缩小问题范围。"empty_finish_nudged: "模型这一轮只有内部推理,已提示其继续执行。"+ reasoning_progress: "模型仍在进行内部推理,尚未生成回答或执行工具。"+ reasoning_budget_exhausted: "模型连续两轮将输出预算耗尽在内部推理中,未生成回答或执行工具。请重试、降低推理强度,或将任务拆分成更小的步骤。"empty:empty_reply: "(空回复)"diff --git a/deeptutor/agents/loop/agent_loop.py b/deeptutor/agents/loop/agent_loop.pyindex dc1aacc88..214d44d77 100644--- a/deeptutor/agents/loop/agent_loop.py+++ b/deeptutor/agents/loop/agent_loop.py@@ -32,6 +32,7 @@ from contextlib import suppressfrom dataclasses import dataclass, fieldimport jsonimport logging+from time import monotonicfrom types import SimpleNamespacefrom typing import TYPE_CHECKING, Any@@ -49,6 +50,7 @@ from deeptutor.runtime.agentic.usage import message_content_chars, record_streamfrom deeptutor.runtime.stream_bus import StreamBusfrom deeptutor.services.llm import (LLMProviderTransportError,+ LLMReasoningBudgetExhausted,clean_thinking_tags,supports_streaming,)@@ -61,6 +63,7 @@ from deeptutor.services.llm.request_compat import (is_transient_transport_error,logged_error_text,)+from deeptutor.services.llm.usage_frame import usage_breakdownfrom deeptutor.services.llm.utils import unreachable_endpoint_hintfrom deeptutor.services.session.provider_response_state import (normalize_provider_response_state,@@ -97,6 +100,33 @@ def _finish_was_truncated(reason: str | None) -> bool:return str(reason or "").strip().lower() in _TRUNCATED_FINISH_REASONS+def _reasoning_budget_exhausted(result: "LLMCallResult", max_tokens: int) -> bool:+ """Detect a round that spent its output budget without taking action."""+ if result.tool_calls or result.visible_text.strip():+ return False+ has_reasoning = bool(result.reasoning_chars or result.reasoning_content) or any(+ isinstance(item, dict) and item.get("type") == "reasoning"+ for item in result.response_output_items+ )+ if not has_reasoning:+ return False+ # Content filtering is a terminal provider decision, not a reasoning+ # budget failure. In particular, do not let the token-count fallback below+ # turn a filtered response that happens to reach the cap into a retry loop.+ if str(result.finish_reason or "").strip().lower() == "content_filter":+ return False+ if _finish_was_truncated(result.finish_reason):+ return True+ completion_tokens = result.usage.get("completion_tokens")+ if completion_tokens is None or completion_tokens < max(1, int(max_tokens)):+ return False+ # Some gateways omit the terminal reason and report an incomplete+ # reasoning response with a zero/absent reasoning-token detail. Once the+ # canonical completion counter reaches this round's request cap, the+ # zero-visible-output shape is enough to identify the exhausted round.+ return True++def _join_answer_parts(parts: list[str], final_text: str) -> str:"""Build the canonical answer returned by RESULT across continuations."""return "".join([*parts, final_text])@@ -110,6 +140,7 @@ class AgentLoopState:exploration_rounds: int = 0settlement_rounds: int = 0tool_steps: int = 0+ reasoning_budget_recoveries: int = 0sources: list[dict[str, Any]] = field(default_factory=list)@@ -122,6 +153,11 @@ class LLMCallResult:tool_calls: list[dict[str, Any]] = field(default_factory=list)# Anthropic's signed thinking blocks, replayed verbatim on the next round.thinking_blocks: list[dict[str, Any]] = field(default_factory=list)+ usage: dict[str, int] = field(default_factory=dict)+ output_chars: int = 0+ reasoning_chars: int = 0+ content_chars: int = 0+ tool_call_chars: int = 0finish_reason: str = ""# This round's ``call_status`` metadata, set whether or not the round was# buffered. A streamed round needs it to publish a correction when its@@ -184,6 +220,34 @@ def _assistant_round_message(result: LLMCallResult) -> dict[str, Any]:return message+def _has_replayable_assistant_state(result: LLMCallResult) -> bool:+ """Whether a tool-less round still has provider state to replay."""+ return bool(+ result.text+ or result.reasoning_content+ or result.response_output_items+ or result.thinking_blocks+ )+++def _reasoning_item_text(item: dict[str, Any]) -> str:+ """Extract display-safe text from a Responses reasoning output item."""+ parts: list[str] = []+ for block in item.get("content") or []:+ if not isinstance(block, dict):+ continue+ text = block.get("text")+ if text:+ parts.append(str(text))+ for summary in item.get("summary") or []:+ if not isinstance(summary, dict):+ continue+ text = summary.get("text")+ if text:+ parts.append(str(text))+ return "".join(parts)++class AgentLoop:"""Run one chat turn as a single agent loop over one conversation."""@@ -357,7 +421,37 @@ class AgentLoop:state.exploration_rounds += 1if not result.tool_calls:final_text = self._clean(result.text)- if _finish_was_truncated(result.finish_reason):+ if _finish_was_truncated(result.finish_reason) or _reasoning_budget_exhausted(+ result, self.pipeline.loop_max_tokens+ ):+ if _reasoning_budget_exhausted(result, self.pipeline.loop_max_tokens):+ await self._release_deferred_output(result)+ if state.reasoning_budget_recoveries >= 1:+ message = self.pipeline._t(+ "notices.reasoning_budget_exhausted",+ default=(+ "The model exhausted its output budget on internal "+ "reasoning twice without producing an answer or "+ "tool action. Please retry, lower reasoning effort, "+ "or split the task into smaller steps."+ ),+ )+ logger.warning(+ "reasoning budget exhausted repeatedly; stopping turn "+ "rounds=%d recoveries=%d",+ state.rounds,+ state.reasoning_budget_recoveries,+ )+ raise LLMReasoningBudgetExhausted(+ message,+ diagnostics={+ "rounds": state.rounds,+ "reasoning_chars": result.reasoning_chars,+ "completion_tokens": result.usage.get("completion_tokens"),+ "reasoning_tokens": result.usage.get("reasoning_tokens"),+ },+ )+ state.reasoning_budget_recoveries += 1# ``length`` is an incomplete generation, not the model's# decision to finish. Keep its visible prefix in protocol# and ask for a continuation. The ordinary exploration /@@ -377,7 +471,7 @@ class AgentLoop:)if result.visible_text:continued_answer_parts.append(result.visible_text)- if result.text:+ if _has_replayable_assistant_state(result):messages.append(_assistant_round_message(result))if result.visible_text:instruction = self.pipeline._t(@@ -439,7 +533,7 @@ class AgentLoop:stage=self.stage,metadata={"trace_kind": "warning"},)- if result.text:+ if _has_replayable_assistant_state(result):messages.append(_assistant_round_message(result))if reasoning_only_recoveries >= MAX_REASONING_ONLY_RECOVERIES:self._append_loop_instruction(@@ -708,6 +802,31 @@ class AgentLoop:continued_answer_parts=continued_answer_parts,)state.rounds += 1+ # Two readings of one scene, at different precisions. The budget+ # check fires only when this round demonstrably hit its cap — that is+ # a configuration the user can act on (lower the effort, split the+ # task), so it is worth failing the turn with the counters that prove+ # it. Everything else that reasoned without answering is a softer+ # miss: the turn still ends, but it says which kind of empty it was+ # rather than reporting an opaque model failure.+ if _reasoning_budget_exhausted(result, self.pipeline.loop_max_tokens):+ message = self.pipeline._t(+ "notices.reasoning_budget_exhausted",+ default=(+ "The model exhausted its output budget on internal reasoning "+ "without producing an answer or tool action. Please retry, "+ "lower reasoning effort, or split the task into smaller steps."+ ),+ )+ raise LLMReasoningBudgetExhausted(+ message,+ diagnostics={+ "rounds": state.rounds,+ "reasoning_chars": result.reasoning_chars,+ "completion_tokens": result.usage.get("completion_tokens"),+ "reasoning_tokens": result.usage.get("reasoning_tokens"),+ },+ )reasoning_without_answer = bool(result.reasoning_content) or bool(result.text.strip() and not self._clean(result.text))@@ -920,7 +1039,14 @@ class AgentLoop:))output_chars = 0+ reasoning_chars = 0+ content_chars = 0+ tool_call_chars = 0+ call_started_at = monotonic()+ last_reasoning_progress_at = call_started_at+ action_started = Falsefinish_reason = ""+ reasoning_progress_task: asyncio.Task[None] | None = Nonethink_filter = InlineThinkFilter()# DeepSeek's Anthropic-compatible endpoint can interleave# user-facing prose and DSML calls in one content stream.@@ -930,18 +1056,25 @@ class AgentLoop:output_emitted = Falseasync def _emit_segments(segments: list[tuple[str, str]]) -> None:- nonlocal answer_content_emitted, output_emitted+ nonlocal action_started, answer_content_emitted, content_chars, output_emitted+ nonlocal reasoning_charsfor kind, segment in segments:if kind == "thinking":# Reasoning goes to the trace on every round shape.# A forced tool round used to skip this whole function,# which discarded the model's own inline ``<think>``# block along with the prose it was written around.+ reasoning_chars += len(segment)output_emitted = True+ await _ensure_reasoning_progress_task()await self.stream.thinking(segment, source=self.source, stage=stage, metadata=chunk_meta)+ await _maybe_emit_reasoning_progress()continue+ if segment.strip():+ action_started = True+ content_chars += len(segment)if forced_tool_choice:# This round exists to produce a call, so its prose is# not an answer and must not reach the reader — but@@ -956,6 +1089,57 @@ class AgentLoop:segment, source=self.source, stage=stage, metadata=chunk_meta)+ async def _maybe_emit_reasoning_progress() -> None:+ nonlocal last_reasoning_progress_at+ if action_started or reasoning_chars <= 0:+ return+ now = monotonic()+ if now - last_reasoning_progress_at < 15.0:+ return+ last_reasoning_progress_at = now+ await self.stream.progress(+ self.pipeline._t(+ "notices.reasoning_progress",+ default=(+ "The model is still reasoning; it has not produced an "+ "answer or tool action yet."+ ),+ ),+ source=self.source,+ stage=stage,+ metadata=merge_trace_metadata(+ trace_meta,+ {+ "trace_kind": "reasoning_progress",+ "reasoning_chars": reasoning_chars,+ "elapsed_s": round(now - call_started_at, 1),+ },+ ),+ )++ async def _reasoning_progress_loop() -> None:+ """Keep progress visible while a provider is between chunks."""+ while True:+ await asyncio.sleep(15.0)+ if action_started or reasoning_chars <= 0:+ return+ await _maybe_emit_reasoning_progress()++ async def _ensure_reasoning_progress_task() -> None:+ nonlocal reasoning_progress_task+ if reasoning_progress_task is None or reasoning_progress_task.done():+ reasoning_progress_task = asyncio.create_task(_reasoning_progress_loop())++ async def _stop_reasoning_progress_task() -> None:+ nonlocal reasoning_progress_task+ task = reasoning_progress_task+ reasoning_progress_task = None+ if task is None or task.done():+ return+ task.cancel()+ with suppress(asyncio.CancelledError):+ await task+response_stream = Nonetry:response_stream = await self._create_response_stream(kwargs, trace_meta, stage)@@ -977,6 +1161,8 @@ class AgentLoop:# handled below. Both end at the same emitter.preview = provider_fields.get("tool_args_preview")if isinstance(preview, dict) and ask_user_drafts is not None:+ if str(preview.get("arguments") or ""):+ action_started = Trueawait ask_user_drafts.observe(call_id=str(preview.get("id") or ""),tool_name=str(preview.get("name") or ""),@@ -995,6 +1181,43 @@ class AgentLoop:response_output_items = [dict(item) for item in native_items if isinstance(item, dict)]+ provider_reasoning = provider_fields.get("reasoning_content")+ if (+ not reasoning_parts+ and isinstance(provider_reasoning, str)+ and provider_reasoning+ ):+ reasoning_parts.append(provider_reasoning)+ reasoning_chars += len(provider_reasoning)+ output_chars += len(provider_reasoning)+ output_emitted = True+ await _ensure_reasoning_progress_task()+ await self.stream.thinking(+ provider_reasoning,+ source=self.source,+ stage=stage,+ metadata=chunk_meta,+ )+ await _maybe_emit_reasoning_progress()+ if not reasoning_parts:+ for item in native_items or []:+ if not isinstance(item, dict) or item.get("type") != "reasoning":+ continue+ item_reasoning = _reasoning_item_text(item)+ if not item_reasoning:+ continue+ reasoning_parts.append(item_reasoning)+ reasoning_chars += len(item_reasoning)+ output_chars += len(item_reasoning)+ output_emitted = True+ await _ensure_reasoning_progress_task()+ await self.stream.thinking(+ item_reasoning,+ source=self.source,+ stage=stage,+ metadata=chunk_meta,+ )+ await _maybe_emit_reasoning_progress()delta = getattr(choice, "delta", None)if delta is None:continue@@ -1006,11 +1229,14 @@ class AgentLoop:)if reasoning_text:reasoning_parts.append(reasoning_text)+ reasoning_chars += len(reasoning_text)output_chars += len(reasoning_text)output_emitted = True+ await _ensure_reasoning_progress_task()await self.stream.thinking(reasoning_text, source=self.source, stage=stage, metadata=chunk_meta)+ await _maybe_emit_reasoning_progress()content = getattr(delta, "content", None)if content:@@ -1024,7 +1250,11 @@ class AgentLoop:await _emit_segments(think_filter.feed(visible_content))for tc_delta in getattr(delta, "tool_calls", None) or []:- output_chars += tool_acc.feed(tc_delta)+ fed_chars = tool_acc.feed(tc_delta)+ tool_call_chars += fed_chars+ output_chars += fed_chars+ if fed_chars:+ action_started = Trueif ask_user_drafts is not None:index = int(getattr(tc_delta, "index", 0) or 0)part = tool_acc.part_at(index)@@ -1107,6 +1337,7 @@ class AgentLoop:partial_response=partial_response,) from excfinally:+ await _stop_reasoning_progress_task()close = getattr(response_stream, "close", None)if callable(close):with suppress(Exception):@@ -1118,6 +1349,7 @@ class AgentLoop:await _emit_segments(think_filter.feed(dsml_tail))await _emit_segments(think_filter.flush())text = "".join(text_parts)+ usage_details = usage_breakdown(usage_seen)record_streamed_usage(self.pipeline.usage,usage_seen,@@ -1189,6 +1421,25 @@ class AgentLoop:)truncated_round = call_kind == "agent_loop_round" and _finish_was_truncated(finish_reason)+ visible_text = "".join(visible_text_parts)+ reasoning_budget_exhausted = bool(+ call_kind == "agent_loop_round"+ and not tool_calls+ and not visible_text.strip()+ and (+ reasoning_chars > 0+ or bool(reasoning_parts)+ or any(+ isinstance(item, dict) and item.get("type") == "reasoning"+ for item in response_output_items+ )+ )+ and str(finish_reason or "").strip().lower() != "content_filter"+ and (+ truncated_round+ or (usage_details.get("completion_tokens", 0) >= max(1, int(max_tokens)))+ )+ )completion_metadata: dict[str, Any] = {"trace_kind": "call_status","call_state": "complete",@@ -1196,7 +1447,48 @@ class AgentLoop:# finish whose text is the user-facing answer. Token-truncated# output remains visible but is not terminal: the loop continues."call_role": "narration" if tool_calls or truncated_round else "finish",+ "finish_reason": finish_reason or "stop",+ "requested_max_tokens": int(max_tokens),+ "usage_reported": bool(usage_details),+ "output_chars": output_chars,+ "reasoning_chars": reasoning_chars,+ "content_chars": content_chars,+ "tool_call_chars": tool_call_chars,+ "tool_call_count": len(tool_calls),}+ for key in ("prompt_tokens", "completion_tokens", "total_tokens", "reasoning_tokens"):+ completion_metadata[key] = usage_details.get(key, "unavailable")+ if reasoning_budget_exhausted:+ completion_metadata["reasoning_budget_exhausted"] = True+ log_line = (+ "agent_loop_round_complete model=%s call_id=%s finish_reason=%s "+ "requested_max_tokens=%d usage_reported=%s prompt_tokens=%s "+ "completion_tokens=%s reasoning_tokens=%s output_chars=%d "+ "reasoning_chars=%d content_chars=%d tool_call_chars=%d tool_call_count=%d"+ )+ log_args = (+ self.pipeline.model,+ call_id,+ finish_reason or "stop",+ int(max_tokens),+ bool(usage_details),+ usage_details.get("prompt_tokens", "unavailable"),+ usage_details.get("completion_tokens", "unavailable"),+ usage_details.get("reasoning_tokens", "unavailable"),+ output_chars,+ reasoning_chars,+ content_chars,+ tool_call_chars,+ len(tool_calls),+ )+ if (+ truncated_round+ or reasoning_budget_exhausted+ or (not tool_calls and not visible_text.strip())+ ):+ logger.warning(log_line, *log_args)+ else:+ logger.info(log_line, *log_args)mastery_tool_round = bool(tool_calls) and bool(self.context.metadata.get("mastery_mode"))if (dsml_calls or truncated_round or mastery_tool_round) and answer_content_emitted:# DSML providers may intentionally combine tutor feedback and an@@ -1226,11 +1518,16 @@ class AgentLoop:)return LLMCallResult(text=text,- visible_text="".join(visible_text_parts),+ visible_text=visible_text,response_output_items=response_output_items,reasoning_content="".join(reasoning_parts),tool_calls=tool_calls,thinking_blocks=thinking_blocks,+ usage=usage_details,+ output_chars=output_chars,+ reasoning_chars=reasoning_chars,+ content_chars=content_chars,+ tool_call_chars=tool_call_chars,finish_reason=finish_reason,completion_metadata=completion_event_metadata,deferred_chunk_metadata=chunk_meta if defer_visible_output else None,diff --git a/deeptutor/runtime/agentic/client.py b/deeptutor/runtime/agentic/client.pyindex 25d2ffe91..12aaf5451 100644--- a/deeptutor/runtime/agentic/client.py+++ b/deeptutor/runtime/agentic/client.py@@ -440,6 +440,8 @@ class _ProviderOpenAIAdapter:_openai_tool_call(tool_call, index=index)for index, tool_call in enumerate(response.tool_calls or [])],+ reasoning_content=response.reasoning_content,+ thinking_blocks=response.thinking_blocks,provider_specific_fields=response.provider_specific_fields,),finish_reason=(diff --git a/deeptutor/runtime/orchestrator.py b/deeptutor/runtime/orchestrator.pyindex 887e982bf..eff356ffb 100644--- a/deeptutor/runtime/orchestrator.py+++ b/deeptutor/runtime/orchestrator.py@@ -132,6 +132,7 @@ class ChatOrchestrator:async def _run() -> None:status = "completed"+ terminal_error_metadata: dict[str, Any] = {}try:await capability.run(context, bus)except Exception as exc:@@ -150,6 +151,11 @@ class ChatOrchestrator:partial_response = getattr(exc, "partial_response", None)if isinstance(partial_response, bool):error_metadata["partial_response"] = partial_response+ terminal_error_metadata = {+ key: error_metadata[key]+ for key in ("error_code", "retryable", "partial_response")+ if key in error_metadata+ }await bus.error(str(exc),source=cap_name,@@ -160,7 +166,7 @@ class ChatOrchestrator:StreamEvent(type=StreamEventType.DONE,source=cap_name,- metadata={"status": status},+ metadata={"status": status, **terminal_error_metadata},))await bus.close()diff --git a/deeptutor/services/llm/__init__.py b/deeptutor/services/llm/__init__.pyindex c3c3756ba..9f37b59eb 100644--- a/deeptutor/services/llm/__init__.py+++ b/deeptutor/services/llm/__init__.py@@ -83,6 +83,7 @@ from .exceptions import (LLMProviderError,LLMProviderTransportError,LLMRateLimitError,+ LLMReasoningBudgetExhausted,LLMTimeoutError,)from .factory import (@@ -138,6 +139,7 @@ __all__ = ["LLMConfigError","LLMProviderError","LLMProviderTransportError",+ "LLMReasoningBudgetExhausted","LLMAPIError","LLMTimeoutError","LLMRateLimitError",diff --git a/deeptutor/services/llm/exceptions.py b/deeptutor/services/llm/exceptions.pyindex fb63c186b..3a55b31a1 100644--- a/deeptutor/services/llm/exceptions.py+++ b/deeptutor/services/llm/exceptions.py@@ -41,6 +41,17 @@ class LLMProviderError(LLMError):pass+class LLMReasoningBudgetExhausted(LLMProviderError):+ """The model exhausted its output budget while producing only reasoning."""++ error_code = "reasoning_budget_exhausted"+ retryable = True++ def __init__(self, message: str, *, diagnostics: dict[str, object] | None = None):+ super().__init__(message)+ self.diagnostics = diagnostics or {}++class LLMProviderTransportError(LLMProviderError):"""A retryable provider connection or response-stream failure."""@@ -160,6 +171,7 @@ __all__ = ["LLMConfigError","LLMProviderError","LLMProviderTransportError",+ "LLMReasoningBudgetExhausted","LLMCircuitBreakerError","LLMAPIError","LLMTimeoutError",diff --git a/deeptutor/services/llm/provider_core/openai_responses/parsing.py b/deeptutor/services/llm/provider_core/openai_responses/parsing.pyindex eaef3e503..6c03d789d 100644--- a/deeptutor/services/llm/provider_core/openai_responses/parsing.py+++ b/deeptutor/services/llm/provider_core/openai_responses/parsing.py@@ -12,7 +12,7 @@ import json_repairfrom loguru import loggerfrom deeptutor.services.llm.provider_core.base import LLMResponse, ToolCallRequest-from deeptutor.services.llm.usage_frame import token_counts+from deeptutor.services.llm.usage_frame import usage_breakdownFINISH_REASON_MAP = {"completed": "stop",@@ -84,8 +84,43 @@ def _citations_from_content_blocks(blocks: Any) -> list[dict[str, str]]:return citations-def map_finish_reason(status: str | None) -> str:- return FINISH_REASON_MAP.get(status or "completed", "stop")+def map_finish_reason(+ status: str | None,+ incomplete_reason: str | None = None,+) -> str:+ """Map a Responses terminal status to the chat-completions vocabulary.++ ``response.incomplete`` is not always a token-limit event: DeepSeek also+ uses it for content filtering. The nested reason is therefore part of the+ mapping instead of treating every incomplete response as ``length``.+ """+ normalized_status = str(status or "completed").strip().lower()+ normalized_reason = str(incomplete_reason or "").strip().lower()+ if normalized_status == "incomplete":+ if normalized_reason == "content_filter":+ return "content_filter"+ return "length"+ return FINISH_REASON_MAP.get(normalized_status, "stop")+++def _response_field(response: Any, key: str) -> Any:+ if isinstance(response, dict):+ return response.get(key)+ return getattr(response, key, None)+++def _incomplete_reason(response: Any) -> str | None:+ details = _response_field(response, "incomplete_details")+ reason = _response_field(details, "reason")+ return str(reason) if reason is not None else None+++def _response_usage(response: Any) -> dict[str, int]:+ return usage_breakdown(+ _response_field(response, "usage"),+ prompt="input_tokens",+ completion="output_tokens",+ )@dataclass(slots=True)@@ -401,9 +436,17 @@ async def consume_sse(arguments=(buf.arguments if buf else "") or item.get("arguments") or "{}",))- elif event_type == "response.completed":- status = (event.get("response") or {}).get("status")- finish_reason = map_finish_reason(status)+ elif event_type in {"response.completed", "response.incomplete"}:+ # The documented shape nests the terminal payload under+ # ``response``; a few gateways flatten it onto the event itself.+ response = event.get("response") or event+ status = _response_field(response, "status") or (+ "incomplete" if event_type == "response.incomplete" else "completed"+ )+ finish_reason = map_finish_reason(status, _incomplete_reason(response))+ usage = _response_usage(response)+ if usage and on_provider_event:+ on_provider_event("usage", usage)elif event_type in {"error", "response.failed"}:raise RuntimeError(f"Response failed: {_response_error_detail(event)[:500]}")@@ -474,9 +517,12 @@ def parse_response_output(response: Any) -> LLMResponse:)# The Responses API names its counters input_/output_tokens.- usage = token_counts(response.get("usage"), prompt="input_tokens", completion="output_tokens")+ usage = _response_usage(response)- finish_reason = map_finish_reason(response.get("status"))+ finish_reason = map_finish_reason(+ response.get("status"),+ _incomplete_reason(response),+ )if not any(item.get("type") == "reasoning" for item in native_output_items):# Preserve the established metadata contract for ordinary native web# search responses. Message/function-call items only need verbatim@@ -597,14 +643,23 @@ async def consume_sdk_stream(reasoning_content = (reasoning_content or "") + delta_textif on_reasoning_delta and delta_text:await on_reasoning_delta(delta_text)- elif event_type == "response.completed":- response = getattr(event, "response", None)- status = getattr(response, "status", None) if response is not None else None- usage_obj = getattr(response, "usage", None) if response is not None else None- finish_reason = map_finish_reason(status)+ elif event_type in {"response.completed", "response.incomplete"}:+ response = getattr(event, "response", None) or event+ status = _response_field(response, "status")+ usage_obj = _response_field(response, "usage")+ if status is None and event_type == "response.incomplete":+ status = "incomplete"+ finish_reason = map_finish_reason(status, _incomplete_reason(response))usage = (- token_counts(usage_obj, prompt="input_tokens", completion="output_tokens") or usage+ usage_breakdown(+ usage_obj,+ prompt="input_tokens",+ completion="output_tokens",+ )+ or usage)+ if usage and on_provider_event:+ on_provider_event("usage", usage)elif event_type in {"error", "response.failed"}:raise RuntimeError(f"Response failed: {_response_error_detail(event)[:500]}")diff --git a/deeptutor/services/llm/usage_frame.py b/deeptutor/services/llm/usage_frame.pyindex d819b1406..d83e7aa12 100644--- a/deeptutor/services/llm/usage_frame.py+++ b/deeptutor/services/llm/usage_frame.py@@ -77,6 +77,50 @@ def token_counts(}+def usage_breakdown(+ payload: Any,+ *,+ prompt: str = "prompt_tokens",+ completion: str = "completion_tokens",+ total: str = "total_tokens",+) -> dict[str, int]:+ """Return canonical token counts plus an optional reasoning-token count.++ OpenAI-compatible chat completions put the reasoning count under+ ``completion_tokens_details`` while Responses API payloads use+ ``output_tokens_details``. Keeping the detail in this small normalized+ frame lets diagnostics distinguish a response that spent its budget on+ reasoning from one that generated visible output, without changing the+ accounting contract of :func:`token_counts`.+ """+ counts = token_counts(payload, prompt=prompt, completion=completion, total=total)+ if not counts:+ return {}++ frame = usage_mapping(+ payload,+ keys=(+ prompt,+ completion,+ total,+ "reasoning_tokens",+ "completion_tokens_details",+ "output_tokens_details",+ ),+ )+ reasoning = frame.get("reasoning_tokens")+ if reasoning is None:+ for key in ("completion_tokens_details", "output_tokens_details"):+ details = usage_mapping(frame.get(key), keys=("reasoning_tokens",))+ if details.get("reasoning_tokens") is not None:+ reasoning = details.get("reasoning_tokens")+ break+ reasoning_tokens = _as_int(reasoning)+ if reasoning is not None:+ counts["reasoning_tokens"] = reasoning_tokens+ return counts++def _as_int(value: Any) -> int:try:return int(value or 0)@@ -84,4 +128,4 @@ def _as_int(value: Any) -> int:return 0-__all__ = ["CANONICAL_KEYS", "token_counts", "usage_mapping"]+__all__ = ["CANONICAL_KEYS", "token_counts", "usage_breakdown", "usage_mapping"]diff --git a/deeptutor/services/session/_turn_runtime_shared.py b/deeptutor/services/session/_turn_runtime_shared.pyindex 5bdf7a523..1e22a30df 100644--- a/deeptutor/services/session/_turn_runtime_shared.py+++ b/deeptutor/services/session/_turn_runtime_shared.py@@ -84,6 +84,21 @@ def _resolve_turn_outcome(return status, error+def _resolve_turn_failure_metadata(+ assistant_events: Sequence[dict[str, Any]],+) -> tuple[str, bool]:+ """Recover structured failure metadata from a terminal error event."""+ for event in reversed(assistant_events):+ metadata = event.get("metadata")+ metadata = metadata if isinstance(metadata, dict) else {}+ if event.get("type") != StreamEventType.ERROR.value or not metadata.get("turn_terminal"):+ continue+ code = str(metadata.get("error_code") or "")+ retryable = _coerce_bool(metadata.get("retryable"), False)+ return code, retryable+ return "", False++def _narration_marker_call_id(event: StreamEvent) -> str | None:"""call_id of a chat-loop round that resolved as narration (a shortpreamble streamed alongside a tool call). Its text belongs to the trace,diff --git a/deeptutor/services/session/turns/executor.py b/deeptutor/services/session/turns/executor.pyindex 96616eee2..e57725af1 100644--- a/deeptutor/services/session/turns/executor.py+++ b/deeptutor/services/session/turns/executor.py@@ -45,6 +45,7 @@ from .._turn_runtime_shared import (_repair_chinese_emphasis_for_persistence,_request_snapshot_metadata,_resolve_selection_tutor_context,+ _resolve_turn_failure_metadata,_resolve_turn_outcome,_should_capture_assistant_content,_stamp_ask_user_content_offset,@@ -989,6 +990,7 @@ class TurnExecutor:assistant_events,pending_done_event,)+ failure_code, retryable = _resolve_turn_failure_metadata(assistant_events)if pending_done_event is None:pending_done_event = StreamEvent(type=StreamEventType.DONE,@@ -1000,6 +1002,10 @@ class TurnExecutor:**pending_done_event.metadata,"status": turn_status,}+ if failure_code:+ pending_done_event.metadata["error_code"] = failure_code+ if retryable:+ pending_done_event.metadata["retryable"] = True# Attach the persisted row ids so the frontend can reconcile its# optimistic (negative) message ids with a targeted in-place swap# instead of refetching and re-rendering the whole session.@@ -1018,7 +1024,13 @@ class TurnExecutor:# synchronously flushed, so a reconnect can never observe a# terminal row with a missing durable event prefix.await self._flush_buffered_events(execution)- transitioned = await self._transition_execution(execution, turn_status, turn_error)+ transitioned = await self._transition_execution(+ execution,+ turn_status,+ turn_error,+ failure_code=failure_code,+ retryable=retryable,+ )if not transitioned:execution.lease_lost = Trueraise asyncio.CancelledError@@ -1143,6 +1155,11 @@ class TurnExecutor:await self._flush_buffered_events(execution)raiseexcept Exception as exc:+ failure_code = str(getattr(exc, "error_code", "") or "")+ retryable_attr = getattr(exc, "retryable", None)+ retryable = retryable_attr if isinstance(retryable_attr, bool) else False+ resolved_failure_code = failure_code or "internal_error"+ resolved_retryable = retryable if failure_code else Trueif stream_done_sent:logger.error("Post-stream persistence for turn %s failed: %s",@@ -1160,8 +1177,8 @@ class TurnExecutor:execution,"failed",str(exc),- failure_code="internal_error",- retryable=True,+ failure_code=resolved_failure_code,+ retryable=resolved_retryable,)else:logger.error("Turn %s failed: %s", turn_id, exc, exc_info=True)@@ -1171,7 +1188,12 @@ class TurnExecutor:type=StreamEventType.ERROR,source=capability_name,content=str(exc),- metadata={"turn_terminal": True, "status": "failed"},+ metadata={+ "turn_terminal": True,+ "status": "failed",+ "error_code": resolved_failure_code,+ "retryable": resolved_retryable,+ },),)await self._publish_live_event(@@ -1179,7 +1201,11 @@ class TurnExecutor:StreamEvent(type=StreamEventType.DONE,source=capability_name,- metadata={"status": "failed"},+ metadata={+ "status": "failed",+ "error_code": resolved_failure_code,+ "retryable": resolved_retryable,+ },),)with contextlib.suppress(Exception):@@ -1188,8 +1214,8 @@ class TurnExecutor:execution,"failed",str(exc),- failure_code="internal_error",- retryable=True,+ failure_code=resolved_failure_code,+ retryable=resolved_retryable,)finally:if llm_scope_token is not None and reset_active_llm_selection is not None:diff --git a/deeptutor/services/session/turns/lifecycle.py b/deeptutor/services/session/turns/lifecycle.pyindex 665220c92..3acfd006d 100644--- a/deeptutor/services/session/turns/lifecycle.py+++ b/deeptutor/services/session/turns/lifecycle.py@@ -17,6 +17,7 @@ from deeptutor.services.session.protocol import SessionStoreProtocolfrom deeptutor.services.session.scope import store_scopefrom .._turn_runtime_shared import (+ _coerce_bool,_LiveSubscriber,_TurnExecution,)@@ -485,6 +486,11 @@ class TurnLifecycle:metadata: dict[str, Any] = {"status": status, "synthesized": True}if error:metadata["error"] = error+ failure_code = str((turn or {}).get("failure_code") or "")+ if failure_code:+ metadata["error_code"] = failure_code+ if _coerce_bool((turn or {}).get("retryable"), False):+ metadata["retryable"] = Truereturn {"type": "done","source": "turn_runtime",@@ -517,6 +523,8 @@ class TurnLifecycle:"status": "failed","synthesized": True,"turn_terminal": True,+ "error_code": str((turn or {}).get("failure_code") or ""),+ "retryable": _coerce_bool((turn or {}).get("retryable"), False),},"session_id": str((turn or {}).get("session_id") or ""),"turn_id": turn_id,diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.pyindex b11fb0692..1bdee31f0 100644--- a/tests/agents/chat/test_agent_loop.py+++ b/tests/agents/chat/test_agent_loop.py@@ -19,7 +19,7 @@ from deeptutor.core.stream import StreamEvent, StreamEventTypefrom deeptutor.core.tool_protocol import ToolResultfrom deeptutor.core.trace import ANSWER_BEARING_CALL_KINDSfrom deeptutor.runtime.stream_bus import StreamBus-from deeptutor.services.llm import LLMProviderTransportError+from deeptutor.services.llm import LLMProviderTransportError, LLMReasoningBudgetExhaustedasync def _collect_bus_events(bus: StreamBus) -> tuple[list[StreamEvent], asyncio.Task[Any]]:@@ -1125,6 +1125,201 @@ async def test_truncated_pure_reasoning_round_is_told_to_act_not_continue(assert _answer_text(events) == "答案是 42。"+async def test_truncated_reasoning_round_replays_state_and_keeps_tools(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The one reasoning-budget recovery keeps provider state and tools."""+ client = _ScriptedChatClient(+ [+ [+ _llm_chunk(+ reasoning_content="I have enough context to act.",+ finish_reason="length",+ )+ ],+ [_llm_chunk(content="Implemented the requested change.")],+ ]+ )+ pipeline = AgenticChatPipeline(language="en")+ pipeline.registry = _Registry()+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: ["web_search"])+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)++ events = await _run(+ pipeline,+ UnifiedContext(session_id="s1", user_message="Implement it", enabled_tools=["web_search"]),+ )++ assert client.call_count == 2+ second_round = client.calls[1]["messages"]+ assert "tools" in client.calls[1]+ assert any(+ message.get("role") == "assistant"+ and message.get("reasoning_content") == "I have enough context to act."+ for message in second_round+ )+ assert "Act now" in str(second_round[-1]["content"])+ first_complete = next(+ event+ for event in events+ if event.type == StreamEventType.PROGRESS+ and event.metadata.get("trace_kind") == "call_status"+ and event.metadata.get("call_state") == "complete"+ and event.metadata.get("finish_reason") == "length"+ )+ assert first_complete.metadata["requested_max_tokens"] == 8000+ assert first_complete.metadata["usage_reported"] is False+ assert first_complete.metadata["completion_tokens"] == "unavailable"+ assert first_complete.metadata["reasoning_chars"] > 0+ assert first_complete.metadata["content_chars"] == 0+ assert first_complete.metadata["tool_call_count"] == 0+ assert _answer_text(events) == "Implemented the requested change."+++async def test_repeated_reasoning_budget_exhaustion_is_retryable_error(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A second pure-reasoning truncation stops after the single recovery."""+ client = _ScriptedChatClient(+ [+ [_llm_chunk(reasoning_content="first pass", finish_reason="length")],+ [_llm_chunk(reasoning_content="second pass", finish_reason="length")],+ ]+ )+ pipeline = AgenticChatPipeline(language="en")+ pipeline.registry = _Registry()+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: ["web_search"])+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)++ with pytest.raises(LLMReasoningBudgetExhausted) as raised:+ await pipeline.run(+ UnifiedContext(+ session_id="s1", user_message="Implement it", enabled_tools=["web_search"]+ ),+ StreamBus(),+ )++ assert client.call_count == 2+ assert raised.value.error_code == "reasoning_budget_exhausted"+ assert raised.value.retryable is True+ assert "useful response" not in str(raised.value).lower()+++async def test_reasoning_progress_is_throttled_and_contains_no_reasoning_text(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Reasoning-only streams emit opaque 15-second progress markers."""+ clock = iter([0.0, 16.0, 20.0, 31.0, 40.0])+ monkeypatch.setattr(agent_loop_mod, "monotonic", lambda: next(clock, 40.0))+ client = _ScriptedChatClient(+ [+ [+ _llm_chunk(reasoning_content="private one"),+ _llm_chunk(reasoning_content="private two"),+ _llm_chunk(reasoning_content="private three"),+ ],+ [_llm_chunk(content="Now acting.")],+ ]+ )+ pipeline = AgenticChatPipeline(language="en")+ pipeline.registry = _Registry()+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: [])+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)++ events = await _run(pipeline, UnifiedContext(session_id="s1", user_message="Do it"))++ progress = [+ event+ for event in events+ if event.type == StreamEventType.PROGRESS+ and event.metadata.get("trace_kind") == "reasoning_progress"+ ]+ assert len(progress) == 2+ assert [event.metadata["reasoning_chars"] for event in progress] == [11, 35]+ assert [event.metadata["elapsed_s"] for event in progress] == [16.0, 31.0]+ assert all(event.metadata.get("call_id") for event in progress)+ assert all("private" not in event.content for event in progress)+ assert _answer_text(events) == "Now acting."+++async def test_reasoning_progress_stops_after_visible_action(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ clock = iter([0.0, 16.0, 20.0, 31.0])+ monkeypatch.setattr(agent_loop_mod, "monotonic", lambda: next(clock, 31.0))+ client = _ScriptedChatClient(+ [+ [+ _llm_chunk(reasoning_content="private"),+ _llm_chunk(content="Started acting."),+ _llm_chunk(reasoning_content="late private"),+ ]+ ]+ )+ pipeline = AgenticChatPipeline(language="en")+ pipeline.registry = _Registry()+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: [])+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)++ events = await _run(pipeline, UnifiedContext(session_id="s1", user_message="Do it"))++ progress = [+ event+ for event in events+ if event.type == StreamEventType.PROGRESS+ and event.metadata.get("trace_kind") == "reasoning_progress"+ ]+ assert len(progress) == 1+ assert _answer_text(events) == "Started acting."+++async def test_forced_finish_reasoning_budget_exhaustion_is_not_empty_success(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The tool-less hard finish has the same dedicated failure boundary."""+ registry = _Registry()+ tool_rounds = [+ [+ _llm_chunk(+ tool_calls=[+ {+ "id": f"call-{index}",+ "name": "web_search",+ "arguments": json.dumps({"query": f"step {index}"}),+ }+ ]+ )+ ]+ for index in range(4)+ ]+ client = _ScriptedChatClient(+ [+ *tool_rounds,+ [_llm_chunk(reasoning_content="still thinking", finish_reason="length")],+ ]+ )+ pipeline = AgenticChatPipeline(language="en")+ pipeline.registry = registry+ pipeline._max_rounds = 1+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: ["web_search"])+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)++ with pytest.raises(LLMReasoningBudgetExhausted) as raised:+ await pipeline.run(+ UnifiedContext(session_id="s1", user_message="Research", enabled_tools=["web_search"]),+ StreamBus(),+ )++ assert client.call_count == 5+ assert raised.value.error_code == "reasoning_budget_exhausted"+ assert raised.value.retryable is True++@pytest.mark.asyncioasync def test_truncated_round_with_visible_text_still_continues(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/runtime/test_orchestrator.py b/tests/runtime/test_orchestrator.pyindex aba74b61a..2b88740eb 100644--- a/tests/runtime/test_orchestrator.py+++ b/tests/runtime/test_orchestrator.py@@ -216,6 +216,13 @@ class TestOrchestratorErrorHandling:"retryable": True,"partial_response": False,}+ done = next(event for event in events if event.type == StreamEventType.DONE)+ assert done.metadata == {+ "status": "failed",+ "error_code": "provider_transport",+ "retryable": True,+ "partial_response": False,+ }# ---------------------------------------------------------------------------diff --git a/tests/services/llm/test_openai_responses_parsing.py b/tests/services/llm/test_openai_responses_parsing.pyindex c2f3b1e2c..29f266aa0 100644--- a/tests/services/llm/test_openai_responses_parsing.py+++ b/tests/services/llm/test_openai_responses_parsing.py@@ -141,6 +141,121 @@ async def test_sdk_preserves_deepseek_reasoning_text_for_next_tool_round() -> No]+async def test_sdk_incomplete_maps_to_length_and_keeps_reasoning_usage() -> None:+ events = [+ SimpleNamespace(type="response.reasoning_text.delta", delta="thinking only"),+ SimpleNamespace(+ type="response.incomplete",+ response=SimpleNamespace(+ status="incomplete",+ incomplete_details=SimpleNamespace(reason="max_output_tokens"),+ usage=SimpleNamespace(+ input_tokens=100,+ output_tokens=8000,+ output_tokens_details=SimpleNamespace(reasoning_tokens=8000),+ ),+ ),+ ),+ ]++ content, tool_calls, finish_reason, usage, reasoning = await consume_sdk_stream(+ _sdk_events(events)+ )++ assert content == ""+ assert tool_calls == []+ assert finish_reason == "length"+ assert usage == {+ "prompt_tokens": 100,+ "completion_tokens": 8000,+ "total_tokens": 8100,+ "reasoning_tokens": 8000,+ }+ assert reasoning == "thinking only"+++async def test_sse_incomplete_maps_to_length_and_reports_usage() -> None:+ provider_events: list[tuple[str, dict]] = []+ response = _SSEFixture(+ [+ {+ "type": "response.incomplete",+ "response": {+ "status": "incomplete",+ "incomplete_details": {"reason": "max_output_tokens"},+ "usage": {+ "input_tokens": 4,+ "output_tokens": 9,+ "output_tokens_details": {"reasoning_tokens": 9},+ },+ },+ }+ ]+ )++ _content, _tool_calls, finish_reason = await consume_sse(+ response,+ on_provider_event=lambda kind, payload: provider_events.append((kind, payload)),+ )++ assert finish_reason == "length"+ assert provider_events == [+ (+ "usage",+ {+ "prompt_tokens": 4,+ "completion_tokens": 9,+ "total_tokens": 13,+ "reasoning_tokens": 9,+ },+ )+ ]+++def test_incomplete_content_filter_is_not_treated_as_token_truncation() -> None:+ result = parse_response_output(+ {+ "status": "incomplete",+ "incomplete_details": {"reason": "content_filter"},+ "output": [],+ }+ )++ assert result.finish_reason == "content_filter"+++def test_nonstream_incomplete_maps_usage_and_reasoning_tokens() -> None:+ result = parse_response_output(+ {+ "status": "incomplete",+ "incomplete_details": {"reason": "max_output_tokens"},+ "output": [+ {+ "type": "reasoning",+ "id": "rs_1",+ "summary": [{"type": "summary_text", "text": "thinking"}],+ }+ ],+ "usage": {+ "input_tokens": 100,+ "output_tokens": 8000,+ "output_tokens_details": {"reasoning_tokens": 8000},+ },+ }+ )++ assert result.finish_reason == "length"+ assert result.usage == {+ "prompt_tokens": 100,+ "completion_tokens": 8000,+ "total_tokens": 8100,+ "reasoning_tokens": 8000,+ }+ assert result.reasoning_content == "thinking"++def test_nonstream_response_preserves_deepseek_reasoning_text_and_native_items() -> None:reasoning_item = {"type": "reasoning",@@ -173,6 +288,23 @@ def test_nonstream_response_preserves_deepseek_reasoning_text_and_native_items()]+async def test_sdk_failed_terminal_event_is_not_misreported_as_stop() -> None:+ with pytest.raises(RuntimeError, match="Response failed"):+ await consume_sdk_stream(+ _sdk_events(+ [+ SimpleNamespace(+ type="response.failed",+ response=SimpleNamespace(+ error=SimpleNamespace(message="provider rejected the request")+ ),+ )+ ]+ )+ )++@pytest.mark.asyncio@pytest.mark.parametrize("consumer", ["sse", "sdk"])async def test_argument_deltas_are_preserved_without_a_done_event(consumer: str) -> None:diff --git a/tests/services/llm/test_usage_frame.py b/tests/services/llm/test_usage_frame.pyindex 5f692eed4..591464a35 100644--- a/tests/services/llm/test_usage_frame.py+++ b/tests/services/llm/test_usage_frame.py@@ -6,7 +6,7 @@ plain-dict case). These tests pin all three shapes plus the two API dialects.from __future__ import annotations-from deeptutor.services.llm.usage_frame import token_counts, usage_mapping+from deeptutor.services.llm.usage_frame import token_counts, usage_breakdown, usage_mappingclass _PydanticLike:@@ -105,3 +105,20 @@ def test_counts_map_responses_api_dialect_from_attributes() -> None:"completion_tokens": 2,"total_tokens": 10,}+++def test_breakdown_preserves_responses_reasoning_tokens() -> None:+ assert usage_breakdown(+ {+ "input_tokens": 30,+ "output_tokens": 12,+ "output_tokens_details": {"reasoning_tokens": 9},+ },+ prompt="input_tokens",+ completion="output_tokens",+ ) == {+ "prompt_tokens": 30,+ "completion_tokens": 12,+ "total_tokens": 42,+ "reasoning_tokens": 9,+ }diff --git a/tests/services/session/test_turn_runtime_subscribe.py b/tests/services/session/test_turn_runtime_subscribe.pyindex 7062ce3d2..1373fa3aa 100644--- a/tests/services/session/test_turn_runtime_subscribe.py+++ b/tests/services/session/test_turn_runtime_subscribe.py@@ -9,6 +9,7 @@ import pytestfrom deeptutor.core.stream import StreamEvent, StreamEventTypefrom deeptutor.learning.storage import LearningStorefrom deeptutor.services.courses import CourseService+from deeptutor.services.session._turn_runtime_shared import _resolve_turn_failure_metadatafrom deeptutor.services.session.sqlite_store import SQLiteSessionStorefrom deeptutor.services.session.turn_runtime import (TurnRuntimeManager,@@ -89,6 +90,25 @@ def test_non_terminal_error_keeps_completed_done_status() -> None:assert error == ""+def test_terminal_error_metadata_resolves_retry_contract() -> None:+ code, retryable = _resolve_turn_failure_metadata(+ [+ {+ "type": "error",+ "content": "The model exhausted its output budget.",+ "metadata": {+ "turn_terminal": True,+ "error_code": "reasoning_budget_exhausted",+ "retryable": True,+ },+ }+ ]+ )++ assert code == "reasoning_budget_exhausted"+ assert retryable is True++@pytest.mark.asyncioasync def test_has_live_executions_counts_placeholders_and_running_tasks(tmp_path) -> None:runtime = TurnRuntimeManager(SQLiteSessionStore(tmp_path / "chat_history.db"))@@ -240,14 +260,27 @@ async def test_subscribe_failed_turn_synthesizes_ordered_error_and_done(tmp_pathruntime = TurnRuntimeManager(store)session = await store.ensure_session(None)turn = await store.create_turn(session["id"], capability="chat")- assert await store.update_turn_status(turn["id"], "failed", "provider failed") is True+ assert (+ await store.transition_turn(+ turn["id"],+ "failed",+ error="provider failed",+ failure_code="reasoning_budget_exhausted",+ retryable=True,+ )+ is True+ )events = [event async for event in runtime.subscribe_turn(turn["id"], after_seq=0)]assert [event["type"] for event in events] == ["error", "done"]assert [event["seq"] for event in events] == [1, 2]assert events[0]["metadata"]["turn_terminal"] is True+ assert events[0]["metadata"]["error_code"] == "reasoning_budget_exhausted"+ assert events[0]["metadata"]["retryable"] is Trueassert events[1]["metadata"]["status"] == "failed"+ assert events[1]["metadata"]["error_code"] == "reasoning_budget_exhausted"+ assert events[1]["metadata"]["retryable"] is True@pytest.mark.asynciodiff --git a/web/features/chat/messages/ChatMessageList.tsx b/web/features/chat/messages/ChatMessageList.tsxindex 850cb7cf4..e6b8f8207 100644--- a/web/features/chat/messages/ChatMessageList.tsx+++ b/web/features/chat/messages/ChatMessageList.tsx@@ -1730,14 +1730,26 @@ export const ChatMessageList = memo(function ChatMessageList({isStreaming && i === lastRenderedAssistantIndex;const msgDone = !isActiveAssistant;const showActions = msgDone && hasVisibleMarkdownContent(msg.content);+ const terminalError = (msg.events ?? []).find(+ (e) =>+ e.type === "error" &&+ Boolean(+ (e.metadata as { turn_terminal?: boolean } | undefined)+ ?.turn_terminal,+ ),+ );+ const terminalErrorRetryable = Boolean(+ (terminalError?.metadata as { retryable?: boolean } | undefined)+ ?.retryable,+ );const isLastAssistant = i === lastRenderedAssistantIndex;const showRegenerate =- showActions &&!isStreaming &&isLastAssistant &&Boolean(pairedUserMessage) &&(!pairedUserMessage?.capability ||- pairedUserMessage?.capability === "chat");+ pairedUserMessage?.capability === "chat") &&+ (showActions || terminalErrorRetryable);const deletableTurnUserId =msgDone && pairedUserMessage?.id != null && onDeleteTurn? pairedUserMessage.id@@ -1808,14 +1820,6 @@ export const ChatMessageList = memo(function ChatMessageList({// with a turn_terminal error event. Surface it as an error// card with an inline retry instead of leaving a bare trace.if (isActiveAssistant) return null;- const terminalError = (msg.events ?? []).find(- (e) =>- e.type === "error" &&- Boolean(- (e.metadata as { turn_terminal?: boolean } | undefined)- ?.turn_terminal,- ),- );if (!terminalError) return null;return (<div className="mt-3 flex w-full max-w-[min(520px,90%)] items-center gap-2 rounded-xl border border-[var(--destructive)]/30 bg-[var(--destructive)]/5 px-3 py-2">diff --git a/web/features/chat/trace/TracePresentation.tsx b/web/features/chat/trace/TracePresentation.tsxindex 69f2e2d16..fada126d6 100644--- a/web/features/chat/trace/TracePresentation.tsx+++ b/web/features/chat/trace/TracePresentation.tsx@@ -1483,6 +1483,29 @@ function getExploreContextStatusLabel(return null;}+function getReasoningProgressStatusLabel(+ events: StreamEvent[],+ t: (key: string, opts?: Record<string, unknown>) => string,+ isStreaming: boolean,+) {+ if (!isStreaming) return null;+ for (let idx = events.length - 1; idx >= 0; idx -= 1) {+ const event = events[idx];+ const meta = getTraceMeta(event);+ if (meta.trace_kind === "reasoning_progress") {+ return t("Still reasoning before acting…");+ }+ if (+ meta.trace_kind === "call_status" &&+ (meta.call_state === "running" || meta.call_state === "complete")+ ) {+ return null;+ }+ if (event.type === "content" || event.type === "tool_call") return null;+ }+ return null;+}+export function StreamingStatus({events,isStreaming,@@ -1563,6 +1586,7 @@ export function StreamingStatus({const label =getExploreContextStatusLabel(events, t, Boolean(isStreaming)) ??getDeepResearchStatusLabel(events, t, Boolean(isStreaming)) ??+ getReasoningProgressStatusLabel(events, t, Boolean(isStreaming)) ??modeLabel;// Single turn-level clock. Ticks every second while the turn is indiff --git a/web/features/chat/trace/model.ts b/web/features/chat/trace/model.tsindex ebbf0615d..d82ce68b5 100644--- a/web/features/chat/trace/model.ts+++ b/web/features/chat/trace/model.ts@@ -12,6 +12,19 @@ export interface TraceMetadata {call_state?: string;call_role?: string;answer_visible?: boolean;+ reasoning_chars?: number;+ finish_reason?: string;+ requested_max_tokens?: number;+ usage_reported?: boolean;+ prompt_tokens?: number | "unavailable";+ completion_tokens?: number | "unavailable";+ total_tokens?: number | "unavailable";+ reasoning_tokens?: number | "unavailable";+ output_chars?: number;+ content_chars?: number;+ tool_call_chars?: number;+ tool_call_count?: number;+ reasoning_budget_exhausted?: boolean;absorbed_into_final?: boolean;step_id?: string;round?: number;diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 07e7fe55a..150133181 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -2053,6 +2053,7 @@"Failed turns are not retried.": "Failed turns are not retried.","The primary model answers every turn; if it fails outright, the turn is retried once on the backup.": "The primary model answers every turn; if it fails outright, the turn is retried once on the backup.","{{name}} Reasoning…": "{{name}} Reasoning…",+ "Still reasoning before acting…": "Still reasoning before acting…","{{name}} Planning…": "{{name}} Planning…","{{name}} Exploring…": "{{name}} Exploring…","{{name}} Quizzing…": "{{name}} Quizzing…",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex e241f4f76..53fb07a60 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -2053,6 +2053,7 @@"Failed turns are not retried.": "失败的轮次不会重试。","The primary model answers every turn; if it fails outright, the turn is retried once on the backup.": "主模型负责每一轮回答;当它彻底失败时,会用备用模型重试一次。","{{name}} Reasoning…": "{{name}} 推理中…",+ "Still reasoning before acting…": "仍在推理,尚未开始回答或执行工具…","{{name}} Planning…": "{{name}} 规划中…","{{name}} Exploring…": "{{name}} 探索中…","{{name}} Quizzing…": "{{name}} 出题中…",diff --git a/web/tests/chat-streaming-status.spec.tsx b/web/tests/chat-streaming-status.spec.tsxindex 38542d83d..1a48642fc 100644--- a/web/tests/chat-streaming-status.spec.tsx+++ b/web/tests/chat-streaming-status.spec.tsx@@ -59,4 +59,48 @@ describe("chat activity status", () => {// region, and carry the settled label.expect(screen.getByRole("button")).toHaveTextContent("Done");});++ it("shows the opaque reasoning-progress status until action starts", () => {+ const events = [+ {+ type: "progress",+ source: "chat",+ stage: "responding",+ content: "The model is still reasoning; it has not produced an answer or tool action yet.",+ metadata: {+ trace_kind: "reasoning_progress",+ call_id: "call-1",+ reasoning_chars: 120,+ elapsed_s: 15,+ },+ timestamp: Date.now() / 1000,+ },+ ] as StreamEvent[];++ const { rerender } = render(+ <StreamingStatus events={events} isStreaming content="" />,+ );++ expect(screen.getByRole("status")).toHaveTextContent(+ "Still reasoning before acting",+ );++ rerender(+ <StreamingStatus+ events={[+ ...events,+ {+ type: "content",+ source: "chat",+ stage: "responding",+ content: "Acting now",+ timestamp: Date.now() / 1000,+ },+ ] as StreamEvent[]}+ isStreaming+ content="Acting now"+ />,+ );+ expect(screen.getByRole("status")).toHaveTextContent("DeepTutor Exploring");+ });});