DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat: DSML streaming robustness, memory observability, and mastery pending questions
Bingxi Zhao (Frank)712d4137f02c
diff --git a/deeptutor/agents/chat/agent_loop.py b/deeptutor/agents/chat/agent_loop.pyindex 12f28336c..e61a08784 100644--- a/deeptutor/agents/chat/agent_loop.py+++ b/deeptutor/agents/chat/agent_loop.py@@ -10,8 +10,10 @@ One chat turn = ONE agent loop over a single growing conversation:* a round that calls NO tools is the ``finish``: its text IS the finaluser-facing answer and the loop ends (the model deciding it is done; afirst round without tool calls is the "no exploration needed" fast path);-* if the round budget runs out while tools are still being requested, one- final tool-less ``finish`` round is forced.+* if the exploration budget runs out while work is still in protocol, a+ small bounded settlement phase keeps tools available for already-started+ follow-up (including user input); one final tool-less round is forced only+ after that settlement allowance is exhausted.``ask_user`` pauses the turn for a reply and resumes in-protocol; anunresolved pause (or a terminator tool) halts the turn.@@ -32,7 +34,7 @@ from typing import TYPE_CHECKING, Anyfrom deeptutor.agents._shared.capability_result import emit_capability_resultfrom deeptutor.agents.chat.context_budget import LLMRequestSnapshot-from deeptutor.agents.chat.dsml_tool_calls import extract_dsml_tool_calls, has_dsml_tool_calls+from deeptutor.agents.chat.dsml_tool_calls import DSMLStreamFilter, extract_dsml_tool_callsfrom deeptutor.core.agentic.messages import assistant_message_with_tool_callsfrom deeptutor.core.agentic.tool_dispatch import DispatchOutcomefrom deeptutor.core.agentic.usage import message_content_chars, record_streamed_usage@@ -52,10 +54,15 @@ if TYPE_CHECKING: # pragma: no coverlogger = logging.getLogger(__name__)-# The loop runs over a single conversation; this is the maximum number of-# tool-calling rounds before a tool-less finish is forced. The model normally-# exits earlier by replying without tool calls.+# The loop runs over a single conversation. Its configured round budget covers+# exploration; bounded settlement and the emergency hard finish are separate.LOOP_STAGE = "responding"+# Settlement is deliberately small but large enough for the longest built-in+# interaction boundary: register state -> ask/resume -> record result -> reply.+# A single additional tool-less hard finish follows if all of these rounds+# still request tools, making the total upper bound ``exploration + 4``.+MAX_SETTLEMENT_ROUNDS = 3+_TRUNCATED_FINISH_REASONS = frozenset({"length", "max_tokens", "max_output_tokens"})_THINK_OPEN_RE = re.compile(r"<\s*think(?:ing)?\b[^>]*>", re.IGNORECASE)_THINK_CLOSE_RE = re.compile(r"<\s*/\s*think(?:ing)?\s*>", re.IGNORECASE)@@ -63,6 +70,16 @@ _THINK_CLOSE_RE = re.compile(r"<\s*/\s*think(?:ing)?\s*>", re.IGNORECASE)_TAG_HOLDBACK_CHARS = 24+def _finish_was_truncated(reason: str | None) -> bool:+ """Return whether a provider ended generation because output hit a cap."""+ return str(reason or "").strip().lower() in _TRUNCATED_FINISH_REASONS+++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])++class InlineThinkFilter:"""Incremental ``<think>``/``<thinking>`` splitter for streamed content.@@ -123,6 +140,8 @@ class AgentLoopState:"""Turn-level counters shared across the loop's rounds."""rounds: int = 0+ exploration_rounds: int = 0+ settlement_rounds: int = 0tool_steps: int = 0sources: list[dict[str, Any]] = field(default_factory=list)@@ -130,6 +149,7 @@ class AgentLoopState:@dataclass(slots=True)class LLMCallResult:text: str+ visible_text: str = ""tool_calls: list[dict[str, Any]] = field(default_factory=list)finish_reason: str = ""@@ -167,6 +187,10 @@ class AgentLoop:self.client = clientself.enabled_tools = enabled_toolsself.tool_schemas = tool_schemas+ # Keep the schema catalog even if a provider rejects native ``tools``+ # and subsequent calls switch to DSML fallback. The parser still needs+ # the declared parameter types to decode string-marked containers.+ self._tool_schema_catalog = tool_schemasself._last_request: LLMRequestSnapshot | None = Noneasync def run(self) -> None:@@ -213,6 +237,7 @@ class AgentLoop:"completed": outcome.completed,"engine": "agent_loop","rounds": state.rounds,+ "settlement_rounds": state.settlement_rounds,"tool_steps": state.tool_steps,}if self._last_request is not None:@@ -246,14 +271,32 @@ class AgentLoop:to the user — is the answer, and the loop ends."""explore_label = self.pipeline._t("labels.exploring", default="Exploring")+ settlement_label = self.pipeline._t("labels.final_response", default="Final response")+ exploration_budget = max(1, self.pipeline.effective_max_rounds(self.context))+ settlement_started = Falsenudged_empty_finish = False- for _round in range(max(1, self.pipeline.effective_max_rounds(self.context))):+ continued_answer_parts: list[str] = []+ while True:+ settling = state.exploration_rounds >= exploration_budget+ if settling:+ if state.settlement_rounds >= MAX_SETTLEMENT_ROUNDS:+ # A model may ignore the settlement directive and keep+ # requesting tools. One tool-less call is the absolute+ # stop, so malformed/empty tool cycles cannot run forever.+ return await self._forced_finish(+ messages,+ state,+ continued_answer_parts=continued_answer_parts,+ )+ if not settlement_started:+ await self._begin_settlement(messages)+ settlement_started = Truetry:result = await self._call_llm(messages=messages,- label=explore_label,+ label=settlement_label if settling else explore_label,call_kind="agent_loop_round",- trace_role="explore",+ trace_role="response" if settling else "explore",max_tokens=self.pipeline.loop_max_tokens,tool_schemas=self.tool_schemas,)@@ -269,10 +312,52 @@ class AgentLoop:state.rounds,exc,)- return await self._forced_finish(messages, state, reason="error")+ return await self._forced_finish(+ messages,+ state,+ reason="error",+ continued_answer_parts=continued_answer_parts,+ )state.rounds += 1+ if settling:+ state.settlement_rounds += 1+ else:+ state.exploration_rounds += 1if not result.tool_calls:final_text = self._clean(result.text)+ if _finish_was_truncated(result.finish_reason):+ # ``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 /+ # settlement counters still apply, so repeated truncation+ # has the same hard upper bound as repeated tool calls.+ await self.stream.progress(+ self.pipeline._t(+ "notices.output_truncated",+ default=(+ "The model output reached its token limit; asked it to continue."+ ),+ ),+ source="chat",+ stage=LOOP_STAGE,+ metadata={"trace_kind": "warning"},+ )+ if result.visible_text:+ continued_answer_parts.append(result.visible_text)+ if result.text:+ messages.append({"role": "assistant", "content": result.text})+ self._append_loop_instruction(+ messages,+ self.pipeline._t(+ "loop.continue_truncated",+ default=(+ "Your previous response stopped at the token limit. "+ "Continue from where it ended without repeating it, "+ "and complete the user-facing answer."+ ),+ ),+ )+ continueif not final_text and not nudged_empty_finish:# The round produced only internal reasoning (e.g. the# whole reply inside <think>) — the model planned but@@ -294,24 +379,26 @@ class AgentLoop:)if result.text:messages.append({"role": "assistant", "content": result.text})- messages.append(- {- "role": "user",- "content": self.pipeline._t(- "loop.finish_empty_nudge",- default=(- "Your previous round produced only internal "- "reasoning — no tool call and no user-facing "- "answer. Continue now: either call the tools "- "to execute your plan, or write the final "- "user-facing answer directly."- ),+ self._append_loop_instruction(+ messages,+ self.pipeline._t(+ "loop.finish_empty_nudge",+ default=(+ "Your previous round produced only internal "+ "reasoning — no tool call and no user-facing "+ "answer. Continue now: either call the tools "+ "to execute your plan, or write the final "+ "user-facing answer directly."),- }+ ),)continue# Finish: the text streamed live this round IS the answer.- return await self._finalize_finish(final_text)+ return await self._finalize_finish(+ final_text,+ visible_text=result.visible_text,+ continued_answer_parts=continued_answer_parts,+ )messages.append(assistant_message_with_tool_calls(result.text, result.tool_calls))dispatch = await self.pipeline._dispatch_tool_calls(@@ -348,13 +435,39 @@ class AgentLoop:if dispatch.terminate:payload = dispatch.terminate_payload or {}await self.pipeline._emit_terminator_final_response(self.stream, payload)+ terminal_text = str(payload.get("content") or "")return LoopOutcome(- final_text=str(payload.get("content") or ""),+ final_text=_join_answer_parts(continued_answer_parts, terminal_text),completed=True,)- # Round budget ran out while still requesting tools — force a finish.- return await self._forced_finish(messages, state)+ async def _begin_settlement(self, messages: list[dict[str, Any]]) -> None:+ """Enter the bounded post-budget phase without dropping tool state."""+ await self.stream.progress(+ self.pipeline._t(+ "notices.loop_settlement",+ default=(+ "Exploration budget reached; completing required follow-up "+ "before the final answer."+ ),+ ),+ source="chat",+ stage=LOOP_STAGE,+ metadata={"trace_kind": "warning"},+ )+ self._append_loop_instruction(+ messages,+ self.pipeline._settle_exhausted_instruction(),+ )++ @staticmethod+ def _append_loop_instruction(messages: list[dict[str, Any]], instruction: str) -> None:+ """Append a loop directive without creating consecutive user roles."""+ if messages and messages[-1].get("role") == "user":+ prior = str(messages[-1].get("content") or "").rstrip()+ messages[-1]["content"] = f"{prior}\n\n{instruction}" if prior else instruction+ return+ messages.append({"role": "user", "content": instruction})def _fold_context_checkpoint(self,@@ -382,6 +495,7 @@ class AgentLoop:state: AgentLoopState,*,reason: str = "budget",+ continued_answer_parts: list[str] | None = None,) -> LoopOutcome:if reason == "error":notice = self.pipeline._t(@@ -399,7 +513,7 @@ class AgentLoop:stage=LOOP_STAGE,metadata={"trace_kind": "warning"},)- messages.append({"role": "user", "content": self.pipeline._finish_exhausted_instruction()})+ self._append_loop_instruction(messages, self.pipeline._finish_exhausted_instruction())try:result = await self._call_llm(messages=messages,@@ -414,12 +528,32 @@ class AgentLoop:# stalling). Don't bubble up and lose the turn — emit the graceful# fallback answer instead.logger.warning("forced-finish LLM call failed: %s", exc)- return await self._finalize_finish("")+ return await self._finalize_finish(+ "",+ continued_answer_parts=continued_answer_parts,+ )state.rounds += 1- return await self._finalize_finish(result.text)+ return await self._finalize_finish(+ result.text,+ visible_text=result.visible_text,+ continued_answer_parts=continued_answer_parts,+ )- async def _finalize_finish(self, raw_text: str) -> LoopOutcome:- final_text = self._clean(raw_text)+ async def _finalize_finish(+ self,+ raw_text: str,+ *,+ visible_text: str | None = None,+ continued_answer_parts: list[str] | None = None,+ ) -> LoopOutcome:+ cleaned_text = self._clean(raw_text)+ if continued_answer_parts:+ final_text = _join_answer_parts(+ continued_answer_parts,+ visible_text if visible_text is not None else cleaned_text,+ )+ else:+ final_text = cleaned_textif not final_text:# The finish round produced no usable text; nothing streamed to# the user, so emit a fallback answer here.@@ -502,16 +636,22 @@ class AgentLoop:output_chars = 0finish_reason = ""think_filter = InlineThinkFilter()- # Once a round's content channel starts carrying DeepSeek DSML tool-call- # markup (issue #666), divert the rest of it to the thinking channel so- # the raw markup never streams as the user-facing answer. It is parsed- # into real tool calls after the stream completes.- dsml_stream_active = False+ # DeepSeek's Anthropic-compatible endpoint can interleave user-facing+ # prose and DSML tool calls in one content stream. Strip only the DSML+ # blocks incrementally; the raw chunks stay in ``text_parts`` for the+ # post-stream parser and the surrounding prose remains visible.+ dsml_filter = DSMLStreamFilter()+ answer_content_emitted = False+ visible_text_parts: list[str] = []chunk_meta = merge_trace_metadata(trace_meta, {"trace_kind": "llm_chunk"})async def _emit_segments(segments: list[tuple[str, str]]) -> None:+ nonlocal answer_content_emittedfor kind, segment in segments:if kind == "content":+ visible_text_parts.append(segment)+ if segment.strip():+ answer_content_emitted = Trueawait self.stream.content(segment, source="chat", stage=stage, metadata=chunk_meta)@@ -551,17 +691,12 @@ class AgentLoop:if content:output_chars += len(content)text_parts.append(content)- # Every round's text streams to the user; the round's- # call_role (emitted at completion) tells the frontend- # whether to render it as narration or as the answer.- # Inline <think> segments are split off to the thinking- # channel so the content stream stays user-facing.- if not dsml_stream_active and has_dsml_tool_calls("".join(text_parts)):- dsml_stream_active = True- segments = think_filter.feed(content)- if dsml_stream_active:- segments = [("thinking", seg) for _, seg in segments]- await _emit_segments(segments)+ # Every round's text streams to the user; inline <think>+ # segments remain trace-only while DSML markup and its+ # argument payload never enter either visible channel.+ visible_content = dsml_filter.feed(content)+ if visible_content:+ await _emit_segments(think_filter.feed(visible_content))for tc_delta in getattr(delta, "tool_calls", None) or []:index = int(getattr(tc_delta, "index", 0) or 0)@@ -586,10 +721,10 @@ class AgentLoop:with suppress(Exception):await close()- flushed = think_filter.flush()- if dsml_stream_active:- flushed = [("thinking", seg) for _, seg in flushed]- await _emit_segments(flushed)+ dsml_tail = dsml_filter.flush()+ if dsml_tail:+ await _emit_segments(think_filter.feed(dsml_tail))+ await _emit_segments(think_filter.flush())text = "".join(text_parts)record_streamed_usage(self.pipeline.usage,@@ -610,14 +745,31 @@ class AgentLoop:# Fallback: a DeepSeek deployment without native function calling emits# its tool calls as DSML markup in the content channel instead of as- # structured ``tool_calls`` (issue #666). Parse them out so the normal- # dispatch path runs the tools, and drop the markup from ``text`` so it- # can't leak into the conversation / answer.- if not tool_calls:- dsml_calls, cleaned_text = extract_dsml_tool_calls(text)- if dsml_calls:+ # structured ``tool_calls`` (issue #666). Always parse/clean the markup+ # (even if the provider also emitted native deltas); prefer native calls+ # when both representations are present to avoid double dispatch.+ dsml_calls, cleaned_text = extract_dsml_tool_calls(text, self._tool_schema_catalog)+ if dsml_calls:+ if not tool_calls:tool_calls = dsml_calls- text = cleaned_text+ text = cleaned_text++ truncated_round = call_kind == "agent_loop_round" and _finish_was_truncated(finish_reason)+ completion_metadata: dict[str, Any] = {+ "trace_kind": "call_status",+ "call_state": "complete",+ # A round with tool calls is narration; a tool-less round is the+ # 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",+ }+ if (dsml_calls or truncated_round) and answer_content_emitted:+ # DSML providers may intentionally combine tutor feedback and an+ # ask_user/tool call in the same round. Preserve only that cleaned+ # surrounding prose in the answer surfaces. Truncated rounds also+ # keep their partial answer visible while retaining a truthful+ # non-terminal ``narration`` role.+ completion_metadata["answer_visible"] = Trueawait self.stream.progress("",@@ -625,16 +777,15 @@ class AgentLoop:stage=stage,metadata=merge_trace_metadata(trace_meta,- {- "trace_kind": "call_status",- "call_state": "complete",- # A round with tool calls is narration; a tool-less round- # is the finish whose text is the user-facing answer.- "call_role": "narration" if tool_calls else "finish",- },+ completion_metadata,),)- return LLMCallResult(text=text, tool_calls=tool_calls, finish_reason=finish_reason)+ return LLMCallResult(+ text=text,+ visible_text="".join(visible_text_parts),+ tool_calls=tool_calls,+ finish_reason=finish_reason,+ )async def _create_response_stream(self,diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.pyindex 0adffb955..112792697 100644--- a/deeptutor/agents/chat/agentic_pipeline.py+++ b/deeptutor/agents/chat/agentic_pipeline.py@@ -417,6 +417,9 @@ class AgenticChatPipeline:def _finish_exhausted_instruction(self) -> str:return self._prompt_assembler.finish_exhausted_instruction()+ def _settle_exhausted_instruction(self) -> str:+ return self._prompt_assembler.settle_exhausted_instruction()+def _tool_manifest(self, enabled_tools: list[str]) -> str:names = list(enabled_tools)if self._deferred_loader is not None:diff --git a/deeptutor/agents/chat/dsml_tool_calls.py b/deeptutor/agents/chat/dsml_tool_calls.pyindex 57aa972a8..33a67836e 100644--- a/deeptutor/agents/chat/dsml_tool_calls.py+++ b/deeptutor/agents/chat/dsml_tool_calls.py@@ -25,7 +25,7 @@ from __future__ import annotationsimport jsonimport re-from typing import Any+from typing import Any, Iterable# A real DSML tool-call tag (not prose that merely mentions "tool_calls"): an# opening ``<...invoke name="`` or any ``<...DSML...>`` tag. Used to decide@@ -46,6 +46,100 @@ _PARAM_RE = re.compile(# The ``<...tool_calls>`` open/close wrapper, stripped from the cleaned text once# we have extracted the invokes inside it._TOOLCALLS_WRAP_RE = re.compile(r"</?[^>]*?tool_calls\s*>", re.IGNORECASE)+_INVOKE_OPEN_TAG_RE = re.compile(+ r"<[^>]*?invoke\s+name\s*=\s*\"[^\"]+\"[^>]*>",+ re.IGNORECASE,+)+_INVOKE_CLOSE_TAG_RE = re.compile(r"</[^>]*?invoke\s*>", re.IGNORECASE)+_TOOLCALLS_OPEN_TAG_RE = re.compile(r"<(?!/)[^>]*?tool_calls\s*>", re.IGNORECASE)+_TOOLCALLS_CLOSE_TAG_RE = re.compile(r"</[^>]*?tool_calls\s*>", re.IGNORECASE)++# A malformed HTML-ish fragment should not make the live stream wait forever+# for a closing ``>``. Real DSML tags are much shorter than this ceiling.+_MAX_PARTIAL_TAG_CHARS = 512+++class DSMLStreamFilter:+ """Incrementally remove complete DSML calls from streamed text.++ Only the DSML envelope and ``invoke`` blocks are suppressed. Text before,+ between, and after calls is returned immediately, so one tool call cannot+ redirect the rest of the round into a different output channel. Incomplete+ invokes are released verbatim by :meth:`flush` instead of silently losing+ provider output.+ """++ def __init__(self) -> None:+ self._buffer = ""+ self._pending_close: re.Pattern[str] | None = None++ @staticmethod+ def _clean_block(block: str) -> str:+ calls, _ = extract_dsml_tool_calls(block)+ if not calls:+ return block+ cleaned = block+ for match in reversed(list(_INVOKE_RE.finditer(block))):+ cleaned = cleaned[: match.start()] + cleaned[match.end() :]+ return _TOOLCALLS_WRAP_RE.sub("", cleaned)++ def feed(self, chunk: str) -> str:+ self._buffer += chunk+ visible: list[str] = []++ while self._buffer:+ if self._pending_close is not None:+ close = self._pending_close.search(self._buffer)+ if close is None:+ break+ block = self._buffer[: close.end()]+ self._buffer = self._buffer[close.end() :]+ self._pending_close = None+ visible.append(self._clean_block(block))+ continue++ tag_start = self._buffer.find("<")+ if tag_start < 0:+ visible.append(self._buffer)+ self._buffer = ""+ break+ if tag_start:+ visible.append(self._buffer[:tag_start])+ self._buffer = self._buffer[tag_start:]++ tag_end = self._buffer.find(">")+ if tag_end < 0:+ if len(self._buffer) <= _MAX_PARTIAL_TAG_CHARS:+ break+ # This is ordinary prose containing ``<``, not a plausible+ # DSML tag. Release one character and keep scanning.+ visible.append(self._buffer[0])+ self._buffer = self._buffer[1:]+ continue++ tag = self._buffer[: tag_end + 1]+ if _TOOLCALLS_OPEN_TAG_RE.fullmatch(tag):+ self._pending_close = _TOOLCALLS_CLOSE_TAG_RE+ # Keep the entire envelope buffered. We only suppress it once+ # a complete invoke was parsed; malformed provider output is+ # released unchanged instead of losing text at the boundary.+ continue+ if _INVOKE_OPEN_TAG_RE.fullmatch(tag):+ self._pending_close = _INVOKE_CLOSE_TAG_RE+ continue+ self._buffer = self._buffer[tag_end + 1 :]+ if _TOOLCALLS_WRAP_RE.fullmatch(tag):+ continue+ visible.append(tag)++ return "".join(visible)++ def flush(self) -> str:+ """Release buffered text, cleaning any complete unwrapped call."""+ remaining = self._buffer+ self._buffer = ""+ self._pending_close = None+ return self._clean_block(remaining)def _looks_like_string(attrs: str) -> bool:@@ -53,8 +147,53 @@ def _looks_like_string(attrs: str) -> bool:return 'string="true"' in normalized.lower()-def _coerce_param_value(raw: str, attrs: str) -> Any:- if _looks_like_string(attrs):+def _schema_types(schema: dict[str, Any] | None) -> set[str]:+ if not isinstance(schema, dict):+ return set()+ value = schema.get("type")+ if isinstance(value, str):+ types = {value}+ elif isinstance(value, list):+ types = {item for item in value if isinstance(item, str)}+ else:+ types = set()+ if "properties" in schema:+ types.add("object")+ if "items" in schema:+ types.add("array")+ for keyword in ("anyOf", "oneOf", "allOf"):+ alternatives = schema.get(keyword)+ if isinstance(alternatives, list):+ for alternative in alternatives:+ types.update(_schema_types(alternative))+ return {str(item) for item in types}+++def _coerce_param_value(+ raw: str,+ attrs: str,+ schema: dict[str, Any] | None = None,+) -> Any:+ stripped = raw.strip()+ schema_types = _schema_types(schema)+ expects_container = bool(schema_types & {"array", "object"})+ explicitly_string = schema_types == {"string"}++ # DeepSeek commonly marks every DSML parameter ``string=true``, including+ # JSON arrays and objects. A declared container schema wins over that wire+ # hint. Without a schema, retain the provider's explicit string contract.+ if expects_container:+ try:+ parsed = json.loads(stripped)+ except (TypeError, ValueError):+ pass+ else:+ matches_array = "array" in schema_types and isinstance(parsed, list)+ matches_object = "object" in schema_types and isinstance(parsed, dict)+ if matches_array or matches_object:+ return parsed++ if _looks_like_string(attrs) or explicitly_string:return raw# Unmarked scalars (numbers, bools, JSON objects/arrays) are parsed; on any# failure the raw string is kept verbatim.@@ -66,30 +205,64 @@ def _coerce_param_value(raw: str, attrs: str) -> Any:def has_dsml_tool_calls(text: str | None) -> bool:"""Cheap check for whether ``text`` carries DSML tool-call markup."""- return bool(text) and bool(DSML_SIGNAL_RE.search(text))+ if not text:+ return False+ return bool(DSML_SIGNAL_RE.search(text))+++def _parameter_schemas(+ tool_schemas: Iterable[dict[str, Any]] | None,+) -> dict[str, dict[str, dict[str, Any]]]:+ by_tool: dict[str, dict[str, dict[str, Any]]] = {}+ for tool in tool_schemas or []:+ function = tool.get("function") if isinstance(tool, dict) else None+ if not isinstance(function, dict):+ continue+ name = str(function.get("name") or "").strip()+ parameters = function.get("parameters")+ properties = parameters.get("properties") if isinstance(parameters, dict) else None+ if not name or not isinstance(properties, dict):+ continue+ by_tool[name] = {+ str(param_name): param_schema+ for param_name, param_schema in properties.items()+ if isinstance(param_schema, dict)+ }+ return by_tool-def extract_dsml_tool_calls(text: str | None) -> tuple[list[dict[str, Any]], str]:+def extract_dsml_tool_calls(+ text: str | None,+ tool_schemas: Iterable[dict[str, Any]] | None = None,+) -> tuple[list[dict[str, Any]], str]:"""Parse DSML tool-call markup out of ``text``.+ ``tool_schemas`` supplies JSON-Schema types for parameters. Container+ schemas deliberately override DeepSeek's blanket ``string=true`` hint.Returns ``(tool_calls, cleaned_text)``. ``tool_calls`` is empty and``cleaned_text is text`` when no well-formed invoke block is present, so thecaller can treat "no calls" as "not a DSML round" and fall throughunchanged."""- if not has_dsml_tool_calls(text):- return [], text or ""+ raw_text = text or ""+ if not has_dsml_tool_calls(raw_text):+ return [], raw_text+ schemas_by_tool = _parameter_schemas(tool_schemas)tool_calls: list[dict[str, Any]] = []spans: list[tuple[int, int]] = []- for idx, match in enumerate(_INVOKE_RE.finditer(text)):+ for idx, match in enumerate(_INVOKE_RE.finditer(raw_text)):name = match.group("name").strip()if not name:continueargs: dict[str, Any] = {}+ parameter_schemas = schemas_by_tool.get(name, {})for param in _PARAM_RE.finditer(match.group("body")):- args[param.group("pname").strip()] = _coerce_param_value(- param.group("pval"), param.group("attrs") or ""+ param_name = param.group("pname").strip()+ args[param_name] = _coerce_param_value(+ param.group("pval"),+ param.group("attrs") or "",+ parameter_schemas.get(param_name),)tool_calls.append({@@ -101,13 +274,18 @@ def extract_dsml_tool_calls(text: str | None) -> tuple[list[dict[str, Any]], strspans.append((match.start(), match.end()))if not tool_calls:- return [], text+ return [], raw_text- cleaned = text+ cleaned = raw_textfor start, end in reversed(spans):cleaned = cleaned[:start] + cleaned[end:]cleaned = _TOOLCALLS_WRAP_RE.sub("", cleaned).strip()return tool_calls, cleaned-__all__ = ["extract_dsml_tool_calls", "has_dsml_tool_calls", "DSML_SIGNAL_RE"]+__all__ = [+ "DSMLStreamFilter",+ "extract_dsml_tool_calls",+ "has_dsml_tool_calls",+ "DSML_SIGNAL_RE",+]diff --git a/deeptutor/agents/chat/prompt_blocks.py b/deeptutor/agents/chat/prompt_blocks.pyindex 474ce2985..332ae1d79 100644--- a/deeptutor/agents/chat/prompt_blocks.py+++ b/deeptutor/agents/chat/prompt_blocks.py@@ -163,6 +163,17 @@ class ChatPromptAssembler:),)+ def settle_exhausted_instruction(self) -> str:+ return self._t(+ "loop.settle_exhausted",+ default=(+ "The exploration round budget is exhausted. Do not start new "+ "searches or optional work. Complete only protocol steps, state "+ "transitions, or user interactions already made necessary by "+ "the work above, then provide the final user-facing answer."+ ),+ )+def _fallback_empty_tool_list(self) -> str:return "- 无" if self.language == "zh" else "- none"diff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yamlindex 7a01a96da..6a850597c 100644--- a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml+++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml@@ -84,6 +84,14 @@ loop:finish_exhausted: |-The round budget ran out before every gap was closed. Stop calling toolsand answer now with what you have, noting briefly what remains uncertain.+ settle_exhausted: |-+ The exploration round budget is exhausted. Do not start new searches or optional work.+ Complete only protocol steps, state transitions, or user interactions already made+ necessary by the work above; tools remain available only for that required follow-up.+ Then stop calling tools and provide the final user-facing answer.+ continue_truncated: |-+ Your previous response stopped at the token limit. Continue from where it ended+ without repeating it, and complete the user-facing answer.finish_empty_nudge: |-Your previous round produced only internal reasoning — no tool call andno user-facing answer. Continue now: either call the tools to execute@@ -106,6 +114,8 @@ notices:start_retrieval: "Starting retrieval"empty_tool_result: "The tool completed without returning text output."loop_budget_exhausted: "Exploration budget reached; answering with what has been gathered."+ loop_settlement: "Exploration budget reached; completing required follow-up before the final answer."+ output_truncated: "The model output reached its token limit; asked it to continue."loop_error_finish: "A step failed; answering with what has been gathered."context_window_guard: "Trimmed older tool results to keep this turn within the model's context window."tool_schema_fallback: "Provider rejected native tool schemas; retrying without tools."diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yamlindex 479f15840..e2d6eb6de 100644--- a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml+++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml@@ -58,6 +58,11 @@ loop:{user_message}finish_exhausted: |-循环轮次预算已用尽,仍有缺口未补齐。现在停止调用工具,基于已有材料作答,并简短说明仍不确定的部分。+ settle_exhausted: |-+ 探索轮次预算已用尽。不要发起新的搜索或可选工作;只完成前面工作已经要求的协议步骤、状态转换或用户交互,+ 工具仅可用于这些必要收尾。随后停止调用工具并给出面向用户的最终回答。+ continue_truncated: |-+ 你上一条回复因 token 上限而中断。请从中断处继续,不要重复已有内容,并完成面向用户的回答。finish_empty_nudge: |-你上一轮只输出了内部推理——既没有调用工具,也没有写出面向用户的回答。现在继续:要么调用工具执行你计划好的步骤,要么直接写出最终回答。@@ -78,6 +83,8 @@ notices:start_retrieval: "开始检索"empty_tool_result: "工具执行完成,但没有返回文本内容。"loop_budget_exhausted: "探索轮次预算已用尽,将基于已收集的材料作答。"+ loop_settlement: "探索轮次预算已用尽;正在完成必要收尾,然后给出最终回答。"+ output_truncated: "模型输出达到 token 上限,已要求其继续完成回答。"loop_error_finish: "某一步执行失败,将基于已收集的材料作答。"context_window_guard: "已裁剪较旧的工具结果,以确保本轮在模型上下文窗口内。"tool_schema_fallback: "服务方拒绝了原生工具 schema;将不带工具重试。"diff --git a/deeptutor/api/main.py b/deeptutor/api/main.pyindex bed5fb64c..279f9996d 100644--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@ -2,9 +2,8 @@ from contextlib import asynccontextmanagerimport loggingimport sys-from fastapi import Depends, FastAPI, HTTPException+from fastapi import Depends, FastAPIfrom fastapi.middleware.cors import CORSMiddleware-from fastapi.staticfiles import StaticFilesfrom deeptutor.logging import configure_loggingfrom deeptutor.services.config import (@@ -41,19 +40,6 @@ CONFIG_DRIFT_ERROR_TEMPLATE = ()-class SafeOutputStaticFiles(StaticFiles):- """Static file mount that only exposes explicitly whitelisted artifacts."""-- def __init__(self, *args, path_service, **kwargs):- super().__init__(*args, **kwargs)- self._path_service = path_service-- async def get_response(self, path: str, scope):- if not self._path_service.is_public_output_path(path):- raise HTTPException(status_code=404, detail="Output not found")- return await super().get_response(path, scope)--def validate_tool_consistency():"""Validate that capability manifests only reference tools that are actually@@ -310,11 +296,6 @@ app.add_middleware(allow_headers=["*"],)-# Mount a filtered view over user outputs.-# Only whitelisted artifact paths are readable through the static handler.-path_service = get_path_service()-user_dir = path_service.get_public_outputs_root()-# Initialize user directories on startuptry:from deeptutor.services.setup import init_user_directories@@ -322,15 +303,10 @@ try:init_user_directories()except Exception:# Fallback: just create the main directory if it doesn't exist+ user_dir = get_path_service().get_public_outputs_root()if not user_dir.exists():user_dir.mkdir(parents=True)-app.mount(- "/api/outputs",- SafeOutputStaticFiles(directory=str(user_dir), path_service=path_service),- name="outputs",-)-# Import routers only after runtime settings are initialized.# Some router modules load YAML settings at import time.from deeptutor.api.routers import (@@ -348,6 +324,7 @@ from deeptutor.api.routers import (mcp_settings,memory,notebook,+ outputs,partners,personas,plugins_api,@@ -371,6 +348,7 @@ from deeptutor.multi_user.router import router as multi_user_router # noqa: E40# Auth router is public — login/logout/register/status require no tokenapp.include_router(auth.router, prefix="/api/v1/auth", tags=["auth"])+app.include_router(outputs.router, prefix="/api/outputs", tags=["outputs"])# All other routers require a valid session when AUTH_ENABLED=true.# require_auth is a no-op when AUTH_ENABLED=false, so this is safe for local use.diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex 2fa90f600..bd60ffee2 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -35,7 +35,7 @@ from deeptutor.api.utils.task_id_manager import TaskIDManagerfrom deeptutor.api.utils.task_log_stream import capture_task_logs, get_task_stream_managerfrom deeptutor.knowledge.add_documents import DocumentAdder, remove_raw_documentfrom deeptutor.knowledge.initializer import KnowledgeBaseInitializer-from deeptutor.knowledge.kb_types import is_connected_kb+from deeptutor.knowledge.kb_types import is_connected_kb, supports_local_raw_filesfrom deeptutor.knowledge.manager import KnowledgeBaseManagerfrom deeptutor.knowledge.naming import validate_knowledge_base_namefrom deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker@@ -702,8 +702,8 @@ def _assert_not_connected_kb(kb_name: str, kb_entry: dict) -> None:raise HTTPException(status_code=409,detail=(- f"Knowledge base '{kb_name}' is connected to an external folder and is "- "read-only. Uploads and re-indexing are not available for it."+ f"Knowledge base '{kb_name}' is connected to an external resource and is "+ "read-only. Local file operations and re-indexing are not available for it."),)@@ -1973,21 +1973,42 @@ async def get_knowledge_base_details(kb_name: str):raise HTTPException(status_code=500, detail=str(e))-def _resolve_kb_raw_dir(kb_name: str) -> Path:- """Resolve the raw/ directory for a KB, validating that it exists."""+def _resolve_kb_raw_dir(kb_name: str, *, allow_unsupported: bool = False) -> Path | None:+ """Resolve a KB's managed ``raw/`` directory without inventing one.++ Connected KBs are external-resource pointers and intentionally have no+ DeepTutor-managed raw directory. File listing treats that as an empty+ collection for backwards compatibility; endpoints that require a local+ file receive an explicit conflict response.+ """manager = _overridden_kb_manager()if manager is not None:resolved_name = _resolve_registered_kb_name(manager, kb_name)- return manager.get_knowledge_base_path(resolved_name) / "raw"- resource = resolve_kb(kb_name)- manager = manager_for_resource(resource)- kb_path = manager.get_knowledge_base_path(resource.name)+ else:+ resource = resolve_kb(kb_name)+ manager = manager_for_resource(resource)+ resolved_name = resource.name++ kb_entry = _load_kb_entry_or_404(manager, resolved_name)+ if not supports_local_raw_files(kb_entry):+ if allow_unsupported:+ return None+ raise HTTPException(+ status_code=409,+ detail=(+ f"Knowledge base '{resolved_name}' is connected to an external resource "+ "and has no local files."+ ),+ )++ kb_path = manager.get_knowledge_base_path(resolved_name)return kb_path / "raw"def _resolve_kb_raw_file_or_404(kb_name: str, filename: str) -> Path:"""Resolve a raw KB file while preventing traversal outside raw/."""raw_dir = _resolve_kb_raw_dir(kb_name)+ assert raw_dir is not None # allow_unsupported=False guarantees a pathif not raw_dir.exists():raise HTTPException(status_code=404, detail="File not found")@@ -2014,7 +2035,9 @@ async def list_kb_raw_files(kb_name: str):before it holds any files. Folders are purely organizational and have noeffect on indexing or retrieval."""- raw_dir = _resolve_kb_raw_dir(kb_name)+ raw_dir = _resolve_kb_raw_dir(kb_name, allow_unsupported=True)+ if raw_dir is None:+ return {"files": []}if not raw_dir.exists() or not raw_dir.is_dir():return {"files": []}@@ -2201,16 +2224,15 @@ async def upload_files("""Upload files to a knowledge base and process them in background."""try:manager, kb_name, kb_base_dir = _writable_kb(kb_name)- kb_path = manager.get_knowledge_base_path(kb_name)- raw_dir = kb_path / "raw"- raw_dir.mkdir(parents=True, exist_ok=True)-requested_provider = Noneif rag_provider is not None and str(rag_provider).strip():requested_provider = _validate_registered_provider(rag_provider)kb_entry = _load_kb_entry_or_404(manager, kb_name)_assert_kb_writable_or_409(kb_name, kb_entry)+ kb_path = manager.get_knowledge_base_path(kb_name)+ raw_dir = kb_path / "raw"+ raw_dir.mkdir(parents=True, exist_ok=True)kb_provider = _validate_registered_provider(kb_entry.get("rag_provider") or DEFAULT_PROVIDER)diff --git a/deeptutor/api/routers/outputs.py b/deeptutor/api/routers/outputs.pynew file mode 100644index 000000000..6d763477a--- /dev/null+++ b/deeptutor/api/routers/outputs.py@@ -0,0 +1,47 @@+"""Request-scoped delivery of generated output artifacts."""++from __future__ import annotations++from pathlib import Path++from fastapi import APIRouter, Depends, HTTPException, status+from fastapi.responses import FileResponse++from deeptutor.api.routers.auth import require_auth+from deeptutor.multi_user.context import get_current_user_or_none+from deeptutor.multi_user.paths import get_path_service_for_scope+from deeptutor.services.auth import TokenPayload+from deeptutor.services.path_service import PathService++router = APIRouter()+++def _request_path_service() -> PathService:+ """Resolve the workspace installed by ``require_auth`` without fallback.++ The general-purpose ``get_path_service()`` retains a compatibility fallback+ to the local admin workspace for non-request callers. A download endpoint+ must fail closed instead: otherwise an authentication/context regression+ could expose an administrator artifact to an ordinary request.+ """+ user = get_current_user_or_none()+ if user is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Output not found")+ return get_path_service_for_scope(user.scope)+++def _resolve_output(path_service: PathService, relative_path: str) -> Path:+ output_path = path_service.resolve_public_output_path(relative_path)+ if output_path is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Output not found")+ return output_path++[email protected]_route("/{output_path:path}", methods=["GET", "HEAD"])+async def read_output(+ output_path: str,+ _auth: TokenPayload | None = Depends(require_auth),+) -> FileResponse:+ """Serve one allowlisted artifact from the authenticated user's workspace."""+ path = _resolve_output(_request_path_service(), output_path)+ return FileResponse(path)diff --git a/deeptutor/api/routers/system.py b/deeptutor/api/routers/system.pyindex a4be0802b..f83b06bdc 100644--- a/deeptutor/api/routers/system.py+++ b/deeptutor/api/routers/system.py@@ -3,6 +3,7 @@ System Status API RouterManages system status checks and model connection tests"""+import asynciofrom datetime import datetimeimport time@@ -10,6 +11,7 @@ from fastapi import APIRouterfrom pydantic import BaseModelfrom deeptutor.multi_user.context import get_current_user+from deeptutor.runtime import memory_probefrom deeptutor.services.config import resolve_search_runtime_configfrom deeptutor.services.embedding import get_embedding_client, get_embedding_configfrom deeptutor.services.llm import complete as llm_complete@@ -145,6 +147,60 @@ async def get_system_status():return result[email protected]("/memory")+async def get_memory_usage():+ """Resident memory of the running DeepTutor process tree.++ Deliberately separate from ``/status``: that snapshot resolves the LLM,+ embedding and search configs and is fetched once per settings mount, while+ this one is cheap enough for the status strip to poll.++ Admin-only, for the same reason ``/status`` strips model names from+ non-admins — process composition and host memory are operational detail a+ tenant has no need for.+ """+ if not get_current_user().is_admin:+ return {"available": False}++ snapshot = await asyncio.to_thread(memory_probe.capture)+ if not snapshot.processes:+ return {"available": False}++ # Fold the tree into one row per role, largest first, so the tooltip stays+ # readable when capabilities have spawned a dozen short-lived sandboxes.+ grouped: dict[str, dict[str, int]] = {}+ for proc in snapshot.processes:+ row = grouped.setdefault(proc.label, {"count": 0, "rss_bytes": 0})+ row["count"] += 1+ row["rss_bytes"] += proc.rss_bytes+ ranked = sorted(grouped.items(), key=lambda item: item[1]["rss_bytes"], reverse=True)++ processes = [+ {"label": label, "count": row["count"], "rss_bytes": row["rss_bytes"]}+ for label, row in ranked[: memory_probe.MAX_REPORTED_PROCESSES]+ ]+ overflow = ranked[memory_probe.MAX_REPORTED_PROCESSES :]+ if overflow:+ processes.append(+ {+ "label": "other",+ "count": sum(row["count"] for _label, row in overflow),+ "rss_bytes": sum(row["rss_bytes"] for _label, row in overflow),+ }+ )++ return {+ "available": True,+ "total_rss_bytes": snapshot.total_rss_bytes,+ "limit_bytes": snapshot.limit_bytes,+ "available_bytes": snapshot.available_bytes,+ "limit_source": snapshot.limit_source,+ "usage_ratio": snapshot.usage_ratio,+ "partial": snapshot.partial,+ "processes": processes,+ }++@router.post("/test/llm", response_model=TestResponse)async def test_llm_connection():"""diff --git a/deeptutor/capabilities/mastery/choices.py b/deeptutor/capabilities/mastery/choices.pyindex b506b05a6..d0e7e5355 100644--- a/deeptutor/capabilities/mastery/choices.py+++ b/deeptutor/capabilities/mastery/choices.py@@ -22,77 +22,17 @@ module free of infrastructure wiring.from __future__ import annotationsimport logging-import refrom typing import Any-logger = logging.getLogger(__name__)--# Matches a labelled option like ``"C: body"`` / ``"C) body"`` / ``"C、body"``,-# capturing the label letter and the body. Used to recover the label a model-# embedded in the option text instead of supplying it positionally.-OPTION_PREFIX_RE = re.compile(r"^\s*([A-Z])\s*[.::、))-]\s*(.+)$", re.IGNORECASE)---def parse_options(options: list[str]) -> dict[str, str]:- """Map option strings to ``{label: body}``.-- ``"C: the answer"`` → ``{"C": "the answer"}``; a bare single character- ``"C"`` maps to itself (a label-only registration); anything else gets a- positional label (A, B, C, … then 27, 28, … past Z).- """- result: dict[str, str] = {}- for idx, raw in enumerate(options):- text = str(raw or "").strip()- if not text:- continue- match = OPTION_PREFIX_RE.match(text)- if match:- result[match.group(1).upper()] = match.group(2).strip()- elif len(text) == 1 and text.isalnum():- result[text.upper()] = text- else:- result[chr(ord("A") + idx) if idx < 26 else str(idx + 1)] = text- return result---def has_option_bodies(options: dict[str, str]) -> bool:- """Whether a choice map holds real answer text, not only A/B/C labels."""- return len(options) >= 2 and all(- value.strip() and value.strip().upper() != key.upper() for key, value in options.items()- )-+from deeptutor.learning.pending import (+ format_options,+ has_option_bodies,+ parse_options,+ resolve_answer,+ resolve_choice_submission,+)-def format_options(options: dict[str, str]) -> list[str]:- """Render a ``{label: body}`` map back to canonical ``"label: body"`` strings."""- return [f"{label}: {body}" for label, body in options.items()]---def resolve_answer(expected_answer: str, options: dict[str, str]) -> str:- """Resolve a model-supplied choice answer to its stable option label.-- Models occasionally send ``"Step 6"`` or the full option text even though- the interactive card returns ``"C"``. Resolve a unique textual match at- registration time so deterministic grading compares like with like. Returns- ``""`` when nothing matches or the match is ambiguous.- """- expected = str(expected_answer or "").strip()- if not expected:- return ""-- key = expected.upper()- if key in options:- return key-- prefix_match = OPTION_PREFIX_RE.match(expected)- if prefix_match and prefix_match.group(1).upper() in options:- return prefix_match.group(1).upper()-- needle = expected.casefold()- exact = [label for label, text in options.items() if text.casefold() == needle]- if len(exact) == 1:- return exact[0]- contained = [label for label, text in options.items() if needle in text.casefold()]- return contained[0] if len(contained) == 1 else ""+logger = logging.getLogger(__name__)def _normalized_prompt(value: str) -> str:@@ -141,3 +81,13 @@ async def recover_options_from_turn(store: Any, turn_id: str, question: str) ->if prompt == target or prompt.startswith(target) or target.startswith(prompt):return recoveredreturn {}+++__all__ = [+ "format_options",+ "has_option_bodies",+ "parse_options",+ "recover_options_from_turn",+ "resolve_answer",+ "resolve_choice_submission",+]diff --git a/deeptutor/capabilities/mastery/loop.py b/deeptutor/capabilities/mastery/loop.pyindex 6e25c7838..70ead2908 100644--- a/deeptutor/capabilities/mastery/loop.py+++ b/deeptutor/capabilities/mastery/loop.py@@ -3,12 +3,45 @@from __future__ import annotationsfrom importlib import resources+import loggingfrom typing import Anyfrom deeptutor.capabilities.mastery.tools import MASTERY_TOOL_NAMESfrom deeptutor.capabilities.protocol import PromptBlockfrom deeptutor.core.context import UnifiedContext+logger = logging.getLogger(__name__)+++def _bind_pending_ask_user_args(kwargs: dict[str, Any], path_id: str) -> dict[str, Any]:+ """Replace model-authored quiz display data with persisted public state.++ Binding at this adapter boundary prevents the model from changing question+ ids or reassigning A/B/C labels after a pause or on a later turn. Generic+ clarification cards remain untouched when no mastery question is pending.+ """+ if not path_id:+ return kwargs+ try:+ from deeptutor.learning.pending import public_pending_question+ from deeptutor.learning.storage import LearningStore++ progress = LearningStore().load(path_id)+ pending = progress.pending_question if progress is not None else None+ except Exception:+ logger.warning("Failed to load pending mastery question for ask_user", exc_info=True)+ return kwargs+ if pending is None:+ return kwargs++ updated = dict(kwargs)+ updated["questions"] = [public_pending_question(pending).to_ask_user_dict()]+ # Remove the accepted legacy shape so it cannot compete with the canonical+ # question list in ``build_ask_user_payload``.+ updated.pop("question", None)+ updated.pop("options", None)+ return updated+class MasteryLoopCapability:"""Turn-scoped integration for mastery-path tutoring.@@ -42,9 +75,14 @@ class MasteryLoopCapability:kwargs: dict[str, Any],context: UnifiedContext,) -> dict[str, Any]:- if self.is_active(context) and tool_name in MASTERY_TOOL_NAMES:+ if not self.is_active(context):+ return kwargs+ path_id = str(context.metadata.get("mastery_path_id") or "").strip()+ if tool_name == "ask_user":+ return _bind_pending_ask_user_args(kwargs, path_id)+ if tool_name in MASTERY_TOOL_NAMES:updated = dict(kwargs)- updated["_mastery_path_id"] = str(context.metadata.get("mastery_path_id") or "").strip()+ updated["_mastery_path_id"] = path_idupdated["_session_id"] = str(context.session_id or "").strip()updated["_turn_id"] = str(context.metadata.get("turn_id") or "").strip()return updateddiff --git a/deeptutor/capabilities/mastery/prompts/en/system.md b/deeptutor/capabilities/mastery/prompts/en/system.mdindex 73a25b898..2ce6b552f 100644--- a/deeptutor/capabilities/mastery/prompts/en/system.md+++ b/deeptutor/capabilities/mastery/prompts/en/system.md@@ -6,7 +6,7 @@ FIRST on every turn, call `mastery_status`. It returns the next objective to worThen act on the objective:- No objectives yet? Design a path from the learner's materials (use `rag` / `read_source` when materials are attached) and call `mastery_build`. Tag each knowledge point: memory (facts), procedure (step-by-step skills), concept (ideas to understand), design (open-ended judgement).- `probe` (untouched): briefly check whether the learner already knows it before teaching. A test-out is not a silent skip — record its result through the gate (`mastery_assess` for concept / design, `mastery_quiz` + `mastery_grade` for memory / procedure) before advancing. Never move past an objective the engine hasn't marked mastered.-- memory / procedure objectives: register the question + its answer with `mastery_quiz`, then ALWAYS present it with the `ask_user` tool so the learner answers on an interactive card — never write the choices as plain numbered text. For multiple choice, pass every full option body to `mastery_quiz.options` in label order (for example `A: ...`, `B: ...`), give the matching `ask_user` options the short labels A / B / C … with those same bodies as their descriptions, and set the correct label as `mastery_quiz`'s `expected_answer`. Never pass bare labels as `mastery_quiz.options`. For open questions use `ask_user` free text. When the answer comes back, score it with `mastery_grade`. Keep working the same objective until `mastery_grade` reports `mastered: true`.+- memory / procedure objectives: register the question + its answer with `mastery_quiz`, then ALWAYS present it with the `ask_user` tool so the learner answers on an interactive card — never write the choices as plain numbered text. For multiple choice, pass every full option body to `mastery_quiz.options` in label order (for example `A: ...`, `B: ...`), give the matching `ask_user` options the short labels A / B / C … with those same bodies as their descriptions, and set the correct label as `mastery_quiz`'s `expected_answer`. Never pass bare labels as `mastery_quiz.options`. If `mastery_status.next.pending_question` exists, reuse its question id, prompt, and option labels/bodies exactly; never regenerate or reorder them. For open questions use `ask_user` free text. When the answer comes back, score it with `mastery_grade`, passing the persisted `question_id`. Keep working the same objective until `mastery_grade` reports `mastered: true`.- concept / design objectives: ask the learner to explain the idea in their own words, judge it, and record the result with `mastery_assess` (`passed: true` only when the explanation truly shows understanding).- `review`: a spaced-repetition item is due — quiz it again to refresh it.- `complete`: congratulate the learner and summarise what they have mastered.diff --git a/deeptutor/capabilities/mastery/prompts/zh/system.md b/deeptutor/capabilities/mastery/prompts/zh/system.mdindex 32423e051..d8e96c641 100644--- a/deeptutor/capabilities/mastery/prompts/zh/system.md+++ b/deeptutor/capabilities/mastery/prompts/zh/system.md@@ -6,7 +6,7 @@然后针对该知识点行动:- 还没有任何知识点?根据学习者的材料设计一条路径(材料已挂载时用 `rag` / `read_source`),调用 `mastery_build`。给每个知识点标类型:memory(记忆/事实)、procedure(程序/步骤技能)、concept(概念/需理解)、design(设计/开放判断)。- `probe`(未触碰):先简短探查学习者是否已经会了再教。"测试通过"不等于直接跳过——仍要用门工具记录结果(concept / design 用 `mastery_assess`,memory / procedure 用 `mastery_quiz` + `mastery_grade`)再推进;绝不要越过引擎尚未标记为"已掌握"的知识点。-- memory / procedure 类:先用 `mastery_quiz` 登记题目与答案,然后**始终用 `ask_user` 工具**把题目呈现成可点选的卡片让学习者作答——绝不要把选项写成纯文字的 1./2./3.。选择题必须把每个选项的完整正文按标签顺序传入 `mastery_quiz.options`(例如 `A:……`、`B:……`),再给 `ask_user` 使用 A / B / C … 短标签,并把相同正文放进对应 description;正确标签设为 `mastery_quiz` 的 `expected_answer`。绝不能只把 A/B/C/D 裸标签传给 `mastery_quiz.options`。简答题用 `ask_user` 的自由输入。收到作答后用 `mastery_grade` 批改。在 `mastery_grade` 返回 `mastered: true` 之前,持续打磨同一个知识点。+- memory / procedure 类:先用 `mastery_quiz` 登记题目与答案,然后**始终用 `ask_user` 工具**把题目呈现成可点选的卡片让学习者作答——绝不要把选项写成纯文字的 1./2./3.。选择题必须把每个选项的完整正文按标签顺序传入 `mastery_quiz.options`(例如 `A:……`、`B:……`),再给 `ask_user` 使用 A / B / C … 短标签,并把相同正文放进对应 description;正确标签设为 `mastery_quiz` 的 `expected_answer`。绝不能只把 A/B/C/D 裸标签传给 `mastery_quiz.options`。如果 `mastery_status.next.pending_question` 存在,必须原样复用其中的题号、题面和选项标签/正文,绝不重新生成或调整顺序。简答题用 `ask_user` 的自由输入。收到作答后用 `mastery_grade` 批改,并传入持久化的 `question_id`。在 `mastery_grade` 返回 `mastered: true` 之前,持续打磨同一个知识点。- concept / design 类:让学习者用自己的话解释该概念,你来判断,并用 `mastery_assess` 记录结果(只有解释确实体现理解时才 `passed: true`)。- `review`:有到期的间隔复习项——再考一次以巩固。- `complete`:祝贺学习者并总结其已掌握的内容。diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.pyindex 023a96f38..f8440323a 100644--- a/deeptutor/capabilities/mastery/tools.py+++ b/deeptutor/capabilities/mastery/tools.py@@ -26,6 +26,7 @@ from deeptutor.capabilities.mastery.choices import (parse_options,recover_options_from_turn,resolve_answer,+ resolve_choice_submission,)from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult@@ -41,6 +42,7 @@ from deeptutor.learning.models import (LearningModule,PendingQuestion,)+from deeptutor.learning.pending import public_pending_questionfrom deeptutor.learning.policy import (QUALITATIVE_TYPES,display_mastery,@@ -97,13 +99,73 @@ def _question_bank_type(question_type: str) -> str:return "short_answer"+def _normalize_quiz_contract(+ raw_question_type: Any,+ raw_options: Any,+ expected_answer: str,+) -> tuple[str, list[str], str]:+ """Validate and canonicalise the persisted quiz shape.++ A missing question type is inferred from the actual payload: options mean+ ``choice`` and no options mean ``short``. Once a caller explicitly chooses+ ``short`` or ``open``, options are rejected instead of being silently+ discarded. Choice answers are stored as labels so the interactive card and+ deterministic grader always compare the same representation.+ """+ if raw_options is None:+ options: list[str] = []+ elif not isinstance(raw_options, list):+ raise ValueError("mastery_quiz.options must be an array of non-empty strings.")+ elif any(not isinstance(option, str) or not option.strip() for option in raw_options):+ raise ValueError("mastery_quiz.options must contain only non-empty strings.")+ else:+ options = [option.strip() for option in raw_options]++ supplied_type = str(raw_question_type or "").strip().lower()+ if supplied_type and supplied_type not in _QUESTION_TYPES:+ allowed = ", ".join(_QUESTION_TYPES)+ raise ValueError(f"mastery_quiz.question_type must be one of: {allowed}.")++ question_type = supplied_type or ("choice" if options else "short")+ if question_type != "choice":+ if options:+ raise ValueError(+ f"mastery_quiz.options cannot be used with question_type={question_type!r}; "+ "omit options or use question_type='choice'."+ )+ return question_type, [], expected_answer++ choice_options = parse_options(options)+ if len(choice_options) != len(options):+ raise ValueError(+ "Choice option labels must be unique; retry mastery_quiz with one full body "+ "for each label."+ )+ if not has_option_bodies(choice_options):+ raise ValueError(+ "Choice questions need full option bodies in mastery_quiz.options "+ "(for example ['A: first answer', 'B: second answer']), not only "+ "the labels A/B/C/D. Retry mastery_quiz with the exact option "+ "descriptions you will show through ask_user."+ )++ resolved_expected = resolve_answer(expected_answer, choice_options)+ if not resolved_expected:+ raise ValueError(+ "Choice expected_answer must be an option label such as A/B/C/D, "+ "or uniquely match one full option body. Retry mastery_quiz with "+ "the correct label."+ )+ return question_type, format_options(choice_options), resolved_expected++async def _resolve_pending_choice(pending: PendingQuestion, turn_id: str) -> tuple[dict[str, str], str]:"""Resolve a pending choice question's ``({label: body}, expected_label)``.- Re-parses the bodies stored at registration; for legacy paths that stored- only ``["A", "B", ...]`` it recovers the real bodies from the turn's+ The persisted options are authoritative. For legacy paths that stored only+ ``["A", "B", ...]`` it recovers the real bodies from the turn's``ask_user`` event. The expected answer is normalised to a stable labelwhen it resolves, else left as registered."""@@ -252,7 +314,8 @@ class MasteryQuizTool(BaseTool):type="string",description=("'choice' (exact match), 'short' (exact / fuzzy for ≤30 "- "chars), or 'open' (keyword overlap). Default 'short'."+ "chars), or 'open' (keyword overlap). When omitted, options "+ "infer 'choice'; otherwise the default is 'short'."),required=False,default="short",@@ -262,10 +325,12 @@ class MasteryQuizTool(BaseTool):name="options",type="array",description=(- "For question_type='choice', every full option in label order, "+ "Every full choice option in label order; providing options "+ "infers question_type='choice' when the type is omitted. ""for example ['A: first answer', 'B: second answer']. Never "- "pass bare labels such as ['A', 'B', 'C', 'D']. Use the same "- "bodies as the ask_user option descriptions."+ "pass options for 'short'/'open' or bare labels such as "+ "['A', 'B', 'C', 'D']. Use the same bodies as the ask_user "+ "option descriptions."),required=False,items={"type": "string"},@@ -285,34 +350,12 @@ class MasteryQuizTool(BaseTool):content="mastery_quiz needs knowledge_point_id, question, and expected_answer.",success=False,)- q_type = str(kwargs.get("question_type") or "short").strip().lower()- if q_type not in _QUESTION_TYPES:- q_type = "short"- options = [str(o) for o in (kwargs.get("options") or []) if str(o).strip()]- if q_type == "choice":- choice_options = parse_options(options)- if not has_option_bodies(choice_options):- return ToolResult(- content=(- "Choice questions need full option bodies in mastery_quiz.options "- "(for example ['A: first answer', 'B: second answer']), not only "- "the labels A/B/C/D. Retry mastery_quiz with the exact option "- "descriptions you will show through ask_user."- ),- success=False,- )- resolved_expected = resolve_answer(expected, choice_options)- if not resolved_expected:- return ToolResult(- content=(- "Choice expected_answer must be an option label such as A/B/C/D, "- "or uniquely match one full option body. Retry mastery_quiz with "- "the correct label."- ),- success=False,- )- expected = resolved_expected- options = format_options(choice_options)+ try:+ q_type, options, expected = _normalize_quiz_contract(+ kwargs.get("question_type"), kwargs.get("options"), expected+ )+ except ValueError as exc:+ return ToolResult(content=str(exc), success=False)service = _new_service()progress = service.get_or_create(path_id)@@ -332,17 +375,21 @@ class MasteryQuizTool(BaseTool):options=options,)service.set_pending_question(progress, pending)+ public_question = public_pending_question(pending)return _json_result({"status": "registered","knowledge_point_id": kp_id,+ "question_id": pending.question_id,+ "question_type": pending.question_type,"question": question,"options": options,+ "pending_question": public_question.to_dict(),+ "ask_user": {"questions": [public_question.to_ask_user_dict()]},"instruction": (- "Present this question with the ask_user tool (use its options "- "for multiple choice; the option labels must match the "- "expected_answer you registered), then call mastery_grade with "- "the learner's answer."+ "Pass ask_user.questions through unchanged: its question id and "+ "option labels are bound to the persisted question. Then call "+ "mastery_grade with the learner's answer and this question_id."),},meta_key="mastery_quiz",@@ -368,6 +415,15 @@ class MasteryGradeTool(BaseTool):type="string",description="The learner's answer, verbatim.",),+ ToolParameter(+ name="question_id",+ type="string",+ description=(+ "Stable question_id from mastery_quiz or mastery_status. "+ "Optional only for legacy pending questions."+ ),+ required=False,+ ),],)@@ -387,19 +443,30 @@ class MasteryGradeTool(BaseTool):content="No question is awaiting an answer. Pose one with mastery_quiz first.",success=False,)+ submitted_question_id = str(kwargs.get("question_id") or "").strip()+ if submitted_question_id and submitted_question_id != pending.question_id:+ return ToolResult(+ content=(+ f"Question {submitted_question_id!r} is no longer pending; "+ f"call mastery_status and answer {pending.question_id!r}."+ ),+ success=False,+ )choice_options: dict[str, str] = {}expected_answer = pending.expected_answer+ answer_for_grading = answerif pending.question_type == "choice":choice_options, expected_answer = await _resolve_pending_choice(pending, _resolve_turn_id(kwargs))+ answer_for_grading = resolve_choice_submission(answer, choice_options) or answeris_correct = service.grade_and_record(progress,question_id=pending.question_id,knowledge_point_id=pending.knowledge_point_id,module_id=pending.module_id,- user_answer=answer,+ user_answer=answer_for_grading,expected_answer=expected_answer,question_type=pending.question_type,scheduler=scheduler,diff --git a/deeptutor/knowledge/kb_types.py b/deeptutor/knowledge/kb_types.pyindex fe18bf075..937e8f0c8 100644--- a/deeptutor/knowledge/kb_types.py+++ b/deeptutor/knowledge/kb_types.py@@ -92,6 +92,16 @@ def is_connected_kb(entry: Any) -> bool:return isinstance(entry, dict) and entry.get("type") in CONNECTED_KB_TYPES+def supports_local_raw_files(entry: Any) -> bool:+ """Whether the KB owns a DeepTutor-managed local ``raw/`` directory.++ Connected KBs are pointers to external resources. Some point at a local+ folder and others at a remote service, but neither kind participates in+ DeepTutor's raw-file upload and management API.+ """+ return isinstance(entry, dict) and not is_connected_kb(entry)++def external_root_of(entry: Any) -> str | None:"""Absolute path a connected KB points at, or ``None`` for ordinary KBs.@@ -111,5 +121,6 @@ __all__ = ["IMA_KB_TYPE","CONNECTED_KB_TYPES","is_connected_kb",+ "supports_local_raw_files","external_root_of",]diff --git a/deeptutor/learning/pending.py b/deeptutor/learning/pending.pynew file mode 100644index 000000000..0c22547fb--- /dev/null+++ b/deeptutor/learning/pending.py@@ -0,0 +1,166 @@+"""Public, stable views of pending mastery questions.++The persisted :class:`~deeptutor.learning.models.PendingQuestion` contains the+server-only expected answer. This module projects it into the smaller contract+that is safe to give to the tutor model and interactive clients. It also owns+the pure multiple-choice translations shared by registration, presentation,+and grading, so all three boundaries use the same immutable label/body map.+"""++from __future__ import annotations++from dataclasses import dataclass+import re+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from deeptutor.learning.models import PendingQuestion+++OPTION_PREFIX_RE = re.compile(r"^\s*([A-Z])\s*[.::、))-]\s*(.+)$", re.IGNORECASE)+++def parse_options(options: list[str]) -> dict[str, str]:+ """Map persisted option strings to their stable ``{label: body}`` form."""+ result: dict[str, str] = {}+ for idx, raw in enumerate(options):+ text = str(raw or "").strip()+ if not text:+ continue+ match = OPTION_PREFIX_RE.match(text)+ if match:+ result[match.group(1).upper()] = match.group(2).strip()+ elif len(text) == 1 and text.isalnum():+ result[text.upper()] = text+ else:+ result[chr(ord("A") + idx) if idx < 26 else str(idx + 1)] = text+ return result+++def has_option_bodies(options: dict[str, str]) -> bool:+ """Whether a choice map holds real answer text, not only A/B/C labels."""+ return len(options) >= 2 and all(+ value.strip() and value.strip().upper() != key.upper() for key, value in options.items()+ )+++def format_options(options: dict[str, str]) -> list[str]:+ """Render a choice map as canonical, persistable ``"label: body"`` strings."""+ return [f"{label}: {body}" for label, body in options.items()]+++def resolve_answer(answer: str, options: dict[str, str]) -> str:+ """Resolve a label, labelled option, or unique body to its stable label."""+ candidate = str(answer or "").strip()+ if not candidate:+ return ""++ key = candidate.upper()+ if key in options:+ return key++ prefix_match = OPTION_PREFIX_RE.match(candidate)+ if prefix_match and prefix_match.group(1).upper() in options:+ return prefix_match.group(1).upper()++ needle = candidate.casefold()+ exact = [label for label, text in options.items() if text.casefold() == needle]+ if len(exact) == 1:+ return exact[0]+ contained = [label for label, text in options.items() if needle in text.casefold()]+ return contained[0] if len(contained) == 1 else ""+++def resolve_choice_submission(answer: str, options: dict[str, str]) -> str:+ """Resolve a learner submission by label or one exact, unique option body.++ Registration remains forgiving of a model-supplied body fragment through+ :func:`resolve_answer`; grading is intentionally stricter so a partial word+ cannot accidentally count as a correct learner answer.+ """+ candidate = str(answer or "").strip()+ if not candidate:+ return ""+ key = candidate.upper()+ if key in options:+ return key+ prefix_match = OPTION_PREFIX_RE.match(candidate)+ if prefix_match and prefix_match.group(1).upper() in options:+ return prefix_match.group(1).upper()+ needle = candidate.casefold()+ exact = [label for label, body in options.items() if body.casefold() == needle]+ return exact[0] if len(exact) == 1 else ""+++@dataclass(frozen=True, slots=True)+class PublicPendingOption:+ """One learner-visible option; ``id`` and ``label`` are intentionally stable."""++ id: str+ label: str+ body: str++ def to_dict(self) -> dict[str, str]:+ return {"id": self.id, "label": self.label, "body": self.body}++ def to_ask_user_dict(self) -> dict[str, str]:+ return {"label": self.label, "description": self.body}+++@dataclass(frozen=True, slots=True)+class PublicPendingQuestion:+ """Learner-visible pending state, deliberately excluding the answer key."""++ question_id: str+ prompt: str+ question_type: str+ options: tuple[PublicPendingOption, ...] = ()++ def to_dict(self) -> dict[str, Any]:+ return {+ "question_id": self.question_id,+ "prompt": self.prompt,+ "question_type": self.question_type,+ "options": [option.to_dict() for option in self.options],+ }++ def to_ask_user_dict(self) -> dict[str, Any]:+ return {+ "id": self.question_id,+ "prompt": self.prompt,+ "options": [option.to_ask_user_dict() for option in self.options],+ "multi_select": False,+ "allow_free_text": True,+ }+++def public_pending_question(pending: PendingQuestion) -> PublicPendingQuestion:+ """Project persisted pending state without exposing ``expected_answer``."""+ choice_map = parse_options(list(pending.options or []))+ options = (+ tuple(+ PublicPendingOption(id=label, label=label, body=body)+ for label, body in choice_map.items()+ )+ if pending.question_type == "choice"+ else ()+ )+ return PublicPendingQuestion(+ question_id=pending.question_id,+ prompt=pending.prompt,+ question_type=pending.question_type,+ options=options,+ )+++__all__ = [+ "OPTION_PREFIX_RE",+ "PublicPendingOption",+ "PublicPendingQuestion",+ "format_options",+ "has_option_bodies",+ "parse_options",+ "public_pending_question",+ "resolve_answer",+ "resolve_choice_submission",+]diff --git a/deeptutor/learning/policy.py b/deeptutor/learning/policy.pyindex b481b7479..9bc2943f1 100644--- a/deeptutor/learning/policy.py+++ b/deeptutor/learning/policy.py@@ -27,6 +27,7 @@ from deeptutor.learning.models import (LearningProgress,ReviewTask,)+from deeptutor.learning.pending import PublicPendingQuestion, public_pending_question# Quantitative gate for objective knowledge types: the learner must reach this# mastery (recency-weighted accuracy; see ``mastery.compute_mastery``) before@@ -122,6 +123,7 @@ class NextStep:threshold: float = 0.0reason: str = ""pending_prompt: str = ""+ pending_question: PublicPendingQuestion | None = Nonedef to_dict(self) -> dict:return {@@ -137,6 +139,9 @@ class NextStep:"threshold": round(self.threshold, 3),"reason": self.reason,"pending_prompt": self.pending_prompt,+ "pending_question": (+ self.pending_question.to_dict() if self.pending_question is not None else None+ ),}@@ -180,6 +185,7 @@ def next_objective(progress: LearningProgress, *, now: float | None = None) -> Nthreshold=gate_threshold(kp.type) if kp else 0.0,reason="A posed question is awaiting the learner's answer; grade it with mastery_grade.",pending_prompt=pending.prompt,+ pending_question=public_pending_question(pending),)due = due_reviews(progress, now=now)diff --git a/deeptutor/learning/tests/test_mastery_choices.py b/deeptutor/learning/tests/test_mastery_choices.pyindex b5064e5d9..fda8e3b09 100644--- a/deeptutor/learning/tests/test_mastery_choices.py+++ b/deeptutor/learning/tests/test_mastery_choices.py@@ -15,6 +15,7 @@ from deeptutor.capabilities.mastery.choices import (parse_options,recover_options_from_turn,resolve_answer,+ resolve_choice_submission,)# ── parse_options ────────────────────────────────────────────────────────────@@ -111,6 +112,13 @@ def test_resolve_answer_blank_when_empty():assert resolve_answer("", {"A": "x", "B": "y"}) == ""+def test_resolve_choice_submission_accepts_label_or_exact_body_only():+ options = {"A": "Step 2", "B": "Step 6"}+ assert resolve_choice_submission("B", options) == "B"+ assert resolve_choice_submission("Step 6", options) == "B"+ assert resolve_choice_submission("Step", options) == ""++# ── recover_options_from_turn ────────────────────────────────────────────────diff --git a/deeptutor/learning/tests/test_mastery_tools.py b/deeptutor/learning/tests/test_mastery_tools.pyindex ec3aea75e..730baa031 100644--- a/deeptutor/learning/tests/test_mastery_tools.py+++ b/deeptutor/learning/tests/test_mastery_tools.py@@ -9,6 +9,7 @@ import jsonimport pytest+from deeptutor.learning.models import PendingQuestionfrom deeptutor.learning.storage import LearningStorefrom deeptutor.services.session.sqlite_store import SQLiteSessionStorefrom deeptutor.tools.mastery_tool import (@@ -244,6 +245,129 @@ async def test_choice_quiz_rejects_bare_option_labels(path_id):assert "full option bodies" in result.content+ ("type_kwargs", "expected_answer"),+ [+ ({}, "B"),+ ({"question_type": ""}, "blue"),+ ],+)+async def test_quiz_infers_choice_and_normalizes_expected_answer(+ path_id, type_kwargs, expected_answer+):+ await _build_basic(path_id)+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)+ kp_id = status["next"]["knowledge_point_id"]++ result = await MasteryQuizTool().execute(+ _mastery_path_id=path_id,+ knowledge_point_id=kp_id,+ question="Pick a colour",+ expected_answer=expected_answer,+ options=["A: red", "B: blue"],+ **type_kwargs,+ )++ assert result.success is True+ pending = LearningStore().load(path_id).pending_question+ assert pending is not None+ assert pending.question_type == "choice"+ assert pending.expected_answer == "B"+ assert pending.options == ["A: red", "B: blue"]++[email protected]("question_type", ["short", "open"])+async def test_explicit_non_choice_without_options_is_unchanged(path_id, question_type):+ await _build_basic(path_id)+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)+ kp_id = status["next"]["knowledge_point_id"]++ result = await MasteryQuizTool().execute(+ _mastery_path_id=path_id,+ knowledge_point_id=kp_id,+ question="Explain it",+ expected_answer="stored as written",+ question_type=question_type,+ options=[],+ )++ assert result.success is True+ pending = LearningStore().load(path_id).pending_question+ assert pending is not None+ assert pending.question_type == question_type+ assert pending.expected_answer == "stored as written"+ assert pending.options == []++[email protected]("question_type", ["short", "open"])+async def test_explicit_non_choice_rejects_options(path_id, question_type):+ await _build_basic(path_id)+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)+ kp_id = status["next"]["knowledge_point_id"]++ result = await MasteryQuizTool().execute(+ _mastery_path_id=path_id,+ knowledge_point_id=kp_id,+ question="Explain it",+ expected_answer="answer",+ question_type=question_type,+ options=["A: first", "B: second"],+ )++ assert result.success is False+ assert "cannot be used" in result.content+ assert LearningStore().load(path_id).pending_question is None+++ ("options", "error"),+ [+ ("A: first, B: second", "must be an array"),+ (["A: first", "A: second", "B: third"], "labels must be unique"),+ (["A: first", ""], "non-empty strings"),+ ],+)+async def test_choice_quiz_rejects_malformed_options(path_id, options, error):+ await _build_basic(path_id)+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)+ kp_id = status["next"]["knowledge_point_id"]++ result = await MasteryQuizTool().execute(+ _mastery_path_id=path_id,+ knowledge_point_id=kp_id,+ question="Pick one",+ expected_answer="A",+ question_type="choice",+ options=options,+ )++ assert result.success is False+ assert error in result.content+++async def test_choice_quiz_requires_options_even_when_type_is_explicit(path_id):+ await _build_basic(path_id)+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)+ kp_id = status["next"]["knowledge_point_id"]++ result = await MasteryQuizTool().execute(+ _mastery_path_id=path_id,+ knowledge_point_id=kp_id,+ question="Pick one",+ expected_answer="A",+ question_type="choice",+ options=[],+ )++ assert result.success is False+ assert "full option bodies" in result.content++@pytest.mark.asyncioasync def test_choice_quiz_preserves_bodies_and_normalizes_answer(path_id, session_store):session = await session_store.create_session(title="Choice Mastery")@@ -291,6 +415,127 @@ async def test_choice_quiz_preserves_bodies_and_normalizes_answer(path_id, sessiassert entry["is_correct"] is True+async def test_pending_choice_status_reuses_public_contract_without_answer(path_id):+ await _build_basic(path_id)+ initial = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)+ kp_id = initial["next"]["knowledge_point_id"]++ registered = json.loads(+ (+ await MasteryQuizTool().execute(+ _mastery_path_id=path_id,+ knowledge_point_id=kp_id,+ question="Pick a colour",+ expected_answer="blue",+ question_type="choice",+ options=["A: red", "B: blue"],+ )+ ).content+ )+ status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)++ pending = status["next"]["pending_question"]+ assert pending == registered["pending_question"]+ assert registered["ask_user"]["questions"][0] == {+ "id": pending["question_id"],+ "prompt": "Pick a colour",+ "options": [+ {"label": "A", "description": "red"},+ {"label": "B", "description": "blue"},+ ],+ "multi_select": False,+ "allow_free_text": True,+ }+ assert "expected_answer" not in registered+ assert "expected_answer" not in pending+++async def test_choice_grade_accepts_unique_persisted_body(path_id):+ await _build_basic(path_id)+ initial = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)+ kp_id = initial["next"]["knowledge_point_id"]+ quiz = json.loads(+ (+ await MasteryQuizTool().execute(+ _mastery_path_id=path_id,+ knowledge_point_id=kp_id,+ question="Pick a colour",+ expected_answer="B",+ question_type="choice",+ options=["A: red", "B: blue"],+ )+ ).content+ )++ grade = json.loads(+ (+ await MasteryGradeTool().execute(+ _mastery_path_id=path_id,+ question_id=quiz["question_id"],+ answer="blue",+ )+ ).content+ )++ assert grade["is_correct"] is True+++async def test_choice_grade_rejects_stale_question_id_without_clearing_pending(path_id):+ await _build_basic(path_id)+ initial = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)+ kp_id = initial["next"]["knowledge_point_id"]+ await MasteryQuizTool().execute(+ _mastery_path_id=path_id,+ knowledge_point_id=kp_id,+ question="Pick a colour",+ expected_answer="B",+ question_type="choice",+ options=["A: red", "B: blue"],+ )++ grade = await MasteryGradeTool().execute(+ _mastery_path_id=path_id,+ question_id="stale-question",+ answer="B",+ )++ assert grade.success is False+ assert LearningStore().load(path_id).pending_question is not None+++async def test_choice_grade_keeps_legacy_bare_label_pending_compatible(path_id):+ await _build_basic(path_id)+ progress = LearningStore().load(path_id)+ assert progress is not None+ kp_id = progress.modules[0].knowledge_points[0].id+ progress.pending_question = PendingQuestion(+ question_id="legacy-question",+ knowledge_point_id=kp_id,+ module_id=progress.modules[0].id,+ prompt="Legacy choice",+ question_type="choice",+ expected_answer="B",+ options=["A", "B"],+ )+ LearningStore().save(progress)++ grade = json.loads(+ (+ await MasteryGradeTool().execute(+ _mastery_path_id=path_id,+ question_id="legacy-question",+ answer="B",+ )+ ).content+ )++ assert grade["is_correct"] is True++# ── assess: the qualitative gate ─────────────────────────────────────────────diff --git a/deeptutor/learning/tests/test_models.py b/deeptutor/learning/tests/test_models.pyindex 3ed5ac357..b16799640 100644--- a/deeptutor/learning/tests/test_models.py+++ b/deeptutor/learning/tests/test_models.py@@ -9,6 +9,7 @@ from deeptutor.learning.models import (LearningModule,LearningProgress,LearningStage,+ PendingQuestion,QuizAttempt,RepetitionState,RetryAttempt,@@ -255,6 +256,26 @@ class TestSerializationRoundtrip:assert lp2.stage_failure_counts["explain"] == 1assert lp2.current_stage == LearningStage.DIAGNOSTIC+ def test_pending_choice_roundtrip_preserves_question_and_option_ids(self):+ lp = LearningProgress(+ book_id="b1",+ pending_question=PendingQuestion(+ question_id="question-1",+ knowledge_point_id="kp1",+ prompt="Pick one",+ question_type="choice",+ expected_answer="B",+ options=["A: first", "B: second"],+ ),+ )++ restored = LearningProgress.model_validate(lp.model_dump(mode="json"))++ assert restored.pending_question is not None+ assert restored.pending_question.question_id == "question-1"+ assert restored.pending_question.options == ["A: first", "B: second"]+ assert restored.pending_question.expected_answer == "B"+def test_legacy_progress_roundtrip(self):# A payload persisted by the old engine (retired stage + dropped fields)# must still deserialize, mapping the stage and ignoring removed keys.diff --git a/deeptutor/learning/tests/test_policy.py b/deeptutor/learning/tests/test_policy.pyindex c484ab226..ce9f0296f 100644--- a/deeptutor/learning/tests/test_policy.py+++ b/deeptutor/learning/tests/test_policy.py@@ -123,6 +123,54 @@ def test_next_objective_pending_question_takes_precedence():assert step.pending_prompt == "?"+def test_pending_choice_context_is_stable_and_does_not_expose_answer():+ kp = _kp("kp1", KnowledgeType.MEMORY)+ progress = _progress(kp)+ progress.pending_question = PendingQuestion(+ question_id="question-stable-1",+ knowledge_point_id="kp1",+ prompt="Pick the blue option",+ question_type="choice",+ expected_answer="B",+ options=["A: red", "B: blue"],+ )++ payload = policy.next_objective(progress).to_dict()++ assert payload["pending_prompt"] == "Pick the blue option" # legacy field+ assert payload["pending_question"] == {+ "question_id": "question-stable-1",+ "prompt": "Pick the blue option",+ "question_type": "choice",+ "options": [+ {"id": "A", "label": "A", "body": "red"},+ {"id": "B", "label": "B", "body": "blue"},+ ],+ }+ assert "expected_answer" not in payload["pending_question"]+++def test_pending_non_choice_context_keeps_type_without_options_or_answer():+ kp = _kp("kp1", KnowledgeType.PROCEDURE)+ progress = _progress(kp)+ progress.pending_question = PendingQuestion(+ question_id="short-1",+ knowledge_point_id="kp1",+ prompt="Name the invariant",+ question_type="short",+ expected_answer="server secret",+ )++ pending = policy.next_objective(progress).to_dict()["pending_question"]++ assert pending == {+ "question_id": "short-1",+ "prompt": "Name the invariant",+ "question_type": "short",+ "options": [],+ }++def test_next_objective_due_review_beats_new_ground():kp1, kp2 = _kp("kp1", KnowledgeType.MEMORY), _kp("kp2", KnowledgeType.MEMORY)progress = _progress(kp1, kp2)diff --git a/deeptutor/runtime/launcher.py b/deeptutor/runtime/launcher.pyindex 9f055ce41..4ac63170f 100644--- a/deeptutor/runtime/launcher.py+++ b/deeptutor/runtime/launcher.py@@ -22,6 +22,7 @@ from urllib import request as urlrequestfrom deeptutor.runtime.banner import labels_for, print_banner, resolve_languagefrom deeptutor.runtime.home import DEEPTUTOR_HOME_ENV, PACKAGE_ROOT, get_runtime_home+from deeptutor.runtime.memory_probe import SUPERVISOR_PID_ENVBACKEND_READY_TIMEOUT = 60FRONTEND_READY_TIMEOUT = 120@@ -1038,6 +1039,11 @@ def start(home: str | Path | None = None, *, dev: bool = False) -> None:common_env["DEEPTUTOR_AUTH_ENABLED"] = "true" if auth_enabled else "false"common_env["PYTHONUNBUFFERED"] = "1"common_env["PYTHONIOENCODING"] = "utf-8:replace"+ # Anchor for deeptutor.runtime.memory_probe: the backend and the frontend+ # are siblings under this process, so only the supervisor's pid identifies+ # the tree that is "DeepTutor". Without it the probe can only measure the+ # backend itself.+ common_env[SUPERVISOR_PID_ENV] = str(os.getpid())_apply_single_user_allocator_env(common_env)if frontend.kind == "source-production":common_env["DEEPTUTOR_NEXT_DIST_DIR"] = SOURCE_PRODUCTION_DIST_DIRdiff --git a/deeptutor/runtime/memory_probe.py b/deeptutor/runtime/memory_probe.pynew file mode 100644index 000000000..527f5c613--- /dev/null+++ b/deeptutor/runtime/memory_probe.py@@ -0,0 +1,343 @@+"""Resident-memory snapshot of the running DeepTutor process tree.++The counterpart to :mod:`deeptutor.runtime.memory_reclaim`: that module *acts*+on memory (cycle collection, ``malloc_trim``), this one *observes* it so the+settings status strip can show what the app actually costs.++Two things make "how much memory does DeepTutor use" more than one ``getrusage``+call:++* The backend is only one of the processes. ``deeptutor.runtime.launcher``+ spawns the Next.js frontend as a *sibling* (see ``_spawn``), and capabilities+ spawn sandboxes and subagent CLIs below it. Answering honestly means walking+ the supervisor's process tree, which is why the launcher stamps its own pid+ into :data:`SUPERVISOR_PID_ENV` — without that anchor a bare+ ``uvicorn deeptutor.api.main:app`` run would climb into the developer's shell+ and count unrelated jobs.+* Inside a container the host's total RAM is the wrong denominator. cgroup's+ own accounting is what the OOM killer reads, so it wins when present.++Summing per-process RSS double-counts pages shared through ``fork``, so the+total is an upper bound. The cheaper, exact-enough alternative (USS) costs a+page-table walk per process, which is too much for a strip that polls.+"""++from __future__ import annotations++from dataclasses import dataclass+import os+from pathlib import Path+import sys+from typing import Any++# Stamped by the launcher onto every child's environment so the backend can+# find the root of the DeepTutor process tree it belongs to.+SUPERVISOR_PID_ENV = "DEEPTUTOR_SUPERVISOR_PID"++_CGROUP_V2_CURRENT = Path("/sys/fs/cgroup/memory.current")+_CGROUP_V2_MAX = Path("/sys/fs/cgroup/memory.max")+_CGROUP_V1_USAGE = Path("/sys/fs/cgroup/memory/memory.usage_in_bytes")+_CGROUP_V1_LIMIT = Path("/sys/fs/cgroup/memory/memory.limit_in_bytes")++# cgroup v1 spells "no limit" as a sentinel near the top of the address space+# rather than as a word, and the exact value varies with page size.+_CGROUP_V1_UNLIMITED = 1 << 62++# Enough detail to explain a large total without turning the tooltip into a+# process list; the rest is folded into one "other" row by the router.+MAX_REPORTED_PROCESSES = 12+++@dataclass(frozen=True, slots=True)+class ProcessMemory:+ """One process in the DeepTutor tree."""++ pid: int+ label: str+ rss_bytes: int+++@dataclass(frozen=True, slots=True)+class MemorySnapshot:+ """What the app costs right now, and what it is allowed to cost."""++ processes: tuple[ProcessMemory, ...]+ total_rss_bytes: int+ limit_bytes: int | None+ available_bytes: int | None+ # "cgroup" when a container limit is in force, "host" for physical RAM,+ # "unknown" when neither could be read.+ limit_source: str+ # True when only this process could be measured, so the total understates+ # the tree. The UI labels the number differently rather than hiding it.+ partial: bool++ @property+ def usage_ratio(self) -> float | None:+ if not self.limit_bytes:+ return None+ return self.total_rss_bytes / self.limit_bytes+++def _load_psutil() -> Any | None:+ """Import psutil lazily; it is a soft dependency (see ``_scan_proc``)."""+ try:+ import psutil+ except ImportError:+ return None+ return psutil+++def _read_int(path: Path) -> int | None:+ try:+ return int(path.read_text(encoding="utf-8").strip())+ except (OSError, ValueError):+ return None+++def _supervisor_pid(pid_exists: Any) -> int | None:+ """Resolve the launcher's pid from the environment, if it is still alive."""+ raw = os.environ.get(SUPERVISOR_PID_ENV, "").strip()+ if not raw.isdigit():+ return None+ pid = int(raw)+ if pid <= 0 or not pid_exists(pid):+ return None+ return pid+++def _classify(pid: int, name: str, cmdline: str, root_pid: int | None = None) -> str:+ """Name a process by the role it plays, never by its full command line.++ Command lines can carry credentials passed as flags, and this snapshot is+ served over HTTP — so classification reads the command line but only ever+ emits one of these fixed role labels or a bare executable name.++ The two roles we know as *facts* (this process, and the tree's root) are+ decided by pid. Guessing them from the command line was wrong in practice:+ the supervisor runs as a bare ``deeptutor`` console script with nothing in+ its argv to match on.+ """+ if pid == os.getpid():+ return "backend"+ if root_pid is not None and pid == root_pid:+ return "supervisor"+ lowered = f"{name} {cmdline}".lower()+ if "next" in lowered or "node" in lowered:+ return "web"+ if "uvicorn" in lowered or "deeptutor.api" in lowered:+ return "backend"+ if "pocketbase" in lowered:+ return "pocketbase"+ if "sandbox" in lowered:+ return "sandbox"+ return (name or "process").split(os.sep)[-1][:32] or "process"+++def _scan_psutil(psutil: Any) -> tuple[list[ProcessMemory], bool]:+ """Walk the supervisor's tree with psutil (the cross-platform path)."""+ root_pid = _supervisor_pid(psutil.pid_exists)+ partial = root_pid is None+ try:+ root = psutil.Process(root_pid if root_pid is not None else os.getpid())+ candidates = [root, *root.children(recursive=True)]+ except psutil.Error:+ return [], True++ found: list[ProcessMemory] = []+ for proc in candidates:+ try:+ with proc.oneshot():+ rss = int(proc.memory_info().rss)+ name = proc.name() or ""+ try:+ cmdline = " ".join(proc.cmdline()[:3])+ except (psutil.AccessDenied, psutil.Error):+ cmdline = ""+ found.append(+ ProcessMemory(+ pid=proc.pid,+ label=_classify(proc.pid, name, cmdline, root_pid),+ rss_bytes=rss,+ )+ )+ except psutil.Error:+ # The tree is live; a child exiting mid-walk is expected, not an error.+ continue+ if not any(p.pid == os.getpid() for p in found):+ # We were not under the anchor after all (stale env var, re-parented+ # process). Reporting a tree that excludes the backend would be wrong.+ return _scan_psutil_self(psutil)+ return found, partial+++def _scan_psutil_self(psutil: Any) -> tuple[list[ProcessMemory], bool]:+ try:+ proc = psutil.Process()+ return [+ ProcessMemory(pid=proc.pid, label="backend", rss_bytes=int(proc.memory_info().rss))+ ], True+ except psutil.Error:+ return [], True+++def _proc_entry(pid: int) -> tuple[int, str, str] | None:+ """Read ``(ppid, comm, cmdline_head)`` for one pid from /proc."""+ try:+ stat = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8", errors="replace")+ except OSError:+ return None+ # comm is parenthesised and may itself contain spaces/parens, so split on+ # the LAST ')' rather than tokenising the whole line.+ open_paren = stat.find("(")+ close_paren = stat.rfind(")")+ if open_paren < 0 or close_paren < open_paren:+ return None+ comm = stat[open_paren + 1 : close_paren]+ rest = stat[close_paren + 2 :].split()+ if len(rest) < 2:+ return None+ try:+ ppid = int(rest[1])+ except ValueError:+ return None+ try:+ cmdline = (+ Path(f"/proc/{pid}/cmdline")+ .read_bytes()+ .replace(b"\0", b" ")+ .decode("utf-8", errors="replace")+ )+ except OSError:+ cmdline = ""+ return ppid, comm, cmdline[:200]+++def _proc_rss(pid: int) -> int | None:+ try:+ fields = Path(f"/proc/{pid}/statm").read_text(encoding="utf-8").split()+ except OSError:+ return None+ if len(fields) < 2:+ return None+ try:+ return int(fields[1]) * os.sysconf("SC_PAGE_SIZE")+ except (ValueError, OSError):+ return None+++def _scan_proc() -> tuple[list[ProcessMemory], bool]:+ """psutil-free fallback for Linux — the platform DeepTutor ships in Docker on."""+ children: dict[int, list[int]] = {}+ meta: dict[int, tuple[str, str]] = {}+ for entry in Path("/proc").iterdir():+ if not entry.name.isdigit():+ continue+ parsed = _proc_entry(int(entry.name))+ if parsed is None:+ continue+ ppid, comm, cmdline = parsed+ children.setdefault(ppid, []).append(int(entry.name))+ meta[int(entry.name)] = (comm, cmdline)++ root_pid = _supervisor_pid(lambda pid: pid in meta)+ partial = root_pid is None+ if root_pid is None:+ root_pid = os.getpid()++ found: list[ProcessMemory] = []+ seen: set[int] = set()+ queue = [root_pid]+ while queue:+ pid = queue.pop()+ if pid in seen:+ continue+ seen.add(pid)+ rss = _proc_rss(pid)+ if rss is not None:+ comm, cmdline = meta.get(pid, ("", ""))+ found.append(+ ProcessMemory(pid=pid, label=_classify(pid, comm, cmdline, root_pid), rss_bytes=rss)+ )+ queue.extend(children.get(pid, ()))+ return found, partial+++def _meminfo_kb(key: str) -> int | None:+ try:+ for line in Path("/proc/meminfo").read_text(encoding="utf-8").splitlines():+ if line.startswith(key):+ return int(line.split()[1]) * 1024+ except (OSError, ValueError, IndexError):+ return None+ return None+++def _cgroup_limit() -> tuple[int, int] | None:+ """Return ``(limit_bytes, current_bytes)`` when a container cap is in force."""+ limit = _read_int(_CGROUP_V2_MAX)+ current = _read_int(_CGROUP_V2_CURRENT)+ if limit is None:+ v1_limit = _read_int(_CGROUP_V1_LIMIT)+ if v1_limit is not None and v1_limit < _CGROUP_V1_UNLIMITED:+ limit = v1_limit+ current = _read_int(_CGROUP_V1_USAGE)+ if limit is None or limit <= 0 or limit >= _CGROUP_V1_UNLIMITED:+ return None+ return limit, current if current is not None else 0+++def _host_memory(psutil: Any | None) -> tuple[int | None, int | None]:+ if psutil is not None:+ try:+ vm = psutil.virtual_memory()+ return int(vm.total), int(vm.available)+ except Exception: # noqa: BLE001 - psutil raises platform-specific errors+ pass+ if sys.platform.startswith("linux"):+ return _meminfo_kb("MemTotal:"), _meminfo_kb("MemAvailable:")+ return None, None+++def capture() -> MemorySnapshot:+ """Snapshot the tree's resident memory and the ceiling it runs against."""+ psutil = _load_psutil()+ if psutil is not None:+ processes, partial = _scan_psutil(psutil)+ elif sys.platform.startswith("linux"):+ processes, partial = _scan_proc()+ else:+ processes, partial = [], True++ processes.sort(key=lambda p: p.rss_bytes, reverse=True)+ total = sum(p.rss_bytes for p in processes)++ cgroup = _cgroup_limit()+ host_total, host_available = _host_memory(psutil)+ if cgroup is not None and (host_total is None or cgroup[0] < host_total):+ limit, current = cgroup+ return MemorySnapshot(+ processes=tuple(processes),+ total_rss_bytes=total,+ limit_bytes=limit,+ available_bytes=max(limit - current, 0),+ limit_source="cgroup",+ partial=partial,+ )+ return MemorySnapshot(+ processes=tuple(processes),+ total_rss_bytes=total,+ limit_bytes=host_total,+ available_bytes=host_available,+ limit_source="host" if host_total is not None else "unknown",+ partial=partial,+ )+++__all__ = [+ "MAX_REPORTED_PROCESSES",+ "SUPERVISOR_PID_ENV",+ "MemorySnapshot",+ "ProcessMemory",+ "capture",+]diff --git a/deeptutor/services/partners/runtime.py b/deeptutor/services/partners/runtime.pyindex 861cbef93..3e7b2d406 100644--- a/deeptutor/services/partners/runtime.py+++ b/deeptutor/services/partners/runtime.py@@ -13,8 +13,8 @@ Event → IM mapping:text (the loop's RESULT is empty for an unresolved ask_user pause — thepending question IS the reply, and the user's next IM message simplystarts the next turn)-* narration rounds (``call_role=narration``) → optional ``_progress``- messages (``send_progress`` channel flag)+* trace-only narration rounds (``call_role=narration``) → optional+ ``_progress`` messages (``send_progress`` channel flag)* ``TOOL_CALL`` → optional ``_tool_hint``"""@@ -247,8 +247,10 @@ class PartnerRunner:round_buffers: dict[str, list[str]] = {}streamed_rounds: dict[str, str] = {} # call_id → accumulated streamed textended_rounds: set[str] = set()+ answer_visible_parts: list[str] = []errors: list[str] = []turn_events: list[dict[str, Any]] = []+ wants_stream = False# Turn setup (context assembly + LLM-selection resolution) runs INSIDE# the try so a setup failure folds into the error list instead of@@ -320,7 +322,15 @@ class PartnerRunner:and meta.get("call_role") == "narration"):call_id = str(meta.get("call_id") or "")- text = "".join(round_buffers.pop(call_id, [])).strip()+ raw_text = "".join(round_buffers.pop(call_id, []))+ text = raw_text.strip()+ if meta.get("answer_visible") is True:+ if raw_text:+ answer_visible_parts.append(raw_text)+ if call_id in streamed_rounds:+ ended_rounds.add(call_id)+ await self._publish_stream_end(msg, turn_id, call_id)+ continueif call_id in streamed_rounds:# Already streamed live — freeze the segment.ended_rounds.add(call_id)@@ -342,6 +352,23 @@ class PartnerRunner:if not final_text.strip():final_text = terminator_text.strip()final_text = final_text.strip()+ if answer_visible_parts and not wants_stream:+ replayed_prefix = "".join(answer_visible_parts)+ display_prefix = "\n\n".join(+ part.strip() for part in answer_visible_parts if part.strip()+ )+ # Continuation rounds return the canonical, fully joined answer in+ # RESULT so SDK and persistence consumers do not lose the prefix.+ # DSML feedback rounds return only their later finish, so prepend+ # the visible narration only when RESULT does not already contain it.+ if not final_text:+ final_text = display_prefix+ elif display_prefix and not (+ final_text.startswith(replayed_prefix)+ or final_text == display_prefix+ or final_text.startswith(f"{display_prefix}\n")+ ):+ final_text = f"{display_prefix}\n\n{final_text}"# Close any stream segments still open (the finish round, or partial# rounds after a crash) so channels can flush their edit buffers.diff --git a/deeptutor/services/path_service.py b/deeptutor/services/path_service.pyindex bd031522f..5e8302cf6 100644--- a/deeptutor/services/path_service.py+++ b/deeptutor/services/path_service.py@@ -132,7 +132,14 @@ class PathService:def get_public_outputs_root(self) -> Path:return self._user_data_dir- def is_public_output_path(self, path: str | Path) -> bool:+ def resolve_public_output_path(self, path: str | Path) -> Path | None:+ """Return a safe, public output file below this service's user root.++ Resolving and authorizing the path in one operation gives callers the+ exact canonical path they may read. In particular, callers should not+ validate against one workspace and then reconstruct the file path from+ a different root.+ """candidate = Path(path)if not candidate.is_absolute():candidate = (self.get_public_outputs_root() / candidate).resolve()@@ -143,52 +150,55 @@ class PathService:try:relative = candidate.relative_to(root)except ValueError:- return False+ return Noneif not candidate.is_file():- return False+ return Noneif candidate.suffix.lower() in self._PRIVATE_SUFFIXES:- return False+ return Noneparts = relative.partsif parts[:3] == ("workspace", "co-writer", "audio"):- return True+ return candidateif (len(parts) >= 5and parts[:3] == ("workspace", "chat", "deep_solve")and "artifacts" in parts[4:]):- return True+ return candidateif (len(parts) >= 5and parts[:3] == ("workspace", "chat", "math_animator")and "artifacts" in parts[4:]):- return True+ return candidateif len(parts) >= 5 and parts[:2] == ("workspace", "chat") and "code_runs" in parts[3:]:- return True+ return candidate# Generated media (imagegen / videogen tools write under <task>/media/).if len(parts) >= 5 and parts[:2] == ("workspace", "chat") and "media" in parts[3:]:- return True+ return candidateif len(parts) >= 5 and parts[:3] == ("workspace", "chat", "chat") and parts[4] == "exec":- return True+ return candidate# Files a CLI app produced. One directory per turn shared by every app,# not one per app, so a model can render with one and post-process with# another. Listed explicitly rather than folded into the ``exec`` branch:# what is publicly linkable is worth being able to read off this function.if len(parts) >= 5 and parts[:3] == ("workspace", "chat", "chat") and parts[4] == "cli":- return True+ return candidateif len(parts) >= 4 and parts[:3] == ("workspace", "chat", "_detached_code_execution"):- return True+ return candidate- return False+ return None++ def is_public_output_path(self, path: str | Path) -> bool:+ return self.resolve_public_output_path(path) is not Nonedef get_workspace_dir(self) -> Path:return self._user_data_dir / "workspace"diff --git a/deeptutor/services/rag/pipelines/lightrag/config.py b/deeptutor/services/rag/pipelines/lightrag/config.pyindex 294ae4647..70e77f2ae 100644--- a/deeptutor/services/rag/pipelines/lightrag/config.py+++ b/deeptutor/services/rag/pipelines/lightrag/config.py@@ -24,6 +24,10 @@ from __future__ import annotationsimport importlib.utilimport logging+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from .worker import OwnerLoopBridgelogger = logging.getLogger(__name__)@@ -82,7 +86,7 @@ def query_kwargs_from_settings() -> dict:return {}-def build_llm_model_func():+def build_llm_model_func(*, io_bridge: OwnerLoopBridge | None = None):"""Wrap DeepTutor's unified LLM callable for LightRAG.Drops LightRAG's internal kwargs while preserving explicit ``messages``.@@ -98,17 +102,20 @@ def build_llm_model_func():messages=None,**_ignored,):- return await base(- prompt or "",- system_prompt=system_prompt,- history_messages=history_messages or [],- messages=messages,- )+ async def request():+ return await base(+ prompt or "",+ system_prompt=system_prompt,+ history_messages=history_messages or [],+ messages=messages,+ )++ return await io_bridge.run(request) if io_bridge is not None else await request()return llm_model_func-def build_vision_model_func():+def build_vision_model_func(*, io_bridge: OwnerLoopBridge | None = None):"""Wrap DeepTutor's vision-capable callable for RAG-Anything's image step."""from deeptutor.services.llm import get_llm_client@@ -122,18 +129,21 @@ def build_vision_model_func():messages=None,**_ignored,):- return await base(- prompt or "",- system_prompt=system_prompt,- history_messages=history_messages or [],- image_data=image_data,- messages=messages,- )+ async def request():+ return await base(+ prompt or "",+ system_prompt=system_prompt,+ history_messages=history_messages or [],+ image_data=image_data,+ messages=messages,+ )++ return await io_bridge.run(request) if io_bridge is not None else await request()return vision_model_func-def build_embedding_func():+def build_embedding_func(*, io_bridge: OwnerLoopBridge | None = None):"""Wrap DeepTutor's embedding client in LightRAG's ``EmbeddingFunc``."""from lightrag.utils import EmbeddingFunc@@ -158,7 +168,11 @@ def build_embedding_func():"query": "search_query","document": "search_document",}.get(str(context or "").strip().lower())- vectors = await client.embed(texts, input_type=input_type)++ async def request():+ return await client.embed(texts, input_type=input_type)++ vectors = await io_bridge.run(request) if io_bridge is not None else await request()return np.asarray(vectors, dtype=np.float32)return EmbeddingFunc(diff --git a/deeptutor/services/rag/pipelines/lightrag/engine.py b/deeptutor/services/rag/pipelines/lightrag/engine.pyindex f3b08d60d..8bf237bda 100644--- a/deeptutor/services/rag/pipelines/lightrag/engine.py+++ b/deeptutor/services/rag/pipelines/lightrag/engine.py@@ -26,11 +26,12 @@ from .config import (normalize_mode,query_kwargs_from_settings,)+from .worker import OwnerLoopBridgelogger = logging.getLogger(__name__)-def build_rag(working_dir: Path) -> Any:+def build_rag(working_dir: Path, *, io_bridge: OwnerLoopBridge | None = None) -> Any:"""Construct a RAG-Anything instance rooted at ``working_dir``.Pinned to RAG-Anything's config-based constructor; this is the single spot@@ -39,11 +40,12 @@ def build_rag(working_dir: Path) -> Any:from raganything import RAGAnything, RAGAnythingConfigconfig = RAGAnythingConfig(working_dir=str(working_dir))+ adapter_kwargs = {"io_bridge": io_bridge} if io_bridge is not None else {}rag = RAGAnything(config=config,- llm_model_func=build_llm_model_func(),- vision_model_func=build_vision_model_func(),- embedding_func=build_embedding_func(),+ llm_model_func=build_llm_model_func(**adapter_kwargs),+ vision_model_func=build_vision_model_func(**adapter_kwargs),+ embedding_func=build_embedding_func(**adapter_kwargs),)# DeepTutor always feeds RAG-Anything a pre-parsed ``content_list`` (the# parse layer runs upstream via DeepTutor's own ParseService), sodiff --git a/deeptutor/services/rag/pipelines/lightrag/pipeline.py b/deeptutor/services/rag/pipelines/lightrag/pipeline.pyindex 1851bef04..bb028421c 100644--- a/deeptutor/services/rag/pipelines/lightrag/pipeline.py+++ b/deeptutor/services/rag/pipelines/lightrag/pipeline.py@@ -16,6 +16,8 @@ message when it is not installed instead of an opaque ``ImportError``.from __future__ import annotations+import asyncio+from collections.abc import Callableimport loggingfrom pathlib import Pathimport shutil@@ -31,6 +33,7 @@ from deeptutor.services.rag.kb_paths import resolve_kb_dirfrom . import config as lr_configfrom . import engine, storage+from .worker import OwnerLoopBridge, run_in_worker_looplogger = logging.getLogger(__name__)@@ -72,7 +75,14 @@ class LightRagPipeline:except Exception as exc: # pragma: no cover - best-effortself.logger.warning("Could not clean up failed version dir %s: %s", root_dir, exc)- async def _ingest(self, rag: Any, file_paths: List[str]) -> int:+ async def _ingest(+ self,+ rag: Any,+ file_paths: List[str],+ *,+ io_bridge: OwnerLoopBridge,+ progress_callback: Callable[[int, int], Any] | None = None,+ ) -> int:"""Parse each file via the shared parse layer and insert it into LightRAG.Returns the number of documents successfully inserted. Per-file failures@@ -82,7 +92,9 @@ class LightRagPipeline:parse_service = get_parse_service()inserted = 0+ total = len(file_paths)for file_path in file_paths:+ io_bridge.raise_if_cancelled()path = Path(file_path)try:doc = parse_service.parse(path)@@ -103,25 +115,57 @@ class LightRagPipeline:file_name=path.name,doc_id=doc.source_hash or path.stem,)+ io_bridge.raise_if_cancelled()doc_error = storage.document_error(Path(rag.working_dir), doc.source_hash or path.stem)if doc_error:raise RuntimeError(f"{path.name}: {doc_error}")inserted += 1self.logger.info("LightRAG: inserted %s", path.name)+ if progress_callback is not None:+ await io_bridge.call(progress_callback, inserted, total)return inserted+ async def _run_indexing(+ self,+ working_dir: Path,+ file_paths: List[str],+ progress_callback: Callable[[int, int], Any] | None,+ ) -> int:+ """Run the complete local LightRAG indexing phase off the service loop.++ The RAG instance is constructed and consumed in one worker thread, so+ its mutable stores and asyncio primitives never cross event loops.+ DeepTutor-owned network calls and progress callbacks cross back through+ ``OwnerLoopBridge`` and remain responsive while local JSON storage is+ busy in the worker.+ """++ async def job(io_bridge: OwnerLoopBridge) -> int:+ io_bridge.raise_if_cancelled()+ rag = engine.build_rag(working_dir, io_bridge=io_bridge)+ return await self._ingest(+ rag,+ file_paths,+ io_bridge=io_bridge,+ progress_callback=progress_callback,+ )++ return await run_in_worker_loop(job)+# ----- indexing -------------------------------------------------------async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:self._ensure_available()+ progress_callback = kwargs.get("progress_callback")kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)self.logger.info("Initializing KB '%s' with %d file(s) using LightRAG", kb_name, len(file_paths))try:- rag = engine.build_rag(storage.working_dir(root_dir))- count = await self._ingest(rag, file_paths)+ count = await self._run_indexing(+ storage.working_dir(root_dir), file_paths, progress_callback+ )if count == 0:self.logger.error("LightRAG: no extractable documents for '%s'", kb_name)self._cleanup_failed_version_dir(root_dir)@@ -137,6 +181,9 @@ class LightRagPipeline:storage.write_meta(root_dir)self.logger.info("KB '%s' initialized with LightRAG (%d docs)", kb_name, count)return True+ except asyncio.CancelledError:+ self._cleanup_failed_version_dir(root_dir)+ raiseexcept Exception as exc:self.logger.error("Failed to initialize LightRAG KB: %s", exc)self.logger.error(traceback.format_exc())@@ -145,10 +192,15 @@ class LightRagPipeline:async def add_documents(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:self._ensure_available()+ progress_callback = kwargs.get("progress_callback")kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)existing = resolve_storage_dir_for_read(kb_dir, None)- is_update = existing is not None and storage.has_output(existing)- root_dir = existing if is_update else resolve_storage_dir_for_rebuild(kb_dir, None)+ if existing is not None and storage.has_output(existing):+ is_update = True+ root_dir = existing+ else:+ is_update = False+ root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)self.logger.info("Adding %d document(s) to LightRAG KB '%s' (update=%s)",@@ -157,8 +209,9 @@ class LightRagPipeline:is_update,)try:- rag = engine.build_rag(storage.working_dir(root_dir))- count = await self._ingest(rag, file_paths)+ count = await self._run_indexing(+ storage.working_dir(root_dir), file_paths, progress_callback+ )if count == 0:self.logger.warning("LightRAG: no extractable documents to add for '%s'", kb_name)return False@@ -174,6 +227,10 @@ class LightRagPipeline:storage.write_meta(root_dir)self.logger.info("Added %d doc(s) to LightRAG KB '%s'", count, kb_name)return True+ except asyncio.CancelledError:+ if not is_update:+ self._cleanup_failed_version_dir(root_dir)+ raiseexcept Exception as exc:self.logger.error("Failed to add documents to LightRAG KB: %s", exc)self.logger.error(traceback.format_exc())diff --git a/deeptutor/services/rag/pipelines/lightrag/worker.py b/deeptutor/services/rag/pipelines/lightrag/worker.pynew file mode 100644index 000000000..9b1701cad--- /dev/null+++ b/deeptutor/services/rag/pipelines/lightrag/worker.py@@ -0,0 +1,137 @@+"""Event-loop isolation helpers for local LightRAG indexing.++RAG-Anything's local storage backends perform synchronous graph merging and+JSON serialization from inside async methods. Running those methods on the+service event loop therefore stalls unrelated API and LLM work. This module+provides one narrow boundary: run the indexing coroutine on a worker thread's+private event loop, while explicitly forwarding network I/O and callbacks to+the event loop that owns the request.+"""++from __future__ import annotations++import asyncio+from collections.abc import Awaitable, Callable+import concurrent.futures+import contextvars+import inspect+import threading+from typing import Any, TypeVar++T = TypeVar("T")+++class OwnerLoopBridge:+ """Run selected awaitables and callbacks on the service event loop.++ The worker receives a copy of the caller's :mod:`contextvars` context.+ ``run`` schedules from that copied context, so request-local model and user+ configuration remains visible on the owner loop.+ """++ def __init__(self, loop: asyncio.AbstractEventLoop) -> None:+ self._loop = loop+ self._cancelled = threading.Event()+ self._pending_lock = threading.Lock()+ self._pending: set[concurrent.futures.Future[Any]] = set()++ def cancel(self) -> None:+ """Reject new owner-loop work and cancel requests already in flight."""+ self._cancelled.set()+ with self._pending_lock:+ pending = tuple(self._pending)+ for future in pending:+ future.cancel()++ def raise_if_cancelled(self) -> None:+ """Cooperatively stop the worker at a safe async boundary."""+ if self._cancelled.is_set():+ raise asyncio.CancelledError++ async def run(self, factory: Callable[[], Awaitable[T]]) -> T:+ """Await ``factory`` on the owner loop and propagate its result/error."""+ self.raise_if_cancelled()+ if asyncio.get_running_loop() is self._loop:+ return await factory()++ async def invoke() -> T:+ return await factory()++ coroutine = invoke()+ try:+ future = asyncio.run_coroutine_threadsafe(coroutine, self._loop)+ except BaseException:+ coroutine.close()+ raise+ with self._pending_lock:+ if self._cancelled.is_set():+ future.cancel()+ else:+ self._pending.add(future)+ try:+ return await asyncio.wrap_future(future)+ except asyncio.CancelledError:+ future.cancel()+ raise+ finally:+ with self._pending_lock:+ self._pending.discard(future)++ async def call(self, callback: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:+ """Invoke a sync or async callback on the owner loop."""++ async def invoke() -> Any:+ result = callback(*args, **kwargs)+ if inspect.isawaitable(result):+ return await result+ return result++ return await self.run(invoke)+++async def run_in_worker_loop(+ job: Callable[[OwnerLoopBridge], Awaitable[T]],+) -> T:+ """Run one async indexing job on a worker thread's private event loop.++ ``job`` and every object it creates should remain confined to that worker.+ The supplied bridge is the only supported route back to the owner loop.+ Worker exceptions are re-raised in the awaiting task.+ """+ owner_loop = asyncio.get_running_loop()+ bridge = OwnerLoopBridge(owner_loop)+ caller_context = contextvars.copy_context()++ async def invoke_job() -> T:+ return await job(bridge)++ def run() -> T:+ return asyncio.run(invoke_job())++ worker = owner_loop.run_in_executor(None, caller_context.run, run)+ try:+ # Shielding keeps cancellation of the request task from orphaning a+ # running worker. Python cannot interrupt arbitrary synchronous code+ # safely, so cancellation becomes cooperative at the next bridge or+ # explicit check; meanwhile the owner loop stays alive for cleanup.+ return await asyncio.shield(worker)+ except asyncio.CancelledError:+ bridge.cancel()+ while not worker.done():+ try:+ await asyncio.shield(worker)+ except asyncio.CancelledError:+ # Repeated cancellation still must not strand the worker on a+ # request scheduled back to this owner loop.+ bridge.cancel()+ # Retrieve the terminal exception so the executor Future never emits+ # an "exception was never retrieved" warning. The caller's+ # cancellation remains authoritative.+ try:+ worker.result()+ except BaseException:+ pass+ raise+++__all__ = ["OwnerLoopBridge", "run_in_worker_loop"]diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex f2926a0e8..169ca1282 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -77,18 +77,37 @@ def _resolve_turn_outcome(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,- not the persisted answer, so it is excluded when assembling content."""+ not the persisted answer, so it is excluded when assembling content.++ DSML rounds may explicitly keep the cleaned prose surrounding a call; that+ narrow exception remains part of the persisted answer.+ """metadata = event.metadata or {}if (metadata.get("trace_kind") == "call_status"and metadata.get("call_state") == "complete"and metadata.get("call_role") == "narration"+ and metadata.get("answer_visible") is not True):call_id = metadata.get("call_id")return str(call_id) if call_id else Nonereturn None+def _assemble_persisted_answer(+ content_segments: Sequence[tuple[str | None, str]],+ narration_call_ids: set[str],+) -> str:+ """Replay visible content bytes, excluding trace-only narration rounds."""+ return clean_thinking_tags(+ "".join(+ text+ for call_id, text in content_segments+ if not (call_id and call_id in narration_call_ids)+ )+ )++def _clip_text(value: str, limit: int = 4000) -> str:text = str(value or "").strip()if len(text) <= limit:@@ -1170,13 +1189,7 @@ class TurnRuntimeManager:# inline <think> in the content channel are split at streaming# time by the agent loop, but anything that slips through must# never be persisted as the user-facing answer.- return clean_thinking_tags(- "".join(- text- for call_id, text in content_segments- if not (call_id and call_id in narration_call_ids)- )- )+ return _assemble_persisted_answer(content_segments, narration_call_ids)# Files the model generated this turn (exec/code_execution artifacts),# persisted as assistant-message attachments so the UI shows openablediff --git a/deeptutor_cli/chat.py b/deeptutor_cli/chat.pyindex a7ab66bf9..39a2bedbd 100644--- a/deeptutor_cli/chat.py+++ b/deeptutor_cli/chat.py@@ -9,6 +9,7 @@ import shlexfrom typing import Anyfrom rich.panel import Panel+from rich.text import Textimport typerfrom deeptutor.app import DeepTutorApp, TurnRequest@@ -284,8 +285,7 @@ def _read_repl_input() -> str:def _print_state(state: ChatState) -> None:- console.print(- "[dim]"+ _print_literal(f"session={state.session_id or '(new)'} "f"capability={state.capability} "f"tools={_format_list(state.tools)} "@@ -293,22 +293,31 @@ def _print_state(state: ChatState) -> None:f"history={_format_list(state.history_references)} "f"notebook_refs={_format_notebook_refs(state.notebook_references)} "f"language={state.language} "- f"config={_format_config(state.config)}"- "[/]",- highlight=False,+ f"config={_format_config(state.config)}",+ style="dim",)def _print_refs(state: ChatState) -> None:- console.print("[bold]Current state:[/]")- console.print(f" session {state.session_id or '(new)'}")- console.print(f" capability {state.capability}")- console.print(f" tools {_format_list(state.tools)}")- console.print(f" kb {_format_list(state.knowledge_bases)}")- console.print(f" history {_format_list(state.history_references)}")- console.print(f" notebooks {_format_notebook_refs(state.notebook_references)}")- console.print(f" language {state.language}")- console.print(f" config {_format_config(state.config)}")+ _print_literal("Current state:", style="bold")+ fields = (+ ("session", state.session_id or "(new)"),+ ("capability", state.capability),+ ("tools", _format_list(state.tools)),+ ("kb", _format_list(state.knowledge_bases)),+ ("history", _format_list(state.history_references)),+ ("notebooks", _format_notebook_refs(state.notebook_references)),+ ("language", state.language),+ ("config", _format_config(state.config)),+ )+ for label, value in fields:+ _print_literal(f" {label:<12}{value}")+++def _print_literal(value: str, *, style: str | None = None) -> None:+ """Print dynamic CLI text without interpreting it as Rich markup."""++ console.print(Text(value, style=style), highlight=False)def _format_list(items: list[str]) -> str:diff --git a/deeptutor_cli/common.py b/deeptutor_cli/common.pyindex 0c9a41791..8da4193df 100644--- a/deeptutor_cli/common.py+++ b/deeptutor_cli/common.py@@ -432,6 +432,8 @@ class TurnStreamRenderer:if call_state == "complete":call_role = str(metadata.get("call_role") or "")if call_role in {"narration", "finish"}:+ if call_role == "narration" and metadata.get("answer_visible") is True:+ call_role = "finish"self._settle_round(str(metadata.get("call_id") or ""), role=call_role)returnif content.strip():diff --git a/pyproject.toml b/pyproject.tomlindex da05b979e..e551bf6dd 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -68,6 +68,10 @@ dependencies = ["pocketbase>=0.12.0","loguru>=0.7.3,<1.0.0","json-repair>=0.57.0,<1.0.0",+ # Process-tree memory readings for /api/v1/system/memory. Soft dependency:+ # deeptutor.runtime.memory_probe imports it lazily and falls back to /proc,+ # so a missing wheel costs the settings strip, not the app.+ "psutil>=5.9.0,<8.0.0",][project.scripts]@@ -118,6 +122,7 @@ server = ["loguru>=0.7.3,<1.0.0","json-repair>=0.57.0,<1.0.0","croniter>=6.0.0,<7.0.0",+ "psutil>=5.9.0,<8.0.0",]# Partner channel SDKs + MCP client. Mirrors requirements/partners.txt.diff --git a/requirements/server.txt b/requirements/server.txtindex 088883ec8..665017ef6 100644--- a/requirements/server.txt+++ b/requirements/server.txt@@ -29,3 +29,8 @@ loguru>=0.7.3,<1.0.0json-repair>=0.57.0,<1.0.0# Built-in cron service (chat & partner scheduled tasks)croniter>=6.0.0,<7.0.0++# --- Runtime observability ---+# Process-tree memory readings behind /api/v1/system/memory. Imported lazily+# with a /proc fallback, so it is soft rather than required.+psutil>=5.9.0,<8.0.0diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.pyindex ab035d53c..b1f008960 100644--- a/tests/agents/chat/test_agent_loop.py+++ b/tests/agents/chat/test_agent_loop.py@@ -501,6 +501,143 @@ async def test_tool_round_then_finish(monkeypatch: pytest.MonkeyPatch) -> None:assert result.metadata["response"] == "Found what was needed."+async def test_dsml_round_keeps_clean_prose_visible_and_decodes_container_args(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A DSML call may share a content stream with tutor feedback.++ Only the call markup is hidden; prose on both sides stays in ``content``.+ The completion marker narrowly opts that cleaned prose out of the normal+ narration demotion, and schema-declared arrays reach the tool as arrays.+ """++ class _PausingRegistry(_Registry):+ async def execute(self, name: str, **kwargs):+ self.executed.append({"name": name, "kwargs": kwargs})+ return ToolResult(+ content="Asked the user.",+ success=True,+ pause_for_user={"questions": kwargs["questions"]},+ )++ registry = _PausingRegistry()+ dsml = (+ "Feedback before. "+ '<||DSML||tool_calls><||DSML||invoke name="ask_user">'+ '<||DSML||parameter name="questions" string="true">'+ '[{"id":"q1","prompt":"Continue?"}]'+ "</||DSML||parameter></||DSML||invoke>"+ "</||DSML||tool_calls> Feedback after."+ )+ # Split inside special tokens, tag names, and the JSON parameter value.+ dsml_chunks = [dsml[index : index + 5] for index in range(0, len(dsml), 5)]+ client = _ScriptedChatClient([[_llm_chunk(content=piece) for piece in dsml_chunks]])+ pipeline = AgenticChatPipeline(language="en")+ pipeline.registry = registry+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: ["ask_user"])+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)++ events = await _run(+ pipeline,+ UnifiedContext(session_id="s1", user_message="Teach me", enabled_tools=["ask_user"]),+ )++ assert registry.executed[0]["name"] == "ask_user"+ assert registry.executed[0]["kwargs"]["questions"] == [{"id": "q1", "prompt": "Continue?"}]+ round_content = "".join(+ event.content+ for event in events+ if event.type == StreamEventType.CONTENT+ and event.metadata.get("call_kind") == "agent_loop_round"+ )+ assert round_content == "Feedback before. Feedback after."+ assert "DSML" not in round_content+ thinking = "".join(event.content for event in events if event.type == StreamEventType.THINKING)+ assert "DSML" not in thinking++ markers = [+ event.metadata+ for event in events+ if event.type == StreamEventType.PROGRESS+ and event.metadata.get("call_state") == "complete"+ and "call_role" in event.metadata+ ]+ assert markers[0]["call_role"] == "narration"+ assert markers[0]["answer_visible"] is True+ result = _result(events)+ assert client.call_count == 1+ assert result.metadata["completed"] is False+ assert result.metadata["response"] == ""+++async def test_dsml_container_schema_survives_native_tool_fallback(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class _FallbackClient:+ def __init__(self, scripted: list[list[SimpleNamespace]]) -> None:+ self.scripted = list(scripted)+ self.calls: list[dict[str, Any]] = []++ class _Completions:+ def __init__(self, parent: _FallbackClient) -> None:+ self.parent = parent++ async def create(self, **kwargs):+ self.parent.calls.append(kwargs)+ if kwargs.get("tools"):+ raise RuntimeError("tool_choice is invalid")+ return _async_llm_stream(self.parent.scripted.pop(0))++ self.chat = SimpleNamespace(completions=_Completions(self))++ class _PausingRegistry(_Registry):+ async def execute(self, name: str, **kwargs):+ self.executed.append({"name": name, "kwargs": kwargs})+ if name == "ask_user":+ return ToolResult(+ content="Asked the user.",+ success=True,+ pause_for_user={"questions": kwargs["questions"]},+ )+ return ToolResult(content="search result", success=True)++ first = (+ '<|DSML|invoke name="web_search">'+ '<|DSML|parameter name="query" string="true">topic'+ "</|DSML|parameter></|DSML|invoke>"+ )+ second = (+ '<|DSML|invoke name="ask_user">'+ '<|DSML|parameter name="questions" string="true">'+ '[{"id":"q1","prompt":"Continue?"}]'+ "</|DSML|parameter></|DSML|invoke>"+ )+ client = _FallbackClient([[_llm_chunk(content=first)], [_llm_chunk(content=second)]])+ registry = _PausingRegistry()+ pipeline = AgenticChatPipeline(language="en")+ pipeline.registry = registry+ monkeypatch.setattr(+ pipeline, "_compose_enabled_tools", lambda _context: ["web_search", "ask_user"]+ )+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)++ await _run(+ pipeline,+ UnifiedContext(+ session_id="s1",+ user_message="Teach me",+ enabled_tools=["web_search", "ask_user"],+ ),+ )++ assert [item["name"] for item in registry.executed] == ["web_search", "ask_user"]+ assert registry.executed[-1]["kwargs"]["questions"] == [{"id": "q1", "prompt": "Continue?"}]+ assert "tools" in client.calls[0]+ assert all("tools" not in call for call in client.calls[1:])++@pytest.mark.asyncioasync def test_midloop_llm_failure_salvages_turn_with_forced_finish(monkeypatch: pytest.MonkeyPatch,@@ -822,7 +959,9 @@ async def test_unresolved_ask_user_halts_turn(monkeypatch: pytest.MonkeyPatch) -@pytest.mark.asyncio-async def test_round_budget_forces_tool_less_finish(monkeypatch: pytest.MonkeyPatch) -> None:+async def test_round_budget_enters_tool_enabled_settlement_then_finishes(+ monkeypatch: pytest.MonkeyPatch,+) -> None:registry = _Registry()client = _ScriptedChatClient([@@ -852,13 +991,266 @@ async def test_round_budget_forces_tool_less_finish(monkeypatch: pytest.MonkeyPa)assert client.call_count == 2- # The forced finish round disables tools and tells the model to answer now.- assert "tools" not in client.calls[-1]- forced_instruction = client.calls[-1]["messages"][-1]["content"]- assert "round budget ran out" in forced_instruction+ # The exploration budget is separate from bounded protocol settlement:+ # one follow-up round retains tools so already-started work can settle.+ assert "tools" in client.calls[-1]+ settlement_instruction = client.calls[-1]["messages"][-1]["content"]+ assert "exploration round budget" in settlement_instruction.lower()result = _result(events)assert result.metadata["response"] == "Best effort answer."assert result.metadata["completed"] is True+ assert result.metadata["settlement_rounds"] == 1+++async def test_budget_settlement_completes_quiz_ask_grade_and_feedback(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A quiz registered on the final exploration round still gets shown,+ answered, graded, and followed by deterministic learner feedback."""++ class _MasteryRegistry(_Registry):+ def build_openai_schemas(self, _enabled):+ schemas = super().build_openai_schemas(_enabled)+ schemas.extend(+ [+ {+ "type": "function",+ "function": {+ "name": name,+ "description": name,+ "parameters": {+ "type": "object",+ "properties": {},+ "additionalProperties": True,+ },+ },+ }+ for name in ("mastery_quiz", "mastery_grade")+ ]+ )+ return schemas++ async def execute(self, name: str, **kwargs):+ self.executed.append({"name": name, "kwargs": kwargs})+ if name == "ask_user":+ return ToolResult(+ content="Asked the learner.",+ success=True,+ pause_for_user={"questions": kwargs["questions"]},+ )+ if name == "mastery_quiz":+ return ToolResult(content="Quiz q1 registered.", success=True)+ if name == "mastery_grade":+ return ToolResult(content="Correct; objective mastered.", success=True)+ raise AssertionError(f"unexpected tool: {name}")++ registry = _MasteryRegistry()+ client = _ScriptedChatClient(+ [+ [+ _llm_chunk(+ tool_calls=[+ {+ "id": "quiz-1",+ "name": "mastery_quiz",+ "arguments": "{}",+ }+ ]+ )+ ],+ [+ _llm_chunk(+ tool_calls=[+ {+ "id": "ask-1",+ "name": "ask_user",+ "arguments": json.dumps(+ {"questions": [{"id": "q1", "prompt": "Which answer?"}]}+ ),+ }+ ]+ )+ ],+ [+ _llm_chunk(+ tool_calls=[+ {+ "id": "grade-1",+ "name": "mastery_grade",+ "arguments": json.dumps({"question_id": "q1", "answer": "B"}),+ }+ ]+ )+ ],+ [_llm_chunk(content="Correct — here is why B is the right answer.")],+ ]+ )+ pipeline = AgenticChatPipeline(language="en")+ pipeline.registry = registry+ pipeline._max_rounds = 1+ monkeypatch.setattr(+ pipeline,+ "_compose_enabled_tools",+ lambda _context: ["mastery_quiz", "ask_user", "mastery_grade"],+ )+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)++ async def _waiter():+ return {"text": "B"}++ events = await _run(+ pipeline,+ UnifiedContext(+ session_id="s1",+ user_message="Quiz me",+ enabled_tools=["mastery_quiz", "ask_user", "mastery_grade"],+ metadata={"wait_for_user_reply": _waiter},+ ),+ )++ assert [entry["name"] for entry in registry.executed] == [+ "mastery_quiz",+ "ask_user",+ "mastery_grade",+ ]+ assert client.call_count == 4+ # All three settlement rounds retain the tool contract; the final one+ # chooses to finish without calling another tool.+ assert all("tools" in call for call in client.calls)+ grade_round = client.calls[2]["messages"]+ assert any(+ message.get("role") == "tool" and "User answered" in str(message.get("content"))+ for message in grade_round+ )+ result = _result(events)+ assert result.metadata["response"] == "Correct — here is why B is the right answer."+ assert result.metadata["completed"] is True+ assert result.metadata["rounds"] == 4+ assert result.metadata["settlement_rounds"] == 3+++async def test_settlement_hard_limit_forces_one_tool_less_finish(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A model that ignores settlement instructions cannot loop forever."""+ registry = _Registry()+ repeated_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([*repeated_tool_rounds, [_llm_chunk(content="Hard-stop answer.")]])+ 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)++ events = await _run(+ pipeline,+ UnifiedContext(session_id="s1", user_message="Research", enabled_tools=["web_search"]),+ )++ # N exploration calls + 3 tool-enabled settlement calls + 1 hard finish.+ assert client.call_count == 5+ assert all("tools" in call for call in client.calls[:4])+ assert "tools" not in client.calls[4]+ assert len(registry.executed) == 4+ result = _result(events)+ assert result.metadata["response"] == "Hard-stop answer."+ assert result.metadata["completed"] is True+ assert result.metadata["rounds"] == 5+ assert result.metadata["settlement_rounds"] == 3+++async def test_length_finish_reason_continues_within_bounded_settlement(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A token-truncated, tool-less round is incomplete, not a finish."""+ registry = _Registry()+ client = _ScriptedChatClient(+ [+ [_llm_chunk(content="Part one is incomplete. ", finish_reason="length")],+ [_llm_chunk(content="Part two completes the answer.", finish_reason="stop")],+ ]+ )+ 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)++ events = await _run(+ pipeline,+ UnifiedContext(session_id="s1", user_message="Explain fully", enabled_tools=["web_search"]),+ )++ assert client.call_count == 2+ continuation_messages = client.calls[1]["messages"]+ assert continuation_messages[-2] == {+ "role": "assistant",+ "content": "Part one is incomplete. ",+ }+ assert "token limit" in continuation_messages[-1]["content"].lower()+ markers = [+ event.metadata+ for event in events+ if event.type == StreamEventType.PROGRESS+ and event.metadata.get("call_state") == "complete"+ and "call_role" in event.metadata+ ]+ assert markers[0]["call_role"] == "narration"+ assert markers[0]["answer_visible"] is True+ assert markers[1]["call_role"] == "finish"+ result = _result(events)+ expected = "Part one is incomplete. Part two completes the answer."+ assert result.metadata["response"] == expected+ # RESULT/SDK and event-replay consumers use the exact same visible bytes.+ assert "".join(_contents(events)) == expected+ assert result.metadata["completed"] is True+ assert result.metadata["settlement_rounds"] == 1+++async def test_repeated_empty_finish_stops_after_one_nudge(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """An empty provider response gets one recovery chance, never a loop."""+ registry = _Registry()+ client = _ScriptedChatClient(+ [+ [_llm_chunk(content="<think>first empty</think>")],+ [_llm_chunk(content="<think>still empty</think>")],+ ]+ )+ pipeline = AgenticChatPipeline(language="en")+ pipeline.registry = registry+ pipeline._max_rounds = 1+ 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="Answer"))++ assert client.call_count == 2+ result = _result(events)+ assert result.metadata["response"] == (+ "I could not produce a useful response from the model output. "+ "Please try again or narrow the request."+ )+ assert result.metadata["completed"] is True+ assert result.metadata["settlement_rounds"] == 1def test_compose_enabled_tools_injects_rag_when_kb_selected(diff --git a/tests/agents/chat/test_dsml_tool_calls.py b/tests/agents/chat/test_dsml_tool_calls.pyindex 5be997025..35abbf747 100644--- a/tests/agents/chat/test_dsml_tool_calls.py+++ b/tests/agents/chat/test_dsml_tool_calls.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport jsonfrom deeptutor.agents.chat.dsml_tool_calls import (+ DSMLStreamFilter,extract_dsml_tool_calls,has_dsml_tool_calls,)@@ -75,6 +76,81 @@ def test_non_string_parameter_is_json_coerced() -> None:assert args["label"] == "3" # string="true" kept verbatim+def test_string_marked_json_containers_follow_tool_schema() -> None:+ text = (+ '<|DSML|invoke name="ask_user">'+ '<|DSML|parameter name="questions" string="true">'+ '[{"id":"q1","prompt":"Pick one"}]'+ "</|DSML|parameter>"+ '<|DSML|parameter name="context" string="true">'+ '{"source":"lesson"}'+ "</|DSML|parameter>"+ '<|DSML|parameter name="literal" string="true">[not JSON]</|DSML|parameter>'+ "</|DSML|invoke>"+ )+ schemas = [+ {+ "type": "function",+ "function": {+ "name": "ask_user",+ "parameters": {+ "type": "object",+ "properties": {+ "questions": {"type": "array", "items": {"type": "object"}},+ "context": {"type": "object"},+ "literal": {"type": "string"},+ },+ },+ },+ }+ ]++ calls, _ = extract_dsml_tool_calls(text, schemas)+ args = json.loads(calls[0]["arguments"])++ assert args["questions"] == [{"id": "q1", "prompt": "Pick one"}]+ assert args["context"] == {"source": "lesson"}+ assert args["literal"] == "[not JSON]"+++def test_string_marked_json_container_stays_string_without_schema() -> None:+ text = (+ '<|DSML|invoke name="ask_user">'+ '<|DSML|parameter name="questions" string="true">["A", "B"]'+ "</|DSML|parameter>"+ "</|DSML|invoke>"+ )++ calls, _ = extract_dsml_tool_calls(text)++ assert json.loads(calls[0]["arguments"])["questions"] == '["A", "B"]'+++def test_schema_container_type_must_match_parsed_value() -> None:+ text = (+ '<|DSML|invoke name="ask_user">'+ '<|DSML|parameter name="questions" string="true">{"not":"a list"}'+ "</|DSML|parameter>"+ "</|DSML|invoke>"+ )+ schemas = [+ {+ "type": "function",+ "function": {+ "name": "ask_user",+ "parameters": {+ "type": "object",+ "properties": {"questions": {"type": "array"}},+ },+ },+ }+ ]++ calls, _ = extract_dsml_tool_calls(text, schemas)++ assert json.loads(calls[0]["arguments"])["questions"] == '{"not":"a list"}'++def test_plain_text_is_untouched() -> None:text = "Here is your answer. No tools needed."assert has_dsml_tool_calls(text) is False@@ -98,3 +174,52 @@ def test_malformed_envelope_without_close_yields_no_calls() -> None:calls, cleaned = extract_dsml_tool_calls(text)assert calls == []assert cleaned == text+++class TestDSMLStreamFilter:+ @staticmethod+ def _run(chunks: list[str]) -> str:+ stream_filter = DSMLStreamFilter()+ visible = "".join(stream_filter.feed(chunk) for chunk in chunks)+ return visible + stream_filter.flush()++ def test_preserves_prose_before_and_after_call(self) -> None:+ text = (+ "Great job! "+ '<|DSML|tool_calls><|DSML|invoke name="ask_user">'+ '<|DSML|parameter name="questions" string="true">[]'+ "</|DSML|parameter></|DSML|invoke></|DSML|tool_calls>"+ " Choose what to study next."+ )++ assert self._run([text]) == "Great job! Choose what to study next."++ def test_handles_every_split_boundary(self) -> None:+ text = (+ "Before "+ '<||DSML||tool_calls><||DSML||invoke name="exec">'+ '<||DSML||parameter name="command" string="true">echo hi'+ "</||DSML||parameter></||DSML||invoke>"+ "</||DSML||tool_calls> after"+ )++ for split_at in range(len(text) + 1):+ assert self._run([text[:split_at], text[split_at:]]) == "Before after"++ tiny_chunks = [text[index : index + 3] for index in range(0, len(text), 3)]+ assert self._run(tiny_chunks) == "Before after"++ def test_incomplete_invoke_is_not_silently_discarded(self) -> None:+ text = '<|DSML|invoke name="exec">unterminated'+ assert self._run([text[:8], text[8:]]) == text++ def test_malformed_envelope_is_not_partially_discarded(self) -> None:+ text = "before <|DSML|tool_calls>not an invoke after"+ assert self._run([text[:20], text[20:]]) == text++ def test_envelope_without_close_still_cleans_complete_invoke(self) -> None:+ text = 'before <|DSML|tool_calls><|DSML|invoke name="exec"></|DSML|invoke> after'+ assert self._run([text[:20], text[20:]]) == "before after"++ def test_plain_angle_brackets_are_untouched(self) -> None:+ assert self._run(["1 < 2 and <b>", "bold</b>"]) == "1 < 2 and <b>bold</b>"diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.pyindex 30a859507..38b4862a3 100644--- a/tests/api/test_knowledge_router.py+++ b/tests/api/test_knowledge_router.py@@ -612,6 +612,75 @@ def test_list_files_returns_nested_tree(monkeypatch, tmp_path: Path) -> None:assert entries["root.txt"]["type"] == "file"+def test_remote_kb_file_listing_is_empty_without_creating_local_storage(+ monkeypatch, tmp_path: Path+) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ manager.register_lightrag_server_kb("remote", "http://localhost:9621")+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)++ with TestClient(_build_app()) as client:+ response = client.get("/api/v1/knowledge/remote/files")++ assert response.status_code == 200+ assert response.json() == {"files": []}+ assert not (manager.base_dir / "remote").exists()+++ ("method", "url", "kwargs"),+ [+ ("get", "/api/v1/knowledge/remote/files/demo.txt", {}),+ ("get", "/api/v1/knowledge/remote/file-preview-text/demo.txt", {}),+ ("delete", "/api/v1/knowledge/remote/files/demo.txt", {}),+ ("post", "/api/v1/knowledge/remote/folders", {"json": {"path": "notes"}}),+ (+ "post",+ "/api/v1/knowledge/remote/files/move",+ {"json": {"source": "demo.txt", "dest_folder": "notes"}},+ ),+ ("post", "/api/v1/knowledge/remote/upload", {"files": _upload_payload()}),+ ],+)+def test_remote_kb_rejects_local_file_operations_without_creating_storage(+ monkeypatch, tmp_path: Path, method: str, url: str, kwargs: dict+) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ manager.register_lightrag_server_kb("remote", "http://localhost:9621")+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)++ with TestClient(_build_app()) as client:+ response = getattr(client, method)(url, **kwargs)++ assert response.status_code == 409+ assert "external resource" in response.json()["detail"]+ assert not (manager.base_dir / "remote").exists()+++def test_list_files_returns_404_for_unknown_kb_without_creating_storage(+ monkeypatch, tmp_path: Path+) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)++ with TestClient(_build_app()) as client:+ response = client.get("/api/v1/knowledge/missing/files")++ assert response.status_code == 404+ assert not (manager.base_dir / "missing").exists()+++def test_raw_file_download_rejects_traversal(monkeypatch, tmp_path: Path) -> None:+ manager = _ready_kb_manager(tmp_path)+ (manager.base_dir / "secret.txt").write_text("secret", encoding="utf-8")+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)++ with TestClient(_build_app()) as client:+ response = client.get("/api/v1/knowledge/kb/files/%2E%2E/secret.txt")++ assert response.status_code == 403++def test_upload_preserves_folder_structure(monkeypatch, tmp_path: Path) -> None:manager = _ready_kb_manager(tmp_path)monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)diff --git a/tests/api/test_output_files.py b/tests/api/test_output_files.pynew file mode 100644index 000000000..ac9be7c2f--- /dev/null+++ b/tests/api/test_output_files.py@@ -0,0 +1,185 @@+"""Request-scoped regression coverage for generated-output downloads (#790)."""++from __future__ import annotations++from collections.abc import Callable+from pathlib import Path++from fastapi import FastAPI+from fastapi.testclient import TestClient+import pytest++from deeptutor.services.auth import TokenPayload+from deeptutor.services.path_service import PathService++OutputAppFactory = Callable[[dict[str, TokenPayload | None], bool], tuple[TestClient, Path, Path]]+++def output_app(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> OutputAppFactory:+ from deeptutor.api.routers import auth as auth_router+ from deeptutor.api.routers import outputs+ from deeptutor.multi_user import paths as multi_user_paths++ admin_root = tmp_path / "data"+ users_root = admin_root / "users"+ monkeypatch.setattr(multi_user_paths, "ADMIN_WORKSPACE_ROOT", admin_root)+ monkeypatch.setattr(multi_user_paths, "USERS_ROOT", users_root)+ monkeypatch.setattr(multi_user_paths, "_path_services", {})++ def make_app(+ tokens: dict[str, TokenPayload | None], auth_enabled: bool = True+ ) -> tuple[TestClient, Path, Path]:+ monkeypatch.setattr(auth_router, "AUTH_ENABLED", auth_enabled)+ monkeypatch.setattr(auth_router, "decode_token", lambda token: tokens.get(token))+ app = FastAPI()+ app.include_router(outputs.router, prefix="/api/outputs")+ return TestClient(app), admin_root, users_root++ return make_app+++def _write_output(workspace_root: Path, relative_path: str, contents: bytes) -> Path:+ output = PathService(workspace_root=workspace_root).get_public_outputs_root() / relative_path+ output.parent.mkdir(parents=True, exist_ok=True)+ output.write_bytes(contents)+ return output+++ ("headers", "cookie"),+ [+ ({}, True),+ ({"Authorization": "Bearer alice-token"}, False),+ ],+)+def test_authenticated_user_downloads_own_output(output_app, headers, cookie) -> None:+ relative_path = "workspace/chat/chat/session-1/code_runs/report.pdf"+ alice = TokenPayload(username="alice", role="user", user_id="u_alice")+ client, _admin_root, users_root = output_app({"alice-token": alice})+ _write_output(users_root / "u_alice", relative_path, b"alice report")++ with client:+ if cookie:+ client.cookies.set("dt_token", "alice-token")+ response = client.get(f"/api/outputs/{relative_path}", headers=headers)++ assert response.status_code == 200+ assert response.content == b"alice report"+ assert response.headers["content-type"] == "application/pdf"+++def test_same_output_url_is_isolated_between_users(output_app) -> None:+ relative_path = "workspace/chat/chat/session-1/code_runs/report.docx"+ tokens = {+ "alice-token": TokenPayload(username="alice", role="user", user_id="u_alice"),+ "bob-token": TokenPayload(username="bob", role="user", user_id="u_bob"),+ "carol-token": TokenPayload(username="carol", role="user", user_id="u_carol"),+ }+ client, _admin_root, users_root = output_app(tokens)+ _write_output(users_root / "u_alice", relative_path, b"alice document")+ _write_output(users_root / "u_bob", relative_path, b"bob document")++ with client:+ client.cookies.set("dt_token", "alice-token")+ alice = client.get(f"/api/outputs/{relative_path}")+ client.cookies.set("dt_token", "bob-token")+ bob = client.get(f"/api/outputs/{relative_path}")+ client.cookies.set("dt_token", "carol-token")+ carol = client.get(f"/api/outputs/{relative_path}")++ assert alice.content == b"alice document"+ assert bob.content == b"bob document"+ assert carol.status_code == 404+ assert "u_alice" not in carol.text+ assert "u_bob" not in carol.text++[email protected]("token", [None, "malformed-token", "expired-token"])+def test_invalid_auth_never_falls_back_to_admin_output(output_app, token) -> None:+ relative_path = "workspace/chat/chat/session-1/code_runs/admin.pdf"+ client, admin_root, _users_root = output_app({"malformed-token": None, "expired-token": None})+ _write_output(admin_root, relative_path, b"admin-only output")+ headers = {} if token is None else {"Authorization": f"Bearer {token}"}++ with client:+ response = client.get(f"/api/outputs/{relative_path}", headers=headers)++ assert response.status_code == 401+ assert "admin-only output" not in response.text+ assert str(admin_root) not in response.text+++def test_auth_disabled_reads_local_admin_output(output_app) -> None:+ relative_path = "workspace/chat/chat/session-1/code_runs/local.pdf"+ client, admin_root, _users_root = output_app({}, auth_enabled=False)+ _write_output(admin_root, relative_path, b"local output")++ with client:+ response = client.get(f"/api/outputs/{relative_path}")++ assert response.status_code == 200+ assert response.content == b"local output"+++def test_private_suffix_is_rejected(output_app) -> None:+ relative_path = "workspace/chat/chat/session-1/code_runs/private.json"+ alice = TokenPayload(username="alice", role="user", user_id="u_alice")+ client, _admin_root, users_root = output_app({"alice-token": alice})+ _write_output(users_root / "u_alice", relative_path, b'{"secret": true}')++ with client:+ client.cookies.set("dt_token", "alice-token")+ response = client.get(f"/api/outputs/{relative_path}")++ assert response.status_code == 404+ assert "secret" not in response.text+++def test_path_traversal_is_rejected(output_app) -> None:+ alice = TokenPayload(username="alice", role="user", user_id="u_alice")+ client, _admin_root, users_root = output_app({"alice-token": alice})+ _write_output(users_root / "u_alice", "secret.pdf", b"outside public allowlist")++ with client:+ client.cookies.set("dt_token", "alice-token")+ response = client.get("/api/outputs/%2E%2E/secret.pdf")++ assert response.status_code == 404+ assert "outside public allowlist" not in response.text+++def test_symlink_outside_user_root_is_rejected(output_app, tmp_path: Path) -> None:+ relative_path = "workspace/chat/chat/session-1/code_runs/escape.pdf"+ alice = TokenPayload(username="alice", role="user", user_id="u_alice")+ client, _admin_root, users_root = output_app({"alice-token": alice})+ external = tmp_path / "external.pdf"+ external.write_bytes(b"other user's data")+ link = _write_output(users_root / "u_alice", relative_path, b"placeholder")+ link.unlink()+ link.symlink_to(external)++ with client:+ client.cookies.set("dt_token", "alice-token")+ response = client.get(f"/api/outputs/{relative_path}")++ assert response.status_code == 404+ assert "other user's data" not in response.text+++def test_absolute_parent_and_symlink_escapes_are_rejected(tmp_path: Path) -> None:+ workspace_root = tmp_path / "data" / "users" / "u_alice"+ service = PathService(workspace_root=workspace_root)+ public_root = service.get_public_outputs_root()+ external = workspace_root / "external.pdf"+ external.parent.mkdir(parents=True, exist_ok=True)+ external.write_bytes(b"outside the public root")++ absolute_parent_escape = public_root / ".." / "external.pdf"+ assert absolute_parent_escape.is_absolute()+ assert service.resolve_public_output_path(absolute_parent_escape) is None++ link = public_root / "workspace" / "chat" / "chat" / "session-1" / "exec" / "link.pdf"+ link.parent.mkdir(parents=True, exist_ok=True)+ link.symlink_to(external)+ assert service.resolve_public_output_path(link.absolute()) is Nonediff --git a/tests/api/test_system_router.py b/tests/api/test_system_router.pyindex 738ce6239..328d14ba5 100644--- a/tests/api/test_system_router.py+++ b/tests/api/test_system_router.py@@ -5,6 +5,20 @@ from types import SimpleNamespaceimport pytestfrom deeptutor.api.routers import system as system_router+from deeptutor.runtime.memory_probe import MemorySnapshot, ProcessMemory+++def _snapshot(*processes: ProcessMemory, **overrides: object) -> MemorySnapshot:+ fields: dict[str, object] = {+ "processes": processes,+ "total_rss_bytes": sum(p.rss_bytes for p in processes),+ "limit_bytes": 16 * 1024**3,+ "available_bytes": 8 * 1024**3,+ "limit_source": "host",+ "partial": False,+ }+ fields.update(overrides)+ return MemorySnapshot(**fields) # type: ignore[arg-type]@pytest.mark.asyncio@@ -48,3 +62,79 @@ async def test_embeddings_connection_rejects_partial_batch_response(assert response.success is Falseassert response.message == "Embeddings connection failed: Invalid response"+++async def test_memory_usage_is_withheld_from_non_admins(monkeypatch: pytest.MonkeyPatch) -> None:+ """Same reason /status strips model names: it is operational detail."""+ monkeypatch.setattr(system_router, "get_current_user", lambda: SimpleNamespace(is_admin=False))+ monkeypatch.setattr(+ system_router.memory_probe,+ "capture",+ lambda: _snapshot(ProcessMemory(pid=1, label="backend", rss_bytes=100)),+ )++ payload = await system_router.get_memory_usage()++ assert payload == {"available": False}+++async def test_memory_usage_groups_processes_by_role(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(system_router, "get_current_user", lambda: SimpleNamespace(is_admin=True))+ monkeypatch.setattr(+ system_router.memory_probe,+ "capture",+ lambda: _snapshot(+ ProcessMemory(pid=1, label="backend", rss_bytes=800),+ ProcessMemory(pid=2, label="web", rss_bytes=500),+ ProcessMemory(pid=3, label="sandbox", rss_bytes=40),+ ProcessMemory(pid=4, label="sandbox", rss_bytes=30),+ ),+ )++ payload = await system_router.get_memory_usage()++ assert payload["available"] is True+ assert payload["total_rss_bytes"] == 1370+ assert payload["usage_ratio"] == 1370 / (16 * 1024**3)+ # Concurrent sandboxes collapse into one row rather than flooding the tooltip.+ assert payload["processes"] == [+ {"label": "backend", "count": 1, "rss_bytes": 800},+ {"label": "web", "count": 1, "rss_bytes": 500},+ {"label": "sandbox", "count": 2, "rss_bytes": 70},+ ]+++async def test_memory_usage_folds_the_long_tail_into_other(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ limit = system_router.memory_probe.MAX_REPORTED_PROCESSES+ roles = [+ ProcessMemory(pid=i, label=f"role-{i}", rss_bytes=(limit + 5 - i) * 10)+ for i in range(limit + 3)+ ]+ monkeypatch.setattr(system_router, "get_current_user", lambda: SimpleNamespace(is_admin=True))+ monkeypatch.setattr(system_router.memory_probe, "capture", lambda: _snapshot(*roles))++ payload = await system_router.get_memory_usage()++ assert len(payload["processes"]) == limit + 1+ tail = payload["processes"][-1]+ assert tail["label"] == "other"+ assert tail["count"] == 3+ # Folding must not lose bytes — the rows still add up to the reported total.+ assert sum(row["rss_bytes"] for row in payload["processes"]) == payload["total_rss_bytes"]+++async def test_memory_usage_unavailable_when_no_process_can_be_read(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(system_router, "get_current_user", lambda: SimpleNamespace(is_admin=True))+ monkeypatch.setattr(system_router.memory_probe, "capture", lambda: _snapshot())++ payload = await system_router.get_memory_usage()++ assert payload == {"available": False}diff --git a/tests/capabilities/test_mastery_capability.py b/tests/capabilities/test_mastery_capability.pynew file mode 100644index 000000000..daff1cd3d--- /dev/null+++ b/tests/capabilities/test_mastery_capability.py@@ -0,0 +1,82 @@+"""Tests for mastery loop hooks that bind persisted pending questions."""++from __future__ import annotations++from pathlib import Path++from deeptutor.capabilities.mastery.loop import MasteryLoopCapability+from deeptutor.core.context import UnifiedContext+from deeptutor.learning.models import LearningProgress, PendingQuestion+from deeptutor.learning.storage import LearningStore+++def _use_store_root(monkeypatch, root: Path) -> None:+ def _init(self, root_arg=None):+ self._root = root / "learning"+ self._root.mkdir(parents=True, exist_ok=True)++ monkeypatch.setattr(LearningStore, "__init__", _init)+++def _context() -> UnifiedContext:+ return UnifiedContext(+ user_message="continue",+ session_id="session-1",+ metadata={"mastery_mode": True, "mastery_path_id": "path-1", "turn_id": "turn-2"},+ )+++def test_pending_question_overrides_reauthored_ask_user_mapping(tmp_path, monkeypatch):+ _use_store_root(monkeypatch, tmp_path)+ progress = LearningProgress(book_id="path-1")+ progress.pending_question = PendingQuestion(+ question_id="stable-question",+ knowledge_point_id="kp-1",+ prompt="Which colour?",+ question_type="choice",+ expected_answer="B",+ options=["A: red", "B: blue"],+ )+ LearningStore().save(progress)++ rebound = MasteryLoopCapability().augment_kwargs(+ "ask_user",+ {+ "intro": "Keep this lead-in",+ "questions": [+ {+ "id": "new-question",+ "prompt": "Rewritten question",+ "options": [+ {"label": "A", "description": "blue"},+ {"label": "B", "description": "red"},+ ],+ }+ ],+ },+ _context(),+ )++ assert rebound == {+ "intro": "Keep this lead-in",+ "questions": [+ {+ "id": "stable-question",+ "prompt": "Which colour?",+ "options": [+ {"label": "A", "description": "red"},+ {"label": "B", "description": "blue"},+ ],+ "multi_select": False,+ "allow_free_text": True,+ }+ ],+ }+++def test_ask_user_is_untouched_without_pending_question(tmp_path, monkeypatch):+ _use_store_root(monkeypatch, tmp_path)+ LearningStore().save(LearningProgress(book_id="path-1"))+ authored = {"questions": [{"id": "clarify", "prompt": "Which scope?"}]}++ assert MasteryLoopCapability().augment_kwargs("ask_user", authored, _context()) == authoreddiff --git a/tests/cli/test_chat_state_output.py b/tests/cli/test_chat_state_output.pynew file mode 100644index 000000000..d12d552c4--- /dev/null+++ b/tests/cli/test_chat_state_output.py@@ -0,0 +1,103 @@+"""Regression tests for literal state values in the interactive chat CLI."""++from __future__ import annotations++from io import StringIO++import pytest+from rich.console import Console+from rich.text import Text++from deeptutor_cli import chat+++def _render(monkeypatch: pytest.MonkeyPatch, render, state: chat.ChatState) -> str: # noqa: ANN001+ output = StringIO()+ monkeypatch.setattr(+ chat,+ "console",+ Console(file=output, force_terminal=False, color_system=None, width=1000),+ )+ render(state)+ return output.getvalue()+++ ("tools", "expected"),+ [+ ([], "tools=[]"),+ (["rag"], "tools=[rag]"),+ (["rag", "web_search"], "tools=[rag, web_search]"),+ ],+)+def test_print_state_renders_tool_lists_literally(+ monkeypatch: pytest.MonkeyPatch,+ tools: list[str],+ expected: str,+) -> None:+ output = _render(monkeypatch, chat._print_state, chat.ChatState(tools=tools))++ assert expected in output+++def test_print_state_renders_rich_markup_characters_literally(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = chat.ChatState(+ session_id="[bold]session[/bold]",+ capability="[cyan]chat[/cyan]",+ tools=["[rag]"],+ knowledge_bases=["[red]kb[/red]"],+ history_references=["[green]history[/green]"],+ notebook_references=[+ {"notebook_id": "[blue]notebook[/blue]", "record_ids": ["[yellow]record[/yellow]"]}+ ],+ language="[magenta]en[/magenta]",+ config={"theme": "[italic]literal[/italic]"},+ )++ output = _render(monkeypatch, chat._print_state, state)++ for literal in (+ "[bold]session[/bold]",+ "[cyan]chat[/cyan]",+ "tools=[[rag]]",+ "kb=[[red]kb[/red]]",+ "history=[[green]history[/green]]",+ "[blue]notebook[/blue]:[yellow]record[/yellow]",+ "[magenta]en[/magenta]",+ '"[italic]literal[/italic]"',+ ):+ assert literal in output+++def test_print_state_keeps_dim_style(monkeypatch: pytest.MonkeyPatch) -> None:+ rendered: list[object] = []++ class RecordingConsole:+ def print(self, value, **_kwargs) -> None: # noqa: ANN001+ rendered.append(value)++ monkeypatch.setattr(chat, "console", RecordingConsole())++ chat._print_state(chat.ChatState(tools=["rag"]))++ assert len(rendered) == 1+ assert isinstance(rendered[0], Text)+ assert rendered[0].style == "dim"+++def test_print_refs_renders_dynamic_values_literally(monkeypatch: pytest.MonkeyPatch) -> None:+ state = chat.ChatState(+ tools=["[bold]rag[/bold]"],+ knowledge_bases=["[red]kb[/red]"],+ history_references=["[green]history[/green]"],+ notebook_references=[{"notebook_id": "[blue]notebook[/blue]", "record_ids": []}],+ )++ output = _render(monkeypatch, chat._print_refs, state)++ assert "tools [[bold]rag[/bold]]" in output+ assert "kb [[red]kb[/red]]" in output+ assert "history [[green]history[/green]]" in output+ assert "notebooks [[blue]notebook[/blue]]" in outputdiff --git a/tests/cli/test_turn_renderer.py b/tests/cli/test_turn_renderer.pyindex 1f4d3772c..c29f7ab44 100644--- a/tests/cli/test_turn_renderer.py+++ b/tests/cli/test_turn_renderer.py@@ -146,6 +146,32 @@ def test_narration_renders_before_tools_and_finish_is_answer(monkeypatch) -> Nonassert "▶ responding" not in result.output+def test_dsml_clean_content_uses_answer_rendering(monkeypatch) -> None:+ events = [+ {"type": "stage_start", "stage": "responding", "source": "chat"},+ _running("r1"),+ _chunk("r1", "Tutor says **well done**."),+ {+ **_marker("r1", "narration"),+ "metadata": {+ **_marker("r1", "narration")["metadata"],+ "answer_visible": True,+ },+ },+ {"type": "stage_end", "stage": "responding", "source": "chat"},+ {"type": "done"},+ ]+ _install_fake_runtime(monkeypatch, events)++ result = runner.invoke(app, ["run", "chat", "hello"])++ assert result.exit_code == 0, result.output+ assert "Tutor says well done." in result.output+ # Plain narration uses Text and would retain the Markdown markers; the+ # DSML-visible marker settles this round through the answer renderer.+ assert "**well done**" not in result.output++def test_done_summary_line_includes_rounds_tools_tokens_cost(monkeypatch) -> None:_install_fake_runtime(monkeypatch, _agent_loop_turn_events())diff --git a/tests/runtime/test_memory_probe.py b/tests/runtime/test_memory_probe.pynew file mode 100644index 000000000..2fbf78e24--- /dev/null+++ b/tests/runtime/test_memory_probe.py@@ -0,0 +1,169 @@+from __future__ import annotations++import os+from pathlib import Path+import sys++import pytest++from deeptutor.runtime import memory_probe+++def test_capture_always_measures_at_least_this_process() -> None:+ snapshot = memory_probe.capture()++ if not snapshot.processes:+ pytest.skip("no memory backend on this platform (no psutil, not Linux)")+ assert snapshot.total_rss_bytes > 0+ assert any(p.pid == os.getpid() for p in snapshot.processes)+++def test_capture_without_supervisor_anchor_reports_partial(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.delenv(memory_probe.SUPERVISOR_PID_ENV, raising=False)++ snapshot = memory_probe.capture()++ if not snapshot.processes:+ pytest.skip("no memory backend on this platform (no psutil, not Linux)")+ # No anchor means the walk started at this process, so the number understates+ # the tree and the UI has to say so.+ assert snapshot.partial is True+++def test_supervisor_pid_ignores_dead_and_malformed_values(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ alive = {os.getpid()}++ monkeypatch.setenv(memory_probe.SUPERVISOR_PID_ENV, "not-a-pid")+ assert memory_probe._supervisor_pid(lambda pid: pid in alive) is None++ monkeypatch.setenv(memory_probe.SUPERVISOR_PID_ENV, "0")+ assert memory_probe._supervisor_pid(lambda pid: pid in alive) is None++ # A pid recycled from a previous run must not silently anchor the walk onto+ # an unrelated tree.+ monkeypatch.setenv(memory_probe.SUPERVISOR_PID_ENV, "999999")+ assert memory_probe._supervisor_pid(lambda pid: pid in alive) is None++ monkeypatch.setenv(memory_probe.SUPERVISOR_PID_ENV, str(os.getpid()))+ assert memory_probe._supervisor_pid(lambda pid: pid in alive) == os.getpid()+++def test_classify_never_echoes_the_command_line() -> None:+ label = memory_probe._classify(+ pid=os.getpid() + 1,+ name="node",+ cmdline="node server.js --token sk-secret-value",+ )++ assert label == "web"+ assert "sk-secret" not in label+++def test_classify_maps_roles_and_falls_back_to_the_executable_name() -> None:+ self_pid = os.getpid()+ other = self_pid + 1++ assert memory_probe._classify(self_pid, "python3.11", "uvicorn") == "backend"+ assert memory_probe._classify(other, "python", "-m uvicorn deeptutor.api.main:app") == "backend"+ assert memory_probe._classify(other, "pocketbase", "serve") == "pocketbase"+ assert memory_probe._classify(other, "bwrap", "sandbox runner") == "sandbox"+ assert memory_probe._classify(other, "mineru-worker", "") == "mineru-worker"+ assert memory_probe._classify(other, "", "") == "process"+++def test_classify_names_the_tree_root_by_pid_not_by_argv() -> None:+ """The supervisor runs as a bare `deeptutor` script — argv has nothing to match."""+ root = os.getpid() + 1++ assert memory_probe._classify(root, "python3.11", "/usr/bin/deeptutor", root_pid=root) == (+ "supervisor"+ )+ # Without the anchor there is no root to name, so it falls back to the name.+ assert memory_probe._classify(root, "python3.11", "/usr/bin/deeptutor") == "python3.11"+ # This process stays "backend" even when it is also the root of the walk.+ assert memory_probe._classify(os.getpid(), "python", "", root_pid=os.getpid()) == "backend"+++def test_cgroup_limit_reads_v2(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ (tmp_path / "memory.max").write_text("2147483648\n", encoding="utf-8")+ (tmp_path / "memory.current").write_text("536870912\n", encoding="utf-8")+ monkeypatch.setattr(memory_probe, "_CGROUP_V2_MAX", tmp_path / "memory.max")+ monkeypatch.setattr(memory_probe, "_CGROUP_V2_CURRENT", tmp_path / "memory.current")++ assert memory_probe._cgroup_limit() == (2147483648, 536870912)+++def test_cgroup_limit_treats_unlimited_as_absent(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ # cgroup v2 writes the literal word; v1 writes a near-max sentinel.+ (tmp_path / "memory.max").write_text("max\n", encoding="utf-8")+ (tmp_path / "limit_in_bytes").write_text(f"{1 << 63}\n", encoding="utf-8")+ monkeypatch.setattr(memory_probe, "_CGROUP_V2_MAX", tmp_path / "memory.max")+ monkeypatch.setattr(memory_probe, "_CGROUP_V2_CURRENT", tmp_path / "missing")+ monkeypatch.setattr(memory_probe, "_CGROUP_V1_LIMIT", tmp_path / "limit_in_bytes")+ monkeypatch.setattr(memory_probe, "_CGROUP_V1_USAGE", tmp_path / "missing")++ assert memory_probe._cgroup_limit() is None+++def test_container_limit_wins_over_host_ram(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Inside a container the host's RAM is the wrong denominator."""+ monkeypatch.setattr(memory_probe, "_cgroup_limit", lambda: (4 * 1024**3, 1024**3))+ monkeypatch.setattr(memory_probe, "_host_memory", lambda _psutil: (64 * 1024**3, 32 * 1024**3))++ snapshot = memory_probe.capture()++ assert snapshot.limit_source == "cgroup"+ assert snapshot.limit_bytes == 4 * 1024**3+ assert snapshot.available_bytes == 3 * 1024**3+++def test_host_ram_used_when_cgroup_limit_exceeds_it(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """An uncapped cgroup often reports a limit larger than physical RAM."""+ monkeypatch.setattr(memory_probe, "_cgroup_limit", lambda: (128 * 1024**3, 1024**3))+ monkeypatch.setattr(memory_probe, "_host_memory", lambda _psutil: (16 * 1024**3, 8 * 1024**3))++ snapshot = memory_probe.capture()++ assert snapshot.limit_source == "host"+ assert snapshot.limit_bytes == 16 * 1024**3+++def test_usage_ratio_is_none_without_a_denominator(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(memory_probe, "_cgroup_limit", lambda: None)+ monkeypatch.setattr(memory_probe, "_host_memory", lambda _psutil: (None, None))++ snapshot = memory_probe.capture()++ assert snapshot.limit_source == "unknown"+ assert snapshot.usage_ratio is None+++def test_capture_falls_back_to_proc_without_psutil(monkeypatch: pytest.MonkeyPatch) -> None:+ if not sys.platform.startswith("linux"):+ pytest.skip("the /proc fallback only applies to Linux")+ monkeypatch.setattr(memory_probe, "_load_psutil", lambda: None)++ snapshot = memory_probe.capture()++ assert snapshot.total_rss_bytes > 0+ assert any(p.pid == os.getpid() for p in snapshot.processes)+++def test_capture_is_empty_when_no_backend_is_available(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(memory_probe, "_load_psutil", lambda: None)+ monkeypatch.setattr(memory_probe.sys, "platform", "darwin")++ snapshot = memory_probe.capture()++ assert snapshot.processes == ()+ assert snapshot.total_rss_bytes == 0diff --git a/tests/services/partners/test_partner_runtime.py b/tests/services/partners/test_partner_runtime.pyindex e46012ca8..4529ccfb7 100644--- a/tests/services/partners/test_partner_runtime.py+++ b/tests/services/partners/test_partner_runtime.py@@ -48,6 +48,22 @@ def _finish(text: str) -> list[StreamEvent]:]+def _answer_visible_narration(call_id: str, text: str) -> list[StreamEvent]:+ return [+ _event(StreamEventType.CONTENT, content=text, metadata={"call_id": call_id}),+ _event(+ StreamEventType.PROGRESS,+ metadata={+ "trace_kind": "call_status",+ "call_state": "complete",+ "call_role": "narration",+ "answer_visible": True,+ "call_id": call_id,+ },+ ),+ ]++class _FakeOrchestrator:"""Yields a scripted event sequence instead of running the chat loop."""@@ -136,6 +152,45 @@ class TestTurnExecution:assert progress.metadata["_progress"] is Trueassert progress.metadata["_tool_hint"] is False+ @pytest.mark.asyncio+ async def test_answer_visible_narration_stays_in_reply(self, partners_root, fake_orchestrator):+ fake_orchestrator.script = _answer_visible_narration(+ "c1", "Great job on that answer."+ ) + _finish("Choose the next topic.")+ runner = _runner(partners_root)++ final = await runner.process_message(_msg())++ assert final == "Great job on that answer.\n\nChoose the next topic."+ assert runner.bus.outbound.empty()++ @pytest.mark.asyncio+ async def test_answer_visible_prefix_is_not_duplicated_when_result_is_canonical(+ self, partners_root, fake_orchestrator+ ):+ fake_orchestrator.script = _answer_visible_narration("c1", "Part one. ") + [+ _event(StreamEventType.CONTENT, content="Part two.", metadata={"call_id": "c2"}),+ _event(+ StreamEventType.PROGRESS,+ metadata={+ "trace_kind": "call_status",+ "call_state": "complete",+ "call_role": "finish",+ "call_id": "c2",+ },+ ),+ _event(+ StreamEventType.RESULT,+ metadata={"response": "Part one. Part two."},+ ),+ ]+ runner = _runner(partners_root)++ final = await runner.process_message(_msg())++ assert final == "Part one. Part two."+ assert runner.bus.outbound.empty()+@pytest.mark.asyncioasync def test_tool_calls_stream_as_hints_by_default(self, partners_root, fake_orchestrator):fake_orchestrator.script = [diff --git a/tests/services/rag/test_lightrag_pipeline.py b/tests/services/rag/test_lightrag_pipeline.pyindex 49a9c621b..59fdb3cbf 100644--- a/tests/services/rag/test_lightrag_pipeline.py+++ b/tests/services/rag/test_lightrag_pipeline.py@@ -10,10 +10,13 @@ index/search orchestration without the heavy deps.from __future__ import annotationsimport asyncio+import contextvarsimport inspectimport jsonfrom pathlib import Pathimport sys+import threading+import timeimport typesimport pytest@@ -28,6 +31,7 @@ from deeptutor.services.rag.index_versioning import resolve_storage_dir_for_readfrom deeptutor.services.rag.pipelines.lightrag import config as lr_configfrom deeptutor.services.rag.pipelines.lightrag import engine, storagefrom deeptutor.services.rag.pipelines.lightrag.pipeline import LightRagPipeline+from deeptutor.services.rag.pipelines.lightrag.worker import run_in_worker_loop# --------------------------------------------------------------------------- ## factory routing + config@@ -157,6 +161,15 @@ class _FakeEmbeddingFunc:self.model_name = model_name+class _RecordingBridge:+ def __init__(self) -> None:+ self.calls = 0++ async def run(self, factory):+ self.calls += 1+ return await factory()++def _install_fake_lightrag(monkeypatch) -> None:fake_lightrag = types.ModuleType("lightrag")fake_utils = types.ModuleType("lightrag.utils")@@ -191,12 +204,14 @@ def test_embedding_func_returns_numpy_array(monkeypatch) -> None:monkeypatch.setattr("deeptutor.services.embedding.get_embedding_config", lambda: _Config())monkeypatch.setattr("deeptutor.services.embedding.get_embedding_client", lambda: _Client())- embedding = lr_config.build_embedding_func()+ bridge = _RecordingBridge()+ embedding = lr_config.build_embedding_func(io_bridge=bridge)vectors = asyncio.run(embedding.func(["a", "b"]))assert embedding.embedding_dim == 3assert embedding.max_token_size == 99assert vectors.shape == (2, 3)assert hasattr(vectors, "size")+ assert bridge.calls == 1def test_embedding_func_maps_lightrag_query_and_document_context(monkeypatch) -> None:@@ -245,7 +260,8 @@ def test_lightrag_llm_adapter_preserves_messages_and_drops_extra_kwargs(monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())- func = lr_config.build_llm_model_func()+ bridge = _RecordingBridge()+ func = lr_config.build_llm_model_func(io_bridge=bridge)result = asyncio.run(func("",@@ -265,6 +281,7 @@ def test_lightrag_llm_adapter_preserves_messages_and_drops_extra_kwargs(assert "response_format" not in capturedassert "hashing_kv" not in capturedassert "keyword_extraction" not in captured+ assert bridge.calls == 1def test_lightrag_vision_adapter_preserves_messages(monkeypatch) -> None:@@ -281,7 +298,8 @@ def test_lightrag_vision_adapter_preserves_messages(monkeypatch) -> None:monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())- func = lr_config.build_vision_model_func()+ bridge = _RecordingBridge()+ func = lr_config.build_vision_model_func(io_bridge=bridge)result = asyncio.run(func("",@@ -294,6 +312,7 @@ def test_lightrag_vision_adapter_preserves_messages(monkeypatch) -> None:assert captured["prompt"] == ""assert captured["image_data"] == "abc123"assert captured["messages"] == [{"role": "user", "content": [{"type": "text", "text": "hi"}]}]+ assert bridge.calls == 1def test_build_rag_skips_raganything_parser_install_check(monkeypatch) -> None:@@ -390,7 +409,7 @@ def _force_available(monkeypatch, available: bool = True) -> None:def _stub_engine(monkeypatch, answer: str = "ANSWER") -> list[dict]:"""Stub the engine so insert writes a readiness marker and query echoes."""inserts: list[dict] = []- monkeypatch.setattr(engine, "build_rag", lambda wd: _FakeRag(wd))+ monkeypatch.setattr(engine, "build_rag", lambda wd, **_: _FakeRag(wd))async def fake_insert(rag, content_list, *, file_name, doc_id):inserts.append({"file": file_name, "doc_id": doc_id, "blocks": content_list})@@ -433,6 +452,185 @@ def _stub_parse(monkeypatch, *, blocks=None, markdown: str = "# md") -> None:monkeypatch.setattr("deeptutor.services.parsing.get_parse_service", lambda: _Service())+def test_indexing_isolated_from_owner_loop_with_context_and_progress(tmp_path, monkeypatch) -> None:+ """Regression for #761: local JSON work must not stall service I/O."""+ from deeptutor.services.parsing.types import ParsedDocument++ request_scope = contextvars.ContextVar("lightrag_test_scope", default="missing")+ captured: dict[str, object] = {"inserts": [], "progress": [], "parse_threads": []}++ class _ParseService:+ def parse(self, path, **_):+ captured["parse_threads"].append(threading.get_ident())+ source = Path(path)+ return ParsedDocument(+ markdown="",+ blocks=[{"type": "text", "text": source.stem, "page_idx": 0}],+ source_hash=f"hash-{source.stem}",+ engine="fake",+ )++ class _BlockingRag:+ def __init__(self, working_dir, io_bridge) -> None:+ self.working_dir = Path(working_dir)+ self.io_bridge = io_bridge++ async def insert_content_list(self, *, content_list, file_path, doc_id):+ captured["worker_thread"] = threading.get_ident()+ captured["worker_context"] = request_scope.get()+ captured["block_started_at"] = time.monotonic()+ time.sleep(0.15)++ async def fake_network_io():+ captured["io_thread"] = threading.get_ident()+ captured["io_context"] = request_scope.get()+ return "io-ok"++ captured["io_result"] = await self.io_bridge.run(fake_network_io)+ captured["inserts"].append(+ {"content_list": content_list, "file_path": file_path, "doc_id": doc_id}+ )+ self.working_dir.mkdir(parents=True, exist_ok=True)+ (self.working_dir / "kv_store_doc_status.json").write_text(+ json.dumps(+ {+ doc_id: {+ "status": "processed",+ "file_path": file_path,+ "chunks_list": ["chunk-1"],+ }+ }+ ),+ encoding="utf-8",+ )++ def fake_build_rag(working_dir, *, io_bridge):+ captured["build_thread"] = threading.get_ident()+ return _BlockingRag(working_dir, io_bridge)++ monkeypatch.setattr("deeptutor.services.parsing.get_parse_service", lambda: _ParseService())+ monkeypatch.setattr(engine, "build_rag", fake_build_rag)+ _force_available(monkeypatch, True)++ docs = [tmp_path / "one.pdf", tmp_path / "two.pdf"]+ for doc in docs:+ doc.write_bytes(b"%PDF")++ async def scenario() -> bool:+ owner_thread = threading.get_ident()+ captured["owner_thread"] = owner_thread+ request_scope.set("user-761")++ async def on_progress(current: int, total: int) -> None:+ await asyncio.sleep(0)+ captured["progress"].append(+ (current, total, threading.get_ident(), request_scope.get())+ )++ async def heartbeat() -> None:+ while "block_started_at" not in captured:+ await asyncio.sleep(0)+ await asyncio.sleep(0.01)+ captured["heartbeat_at"] = time.monotonic()++ pipe = LightRagPipeline(kb_base_dir=str(tmp_path))+ indexing = asyncio.create_task(+ pipe.initialize("kb", [str(doc) for doc in docs], progress_callback=on_progress)+ )+ pulse = asyncio.create_task(heartbeat())+ result = await indexing+ await pulse+ return result++ assert asyncio.run(scenario()) is True+ owner_thread = captured["owner_thread"]+ assert captured["build_thread"] != owner_thread+ assert captured["worker_thread"] != owner_thread+ assert set(captured["parse_threads"]) == {captured["worker_thread"]}+ assert captured["io_thread"] == owner_thread+ assert captured["worker_context"] == "user-761"+ assert captured["io_context"] == "user-761"+ assert captured["io_result"] == "io-ok"+ assert captured["heartbeat_at"] - captured["block_started_at"] < 0.1+ assert captured["progress"] == [+ (1, 2, owner_thread, "user-761"),+ (2, 2, owner_thread, "user-761"),+ ]+ assert captured["inserts"] == [+ {+ "content_list": [{"type": "text", "text": "one", "page_idx": 0}],+ "file_path": "one.pdf",+ "doc_id": "hash-one",+ },+ {+ "content_list": [{"type": "text", "text": "two", "page_idx": 0}],+ "file_path": "two.pdf",+ "doc_id": "hash-two",+ },+ ]+++def test_indexing_worker_exception_propagates_unchanged(tmp_path, monkeypatch) -> None:+ class _IndexingFailure(RuntimeError):+ pass++ class _FailingRag:+ def __init__(self, working_dir) -> None:+ self.working_dir = Path(working_dir)++ async def insert_content_list(self, **_):+ raise _IndexingFailure("nano-vdb merge failed")++ monkeypatch.setattr(engine, "build_rag", lambda wd, **_: _FailingRag(wd))+ _stub_parse(monkeypatch, blocks=[{"type": "text", "text": "x", "page_idx": 0}])+ _force_available(monkeypatch, True)+ document = tmp_path / "bad.pdf"+ document.write_bytes(b"%PDF")++ pipe = LightRagPipeline(kb_base_dir=str(tmp_path))+ with pytest.raises(_IndexingFailure, match="nano-vdb merge failed"):+ asyncio.run(pipe.initialize("kb", [str(document)]))+++def test_indexing_cancellation_waits_for_worker_loop_to_close() -> None:+ started = threading.Event()+ stopped = threading.Event()+ owner_callback_called = False+ worker_loop: asyncio.AbstractEventLoop | None = None++ async def scenario() -> None:+ async def job(io_bridge) -> None:+ nonlocal owner_callback_called, worker_loop+ worker_loop = asyncio.get_running_loop()+ started.set()+ try:+ # Stand in for an uninterruptible synchronous NanoVectorDB+ # flush. Cancellation is observed at the next bridge call.+ time.sleep(0.05)++ def owner_callback() -> None:+ nonlocal owner_callback_called+ owner_callback_called = True++ await io_bridge.call(owner_callback)+ finally:+ stopped.set()++ task = asyncio.create_task(run_in_worker_loop(job))+ while not started.is_set():+ await asyncio.sleep(0)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ asyncio.run(scenario())++ assert stopped.is_set()+ assert worker_loop is not None+ assert worker_loop.is_closed()+ assert owner_callback_called is False++def test_initialize_requires_lightrag(tmp_path, monkeypatch) -> None:_force_available(monkeypatch, False)pipe = LightRagPipeline(kb_base_dir=str(tmp_path))@@ -488,7 +686,7 @@ def test_initialize_no_content_returns_false(tmp_path, monkeypatch) -> None:def test_initialize_fails_when_lightrag_records_doc_failure(tmp_path, monkeypatch) -> None:_force_available(monkeypatch, True)- monkeypatch.setattr(engine, "build_rag", lambda wd: _FakeRag(wd))+ monkeypatch.setattr(engine, "build_rag", lambda wd, **_: _FakeRag(wd))async def fake_insert(rag, content_list, *, file_name, doc_id):(rag.working_dir / "kv_store_doc_status.json").write_text(diff --git a/tests/services/session/test_turn_runtime.py b/tests/services/session/test_turn_runtime.pyindex 9c87c666c..136020955 100644--- a/tests/services/session/test_turn_runtime.py+++ b/tests/services/session/test_turn_runtime.py@@ -6,6 +6,7 @@ import pytestfrom deeptutor.core.stream import StreamEvent, StreamEventTypefrom deeptutor.services.session.turn_runtime import (+ _assemble_persisted_answer,_clip_text,_extract_followup_question_context,_extract_memory_references,@@ -86,6 +87,19 @@ class TestNarrationMarkerCallId:)assert _narration_marker_call_id(event) is None+ def test_dsml_clean_content_is_kept_in_persisted_answer(self) -> None:+ event = StreamEvent(+ type=StreamEventType.PROGRESS,+ metadata={+ "call_id": "round-dsml",+ "trace_kind": "call_status",+ "call_state": "complete",+ "call_role": "narration",+ "answer_visible": True,+ },+ )+ assert _narration_marker_call_id(event) is None+def test_running_status_is_not_narration(self) -> None:event = StreamEvent(type=StreamEventType.PROGRESS,@@ -99,6 +113,24 @@ class TestNarrationMarkerCallId:assert _narration_marker_call_id(event) is None+class TestAssemblePersistedAnswer:+ def test_continuation_preserves_exact_visible_boundary(self) -> None:+ segments = [+ ("round-part-1", "Part one. "),+ ("round-part-2", "Part two."),+ ]++ assert _assemble_persisted_answer(segments, set()) == "Part one. Part two."++ def test_trace_only_narration_is_still_excluded(self) -> None:+ segments = [+ ("search-round", "Searching."),+ ("finish-round", "Answer."),+ ]++ assert _assemble_persisted_answer(segments, {"search-round"}) == "Answer."++# ---------------------------------------------------------------------------# _clip_text# ---------------------------------------------------------------------------diff --git a/web/components/chat/home/TracePanels.tsx b/web/components/chat/home/TracePanels.tsxindex 368d4c712..4fba7737b 100644--- a/web/components/chat/home/TracePanels.tsx+++ b/web/components/chat/home/TracePanels.tsx@@ -36,6 +36,9 @@ type TraceMetadata = {// The "finish" marker is the signal that the turn entered its final// answer phase.call_role?: string;+ // A tool-calling round can explicitly keep its content in the answer rather+ // than demoting it to trace-only narration.+ answer_visible?: boolean;// Set by the chat pipeline on the final iteration's reasoning sub-trace.// Marks "this sub-trace's text has been re-emitted as the final-response// CONTENT event in the same turn, so don't render it as a duplicate row."@@ -591,7 +594,8 @@ function isNarrationRound(events: StreamEvent[]): boolean {return (meta.trace_kind === "call_status" &&meta.call_state === "complete" &&- meta.call_role === "narration"+ meta.call_role === "narration" &&+ meta.answer_visible !== true);});}diff --git a/web/components/settings/MemoryUsageItem.tsx b/web/components/settings/MemoryUsageItem.tsxnew file mode 100644index 000000000..88f69f0f0--- /dev/null+++ b/web/components/settings/MemoryUsageItem.tsx@@ -0,0 +1,178 @@+"use client";++import { Fragment, useCallback, useEffect, useState } from "react";+import { useTranslation } from "react-i18next";++import { apiFetch, apiUrl } from "@/lib/api";+import { StatusStripDivider } from "@/components/settings/shared";++/**+ * Live resident-memory readout — the whole point of the settings status strip+ * now that the model/search items moved into their own pages.+ *+ * Backed by `/api/v1/system/memory` (deeptutor/runtime/memory_probe.py), which+ * walks the whole DeepTutor process tree — backend, the Next.js server, and+ * whatever sandboxes and subagent CLIs are alive — rather than just this+ * process. Its own endpoint, not part of `/system/status`: that snapshot+ * resolves model configs and is fetched once per mount, while this polls.+ *+ * Everything is inline rather than behind a hover: the per-process split is+ * the number you actually want when watching memory move, and hiding it makes+ * you chase a tooltip while the value changes underneath you.+ *+ * The endpoint answers `{available: false}` for non-admins and on platforms+ * where the tree can't be read, and this renders nothing in that case.+ */++const POLL_MS = 10_000;++/** One role in the tree; `count` collapses e.g. three live sandboxes into a row. */+interface MemoryProcess {+ label: string;+ count: number;+ rss_bytes: number;+}++interface MemoryUsage {+ available: boolean;+ total_rss_bytes?: number;+ limit_bytes?: number | null;+ available_bytes?: number | null;+ limit_source?: string;+ usage_ratio?: number | null;+ partial?: boolean;+ processes?: MemoryProcess[];+}++function formatBytes(bytes: number | null | undefined): string {+ if (bytes == null) return "—";+ if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;+ return `${Math.round(bytes / 1024 ** 2)} MB`;+}++/** Green under two thirds, amber past it, red once the OOM killer is plausible. */+function pressureDotClass(ratio: number | null | undefined): string {+ if (ratio == null) return "bg-emerald-500";+ if (ratio >= 0.9) return "bg-red-400";+ if (ratio >= 0.7) return "bg-amber-400";+ return "bg-emerald-500";+}++export default function MemoryUsageItem() {+ const { t } = useTranslation();+ const [usage, setUsage] = useState<MemoryUsage | null>(null);++ const roleLabel = useCallback(+ (row: MemoryProcess) => {+ const known: Record<string, string> = {+ backend: t("Backend"),+ web: t("Frontend"),+ sandbox: t("Sandbox"),+ supervisor: t("Supervisor"),+ other: t("Other"),+ };+ const name = known[row.label] ?? row.label;+ return row.count > 1 ? `${name} ×${row.count}` : name;+ },+ [t],+ );++ useEffect(() => {+ let cancelled = false;+ let timer: ReturnType<typeof setTimeout> | null = null;++ const poll = async () => {+ try {+ const res = await apiFetch(apiUrl("/api/v1/system/memory"));+ if (cancelled) return;+ if (res.ok) setUsage((await res.json()) as MemoryUsage);+ } catch {+ // A failed probe is not worth a console entry every 10s; the strip+ // simply keeps the last reading until the next poll succeeds.+ }+ if (!cancelled) timer = setTimeout(poll, POLL_MS);+ };++ // Polling a hidden tab burns a request per user per 10s for a number+ // nobody is looking at; resume with an immediate read so the value is+ // fresh the moment the tab comes back.+ const onVisibility = () => {+ if (document.hidden) {+ if (timer) clearTimeout(timer);+ timer = null;+ } else if (timer === null) {+ void poll();+ }+ };++ void poll();+ document.addEventListener("visibilitychange", onVisibility);+ return () => {+ cancelled = true;+ if (timer) clearTimeout(timer);+ document.removeEventListener("visibilitychange", onVisibility);+ };+ }, []);++ if (!usage?.available) return null;++ const ratio = usage.usage_ratio ?? null;+ const percent = ratio == null ? null : Math.max(Math.round(ratio * 100), 1);+ const used = formatBytes(usage.total_rss_bytes);+ const summary =+ percent == null || !usage.limit_bytes+ ? used+ : t("{{used}} · {{percent}}% of {{total}}", {+ used,+ percent,+ total: formatBytes(usage.limit_bytes),+ });++ return (+ <Fragment>+ <StatusStripDivider />+ <div className="flex items-center gap-2.5">+ <span+ className={`h-2 w-2 shrink-0 rounded-full ${pressureDotClass(ratio)}`}+ />+ <div className="flex items-baseline gap-2">+ <span className="text-[13px] font-medium leading-none tracking-tight text-[var(--foreground)]">+ {t("Memory")}+ </span>+ <span className="text-[12px] leading-none tabular-nums text-[var(--muted-foreground)]">+ {summary}+ </span>+ </div>+ </div>++ <StatusStripDivider />+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1.5 text-[12px] leading-none text-[var(--muted-foreground)]">+ {(usage.processes ?? []).map((row) => (+ <span key={row.label} className="tabular-nums">+ {roleLabel(row)}{" "}+ <span className="text-[var(--foreground)]/70">+ {formatBytes(row.rss_bytes)}+ </span>+ </span>+ ))}+ <span className="tabular-nums">+ {usage.limit_source === "cgroup"+ ? t("Container available")+ : t("System available")}{" "}+ <span className="text-[var(--foreground)]/70">+ {formatBytes(usage.available_bytes)}+ </span>+ </span>+ {usage.partial && (+ <span+ title={t(+ "Only the backend and its own children. Start DeepTutor through the launcher to include the web server.",+ )}+ >+ {t("(backend only)")}+ </span>+ )}+ </div>+ </Fragment>+ );+}diff --git a/web/components/settings/SettingsStatusPanel.tsx b/web/components/settings/SettingsStatusPanel.tsxindex bfd62553f..673ccd184 100644--- a/web/components/settings/SettingsStatusPanel.tsx+++ b/web/components/settings/SettingsStatusPanel.tsx@@ -1,16 +1,19 @@"use client";-import { Fragment } from "react";import { useTranslation } from "react-i18next";+import MemoryUsageItem from "@/components/settings/MemoryUsageItem";import { useSettings } from "@/components/settings/SettingsContext";import { statusDotClass } from "@/components/settings/shared";/*** Resident status module on the settings hub — the old `/settings/status` page- * demoted to an always-visible strip. Reads the runtime `/system/status`- * snapshot (available to every user, unlike the editable catalog), so it- * reflects what is actually running rather than the draft.+ * demoted to an always-visible strip.+ *+ * Scope is deliberately narrow: is the backend up, and what is it costing.+ * The LLM / embedding / search items that used to sit here restated what the+ * Models and Chat pages already own, so the strip now carries only the two+ * runtime facts no settings page shows.** Compact, left-aligned, hairline-separated items — no stretched grid or* uppercase eyebrow (CJK reads badly with letter-spacing).@@ -19,75 +22,27 @@ export default function SettingsStatusPanel() {const { t } = useTranslation();const { status } = useSettings();- const items = [- {- key: "backend",- name: t("Backend"),- configured: status?.backend.status === "online",- hasError: false,- value: status- ? status.backend.status === "online"- ? t("Online")- : t("Checking")- : t("Checking"),- },- {- key: "llm",- name: t("LLM"),- configured: Boolean(status?.llm.model),- hasError: Boolean(status?.llm.error),- value: status?.llm.model || t("Not set"),- },- {- key: "embedding",- name: t("Embedding"),- configured: Boolean(status?.embeddings.model),- hasError: Boolean(status?.embeddings.error),- value: status?.embeddings.model || t("Not set"),- },- {- key: "search",- name: t("Search"),- configured: Boolean(status?.search.provider),- hasError: Boolean(status?.search.error),- value: status?.search.provider || t("Not set"),- },- ];+ const online = status?.backend.status === "online";return (<sectiondata-tour="tour-status"className="flex flex-wrap items-center gap-x-5 gap-y-2.5 rounded-2xl border border-[var(--border)]/70 bg-[var(--card)]/50 px-5 py-3.5">- {items.map((item, i) => (- <Fragment key={item.key}>- {i > 0 && (- <span- aria-hidden- className="hidden h-7 w-px shrink-0 bg-[var(--border)]/70 sm:block"- />- )}- <div className="flex items-center gap-2.5">- <span- className={`h-2 w-2 shrink-0 rounded-full ${statusDotClass(- item.configured,- item.hasError,- )}`}- />- <div className="flex items-baseline gap-2">- <span className="text-[13px] font-medium leading-none tracking-tight text-[var(--foreground)]">- {item.name}- </span>- <span- className="max-w-[220px] truncate text-[12px] leading-none text-[var(--muted-foreground)]"- title={item.value}- >- {item.value}- </span>- </div>- </div>- </Fragment>- ))}+ <div className="flex items-center gap-2.5">+ <span+ className={`h-2 w-2 shrink-0 rounded-full ${statusDotClass(online, false)}`}+ />+ <div className="flex items-baseline gap-2">+ <span className="text-[13px] font-medium leading-none tracking-tight text-[var(--foreground)]">+ {t("Backend")}+ </span>+ <span className="text-[12px] leading-none text-[var(--muted-foreground)]">+ {online ? t("Online") : t("Checking")}+ </span>+ </div>+ </div>+ <MemoryUsageItem /></section>);}diff --git a/web/components/settings/shared.tsx b/web/components/settings/shared.tsxindex 14796d82b..b5a976910 100644--- a/web/components/settings/shared.tsx+++ b/web/components/settings/shared.tsx@@ -48,6 +48,21 @@ export function statusDotClass(configured: boolean, hasError: boolean): string {return "bg-[var(--border)]";}+/**+ * Hairline between two items of the settings status strip. Lives here rather+ * than inside the strip because items that can render nothing (MemoryUsageItem)+ * have to draw their own leading rule — otherwise hiding the item leaves a+ * dangling separator behind.+ */+export function StatusStripDivider() {+ return (+ <span+ aria-hidden+ className="hidden h-7 w-px shrink-0 bg-[var(--border)]/70 sm:block"+ />+ );+}+export function formatContextWindowSource(source: string | undefined,t: (key: string) => string,diff --git a/web/lib/stream.ts b/web/lib/stream.tsindex 48412517c..47283dc9d 100644--- a/web/lib/stream.ts+++ b/web/lib/stream.ts@@ -5,6 +5,7 @@ type ContentMeta = {call_kind?: string;call_state?: string;call_role?: string;+ answer_visible?: boolean;trace_kind?: string;};@@ -30,6 +31,7 @@ export function shouldAppendEventContent(event: StreamEvent): boolean {* call_ids whose round resolved as "narration" — a short preamble the chat* loop streamed alongside a tool call. That text belongs to the trace, not* the answer, so it is excluded once the round's call_status marker arrives.+ * DSML rounds can explicitly preserve cleaned prose that surrounded a call.*/export function collectNarrationCallIds(events: StreamEvent[]): Set<string> {const ids = new Set<string>();@@ -39,6 +41,7 @@ export function collectNarrationCallIds(events: StreamEvent[]): Set<string> {meta.trace_kind === "call_status" &&meta.call_state === "complete" &&meta.call_role === "narration" &&+ meta.answer_visible !== true &&meta.call_id) {ids.add(meta.call_id);@@ -47,13 +50,14 @@ export function collectNarrationCallIds(events: StreamEvent[]): Set<string> {return ids;}-/** True for the per-round marker that flips a round to "narration". */+/** True for a per-round marker that demotes its content to narration. */export function isNarrationMarker(event: StreamEvent): boolean {const meta = eventMeta(event);return (meta.trace_kind === "call_status" &&meta.call_state === "complete" &&- meta.call_role === "narration"+ meta.call_role === "narration" &&+ meta.answer_visible !== true);}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 1eb4f3de1..ff90b5cf9 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -1173,7 +1173,7 @@"settingsTour.appearance.title": "Appearance","settingsTour.appearance.desc": "Visual theme and interface language. Changes apply immediately.","settingsTour.status.title": "Status",- "settingsTour.status.desc": "Runtime state of the backend and your configured model services — always visible here on the hub.",+ "settingsTour.status.desc": "Whether the backend is up and what the running DeepTutor processes cost in memory — always visible here on the hub.","settingsTour.network.title": "Network","settingsTour.network.desc": "Ports, the browser-facing API base, and CORS origins — for Docker, LAN, and reverse-proxy deployments.","settingsTour.models.title": "Models",@@ -2919,5 +2919,14 @@"Running {{app}}": "Running {{app}}","Product names and logos are trademarks of their respective owners, shown for identification only.": "Product names and logos are trademarks of their respective owners, shown for identification only.","Needs authorization": "Needs authorization",- "Reauthorize": "Reauthorize"+ "Reauthorize": "Reauthorize",+ "Frontend": "Frontend",+ "Sandbox": "Sandbox",+ "Supervisor": "Supervisor",+ "Other": "Other",+ "System available": "System available",+ "Container available": "Container available",+ "{{used}} · {{percent}}% of {{total}}": "{{used}} · {{percent}}% of {{total}}",+ "(backend only)": "(backend only)",+ "Only the backend and its own children. Start DeepTutor through the launcher to include the web server.": "Only the backend and its own children. Start DeepTutor through the launcher to include the web server."}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 56120cfa1..5cec632a7 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -1205,7 +1205,7 @@"settingsTour.appearance.title": "外观","settingsTour.appearance.desc": "选择视觉主题和界面语言,改动立即生效。","settingsTour.status.title": "状态",- "settingsTour.status.desc": "后端与已配置模型服务的运行状态,常驻主页一目了然。",+ "settingsTour.status.desc": "后端是否在线,以及 DeepTutor 各进程当前占用的内存,常驻主页一目了然。","settingsTour.network.title": "网络","settingsTour.network.desc": "端口、浏览器访问后端的 API 地址与 CORS 来源——Docker、局域网、反向代理部署在这里配。","settingsTour.models.title": "模型",@@ -2919,5 +2919,14 @@"Running {{app}}": "运行 {{app}}","Product names and logos are trademarks of their respective owners, shown for identification only.": "产品名称与标识为其各自所有者的商标,此处仅用于标识。","Needs authorization": "待授权",- "Reauthorize": "重新授权"+ "Reauthorize": "重新授权",+ "Frontend": "前端",+ "Sandbox": "沙箱",+ "Supervisor": "主进程",+ "Other": "其他",+ "System available": "系统可用",+ "Container available": "容器可用",+ "{{used}} · {{percent}}% of {{total}}": "{{used}} · 占 {{total}} 的 {{percent}}%",+ "(backend only)": "(仅后端)",+ "Only the backend and its own children. Start DeepTutor through the launcher to include the web server.": "仅统计后端及其子进程。通过 DeepTutor 启动器运行才能把前端服务一起算进来。"}diff --git a/web/tests/stream.test.ts b/web/tests/stream.test.tsnew file mode 100644index 000000000..064fba68d--- /dev/null+++ b/web/tests/stream.test.ts@@ -0,0 +1,93 @@+import test from "node:test";+import assert from "node:assert/strict";+import {+ collectNarrationCallIds,+ isNarrationMarker,+ recomputeAnswerContent,+} from "../lib/stream";+import type { StreamEvent } from "../lib/unified-ws";++function event(+ type: StreamEvent["type"],+ content: string,+ metadata: Record<string, unknown>,+): StreamEvent {+ return {+ type,+ source: "chat",+ stage: "responding",+ content,+ metadata,+ session_id: "session-1",+ turn_id: "turn-1",+ seq: 1,+ timestamp: 0,+ };+}++test("ordinary narration is removed from answer content", () => {+ const events = [+ event("content", "Searching.", {+ call_id: "round-1",+ call_kind: "agent_loop_round",+ }),+ event("progress", "", {+ call_id: "round-1",+ trace_kind: "call_status",+ call_state: "complete",+ call_role: "narration",+ }),+ ];++ assert.deepEqual([...collectNarrationCallIds(events)], ["round-1"]);+ assert.equal(isNarrationMarker(events[1]), true);+ assert.equal(recomputeAnswerContent(events), "");+});++test("clean prose surrounding a DSML call remains answer-visible", () => {+ const events = [+ event("content", "Great job! Choose the next topic.", {+ call_id: "round-dsml",+ call_kind: "agent_loop_round",+ }),+ event("progress", "", {+ call_id: "round-dsml",+ trace_kind: "call_status",+ call_state: "complete",+ call_role: "narration",+ answer_visible: true,+ }),+ ];++ assert.deepEqual([...collectNarrationCallIds(events)], []);+ assert.equal(isNarrationMarker(events[1]), false);+ assert.equal(recomputeAnswerContent(events), "Great job! Choose the next topic.");+});++test("token-limit continuation replays the exact visible answer", () => {+ const events = [+ event("content", "Part one. ", {+ call_id: "round-part-1",+ call_kind: "agent_loop_round",+ }),+ event("progress", "", {+ call_id: "round-part-1",+ trace_kind: "call_status",+ call_state: "complete",+ call_role: "narration",+ answer_visible: true,+ }),+ event("content", "Part two.", {+ call_id: "round-part-2",+ call_kind: "agent_loop_round",+ }),+ event("progress", "", {+ call_id: "round-part-2",+ trace_kind: "call_status",+ call_state: "complete",+ call_role: "finish",+ }),+ ];++ assert.equal(recomputeAnswerContent(events), "Part one. Part two.");+});