DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(answer-now): per-capability fast paths instead of forced chat reroute
Bingxi Zhao (Frank)4ef783066c2c
diff --git a/assets/releases/ver1-1-1.md b/assets/releases/ver1-1-1.mdindex 9391206ff..13093269a 100644--- a/assets/releases/ver1-1-1.md+++ b/assets/releases/ver1-1-1.md@@ -4,8 +4,17 @@## Highlights-### Universal "Answer Now" Escape Hatch-Promoted "Answer now" from a chat-only affordance to a universal interrupt that works across every capability. The orchestrator now inspects `config_overrides["answer_now_context"]` and re-routes the turn to `chat._stage_answer_now` regardless of the originally selected capability, so users can short-circuit `deep_solve`, `deep_research`, `math_animator`, etc. and synthesize a final answer from whatever partial trace has streamed so far. The frontend mirrors the contract by forcing the follow-up turn to `chat` and packaging the in-flight assistant content + events into the snapshot. A new `AnswerNowRow` component renders the action inline below the streaming trace panel and disables itself after a single click to prevent duplicate cancel/restart races.+### Universal "Answer Now" Escape Hatch — Per-Capability Fast Paths+Promoted "Answer now" from a chat-only affordance to a universal interrupt that respects each capability's output shape. A new shared helper `deeptutor/capabilities/_answer_now.py` provides the gate (`extract_answer_now_context`) and the prompt-friendly trace summary, and every built-in capability now owns its own fast-path branch at the top of `run()`:++- `chat` — synthesize the final markdown answer from the partial trace (existing behavior).+- `deep_solve` — skip planning + reasoning, jump straight into the writer.+- `deep_question` — skip ideation/templates, emit the full quiz JSON in one structured call (still rendered by `QuizViewer`).+- `deep_research` — skip rephrase/decompose/research, write the report directly from accumulated evidence.+- `math_animator` — skip analysis + design + summary but **keep code generation + render**, so the user still gets a real animation.+- `visualize` — skip analysis + review, emit the final renderable code in one structured call.++Each fast-path preserves the same result envelope as the normal pipeline (so the Quiz / MathAnimator / Visualization viewers render unchanged) and prepends a `> ⚡ Skipped X stage(s)` notice so users know it was a best-effort early exit. The orchestrator no longer re-routes `answer_now` to `chat`; it now keeps `active_capability` and only falls back to `chat` if the originally selected capability has been removed from the registry. The frontend matches: `handleAnswerNow` no longer overrides the snapshot's capability, and a single-shot guarded `AnswerNowRow` component renders the action inline below the streaming trace panel.### Co-Writer — Resizable Split & Line-Anchored Scroll SyncThe Co-Writer page picked up a draggable splitter between the editor and preview panes (with a persisted ratio in `localStorage`) and a true bidirectional scroll-sync that survives soft-wrapped lines. Each preview block now carries a `data-source-line` attribute pointing back at its starting line in the markdown source (provided by remark's AST positions); on the editor side a hidden mirror element mimics the textarea's wrap geometry so we can read the real pixel-`y` of every source line. With both sides expressed as pixel coordinates the sync becomes a single piecewise-linear interpolation in either direction, with a per-source-line cache that invalidates only when the content or wrap width changes.@@ -41,7 +50,7 @@ Backend system messages (e.g. quiz follow-up grounding context written by the tu- **`.env.example_CN`** — removed an accidental `// README` suffix on the provider-list comment.### Test Suite Expansion-Added a new `tests/services/tutorbot/test_manager_config.py` module covering load/save round-trips, the corrupt-yaml fallback, atomic temp-file writes, failure-recovery after a mid-write `OSError`, and all four `merge_bot_config` semantics (no existing config, omitted-field passthrough, `None`-as-not-provided, and empty-value-as-explicit-clear). Extended `tests/api/test_tutorbot_router.py` with the explicit-clear test class, and added an orchestrator routing test (`test_answer_now_context_reroutes_to_chat`) that asserts a `deep_solve` turn is intercepted and handed to the chat capability when `answer_now_context` is present.+Added a new `tests/services/tutorbot/test_manager_config.py` module covering load/save round-trips, the corrupt-yaml fallback, atomic temp-file writes, failure-recovery after a mid-write `OSError`, and all four `merge_bot_config` semantics (no existing config, omitted-field passthrough, `None`-as-not-provided, and empty-value-as-explicit-clear). Extended `tests/api/test_tutorbot_router.py` with the explicit-clear test class. Rewrote the orchestrator answer-now routing tests to pin the new contract — `active_capability` is preserved when `answer_now_context` is set, the orchestrator falls back to `chat` only when the original capability is missing, and emits a clear error when neither is registered. Added a new `tests/capabilities/test_answer_now.py` module with 28 cases covering the shared helpers (`extract_answer_now_context`, `format_trace_summary` truncation/i18n, `make_skip_notice`, `labeled_block`, `join_chunks`) and every per-capability fast-path: `chat`, `deep_solve`, `deep_question` (including the unparseable-JSON fallback), `deep_research`, `visualize` (including code-fence stripping and invalid `render_type` recovery), and `math_animator` (verifying that `run_analysis`/`run_design`/`run_summary` are *not* invoked while `run_code_generation`/`run_render` *are*). A reverse test confirms that capabilities still take their normal pipeline when no `answer_now_context` is present.## Community Contributionsdiff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.pyindex 7b2df7646..26a44eda3 100644--- a/deeptutor/agents/chat/agentic_pipeline.py+++ b/deeptutor/agents/chat/agentic_pipeline.py@@ -945,13 +945,10 @@ class AgenticChatPipeline:@staticmethoddef _extract_answer_now_context(context: UnifiedContext) -> dict[str, Any] | None:- raw = context.config_overrides.get("answer_now_context")- if not isinstance(raw, dict):- return None- original_user_message = str(raw.get("original_user_message") or "").strip()- if not original_user_message:- return None- return raw+ # Delegate to the shared helper so every capability uses the+ # exact same gate (presence + non-empty original_user_message).+ from deeptutor.capabilities._answer_now import extract_answer_now_context+ return extract_answer_now_context(context)async def _execute_tool_call(self,diff --git a/deeptutor/capabilities/_answer_now.py b/deeptutor/capabilities/_answer_now.pynew file mode 100644index 000000000..2bd31126c--- /dev/null+++ b/deeptutor/capabilities/_answer_now.py@@ -0,0 +1,249 @@+"""+Answer-Now Helpers+==================++Per-capability fast-path utilities for the universal "Answer now" interrupt.++Each capability owns *what* its fast path produces (text answer, quiz JSON,+manim code, ...). This module provides the shared plumbing:++* :func:`extract_answer_now_context` — parse and validate the payload that+ the frontend bundled with the cancelled turn.+* :func:`format_trace_summary` — render captured stream events into a+ compact, prompt-friendly summary the LLM can read in one shot.+* :func:`stream_synthesis` — thin async generator wrapper around the LLM+ service that yields text chunks while pushing them into the StreamBus.+* :func:`make_skip_notice` — i18n-aware notice prepended/appended to the+ fast-path output so the user knows which stages were skipped.++The orchestrator no longer re-routes ``answer_now`` to ``chat``; instead+each capability checks for the payload at the top of ``run()`` and+dispatches to its own answer-now path. ``chat`` keeps its original+synthesis behavior; structured-output capabilities (deep_question,+math_animator, visualize) collapse the remaining stages into a single+LLM call (or a code-gen + render pair, in math_animator's case).+"""++from __future__ import annotations++from typing import Any, AsyncIterator++from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.trace import build_trace_metadata, merge_trace_metadata, new_call_id+from deeptutor.services.llm import (+ clean_thinking_tags,+ get_llm_config,+ get_token_limit_kwargs,+ stream as llm_stream,+)+++# Per-event content cap. The trace can grow unbounded (especially for+# deep_research / deep_solve with many tool calls) so we truncate each+# entry rather than the whole transcript — this preserves event+# coverage at the cost of detail per step.+_MAX_EVENT_SNIPPET = 800+# Total trace summary cap. Far above this and we start eating into the+# answer budget on small-context models.+_MAX_TRACE_TOTAL = 6000+++def extract_answer_now_context(context: UnifiedContext) -> dict[str, Any] | None:+ """+ Return the validated ``answer_now_context`` payload or ``None``.++ The frontend always packages ``original_user_message`` + an optional+ ``partial_response`` + an ``events`` array. We require at minimum a+ non-empty ``original_user_message`` because that's what every+ fast-path prompt is anchored on; if it is missing the capability+ falls through to its normal pipeline.+ """+ raw = context.config_overrides.get("answer_now_context")+ if not isinstance(raw, dict):+ return None+ if not str(raw.get("original_user_message") or "").strip():+ return None+ return raw+++def format_trace_summary(events: Any, *, language: str = "en") -> str:+ """Render captured stream events into a compact text summary.++ Truncates each event to ``_MAX_EVENT_SNIPPET`` chars and the whole+ transcript to ``_MAX_TRACE_TOTAL`` chars so the prompt stays bounded.+ """+ fallback = (+ "没有可用的中间执行记录。"+ if language.startswith("zh")+ else "No intermediate execution trace was provided."+ )+ if not isinstance(events, list) or not events:+ return fallback++ lines: list[str] = []+ for index, event in enumerate(events, start=1):+ if not isinstance(event, dict):+ continue+ event_type = str(event.get("type") or "event").strip()+ stage = str(event.get("stage") or "").strip()+ content = str(event.get("content") or "").strip()+ metadata = event.get("metadata") if isinstance(event.get("metadata"), dict) else {}++ label_parts = [event_type]+ if stage:+ label_parts.append(stage)+ line = f"{index}. {' / '.join(label_parts)}"+ if content:+ snippet = (+ content+ if len(content) <= _MAX_EVENT_SNIPPET+ else content[: _MAX_EVENT_SNIPPET - 3].rstrip() + "..."+ )+ line += f": {snippet}"+ if isinstance(metadata, dict):+ tool_name = str(metadata.get("tool_name") or metadata.get("tool") or "").strip()+ if tool_name:+ line += f" [tool={tool_name}]"+ lines.append(line)++ if not lines:+ return fallback++ text = "\n".join(lines)+ if len(text) > _MAX_TRACE_TOTAL:+ text = text[: _MAX_TRACE_TOTAL - 3].rstrip() + "..."+ return text+++def labeled_block(label: str, content: str) -> str:+ """Format a labeled section in a way the LLM reliably picks up."""+ body = content.strip() if isinstance(content, str) and content.strip() else "(empty)"+ return f"[{label}]\n{body}"+++def make_skip_notice(*, capability: str, language: str, stages_skipped: list[str]) -> str:+ """A short user-visible note prepended to the fast-path output.++ Helps the user understand that the result is a "best-effort early+ exit" rather than the full pipeline output.+ """+ if not stages_skipped:+ return ""+ if language.startswith("zh"):+ joined = "、".join(stages_skipped)+ return (+ f"> ⚡ 已跳过 `{capability}` 的 {joined} 阶段,以下为基于已有信息的快速结果。"+ )+ joined = ", ".join(stages_skipped)+ return (+ f"> ⚡ Skipped {joined} stage(s) of `{capability}`; the result below is "+ f"a best-effort synthesis from the partial trace."+ )+++def build_answer_now_trace_metadata(+ *,+ capability: str,+ phase: str,+ label: str,+) -> dict[str, Any]:+ """Standard trace card metadata for an answer-now stage."""+ return build_trace_metadata(+ call_id=new_call_id(f"{capability}-answer-now"),+ phase=phase,+ label=label,+ call_kind="llm_final_response",+ trace_id=f"{capability}-answer-now",+ trace_role="response",+ trace_group="stage",+ )+++async def stream_synthesis(+ *,+ stream: StreamBus,+ source: str,+ stage: str,+ trace_meta: dict[str, Any],+ system_prompt: str,+ user_prompt: str,+ max_tokens: int = 1800,+ push_content: bool = True,+ response_format: dict[str, Any] | None = None,+) -> AsyncIterator[str]:+ """+ Stream a single LLM synthesis call into the StreamBus.++ Yields raw chunks (still useful for capabilities that need to+ parse them, e.g. structured JSON outputs). When ``push_content``+ is true (default), every chunk is also pushed as a ``CONTENT``+ event so the frontend renders the answer live.+ """+ llm_config = get_llm_config()+ model = getattr(llm_config, "model", None)++ await stream.progress(+ trace_meta.get("label", "Answer now"),+ source=source,+ stage=stage,+ metadata=merge_trace_metadata(+ trace_meta,+ {"trace_kind": "call_status", "call_state": "running"},+ ),+ )++ extra_kwargs: dict[str, Any] = {"temperature": 0.2}+ if model:+ extra_kwargs.update(get_token_limit_kwargs(model, max_tokens))+ if response_format is not None:+ extra_kwargs["response_format"] = response_format++ chunks: list[str] = []+ try:+ async for chunk in llm_stream(+ prompt=user_prompt,+ system_prompt=system_prompt,+ **extra_kwargs,+ ):+ if not chunk:+ continue+ chunks.append(chunk)+ if push_content:+ await stream.content(+ chunk,+ source=source,+ stage=stage,+ metadata=merge_trace_metadata(trace_meta, {"trace_kind": "llm_chunk"}),+ )+ yield chunk+ finally:+ await stream.progress(+ "",+ source=source,+ stage=stage,+ metadata=merge_trace_metadata(+ trace_meta,+ {"trace_kind": "call_status", "call_state": "complete"},+ ),+ )+++def join_chunks(chunks: list[str]) -> str:+ """Concatenate chunks and strip OpenAI-style ``<think>`` wrappers."""+ text = "".join(chunks)+ llm_config = get_llm_config()+ binding = getattr(llm_config, "binding", None) or "openai"+ model = getattr(llm_config, "model", None)+ return clean_thinking_tags(text, binding, model)+++__all__ = [+ "build_answer_now_trace_metadata",+ "extract_answer_now_context",+ "format_trace_summary",+ "join_chunks",+ "labeled_block",+ "make_skip_notice",+ "stream_synthesis",+]diff --git a/deeptutor/capabilities/deep_question.py b/deeptutor/capabilities/deep_question.pyindex 0fd5ea03f..df8a1ca0b 100644--- a/deeptutor/capabilities/deep_question.py+++ b/deeptutor/capabilities/deep_question.py@@ -32,9 +32,15 @@ class DeepQuestionCapability(BaseCapability):async def run(self, context: UnifiedContext, stream: StreamBus) -> None:from deeptutor.agents.question.coordinator import AgentCoordinator+ from deeptutor.capabilities._answer_now import extract_answer_now_contextfrom deeptutor.services.llm.config import get_llm_configfrom deeptutor.services.path_service import get_path_service+ answer_now_payload = extract_answer_now_context(context)+ if answer_now_payload is not None:+ await self._run_answer_now(context, stream, answer_now_payload)+ return+llm_config = get_llm_config()kb_name = context.knowledge_bases[0] if context.knowledge_bases else Noneturn_id = str(context.metadata.get("turn_id", "") or context.session_id or "deep-question")@@ -188,6 +194,188 @@ class DeepQuestionCapability(BaseCapability):result_payload["metadata"] = {"cost_summary": cost_meta}await stream.result(result_payload, source=self.name)+ async def _run_answer_now(+ self,+ context: UnifiedContext,+ stream: StreamBus,+ payload: dict[str, Any],+ ) -> None:+ """+ Fast-path for ``deep_question``: skip ideation/template generation+ and synthesise a complete quiz in one structured LLM call.++ The result envelope mirrors the standard pipeline (``summary.results``+ with ``qa_pair`` items) so the existing ``QuizViewer`` renders it+ without changes.+ """+ import json++ from deeptutor.capabilities._answer_now import (+ build_answer_now_trace_metadata,+ format_trace_summary,+ join_chunks,+ labeled_block,+ make_skip_notice,+ stream_synthesis,+ )++ is_zh = context.language.lower().startswith("zh")+ original = str(payload.get("original_user_message") or context.user_message).strip()+ partial = str(payload.get("partial_response") or "").strip()+ trace_summary = format_trace_summary(payload.get("events"), language=context.language)++ overrides = context.config_overrides+ topic = str(overrides.get("topic") or original).strip() or original+ num_questions = max(1, int(overrides.get("num_questions", 1) or 1))+ difficulty = str(overrides.get("difficulty", "") or "auto")+ question_type = str(overrides.get("question_type", "") or "auto")++ if is_zh:+ system_prompt = (+ "你是 DeepTutor 的题目生成器。用户已经在等待,请基于现有信息直接输出一组题目。"+ "严格输出 JSON:{\"questions\": [{\"question_id\": \"q_1\", "+ "\"question\": \"...\", \"question_type\": \"choice|written|coding\", "+ "\"options\": {\"A\": \"...\"}, \"correct_answer\": \"...\", "+ "\"explanation\": \"...\", \"difficulty\": \"...\", "+ "\"concentration\": \"...\"}, ...]}。"+ "若不是 choice 题,options 字段可省略。所有字符串使用 UTF-8。"+ )+ user_prompt = (+ f"用户原始问题/主题:{topic}\n\n"+ f"题量要求:{num_questions}\n"+ f"题型偏好:{question_type}(auto 表示自由选择)\n"+ f"难度偏好:{difficulty}\n\n"+ f"{labeled_block('Current Draft', partial)}\n\n"+ f"{labeled_block('Execution Trace', trace_summary)}\n\n"+ "立即输出符合上述 JSON schema 的题目集合,不要包含其他文字。"+ )+ else:+ system_prompt = (+ "You are DeepTutor's question generator. The user is waiting, "+ "so produce a complete question set in one shot using the "+ "context already gathered. Output strictly the JSON schema "+ "{\"questions\": [{\"question_id\": \"q_1\", \"question\": "+ "\"...\", \"question_type\": \"choice|written|coding\", "+ "\"options\": {\"A\": \"...\"}, \"correct_answer\": \"...\", "+ "\"explanation\": \"...\", \"difficulty\": \"...\", "+ "\"concentration\": \"...\"}, ...]}. Omit ``options`` when the "+ "type is not ``choice``."+ )+ user_prompt = (+ f"Topic: {topic}\n\n"+ f"Number of questions requested: {num_questions}\n"+ f"Preferred type: {question_type} (auto = free choice)\n"+ f"Preferred difficulty: {difficulty}\n\n"+ f"{labeled_block('Current Draft', partial)}\n\n"+ f"{labeled_block('Execution Trace', trace_summary)}\n\n"+ "Emit the JSON object now, no surrounding prose."+ )++ trace_meta = build_answer_now_trace_metadata(+ capability=self.name, phase="generation", label="Answer now"+ )++ notice = make_skip_notice(+ capability=self.name,+ language=context.language,+ stages_skipped=["ideation"],+ )++ chunks: list[str] = []+ async with stream.stage("generation", source=self.name, metadata=trace_meta):+ async for chunk in stream_synthesis(+ stream=stream,+ source=self.name,+ stage="generation",+ trace_meta=trace_meta,+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ max_tokens=2400,+ push_content=False,+ response_format={"type": "json_object"},+ ):+ chunks.append(chunk)++ raw = join_chunks(chunks).strip()+ questions = self._parse_answer_now_json(raw, num_questions=num_questions)++ results = [+ {+ "qa_pair": {+ "question_id": q.get("question_id") or f"q_{idx+1}",+ "question": q.get("question", ""),+ "question_type": q.get("question_type", "written"),+ "options": q.get("options") or {},+ "correct_answer": q.get("correct_answer", ""),+ "explanation": q.get("explanation", ""),+ "difficulty": q.get("difficulty", ""),+ "concentration": q.get("concentration", ""),+ },+ "metadata": {"answer_now": True},+ }+ for idx, q in enumerate(questions)+ ]+ summary = {"results": results, "mode": "answer_now"}++ markdown = self._render_summary_markdown(summary)+ body = (notice + "\n\n" + markdown).strip() if notice else markdown+ if body:+ await stream.content(body, source=self.name, stage="generation")++ result_payload: dict[str, Any] = {+ "response": body or "No questions generated.",+ "summary": summary,+ "mode": "answer_now",+ "metadata": {"answer_now": True},+ }+ cost_meta = self._collect_cost_summary("question")+ if cost_meta:+ result_payload["metadata"]["cost_summary"] = cost_meta+ await stream.result(result_payload, source=self.name)++ @staticmethod+ def _parse_answer_now_json(raw: str, *, num_questions: int) -> list[dict[str, Any]]:+ """Tolerantly parse the model's JSON answer-now payload.++ We accept either ``{"questions": [...]}`` or a bare list. Anything+ unparseable yields a single placeholder so the UI doesn't crash.+ """+ import json++ if not raw:+ return []+ text = raw.strip()+ # Some models wrap JSON in fences even when response_format=json_object+ # is requested; strip a single fenced block defensively.+ if text.startswith("```"):+ text = text.strip("`")+ if "\n" in text:+ text = text.split("\n", 1)[1]+ if text.endswith("```"):+ text = text[: -3]+ text = text.strip()+ try:+ parsed = json.loads(text)+ except json.JSONDecodeError:+ return [+ {+ "question_id": "q_1",+ "question": raw[:500],+ "question_type": "written",+ "correct_answer": "",+ "explanation": "Model returned unparseable JSON during answer-now.",+ }+ ]++ if isinstance(parsed, dict):+ items = parsed.get("questions")+ else:+ items = parsed+ if not isinstance(items, list):+ return []+ cleaned = [item for item in items if isinstance(item, dict)]+ return cleaned[: max(num_questions, 1)] if cleaned else []+@staticmethoddef _collect_cost_summary(module_name: str) -> dict[str, Any] | None:from deeptutor.agents.base_agent import BaseAgentdiff --git a/deeptutor/capabilities/deep_research.py b/deeptutor/capabilities/deep_research.pyindex e5a40e6fc..47a220c71 100644--- a/deeptutor/capabilities/deep_research.py+++ b/deeptutor/capabilities/deep_research.py@@ -34,9 +34,15 @@ class DeepResearchCapability(BaseCapability):build_research_runtime_config,validate_research_request_config,)+ from deeptutor.capabilities._answer_now import extract_answer_now_contextfrom deeptutor.services.config import load_config_with_mainfrom deeptutor.services.llm.config import get_llm_config+ answer_now_payload = extract_answer_now_context(context)+ if answer_now_payload is not None:+ await self._run_answer_now(context, stream, answer_now_payload)+ return+llm_config = get_llm_config()kb_name = context.knowledge_bases[0] if context.knowledge_bases else Nonetopic = context.user_message@@ -346,6 +352,96 @@ class DeepResearchCapability(BaseCapability):source=self.name,)+ async def _run_answer_now(+ self,+ context: UnifiedContext,+ stream: StreamBus,+ payload: dict[str, Any],+ ) -> None:+ """+ Fast-path for ``deep_research``: skip the rephrase/decompose/research+ loop and synthesize the report directly from whatever evidence the+ partial trace already contains.+ """+ from deeptutor.capabilities._answer_now import (+ build_answer_now_trace_metadata,+ format_trace_summary,+ join_chunks,+ labeled_block,+ make_skip_notice,+ stream_synthesis,+ )++ is_zh = context.language.lower().startswith("zh")+ original = str(payload.get("original_user_message") or context.user_message).strip()+ partial = str(payload.get("partial_response") or "").strip()+ trace_summary = format_trace_summary(payload.get("events"), language=context.language)++ if is_zh:+ system_prompt = (+ "你是 DeepTutor 的研究报告写作组件。用户已经在等待,"+ "请根据当前已经收集到的研究 trace(包括 rephrase、decompose、检索结果、"+ "笔记/纲要等)直接输出一篇结构清晰的研究报告。"+ "不要再继续检索或调用工具。如果证据稀薄,请在报告中标注信息覆盖度。"+ "使用 Markdown,包含 1) 引言、2) 主体小节(按你能识别的子主题)、3) 结论。"+ )+ user_prompt = (+ f"研究主题:{original}\n\n"+ f"{labeled_block('Current Draft', partial)}\n\n"+ f"{labeled_block('Research Trace', trace_summary)}\n\n"+ "请基于以上材料立即输出最终报告。"+ )+ else:+ system_prompt = (+ "You are DeepTutor's research-report writer. The user is "+ "waiting, so produce a structured research report right now "+ "from whatever evidence has streamed so far (rephrase, "+ "decompose, search hits, notes/outline, ...). Do not retrieve "+ "more evidence and do not call tools. If coverage is thin, "+ "say so explicitly in the report. Use Markdown with: 1) intro, "+ "2) body sections (one per identifiable subtopic), 3) conclusion."+ )+ user_prompt = (+ f"Research topic: {original}\n\n"+ f"{labeled_block('Current Draft', partial)}\n\n"+ f"{labeled_block('Research Trace', trace_summary)}\n\n"+ "Produce the final research report from this material now."+ )++ trace_meta = build_answer_now_trace_metadata(+ capability=self.name, phase="reporting", label="Answer now"+ )+ notice = make_skip_notice(+ capability=self.name,+ language=context.language,+ stages_skipped=["rephrasing", "decomposing", "researching"],+ )++ async with stream.stage("reporting", source=self.name, metadata=trace_meta):+ if notice:+ await stream.content(notice + "\n\n", source=self.name, stage="reporting")+ chunks: list[str] = []+ async for chunk in stream_synthesis(+ stream=stream,+ source=self.name,+ stage="reporting",+ trace_meta=trace_meta,+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ max_tokens=3200,+ ):+ chunks.append(chunk)++ report = join_chunks(chunks)+ full = (notice + "\n\n" + report).strip() if notice else report+ await stream.result(+ {+ "response": full,+ "metadata": {"answer_now": True},+ },+ source=self.name,+ )+@staticmethoddef _outline_to_markdown(topic: str, sub_topics: list[dict[str, str]]diff --git a/deeptutor/capabilities/deep_solve.py b/deeptutor/capabilities/deep_solve.pyindex a70583ecc..8c0e3e139 100644--- a/deeptutor/capabilities/deep_solve.py+++ b/deeptutor/capabilities/deep_solve.py@@ -9,6 +9,8 @@ Wraps the existing ``MainSolver``.from __future__ import annotationsimport asyncio+from typing import Any+from deeptutor.capabilities.request_contracts import get_capability_request_schemafrom deeptutor.core.capability_protocol import BaseCapability, CapabilityManifestfrom deeptutor.core.context import UnifiedContext@@ -28,8 +30,14 @@ class DeepSolveCapability(BaseCapability):async def run(self, context: UnifiedContext, stream: StreamBus) -> None:from deeptutor.agents.solve.main_solver import MainSolver+ from deeptutor.capabilities._answer_now import extract_answer_now_contextfrom deeptutor.services.llm.config import get_llm_config+ answer_now_payload = extract_answer_now_context(context)+ if answer_now_payload is not None:+ await self._run_answer_now(context, stream, answer_now_payload)+ return+llm_config = get_llm_config()detailed = context.config_overrides.get("detailed_answer", True)enabled_tools = (@@ -265,3 +273,105 @@ class DeepSolveCapability(BaseCapability):},source=self.name,)++ async def _run_answer_now(+ self,+ context: UnifiedContext,+ stream: StreamBus,+ payload: dict[str, Any],+ ) -> None:+ """+ Fast-path for ``deep_solve``: skip Plan + ReAct, jump straight into+ the writer with whatever reasoning trace has streamed so far.++ The result payload preserves the same envelope shape as a normal+ ``deep_solve`` turn (``response`` + ``metadata``) so the frontend+ renders it identically.+ """+ from deeptutor.capabilities._answer_now import (+ build_answer_now_trace_metadata,+ format_trace_summary,+ join_chunks,+ labeled_block,+ make_skip_notice,+ stream_synthesis,+ )++ is_zh = context.language.lower().startswith("zh")+ original = str(payload.get("original_user_message") or context.user_message).strip()+ partial = str(payload.get("partial_response") or "").strip()+ trace_summary = format_trace_summary(payload.get("events"), language=context.language)++ if is_zh:+ system_prompt = (+ "你是 DeepTutor 的写作组件。用户已经在等待,"+ "你必须基于当前已经收集到的推理与工具调用轨迹直接输出最终答复。"+ "不要再做新的规划或调用工具,不要提到内部阶段。"+ "如果信息仍有缺口,请诚实说明不确定之处,但仍尽可能给出当前最有用的回答。"+ )+ user_prompt = (+ f"用户原始问题:\n{original}\n\n"+ f"{labeled_block('Current Draft', partial)}\n\n"+ f"{labeled_block('Execution Trace', trace_summary)}\n\n"+ "请基于以上材料立即生成给用户的最终回答。"+ )+ notice_label = "Writing"+ else:+ system_prompt = (+ "You are the writer component of DeepTutor. The user is "+ "already waiting, so produce the final user-facing answer "+ "right now using only the partial reasoning trace that has "+ "streamed so far. Do not plan further or call tools, and do "+ "not mention internal stages. If something is still uncertain, "+ "acknowledge it briefly while still giving the most useful "+ "answer you can."+ )+ user_prompt = (+ f"Original user request:\n{original}\n\n"+ f"{labeled_block('Current Draft', partial)}\n\n"+ f"{labeled_block('Execution Trace', trace_summary)}\n\n"+ "Produce the final user-facing answer using only this context."+ )+ notice_label = "Writing"++ trace_meta = build_answer_now_trace_metadata(+ capability=self.name, phase="writing", label="Answer now"+ )++ notice = make_skip_notice(+ capability=self.name,+ language=context.language,+ stages_skipped=["planning", "reasoning"],+ )++ async with stream.stage("writing", source=self.name, metadata=trace_meta):+ if notice:+ await stream.content(+ notice + "\n\n",+ source=self.name,+ stage="writing",+ )+ chunks: list[str] = []+ async for chunk in stream_synthesis(+ stream=stream,+ source=self.name,+ stage="writing",+ trace_meta=trace_meta,+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ max_tokens=2000,+ ):+ chunks.append(chunk)++ final_answer = join_chunks(chunks)+ await stream.result(+ {+ "response": (notice + "\n\n" + final_answer).strip() if notice else final_answer,+ "output_dir": "",+ "metadata": {+ "answer_now": True,+ "synthesizer": notice_label,+ },+ },+ source=self.name,+ )diff --git a/deeptutor/capabilities/math_animator.py b/deeptutor/capabilities/math_animator.pyindex c8ce7981a..e9bbe8621 100644--- a/deeptutor/capabilities/math_animator.py+++ b/deeptutor/capabilities/math_animator.py@@ -46,6 +46,7 @@ class MathAnimatorCapability(BaseCapability):from deeptutor.agents.math_animator.request_config import (validate_math_animator_request_config,)+ from deeptutor.capabilities._answer_now import extract_answer_now_contextfrom deeptutor.services.llm.config import get_llm_configllm_config = get_llm_config()@@ -58,6 +59,17 @@ class MathAnimatorCapability(BaseCapability):trace_callback=self._build_trace_bridge(stream),)+ answer_now_payload = extract_answer_now_context(context)+ if answer_now_payload is not None:+ await self._run_answer_now(+ context=context,+ stream=stream,+ payload=answer_now_payload,+ pipeline=pipeline,+ request_config=request_config,+ )+ return+timings: dict[str, float] = {}turn_id = str(context.metadata.get("turn_id", "") or context.session_id or "math-animator")history_context = str(context.metadata.get("conversation_context_text", "") or "").strip()@@ -202,6 +214,194 @@ class MathAnimatorCapability(BaseCapability):source=self.name,)+ async def _run_answer_now(+ self,+ *,+ context: UnifiedContext,+ stream: StreamBus,+ payload: dict[str, Any],+ pipeline, # MathAnimatorPipeline+ request_config, # MathAnimatorRequestConfig+ ) -> None:+ """+ Fast-path for ``math_animator``:++ * Skip ``concept_analysis`` + ``concept_design`` + ``summary`` —+ we synthesise minimal stub objects from the partial trace.+ * **Keep** ``code_generation`` + ``render`` so the user still gets+ a real video / animation, which is the whole point of this+ capability.++ The result envelope mirrors the standard pipeline so+ ``MathAnimatorViewer`` renders the artefacts unchanged.+ """+ import time++ from deeptutor.agents.math_animator.models import ConceptAnalysis, SceneDesign+ from deeptutor.capabilities._answer_now import (+ format_trace_summary,+ make_skip_notice,+ )++ original = str(payload.get("original_user_message") or context.user_message).strip()+ partial = str(payload.get("partial_response") or "").strip()+ trace_summary = format_trace_summary(payload.get("events"), language=context.language)++ # Build minimal stubs so ``code_agent.generate(...)`` still has the+ # field shape it expects. We weave the partial trace into the+ # ``learning_goal`` / ``visual_style`` so the generator has at least+ # *some* design intent to work from.+ narrative_seed = "\n".join(+ line for line in partial.splitlines() if line.strip()+ )[:400]+ analysis = ConceptAnalysis(+ learning_goal=original,+ math_focus=[],+ visual_targets=[],+ narrative_steps=[narrative_seed] if narrative_seed else [],+ reference_usage="",+ output_intent=request_config.output_mode,+ )+ design = SceneDesign(+ title=original[:80] or "Math animation",+ scene_outline=[],+ visual_style=request_config.style_hint or "",+ animation_notes=[trace_summary[:600]] if trace_summary else [],+ image_plan=[],+ code_constraints=[],+ )++ timings: dict[str, float] = {}+ turn_id = str(context.metadata.get("turn_id", "") or context.session_id or "math-animator")+ render_call_meta = build_trace_metadata(+ call_id=new_call_id("math-render"),+ phase="render_output",+ label="Render output",+ call_kind="math_render_output",+ trace_role="render",+ trace_kind="progress",+ output_mode=request_config.output_mode,+ quality=request_config.quality,+ )++ stage_start = time.perf_counter()+ async with stream.stage("code_generation", source=self.name):+ generated = await pipeline.run_code_generation(+ user_input=original,+ request_config=request_config,+ analysis=analysis,+ design=design,+ )+ await stream.progress(+ message="Manim code prepared (answer-now fast path).",+ source=self.name,+ stage="code_generation",+ )+ timings["code_generation"] = round(time.perf_counter() - stage_start, 3)++ async def _on_retry(retry_attempt) -> None:+ await stream.progress(+ message=f"Retry {retry_attempt.attempt}: {retry_attempt.error}",+ source=self.name,+ stage="code_retry",+ metadata={**render_call_meta, "trace_layer": "raw"},+ )++ async def _on_render_progress(message: str, raw: bool) -> None:+ await stream.progress(+ message=message,+ source=self.name,+ stage="render_output",+ metadata={+ **render_call_meta,+ "trace_layer": "raw" if raw else "summary",+ },+ )++ async def _on_retry_status(message: str) -> None:+ await stream.progress(+ message=message,+ source=self.name,+ stage="code_retry",+ metadata={"trace_layer": "summary"},+ )++ stage_start = time.perf_counter()+ async with stream.stage("code_retry", source=self.name):+ await stream.progress(+ message=(+ f"Rendering {request_config.output_mode} "+ f"(quality={request_config.quality}) — answer-now fast path."+ ),+ source=self.name,+ stage="code_retry",+ metadata={**render_call_meta, "call_state": "running"},+ )+ final_code, render_result = await pipeline.run_render(+ turn_id=turn_id,+ user_input=original,+ request_config=request_config,+ initial_code=generated.code,+ on_retry=_on_retry,+ on_render_progress=_on_render_progress,+ on_retry_status=_on_retry_status,+ )+ timings["code_retry"] = round(time.perf_counter() - stage_start, 3)++ async with stream.stage("render_output", source=self.name):+ await stream.progress(+ message=(+ f"Prepared {len(render_result.artifacts)} "+ f"{'artifact' if len(render_result.artifacts) == 1 else 'artifacts'} "+ "(answer-now)."+ ),+ source=self.name,+ stage="render_output",+ metadata={**render_call_meta, "call_state": "complete"},+ )+ timings["render_output"] = 0.0+ visual_review = getattr(render_result, "visual_review", None)++ notice = make_skip_notice(+ capability=self.name,+ language=context.language,+ stages_skipped=["concept_analysis", "concept_design", "summary"],+ )+ summary_text = notice or "Answer-now: code generated and rendered without prior analysis/design."+ if notice:+ await stream.content(summary_text, source=self.name, stage="summary")++ await stream.result(+ {+ "response": summary_text,+ "summary": {+ "summary_text": summary_text,+ "user_request": original,+ "generated_output": "",+ "key_points": [],+ "answer_now": True,+ },+ "code": {+ "language": "python",+ "content": final_code,+ },+ "output_mode": request_config.output_mode,+ "artifacts": [artifact.model_dump() for artifact in render_result.artifacts],+ "timings": timings,+ "render": {+ "quality": request_config.quality,+ "retry_attempts": render_result.retry_attempts,+ "retry_history": [item.model_dump() for item in render_result.retry_history],+ "source_code_path": render_result.source_code_path,+ "visual_review": visual_review.model_dump() if visual_review else None,+ },+ "analysis": analysis.model_dump(),+ "design": design.model_dump(),+ "metadata": {"answer_now": True},+ },+ source=self.name,+ )+def _build_trace_bridge(self, stream: StreamBus):async def _trace_bridge(update: dict[str, Any]) -> None:event = str(update.get("event", "") or "")diff --git a/deeptutor/capabilities/visualize.py b/deeptutor/capabilities/visualize.pyindex f7479c942..f962ae698 100644--- a/deeptutor/capabilities/visualize.py+++ b/deeptutor/capabilities/visualize.py@@ -29,8 +29,14 @@ class VisualizeCapability(BaseCapability):async def run(self, context: UnifiedContext, stream: StreamBus) -> None:from deeptutor.agents.visualize.pipeline import VisualizePipeline+ from deeptutor.capabilities._answer_now import extract_answer_now_contextfrom deeptutor.services.llm.config import get_llm_config+ answer_now_payload = extract_answer_now_context(context)+ if answer_now_payload is not None:+ await self._run_answer_now(context, stream, answer_now_payload)+ return+llm_config = get_llm_config()history_context = str(context.metadata.get("conversation_context_text", "") or ""@@ -134,6 +140,146 @@ class VisualizeCapability(BaseCapability):source=self.name,)+ async def _run_answer_now(+ self,+ context: UnifiedContext,+ stream: StreamBus,+ payload: dict[str, Any],+ ) -> None:+ """+ Fast-path for ``visualize``: skip analysis + review and emit final+ code in a single structured LLM call. The result envelope mirrors+ the standard pipeline so ``VisualizationViewer`` renders it+ directly.+ """+ import json+ import re++ from deeptutor.capabilities._answer_now import (+ build_answer_now_trace_metadata,+ format_trace_summary,+ join_chunks,+ labeled_block,+ make_skip_notice,+ stream_synthesis,+ )++ is_zh = context.language.lower().startswith("zh")+ original = str(payload.get("original_user_message") or context.user_message).strip()+ partial = str(payload.get("partial_response") or "").strip()+ trace_summary = format_trace_summary(payload.get("events"), language=context.language)++ render_mode = str(+ context.config_overrides.get("render_mode", "auto") or "auto"+ ).strip().lower()++ if is_zh:+ system_prompt = (+ "你是 DeepTutor 的可视化代码生成器。用户已经在等待,"+ "请直接输出最终可渲染的代码。"+ "严格输出 JSON:{\"render_type\": \"svg|chartjs|mermaid\", "+ "\"code\": \"...\"}。"+ "code 字段是可直接渲染的源代码(SVG 标签 / Chart.js JS 代码 / Mermaid 文本)。"+ )+ user_prompt = (+ f"用户请求:{original}\n\n"+ f"render_mode:{render_mode}\n\n"+ f"{labeled_block('Current Draft', partial)}\n\n"+ f"{labeled_block('Execution Trace', trace_summary)}\n\n"+ "立即输出符合 schema 的 JSON。"+ )+ else:+ system_prompt = (+ "You are DeepTutor's visualization code generator. The user "+ "is waiting, so emit the final renderable code in one shot. "+ "Output strictly the JSON {\"render_type\": "+ "\"svg|chartjs|mermaid\", \"code\": \"...\"}, where ``code`` "+ "is the renderable source (SVG markup, Chart.js JS, or "+ "Mermaid DSL)."+ )+ user_prompt = (+ f"User request: {original}\n\n"+ f"render_mode hint: {render_mode}\n\n"+ f"{labeled_block('Current Draft', partial)}\n\n"+ f"{labeled_block('Execution Trace', trace_summary)}\n\n"+ "Emit the JSON now."+ )++ trace_meta = build_answer_now_trace_metadata(+ capability=self.name, phase="generating", label="Answer now"+ )+ notice = make_skip_notice(+ capability=self.name,+ language=context.language,+ stages_skipped=["analyzing", "reviewing"],+ )++ chunks: list[str] = []+ async with stream.stage("generating", source=self.name, metadata=trace_meta):+ async for chunk in stream_synthesis(+ stream=stream,+ source=self.name,+ stage="generating",+ trace_meta=trace_meta,+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ max_tokens=2400,+ push_content=False,+ response_format={"type": "json_object"},+ ):+ chunks.append(chunk)++ raw = join_chunks(chunks).strip()+ # Strip optional code fences for resilience.+ if raw.startswith("```"):+ raw = re.sub(r"^```[a-zA-Z]*\n?", "", raw)+ if raw.endswith("```"):+ raw = raw[: -3].rstrip()+ try:+ parsed = json.loads(raw)+ except json.JSONDecodeError:+ parsed = {"render_type": "svg", "code": raw}+ if not isinstance(parsed, dict):+ parsed = {"render_type": "svg", "code": str(parsed)}++ render_type = str(parsed.get("render_type") or "svg").strip().lower()+ if render_type not in {"svg", "chartjs", "mermaid"}:+ render_type = "svg"+ final_code = str(parsed.get("code") or "").strip()++ lang_tag = "svg" if render_type == "svg" else (+ "mermaid" if render_type == "mermaid" else "javascript"+ )+ content_md = f"```{lang_tag}\n{final_code}\n```"+ body = (notice + "\n\n" + content_md).strip() if notice else content_md+ await stream.content(body, source=self.name, stage="generating")++ await stream.result(+ {+ "response": body,+ "render_type": render_type,+ "code": {+ "language": lang_tag,+ "content": final_code,+ },+ "analysis": {+ "render_type": render_type,+ "description": "Answer-now: skipped analysis stage.",+ "data_description": "",+ "chart_type": "",+ "visual_elements": [],+ "rationale": "",+ },+ "review": {+ "optimized_code": final_code,+ "changed": False,+ "review_notes": "Answer-now: skipped review stage.",+ },+ "metadata": {"answer_now": True},+ },+ source=self.name,+ )+def _build_trace_bridge(self, stream: StreamBus):async def _trace_bridge(update: dict[str, Any]) -> None:event = str(update.get("event", "") or "")diff --git a/deeptutor/runtime/orchestrator.py b/deeptutor/runtime/orchestrator.pyindex d5a4039b0..464e649bd 100644--- a/deeptutor/runtime/orchestrator.py+++ b/deeptutor/runtime/orchestrator.py@@ -43,20 +43,31 @@ class ChatOrchestrator:if not context.session_id:context.session_id = str(uuid.uuid4())- # "Answer now" is a universal escape hatch: the user is impatient and- # wants the system to synthesize a final reply from the partial trace- # captured so far. The chat capability owns this synthesis path- # (see _stage_answer_now), so we re-route here regardless of the- # original capability so this works uniformly across deep_solve,- # deep_research, math_animator, etc.- if isinstance(context.config_overrides, dict) and context.config_overrides.get(- "answer_now_context"- ):- cap_name = "chat"- else:- cap_name = context.active_capability or "chat"+ # "Answer now" is a universal escape hatch but the actual fast-path+ # is *capability-specific* (deep_solve jumps to writing, deep_question+ # jumps to generation, math_animator skips analysis/design but still+ # renders, etc.). Each capability inspects ``answer_now_context`` at+ # the top of its own ``run()``; the orchestrator only adds a defensive+ # fallback here: if the requested capability has been removed from+ # the registry but the user is mid-``answer_now``, route to ``chat``+ # so they still get *some* response instead of a hard error.+ cap_name = context.active_capability or "chat"capability = self._cap_registry.get(cap_name)+ is_answer_now = bool(+ isinstance(context.config_overrides, dict)+ and context.config_overrides.get("answer_now_context")+ )+ if capability is None and is_answer_now:+ fallback = self._cap_registry.get("chat")+ if fallback is not None:+ logger.info(+ "Capability %s missing for answer_now; falling back to chat.",+ cap_name,+ )+ cap_name = "chat"+ capability = fallback+if capability is None:bus = StreamBus()await bus.error(diff --git a/tests/capabilities/__init__.py b/tests/capabilities/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/capabilities/test_answer_now.py b/tests/capabilities/test_answer_now.pynew file mode 100644index 000000000..8c2dcec23--- /dev/null+++ b/tests/capabilities/test_answer_now.py@@ -0,0 +1,658 @@+"""+Tests for the per-capability ``answer_now`` fast-paths.++Each capability now owns its own answer-now branch (instead of every+turn being re-routed to ``chat``). These tests pin the contract:++* Detection — the shared ``extract_answer_now_context`` correctly gates+ the branch on a non-empty ``original_user_message``.+* Trace formatting — long event lists are summarised, truncation+ applied, empty inputs fall back to a sentinel string.+* Skip notice — i18n-aware, omits when no stages were skipped.+* Per-capability flow — for each registered capability we mock the+ underlying LLM stream and assert the result envelope shape that the+ frontend depends on (``response`` always, plus capability-specific+ keys like ``summary.results`` for ``deep_question`` or ``code`` for+ ``visualize``).++The tests deliberately avoid touching the real LLM stack: we patch+``deeptutor.capabilities._answer_now.llm_stream`` (the alias the helper+imports) and ``deeptutor.capabilities._answer_now.get_llm_config`` so+the fast-paths run end-to-end without network or API keys.+"""++from __future__ import annotations++import json+from typing import Any, AsyncIterator+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from deeptutor.capabilities import _answer_now+from deeptutor.capabilities._answer_now import (+ extract_answer_now_context,+ format_trace_summary,+ join_chunks,+ labeled_block,+ make_skip_notice,+)+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream import StreamEvent, StreamEventType+from deeptutor.core.stream_bus import StreamBus+++# ---------------------------------------------------------------------------+# Shared helpers+# ---------------------------------------------------------------------------+++async def _drain(bus: StreamBus, task) -> list[StreamEvent]:+ """Run ``task`` to completion, then return everything emitted on ``bus``."""+ await task+ await bus.close()+ return [event async for event in bus.subscribe()]+++def _fake_llm_config(model: str = "gpt-4o-mini") -> MagicMock:+ cfg = MagicMock()+ cfg.binding = "openai"+ cfg.model = model+ cfg.api_key = "sk-test"+ cfg.base_url = None+ cfg.api_version = None+ return cfg+++def _make_stream_factory(chunks: list[str]):+ """Return an async generator factory that yields the given chunks once."""++ async def _stream(*_args: Any, **_kwargs: Any) -> AsyncIterator[str]:+ for chunk in chunks:+ yield chunk++ return _stream+++def _build_context(+ *,+ capability: str,+ payload: dict[str, Any] | None,+ user_message: str = "What is a Fourier transform?",+ config_overrides: dict[str, Any] | None = None,+ language: str = "en",+) -> UnifiedContext:+ overrides: dict[str, Any] = dict(config_overrides or {})+ if payload is not None:+ overrides["answer_now_context"] = payload+ return UnifiedContext(+ session_id="sess-test",+ user_message=user_message,+ active_capability=capability,+ config_overrides=overrides,+ language=language,+ metadata={"turn_id": "turn-test"},+ )+++def _result_event(events: list[StreamEvent]) -> StreamEvent:+ """Return the single ``RESULT`` event; raise if absent."""+ matches = [e for e in events if e.type == StreamEventType.RESULT]+ assert len(matches) == 1, f"expected 1 RESULT event, got {len(matches)}"+ return matches[0]+++def _content_text(events: list[StreamEvent]) -> str:+ return "".join(e.content for e in events if e.type == StreamEventType.CONTENT)+++# ---------------------------------------------------------------------------+# 1. Shared helpers — pure functions+# ---------------------------------------------------------------------------+++class TestExtractAnswerNowContext:+ def test_returns_payload_when_present(self) -> None:+ ctx = _build_context(+ capability="chat",+ payload={"original_user_message": "hi", "events": []},+ )+ assert extract_answer_now_context(ctx) == {+ "original_user_message": "hi",+ "events": [],+ }++ def test_returns_none_when_missing(self) -> None:+ ctx = _build_context(capability="chat", payload=None)+ assert extract_answer_now_context(ctx) is None++ def test_returns_none_when_not_dict(self) -> None:+ ctx = UnifiedContext(+ user_message="x",+ config_overrides={"answer_now_context": "not-a-dict"},+ )+ assert extract_answer_now_context(ctx) is None++ def test_returns_none_when_original_user_message_empty(self) -> None:+ ctx = _build_context(+ capability="chat",+ payload={"original_user_message": " "},+ )+ assert extract_answer_now_context(ctx) is None+++class TestFormatTraceSummary:+ def test_empty_events_returns_fallback_en(self) -> None:+ assert "No intermediate" in format_trace_summary([], language="en")++ def test_empty_events_returns_fallback_zh(self) -> None:+ assert "没有可用" in format_trace_summary([], language="zh")++ def test_non_list_returns_fallback(self) -> None:+ assert "No intermediate" in format_trace_summary("nope", language="en")++ def test_renders_event_with_stage_and_tool(self) -> None:+ events = [+ {+ "type": "tool_call",+ "stage": "acting",+ "content": "rag.query",+ "metadata": {"tool_name": "rag"},+ }+ ]+ out = format_trace_summary(events, language="en")+ assert "1. tool_call / acting" in out+ assert "rag.query" in out+ assert "[tool=rag]" in out++ def test_truncates_long_event_content(self) -> None:+ events = [+ {+ "type": "thinking",+ "stage": "planning",+ "content": "x" * 5000,+ }+ ]+ out = format_trace_summary(events, language="en")+ assert out.endswith("...")+ # The per-event cap is 800 chars; the rendered line stays bounded.+ assert len(out) < 1000++ def test_truncates_overall_transcript(self) -> None:+ events = [+ {"type": "thinking", "stage": "s", "content": "a" * 700}+ for _ in range(20)+ ]+ out = format_trace_summary(events, language="en")+ assert len(out) <= 6000+ assert out.endswith("...")++ def test_skips_non_dict_entries(self) -> None:+ events = ["bad", 42, {"type": "thinking", "content": "good"}]+ out = format_trace_summary(events, language="en")+ assert "good" in out+ assert "bad" not in out+++class TestMakeSkipNotice:+ def test_empty_when_no_stages(self) -> None:+ assert make_skip_notice(capability="chat", language="en", stages_skipped=[]) == ""++ def test_english_lists_stages(self) -> None:+ notice = make_skip_notice(+ capability="deep_solve",+ language="en",+ stages_skipped=["planning", "reasoning"],+ )+ assert "planning, reasoning" in notice+ assert "`deep_solve`" in notice++ def test_chinese_uses_full_width_separator(self) -> None:+ notice = make_skip_notice(+ capability="deep_solve",+ language="zh",+ stages_skipped=["planning", "reasoning"],+ )+ assert "planning、reasoning" in notice+ assert "已跳过" in notice+++class TestLabeledBlock:+ def test_renders_label_and_content(self) -> None:+ assert labeled_block("X", "hello") == "[X]\nhello"++ def test_uses_sentinel_for_empty_content(self) -> None:+ assert labeled_block("X", " ") == "[X]\n(empty)"+++class TestJoinChunks:+ def test_joins_and_strips_thinking_tags(self) -> None:+ with patch.object(_answer_now, "get_llm_config", return_value=_fake_llm_config()):+ text = join_chunks(["<think>private</think>", "Answer."])+ # ``clean_thinking_tags`` for the openai binding is a no-op, but+ # we still want to make sure the function does not blow up.+ assert "Answer." in text+++# ---------------------------------------------------------------------------+# 2. Per-capability fast paths+# ---------------------------------------------------------------------------+++class TestChatAnswerNow:+ """``chat`` keeps its existing synthesizer; we only assert the high-+ level behavior so a future refactor of ``_stage_answer_now`` doesn't+ silently change the contract."""++ @pytest.mark.asyncio+ async def test_chat_synthesises_final_answer_from_partial_trace(self) -> None:+ from deeptutor.agents.chat import agentic_pipeline as ap_module++ async def _fake_stream(self: Any, _messages: Any, **_kwargs: Any):+ for chunk in ("Hello", " ", "world"):+ yield chunk++ cfg = _fake_llm_config()++ with patch.object(+ ap_module.AgenticChatPipeline,+ "_stream_messages",+ _fake_stream,+ ), patch(+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",+ return_value=cfg,+ ):+ from deeptutor.capabilities.chat import ChatCapability++ ctx = _build_context(+ capability="chat",+ payload={+ "original_user_message": "Explain Fourier",+ "partial_response": "We had begun to think about ...",+ "events": [+ {"type": "thinking", "stage": "thinking", "content": "warming up"}+ ],+ },+ )+ bus = StreamBus()+ cap = ChatCapability()+ events = await _drain(bus, cap.run(ctx, bus))++ text = _content_text(events)+ assert "Hello" in text+ result = _result_event(events)+ assert result.metadata.get("answer_now") is True+ assert "Hello world" in str(result.metadata.get("response", ""))+++class TestDeepSolveAnswerNow:+ @pytest.mark.asyncio+ async def test_jumps_to_writing_stage(self) -> None:+ cfg = _fake_llm_config()+ chunks = ["The Fourier transform ", "decomposes signals."]+ with patch.object(_answer_now, "get_llm_config", return_value=cfg), patch.object(+ _answer_now, "llm_stream", _make_stream_factory(chunks)+ ):+ from deeptutor.capabilities.deep_solve import DeepSolveCapability++ ctx = _build_context(+ capability="deep_solve",+ payload={+ "original_user_message": "Explain Fourier transform",+ "partial_response": "Planning ...",+ "events": [+ {+ "type": "thinking",+ "stage": "planning",+ "content": "Need to break this into intuition + math",+ }+ ],+ },+ language="en",+ )+ bus = StreamBus()+ cap = DeepSolveCapability()+ events = await _drain(bus, cap.run(ctx, bus))++ stage_starts = [+ e for e in events if e.type == StreamEventType.STAGE_START+ ]+ assert any(e.stage == "writing" for e in stage_starts)++ text = _content_text(events)+ assert "Skipped" in text # the skip notice prepended+ assert "decomposes signals" in text++ result = _result_event(events)+ assert result.metadata.get("metadata", {}).get("answer_now") is True+ assert result.metadata.get("response", "").endswith("decomposes signals.")+ assert result.metadata.get("output_dir") == ""+++class TestDeepQuestionAnswerNow:+ @pytest.mark.asyncio+ async def test_emits_quiz_envelope(self) -> None:+ cfg = _fake_llm_config()+ payload_json = json.dumps(+ {+ "questions": [+ {+ "question_id": "q_1",+ "question": "What is 2+2?",+ "question_type": "choice",+ "options": {"A": "3", "B": "4", "C": "5"},+ "correct_answer": "B",+ "explanation": "Basic arithmetic.",+ "difficulty": "easy",+ "concentration": "arithmetic",+ },+ {+ "question_id": "q_2",+ "question": "Define derivative.",+ "question_type": "written",+ "correct_answer": "Limit of difference quotient.",+ "explanation": "Standard textbook definition.",+ },+ ]+ }+ )+ with patch.object(_answer_now, "get_llm_config", return_value=cfg), patch.object(+ _answer_now, "llm_stream", _make_stream_factory([payload_json])+ ):+ from deeptutor.capabilities.deep_question import DeepQuestionCapability++ ctx = _build_context(+ capability="deep_question",+ payload={+ "original_user_message": "Generate calc warm-ups",+ "events": [],+ },+ config_overrides={"num_questions": 2, "topic": "calculus warm-ups"},+ )+ bus = StreamBus()+ cap = DeepQuestionCapability()+ events = await _drain(bus, cap.run(ctx, bus))++ result = _result_event(events)+ summary = result.metadata.get("summary") or {}+ results = summary.get("results") or []+ assert len(results) == 2+ assert results[0]["qa_pair"]["question"] == "What is 2+2?"+ assert results[0]["qa_pair"]["options"]["B"] == "4"+ assert result.metadata.get("mode") == "answer_now"+ assert result.metadata.get("metadata", {}).get("answer_now") is True++ # The rendered markdown should make it into a CONTENT event so+ # the chat surface still shows a textual recap of the quiz.+ text = _content_text(events)+ assert "What is 2+2?" in text+ assert "Skipped" in text # skip notice++ @pytest.mark.asyncio+ async def test_handles_unparseable_json_gracefully(self) -> None:+ cfg = _fake_llm_config()+ with patch.object(_answer_now, "get_llm_config", return_value=cfg), patch.object(+ _answer_now, "llm_stream", _make_stream_factory(["not json at all"])+ ):+ from deeptutor.capabilities.deep_question import DeepQuestionCapability++ ctx = _build_context(+ capability="deep_question",+ payload={"original_user_message": "x", "events": []},+ config_overrides={"num_questions": 1, "topic": "x"},+ )+ bus = StreamBus()+ cap = DeepQuestionCapability()+ events = await _drain(bus, cap.run(ctx, bus))++ # Should still produce a result event with a placeholder+ # question, not crash with a JSONDecodeError.+ result = _result_event(events)+ results = (result.metadata.get("summary") or {}).get("results") or []+ assert len(results) == 1+ assert results[0]["qa_pair"]["question_type"] == "written"+++class TestDeepResearchAnswerNow:+ @pytest.mark.asyncio+ async def test_emits_report_envelope(self) -> None:+ cfg = _fake_llm_config()+ chunks = ["# Report\n\n", "Body section.\n\n", "## Conclusion\n\nWrap-up."]+ with patch.object(_answer_now, "get_llm_config", return_value=cfg), patch.object(+ _answer_now, "llm_stream", _make_stream_factory(chunks)+ ):+ from deeptutor.capabilities.deep_research import DeepResearchCapability++ ctx = _build_context(+ capability="deep_research",+ payload={+ "original_user_message": "State of LLM evals 2025",+ "events": [+ {+ "type": "tool_result",+ "stage": "researching",+ "content": "Found 3 evals.",+ "metadata": {"tool": "web_search"},+ }+ ],+ },+ language="en",+ )+ bus = StreamBus()+ cap = DeepResearchCapability()+ events = await _drain(bus, cap.run(ctx, bus))++ stage_starts = [+ e for e in events if e.type == StreamEventType.STAGE_START+ ]+ assert any(e.stage == "reporting" for e in stage_starts)++ result = _result_event(events)+ assert result.metadata.get("metadata", {}).get("answer_now") is True+ response = str(result.metadata.get("response", ""))+ assert "# Report" in response+ assert "Conclusion" in response+++class TestVisualizeAnswerNow:+ @pytest.mark.asyncio+ async def test_emits_renderable_code_envelope(self) -> None:+ cfg = _fake_llm_config()+ payload_json = json.dumps(+ {+ "render_type": "svg",+ "code": "<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'/>",+ }+ )+ with patch.object(_answer_now, "get_llm_config", return_value=cfg), patch.object(+ _answer_now, "llm_stream", _make_stream_factory([payload_json])+ ):+ from deeptutor.capabilities.visualize import VisualizeCapability++ ctx = _build_context(+ capability="visualize",+ payload={+ "original_user_message": "Draw a circle",+ "events": [],+ },+ config_overrides={"render_mode": "svg"},+ )+ bus = StreamBus()+ cap = VisualizeCapability()+ events = await _drain(bus, cap.run(ctx, bus))++ result = _result_event(events)+ assert result.metadata.get("render_type") == "svg"+ code = result.metadata.get("code") or {}+ assert code.get("language") == "svg"+ assert "<svg" in code.get("content", "")+ assert result.metadata.get("metadata", {}).get("answer_now") is True++ content = _content_text(events)+ assert "```svg" in content++ @pytest.mark.asyncio+ async def test_falls_back_to_svg_when_render_type_invalid(self) -> None:+ cfg = _fake_llm_config()+ payload_json = json.dumps({"render_type": "totally-bogus", "code": "x"})+ with patch.object(_answer_now, "get_llm_config", return_value=cfg), patch.object(+ _answer_now, "llm_stream", _make_stream_factory([payload_json])+ ):+ from deeptutor.capabilities.visualize import VisualizeCapability++ ctx = _build_context(+ capability="visualize",+ payload={"original_user_message": "x", "events": []},+ )+ bus = StreamBus()+ cap = VisualizeCapability()+ events = await _drain(bus, cap.run(ctx, bus))++ result = _result_event(events)+ assert result.metadata.get("render_type") == "svg"++ @pytest.mark.asyncio+ async def test_strips_code_fences_around_json(self) -> None:+ cfg = _fake_llm_config()+ fenced = "```json\n{\"render_type\": \"mermaid\", \"code\": \"graph TD;A-->B\"}\n```"+ with patch.object(_answer_now, "get_llm_config", return_value=cfg), patch.object(+ _answer_now, "llm_stream", _make_stream_factory([fenced])+ ):+ from deeptutor.capabilities.visualize import VisualizeCapability++ ctx = _build_context(+ capability="visualize",+ payload={"original_user_message": "diagram", "events": []},+ )+ bus = StreamBus()+ cap = VisualizeCapability()+ events = await _drain(bus, cap.run(ctx, bus))++ result = _result_event(events)+ assert result.metadata.get("render_type") == "mermaid"+ assert "graph TD" in (result.metadata.get("code") or {}).get("content", "")+++class TestMathAnimatorAnswerNow:+ """Math animator's fast-path keeps the real ``code_generation`` ++ ``render`` stages — those are the whole point of the capability —+ while skipping ``concept_analysis``, ``concept_design`` and+ ``summary``. We verify dispatch and result envelope by mocking the+ pipeline's two retained stages so we don't actually invoke Manim."""++ @pytest.mark.asyncio+ async def test_skips_analysis_design_summary_but_calls_codegen_and_render(+ self,+ ) -> None:+ from deeptutor.agents.math_animator.models import (+ GeneratedCode,+ RenderResult,+ )++ # Skip the whole test cleanly when manim isn't available, since+ # math_animator.run() short-circuits before we can patch anything.+ import importlib.util as _ilu++ if _ilu.find_spec("manim") is None:+ pytest.skip("manim not installed; math_animator answer-now test skipped")++ from deeptutor.capabilities.math_animator import MathAnimatorCapability++ analysis_agent_calls: list[Any] = []+ design_agent_calls: list[Any] = []+ summary_agent_calls: list[Any] = []++ with patch(+ "deeptutor.agents.math_animator.pipeline.MathAnimatorPipeline"+ ) as PipelineCls:+ pipeline_instance = PipelineCls.return_value+ pipeline_instance.run_analysis = AsyncMock(+ side_effect=lambda *a, **k: analysis_agent_calls.append(("a",))+ )+ pipeline_instance.run_design = AsyncMock(+ side_effect=lambda *a, **k: design_agent_calls.append(("d",))+ )+ pipeline_instance.run_summary = AsyncMock(+ side_effect=lambda *a, **k: summary_agent_calls.append(("s",))+ )+ pipeline_instance.run_code_generation = AsyncMock(+ return_value=GeneratedCode(code="from manim import *\nclass S(Scene): pass")+ )+ pipeline_instance.run_render = AsyncMock(+ return_value=(+ "from manim import *\nclass S(Scene): pass",+ RenderResult(+ output_mode="video",+ artifacts=[],+ public_code_path="",+ source_code_path="/tmp/scene.py",+ quality="medium",+ retry_attempts=0,+ retry_history=[],+ visual_review=None,+ ),+ )+ )++ cap = MathAnimatorCapability()+ ctx = _build_context(+ capability="math_animator",+ payload={+ "original_user_message": "Animate a sine wave",+ "events": [],+ },+ config_overrides={"output_mode": "video", "quality": "medium"},+ )+ bus = StreamBus()+ events = await _drain(bus, cap.run(ctx, bus))++ # Skipped stages must NOT have been invoked.+ assert pipeline_instance.run_analysis.await_count == 0+ assert pipeline_instance.run_design.await_count == 0+ assert pipeline_instance.run_summary.await_count == 0+ # Retained stages MUST have been invoked exactly once.+ assert pipeline_instance.run_code_generation.await_count == 1+ assert pipeline_instance.run_render.await_count == 1++ result = _result_event(events)+ assert result.metadata.get("metadata", {}).get("answer_now") is True+ assert result.metadata.get("output_mode") == "video"+ assert result.metadata.get("code", {}).get("language") == "python"+++# ---------------------------------------------------------------------------+# 3. Bypass — when no payload is set, the normal path runs+# ---------------------------------------------------------------------------+++class TestNormalPathWhenNoAnswerNow:+ """A defensive check: capabilities must NOT enter the fast-path+ when ``answer_now_context`` is absent. If they did, the regular+ pipeline would be silently shadowed."""++ @pytest.mark.asyncio+ async def test_deep_solve_without_payload_calls_main_solver(self) -> None:+ from deeptutor.capabilities.deep_solve import DeepSolveCapability++ # We patch MainSolver at its import site inside the capability.+ with patch(+ "deeptutor.agents.solve.main_solver.MainSolver"+ ) as SolverCls, patch(+ "deeptutor.services.llm.config.get_llm_config", return_value=_fake_llm_config()+ ):+ solver = SolverCls.return_value+ solver.ainit = AsyncMock()+ solver.solve = AsyncMock(return_value={"final_answer": "from solver"})++ cap = DeepSolveCapability()+ ctx = _build_context(+ capability="deep_solve",+ payload=None,+ user_message="topic",+ )+ bus = StreamBus()+ events = await _drain(bus, cap.run(ctx, bus))++ solver.solve.assert_awaited_once()+ result = _result_event(events)+ assert "from solver" in str(result.metadata.get("response", ""))diff --git a/tests/runtime/test_orchestrator.py b/tests/runtime/test_orchestrator.pyindex 47240dbff..1520b02f0 100644--- a/tests/runtime/test_orchestrator.py+++ b/tests/runtime/test_orchestrator.py@@ -116,19 +116,24 @@ class TestOrchestratorRouting:assert content_events[0].content == "hello"@pytest.mark.asyncio- async def test_answer_now_context_reroutes_to_chat(self) -> None:- """When ``answer_now_context`` is set, the orchestrator must route- to the ``chat`` capability so the answer-now synthesizer handles the- turn regardless of the original ``active_capability``."""+ async def test_answer_now_context_preserves_active_capability(self) -> None:+ """``answer_now_context`` must be handled by the originally+ selected capability — each capability owns its own fast-path now.++ Regression test for the previous behavior where the orchestrator+ force-routed every answer-now turn into the ``chat`` capability.+ """chat_cap = _EchoCapability()chat_cap.manifest = CapabilityManifest(name="chat", description="Chat capability.", stages=["responding"])+ chat_cap.run = AsyncMock(+ side_effect=AssertionError("chat must not steal answer_now from deep_solve")+ )deep_cap = _EchoCapability()deep_cap.manifest = CapabilityManifest(name="deep_solve", description="Deep solve.", stages=["responding"])- deep_cap.run = AsyncMock(side_effect=AssertionError("deep_solve must not run"))orch = _make_orchestrator({"chat": chat_cap, "deep_solve": deep_cap})ctx = UnifiedContext(@@ -149,7 +154,64 @@ class TestOrchestratorRouting:content_events = [e for e in events if e.type == StreamEventType.CONTENT]assert len(content_events) == 1assert content_events[0].content == "ping"- deep_cap.run.assert_not_called()+ chat_cap.run.assert_not_called()++ @pytest.mark.asyncio+ async def test_answer_now_falls_back_to_chat_when_capability_missing(self) -> None:+ """If the originally selected capability is no longer registered+ but the user is mid-``answer_now``, the orchestrator should+ gracefully degrade to ``chat`` instead of erroring out."""+ chat_cap = _EchoCapability()+ chat_cap.manifest = CapabilityManifest(+ name="chat", description="Chat capability.", stages=["responding"]+ )+ orch = _make_orchestrator({"chat": chat_cap})++ ctx = UnifiedContext(+ user_message="ping",+ active_capability="removed_capability",+ config_overrides={+ "answer_now_context": {+ "original_user_message": "ping",+ "partial_response": "",+ "events": [],+ }+ },+ )+ events: list[StreamEvent] = []+ async for event in orch.handle(ctx):+ events.append(event)++ error_events = [e for e in events if e.type == StreamEventType.ERROR]+ content_events = [e for e in events if e.type == StreamEventType.CONTENT]+ assert error_events == []+ assert len(content_events) == 1+ assert content_events[0].content == "ping"++ @pytest.mark.asyncio+ async def test_answer_now_without_chat_fallback_still_errors(self) -> None:+ """If neither the requested capability nor ``chat`` is present,+ the orchestrator must still emit a clear error rather than hang."""+ orch = _make_orchestrator({})++ ctx = UnifiedContext(+ user_message="ping",+ active_capability="missing",+ config_overrides={+ "answer_now_context": {+ "original_user_message": "ping",+ "partial_response": "",+ "events": [],+ }+ },+ )+ events: list[StreamEvent] = []+ async for event in orch.handle(ctx):+ events.append(event)++ error_events = [e for e in events if e.type == StreamEventType.ERROR]+ assert len(error_events) == 1+ assert "Unknown capability" in error_events[0].content@pytest.mark.asyncioasync def test_unknown_capability_yields_error(self) -> None:diff --git a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx b/web/app/(workspace)/chat/[[...sessionId]]/page.tsxindex c28e62c58..119f61288 100644--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx@@ -357,13 +357,13 @@ export default function ChatPage() {metadata: event.metadata ?? {},}));cancelStreamingTurn();- // Force the follow-up turn to the chat capability so the answer-now- // synthesizer (chat._stage_answer_now) handles it regardless of- // whether the original turn was deep_solve / deep_research / etc.- // The orchestrator also re-routes server-side as a defensive guard.+ // Preserve the original capability — each capability now owns its+ // own answer-now fast-path (deep_solve jumps to writing,+ // deep_question to direct quiz synthesis, math_animator to+ // code-gen + render, etc.). The backend orchestrator only falls+ // back to ``chat`` if the requested capability is missing.const answerNowSnapshot: MessageRequestSnapshot = {...snapshot,- capability: "chat",config: {...(snapshot.config || {}),answer_now_context: {