Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

refactor chat capability & RAG pipeline(llamaindex)

Bingxi Zhao (Frank)1596807242bc
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index 6a2849e04..f74e2fcbb 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -1,9 +1,29 @@
-"""Agentic chat pipeline with thinking, acting, observing, and responding."""
+"""Single-loop agentic chat pipeline.
+
+The chat capability used to run four sequential LLM calls (thinking → acting
+→ observing → responding) regardless of question complexity. Simple questions
+paid for three unnecessary calls; complex questions couldn't iterate because
+``acting`` was a single-shot tool call.
+
+This module replaces that with one iterative LLM loop. Each iteration:
+
+* Streams an LLM call (with native tool schemas attached when applicable).
+* If the model emitted tool calls, dispatches them, appends the tool
+ messages, and continues to the next iteration.
+* Otherwise the iteration's text is the final answer and the loop exits.
+
+The chat-only ``read_source`` tool is auto-included whenever the turn has a
+non-empty ``source_manifest`` (the manifest itself is appended to the
+system prompt by :py:meth:`_build_system_prompt`). The per-turn
+``{source_id: full_text}`` map flows in via ``context.metadata['source_index']``.
+
+History compression (branch-safe) is handled upstream by
+``ContextBuilder.build`` so it does not appear here.
+"""
from __future__ import annotations
import asyncio
-from dataclasses import asdict, dataclass
import json
import logging
from typing import Any
@@ -26,12 +46,12 @@ from deeptutor.services.llm import (
get_llm_config,
get_token_limit_kwargs,
prepare_multimodal_messages,
- supports_response_format,
supports_tools,
)
from deeptutor.services.llm import (
stream as llm_stream,
)
+from deeptutor.services.llm.context_window import resolve_effective_context_window
from deeptutor.services.prompt import get_prompt_manager
from deeptutor.services.prompt.language import append_language_directive
from deeptutor.tools.builtin import BUILTIN_TOOL_NAMES
@@ -40,69 +60,75 @@ from deeptutor.utils.json_parser import parse_json_response
logger = logging.getLogger(__name__)
CHAT_EXCLUDED_TOOLS = {"geogebra_analysis"}
-CHAT_OPTIONAL_TOOLS = [name for name in BUILTIN_TOOL_NAMES if name not in CHAT_EXCLUDED_TOOLS]
+# Optional tools the user can toggle from the composer. ``read_source`` is
+# intentionally excluded — it is auto-enabled by the pipeline when sources
+# are attached and is invisible in the frontend tool list.
+CHAT_OPTIONAL_TOOLS = [
+ name
+ for name in BUILTIN_TOOL_NAMES
+ if name not in CHAT_EXCLUDED_TOOLS and name != "read_source"
+]
MAX_PARALLEL_TOOL_CALLS = 8
MAX_TOOL_RESULT_CHARS = 4000
-
-CHAT_STAGE_KEYS: tuple[str, ...] = (
- "responding",
- "answer_now",
- "thinking",
- "observing",
- "acting",
- "react_fallback",
+# Tool-iteration ceiling: small enough to prevent runaway loops, large
+# enough for genuinely multi-step retrieval. The default mirrors common
+# agent-framework defaults and is overridable via capabilities.chat.max_iterations.
+DEFAULT_MAX_ITERATIONS = 8
+# When messages exceed this fraction of the model's effective context
+# window, the in-turn guard replaces the largest stale tool-result with a
+# snip marker. Keeps headroom for the next LLM call without aborting.
+CONTEXT_WINDOW_GUARD_RATIO = 0.9
+TOOL_RESULT_SNIP_MARKER = (
+ "[earlier tool result snipped to stay within context window — "
+ "call the same tool again if the content is still needed]"
)
-
-@dataclass
-class _ChatLimits:
- """Per-stage ``max_tokens`` resolved from ``capabilities.chat`` in agents.yaml."""
-
- responding: int
- answer_now: int
- thinking: int
- observing: int
- acting: int
- react_fallback: int
-
- @classmethod
- def from_config(cls, cfg: dict[str, Any]) -> "_ChatLimits":
- # Defaults below mirror DEFAULT_CHAT_PARAMS so the pipeline still works
- # if the YAML block is missing entirely (e.g. minimal/legacy installs).
- fallback = {
- "responding": 8000,
- "answer_now": 8000,
- "thinking": 2000,
- "observing": 2000,
- "acting": 2000,
- "react_fallback": 1500,
- }
- resolved: dict[str, int] = {}
- for key in CHAT_STAGE_KEYS:
- stage_cfg = cfg.get(key) if isinstance(cfg, dict) else None
- if isinstance(stage_cfg, dict):
- value = stage_cfg.get("max_tokens", fallback[key])
- else:
- value = fallback[key]
- try:
- resolved[key] = int(value)
- except (TypeError, ValueError):
- resolved[key] = fallback[key]
- return cls(**resolved)
-
-
-@dataclass
-class ToolTrace:
- name: str
- arguments: dict[str, Any]
- result: str
- success: bool
- sources: list[dict[str, Any]]
- metadata: dict[str, Any]
+# Output protocol labels. The system prompt instructs the model to emit
+# exactly one of these as the FIRST line of every reply, wrapped in two
+# backticks each side, e.g. ``FINISH``. The pipeline parses this label
+# upfront and routes the rest of the stream accordingly:
+# FINISH → content events go straight to the answer body (llm_final_response)
+# TOOL → reply will use native tool_calls; prose goes to a reasoning sub-trace
+# THINK → intermediate reasoning only, no tools; loop continues; prose goes to a sub-trace
+# UNKNOWN is the parser's fallback when no valid label is detected within
+# LABEL_PROBE_MAX_CHARS — the pipeline then uses the legacy absorb-into-final
+# mechanism based on whether tool_calls came in.
+LABEL_FINISH = "FINISH"
+LABEL_TOOL = "TOOL"
+LABEL_THINK = "THINK"
+LABEL_UNKNOWN = "UNKNOWN"
+LABEL_OPTIONS: tuple[str, ...] = (LABEL_FINISH, LABEL_TOOL, LABEL_THINK)
+LABEL_PROBE_MAX_CHARS = 64
+
+
+def _classify_label(buffer: str) -> tuple[str, str] | None:
+ r"""Inspect a content buffer for a protocol label at the start.
+
+ Returns ``(label, after_text)`` once a valid ``\`\`FINISH\`\```/
+ ``\`\`TOOL\`\```/``\`\`THINK\`\``` prefix is detected (after any leading
+ whitespace) — caller routes ``after_text`` and all subsequent chunks
+ accordingly.
+
+ Returns ``None`` while the buffer is too short or still a partial prefix
+ match. Caller keeps buffering and tries again on the next chunk. The
+ caller is responsible for falling back to ``LABEL_UNKNOWN`` once
+ ``len(buffer) > LABEL_PROBE_MAX_CHARS``.
+ """
+ stripped = buffer.lstrip()
+ for label in LABEL_OPTIONS:
+ prefix = f"``{label}``"
+ if stripped.startswith(prefix):
+ after = stripped[len(prefix):]
+ # Eat the single separating newline / spaces after the label so
+ # the answer body / reasoning text doesn't start with stray
+ # blank lines.
+ return label, after.lstrip("\n\r ")
+ # Could still match — return None to keep buffering.
+ return None
class AgenticChatPipeline:
- """Run chat as a 4-stage agentic pipeline."""
+ """Run chat as a single iterative LLM loop with native tool calling."""
def __init__(self, language: str = "en") -> None:
self.language = "zh" if language.lower().startswith("zh") else "en"
@@ -115,9 +141,7 @@ class AgenticChatPipeline:
self.extra_headers = getattr(self.llm_config, "extra_headers", None) or {}
self.registry = get_tool_registry()
self._usage = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, "calls": 0}
- # capabilities.chat in agents.yaml drives token budgets and temperature
- # for every LLM call below; falls back to DEFAULT_CHAT_PARAMS if the
- # block is missing.
+
try:
chat_cfg = get_chat_params()
except Exception as exc:
@@ -127,9 +151,19 @@ class AgenticChatPipeline:
self._chat_temperature = float(chat_cfg.get("temperature", 0.2))
except (TypeError, ValueError):
self._chat_temperature = 0.2
- self._chat_limits = _ChatLimits.from_config(chat_cfg)
- # Prompts live in deeptutor/agents/chat/prompts/{zh,en}/agentic_chat.yaml
- # so all user-visible / LLM-facing copy is editable without touching code.
+ # Token budgets for the two LLM call shapes used by this pipeline.
+ # ``responding`` caps each loop iteration; ``answer_now`` caps the
+ # single-shot fallback when the user clicks "Answer now" mid-stream.
+ self._responding_max_tokens = _read_int(
+ chat_cfg.get("responding"), key="max_tokens", default=8000
+ )
+ self._answer_now_max_tokens = _read_int(
+ chat_cfg.get("answer_now"), key="max_tokens", default=8000
+ )
+ self._max_iterations = _read_int(
+ chat_cfg, key="max_iterations", default=DEFAULT_MAX_ITERATIONS
+ )
+
try:
self._prompts: dict[str, Any] = (
get_prompt_manager().load_prompts(
@@ -143,826 +177,734 @@ class AgenticChatPipeline:
logger.warning("Failed to load agentic_chat prompts: %s", exc)
self._prompts = {}
- def _accumulate_usage(self, response: Any) -> None:
- usage = getattr(response, "usage", None)
- if usage:
- self._usage["prompt_tokens"] += getattr(usage, "prompt_tokens", 0) or 0
- self._usage["completion_tokens"] += getattr(usage, "completion_tokens", 0) or 0
- self._usage["total_tokens"] += getattr(usage, "total_tokens", 0) or 0
- self._usage["calls"] += 1
-
- def _get_cost_summary(self) -> dict[str, Any] | None:
- if self._usage["calls"] == 0:
- return None
- return {
- "total_cost_usd": 0,
- "total_tokens": self._usage["total_tokens"],
- "total_calls": self._usage["calls"],
- }
-
+ # ------------------------------------------------------------------
+ # Public entry point
+ # ------------------------------------------------------------------
async def run(self, context: UnifiedContext, stream: StreamBus) -> None:
answer_now_context = self._extract_answer_now_context(context)
if answer_now_context is not None:
- final_response, trace_meta = await self._stage_answer_now(
- context=context,
- answer_now_context=answer_now_context,
- stream=stream,
- )
- result_payload: dict[str, Any] = {
- "response": final_response,
- "answer_now": True,
- "source_trace": trace_meta.get("label", "Answer now"),
- }
- cs = self._get_cost_summary()
- if cs:
- result_payload["metadata"] = {"cost_summary": cs}
- await stream.result(result_payload, source="chat")
+ await self._run_answer_now(context, answer_now_context, stream)
return
enabled_tools = self._compose_enabled_tools(context)
- thinking_text = await self._stage_thinking(context, enabled_tools, stream)
- tool_traces = await self._stage_acting(
- context=context,
- enabled_tools=enabled_tools,
- thinking_text=thinking_text,
- stream=stream,
+ use_native_tools = bool(enabled_tools) and self._can_use_native_tool_calling()
+ tool_schemas = (
+ self._build_llm_tool_schemas(enabled_tools, context)
+ if use_native_tools
+ else None
)
- observation = await self._stage_observing(
- context=context,
- enabled_tools=enabled_tools,
- thinking_text=thinking_text,
- tool_traces=tool_traces,
- stream=stream,
+
+ system_prompt = self._build_system_prompt(enabled_tools, context)
+ user_content = self._t(
+ "user_template",
+ default=context.user_message,
+ user_message=context.user_message,
)
- final_response, responding_trace = await self._stage_responding(
+ messages = self._build_messages(
context=context,
- enabled_tools=enabled_tools,
- thinking_text=thinking_text,
- observation=observation,
- tool_traces=tool_traces,
- stream=stream,
+ system_prompt=system_prompt,
+ user_content=user_content,
)
+ messages, images_stripped = self._prepare_messages_with_attachments(messages, context)
- all_sources: list[dict[str, Any]] = []
- for trace in tool_traces:
- all_sources.extend(trace.sources)
- if all_sources:
- await stream.sources(
- all_sources,
+ if images_stripped:
+ # ``images_stripped`` is a transient warning, not a sub-trace, so
+ # it carries no call_id (frontend ``CallTracePanel`` groups by
+ # call_id and would otherwise spawn an empty sub-trace row).
+ await stream.thinking(
+ self._t("notices.images_stripped", model=self.model or ""),
source="chat",
stage="responding",
- metadata=merge_trace_metadata(
- responding_trace,
- {"trace_kind": "sources"},
- ),
+ metadata={"trace_kind": "warning"},
)
- result_payload: dict[str, Any] = {
- "response": final_response,
- "observation": observation,
- "tool_traces": [asdict(trace) for trace in tool_traces],
- }
- cs = self._get_cost_summary()
- if cs:
- result_payload["metadata"] = {"cost_summary": cs}
- await stream.result(result_payload, source="chat")
-
- async def _stage_thinking(
- self,
- context: UnifiedContext,
- enabled_tools: list[str],
- stream: StreamBus,
- ) -> str:
- trace_meta = build_trace_metadata(
- call_id=new_call_id("chat-thinking"),
- phase="thinking",
- label=self._t("labels.reasoning", default="Reasoning"),
- call_kind="llm_reasoning",
- trace_id="chat-thinking",
- trace_role="thought",
- trace_group="stage",
- )
- async with stream.stage("thinking", source="chat", metadata=trace_meta):
- await stream.progress(
- trace_meta["label"],
- source="chat",
- stage="thinking",
- metadata=merge_trace_metadata(
- trace_meta,
- {"trace_kind": "call_status", "call_state": "running"},
- ),
- )
- thinking_user = self._t(
- "thinking.user",
- user_message=context.user_message,
- )
- messages = self._build_messages(
- context=context,
- system_prompt=self._thinking_system_prompt(enabled_tools, context),
- user_content=thinking_user or context.user_message,
- )
- messages, images_stripped = self._prepare_messages_with_attachments(
- messages,
- context,
- )
- if images_stripped:
- await stream.thinking(
- self._images_stripped_notice(),
- source="chat",
- stage="thinking",
- metadata=merge_trace_metadata(trace_meta, {"trace_kind": "llm_chunk"}),
+ aggregated_sources: list[dict[str, Any]] = []
+ final_text = ""
+ max_iter = max(1, self._max_iterations)
+ completed = False
+ iteration = 0
+ # Outer ``stage("responding")`` only drives the frontend's
+ # ``currentStage`` indicator ("DeepTutor responding…"). It carries no
+ # call_id so it does NOT spawn its own sub-trace; each LLM iteration
+ # and each tool call below allocate their own call_id and surface as
+ # individual sub-traces in CallTracePanel.
+ async with stream.stage("responding", source="chat"):
+ for iteration in range(max_iter):
+ await self._guard_context_window(messages, stream)
+
+ # Per-iter sub-trace identity. Created up front but ONLY
+ # opened by ``_stream_one_iteration`` when the resolved
+ # label is THINK / TOOL / UNKNOWN. A FINISH iter never
+ # opens it, so no empty sub-trace appears in the trace box.
+ iter_call_id = new_call_id(f"chat-iter-{iteration}")
+ iter_meta = build_trace_metadata(
+ call_id=iter_call_id,
+ phase="responding",
+ label=self._t("labels.reasoning", default="Reasoning"),
+ call_kind="llm_reasoning",
+ trace_id=iter_call_id,
+ trace_role="thought",
+ trace_group="stage",
)
-
- chunks: list[str] = []
- async for chunk in self._stream_messages(
- messages, max_tokens=self._chat_limits.thinking
- ):
- if not chunk:
- continue
- chunks.append(chunk)
- await stream.thinking(
- chunk,
- source="chat",
- stage="thinking",
- metadata=merge_trace_metadata(trace_meta, {"trace_kind": "llm_chunk"}),
- )
- await stream.progress(
- "",
- source="chat",
- stage="thinking",
- metadata=merge_trace_metadata(
- trace_meta,
- {"trace_kind": "call_status", "call_state": "complete"},
- ),
- )
- return clean_thinking_tags("".join(chunks), self.binding, self.model)
-
- async def _stage_acting(
- self,
- context: UnifiedContext,
- enabled_tools: list[str],
- thinking_text: str,
- stream: StreamBus,
- ) -> list[ToolTrace]:
- async with stream.stage("acting", source="chat"):
- if not enabled_tools:
- await stream.progress(
- self._t("notices.no_tools_enabled"),
- source="chat",
- stage="acting",
+ # Fresh final-response trace id per iter — FINISH path uses
+ # it to scope the body content events; intermediate iters
+ # never touch it.
+ final_call_id = new_call_id("chat-final-response")
+ final_meta = build_trace_metadata(
+ call_id=final_call_id,
+ phase="responding",
+ label=self._t("labels.final_response", default="Final response"),
+ call_kind="llm_final_response",
+ trace_id=final_call_id,
+ trace_role="response",
+ trace_group="stage",
)
- return []
- if self._can_use_native_tool_calling():
- return await self._run_native_tool_loop(
- context=context,
- enabled_tools=enabled_tools,
- thinking_text=thinking_text,
+ label, iteration_text, tool_calls = await self._stream_one_iteration(
+ messages=messages,
+ tool_schemas=tool_schemas,
stream=stream,
+ iter_meta=iter_meta,
+ final_meta=final_meta,
)
- await stream.progress(
- self._t("notices.react_fallback_switch"),
- source="chat",
- stage="acting",
- )
- return await self._run_react_fallback(
- context=context,
- enabled_tools=enabled_tools,
- thinking_text=thinking_text,
- stream=stream,
- )
-
- async def _stage_observing(
- self,
- context: UnifiedContext,
- enabled_tools: list[str],
- thinking_text: str,
- tool_traces: list[ToolTrace],
- stream: StreamBus,
- ) -> str:
- trace_meta = build_trace_metadata(
- call_id=new_call_id("chat-observing"),
- phase="observing",
- label=self._t("labels.observation", default="Observation"),
- call_kind="llm_observation",
- trace_id="chat-observing",
- trace_role="observe",
- trace_group="stage",
- )
- async with stream.stage("observing", source="chat", metadata=trace_meta):
- await stream.progress(
- trace_meta["label"],
- source="chat",
- stage="observing",
- metadata=merge_trace_metadata(
- trace_meta,
- {"trace_kind": "call_status", "call_state": "running"},
- ),
- )
- observation_prompt = self._t("observing.user_intro")
- messages = self._build_messages(
- context=context,
- system_prompt=self._observing_system_prompt(enabled_tools),
- user_content=(
- f"{observation_prompt}\n\n"
- f"{self._labeled_block('Thinking', thinking_text)}\n\n"
- f"{self._labeled_block('Tool Trace', self._format_tool_traces(tool_traces))}"
- ),
- )
-
- chunks: list[str] = []
- async for chunk in self._stream_messages(
- messages, max_tokens=self._chat_limits.observing
- ):
- if not chunk:
+ # Reconcile contradictions between the declared label and
+ # actual stream signals, then dispatch on the resolved
+ # action.
+ if label == LABEL_TOOL and not tool_calls:
+ # Model said TOOL but never emitted calls — fall back
+ # to a THINK iteration (the prose was reasoning).
+ label = LABEL_THINK
+ if label == LABEL_FINISH and tool_calls:
+ # Model said FINISH but still emitted tool_calls. Trust
+ # the tool intent — those calls happened mid-stream and
+ # the body already received the prose chunks before the
+ # calls appeared. Promote to TOOL so we dispatch.
+ label = LABEL_TOOL
+
+ if label == LABEL_FINISH:
+ # Content already streamed live to the answer body via
+ # the ``stream.content(call_kind=llm_final_response)``
+ # path inside ``_stream_one_iteration``. Nothing more
+ # to do — just record and exit.
+ final_text += iteration_text
+ completed = True
+ break
+
+ if label == LABEL_TOOL:
+ messages.append(
+ self._assistant_message_with_tool_calls(
+ content=iteration_text,
+ tool_calls=tool_calls,
+ )
+ )
+ iter_sources, tool_messages = await self._dispatch_tool_calls(
+ tool_calls=tool_calls,
+ context=context,
+ stream=stream,
+ iteration_index=iteration,
+ )
+ aggregated_sources.extend(iter_sources)
+ messages.extend(tool_messages)
continue
- chunks.append(chunk)
- await stream.observation(
- chunk,
- source="chat",
- stage="observing",
- metadata=merge_trace_metadata(trace_meta, {"trace_kind": "observation"}),
- )
- await stream.progress(
- "",
- source="chat",
- stage="observing",
- metadata=merge_trace_metadata(
- trace_meta,
- {"trace_kind": "call_status", "call_state": "complete"},
- ),
- )
- return clean_thinking_tags("".join(chunks), self.binding, self.model)
- async def _stage_responding(
- self,
- context: UnifiedContext,
- enabled_tools: list[str],
- thinking_text: str,
- observation: str,
- tool_traces: list[ToolTrace],
- stream: StreamBus,
- ) -> tuple[str, dict[str, Any]]:
- trace_meta = build_trace_metadata(
- call_id=new_call_id("chat-responding"),
- phase="responding",
- label=self._t("labels.final_response", default="Final response"),
- call_kind="llm_final_response",
- trace_id="chat-responding",
- trace_role="response",
- trace_group="stage",
- )
- async with stream.stage("responding", source="chat", metadata=trace_meta):
- await stream.progress(
- trace_meta["label"],
- source="chat",
- stage="responding",
- metadata=merge_trace_metadata(
- trace_meta,
- {"trace_kind": "call_status", "call_state": "running"},
- ),
- )
- user_prompt = self._t(
- "responding.user",
- user_message=context.user_message,
- observation=observation.strip() if observation.strip() else "(empty)",
- tool_trace=self._format_tool_traces(tool_traces),
- )
- messages = self._build_messages(
- context=context,
- system_prompt=self._responding_system_prompt(enabled_tools),
- user_content=user_prompt,
- )
- messages, _ = self._prepare_messages_with_attachments(messages, context)
+ if label == LABEL_THINK:
+ # Intermediate reasoning — no tools, no answer yet.
+ # Persist the prose into the conversation so the next
+ # iteration's LLM call can build on it.
+ if iteration_text:
+ messages.append(
+ {"role": "assistant", "content": iteration_text}
+ )
+ continue
- chunks: list[str] = []
- async for chunk in self._stream_messages(
- messages, max_tokens=self._chat_limits.responding
- ):
- if not chunk:
+ # LABEL_UNKNOWN — protocol violation fallback. Behave like
+ # the legacy "absorb-into-final" logic: if tool_calls came,
+ # treat as TOOL; otherwise treat as FINISH by emitting one
+ # synthetic content event and marking the existing sub-trace
+ # as absorbed so it doesn't visually duplicate the answer.
+ if tool_calls:
+ messages.append(
+ self._assistant_message_with_tool_calls(
+ content=iteration_text,
+ tool_calls=tool_calls,
+ )
+ )
+ iter_sources, tool_messages = await self._dispatch_tool_calls(
+ tool_calls=tool_calls,
+ context=context,
+ stream=stream,
+ iteration_index=iteration,
+ )
+ aggregated_sources.extend(iter_sources)
+ messages.extend(tool_messages)
continue
- chunks.append(chunk)
- await stream.content(
- chunk,
+
+ # No tool_calls + no valid label → treat as FINISH-fallback.
+ # The sub-trace was already opened during streaming; mark it
+ # absorbed so the frontend hides it, then emit the answer
+ # body content.
+ await stream.progress(
+ "",
source="chat",
stage="responding",
- metadata=merge_trace_metadata(trace_meta, {"trace_kind": "llm_chunk"}),
- )
- await stream.progress(
- "",
- source="chat",
- stage="responding",
- metadata=merge_trace_metadata(
- trace_meta,
- {"trace_kind": "call_status", "call_state": "complete"},
- ),
- )
- final_response = clean_thinking_tags("".join(chunks), self.binding, self.model)
- if not final_response.strip():
- # The provider returned an empty stream (zero non-empty chunks)
- # or only whitespace. This typically means: model hit a token
- # limit, was filtered, or treated the observation as the final
- # answer. Surface a non-terminal warning so the operator sees
- # the cause in logs and the UI can hint a Regenerate.
- prompt_chars = sum(len(str(m.get("content") or "")) for m in messages)
- logger.warning(
- "[%s] responding stage returned empty response "
- "(model=%s, chunks=%d, prompt_chars=%d, max_tokens=%d, observation_chars=%d)",
- trace_meta.get("call_id"),
- self.model,
- len(chunks),
- prompt_chars,
- self._chat_limits.responding,
- len(observation or ""),
- )
- await stream.error(
- self._t(
- "notices.empty_response",
- default=(
- "The model returned an empty response. "
- "Try Regenerate or rephrase the question."
- ),
+ metadata=merge_trace_metadata(
+ iter_meta,
+ {
+ "trace_kind": "call_status",
+ "call_state": "complete",
+ "absorbed_into_final": True,
+ },
),
+ )
+ await stream.content(
+ iteration_text,
source="chat",
stage="responding",
metadata=merge_trace_metadata(
- trace_meta,
- {
- "trace_kind": "warning",
- "warning_kind": "empty_response",
- "chunks": len(chunks),
- "prompt_chars": prompt_chars,
- "max_tokens": self._chat_limits.responding,
- # Explicitly mark as non-terminal so the runtime
- # does not flip the turn to ``failed``.
- "turn_terminal": False,
- },
+ final_meta, {"trace_kind": "llm_output"}
),
)
- return final_response, trace_meta
+ final_text += iteration_text
+ completed = True
+ break
+ else:
+ # Loop exhausted without a clean final response. Emit a
+ # one-off warning event (no call_id — not a sub-trace).
+ await stream.progress(
+ self._t("notices.max_iterations_reached"),
+ source="chat",
+ stage="responding",
+ metadata={"trace_kind": "warning"},
+ )
+
+ if aggregated_sources:
+ await stream.sources(
+ aggregated_sources,
+ source="chat",
+ stage="responding",
+ metadata={"trace_kind": "sources"},
+ )
- async def _stage_answer_now(
+ result_payload: dict[str, Any] = {
+ "response": final_text,
+ "iterations": iteration + 1,
+ "completed": completed,
+ }
+ cs = self._get_cost_summary()
+ if cs:
+ result_payload["metadata"] = {"cost_summary": cs}
+ await stream.result(result_payload, source="chat")
+
+ # ------------------------------------------------------------------
+ # Iteration core: one streaming LLM call with tools
+ # ------------------------------------------------------------------
+ async def _stream_one_iteration(
self,
- context: UnifiedContext,
- answer_now_context: dict[str, Any],
+ *,
+ messages: list[dict[str, Any]],
+ tool_schemas: list[dict[str, Any]] | None,
stream: StreamBus,
- ) -> tuple[str, dict[str, Any]]:
- trace_meta = build_trace_metadata(
- call_id=new_call_id("chat-answer-now"),
- phase="responding",
- label=self._t("labels.answer_now", default="Answer now"),
- call_kind="llm_final_response",
- trace_id="chat-answer-now",
- trace_role="response",
- trace_group="stage",
- )
- async with stream.stage("responding", source="chat", metadata=trace_meta):
+ iter_meta: dict[str, Any],
+ final_meta: dict[str, Any],
+ ) -> tuple[str, str, list[dict[str, Any]]]:
+ r"""Run one LLM streaming call. Parses the protocol label
+ (``\`\`FINISH\`\``` / ``\`\`TOOL\`\``` / ``\`\`THINK\`\```) from the FIRST chunks of
+ the content stream, then routes subsequent chunks accordingly:
+
+ * ``FINISH``: post-label chunks stream **directly to the answer body**
+ via ``stream.content(call_kind="llm_final_response")``. No iteration
+ sub-trace is ever opened — there's nothing intermediate to show.
+ * ``TOOL`` / ``THINK``: post-label chunks stream as ``stream.thinking``
+ events scoped to ``iter_meta.call_id`` so they fill a single
+ "Reasoning" sub-trace in CallTracePanel.
+
+ ``UNKNOWN`` is returned if the buffer exceeds ``LABEL_PROBE_MAX_CHARS``
+ without a valid label — the caller falls back to the legacy
+ absorb-into-final mechanism.
+
+ Returns ``(label, accumulated_post_label_text, parsed_tool_calls)``.
+ For ``FINISH`` the text reflects only what was streamed to the body;
+ for ``TOOL``/``THINK`` it's the reasoning prose that the next
+ iteration will see as the assistant's previous message.
+ """
+ client = self._build_openai_client()
+ kwargs: dict[str, Any] = {
+ "model": self.model,
+ "messages": messages,
+ "stream": True,
+ **self._completion_kwargs(max_tokens=self._responding_max_tokens),
+ }
+ if tool_schemas:
+ kwargs["tools"] = tool_schemas
+ kwargs["tool_choice"] = "auto"
+
+ label: str | None = None
+ label_buf = ""
+ sub_trace_opened = False
+ content_acc: list[str] = []
+ tc_acc: dict[int, dict[str, Any]] = {}
+ usage_seen: Any = None
+
+ async def _open_sub_trace() -> None:
+ nonlocal sub_trace_opened
+ if sub_trace_opened:
+ return
await stream.progress(
- trace_meta["label"],
+ iter_meta["label"],
source="chat",
stage="responding",
metadata=merge_trace_metadata(
- trace_meta,
+ iter_meta,
{"trace_kind": "call_status", "call_state": "running"},
),
)
+ sub_trace_opened = True
- original_user_message = str(
- answer_now_context.get("original_user_message") or context.user_message
- ).strip()
- partial_response = str(answer_now_context.get("partial_response") or "").strip()
- trace_summary = self._format_answer_now_events(answer_now_context.get("events"))
- user_prompt = self._t(
- "answer_now.user",
- original_user_message=original_user_message,
- partial_response=partial_response.strip()
- if partial_response.strip()
- else "(empty)",
- trace_summary=trace_summary,
- )
- messages = self._build_messages(
- context=context,
- system_prompt=self._responding_system_prompt([]),
- user_content=user_prompt,
- )
-
- chunks: list[str] = []
- async for chunk in self._stream_messages(
- messages, max_tokens=self._chat_limits.answer_now
- ):
- if not chunk:
- continue
- chunks.append(chunk)
+ async def _emit_text(text: str) -> None:
+ """Route a post-label text fragment to body or sub-trace."""
+ if not text:
+ return
+ content_acc.append(text)
+ if label == LABEL_FINISH:
await stream.content(
- chunk,
+ text,
source="chat",
stage="responding",
- metadata=merge_trace_metadata(trace_meta, {"trace_kind": "llm_chunk"}),
+ metadata=merge_trace_metadata(final_meta, {"trace_kind": "llm_chunk"}),
)
+ else:
+ # THINK / TOOL / UNKNOWN — all surface as reasoning sub-trace.
+ await _open_sub_trace()
+ await stream.thinking(
+ text,
+ source="chat",
+ stage="responding",
+ metadata=merge_trace_metadata(iter_meta, {"trace_kind": "llm_chunk"}),
+ )
+
+ response_stream = await client.chat.completions.create(**kwargs)
+ try:
+ async for chunk in response_stream:
+ if getattr(chunk, "usage", None):
+ usage_seen = chunk.usage
+ if not chunk.choices:
+ continue
+ delta = chunk.choices[0].delta
+ if delta is None:
+ continue
+
+ if delta.content:
+ text = delta.content
+ if label is None:
+ label_buf += text
+ parsed = _classify_label(label_buf)
+ if parsed is not None:
+ label, after_label = parsed
+ label_buf = ""
+ await _emit_text(after_label)
+ elif len(label_buf) > LABEL_PROBE_MAX_CHARS:
+ # Model didn't follow the protocol. Fall back —
+ # stream what we've buffered as reasoning and
+ # let the caller decide based on tool_calls.
+ label = LABEL_UNKNOWN
+ flushed = label_buf
+ label_buf = ""
+ await _emit_text(flushed)
+ else:
+ await _emit_text(text)
+
+ for tc_delta in getattr(delta, "tool_calls", None) or []:
+ # Tool-call delta is authoritative for the TOOL path.
+ # If we're still buffering a label, force-resolve as TOOL
+ # so the buffered prose flushes into the reasoning sub-
+ # trace and subsequent prose continues there.
+ if label is None:
+ label = LABEL_TOOL
+ flushed = label_buf
+ label_buf = ""
+ if flushed:
+ await _emit_text(flushed)
+ idx = getattr(tc_delta, "index", 0)
+ entry = tc_acc.setdefault(
+ idx, {"id": "", "name": "", "arguments": ""}
+ )
+ if getattr(tc_delta, "id", None):
+ entry["id"] = tc_delta.id
+ fn = getattr(tc_delta, "function", None)
+ if fn is not None:
+ if getattr(fn, "name", None):
+ entry["name"] = entry["name"] + fn.name
+ if getattr(fn, "arguments", None):
+ entry["arguments"] = entry["arguments"] + fn.arguments
+ finally:
+ close = getattr(response_stream, "close", None)
+ if callable(close):
+ with self._suppress_close_errors():
+ await close()
+
+ if usage_seen is not None:
+ self._accumulate_usage(_UsageShim(usage_seen))
+
+ # Stream ended while still buffering a label (very short reply that
+ # never reached LABEL_PROBE_MAX_CHARS and never matched). Flush as
+ # UNKNOWN — the caller will decide based on tool_calls.
+ if label is None:
+ label = LABEL_UNKNOWN
+ if label_buf:
+ await _emit_text(label_buf)
+ label_buf = ""
+
+ # Close the sub-trace if it was opened (THINK / TOOL / UNKNOWN
+ # paths). FINISH never opened one — its content went straight to
+ # the body.
+ if sub_trace_opened:
await stream.progress(
"",
source="chat",
stage="responding",
metadata=merge_trace_metadata(
- trace_meta,
+ iter_meta,
{"trace_kind": "call_status", "call_state": "complete"},
),
)
- return clean_thinking_tags("".join(chunks), self.binding, self.model), trace_meta
- async def _run_native_tool_loop(
+ text = clean_thinking_tags("".join(content_acc), self.binding, self.model)
+ ordered_tool_calls = [tc_acc[k] for k in sorted(tc_acc.keys())]
+ # Filter out empty / malformed deltas that some providers emit.
+ ordered_tool_calls = [tc for tc in ordered_tool_calls if tc.get("name")]
+ return label, text, ordered_tool_calls
+
+ # ------------------------------------------------------------------
+ # Tool dispatch
+ # ------------------------------------------------------------------
+ async def _dispatch_tool_calls(
self,
+ *,
+ tool_calls: list[dict[str, Any]],
context: UnifiedContext,
- enabled_tools: list[str],
- thinking_text: str,
stream: StreamBus,
- ) -> list[ToolTrace]:
- tool_schemas = self._build_llm_tool_schemas(enabled_tools, context)
- messages = self._build_messages(
- context=context,
- system_prompt=self._acting_system_prompt(enabled_tools, context),
- user_content=self._acting_user_prompt(context, thinking_text),
- )
- messages, _ = self._prepare_messages_with_attachments(messages, context)
- tool_traces: list[ToolTrace] = []
- client = self._build_openai_client()
- trace_meta = build_trace_metadata(
- call_id=new_call_id("chat-acting"),
- phase="acting",
- label=self._t("labels.tool_call", default="Tool call"),
- call_kind="tool_planning",
- trace_id="chat-acting",
- trace_role="tool",
- trace_group="tool_call",
- )
- await stream.progress(
- trace_meta["label"],
- source="chat",
- stage="acting",
- metadata=merge_trace_metadata(
- trace_meta,
- {"trace_kind": "call_status", "call_state": "running"},
- ),
- )
- response = await client.chat.completions.create(
- model=self.model,
- messages=messages,
- tools=tool_schemas,
- tool_choice="auto",
- **self._completion_kwargs(max_tokens=self._chat_limits.acting),
- )
- self._accumulate_usage(response)
- if not response.choices:
- return tool_traces
-
- choice = response.choices[0]
- message = choice.message
- assistant_content = self._message_text(message.content)
- raw_tool_calls = list(message.tool_calls or [])
-
- if assistant_content:
- await stream.thinking(
- assistant_content,
- source="chat",
- stage="acting",
- metadata=merge_trace_metadata(trace_meta, {"trace_kind": "llm_output"}),
- )
-
- if not raw_tool_calls:
- await stream.progress(
- self._t("notices.no_tool_call_needed"),
- source="chat",
- stage="acting",
- metadata=merge_trace_metadata(trace_meta, {"trace_kind": "progress"}),
- )
- await stream.progress(
- "",
- source="chat",
- stage="acting",
- metadata=merge_trace_metadata(
- trace_meta,
- {"trace_kind": "call_status", "call_state": "complete"},
- ),
- )
- return tool_traces
-
- pending_calls: list[tuple[str, str, dict[str, Any], dict[str, Any]]] = []
- if len(raw_tool_calls) > MAX_PARALLEL_TOOL_CALLS:
+ iteration_index: int,
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
+ """Execute one iteration's tool calls in parallel.
+
+ Each individual tool call is given its own trace ``call_id`` so
+ ``CallTracePanel`` renders each as a separate sub-trace row
+ (e.g. "Tool call · code_execution" + "Retrieve" + …) — matching the
+ user's "one LLM call or one tool call = one sub-trace" expectation.
+
+ Returns ``(aggregated_sources, tool_role_messages)``. Tool messages
+ are formatted for the OpenAI ``role=tool`` protocol so the next
+ iteration's LLM call sees them.
+ """
+ if len(tool_calls) > MAX_PARALLEL_TOOL_CALLS:
+ # Capped truncation notice carries no call_id — it's a one-off
+ # warning, not a sub-trace.
await stream.progress(
self._t(
"notices.too_many_tool_calls",
- requested=len(raw_tool_calls),
+ requested=len(tool_calls),
limit=MAX_PARALLEL_TOOL_CALLS,
),
source="chat",
stage="acting",
- metadata=merge_trace_metadata(trace_meta, {"trace_kind": "progress"}),
+ metadata={"trace_kind": "warning"},
)
- for tool_call in raw_tool_calls[:MAX_PARALLEL_TOOL_CALLS]:
- tool_name = tool_call.function.name
+ tool_calls = tool_calls[:MAX_PARALLEL_TOOL_CALLS]
+
+ prepared: list[tuple[str, str, dict[str, Any], dict[str, Any]]] = []
+ for tc in tool_calls:
+ tool_name = str(tc.get("name") or "").strip()
+ tool_call_id = str(tc.get("id") or "").strip()
tool_args = parse_json_response(
- tool_call.function.arguments or "{}",
+ tc.get("arguments") or "{}",
logger_instance=logger,
fallback={},
)
if not isinstance(tool_args, dict):
tool_args = {}
- execution_args = self._augment_tool_kwargs(
- tool_name,
- tool_args,
- context,
- thinking_text,
+ execution_args = self._augment_tool_kwargs(tool_name, tool_args, context)
+ prepared.append((tool_call_id, tool_name, dict(execution_args), execution_args))
+
+ # Allocate a fresh trace call_id per tool call so each shows as its
+ # own sub-trace in CallTracePanel. The OpenAI ``tool_call_id`` (used
+ # for the role=tool message protocol) is separate from this trace id.
+ per_tool_trace_meta: list[dict[str, Any]] = []
+ for tool_index, (tool_call_id, tool_name, _display, _exec_args) in enumerate(prepared):
+ trace_call_id = new_call_id(f"chat-iter-{iteration_index}-tool-{tool_index}")
+ base_meta = build_trace_metadata(
+ call_id=trace_call_id,
+ phase="acting",
+ label=self._t("labels.tool_call", default="Tool call"),
+ call_kind="tool_planning",
+ trace_id=trace_call_id,
+ trace_role="tool",
+ trace_group="tool_call",
+ )
+ per_tool_trace_meta.append(
+ merge_trace_metadata(
+ base_meta,
+ {
+ "tool_call_id": tool_call_id,
+ "tool_name": tool_name,
+ "tool_index": tool_index,
+ "iteration_index": iteration_index,
+ "session_id": context.session_id,
+ "turn_id": str(context.metadata.get("turn_id", "")),
+ },
+ )
)
- pending_calls.append((tool_call.id, tool_name, dict(execution_args), execution_args))
- for tool_index, (tool_call_id, tool_name, display_args, _execution_args) in enumerate(
- pending_calls
- ):
+ for tool_index, (tool_call_id, tool_name, display_args, _exec_args) in enumerate(prepared):
+ tool_meta = per_tool_trace_meta[tool_index]
await stream.tool_call(
tool_name=tool_name,
args=display_args,
source="chat",
stage="acting",
- metadata=self._tool_trace_metadata(
- trace_meta,
- context=context,
- tool_call_id=tool_call_id,
- tool_name=tool_name,
- tool_index=tool_index,
- ),
+ metadata=merge_trace_metadata(tool_meta, {"trace_kind": "tool_call"}),
)
- tool_results = await asyncio.gather(
+ results = await asyncio.gather(
*[
self._execute_tool_call(
tool_name,
- execution_args,
+ exec_args,
stream=stream,
retrieve_meta=self._retrieve_trace_metadata(
- trace_meta,
+ per_tool_trace_meta[tool_index],
context=context,
- tool_call_id=tool_call_id,
tool_name=tool_name,
- tool_index=tool_index,
- tool_args=execution_args,
+ tool_args=exec_args,
),
)
- for tool_index, (
- tool_call_id,
- tool_name,
- _display_args,
- execution_args,
- ) in enumerate(pending_calls)
+ for tool_index, (_tool_call_id, tool_name, _display, exec_args) in enumerate(
+ prepared
+ )
]
)
- for tool_index, (
- (tool_call_id, tool_name, display_args, _execution_args),
- tool_result,
- ) in enumerate(zip(pending_calls, tool_results, strict=False)):
- result_text = tool_result["result_text"]
- success = bool(tool_result["success"])
- sources = tool_result["sources"]
- metadata = tool_result["metadata"]
+ aggregated_sources: list[dict[str, Any]] = []
+ tool_messages: list[dict[str, Any]] = []
+ for tool_index, ((tool_call_id, tool_name, display_args, _exec_args), result) in enumerate(
+ zip(prepared, results, strict=False)
+ ):
+ result_text = str(result["result_text"])
+ tool_meta = per_tool_trace_meta[tool_index]
await stream.tool_result(
tool_name=tool_name,
result=result_text,
source="chat",
stage="acting",
- metadata=self._tool_trace_metadata(
- trace_meta,
- context=context,
- tool_call_id=tool_call_id,
- tool_name=tool_name,
- tool_index=tool_index,
- trace_kind="tool_result",
- ),
+ metadata=merge_trace_metadata(tool_meta, {"trace_kind": "tool_result"}),
)
-
- tool_traces.append(
- ToolTrace(
- name=tool_name,
- arguments=display_args,
- result=result_text,
- success=success,
- sources=sources,
- metadata=metadata,
- )
+ aggregated_sources.extend(result.get("sources") or [])
+ tool_messages.append(
+ {
+ "role": "tool",
+ "tool_call_id": tool_call_id,
+ "name": tool_name,
+ "content": result_text,
+ }
)
-
- await stream.progress(
- "",
- source="chat",
- stage="acting",
- metadata=merge_trace_metadata(
- trace_meta,
- {"trace_kind": "call_status", "call_state": "complete"},
- ),
- )
-
- return tool_traces
-
- async def _run_react_fallback(
+ return aggregated_sources, tool_messages
+
+ # ------------------------------------------------------------------
+ # Answer-now: cancel mid-stream and produce a final answer from what's
+ # already been generated. Single LLM call, tools disabled, partial draft
+ # injected as a fake assistant message so the model continues naturally.
+ # ------------------------------------------------------------------
+ async def _run_answer_now(
self,
context: UnifiedContext,
- enabled_tools: list[str],
- thinking_text: str,
+ answer_now_context: dict[str, Any],
stream: StreamBus,
- ) -> list[ToolTrace]:
- tool_traces: list[ToolTrace] = []
- tool_table = self.registry.build_prompt_text(
- enabled_tools,
- format="table",
- language=self.language,
- control_actions=[
- {
- "name": "done",
- "when_to_use": self._t("react_fallback.done_when_to_use"),
- "input_format": self._t("react_fallback.done_input_format"),
- }
- ],
- )
+ ) -> None:
+ partial_response = str(answer_now_context.get("partial_response") or "").strip()
+ original_user_message = str(
+ answer_now_context.get("original_user_message") or context.user_message
+ ).strip()
trace_meta = build_trace_metadata(
- call_id=new_call_id("chat-react"),
- phase="acting",
- label=self._t("labels.tool_call", default="Tool call"),
- call_kind="tool_planning",
- trace_id="chat-react",
- trace_role="tool",
- trace_group="tool_call",
- )
- await stream.progress(
- trace_meta["label"],
- source="chat",
- stage="acting",
- metadata=merge_trace_metadata(
- trace_meta,
- {"trace_kind": "call_status", "call_state": "running"},
- ),
+ call_id=new_call_id("chat-answer-now"),
+ phase="responding",
+ label=self._t("labels.answer_now", default="Answer now"),
+ call_kind="llm_final_response",
+ trace_id="chat-answer-now",
+ trace_role="response",
+ trace_group="stage",
)
- _fb_prompt = self._acting_user_prompt(context, thinking_text)
- _fb_system = self._react_fallback_system_prompt(tool_table, context)
- _chunks: list[str] = []
- async for _c in llm_stream(
- prompt=_fb_prompt,
- system_prompt=_fb_system,
- model=self.model,
- api_key=self.api_key,
- base_url=self.base_url,
- api_version=self.api_version,
- binding=self.binding,
- extra_headers=self.extra_headers or None,
- response_format={"type": "json_object"}
- if supports_response_format(self.binding, self.model)
- else None,
- **self._completion_kwargs(max_tokens=self._chat_limits.react_fallback),
- ):
- _chunks.append(_c)
- response = "".join(_chunks)
- _fb_in = int((len(_fb_prompt) + len(_fb_system)) / 3.5)
- _fb_out = int(len(response) / 3.5)
- self._usage["prompt_tokens"] += _fb_in
- self._usage["completion_tokens"] += _fb_out
- self._usage["total_tokens"] += _fb_in + _fb_out
- self._usage["calls"] += 1
-
- payload = parse_json_response(response, logger_instance=logger, fallback={})
- if not isinstance(payload, dict):
- payload = {}
-
- action = str(payload.get("action") or "done").strip()
- raw_action_input = payload.get("action_input")
- if isinstance(raw_action_input, dict):
- action_input = raw_action_input
- elif action == "rag" and isinstance(raw_action_input, str):
- action_input = {"query": raw_action_input}
- else:
- action_input = {}
- if action == "rag":
- # ReAct fallback has no schema enum to constrain kb_name; route to
- # the first attached KB so the action stays single-step for legacy
- # bindings. Native tool-calling lets the model pick autonomously.
- kb_choices = self._selected_kbs(context)
- if kb_choices:
- action_input.setdefault("kb_name", kb_choices[0])
-
- if action == "done":
- if response:
- await stream.thinking(
- response,
- source="chat",
- stage="acting",
- metadata=merge_trace_metadata(trace_meta, {"trace_kind": "llm_output"}),
- )
+ async with stream.stage("responding", source="chat", metadata=trace_meta):
await stream.progress(
- self._t("notices.no_tool_call_needed"),
+ trace_meta["label"],
source="chat",
- stage="acting",
- metadata=merge_trace_metadata(trace_meta, {"trace_kind": "progress"}),
+ stage="responding",
+ metadata=merge_trace_metadata(
+ trace_meta, {"trace_kind": "call_status", "call_state": "running"}
+ ),
+ )
+
+ system_prompt = self._build_system_prompt(enabled_tools=[], context=context)
+ messages = self._build_messages(
+ context=context,
+ system_prompt=system_prompt,
+ user_content=original_user_message,
)
+ messages, _ = self._prepare_messages_with_attachments(messages, context)
+ if partial_response:
+ messages.append({"role": "assistant", "content": partial_response})
+ messages.append(
+ {"role": "user", "content": self._t("answer_now.user", default="Finalize now.")}
+ )
+
+ chunks: list[str] = []
+ async for chunk in self._stream_messages(
+ messages, max_tokens=self._answer_now_max_tokens
+ ):
+ if not chunk:
+ continue
+ chunks.append(chunk)
+ await stream.content(
+ chunk,
+ source="chat",
+ stage="responding",
+ metadata=merge_trace_metadata(trace_meta, {"trace_kind": "llm_chunk"}),
+ )
await stream.progress(
"",
source="chat",
- stage="acting",
+ stage="responding",
metadata=merge_trace_metadata(
- trace_meta,
- {"trace_kind": "call_status", "call_state": "complete"},
+ trace_meta, {"trace_kind": "call_status", "call_state": "complete"}
),
)
- return tool_traces
+ final_text = clean_thinking_tags("".join(chunks), self.binding, self.model)
- tool_args = self._augment_tool_kwargs(action, action_input, context, thinking_text)
- display_args = dict(tool_args)
- if response:
- await stream.thinking(
- response,
- source="chat",
- stage="acting",
- metadata=merge_trace_metadata(trace_meta, {"trace_kind": "llm_output"}),
- )
- await stream.tool_call(
- tool_name=action,
- args=display_args,
- source="chat",
- stage="acting",
- metadata=merge_trace_metadata(
- trace_meta,
- {"trace_kind": "tool_call", "trace_role": "tool", "tool_name": action},
- ),
- )
+ result_payload: dict[str, Any] = {
+ "response": final_text,
+ "answer_now": True,
+ "source_trace": trace_meta.get("label", "Answer now"),
+ }
+ cs = self._get_cost_summary()
+ if cs:
+ result_payload["metadata"] = {"cost_summary": cs}
+ await stream.result(result_payload, source="chat")
+ # ------------------------------------------------------------------
+ # In-turn context-window guard
+ # ------------------------------------------------------------------
+ async def _guard_context_window(
+ self,
+ messages: list[dict[str, Any]],
+ stream: StreamBus,
+ ) -> None:
+ """Replace oldest tool-result contents with a snip marker until total
+ token count fits under ``CONTEXT_WINDOW_GUARD_RATIO`` of the model's
+ effective window. Never touches the system message or the original
+ user message — only ``role == 'tool'`` payloads. Cross-turn history
+ compression is handled separately by ``ContextBuilder``.
+ """
try:
- result = await self._execute_tool_call(
- action,
- tool_args,
- stream=stream,
- retrieve_meta=self._retrieve_trace_metadata(
- trace_meta,
- context=context,
- tool_call_id="chat-react-tool",
- tool_name=action,
- tool_index=0,
- tool_args=tool_args,
- ),
+ window = resolve_effective_context_window(
+ context_window=getattr(self.llm_config, "context_window", None),
+ model=str(self.model or ""),
+ max_tokens=getattr(self.llm_config, "max_tokens", None),
)
- result_text = result["result_text"]
- success = result["success"]
- sources = result["sources"]
- metadata = result["metadata"]
except Exception:
- logger.error("Fallback tool %s failed", action, exc_info=True)
- result_text = self._t("notices.tool_unknown_error", tool=action)
- success = False
- sources = []
- metadata = {"error": result_text}
-
- await stream.tool_result(
- tool_name=action,
- result=result_text,
- source="chat",
- stage="acting",
- metadata=merge_trace_metadata(
- trace_meta,
- {"trace_kind": "tool_result", "trace_role": "tool", "tool_name": action},
- ),
- )
- tool_traces.append(
- ToolTrace(
- name=action,
- arguments=display_args,
- result=result_text,
- success=success,
- sources=sources,
- metadata=metadata,
+ return
+ if not window or window <= 0:
+ return
+ budget = int(window * CONTEXT_WINDOW_GUARD_RATIO)
+ if self._estimate_messages_tokens(messages) <= budget:
+ return
+ snipped = False
+ for msg in messages:
+ if msg.get("role") != "tool":
+ continue
+ current_content = msg.get("content")
+ if current_content == TOOL_RESULT_SNIP_MARKER:
+ continue
+ msg["content"] = TOOL_RESULT_SNIP_MARKER
+ snipped = True
+ if self._estimate_messages_tokens(messages) <= budget:
+ break
+ if snipped:
+ # Warning is not a sub-trace — emit without a call_id.
+ await stream.progress(
+ self._t("notices.context_window_guard"),
+ source="chat",
+ stage="responding",
+ metadata={"trace_kind": "warning"},
)
+
+ @staticmethod
+ def _estimate_messages_tokens(messages: list[dict[str, Any]]) -> int:
+ # Local import to break the agents.chat ↔ services.session
+ # import cycle (context_builder pulls in agents.base_agent which
+ # re-enters this module during package init).
+ from deeptutor.services.session.context_builder import count_tokens
+
+ total = 0
+ for msg in messages:
+ content = msg.get("content")
+ if isinstance(content, str):
+ total += count_tokens(content)
+ elif isinstance(content, list):
+ for part in content:
+ if isinstance(part, dict) and part.get("type") == "text":
+ total += count_tokens(str(part.get("text") or ""))
+ return total
+
+ # ------------------------------------------------------------------
+ # System prompt + message construction
+ # ------------------------------------------------------------------
+ def _build_system_prompt(
+ self,
+ enabled_tools: list[str],
+ context: UnifiedContext,
+ ) -> str:
+ # ``list_with_usage`` renders one bullet per tool including the tool's
+ # ``when_to_use`` and ``input_format`` — pulled from per-tool YAML
+ # under ``deeptutor/tools/prompting/hints/{lang}/{tool}.yaml``. This
+ # is the only place per-tool guidance enters the chat persona prompt:
+ # disabled tools contribute nothing, so the model never sees
+ # instructions for tools it cannot call.
+ tool_list = self.registry.build_prompt_text(
+ enabled_tools,
+ format="list_with_usage",
+ language=self.language,
)
- await stream.progress(
- "",
- source="chat",
- stage="acting",
- metadata=merge_trace_metadata(
- trace_meta,
- {"trace_kind": "call_status", "call_state": "complete"},
- ),
+ system = self._t(
+ "system",
+ tool_list=tool_list or self._fallback_empty_tool_list(),
+ kb_note=self._kb_system_note(context),
)
-
- return tool_traces
+ return append_language_directive(system, self.language)
def _build_messages(
self,
+ *,
context: UnifiedContext,
system_prompt: str,
user_content: str,
) -> list[dict[str, Any]]:
+ """Assemble ``[system] + history + user``.
+
+ ``memory_context``, ``skills_context``, and ``source_manifest`` are
+ appended as separate ``---``-delimited sections after the main
+ system prompt so prompt caching stays effective when only the
+ manifest tail changes between turns.
+ """
system_parts = [system_prompt]
if context.memory_context:
system_parts.append(context.memory_context)
if context.skills_context:
system_parts.append(context.skills_context)
-
- messages: list[dict[str, Any]] = [{"role": "system", "content": "\n\n".join(system_parts)}]
+ if context.source_manifest:
+ system_parts.append(context.source_manifest)
+ messages: list[dict[str, Any]] = [
+ {"role": "system", "content": "\n\n---\n\n".join(system_parts)}
+ ]
for item in context.conversation_history:
role = item.get("role")
content = item.get("content")
@@ -984,88 +926,29 @@ class AgenticChatPipeline:
)
return mm_result.messages, mm_result.images_stripped
- async def _stream_messages(
- self,
- messages: list[dict[str, Any]],
- max_tokens: int,
- ):
- output_chars = 0
- async for chunk in llm_stream(
- prompt="",
- system_prompt="",
- model=self.model,
- api_key=self.api_key,
- base_url=self.base_url,
- api_version=self.api_version,
- binding=self.binding,
- messages=messages,
- extra_headers=self.extra_headers or None,
- **self._completion_kwargs(max_tokens=max_tokens),
- ):
- output_chars += len(chunk)
- yield chunk
- input_chars = sum(len(str(m.get("content", ""))) for m in messages)
- est_input = int(input_chars / 3.5)
- est_output = int(output_chars / 3.5)
- self._usage["prompt_tokens"] += est_input
- self._usage["completion_tokens"] += est_output
- self._usage["total_tokens"] += est_input + est_output
- self._usage["calls"] += 1
-
- def _build_openai_client(self):
- http_client = None
- if load_system_settings()["disable_ssl_verify"]:
- http_client = httpx.AsyncClient(verify=False) # nosec B501
-
- default_headers = self.extra_headers or None
- if self.binding == "azure_openai" or (self.binding == "openai" and self.api_version):
- return AsyncAzureOpenAI(
- api_key=self.api_key or "sk-no-key-required",
- azure_endpoint=self.base_url,
- api_version=self.api_version,
- http_client=http_client,
- default_headers=default_headers,
- )
- return AsyncOpenAI(
- api_key=self.api_key or "sk-no-key-required",
- base_url=self.base_url or None,
- http_client=http_client,
- default_headers=default_headers,
- )
-
- def _completion_kwargs(self, max_tokens: int) -> dict[str, Any]:
- kwargs: dict[str, Any] = {"temperature": self._chat_temperature}
- if self.model:
- kwargs.update(get_token_limit_kwargs(self.model, max_tokens))
- return kwargs
-
- def _can_use_native_tool_calling(self) -> bool:
- if not supports_tools(self.binding, self.model):
- return False
- return self.binding not in {
- "anthropic",
- "claude",
- "ollama",
- "lm_studio",
- "vllm",
- "llama_cpp",
- }
-
+ # ------------------------------------------------------------------
+ # Tool selection + scheme construction
+ # ------------------------------------------------------------------
def _compose_enabled_tools(self, context: UnifiedContext) -> list[str]:
"""Resolve the tool set for this turn.
- RAG is no longer a user-selectable tool: it is automatically available
- iff the user attached one or more knowledge bases. Selecting KBs is the
- only signal — the LLM still decides whether (and which KB) to query.
+ - User-toggled tools come from ``context.enabled_tools``, filtered
+ by ``CHAT_OPTIONAL_TOOLS`` (so ``geogebra_analysis`` and
+ ``read_source`` are never user-toggleable here).
+ - ``rag`` is auto-included iff the user attached any KB.
+ - ``read_source`` is auto-included iff the turn has a non-empty
+ source index (notebook / book / history / question / attachment).
"""
requested = [tool for tool in (context.enabled_tools or []) if tool != "rag"]
normalized = [
tool.name
for tool in self.registry.get_enabled(requested)
- if tool.name not in CHAT_EXCLUDED_TOOLS
+ if tool.name in CHAT_OPTIONAL_TOOLS
]
if self._selected_kbs(context):
normalized.append("rag")
+ if self._source_index(context):
+ normalized.append("read_source")
return normalized
def _build_llm_tool_schemas(
@@ -1073,40 +956,47 @@ class AgenticChatPipeline:
enabled_tools: list[str],
context: UnifiedContext,
) -> list[dict[str, Any]]:
- """Return per-turn OpenAI tool schemas.
+ """Return per-turn OpenAI tool schemas, with per-tool constraints.
- For ``rag``, ``kb_name`` is constrained to the user's attached
- knowledge bases so the model picks one explicitly — even when only a
- single KB is attached, the enum still has one element.
+ - ``rag.kb_name`` is restricted to the attached KBs as an enum.
+ - ``read_source.source_id`` is restricted to the attached source
+ ids as an enum (this makes the LLM less likely to hallucinate
+ ids and lets the OpenAI SDK validate the call client-side).
"""
schemas = self.registry.build_openai_schemas(enabled_tools)
kb_choices = self._selected_kbs(context)
+ source_ids = sorted((self._source_index(context) or {}).keys())
for schema in schemas:
function = schema.get("function") if isinstance(schema, dict) else None
- if not isinstance(function, dict) or function.get("name") != "rag":
+ if not isinstance(function, dict):
continue
parameters = function.get("parameters")
if not isinstance(parameters, dict):
continue
- properties = parameters.get("properties")
- if isinstance(properties, dict):
+ properties = parameters.get("properties") or {}
+ if function.get("name") == "rag" and isinstance(properties, dict):
query_schema = properties.get("query")
if isinstance(query_schema, dict):
query_schema.setdefault("minLength", 1)
kb_schema = properties.get("kb_name")
if isinstance(kb_schema, dict):
kb_schema["enum"] = kb_choices
+ if function.get("name") == "read_source" and isinstance(properties, dict):
+ sid_schema = properties.get("source_id")
+ if isinstance(sid_schema, dict) and source_ids:
+ sid_schema["enum"] = source_ids
parameters["additionalProperties"] = False
return schemas
@staticmethod
def _extract_answer_now_context(context: UnifiedContext) -> dict[str, Any] | None:
- # 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)
+ # ------------------------------------------------------------------
+ # Tool execution
+ # ------------------------------------------------------------------
async def _execute_tool_call(
self,
tool_name: str,
@@ -1189,63 +1079,11 @@ class AgenticChatPipeline:
"metadata": {"error": str(exc)},
}
- def _tool_trace_metadata(
- self,
- trace_meta: dict[str, Any],
- *,
- context: UnifiedContext,
- tool_call_id: str,
- tool_name: str,
- tool_index: int,
- trace_kind: str = "tool_call",
- ) -> dict[str, Any]:
- return merge_trace_metadata(
- trace_meta,
- {
- "trace_kind": trace_kind,
- "trace_role": "tool",
- "tool_call_id": tool_call_id,
- "tool_name": tool_name,
- "tool_index": tool_index,
- "session_id": context.session_id,
- "turn_id": str(context.metadata.get("turn_id", "")),
- },
- )
-
- def _retrieve_trace_metadata(
- self,
- trace_meta: dict[str, Any],
- *,
- context: UnifiedContext,
- tool_call_id: str,
- tool_name: str,
- tool_index: int,
- tool_args: dict[str, Any],
- ) -> dict[str, Any] | None:
- if tool_name != "rag":
- return None
- return derive_trace_metadata(
- trace_meta,
- call_id=new_call_id(f"chat-retrieve-{tool_index + 1}"),
- label=self._t("labels.retrieve", default="Retrieve"),
- call_kind="rag_retrieval",
- trace_role="retrieve",
- trace_group="retrieve",
- trace_id=f"{trace_meta.get('trace_id', 'chat')}-retrieve-{tool_index + 1}",
- tool_call_id=tool_call_id,
- tool_name=tool_name,
- tool_index=tool_index,
- session_id=context.session_id,
- turn_id=str(context.metadata.get("turn_id", "")),
- query=str(tool_args.get("query", "") or ""),
- )
-
def _augment_tool_kwargs(
self,
tool_name: str,
args: dict[str, Any],
context: UnifiedContext,
- thinking_text: str,
) -> dict[str, Any]:
from deeptutor.services.path_service import get_path_service
@@ -1265,7 +1103,7 @@ class AgenticChatPipeline:
if task_dir is not None:
kwargs.setdefault("workspace_dir", str(task_dir / "code_runs"))
elif tool_name in {"reason", "brainstorm"}:
- kwargs.setdefault("context", thinking_text)
+ kwargs.setdefault("context", context.user_message)
elif tool_name == "paper_search":
kwargs.setdefault("max_results", 3)
kwargs.setdefault("years_limit", 3)
@@ -1274,185 +1112,197 @@ class AgenticChatPipeline:
kwargs.setdefault("query", context.user_message)
if task_dir is not None:
kwargs.setdefault("output_dir", str(task_dir / "web_search"))
+ elif tool_name == "read_source":
+ # ReadSourceTool reads from this per-turn map rather than from
+ # any shared state, so each turn's sources stay isolated.
+ kwargs["source_index"] = self._source_index(context)
return kwargs
- def _acting_system_prompt(self, enabled_tools: list[str], context: UnifiedContext) -> str:
- tool_list = self.registry.build_prompt_text(
- enabled_tools,
- format="list",
- language=self.language,
- )
- tool_aliases = self.registry.build_prompt_text(
- enabled_tools,
- format="aliases",
- language=self.language,
- )
- return self._t(
- "acting.system",
- tool_list=tool_list or self._fallback_empty_tool_list(),
- tool_aliases=tool_aliases or self._fallback_empty_tool_list(),
- max_parallel_tools=MAX_PARALLEL_TOOL_CALLS,
- kb_note=self._kb_system_note(context),
- )
-
- def _react_fallback_system_prompt(self, tool_table: str, context: UnifiedContext) -> str:
- return self._t(
- "react_fallback.system",
- tool_table=tool_table,
- kb_note=self._kb_system_note(context),
- )
-
- def _thinking_system_prompt(self, enabled_tools: list[str], context: UnifiedContext) -> str:
- tool_list = self.registry.build_prompt_text(
- enabled_tools,
- format="list",
- language=self.language,
- )
- return self._t(
- "thinking.system",
- tool_list=tool_list or self._fallback_empty_tool_list(),
- kb_note=self._kb_system_note(context),
+ # ------------------------------------------------------------------
+ # Tool / KB metadata helpers
+ # ------------------------------------------------------------------
+ def _retrieve_trace_metadata(
+ self,
+ tool_meta: dict[str, Any],
+ *,
+ context: UnifiedContext,
+ tool_name: str,
+ tool_args: dict[str, Any],
+ ) -> dict[str, Any] | None:
+ """Build the retrieve-flavoured metadata for ``rag`` progress events.
+
+ Each RAG call already has its own ``tool_meta`` (with its own
+ ``call_id``) allocated by :py:meth:`_dispatch_tool_calls`; we
+ derive a "retrieve" variant of it so the in-tool progress events
+ (provider selection, chunk retrieval, etc.) stay attached to the
+ same sub-trace but show as ``trace_role=retrieve`` for the
+ chevron icon. For non-rag tools we return ``None`` so the
+ executor skips the retrieve-progress surface.
+ """
+ if tool_name != "rag":
+ return None
+ return derive_trace_metadata(
+ tool_meta,
+ label=self._t("labels.retrieve", default="Retrieve"),
+ call_kind="rag_retrieval",
+ trace_role="retrieve",
+ trace_group="retrieve",
+ query=str(tool_args.get("query", "") or ""),
)
- def _selected_kbs(self, context: UnifiedContext) -> list[str]:
+ @staticmethod
+ def _selected_kbs(context: UnifiedContext) -> list[str]:
return [str(kb).strip() for kb in context.knowledge_bases if str(kb).strip()]
+ @staticmethod
+ def _source_index(context: UnifiedContext) -> dict[str, str]:
+ idx = context.metadata.get("source_index")
+ if isinstance(idx, dict) and idx:
+ return idx
+ return {}
+
def _kb_system_note(self, context: UnifiedContext) -> str:
kbs = self._selected_kbs(context)
if not kbs:
return ""
joined = ", ".join(kbs)
- if getattr(self, "language", "en") == "zh":
+ if self.language == "zh":
return f"用户已挂载知识库:{joined}。调用 rag 时,kb_name 必须从其中选一个。"
return (
f"Attached knowledge bases: {joined}. When calling rag, kb_name must "
"be one of these names."
)
- def _observing_system_prompt(self, enabled_tools: list[str]) -> str:
- tool_list = self.registry.build_prompt_text(
- enabled_tools,
- format="list",
- language=self.language,
- )
- has_rag = "rag" in enabled_tools
- rag_hint = self._t("observing.rag_hint") if has_rag else ""
- return self._t(
- "observing.system",
- tool_list=tool_list or self._fallback_empty_tool_list(),
- rag_hint=rag_hint,
- )
-
- def _responding_system_prompt(self, enabled_tools: list[str]) -> str:
- tool_list = self.registry.build_prompt_text(
- enabled_tools,
- format="list",
- language=self.language,
- )
- has_rag = "rag" in enabled_tools
- rag_hint = self._t("responding.rag_hint") if has_rag else ""
- system_prompt = self._t(
- "responding.system",
- tool_list=tool_list or self._fallback_empty_tool_list(),
- rag_hint=rag_hint,
- )
- return append_language_directive(system_prompt, self.language)
-
- def _acting_user_prompt(self, context: UnifiedContext, thinking_text: str) -> str:
- return self._t(
- "acting.user",
- user_message=context.user_message,
- thinking=thinking_text.strip() if thinking_text.strip() else "(empty)",
- max_parallel_tools=MAX_PARALLEL_TOOL_CALLS,
- )
-
def _fallback_empty_tool_list(self) -> str:
return "- 无" if self.language == "zh" else "- none"
- def _format_tool_traces(self, tool_traces: list[ToolTrace]) -> str:
- if not tool_traces:
- return self._t("empty.no_tool_traces")
-
- blocks: list[str] = []
- for idx, trace in enumerate(tool_traces, start=1):
- blocks.append(
- "\n".join(
- [
- f"{idx}. {trace.name}",
- f"arguments: {json.dumps(trace.arguments, ensure_ascii=False)}",
- f"success: {trace.success}",
- f"result: {self._truncate_tool_result(trace.result)}",
- ]
- )
- )
- return "\n\n".join(blocks)
-
- def _format_answer_now_events(self, events: Any) -> str:
- if not isinstance(events, list) or not events:
- return self._t("empty.no_intermediate_trace")
+ # ------------------------------------------------------------------
+ # LLM call helpers
+ # ------------------------------------------------------------------
+ @staticmethod
+ def _assistant_message_with_tool_calls(
+ content: str,
+ tool_calls: list[dict[str, Any]],
+ ) -> dict[str, Any]:
+ return {
+ "role": "assistant",
+ "content": content or None,
+ "tool_calls": [
+ {
+ "id": tc["id"],
+ "type": "function",
+ "function": {
+ "name": tc["name"],
+ "arguments": tc.get("arguments") or "{}",
+ },
+ }
+ for tc in tool_calls
+ ],
+ }
- 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")
- label_parts = [event_type]
- if stage:
- label_parts.append(stage)
- line = f"{index}. {' / '.join(label_parts)}"
- if content:
- line += f": {self._truncate_tool_result(content, limit=1200)}"
- 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 self._t("empty.no_intermediate_trace")
- return "\n".join(lines)
+ async def _stream_messages(
+ self,
+ messages: list[dict[str, Any]],
+ max_tokens: int,
+ ):
+ """Stream a single tool-less LLM call. Used by answer-now."""
+ output_chars = 0
+ async for chunk in llm_stream(
+ prompt="",
+ system_prompt="",
+ model=self.model,
+ api_key=self.api_key,
+ base_url=self.base_url,
+ api_version=self.api_version,
+ binding=self.binding,
+ messages=messages,
+ extra_headers=self.extra_headers or None,
+ **self._completion_kwargs(max_tokens=max_tokens),
+ ):
+ output_chars += len(chunk)
+ yield chunk
+ input_chars = sum(len(str(m.get("content", ""))) for m in messages)
+ est_input = int(input_chars / 3.5)
+ est_output = int(output_chars / 3.5)
+ self._usage["prompt_tokens"] += est_input
+ self._usage["completion_tokens"] += est_output
+ self._usage["total_tokens"] += est_input + est_output
+ self._usage["calls"] += 1
- @staticmethod
- def _message_text(content: Any) -> str:
- if isinstance(content, str):
- return content
- if isinstance(content, list):
- texts = [
- str(part.get("text", ""))
- for part in content
- if isinstance(part, dict) and part.get("type") == "text"
- ]
- return "\n".join(texts).strip()
- return str(content or "")
+ def _build_openai_client(self):
+ http_client = None
+ if load_system_settings()["disable_ssl_verify"]:
+ http_client = httpx.AsyncClient(verify=False) # nosec B501
+ default_headers = self.extra_headers or None
+ if self.binding == "azure_openai" or (self.binding == "openai" and self.api_version):
+ return AsyncAzureOpenAI(
+ api_key=self.api_key or "sk-no-key-required",
+ azure_endpoint=self.base_url,
+ api_version=self.api_version,
+ http_client=http_client,
+ default_headers=default_headers,
+ )
+ return AsyncOpenAI(
+ api_key=self.api_key or "sk-no-key-required",
+ base_url=self.base_url or None,
+ http_client=http_client,
+ default_headers=default_headers,
+ )
- @staticmethod
- def _truncate_tool_result(content: str, limit: int = MAX_TOOL_RESULT_CHARS) -> str:
- cleaned = content.strip()
- if len(cleaned) <= limit:
- return cleaned
- return cleaned[: limit - 3].rstrip() + "..."
+ def _completion_kwargs(self, max_tokens: int) -> dict[str, Any]:
+ kwargs: dict[str, Any] = {"temperature": self._chat_temperature}
+ if self.model:
+ kwargs.update(get_token_limit_kwargs(self.model, max_tokens))
+ return kwargs
- def _images_stripped_notice(self) -> str:
- return self._t("notices.images_stripped", model=self.model or "")
+ def _can_use_native_tool_calling(self) -> bool:
+ # Same gating as before: providers we know reliably support OpenAI
+ # function-calling. For other bindings the loop still runs but
+ # without tool schemas — the model just chats.
+ if not supports_tools(self.binding, self.model):
+ return False
+ return self.binding not in {
+ "anthropic",
+ "claude",
+ "ollama",
+ "lm_studio",
+ "vllm",
+ "llama_cpp",
+ }
- @staticmethod
- def _labeled_block(label: str, content: str) -> str:
- return f"[{label}]\n{content.strip() if content.strip() else '(empty)'}"
+ # ------------------------------------------------------------------
+ # Usage tracking
+ # ------------------------------------------------------------------
+ def _accumulate_usage(self, response: Any) -> None:
+ usage = getattr(response, "usage", None) or response
+ prompt = getattr(usage, "prompt_tokens", 0) or 0
+ completion = getattr(usage, "completion_tokens", 0) or 0
+ total = getattr(usage, "total_tokens", prompt + completion) or 0
+ if prompt or completion or total:
+ self._usage["prompt_tokens"] += int(prompt)
+ self._usage["completion_tokens"] += int(completion)
+ self._usage["total_tokens"] += int(total)
+ self._usage["calls"] += 1
- def _text(self, *, zh: str, en: str) -> str:
- return zh if self.language == "zh" else en
+ def _get_cost_summary(self) -> dict[str, Any] | None:
+ if self._usage["calls"] == 0:
+ return None
+ return {
+ "total_cost_usd": 0,
+ "total_tokens": self._usage["total_tokens"],
+ "total_calls": self._usage["calls"],
+ "prompt_tokens": self._usage["prompt_tokens"],
+ "completion_tokens": self._usage["completion_tokens"],
+ }
+ # ------------------------------------------------------------------
+ # YAML prompt lookup
+ # ------------------------------------------------------------------
def _t(self, key: str, default: str = "", **kwargs: Any) -> str:
- """Look up a YAML-loaded prompt by dotted key (e.g. ``thinking.system``).
-
- - Returns ``default`` if the key is missing or value is not a string.
- - When ``kwargs`` are passed, the string is rendered via ``str.format``;
- missing placeholders fall back to the unrendered template instead of
- crashing the pipeline.
- """
+ """Look up a YAML-loaded prompt by dotted key. Returns ``default``
+ when missing. Renders via ``str.format`` when ``kwargs`` are
+ provided; missing placeholders leave the template unrendered
+ instead of crashing the pipeline."""
value: Any = self._prompts
for part in key.split("."):
if not isinstance(value, dict) or part not in value:
@@ -1466,3 +1316,32 @@ class AgenticChatPipeline:
except (KeyError, IndexError, ValueError):
return value
return value
+
+ # ------------------------------------------------------------------
+ # Misc small helpers
+ # ------------------------------------------------------------------
+ @staticmethod
+ def _suppress_close_errors():
+ from contextlib import suppress
+
+ return suppress(Exception)
+
+
+class _UsageShim:
+ """Adapt OpenAI streaming ``CompletionUsage`` into the shape
+ ``_accumulate_usage`` expects (it walks ``response.usage`` fields)."""
+
+ def __init__(self, raw: Any) -> None:
+ self.usage = raw
+
+
+def _read_int(cfg: Any, *, key: str, default: int) -> int:
+ """Pull an integer from a nested YAML dict, falling back to ``default``."""
+ if isinstance(cfg, dict):
+ value = cfg.get(key, default)
+ else:
+ value = default
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return default
diff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
index 7103cb89c..02bdf4d6c 100644
--- a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
+++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
@@ -1,176 +1,115 @@
# AgenticChatPipeline prompts (English)
-# These prompts are consumed by deeptutor.agents.chat.agentic_pipeline.AgenticChatPipeline,
-# which powers the chat capability's 4-stage pipeline: thinking → acting → observing → responding.
-# Independent from chat_agent.yaml in this folder (used by the legacy single-turn ChatAgent).
+# Single-loop chat pipeline: one merged system prompt; the LLM decides whether
+# to call tools natively, and the pipeline iterates until the model returns a
+# final response. Consumed by deeptutor.agents.chat.agentic_pipeline.
# ---------------------------------------------------------------------------
# Stage labels (used in trace metadata, surfaced in UI)
# ---------------------------------------------------------------------------
labels:
reasoning: "Reasoning"
- observation: "Observation"
- final_response: "Final response"
tool_call: "Tool call"
retrieve: "Retrieve"
+ final_response: "Final response"
answer_now: "Answer now"
# ---------------------------------------------------------------------------
-# Thinking stage
+# Single chat system prompt (capability-agnostic chat persona)
# ---------------------------------------------------------------------------
-thinking:
- system: |-
- You are DeepTutor's internal thinking module (NOT user-facing). Your output is a brief internal analysis memo consumed by the downstream acting / responding stages. It will never be shown to the user directly.
-
- Output format (use natural paragraphs, no headings needed):
- - User goal: summarize what the user actually wants in 1-2 sentences.
- - Known vs. missing: what information is already available in the conversation, and what is still missing.
- - Tool plan: which tools could fill the gaps, with brief rationale. Write "No tools needed" if information is sufficient.
- - Answer key points: 2-4 key points the final answer should cover.
-
- Critical constraints:
- - Output ONLY the internal analysis memo. Do NOT produce a user-facing answer, conclusion, or worked solution.
- - You may mention which tools seem useful, but do not call tools in this stage.
- - Keep it concise — no more than 200 words.
-
- {kb_note}
- Enabled tools:
- {tool_list}
- user: |-
- [User request]
- {user_message}
+# This template names NO specific tools and contains NO tool-specific usage
+# guidance. All "when to use which tool, with what arguments" copy is
+# injected dynamically through {tool_list} from per-tool YAML hints, and only
+# appears when the corresponding tool is actually enabled.
+#
+# Placeholders filled by the pipeline at call time:
+# {kb_note} — knowledge-base attachment notice (may be empty)
+# {tool_list} — enabled-tool catalog with short_description / when_to_use /
+# input_format (may be empty)
+#
+# memory_context, skills_context, and source_manifest are appended as
+# separate top-level system sections by the pipeline — they are NOT
+# substituted into this template — so prompt caching stays effective when
+# only the manifest tail changes between turns.
+system: |-
+ You are DeepTutor, an interactive tutor that helps the user think through their question. Reply directly to the user — never describe your internal pipeline, stages, or planning out loud.
- Produce the internal analysis memo (do NOT answer the user or draw conclusions).
+ # Output protocol (mandatory — every reply must comply)
-# ---------------------------------------------------------------------------
-# Acting stage
-# ---------------------------------------------------------------------------
-acting:
- system: |-
- You are DeepTutor's tool-using agent. Based on the user request and prior thinking, autonomously choose and call only the enabled tools that are truly helpful.
-
- Rules:
- 1. Review the full enabled tool list before deciding; do not fixate on a single tool too early.
- 2. For complex questions that need definitions, grounding, outside evidence, papers, calculation, or deeper reasoning, prefer calling multiple complementary tools in parallel so each one covers a distinct information need.
- 3. Call tools only when they add value, but when they materially improve answer quality you should use them fully.
- 4. Use concrete, executable arguments grounded in the user's request, and adapt the wording when different tools need different query styles.
- 5. When calling rag, the query must be a non-empty natural-language retrieval sentence and kb_name must be one of the attached knowledge bases. To consult several knowledge bases, issue one rag call per kb_name in the same turn.
- 6. If enough evidence already exists, you may skip tool use.
- 7. Do not produce the final student-facing answer here; this stage is only for tool use.
- 8. At most {max_parallel_tools} tools may run in parallel in one turn; if several complementary tools are relevant, prefer issuing them together in the same turn.
-
- {kb_note}
- Enabled tools:
- {tool_list}
-
- Tool usage notes:
- {tool_aliases}
- user: |-
- User request:
- {user_message}
+ Every reply MUST begin with exactly one of these three labels on the very first line, all-caps, wrapped with two backticks on each side:
- [Thinking]
- {thinking}
+ ``FINISH`` → This reply IS the final user-facing answer. No tools. Whatever follows the label is the answer.
+ ``TOOL`` → This reply will use tools. After the label you may write one short sentence of intent, then emit native tool_calls.
+ ``THINK`` → This reply is intermediate reasoning — **no tools, and not the final answer either**. You're writing your thoughts to push toward the next iteration. The next iteration will continue from here and eventually finish with ``FINISH``.
- First reason about which information gaps require tools, using the full enabled tool list. If tool use is needed, prefer calling multiple complementary tools in the same turn, up to {max_parallel_tools} total.
+ Pick one per reply based on current context:
+ - Simple question / enough info → ``FINISH``.
+ - Need external info / computation / retrieval → ``TOOL``.
+ - Complex problem that benefits from multi-step reasoning before acting → ``THINK`` (loop a few rounds; always close with ``FINISH``).
-# ---------------------------------------------------------------------------
-# Observing stage
-# ---------------------------------------------------------------------------
-observing:
- system: |-
- You are DeepTutor's observing stage. Based on the outputs from the thinking and acting stages, prepare an internal synthesis for the final answer stage. Do not answer the student directly.
-
- Prioritize:
- 1. confirmed facts and conclusions
- 2. key evidence from tool outputs
- 3. what the final answer must explain clearly
- {rag_hint}
- Tool context for this turn:
- {tool_list}
- # Injected at {rag_hint} when RAG is enabled
- rag_hint: |-
- If RAG (knowledge base retrieval) was called, assess whether the question is best answered from the retrieved content, from memory / general knowledge, or a mix of both — include this judgment in your synthesis. When tool evidence conflicts with the initial thinking, prefer the evidence.
- user_intro: |-
- Summarize what was learned from the reasoning and tool execution for the tutor's internal observation note. Focus on confirmed facts, remaining uncertainty, and what the final answer should emphasize. Do not address the student directly.
+ Examples:
+ ``FINISH``
+ 9876543 + 234567 = 10,111,110.
-# ---------------------------------------------------------------------------
-# Responding stage (final user-facing answer)
-# ---------------------------------------------------------------------------
-responding:
- system: |-
- You are DeepTutor's final response stage. Use the observation and tool evidence to provide a clear, direct, well-structured answer to the user.
-
- Requirements:
- 1. Output only the final user-facing answer.
- 2. Do not reveal the internal chain, reasoning, or tool orchestration.
- 3. Naturally integrate evidence or limits surfaced by the tools.
- {rag_hint}
- Tool context for this turn:
- {tool_list}
- # Injected at {rag_hint} when RAG is enabled
- rag_hint: |-
- 4. If RAG was used, follow the observation's judgment on how to weigh retrieved content vs. general knowledge. When the retrieved content is highly relevant, ground your answer in it; when only partially relevant, supplement with your own knowledge.
- user: |-
- User request:
- {user_message}
+ ``TOOL``
+ Let me run Python.
+ [native tool_call: code_execution(...)]
- [Observation]
- {observation}
+ ``THINK``
+ This problem has three steps: X, then Y, then Z. Next iteration I'll tackle X first…
- [Tool Trace]
- {tool_trace}
+ Never:
+ - Put anything before the label (no leading prose, quotes, or stray characters).
+ - Use single backticks, brackets, or any alternate wrapper.
+ - Emit more than one label in a single reply.
- Use this material to produce the final answer for the user. Do not mention the internal pipeline, thinking, or observing stages.
+ # Per-turn reasoning
-# ---------------------------------------------------------------------------
-# ReAct fallback (when native tool calling is unavailable)
-# ---------------------------------------------------------------------------
-react_fallback:
- system: |-
- You are DeepTutor's ReAct tool agent. Output exactly one JSON object and nothing else.
+ 1. Read the user's request. If you already have enough information for a reliable answer, answer directly with ``FINISH``. When unsure, lean on enabled tools rather than guessing — never fabricate precise values, external facts, or citations.
+ 2. In a ``TOOL`` reply, multiple complementary tools may run in the same iteration. In a ``THINK`` reply, write your reasoning only — no tools. In a ``FINISH`` reply, deliver the answer and stop.
+ 3. Once enough material is gathered, close with ``FINISH``.
- JSON format:
- {{
- "action": "<tool_name_or_done>",
- "action_input": {{ ... }}
- }}
+ Hard rules for tool calls:
+ - Tool names, parameter names, source ids, and KB names must be copied verbatim from the "Enabled tools" and "Knowledge bases / sources" blocks below. Never invent.
+ - Arguments must be concrete and executable; once you decide to call a tool, fill the arguments meaningfully — empty queries and placeholders are invalid.
- Available actions:
- {tool_table}
+ When to skip tools (use ``FINISH``):
+ - Pure conversation: greetings, chitchat, emotional response.
+ - Text rewriting, translation, formatting, Markdown polish.
+ - Definitional / conceptual questions where you are 100% confident and no precision or recency is required.
- {kb_note}
- Decide from the user request and the full enabled tool list whether tool use is truly needed; if it is, choose the single tool that best closes the most important information gap. If you call rag, action_input must include a non-empty query. If no tool is needed, set action=done.
- done_when_to_use: "Use when the available information is sufficient and no more tools are needed."
- done_input_format: "Empty string."
+ {kb_note}
+ Enabled tools:
+ {tool_list}
# ---------------------------------------------------------------------------
-# Answer-now stage (user explicitly requested "answer now", skip further planning)
+# User-message wrapper (kept trivial — most prompts will just be the raw user
+# question; attached sources flow in via the separately-appended manifest).
+# ---------------------------------------------------------------------------
+user_template: |-
+ {user_message}
+
+# ---------------------------------------------------------------------------
+# Answer-now path (user explicitly clicked "Answer now" mid-stream — used as
+# a synthetic user message after the captured partial draft is injected as a
+# fake assistant turn; the pipeline calls the LLM once with tools disabled).
# ---------------------------------------------------------------------------
answer_now:
user: |-
- Original user request:
- {original_user_message}
-
- [Current Draft]
- {partial_response}
-
- [Execution Trace]
- {trace_summary}
-
- Using only the material already gathered so far, produce the final user-facing answer now. Do not continue planning or call tools, and do not mention internal stages. If something is still uncertain, be explicit about the uncertainty while still giving the most useful answer you can.
+ Stop using tools and produce the user-facing answer now based on what you have already produced and any tool evidence you've gathered. Do not mention internal stages or planning. If something is still uncertain, say so briefly while giving the most useful answer you can.
# ---------------------------------------------------------------------------
# Progress notices and short copy
# ---------------------------------------------------------------------------
notices:
- no_tools_enabled: "No tools are enabled for this turn, so tool execution was skipped."
- react_fallback_switch: "The current model does not support native tool calling, so ReAct text orchestration is used."
+ no_tools_enabled: "No tools are enabled for this turn."
no_tool_call_needed: "No tool call was needed for this turn."
- too_many_tool_calls: "The model requested {requested} tools. At most {limit} can run in parallel in one turn, so the list was truncated."
+ too_many_tool_calls: "The model requested {requested} tools. At most {limit} can run in parallel in one iteration, so the list was truncated."
tool_unknown_error: "An unknown error occurred while executing {tool}."
start_retrieval: "Starting retrieval"
empty_tool_result: "The tool completed without returning text output."
- images_stripped: "The current model `{model}` does not support image input, so image attachments were ignored in the thinking stage."
+ images_stripped: "The current model `{model}` does not support image input, so image attachments were ignored."
+ max_iterations_reached: "Reached the maximum number of tool iterations for this turn. Producing the best answer I can with what I have."
+ context_window_guard: "Trimmed older tool results to keep this turn within the model's context window."
# ---------------------------------------------------------------------------
# Empty-state copy
diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
index 68a5d1bd9..b9e53105c 100644
--- a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
+++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
@@ -1,176 +1,97 @@
# AgenticChatPipeline 提示词(中文)
-# 这些提示词供 deeptutor.agents.chat.agentic_pipeline.AgenticChatPipeline 使用,
-# 对应 chat capability 的四阶段 pipeline:thinking → acting → observing → responding。
-# 与同目录下 chat_agent.yaml(旧的 REST 单轮 ChatAgent 用)不冲突。
+# 单循环 chat pipeline:单一合并 system prompt;LLM 自行决定是否原生调用工具,
+# pipeline 反复迭代直到模型给出最终回答。供 deeptutor.agents.chat.agentic_pipeline 使用。
# ---------------------------------------------------------------------------
# 各阶段标签(用于 trace metadata,前端展示)
# ---------------------------------------------------------------------------
labels:
- reasoning: "推理中"
- observation: "整理观察"
- final_response: "生成回答"
+ reasoning: "推理"
tool_call: "调用工具"
retrieve: "检索"
+ final_response: "生成回答"
answer_now: "直接回答"
# ---------------------------------------------------------------------------
-# Thinking 阶段
+# 单一 chat system prompt(capability-agnostic chat persona)
# ---------------------------------------------------------------------------
-thinking:
- system: |-
- 你是 DeepTutor 内部的 thinking 模块(不面向用户)。你的产出是一份简短的内部分析备忘,供后续 acting / responding 阶段消费,绝不会直接展示给用户。
-
- 产出格式(用自然段落,不需要标题):
- - 用户目标:用一两句话概括用户真正想要什么。
- - 已知 vs. 缺失:当前对话和上下文中已经有什么信息,还缺什么。
- - 工具规划:哪些工具可能补足缺失信息,简要说明理由。如果信息已足够,写"无需工具"。
- - 回答要点:最终回答应覆盖的关键点(列 2-4 条)。
-
- 关键约束:
- - 你只输出内部分析备忘,不要给出面向用户的回答、结论或解题过程。
- - 可以提及预计使用哪些工具,但不要真正调用工具。
- - 保持简洁,不超过 200 字。
-
- {kb_note}
- 当前启用工具:
- {tool_list}
- user: |-
- [用户问题]
- {user_message}
+# 不在这里点名任何具体工具,也不写工具适用场景。所有"什么时候用什么工具、
+# 怎么用"的信息都通过 {tool_list} 动态注入——只在用户启用了对应工具时才出现。
+#
+# pipeline 在调用时替换的占位符:
+# {kb_note} — 知识库挂载提示(可能为空)
+# {tool_list} — 启用工具列表(含 short_description / when_to_use / input_format,可能为空)
+#
+# memory_context、skills_context、source_manifest 由 pipeline 作为独立的
+# system 段落分别附加在本模板之后——不替换进本模板,保留 prompt cache。
+system: |-
+ 你是 DeepTutor,一名互动式教练,帮助用户思考问题。直接面向用户作答——不要描述内部 pipeline、阶段或规划过程。
- 请输出内部分析备忘(不要回答用户,不要给出结论)。
+ # 输出协议(强制,每一轮回复都必须遵守)
-# ---------------------------------------------------------------------------
-# Acting 阶段
-# ---------------------------------------------------------------------------
-acting:
- system: |-
- 你是 DeepTutor 的工具调用代理。你的任务是根据用户问题和前序 thinking,从当前已启用的工具中自主选择必要工具并调用。
-
- 规则:
- 1. 先完整审视所有已启用工具,再决定最有帮助的工具组合;不要只盯住单个工具。
- 2. 对于需要定义、事实核验、外部资料、论文、计算、推理等不同信息面的复杂问题,优先并行调用多个互补工具来覆盖这些信息面。
- 3. 只调用真正有帮助的工具,但只要工具能显著提升答案质量,就应充分调用。
- 4. 参数要具体、可执行,优先使用用户原问题中的关键信息,必要时针对不同工具改写成最适合它的查询。
- 5. 调用 rag 时,query 必须是非空的自然语言检索句,kb_name 必须从已挂载的知识库中选一个。如果要查多个知识库,请在同一轮内对每个 kb_name 各发起一次 rag 调用。
- 6. 如果信息已经足够,可以不调用工具。
- 7. 不要输出最终回答给学生;这里只负责工具选择与调用。
- 8. 单轮最多并行调用 {max_parallel_tools} 个工具;如果有多个互补工具都相关,优先在同一轮一起调用。
-
- {kb_note}
- 当前可用工具:
- {tool_list}
-
- 工具使用提示:
- {tool_aliases}
- user: |-
- 用户问题:
- {user_message}
+ 你的回复**必须以下面三个标签之一作为最开头**,整体顶格写、独占一行、全大写、左右各用两个反引号包裹:
- [Thinking]
- {thinking}
+ ``FINISH`` → 本轮就是面向用户的最终回答,不调用任何工具,标签后面的全部内容就是答案正文。
+ ``TOOL`` → 本轮要调用工具。标签后可以用一句话简述要做什么,然后通过原生 tool_calls 发起工具调用。
+ ``THINK`` → 本轮是中间推理,**不调用工具,但也不是最终答案**——你只是在边想边写、为下一轮做准备。下一轮你会继续基于这一轮的思路推进,最终会以 ``FINISH`` 收尾。
- 请先基于问题与全部可用工具,判断有哪些信息缺口需要工具补足。如果需要,请尽量在同一轮并行调用多个互补工具,但总数不要超过 {max_parallel_tools} 个。
+ 你自己根据当前问题难度、已有信息和工具情况自主选择三者之一:
+ - 简单问题、信息已足 → 直接 ``FINISH``。
+ - 需要外部信息 / 计算 / 检索 → ``TOOL``。
+ - 问题很复杂、需要把推理拆成多步先想清楚再回答 → ``THINK``(最多迭代几轮,每轮一个 ``THINK``,最后一定要 ``FINISH``)。
-# ---------------------------------------------------------------------------
-# Observing 阶段
-# ---------------------------------------------------------------------------
-observing:
- system: |-
- 你是 DeepTutor 的 observing 阶段。请基于 thinking 和 acting 阶段的输出,整理一份内部观察总结,供最终回答阶段使用。不要直接回答学生。
-
- 优先总结:
- 1. 已确认的事实与结论
- 2. 工具结果带来的关键证据
- 3. 仍需在最终回答中解释清楚的点
- {rag_hint}
- 本轮可用工具背景:
- {tool_list}
- # 当 RAG 工具被启用时,插入到 system 的 {rag_hint} 占位处
- rag_hint: |-
- 若本轮调用了知识库检索(RAG),请评估用户问题更适合基于检索到的知识库内容回答、基于记忆与通识回答、还是两者结合,并将判断写入总结。当工具返回的证据与初始 thinking 的推断不一致时,以实际证据为准。
- user_intro: |-
- 请整理本轮推理与工具执行得到的关键信息,输出给 tutor 自己看的观察总结。聚焦:已确认事实、仍不确定的点、最终回答应强调什么。不要直接写给学生。
+ 绝对不要:
+ - 在标签前面加任何字符(空格、引号、换行除外)。
+ - 用单反引号、方括号或别的格式代替双反引号包裹。
+ - 在同一轮里输出多个标签。
-# ---------------------------------------------------------------------------
-# Responding 阶段(最终面向用户)
-# ---------------------------------------------------------------------------
-responding:
- system: |-
- 你是 DeepTutor 的最终回答阶段。请根据 observation 和工具结果,给用户一个清晰、直接、结构良好的正式答复。
-
- 要求:
- 1. 只输出面向用户的正式回答。
- 2. 不要暴露内部链路、思考过程或工具编排。
- 3. 若工具结果提供了证据或限制,请自然融入答案。
- {rag_hint}
- 本轮工具背景:
- {tool_list}
- # 当 RAG 工具被启用时,插入到 system 的 {rag_hint} 占位处
- rag_hint: |-
- 4. 若使用了知识库检索,请根据 observation 的判断,合理权衡检索内容与通识。当检索内容与问题高度相关时,以其为核心依据;部分相关时,可结合自身知识补充。
- user: |-
- 用户问题:
- {user_message}
+ # 每一轮的处理思路
+
+ 1. 仔细读用户的问题。判断现有信息是否已足以给出可靠回答;不确定时倾向使用已启用工具,不要凭脑补给精确数值或外部事实。
+ 2. ``TOOL`` 轮里可以并行调用多个互补工具;``THINK`` 轮里不调工具,而是深入的思考可以用的思路;``FINISH`` 轮里给最终答案、不再调工具。
+ 3. 一旦素材足够,用 ``FINISH`` 结尾。
- [Observation]
- {observation}
+ 调用工具时的硬规则:
+ - 工具名、参数名、source id、知识库名只能从下方"启用工具"和"知识库 / 来源"中复制,不要凭空发明。
+ - 参数要具体、可执行;一旦决定调用,参数填实——空查询、占位符是无效的。
- [Tool Trace]
- {tool_trace}
+ 什么时候不调工具(用 ``FINISH`` 直接答即可):
+ - 纯对话:打招呼、闲聊、情绪回应。
+ - 文本改写、翻译、格式调整、Markdown 美化。
+ - 问的就是定义、概念且你 100% 确信答案、不存在精度或时效要求。
- 请基于以上内容,直接给出正式回答。不要暴露内部 pipeline、thinking、observing 等字样。
+ {kb_note}
+ 启用工具:
+ {tool_list}
# ---------------------------------------------------------------------------
-# ReAct fallback(不支持原生 tool-calling 时的回退)
+# user message 包装(保持最小——大多数情况下就是原始用户问题;
+# 挂载的来源由独立附加的 manifest 段提供)。
# ---------------------------------------------------------------------------
-react_fallback:
- system: |-
- 你是 DeepTutor 的 ReAct 工具代理。你必须只输出一个 JSON 对象,不要输出其他文本。
-
- JSON 格式:
- {{
- "action": "<tool_name_or_done>",
- "action_input": {{ ... }}
- }}
-
- 可选动作如下:
- {tool_table}
-
- {kb_note}
- 先基于用户问题和可用工具列表判断是否真的需要工具;若需要,请选择最能补足关键信息缺口的那个工具。如果调用 rag,action_input 中 query 必须是非空检索句。如果不需要工具,请输出 action=done。
- done_when_to_use: "当已有信息足够,且不需要继续调用工具时使用。"
- done_input_format: "空字符串。"
+user_template: |-
+ {user_message}
# ---------------------------------------------------------------------------
-# Answer-now 阶段(用户主动请求"立即回答",跳过后续规划)
+# Answer-now 路径(用户主动点击"直接回答"中途打断——用作合成 user 消息,
+# 此前已捕获的草稿会作为伪造的 assistant 轮注入;pipeline 关闭工具单轮调用)
# ---------------------------------------------------------------------------
answer_now:
user: |-
- 用户原始问题:
- {original_user_message}
-
- [Current Draft]
- {partial_response}
-
- [Execution Trace]
- {trace_summary}
-
- 请基于当前已经完成的内容,立刻直接生成给用户的最终答复。不要继续规划或调用工具,不要提到内部阶段。如果信息仍有缺口,请诚实说明不确定之处,但仍尽可能先给出当前最有用的回答。
+ 请基于你已经产出的内容和已收集到的工具证据,立刻给出面向用户的最终答复,不要再调工具。不要提到内部阶段或规划。如果仍有不确定,请简短说明,但仍然给出当前最有用的回答。
# ---------------------------------------------------------------------------
# 进度提示与短文案
# ---------------------------------------------------------------------------
notices:
- no_tools_enabled: "当前没有启用任何工具,本轮跳过工具调用。"
- react_fallback_switch: "当前模型不支持原生工具调用,已切换到 ReAct 文本编排。"
+ no_tools_enabled: "本轮没有启用任何工具。"
no_tool_call_needed: "本轮不需要调用工具。"
- too_many_tool_calls: "模型请求了 {requested} 个工具,本轮最多并行执行 {limit} 个,已截断。"
+ too_many_tool_calls: "模型请求了 {requested} 个工具,单次迭代最多并行执行 {limit} 个,已截断。"
tool_unknown_error: "执行工具 {tool} 时发生未知错误。"
start_retrieval: "开始检索"
empty_tool_result: "工具执行完成,但没有返回文本内容。"
- images_stripped: "当前模型 `{model}` 不支持图像输入,thinking 阶段已忽略本轮图片附件。"
+ images_stripped: "当前模型 `{model}` 不支持图像输入,本轮图片附件已被忽略。"
+ max_iterations_reached: "已达到本轮工具迭代上限,将基于当前材料给出最佳回答。"
+ context_window_guard: "已裁剪较旧的工具结果,以确保本轮在模型上下文窗口内。"
# ---------------------------------------------------------------------------
# 空状态文案
diff --git a/deeptutor/api/routers/co_writer.py b/deeptutor/api/routers/co_writer.py
index 5df368aa7..303e51345 100644
--- a/deeptutor/api/routers/co_writer.py
+++ b/deeptutor/api/routers/co_writer.py
@@ -1,5 +1,4 @@
import asyncio
-from dataclasses import asdict
from datetime import datetime
import json
import logging
@@ -11,13 +10,11 @@ from fastapi import APIRouter, HTTPException
from fastapi.responses import Response, StreamingResponse
from pydantic import BaseModel
-from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
from deeptutor.co_writer.edit_agent import (
EditAgent,
load_history,
print_stats,
save_history,
- save_tool_call,
tool_calls_dir,
)
from deeptutor.co_writer.storage import (
@@ -25,7 +22,6 @@ from deeptutor.co_writer.storage import (
CoWriterDocumentSummary,
get_co_writer_storage,
)
-from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream_bus import StreamBus
from deeptutor.services.config import PROJECT_ROOT, load_config_with_main
from deeptutor.services.llm import clean_thinking_tags
@@ -226,34 +222,22 @@ async def _run_react_edit(
language: str,
stream: StreamBus | None = None,
) -> dict[str, object]:
- selected_text, instruction, tools, knowledge_bases, prompt = _prepare_react_edit_request(
+ selected_text, instruction, tools, _knowledge_bases, _prompt = _prepare_react_edit_request(
request, language
)
operation_id = datetime.now().strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:6]
- context = UnifiedContext(
- session_id="",
- user_message=prompt,
- conversation_history=[],
- enabled_tools=tools,
- active_capability="chat",
- knowledge_bases=knowledge_bases,
- attachments=[],
- config_overrides={},
- language=language,
- metadata={"source": "co_writer_react_edit", "mode": request.mode},
- )
-
- pipeline = AgenticChatPipeline(language=language)
+ # NOTE: this endpoint previously invoked the chat pipeline's private
+ # stage methods to pre-compute a "thinking" pass and a one-shot tool
+ # round before the edit agent ran. That coupling broke when the chat
+ # pipeline collapsed to a single iterative loop. The endpoint kept its
+ # response shape (``thinking`` and ``tool_traces``) but the values are
+ # now empty by default — the edit agent does its job directly. If
+ # pre-edit retrieval becomes needed again, build it inside co_writer
+ # rather than parasitising the chat pipeline.
active_stream = stream or StreamBus()
- enabled_tools = pipeline._normalize_enabled_tools(context.enabled_tools)
- thinking_text = await pipeline._stage_thinking(context, enabled_tools, active_stream)
- tool_traces = await pipeline._stage_acting(
- context=context,
- enabled_tools=enabled_tools,
- thinking_text=thinking_text,
- stream=active_stream,
- )
+ thinking_text = ""
+ tool_traces: list = []
agent = get_edit_agent()
system_prompt = (
@@ -267,23 +251,6 @@ async def _run_react_edit(
mode=request.mode,
language=language,
)
- if thinking_text.strip():
- if language.startswith("zh"):
- final_prompt += f"\n内部推理摘要(不要暴露给用户):\n{thinking_text.strip()}\n"
- else:
- final_prompt += (
- f"\nInternal reasoning summary (do not reveal):\n{thinking_text.strip()}\n"
- )
- if tool_traces:
- formatted_traces = pipeline._format_tool_traces(tool_traces)
- if language.startswith("zh"):
- final_prompt += f"\n工具结果(只吸收事实,不要解释过程):\n{formatted_traces}\n"
- else:
- final_prompt += (
- f"\nTool results (absorb the facts only, do not explain the process):\n"
- f"{formatted_traces}\n"
- )
-
response_chunks: list[str] = []
if stream is None:
async for _c in agent.stream_llm(
@@ -321,21 +288,6 @@ async def _run_react_edit(
)
tool_call_file = None
- if tool_traces:
- tool_call_file = save_tool_call(
- operation_id,
- "react_tools",
- {
- "type": "react_tools",
- "timestamp": datetime.now().isoformat(),
- "operation_id": operation_id,
- "mode": request.mode,
- "tools": tools,
- "kb_name": request.kb_name,
- "thinking": thinking_text,
- "tool_traces": [asdict(trace) for trace in tool_traces],
- },
- )
history = load_history()
history.append(
@@ -362,7 +314,7 @@ async def _run_react_edit(
"edited_text": edited_text,
"operation_id": operation_id,
"thinking": thinking_text,
- "tool_traces": [asdict(trace) for trace in tool_traces],
+ "tool_traces": tool_traces,
}
if stream is not None:
await active_stream.result(result, source="co_writer_react_edit")
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index 4724b2298..f476182a5 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -159,6 +159,18 @@ class SupportedFileTypesInfo(BaseModel):
max_pdf_size_bytes: int
+IMAGE_ACCEPT_MIME_TYPES = {
+ ".bmp": "image/bmp",
+ ".gif": "image/gif",
+ ".jpeg": "image/jpeg",
+ ".jpg": "image/jpeg",
+ ".png": "image/png",
+ ".tif": "image/tiff",
+ ".tiff": "image/tiff",
+ ".webp": "image/webp",
+}
+
+
def _build_unique_task_id(task_type: str, task_key_prefix: str) -> str:
task_manager = TaskIDManager.get_instance()
task_key = f"{task_key_prefix}_{datetime.now().isoformat()}_{uuid4().hex[:8]}"
@@ -426,7 +438,6 @@ async def run_initialization_task(initializer: KnowledgeBaseInitializer, task_id
await initializer.process_documents()
_task_log(task_id, "Document processing complete")
- initializer.extract_numbered_items()
_task_log(task_id, "Finalizing initialization")
indexed_count = len(FileTypeRouter.collect_supported_files(initializer.raw_dir))
@@ -558,15 +569,6 @@ async def run_upload_processing_task(
processed_files = await adder.process_new_documents(staged_files)
_task_log(task_id, f"Indexed {len(processed_files)} file(s)")
- if processed_files:
- progress_tracker.update(
- ProgressStage.EXTRACTING_ITEMS,
- "Extracting numbered items...",
- current=0,
- total=len(processed_files),
- )
- adder.extract_numbered_items_for_new_docs(processed_files, batch_size=20)
-
adder.update_metadata(len(processed_files) if processed_files else 0)
if folder_id and processed_files:
@@ -651,9 +653,14 @@ async def get_rag_providers():
async def get_supported_file_types():
"""Return the current upload policy so the web client stays in sync."""
extensions = sorted(FileTypeRouter.get_supported_extensions())
+ accept_items = extensions + [
+ mime
+ for extension, mime in sorted(IMAGE_ACCEPT_MIME_TYPES.items())
+ if extension in FileTypeRouter.IMAGE_EXTENSIONS
+ ]
return SupportedFileTypesInfo(
extensions=extensions,
- accept=",".join(extensions),
+ accept=",".join(dict.fromkeys(accept_items)),
max_file_size_bytes=DocumentValidator.MAX_FILE_SIZE,
max_pdf_size_bytes=DocumentValidator.MAX_PDF_SIZE,
)
diff --git a/deeptutor/api/routers/sessions.py b/deeptutor/api/routers/sessions.py
index a5db87c82..b09e99360 100644
--- a/deeptutor/api/routers/sessions.py
+++ b/deeptutor/api/routers/sessions.py
@@ -21,6 +21,16 @@ class SessionRenameRequest(BaseModel):
title: str = Field(..., min_length=1, max_length=100)
+class BranchSelectionRequest(BaseModel):
+ """Edit-branch picker state: `{parent_message_id: chosen_child_id}`.
+
+ Stored inside the session preferences blob so it survives reloads
+ without a dedicated column.
+ """
+
+ selected_branches: dict[str, int] = Field(default_factory=dict)
+
+
class QuizResultItem(BaseModel):
question_id: str = ""
question: str = Field(..., min_length=1)
@@ -114,6 +124,20 @@ async def delete_session(session_id: str):
return {"deleted": True, "session_id": session_id}
[email protected]("/{session_id}/branch-selection")
+async def update_branch_selection(session_id: str, payload: BranchSelectionRequest):
+ store = get_sqlite_session_store()
+ session = await store.get_session(session_id)
+ if session is None:
+ raise HTTPException(status_code=404, detail="Session not found")
+ updated = await store.update_session_preferences(
+ session_id, {"selected_branches": dict(payload.selected_branches)}
+ )
+ if not updated:
+ raise HTTPException(status_code=404, detail="Session not found")
+ return {"selected_branches": payload.selected_branches}
+
+
@router.delete("/{session_id}/messages/{message_id}")
async def delete_turn_by_message(session_id: str, message_id: int):
store = get_sqlite_session_store()
diff --git a/deeptutor/core/context.py b/deeptutor/core/context.py
index 28ea105e7..0364f58ba 100644
--- a/deeptutor/core/context.py
+++ b/deeptutor/core/context.py
@@ -47,6 +47,12 @@ class UnifiedContext:
attachments: Images / files sent with the message.
config_overrides: Per-request config tweaks (e.g. temperature).
language: UI / response language ("en" | "zh").
+ memory_context: Memory snapshot text injected into the system prompt.
+ skills_context: Skill instructions injected into the system prompt.
+ source_manifest: Plain-text manifest of attached sources (one line per
+ source: id/name/type/preview). Empty when no sources are attached.
+ Consumed by the chat capability to render an "Attached Sources"
+ section in the system prompt and to enable the ``read_source`` tool.
metadata: Catch-all for capability-specific extras.
"""
@@ -59,8 +65,7 @@ class UnifiedContext:
attachments: list[Attachment] = field(default_factory=list)
config_overrides: dict[str, Any] = field(default_factory=dict)
language: str = "en"
- notebook_context: str = ""
- history_context: str = ""
memory_context: str = ""
skills_context: str = ""
+ source_manifest: str = ""
metadata: dict[str, Any] = field(default_factory=dict)
diff --git a/deeptutor/knowledge/add_documents.py b/deeptutor/knowledge/add_documents.py
index a23c74b1a..5ec3fcf6d 100644
--- a/deeptutor/knowledge/add_documents.py
+++ b/deeptutor/knowledge/add_documents.py
@@ -171,14 +171,6 @@ class DocumentAdder:
with open(self.metadata_file, "w", encoding="utf-8") as f:
json.dump(metadata, f, indent=2, ensure_ascii=False)
- def extract_numbered_items_for_new_docs(
- self, processed_files: List[Path], batch_size: int = 20
- ) -> None:
- """Compatibility no-op: numbered-item extraction is deprecated."""
- _ = batch_size
- if processed_files:
- logger.info("Skipping numbered items extraction for incremental add (feature removed)")
-
def update_metadata(self, added_count: int) -> None:
"""Update metadata after incremental add."""
metadata: dict = {}
@@ -266,7 +258,6 @@ async def add_documents(
)
return 0
processed = await adder.process_new_documents(new_files)
- adder.extract_numbered_items_for_new_docs(processed)
adder.update_metadata(len(processed))
manager.update_kb_status(
diff --git a/deeptutor/knowledge/initializer.py b/deeptutor/knowledge/initializer.py
index 4018d3764..b9799be17 100644
--- a/deeptutor/knowledge/initializer.py
+++ b/deeptutor/knowledge/initializer.py
@@ -223,11 +223,6 @@ class KnowledgeBaseInitializer:
"""No-op retained for compatibility with previous pipelines."""
logger.info("Skipping legacy structure cleanup (llamaindex-only mode)")
- def extract_numbered_items(self, batch_size: int = 20) -> None:
- """Compatibility no-op: numbered-item extraction is deprecated."""
- _ = batch_size
- logger.info("Skipping numbered items extraction (deprecated feature removed)")
-
async def display_statistics_generic(self) -> None:
"""Display basic statistics."""
raw_files = list(self.raw_dir.glob("*")) if self.raw_dir.exists() else []
@@ -250,7 +245,6 @@ async def initialize_knowledge_base(
base_dir: str = "./data/knowledge_bases",
api_key: Optional[str] = None,
base_url: Optional[str] = None,
- skip_extract: bool = False,
) -> bool:
"""Convenience initializer used by CLI wrappers."""
from deeptutor.knowledge.manager import KnowledgeBaseManager
@@ -267,8 +261,6 @@ async def initialize_knowledge_base(
initializer.create_directory_structure()
copied_files = initializer.copy_documents(source_files)
await initializer.process_documents()
- if not skip_extract:
- initializer.extract_numbered_items()
manager.update_kb_status(
name=kb_name,
status="ready",
@@ -322,8 +314,6 @@ async def main() -> None:
parser.add_argument("--api-key", default=default_api_key)
parser.add_argument("--base-url", default=default_base_url)
parser.add_argument("--skip-processing", action="store_true")
- parser.add_argument("--skip-extract", action="store_true")
- parser.add_argument("--batch-size", type=int, default=20)
args = parser.parse_args()
@@ -348,8 +338,6 @@ async def main() -> None:
if not args.skip_processing:
await initializer.process_documents()
- if not args.skip_processing and not args.skip_extract:
- initializer.extract_numbered_items(batch_size=args.batch_size)
if __name__ == "__main__":
diff --git a/deeptutor/knowledge/progress_tracker.py b/deeptutor/knowledge/progress_tracker.py
index a1c1b712b..f3e8056db 100644
--- a/deeptutor/knowledge/progress_tracker.py
+++ b/deeptutor/knowledge/progress_tracker.py
@@ -25,7 +25,6 @@ class ProgressStage(Enum):
INITIALIZING = "initializing" # Initializing
PROCESSING_DOCUMENTS = "processing_documents" # Processing documents
PROCESSING_FILE = "processing_file" # Processing single file
- EXTRACTING_ITEMS = "extracting_items" # Extracting numbered items
COMPLETED = "completed" # Completed
ERROR = "error" # Error
@@ -93,7 +92,6 @@ class ProgressTracker:
"initializing",
"processing_documents",
"processing_file",
- "extracting_items",
]:
status = "processing"
else:
diff --git a/deeptutor/runtime/registry/tool_registry.py b/deeptutor/runtime/registry/tool_registry.py
index 14f7ff181..b0720ef92 100644
--- a/deeptutor/runtime/registry/tool_registry.py
+++ b/deeptutor/runtime/registry/tool_registry.py
@@ -113,6 +113,8 @@ class ToolRegistry:
hints = self.get_prompt_hints(names, language=language)
if format == "list":
return composer.format_list(hints)
+ if format == "list_with_usage":
+ return composer.format_list_with_usage(hints)
if format == "table":
return composer.format_table(
hints,
diff --git a/deeptutor/services/config/context_window_detection.py b/deeptutor/services/config/context_window_detection.py
index e6ffd5431..9f82de71b 100644
--- a/deeptutor/services/config/context_window_detection.py
+++ b/deeptutor/services/config/context_window_detection.py
@@ -31,6 +31,10 @@ _CONTEXT_WINDOW_KEYS = (
"max_sequence_length",
)
+_KNOWN_CONTEXT_WINDOWS: tuple[tuple[str, int], ...] = (
+ ("deepseek-v4", 1_000_000),
+)
+
@dataclass(frozen=True)
class ContextWindowDetectionResult:
@@ -61,6 +65,16 @@ def _record_identities(item: Mapping[str, Any]) -> set[str]:
return aliases
+def _known_context_window(model: str) -> int | None:
+ normalized = (model or "").strip().lower()
+ if not normalized:
+ return None
+ for pattern, context_window in _KNOWN_CONTEXT_WINDOWS:
+ if pattern in normalized:
+ return context_window
+ return None
+
+
def _recursive_context_window(value: Any) -> int | None:
if isinstance(value, Mapping):
for key in _CONTEXT_WINDOW_KEYS:
@@ -175,6 +189,15 @@ async def detect_context_window(
detected_at=detected_at,
)
+ known_window = _known_context_window(llm_config.model)
+ if known_window is not None:
+ return ContextWindowDetectionResult(
+ context_window=known_window,
+ source="known_model",
+ detail="Matched built-in context-window metadata for this model family.",
+ detected_at=detected_at,
+ )
+
fallback = default_context_window_for_model(
model=llm_config.model,
max_tokens=llm_config.max_tokens,
diff --git a/deeptutor/services/config/test_runner.py b/deeptutor/services/config/test_runner.py
index e4d43945a..0a8081cde 100644
--- a/deeptutor/services/config/test_runner.py
+++ b/deeptutor/services/config/test_runner.py
@@ -29,6 +29,21 @@ def _redact(value: str) -> str:
return f"{value[:4]}...{value[-4:]}"
+def _coerce_int(value: Any, default: int, *, minimum: int = 1) -> int:
+ try:
+ parsed = int(value)
+ except (TypeError, ValueError):
+ return default
+ return max(minimum, parsed)
+
+
+def _coerce_float(value: Any, default: float) -> float:
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return default
+
+
@dataclass
class TestRun:
id: str
@@ -235,20 +250,25 @@ class ConfigTestRunner:
from .loader import get_agent_params
probe_params = get_agent_params("llm_probe")
- max_tokens = max(1, int(probe_params.get("max_tokens", 1024)))
+ max_tokens = _coerce_int(probe_params.get("max_tokens"), 1024)
+ temperature = _coerce_float(probe_params.get("temperature"), 0.1)
token_kwargs: dict[str, Any] = get_token_limit_kwargs(
llm_config.model, max_tokens=max_tokens
)
run.emit("info", f"Token options: {json.dumps(token_kwargs)}")
+ if llm_config.reasoning_effort:
+ run.emit("info", f"Reasoning effort: {llm_config.reasoning_effort}")
response = await llm_complete(
model=llm_config.model,
prompt="Say 'OK' and identify the model you are using.",
system_prompt="Respond briefly but include your model identity if possible.",
binding=llm_config.binding,
api_key=llm_config.api_key or "sk-no-key-required",
- base_url=llm_config.base_url or "",
- temperature=0.1,
+ base_url=llm_config.effective_url or llm_config.base_url or "",
+ api_version=llm_config.api_version,
+ temperature=temperature,
extra_headers=llm_config.extra_headers,
+ reasoning_effort=llm_config.reasoning_effort,
**token_kwargs,
)
snippet = (response or "").strip()
@@ -289,7 +309,7 @@ class ConfigTestRunner:
run.emit("info", "Loading embedding config from the active catalog selection.")
resolved = resolve_embedding_runtime_config(catalog=catalog)
- catalog_dim = int(str(model.get("dimension") or 0))
+ catalog_dim = _coerce_int(model.get("dimension"), 0, minimum=0)
# Force the smoke probe to send NO `dimensions=` parameter so we get
# the model's native max dim back. If we used the configured dim,
# Matryoshka models (OpenAI text-embedding-3-*, Cohere embed-v4,
@@ -403,18 +423,12 @@ class ConfigTestRunner:
# Always persist: the probe runs end-to-end successfully, so the
# detected dim is authoritative. ``_persist_embedding_dimension`` also
# writes the refreshed ``supported_dimensions`` CSV in the same save.
- try:
- saved_catalog = self._persist_embedding_dimension(catalog, model, detected_dim)
- run.emit(
- "catalog",
- "Saved detected embedding dimension to model_catalog.json.",
- catalog=saved_catalog,
- )
- except Exception as exc: # pragma: no cover - persistence best-effort
- run.emit(
- "warning",
- f"Could not save detected embedding dimension: {exc}",
- )
+ saved_catalog = self._persist_embedding_dimension(catalog, model, detected_dim)
+ run.emit(
+ "catalog",
+ "Saved detected embedding dimension to model_catalog.json.",
+ catalog=saved_catalog,
+ )
def _test_search(self, run: TestRun, catalog: dict[str, Any]) -> None:
from deeptutor.services.search import web_search
diff --git a/deeptutor/services/embedding/adapters/base.py b/deeptutor/services/embedding/adapters/base.py
index 580f1278e..875f08421 100644
--- a/deeptutor/services/embedding/adapters/base.py
+++ b/deeptutor/services/embedding/adapters/base.py
@@ -11,6 +11,23 @@ from dataclasses import dataclass
from typing import Any, Dict, List, Optional
+def looks_like_multimodal_embedding_model(model_name: Optional[str]) -> bool:
+ """Best-effort guard for OpenAI-compatible multimodal embedding models."""
+ if not model_name:
+ return False
+ normalized = model_name.lower().replace("_", "-")
+ return any(
+ marker in normalized
+ for marker in (
+ "qwen3-vl-embedding",
+ "multimodal-embedding",
+ "vision-embedding",
+ "vl-embedding",
+ "image-embedding",
+ )
+ )
+
+
@dataclass
class EmbeddingRequest:
"""
diff --git a/deeptutor/services/embedding/adapters/cohere.py b/deeptutor/services/embedding/adapters/cohere.py
index e9eee8ea0..6e955aa91 100644
--- a/deeptutor/services/embedding/adapters/cohere.py
+++ b/deeptutor/services/embedding/adapters/cohere.py
@@ -20,26 +20,31 @@ class CohereEmbeddingAdapter(BaseEmbeddingAdapter):
"dimensions": [256, 512, 1024, 1536],
"default": 1024,
"api_version": "v2",
+ "multimodal": True,
},
"embed-english-v3.0": {
"dimensions": [1024],
"default": 1024,
"api_version": "v1",
+ "multimodal": False,
},
"embed-multilingual-v3.0": {
"dimensions": [1024],
"default": 1024,
"api_version": "v1",
+ "multimodal": False,
},
"embed-multilingual-light-v3.0": {
"dimensions": [384],
"default": 384,
"api_version": "v1",
+ "multimodal": False,
},
"embed-english-light-v3.0": {
"dimensions": [384],
"default": 384,
"api_version": "v1",
+ "multimodal": False,
},
}
@@ -75,6 +80,10 @@ class CohereEmbeddingAdapter(BaseEmbeddingAdapter):
if not request.truncate:
payload["truncate"] = "NONE"
else:
+ if request.contents and not bool(model_info.get("multimodal", False)):
+ raise ValueError(
+ f"Cohere model '{model_name}' does not support multimodal `contents`."
+ )
payload = {
"model": model_name,
"embedding_types": ["float"],
@@ -151,11 +160,13 @@ class CohereEmbeddingAdapter(BaseEmbeddingAdapter):
def get_model_info(self) -> Dict[str, Any]:
model_info = self.MODELS_INFO.get(self.model, {})
dimensions_list = model_info.get("dimensions", [])
+ api_version = self.api_version or model_info.get("api_version") or "v2"
return {
"model": self.model,
"dimensions": model_info.get("default", self.dimensions),
"supports_variable_dimensions": len(dimensions_list) > 1
if isinstance(dimensions_list, list)
else False,
+ "multimodal": bool(model_info.get("multimodal", False)) and api_version != "v1",
"provider": "cohere",
}
diff --git a/deeptutor/services/embedding/adapters/jina.py b/deeptutor/services/embedding/adapters/jina.py
index 0d6737387..a10eb630c 100644
--- a/deeptutor/services/embedding/adapters/jina.py
+++ b/deeptutor/services/embedding/adapters/jina.py
@@ -14,8 +14,16 @@ logger = logging.getLogger(__name__)
class JinaEmbeddingAdapter(BaseEmbeddingAdapter):
MODELS_INFO = {
- "jina-embeddings-v3": {"default": 1024, "dimensions": [32, 64, 128, 256, 512, 768, 1024]},
- "jina-embeddings-v4": {"default": 1024, "dimensions": [32, 64, 128, 256, 512, 768, 1024]},
+ "jina-embeddings-v3": {
+ "default": 1024,
+ "dimensions": [32, 64, 128, 256, 512, 768, 1024],
+ "multimodal": False,
+ },
+ "jina-embeddings-v4": {
+ "default": 1024,
+ "dimensions": [32, 64, 128, 256, 512, 768, 1024],
+ "multimodal": True,
+ },
}
INPUT_TYPE_TO_TASK = {
@@ -43,6 +51,10 @@ class JinaEmbeddingAdapter(BaseEmbeddingAdapter):
)
return False
+ def _supports_multimodal(self, model_name: str | None) -> bool:
+ info = self.MODELS_INFO.get(model_name or "")
+ return bool(isinstance(info, dict) and info.get("multimodal", False))
+
async def embed(self, request: EmbeddingRequest) -> EmbeddingResponse:
headers = {
"Authorization": f"Bearer {self.api_key}",
@@ -54,6 +66,11 @@ class JinaEmbeddingAdapter(BaseEmbeddingAdapter):
# arrays in `input`; v3 is text-only. Treat `contents` as advisory:
# if set, flatten each {"text"|"image"|"video": value} to its value.
if request.contents:
+ if not self._supports_multimodal(request.model or self.model):
+ raise ValueError(
+ f"Jina model '{request.model or self.model}' does not support "
+ "multimodal `contents`."
+ )
input_payload = [
next(iter(item.values())) for item in request.contents if isinstance(item, dict)
]
@@ -123,6 +140,7 @@ class JinaEmbeddingAdapter(BaseEmbeddingAdapter):
"dimensions": model_info.get("default", self.dimensions),
"supported_dimensions": model_info.get("dimensions", []),
"supports_variable_dimensions": True,
+ "multimodal": bool(model_info.get("multimodal", False)),
"provider": "jina",
}
else:
@@ -130,5 +148,6 @@ class JinaEmbeddingAdapter(BaseEmbeddingAdapter):
"model": self.model,
"dimensions": model_info or self.dimensions,
"supports_variable_dimensions": False,
+ "multimodal": False,
"provider": "jina",
}
diff --git a/deeptutor/services/embedding/adapters/ollama.py b/deeptutor/services/embedding/adapters/ollama.py
index 0c950de28..bf4cb5440 100644
--- a/deeptutor/services/embedding/adapters/ollama.py
+++ b/deeptutor/services/embedding/adapters/ollama.py
@@ -140,5 +140,6 @@ class OllamaEmbeddingAdapter(BaseEmbeddingAdapter):
"dimensions": self.MODELS_INFO.get(self.model, self.dimensions),
"local": True,
"supports_variable_dimensions": False,
+ "multimodal": False,
"provider": "ollama",
}
diff --git a/deeptutor/services/embedding/adapters/openai_compatible.py b/deeptutor/services/embedding/adapters/openai_compatible.py
index 0bd45d6a8..dd9b1234d 100644
--- a/deeptutor/services/embedding/adapters/openai_compatible.py
+++ b/deeptutor/services/embedding/adapters/openai_compatible.py
@@ -13,6 +13,7 @@ from .base import (
EmbeddingProviderError,
EmbeddingRequest,
EmbeddingResponse,
+ looks_like_multimodal_embedding_model,
)
logger = logging.getLogger(__name__)
@@ -151,15 +152,21 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
headers["Authorization"] = f"Bearer {api_key}"
headers.update({str(k): str(v) for k, v in self.extra_headers.items()})
- # Multimodal: pass `contents` through as `input` when set. SiliconFlow's
- # Qwen3-VL family accepts mixed [{"text"}, {"image"}] arrays in `input`.
- # Pure text-only OpenAI rejects them; that's on the user to pair models
- # and providers correctly.
+ # Multimodal: pass `contents` through as `input` only for model names
+ # that clearly advertise image/vision embedding support. This prevents
+ # image indexing from accidentally hitting ordinary text-embedding
+ # models just because the provider family has some multimodal models.
+ model = request.model or self.model
+ if request.contents and not looks_like_multimodal_embedding_model(model):
+ raise ValueError(
+ f"OpenAI-compatible embedding model '{model}' does not support "
+ "multimodal `contents`."
+ )
input_payload: Any = request.contents if request.contents else request.texts
payload = {
"input": input_payload,
- "model": request.model or self.model,
+ "model": model,
"encoding_format": request.encoding_format or "float",
}
@@ -169,7 +176,7 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
# supports the param — other providers (e.g. Qwen text-embedding-v4 via
# litellm gateway) return HTTP 400 if we send it.
dim_value = request.dimensions or self.dimensions
- if dim_value and self._should_send_dimensions(request.model or self.model):
+ if dim_value and self._should_send_dimensions(model):
payload["dimensions"] = dim_value
# URL transparency: hit `base_url` verbatim. Azure's `?api-version=...`
@@ -216,7 +223,7 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
f"Embedding provider returned HTTP {response.status_code}",
status=response.status_code,
body=body_text,
- model=request.model or self.model,
+ model=model,
url=url,
provider="openai_compat",
)
@@ -253,7 +260,7 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
),
status=response.status_code,
body=body_text,
- model=request.model or self.model,
+ model=model,
url=url,
provider="openai_compat",
) from exc
@@ -291,7 +298,7 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
expected_dims = request.dimensions or self.dimensions
model_name = data.get("model") if isinstance(data, dict) else None
if not model_name:
- model_name = request.model or self.model
+ model_name = model
if expected_dims and actual_dims != expected_dims:
logger.warning(
@@ -320,6 +327,7 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
"dimensions": model_info.get("default", self.dimensions),
"supported_dimensions": model_info.get("dimensions", []),
"supports_variable_dimensions": len(model_info.get("dimensions", [])) > 1,
+ "multimodal": looks_like_multimodal_embedding_model(self.model),
"provider": "openai_compatible",
}
else:
@@ -327,5 +335,6 @@ class OpenAICompatibleEmbeddingAdapter(BaseEmbeddingAdapter):
"model": self.model,
"dimensions": model_info or self.dimensions,
"supports_variable_dimensions": False,
+ "multimodal": looks_like_multimodal_embedding_model(self.model),
"provider": "openai_compatible",
}
diff --git a/deeptutor/services/embedding/adapters/openai_sdk.py b/deeptutor/services/embedding/adapters/openai_sdk.py
index 7dbf246ca..dd2a7e8a7 100644
--- a/deeptutor/services/embedding/adapters/openai_sdk.py
+++ b/deeptutor/services/embedding/adapters/openai_sdk.py
@@ -147,5 +147,6 @@ class OpenAISDKEmbeddingAdapter(BaseEmbeddingAdapter):
"model": self.model,
"dimensions": self.dimensions,
"supports_variable_dimensions": False,
+ "multimodal": False,
"provider": "openai_sdk",
}
diff --git a/deeptutor/services/embedding/client.py b/deeptutor/services/embedding/client.py
index 86283505a..8dd3c287f 100644
--- a/deeptutor/services/embedding/client.py
+++ b/deeptutor/services/embedding/client.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import logging
-from typing import List, Optional
+from typing import Any, Dict, List, Optional
from deeptutor.services.config.provider_runtime import (
EMBEDDING_PROVIDERS,
@@ -151,6 +151,76 @@ class EmbeddingClient:
)
return all_embeddings
+ def supports_multimodal_contents(self) -> bool:
+ """Return whether the configured adapter/model accepts multimodal contents."""
+ try:
+ info = self.adapter.get_model_info()
+ if "multimodal" in info:
+ return bool(info.get("multimodal"))
+ except Exception:
+ pass
+
+ spec = EMBEDDING_PROVIDERS.get(self.config.binding)
+ return bool(spec and spec.multimodal)
+
+ async def embed_contents(
+ self,
+ contents: List[Dict[str, Any]],
+ *,
+ progress_callback=None,
+ ) -> List[List[float]]:
+ """Embed provider-agnostic multimodal content items.
+
+ ``contents`` uses the same simple contract as ``EmbeddingRequest``:
+ ``[{"text": "..."}, {"image": "data:...|url"}, {"video": "..."}]``.
+ """
+ if not contents:
+ return []
+ if not self.supports_multimodal_contents():
+ raise ValueError(
+ "Configured embedding provider/model does not support multimodal contents."
+ )
+
+ import asyncio
+
+ spec = EMBEDDING_PROVIDERS.get(self.config.binding)
+ provider_max = spec.max_batch_items if spec else 256
+ batch_size = max(1, min(self.config.batch_size, provider_max))
+ all_embeddings: List[List[float]] = []
+ total_batches = (len(contents) + batch_size - 1) // batch_size
+
+ for i, start in enumerate(range(0, len(contents), batch_size)):
+ batch = contents[start : start + batch_size]
+ request = EmbeddingRequest(
+ texts=[],
+ model=self.config.model,
+ dimensions=self.config.dim or None,
+ contents=batch,
+ enable_fusion=False,
+ )
+ response = await self.adapter.embed(request)
+ validated = validate_embedding_batch(
+ response.embeddings,
+ expected_count=len(batch),
+ binding=self.config.binding,
+ model=self.config.model,
+ batch_index=i + 1,
+ total_batches=total_batches,
+ start_index=start,
+ )
+ all_embeddings.extend(validated)
+
+ if progress_callback:
+ try:
+ progress_callback(i + 1, total_batches)
+ except Exception:
+ pass
+
+ if i < total_batches - 1 and self.config.batch_delay > 0:
+ await asyncio.sleep(self.config.batch_delay)
+
+ return all_embeddings
+
def embed_sync(self, texts: List[str]) -> List[List[float]]:
import asyncio
diff --git a/deeptutor/services/llm/capabilities.py b/deeptutor/services/llm/capabilities.py
index 51587672c..280882207 100644
--- a/deeptutor/services/llm/capabilities.py
+++ b/deeptutor/services/llm/capabilities.py
@@ -174,9 +174,20 @@ MODEL_OVERRIDES: dict[str, dict[str, object]] = {
"has_thinking_tags": True,
"supports_vision": False,
},
+ # Qwen text models often share the same provider/gateway as Qwen-VL.
+ # Keep thinking-tag handling broad, but only mark explicit VL/vision model
+ # names as image-capable so RAG image indexing can fail closed.
+ "qwen/qwen2.5-vl": {"has_thinking_tags": True, "supports_vision": True},
+ "qwen/qwen3-vl": {"has_thinking_tags": True, "supports_vision": True},
+ "qwen/qwen2-vl": {"has_thinking_tags": True, "supports_vision": True},
+ "qwen/qwen-vl": {"has_thinking_tags": True, "supports_vision": True},
+ "qwen2.5-vl": {"has_thinking_tags": True, "supports_vision": True},
+ "qwen3-vl": {"has_thinking_tags": True, "supports_vision": True},
+ "qwen2-vl": {"has_thinking_tags": True, "supports_vision": True},
+ "qwen-vl": {"has_thinking_tags": True, "supports_vision": True},
"qwen": {
"has_thinking_tags": True,
- "supports_vision": True,
+ "supports_vision": False,
},
"qwq": {
"has_thinking_tags": True,
diff --git a/deeptutor/services/llm/client.py b/deeptutor/services/llm/client.py
index fa625b902..c1773f402 100644
--- a/deeptutor/services/llm/client.py
+++ b/deeptutor/services/llm/client.py
@@ -12,6 +12,7 @@ from collections.abc import Awaitable, Callable
import logging
from typing import cast
+from .capabilities import supports_vision
from .config import LLMConfig, get_llm_config
from .utils import sanitize_url
@@ -139,6 +140,10 @@ class LLMClient:
"""
return self._build_factory_model_func(allow_multimodal=True)
+ def supports_multimodal_images(self) -> bool:
+ """Return whether the configured LLM can accept image input."""
+ return supports_vision(getattr(self.config, "binding", "openai"), self.config.model)
+
def _build_factory_model_func(self, allow_multimodal: bool) -> Callable[..., object]:
"""Build adapter callables on top of the unified factory.complete API."""
from . import factory
diff --git a/deeptutor/services/llm/factory.py b/deeptutor/services/llm/factory.py
index 25c9ec9b5..4393cf4d9 100644
--- a/deeptutor/services/llm/factory.py
+++ b/deeptutor/services/llm/factory.py
@@ -27,6 +27,9 @@ from .utils import is_local_llm_server
DEFAULT_MAX_RETRIES = settings.retry.max_retries
DEFAULT_RETRY_DELAY = settings.retry.base_delay
DEFAULT_EXPONENTIAL_BACKOFF = settings.retry.exponential_backoff
+DEFAULT_STREAM_COALESCE_CHARS = 64
+DEFAULT_STREAM_COALESCE_SECONDS = 0.04
+STREAM_CONTROL_TOKENS = {"<think>", "</think>"}
CallKwargs = dict[str, Any]
@@ -276,6 +279,20 @@ def _find_last_user_message(messages: list[dict[str, Any]]) -> dict[str, Any] |
return None
+def _coerce_stream_coalesce_chars(value: Any) -> int:
+ try:
+ return max(1, int(value))
+ except (TypeError, ValueError):
+ return DEFAULT_STREAM_COALESCE_CHARS
+
+
+def _coerce_stream_coalesce_seconds(value: Any) -> float:
+ try:
+ return max(0.0, float(value))
+ except (TypeError, ValueError):
+ return DEFAULT_STREAM_COALESCE_SECONDS
+
+
def _append_image_placeholder(messages: list[dict[str, Any]]) -> None:
target = _find_last_user_message(messages)
placeholder = "[image omitted]"
@@ -299,6 +316,8 @@ def _apply_inline_image_data(
binding: str,
model: str,
image_data: str | None,
+ image_mime_type: str = "image/png",
+ image_filename: str = "image.png",
) -> list[dict[str, Any]]:
if not image_data:
return messages
@@ -306,8 +325,8 @@ def _apply_inline_image_data(
attachment = SimpleNamespace(
type="image",
base64=image_data,
- filename="image.png",
- mime_type="image/png",
+ filename=image_filename,
+ mime_type=image_mime_type,
)
result = prepare_multimodal_messages(messages, [attachment], binding=binding, model=model)
if result.images_stripped:
@@ -325,6 +344,8 @@ def _sanitize_call_kwargs(
for key in (
"messages",
"image_data",
+ "image_mime_type",
+ "image_filename",
"api_key",
"base_url",
"api_version",
@@ -356,6 +377,8 @@ async def complete(
caller_extra_headers = kwargs.pop("extra_headers", None)
reasoning_effort = kwargs.pop("reasoning_effort", None)
image_data = kwargs.pop("image_data", None)
+ image_mime_type = kwargs.pop("image_mime_type", "image/png")
+ image_filename = kwargs.pop("image_filename", "image.png")
config, provider_spec = _resolve_call_config(
model=model,
@@ -374,6 +397,8 @@ async def complete(
binding=capability_binding,
model=config.model,
image_data=image_data,
+ image_mime_type=str(image_mime_type or "image/png"),
+ image_filename=str(image_filename or "image.png"),
)
retry_delays = _build_retry_delays(max_retries, retry_delay, exponential_backoff)
extra_kwargs = _sanitize_call_kwargs(
@@ -415,6 +440,14 @@ async def stream(
caller_extra_headers = kwargs.pop("extra_headers", None)
reasoning_effort = kwargs.pop("reasoning_effort", None)
image_data = kwargs.pop("image_data", None)
+ image_mime_type = kwargs.pop("image_mime_type", "image/png")
+ image_filename = kwargs.pop("image_filename", "image.png")
+ stream_coalesce_chars = _coerce_stream_coalesce_chars(
+ kwargs.pop("stream_coalesce_chars", DEFAULT_STREAM_COALESCE_CHARS)
+ )
+ stream_coalesce_seconds = _coerce_stream_coalesce_seconds(
+ kwargs.pop("stream_coalesce_seconds", DEFAULT_STREAM_COALESCE_SECONDS)
+ )
config, provider_spec = _resolve_call_config(
model=model,
@@ -433,6 +466,8 @@ async def stream(
binding=capability_binding,
model=config.model,
image_data=image_data,
+ image_mime_type=str(image_mime_type or "image/png"),
+ image_filename=str(image_filename or "image.png"),
)
retry_delays = _build_retry_delays(max_retries, retry_delay, exponential_backoff)
extra_kwargs = _sanitize_call_kwargs(
@@ -503,13 +538,70 @@ async def stream(
task = asyncio.create_task(_runner())
try:
+ sent_first_text_chunk = False
+ buffered_chunks: list[str] = []
+ buffered_chars = 0
+
+ def _flush_buffer() -> str:
+ nonlocal buffered_chars
+ text = "".join(buffered_chunks)
+ buffered_chunks.clear()
+ buffered_chars = 0
+ return text
+
+ async def _queue_get(timeout: float | None = None) -> str | BaseException | None:
+ if timeout is None:
+ return await queue.get()
+ return await asyncio.wait_for(queue.get(), timeout=timeout)
+
while True:
item = await queue.get()
if item is None:
+ if buffered_chunks:
+ yield _flush_buffer()
break
if isinstance(item, BaseException):
+ if buffered_chunks:
+ yield _flush_buffer()
raise item
- yield item
+ if item in STREAM_CONTROL_TOKENS or stream_coalesce_seconds <= 0:
+ if buffered_chunks:
+ yield _flush_buffer()
+ yield item
+ continue
+ if not sent_first_text_chunk:
+ sent_first_text_chunk = True
+ yield item
+ continue
+ buffered_chunks.append(item)
+ buffered_chars += len(item)
+ deadline = asyncio.get_running_loop().time() + stream_coalesce_seconds
+ while buffered_chunks and buffered_chars < stream_coalesce_chars:
+ timeout = deadline - asyncio.get_running_loop().time()
+ if timeout <= 0:
+ break
+ try:
+ next_item = await _queue_get(timeout)
+ except asyncio.TimeoutError:
+ break
+ if next_item is None:
+ if buffered_chunks:
+ yield _flush_buffer()
+ await task
+ return
+ if isinstance(next_item, BaseException):
+ if buffered_chunks:
+ yield _flush_buffer()
+ raise next_item
+ if next_item in STREAM_CONTROL_TOKENS:
+ if buffered_chunks:
+ yield _flush_buffer()
+ yield next_item
+ break
+ buffered_chunks.append(next_item)
+ buffered_chars += len(next_item)
+ if buffered_chunks:
+ yield _flush_buffer()
await task
finally:
if not task.done():
diff --git a/deeptutor/services/llm/provider_core/openai_compat_provider.py b/deeptutor/services/llm/provider_core/openai_compat_provider.py
index 1b0cc7df3..e188068c3 100644
--- a/deeptutor/services/llm/provider_core/openai_compat_provider.py
+++ b/deeptutor/services/llm/provider_core/openai_compat_provider.py
@@ -56,6 +56,9 @@ _THINKING_STYLE_MAP = {
"enable_thinking": lambda enabled: {"enable_thinking": enabled},
"reasoning_split": lambda enabled: {"reasoning_split": enabled},
}
+_THINKING_DISABLED_BY_DEFAULT: tuple[tuple[str, str], ...] = (
+ ("deepseek", "deepseek-v4-flash"),
+)
def _short_tool_id() -> str:
@@ -105,6 +108,16 @@ def _responses_circuit_key(
return f"{model_name}|{effort}"
+def _disable_thinking_by_default(spec: "ProviderSpec | None", model_name: str) -> bool:
+ if not spec:
+ return False
+ normalized = (model_name or "").strip().lower()
+ return any(
+ spec.name == provider and pattern in normalized
+ for provider, pattern in _THINKING_DISABLED_BY_DEFAULT
+ )
+
+
class OpenAICompatProvider(LLMProvider):
"""Unified provider for all OpenAI-compatible APIs.
@@ -323,6 +336,16 @@ class OpenAICompatProvider(LLMProvider):
)
if extra:
kwargs.setdefault("extra_body", {}).update(extra)
+ elif (
+ spec
+ and spec.thinking_style
+ and _disable_thinking_by_default(spec, model_name)
+ ):
+ extra = _THINKING_STYLE_MAP.get(spec.thinking_style, lambda _enabled: None)(
+ False
+ )
+ if extra:
+ kwargs.setdefault("extra_body", {}).update(extra)
if tools:
kwargs["tools"] = tools
diff --git a/deeptutor/services/rag/factory.py b/deeptutor/services/rag/factory.py
index 74af6c4f1..a87c0ca7f 100644
--- a/deeptutor/services/rag/factory.py
+++ b/deeptutor/services/rag/factory.py
@@ -54,7 +54,7 @@ def list_pipelines() -> List[Dict[str, str]]:
{
"id": DEFAULT_PROVIDER,
"name": "LlamaIndex",
- "description": "Pure vector retrieval, fastest processing speed.",
+ "description": "LlamaIndex retrieval with hybrid BM25/vector fusion when available.",
}
]
diff --git a/deeptutor/services/rag/file_routing.py b/deeptutor/services/rag/file_routing.py
index 328d5122a..f5c7655f8 100644
--- a/deeptutor/services/rag/file_routing.py
+++ b/deeptutor/services/rag/file_routing.py
@@ -34,6 +34,7 @@ class FileClassification:
parser_files: List[str]
text_files: List[str]
+ image_files: List[str]
unsupported: List[str]
@@ -217,6 +218,7 @@ class FileTypeRouter:
"""Classify a list of files by processing method."""
parser_files = []
text_files = []
+ image_files = []
unsupported = []
for path in file_paths:
@@ -231,17 +233,21 @@ class FileTypeRouter:
parser_files.append(path)
elif doc_type in (DocumentType.TEXT, DocumentType.MARKDOWN):
text_files.append(path)
+ elif doc_type == DocumentType.IMAGE:
+ image_files.append(path)
else:
unsupported.append(path)
logger.debug(
f"Classified {len(file_paths)} files: "
- f"{len(parser_files)} parser, {len(text_files)} text, {len(unsupported)} unsupported"
+ f"{len(parser_files)} parser, {len(text_files)} text, "
+ f"{len(image_files)} image, {len(unsupported)} unsupported"
)
return FileClassification(
parser_files=parser_files,
text_files=text_files,
+ image_files=image_files,
unsupported=unsupported,
)
@@ -303,7 +309,7 @@ class FileTypeRouter:
@classmethod
def get_supported_extensions(cls) -> set[str]:
"""Get the set of all supported file extensions."""
- return cls.PARSER_EXTENSIONS | cls.TEXT_EXTENSIONS
+ return cls.PARSER_EXTENSIONS | cls.TEXT_EXTENSIONS | cls.IMAGE_EXTENSIONS
@classmethod
def has_supported_extension(cls, file_path: str | Path) -> bool:
diff --git a/deeptutor/services/rag/pipelines/llamaindex/config.py b/deeptutor/services/rag/pipelines/llamaindex/config.py
new file mode 100644
index 000000000..713911109
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/llamaindex/config.py
@@ -0,0 +1,60 @@
+"""Configuration helpers for DeepTutor's LlamaIndex RAG pipeline."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import os
+
+
+VECTOR_PROFILE = "vector"
+HYBRID_PROFILE = "hybrid"
+SUPPORTED_RETRIEVAL_PROFILES = {VECTOR_PROFILE, HYBRID_PROFILE}
+
+
+@dataclass(frozen=True)
+class RetrievalConfig:
+ """Runtime retrieval knobs for the LlamaIndex pipeline."""
+
+ profile: str = HYBRID_PROFILE
+ vector_top_k_multiplier: int = 2
+ bm25_top_k_multiplier: int = 2
+ fusion_num_queries: int = 1
+
+ def candidate_top_k(self, top_k: int, multiplier: int) -> int:
+ """Return the number of candidates to ask a child retriever for."""
+ requested = max(1, int(top_k))
+ return max(requested, requested * max(1, int(multiplier)))
+
+
+def normalize_retrieval_profile(value: str | None) -> str:
+ """Return a supported retrieval profile, defaulting to hybrid."""
+ profile = (value or "").strip().lower()
+ if profile in SUPPORTED_RETRIEVAL_PROFILES:
+ return profile
+ return HYBRID_PROFILE
+
+
+def retrieval_config_from_env() -> RetrievalConfig:
+ """Build retrieval config from environment variables.
+
+ The default is intentionally ``hybrid``. If the optional LlamaIndex BM25
+ integration is not installed, the retriever builder transparently falls
+ back to plain vector retrieval.
+ """
+
+ return RetrievalConfig(
+ profile=normalize_retrieval_profile(
+ os.getenv("DEEPTUTOR_RAG_RETRIEVAL_PROFILE")
+ or os.getenv("RAG_RETRIEVAL_PROFILE")
+ )
+ )
+
+
+__all__ = [
+ "HYBRID_PROFILE",
+ "RetrievalConfig",
+ "SUPPORTED_RETRIEVAL_PROFILES",
+ "VECTOR_PROFILE",
+ "normalize_retrieval_profile",
+ "retrieval_config_from_env",
+]
diff --git a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py b/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
index b22141d7d..42dfb6b70 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
@@ -2,16 +2,33 @@
from __future__ import annotations
+import base64
import logging
+import mimetypes
from pathlib import Path
-from typing import Iterable
+from typing import Any, Iterable
from llama_index.core import Document
+from llama_index.core.schema import ImageNode
+from deeptutor.services.embedding import get_embedding_client
+from deeptutor.services.llm.client import get_llm_client
from deeptutor.services.rag.file_routing import FileTypeRouter
from deeptutor.utils.document_extractor import DocumentExtractionError, extract_text_from_path
from deeptutor.utils.document_validator import DocumentValidator
+IMAGE_DESCRIPTION_SYSTEM_PROMPT = (
+ "You describe images for a retrieval-augmented knowledge base. "
+ "Be factual, concise, and include any visible text, labels, diagrams, "
+ "tables, logos, or important visual relationships. Do not invent details."
+)
+
+IMAGE_DESCRIPTION_PROMPT = (
+ "Describe this image so that a text-only answer generator can understand "
+ "and cite it later. Include visible text/OCR if present, the main subject, "
+ "and any educational or technical meaning. Keep the answer under 180 words."
+)
+
class LlamaIndexDocumentLoader:
"""Convert source files into LlamaIndex ``Document`` objects."""
@@ -19,8 +36,8 @@ class LlamaIndexDocumentLoader:
def __init__(self, logger=None) -> None:
self.logger = logger or logging.getLogger(__name__)
- async def load(self, file_paths: Iterable[str]) -> list[Document]:
- documents: list[Document] = []
+ async def load(self, file_paths: Iterable[str]) -> list[Any]:
+ documents: list[Any] = []
classification = FileTypeRouter.classify_files(list(file_paths))
for file_path_str in classification.parser_files:
@@ -35,6 +52,10 @@ class LlamaIndexDocumentLoader:
text = await FileTypeRouter.read_text_file(str(file_path))
self._append_if_nonempty(documents, file_path, text)
+ if classification.image_files:
+ image_nodes = await self._load_image_nodes(classification.image_files)
+ documents.extend(image_nodes)
+
for file_path_str in classification.unsupported:
self.logger.warning(f"Skipped unsupported file: {Path(file_path_str).name}")
@@ -52,7 +73,128 @@ class LlamaIndexDocumentLoader:
self.logger.error(f"Failed to extract {file_path.name}: {exc}")
return ""
- def _append_if_nonempty(self, documents: list[Document], file_path: Path, text: str) -> None:
+ async def _load_image_nodes(self, file_paths: list[str]) -> list[ImageNode]:
+ embedding_client = get_embedding_client()
+ llm_client = get_llm_client()
+
+ unsupported_reasons = []
+ if not embedding_client.supports_multimodal_contents():
+ unsupported_reasons.append(
+ "embedding provider/model does not support multimodal contents "
+ f"(binding={embedding_client.config.binding}, "
+ f"model={embedding_client.config.model})"
+ )
+ if not llm_client.supports_multimodal_images():
+ unsupported_reasons.append(
+ "LLM provider/model does not support multimodal image input "
+ f"(binding={llm_client.config.binding}, model={llm_client.config.model})"
+ )
+ if unsupported_reasons:
+ reason_text = "; ".join(unsupported_reasons)
+ for file_path_str in file_paths:
+ self.logger.warning(
+ "Skipped image file because image indexing requires both "
+ f"multimodal embedding and multimodal LLM support; {reason_text}: "
+ f"{Path(file_path_str).name}"
+ )
+ return []
+
+ paths = [Path(file_path_str) for file_path_str in file_paths]
+ embedded_paths: list[Path] = []
+ descriptions: list[str] = []
+ contents = []
+ for path in paths:
+ try:
+ image_payload = self._load_image_payload(path)
+ description = await self._describe_image(
+ path,
+ image_payload["base64"],
+ image_payload["mimetype"],
+ )
+ if not description:
+ self.logger.warning(
+ "Skipped image file because the configured multimodal LLM "
+ f"returned no description: {path.name}"
+ )
+ continue
+ contents.append({"image": image_payload["data_uri"]})
+ embedded_paths.append(path)
+ descriptions.append(description)
+ except OSError as exc:
+ self.logger.error(f"Failed to read image {path.name}: {exc}")
+ except Exception as exc:
+ self.logger.error(
+ "Failed to describe image %s with configured multimodal LLM "
+ "(binding=%s, model=%s): %s",
+ path.name,
+ llm_client.config.binding,
+ llm_client.config.model,
+ exc,
+ )
+
+ if not contents:
+ return []
+
+ try:
+ embeddings = await embedding_client.embed_contents(contents)
+ except Exception as exc:
+ self.logger.error(
+ "Failed to embed image contents with configured multimodal embedding "
+ "provider/model (binding=%s, model=%s): %s",
+ embedding_client.config.binding,
+ embedding_client.config.model,
+ exc,
+ )
+ return []
+ nodes: list[ImageNode] = []
+ for path, description, embedding in zip(embedded_paths, descriptions, embeddings):
+ mimetype = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
+ nodes.append(
+ ImageNode(
+ text=f"[Image] {path.name}\n\n{description}",
+ image_path=str(path),
+ image_mimetype=mimetype,
+ metadata={
+ "file_name": path.name,
+ "file_path": str(path),
+ "content_type": "image",
+ "image_description": description,
+ },
+ embedding=embedding,
+ )
+ )
+ self.logger.info(f"Loaded image: {path.name} ({len(embedding)}D vector)")
+ return nodes
+
+ async def _describe_image(
+ self, file_path: Path, image_base64: str, mimetype: str
+ ) -> str:
+ llm_client = get_llm_client()
+ response = await llm_client.complete(
+ IMAGE_DESCRIPTION_PROMPT,
+ system_prompt=IMAGE_DESCRIPTION_SYSTEM_PROMPT,
+ image_data=image_base64,
+ image_mime_type=mimetype,
+ image_filename=file_path.name,
+ )
+ return response.strip()
+
+ def _load_image_payload(self, file_path: Path) -> dict[str, str]:
+ size = file_path.stat().st_size
+ if size > DocumentValidator.MAX_FILE_SIZE:
+ raise OSError(
+ f"image file too large: {size} bytes; "
+ f"maximum allowed: {DocumentValidator.MAX_FILE_SIZE} bytes"
+ )
+ mimetype = mimetypes.guess_type(file_path.name)[0] or "application/octet-stream"
+ encoded = base64.b64encode(file_path.read_bytes()).decode("ascii")
+ return {
+ "base64": encoded,
+ "data_uri": f"data:{mimetype};base64,{encoded}",
+ "mimetype": mimetype,
+ }
+
+ def _append_if_nonempty(self, documents: list[Any], file_path: Path, text: str) -> None:
if text.strip():
documents.append(
Document(
diff --git a/deeptutor/services/rag/pipelines/llamaindex/ingestion.py b/deeptutor/services/rag/pipelines/llamaindex/ingestion.py
new file mode 100644
index 000000000..774b2e9a6
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/llamaindex/ingestion.py
@@ -0,0 +1,78 @@
+"""LlamaIndex ingestion helpers.
+
+This module keeps DeepTutor's indexing path thin by delegating parsing
+transformations and embedding to LlamaIndex's official IngestionPipeline.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+from llama_index.core import Settings, VectorStoreIndex
+from llama_index.core.ingestion import IngestionPipeline
+from llama_index.core.node_parser import SentenceSplitter
+from llama_index.core.schema import BaseNode
+
+
+def build_ingestion_pipeline() -> IngestionPipeline:
+ """Create the default DeepTutor ingestion pipeline.
+
+ The embedding step uses ``Settings.embed_model``, which is configured by
+ ``embedding_adapter.configure_llamaindex_settings`` to call DeepTutor's
+ configured embedding service rather than any local model.
+ """
+
+ return IngestionPipeline(
+ transformations=[
+ SentenceSplitter(
+ chunk_size=Settings.chunk_size,
+ chunk_overlap=Settings.chunk_overlap,
+ ),
+ Settings.embed_model,
+ ],
+ )
+
+
+def documents_to_nodes(documents: list[Any], *, show_progress: bool = True) -> list[Any]:
+ """Convert LlamaIndex documents into embedded nodes.
+
+ Pre-embedded nodes, such as ImageNode instances produced by the document
+ loader, pass through unchanged so they are not re-embedded as text.
+ """
+ text_documents = [document for document in documents if not isinstance(document, BaseNode)]
+ preembedded_nodes = [document for document in documents if isinstance(document, BaseNode)]
+
+ nodes: list[Any] = []
+ if text_documents:
+ pipeline = build_ingestion_pipeline()
+ nodes.extend(pipeline.run(documents=text_documents, show_progress=show_progress))
+ nodes.extend(preembedded_nodes)
+ return nodes
+
+
+def create_index_from_documents(
+ documents: list[Any], storage_dir: Path, *, show_progress: bool = True
+) -> tuple[VectorStoreIndex, int]:
+ """Create and persist a VectorStoreIndex from documents."""
+ nodes = documents_to_nodes(documents, show_progress=show_progress)
+ index = VectorStoreIndex(nodes=nodes, show_progress=show_progress)
+ index.storage_context.persist(persist_dir=str(storage_dir))
+ return index, len(documents)
+
+
+def insert_documents_into_index(
+ index: Any, documents: list[Any], *, show_progress: bool = True
+) -> int:
+ """Transform documents once, then insert nodes into an existing index."""
+ nodes = documents_to_nodes(documents, show_progress=show_progress)
+ index.insert_nodes(nodes)
+ return len(documents)
+
+
+__all__ = [
+ "build_ingestion_pipeline",
+ "create_index_from_documents",
+ "documents_to_nodes",
+ "insert_documents_into_index",
+]
diff --git a/deeptutor/services/rag/pipelines/llamaindex/retrievers.py b/deeptutor/services/rag/pipelines/llamaindex/retrievers.py
new file mode 100644
index 000000000..1833eea15
--- /dev/null
+++ b/deeptutor/services/rag/pipelines/llamaindex/retrievers.py
@@ -0,0 +1,139 @@
+"""Retriever composition for the LlamaIndex RAG pipeline."""
+
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+import shutil
+from typing import Any
+
+from llama_index.core.llms.mock import MockLLM
+from llama_index.core.retrievers import QueryFusionRetriever
+from llama_index.core.retrievers.fusion_retriever import FUSION_MODES
+
+from .config import HYBRID_PROFILE, VECTOR_PROFILE, RetrievalConfig, retrieval_config_from_env
+
+logger = logging.getLogger(__name__)
+
+BM25_PERSIST_DIRNAME = "bm25_retriever"
+
+
+def _import_bm25_retriever():
+ try:
+ from llama_index.retrievers.bm25 import BM25Retriever
+
+ return BM25Retriever
+ except ImportError:
+ return None
+
+
+def _bm25_persist_dir(storage_dir: Path) -> Path:
+ return storage_dir / BM25_PERSIST_DIRNAME
+
+
+def _set_similarity_top_k(retriever: Any, top_k: int) -> Any:
+ if hasattr(retriever, "similarity_top_k"):
+ retriever.similarity_top_k = top_k
+ return retriever
+
+
+def build_bm25_retriever(index: Any, storage_dir: Path, *, top_k: int) -> Any | None:
+ """Build or load LlamaIndex's official BM25 retriever if available."""
+ top_k = max(1, int(top_k))
+ bm25_cls = _import_bm25_retriever()
+ if bm25_cls is None:
+ logger.info(
+ "LlamaIndex BM25 retriever package is not installed; "
+ "falling back to vector retrieval."
+ )
+ return None
+
+ persist_dir = _bm25_persist_dir(storage_dir)
+ if persist_dir.exists():
+ try:
+ retriever = bm25_cls.from_persist_dir(str(persist_dir))
+ return _set_similarity_top_k(retriever, top_k)
+ except Exception as exc:
+ logger.warning("Failed to load persisted BM25 retriever from %s: %s", persist_dir, exc)
+
+ try:
+ return bm25_cls.from_defaults(index=index, similarity_top_k=top_k)
+ except Exception as exc:
+ logger.warning("Failed to build BM25 retriever; falling back to vector retrieval: %s", exc)
+ return None
+
+
+def persist_bm25_retriever(index: Any, storage_dir: Path, *, top_k: int) -> bool:
+ """Persist BM25 sidecar index for faster hybrid retrieval.
+
+ Missing optional dependencies are non-fatal because hybrid retrieval can
+ still be enabled in deployments that install ``llama-index-retrievers-bm25``.
+ """
+ top_k = max(1, int(top_k))
+ bm25_cls = _import_bm25_retriever()
+ if bm25_cls is None:
+ return False
+
+ persist_dir = _bm25_persist_dir(storage_dir)
+ if persist_dir.exists():
+ shutil.rmtree(persist_dir, ignore_errors=True)
+
+ try:
+ retriever = bm25_cls.from_defaults(index=index, similarity_top_k=top_k)
+ except Exception as exc:
+ logger.warning("Failed to build BM25 retriever for persistence: %s", exc)
+ return False
+
+ if not hasattr(retriever, "persist"):
+ return False
+
+ persist_dir.mkdir(parents=True, exist_ok=True)
+ try:
+ retriever.persist(str(persist_dir))
+ return True
+ except Exception as exc:
+ logger.warning("Failed to persist BM25 retriever to %s: %s", persist_dir, exc)
+ return False
+
+
+def build_retriever(
+ index: Any,
+ storage_dir: Path,
+ *,
+ top_k: int = 5,
+ config: RetrievalConfig | None = None,
+) -> Any:
+ """Compose the retrieval stack from official LlamaIndex retrievers."""
+ top_k = max(1, int(top_k))
+ retrieval_config = config or retrieval_config_from_env()
+ if retrieval_config.profile == VECTOR_PROFILE:
+ return index.as_retriever(similarity_top_k=top_k)
+
+ bm25_top_k = retrieval_config.candidate_top_k(top_k, retrieval_config.bm25_top_k_multiplier)
+ bm25_retriever = build_bm25_retriever(index, storage_dir, top_k=bm25_top_k)
+ if bm25_retriever is None:
+ return index.as_retriever(similarity_top_k=top_k)
+
+ if retrieval_config.profile == HYBRID_PROFILE:
+ vector_top_k = retrieval_config.candidate_top_k(
+ top_k, retrieval_config.vector_top_k_multiplier
+ )
+ vector_retriever = index.as_retriever(similarity_top_k=vector_top_k)
+ return QueryFusionRetriever(
+ [vector_retriever, bm25_retriever],
+ llm=MockLLM(),
+ mode=FUSION_MODES.RECIPROCAL_RANK,
+ similarity_top_k=top_k,
+ num_queries=retrieval_config.fusion_num_queries,
+ use_async=False,
+ )
+
+ return index.as_retriever(similarity_top_k=top_k)
+
+
+__all__ = [
+ "BM25_PERSIST_DIRNAME",
+ "build_bm25_retriever",
+ "build_retriever",
+ "persist_bm25_retriever",
+]
diff --git a/deeptutor/services/rag/pipelines/llamaindex/storage.py b/deeptutor/services/rag/pipelines/llamaindex/storage.py
index a82251712..7f8c04df5 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/storage.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/storage.py
@@ -8,7 +8,7 @@ from pathlib import Path
import shutil
from typing import Any
-from llama_index.core import StorageContext, VectorStoreIndex, load_index_from_storage
+from llama_index.core import StorageContext, load_index_from_storage
from deeptutor.services.embedding.validation import validate_embedding_batch
from deeptutor.services.rag.index_versioning import (
@@ -18,6 +18,8 @@ from deeptutor.services.rag.index_versioning import (
resolve_storage_dir_for_write,
)
+from . import ingestion, retrievers
+
@dataclass(frozen=True)
class AddStoragePlan:
@@ -65,19 +67,27 @@ def resolve_add_storage_plan(kb_dir: Path, signature: EmbeddingSignature | None)
def create_index(documents: list[Any], storage_dir: Path, *, show_progress: bool = True) -> int:
- index = VectorStoreIndex.from_documents(documents, show_progress=show_progress)
- index.storage_context.persist(persist_dir=str(storage_dir))
- return len(documents)
+ index, count = ingestion.create_index_from_documents(
+ documents, storage_dir, show_progress=show_progress
+ )
+ retrievers.persist_bm25_retriever(index, storage_dir, top_k=20)
+ return count
def insert_documents(existing_storage: Path, storage_dir: Path, documents: list[Any]) -> int:
storage_context = StorageContext.from_defaults(persist_dir=str(existing_storage))
index = load_index_from_storage(storage_context)
_validate_persisted_embeddings(index, existing_storage)
- for document in documents:
- index.insert(document)
+ if hasattr(index, "insert_nodes"):
+ count = ingestion.insert_documents_into_index(index, documents, show_progress=True)
+ else:
+ # Some tests use a tiny fake index that only implements insert().
+ for document in documents:
+ index.insert(document)
+ count = len(documents)
index.storage_context.persist(persist_dir=str(storage_dir))
- return len(documents)
+ retrievers.persist_bm25_retriever(index, storage_dir, top_k=20)
+ return count
def _validate_embedding_dict(embedding_dict: Any, *, label: str) -> None:
@@ -166,7 +176,7 @@ def retrieve_nodes(storage_dir: Path, query: str, *, top_k: int = 5) -> list[Any
storage_context = StorageContext.from_defaults(persist_dir=str(storage_dir))
index = load_index_from_storage(storage_context)
_validate_persisted_embeddings(index, storage_dir)
- retriever = index.as_retriever(similarity_top_k=top_k)
+ retriever = retrievers.build_retriever(index, storage_dir, top_k=top_k)
return retriever.retrieve(query)
diff --git a/deeptutor/services/session/context_builder.py b/deeptutor/services/session/context_builder.py
index cf5346ece..2d6360149 100644
--- a/deeptutor/services/session/context_builder.py
+++ b/deeptutor/services/session/context_builder.py
@@ -310,9 +310,15 @@ class ContextBuilder:
llm_config: LLMConfig,
language: str = "en",
on_event: Callable[[StreamEvent], Awaitable[None]] | None = None,
+ leaf_message_id: int | None = None,
) -> ContextBuildResult:
session = await self.store.get_session(session_id)
- messages = await self.store.get_messages_for_context(session_id)
+ # When ``leaf_message_id`` is given (edit-branch turn), only the
+ # ancestor path of that message is included in context — sibling
+ # branches at any depth are excluded.
+ messages = await self.store.get_messages_for_context(
+ session_id, leaf_message_id=leaf_message_id
+ )
if session is None:
return ContextBuildResult([], "", "", [], 0, self._history_budget(llm_config))
diff --git a/deeptutor/services/session/pocketbase_store.py b/deeptutor/services/session/pocketbase_store.py
index a2741086a..6b78b55f5 100644
--- a/deeptutor/services/session/pocketbase_store.py
+++ b/deeptutor/services/session/pocketbase_store.py
@@ -290,7 +290,12 @@ class PocketBaseSessionStore:
events: list[dict[str, Any]] | None = None,
attachments: list[dict[str, Any]] | None = None,
metadata: dict[str, Any] | None = None,
+ parent_message_id: int | None = None,
) -> int:
+ # ``parent_message_id`` is accepted to match the protocol shape but is
+ # not yet wired through PocketBase storage — branching only works on
+ # the SQLite backend today.
+ _ = parent_message_id
now = time.time()
def _add():
@@ -385,7 +390,12 @@ class PocketBaseSessionStore:
logger.warning(f"get_messages failed: {exc}")
return []
- async def get_messages_for_context(self, session_id: str) -> list[dict[str, Any]]:
+ async def get_messages_for_context(
+ self, session_id: str, leaf_message_id: int | None = None
+ ) -> list[dict[str, Any]]:
+ # leaf_message_id (branch-aware context) is not supported on PocketBase
+ # yet; fall back to the linear, append-only view.
+ _ = leaf_message_id
messages = await self.get_messages(session_id)
return [
{"id": m["id"], "role": m["role"], "content": m["content"] or ""}
diff --git a/deeptutor/services/session/protocol.py b/deeptutor/services/session/protocol.py
index 3ede58974..b1c1c1a40 100644
--- a/deeptutor/services/session/protocol.py
+++ b/deeptutor/services/session/protocol.py
@@ -54,6 +54,7 @@ class SessionStoreProtocol(Protocol):
events: list[dict[str, Any]] | None = None,
attachments: list[dict[str, Any]] | None = None,
metadata: dict[str, Any] | None = None,
+ parent_message_id: int | None = None,
) -> int: ...
async def delete_message(self, message_id: int | str) -> bool: ...
@@ -64,7 +65,9 @@ class SessionStoreProtocol(Protocol):
async def get_messages(self, session_id: str) -> list[dict[str, Any]]: ...
- async def get_messages_for_context(self, session_id: str) -> list[dict[str, Any]]: ...
+ async def get_messages_for_context(
+ self, session_id: str, leaf_message_id: int | None = None
+ ) -> list[dict[str, Any]]: ...
async def list_sessions(
self,
diff --git a/deeptutor/services/session/source_inventory.py b/deeptutor/services/session/source_inventory.py
new file mode 100644
index 000000000..841be4564
--- /dev/null
+++ b/deeptutor/services/session/source_inventory.py
@@ -0,0 +1,671 @@
+"""Branch-isolated, cumulative source inventory for the chat capability.
+
+The chat pipeline shows the LLM an "Attached Sources" manifest each turn so
+it can decide whether to call ``read_source(id)`` for full text. Historically
+this manifest only listed sources the user attached in the *current* turn —
+so the model forgot anything uploaded in earlier turns unless re-attached.
+
+This module materialises the manifest as a **session-cumulative inventory**:
+
+* Sources attached in the current turn (the "fresh" set) get a full preview
+ in the manifest, just like before.
+* Sources attached in *prior* turns on the active branch's ancestor chain
+ (the "historical" set) get a compact one-line row: id, name, kind, size,
+ and the turn ordinal where they first appeared. The LLM can call
+ ``read_source(id)`` to load full text when the question warrants it.
+
+Both sets dedupe by source id; fresh always wins on collision. Branch
+isolation is enforced by walking ``parent_message_id`` from the active
+branch's leaf, so sibling branches never leak sources into each other.
+
+The output is decoupled from the rest of ``turn_runtime``:
+
+ inventory = await build_inventory(store, ..., fresh_*=...)
+ manifest_text, source_index = render_manifest(inventory)
+
+``source_index`` is the per-turn ``{source_id: full_text}`` map handed to
+``ReadSourceTool`` via tool-call kwargs injection.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass, field
+from typing import Any, Sequence
+
+from deeptutor.services.session.protocol import SessionStoreProtocol
+
+logger = logging.getLogger(__name__)
+
+# Per-source text-preview caps. Fresh sources get a meaningful preview so
+# the model can answer simple "is this the right one?" questions without
+# read_source. Historical sources surface only their identity — the model
+# pays the read_source cost only when it actually needs them.
+MANIFEST_PREVIEW_CHARS_FRESH = 2000
+# Image attachments flow through the multimodal block path; never list them.
+_IMAGE_MIME_PREFIX = "image/"
+
+
+@dataclass(frozen=True)
+class SourceEntry:
+ """One row in the per-turn Attached Sources manifest."""
+
+ sid: str
+ kind: str # "notebook" | "book" | "history" | "question" | "attachment"
+ name: str
+ full_text: str
+ fresh: bool
+ # 1-indexed ordinal of the user turn this source first appeared in,
+ # within the active branch's lineage. Fresh sources use the **current**
+ # turn's ordinal so the manifest can label them consistently.
+ first_seen_turn: int
+
+ @property
+ def char_count(self) -> int:
+ return len(self.full_text)
+
+
+@dataclass
+class SourceInventory:
+ """Ordered set of ``SourceEntry`` keyed by ``sid``.
+
+ ``add`` is the only mutator. On duplicate ``sid`` the existing entry is
+ upgraded to ``fresh=True`` if the incoming entry is fresh — so a source
+ attached in the current turn always renders with a preview even if it
+ was also attached in a prior turn.
+ """
+
+ entries: list[SourceEntry] = field(default_factory=list)
+ _index: dict[str, int] = field(default_factory=dict, repr=False)
+
+ def add(self, entry: SourceEntry) -> None:
+ if not entry.sid:
+ return
+ if not entry.full_text.strip():
+ return
+ existing_pos = self._index.get(entry.sid)
+ if existing_pos is None:
+ self._index[entry.sid] = len(self.entries)
+ self.entries.append(entry)
+ return
+ existing = self.entries[existing_pos]
+ # Fresh always wins; otherwise keep the earlier registration.
+ if entry.fresh and not existing.fresh:
+ self.entries[existing_pos] = entry
+
+ def is_empty(self) -> bool:
+ return not self.entries
+
+ def __contains__(self, sid: str) -> bool:
+ return sid in self._index
+
+
+# ---------------------------------------------------------------------------
+# Public API: build + render
+# ---------------------------------------------------------------------------
+
+
+async def build_inventory(
+ store: SessionStoreProtocol,
+ *,
+ session_id: str,
+ leaf_message_id: int | None,
+ current_turn_ordinal: int,
+ fresh_attachment_records: Sequence[dict[str, Any]],
+ fresh_notebook_records: Sequence[dict[str, Any]],
+ fresh_book_context_text: str,
+ fresh_book_references: Sequence[dict[str, Any]],
+ fresh_history_session_ids: Sequence[Any],
+ fresh_question_entry_ids: Sequence[Any],
+) -> SourceInventory:
+ """Compose the session-cumulative inventory for one chat turn.
+
+ Fresh refs are added first (so they shadow historical entries on the
+ same sid); historical refs are then collected from the active branch's
+ ancestor messages. The caller passes already-resolved notebook records
+ and the already-rendered book context — keeping side-effects (LLM
+ summarisation, file I/O) under the caller's control rather than buried
+ inside this module.
+ """
+ inv = SourceInventory()
+ _add_fresh(
+ inv,
+ current_turn_ordinal=current_turn_ordinal,
+ attachment_records=fresh_attachment_records,
+ notebook_records=fresh_notebook_records,
+ book_context_text=fresh_book_context_text,
+ book_references=fresh_book_references,
+ )
+ # History + question entries are async (per-id store fetches), keep them
+ # in a separate phase so the sync fresh additions don't block.
+ await _add_fresh_history(
+ inv,
+ store=store,
+ history_session_ids=fresh_history_session_ids,
+ current_turn_ordinal=current_turn_ordinal,
+ )
+ await _add_fresh_questions(
+ inv,
+ store=store,
+ question_entry_ids=fresh_question_entry_ids,
+ current_turn_ordinal=current_turn_ordinal,
+ )
+ await _add_historical(
+ inv, store=store, session_id=session_id, leaf_message_id=leaf_message_id
+ )
+ return inv
+
+
+def render_manifest(inv: SourceInventory) -> tuple[str, dict[str, str]]:
+ """Render the inventory into (manifest_text, source_index).
+
+ ``manifest_text`` is the human/LLM-readable block injected at the tail
+ of the chat system prompt. ``source_index`` maps each source id to its
+ full extracted text and is handed to ``ReadSourceTool`` so the LLM can
+ read on demand.
+ """
+ if inv.is_empty():
+ return "", {}
+
+ source_index: dict[str, str] = {sid: e.full_text for sid, e in _iter_sid_entries(inv)}
+ rendered_rows: list[str] = []
+ for entry in inv.entries:
+ rendered_rows.append(_render_row(entry))
+
+ header = (
+ "[Attached Sources]\n"
+ "Sources the user has attached in this conversation. Rows marked "
+ "`previously attached (turn N)` were uploaded in earlier turns and "
+ "show only their identity — call `read_source(source_id)` to load "
+ "their full text when the question warrants it. Rows with a "
+ "`preview` field were attached **this turn** and the preview is "
+ "often enough to answer without another tool call. Never invent "
+ "source ids."
+ )
+ return header + "\n\n" + "\n\n".join(rendered_rows), source_index
+
+
+# ---------------------------------------------------------------------------
+# Internals
+# ---------------------------------------------------------------------------
+
+
+def _iter_sid_entries(inv: SourceInventory):
+ seen: set[str] = set()
+ for e in inv.entries:
+ if e.sid in seen:
+ continue
+ seen.add(e.sid)
+ yield e.sid, e
+
+
+def _clip_preview(text: str, limit: int = MANIFEST_PREVIEW_CHARS_FRESH) -> str:
+ cleaned = (text or "").strip()
+ if len(cleaned) <= limit:
+ return cleaned
+ return cleaned[:limit].rstrip() + "…"
+
+
+def _format_size(char_count: int) -> str:
+ """Compact size hint for historical rows ('~3 KB', '~120 chars')."""
+ if char_count >= 1024:
+ return f"~{round(char_count / 1024)} KB"
+ return f"~{char_count} chars"
+
+
+def _render_row(entry: SourceEntry) -> str:
+ if entry.fresh:
+ preview = _clip_preview(entry.full_text)
+ return (
+ f"- id={entry.sid} type={entry.kind} name={entry.name!r}\n"
+ f" preview: {preview!r}"
+ )
+ return (
+ f"- id={entry.sid} type={entry.kind} name={entry.name!r}"
+ f" size={_format_size(entry.char_count)} "
+ f"source: previously attached (turn {entry.first_seen_turn})"
+ )
+
+
+# ----- Fresh source addition (current-turn payload) -----------------------
+
+
+def _add_fresh(
+ inv: SourceInventory,
+ *,
+ current_turn_ordinal: int,
+ attachment_records: Sequence[dict[str, Any]],
+ notebook_records: Sequence[dict[str, Any]],
+ book_context_text: str,
+ book_references: Sequence[dict[str, Any]],
+) -> None:
+ """Add the synchronously-available fresh sources (notebook records,
+ book pages, attachments)."""
+ for rec in notebook_records:
+ rid = str(rec.get("id", "") or "").strip()
+ full = str(rec.get("output", "") or "")
+ if not rid or not full.strip():
+ continue
+ inv.add(
+ SourceEntry(
+ sid=f"nb-{rid}",
+ kind="notebook",
+ name=str(rec.get("title") or rec.get("name") or "Untitled record"),
+ full_text=full,
+ fresh=True,
+ first_seen_turn=current_turn_ordinal,
+ )
+ )
+
+ # Books: split the cumulative ``build_book_context`` output by the
+ # ``---`` section separator so each book gets its own ``bk-{book_id}``
+ # sid. The order in ``book_references`` matches the order
+ # ``build_book_context`` produces sections in, so we can zip them.
+ book_sections = _split_book_sections(book_context_text)
+ for ref, section in zip(book_references, book_sections, strict=False):
+ book_id = str(ref.get("book_id") or "").strip()
+ if not book_id or not section.strip():
+ continue
+ inv.add(
+ SourceEntry(
+ sid=f"bk-{book_id}",
+ kind="book",
+ name=_extract_book_title(section, fallback=f"Book {book_id}"),
+ full_text=section,
+ fresh=True,
+ first_seen_turn=current_turn_ordinal,
+ )
+ )
+
+ for record in attachment_records:
+ if str(record.get("type", "")).lower() == "image":
+ continue
+ mime = str(record.get("mime_type", "")).lower()
+ if mime.startswith(_IMAGE_MIME_PREFIX):
+ continue
+ text = str(record.get("extracted_text", "") or "")
+ att_id = str(record.get("id", "") or "").strip()
+ if not text.strip() or not att_id:
+ continue
+ inv.add(
+ SourceEntry(
+ sid=f"at-{att_id}",
+ kind="attachment",
+ name=str(record.get("filename") or "Untitled file"),
+ full_text=text,
+ fresh=True,
+ first_seen_turn=current_turn_ordinal,
+ )
+ )
+
+
+async def _add_fresh_history(
+ inv: SourceInventory,
+ *,
+ store: SessionStoreProtocol,
+ history_session_ids: Sequence[Any],
+ current_turn_ordinal: int,
+) -> None:
+ for raw in history_session_ids:
+ hs_id = str(raw or "").strip()
+ if not hs_id:
+ continue
+ text, name = await _load_history_session(store, hs_id)
+ if not text:
+ continue
+ inv.add(
+ SourceEntry(
+ sid=f"hs-{hs_id}",
+ kind="history",
+ name=name,
+ full_text=text,
+ fresh=True,
+ first_seen_turn=current_turn_ordinal,
+ )
+ )
+
+
+async def _add_fresh_questions(
+ inv: SourceInventory,
+ *,
+ store: SessionStoreProtocol,
+ question_entry_ids: Sequence[Any],
+ current_turn_ordinal: int,
+) -> None:
+ get_entry = getattr(store, "get_notebook_entry", None)
+ if not callable(get_entry):
+ return
+ for raw in question_entry_ids:
+ try:
+ eid = int(raw)
+ except (TypeError, ValueError):
+ continue
+ block, stem = await _load_question_entry(store, eid)
+ if not block:
+ continue
+ inv.add(
+ SourceEntry(
+ sid=f"qb-{eid}",
+ kind="question",
+ name=stem,
+ full_text=block,
+ fresh=True,
+ first_seen_turn=current_turn_ordinal,
+ )
+ )
+
+
+# ----- Historical source collection ---------------------------------------
+
+
+async def _add_historical(
+ inv: SourceInventory,
+ *,
+ store: SessionStoreProtocol,
+ session_id: str,
+ leaf_message_id: int | None,
+) -> None:
+ """Walk the active branch's ancestor user messages and pull in
+ references they carried. Sources already in ``inv`` (i.e. fresh
+ duplicates) are skipped — fresh entries always win."""
+ lineage = await _load_lineage(store, session_id, leaf_message_id)
+ user_turn_ordinal = 0
+ for msg in lineage:
+ if msg.get("role") != "user":
+ continue
+ user_turn_ordinal += 1
+ await _collect_from_user_message(
+ inv, store=store, msg=msg, turn_ordinal=user_turn_ordinal
+ )
+
+
+async def _collect_from_user_message(
+ inv: SourceInventory,
+ *,
+ store: SessionStoreProtocol,
+ msg: dict[str, Any],
+ turn_ordinal: int,
+) -> None:
+ """Drain one prior user message into the inventory as historical
+ entries. Attachments are pulled from the persisted ``attachments``
+ JSON; space refs are pulled from ``metadata.request_snapshot`` and
+ re-resolved through their respective services so the historical
+ full text always reflects the current state of the referenced object.
+ """
+ # Attachments — extracted_text was persisted at upload time, no
+ # external lookup needed.
+ for att in msg.get("attachments") or []:
+ att_id = str(att.get("id", "") or "").strip()
+ if not att_id:
+ continue
+ sid = f"at-{att_id}"
+ if sid in inv:
+ continue
+ mime = str(att.get("mime_type", "")).lower()
+ if mime.startswith(_IMAGE_MIME_PREFIX):
+ continue
+ text = str(att.get("extracted_text") or "")
+ if not text.strip():
+ continue
+ inv.add(
+ SourceEntry(
+ sid=sid,
+ kind="attachment",
+ name=str(att.get("filename") or "Untitled file"),
+ full_text=text,
+ fresh=False,
+ first_seen_turn=turn_ordinal,
+ )
+ )
+
+ snap = (msg.get("metadata") or {}).get("request_snapshot") or {}
+ if not isinstance(snap, dict):
+ return
+
+ # Notebook records — re-resolve through the notebook service.
+ notebook_refs = snap.get("notebookReferences") or []
+ if notebook_refs:
+ from deeptutor.services.notebook import get_notebook_manager
+
+ try:
+ records = get_notebook_manager().get_records_by_references(list(notebook_refs))
+ except Exception:
+ records = []
+ for rec in records:
+ rid = str(rec.get("id", "") or "").strip()
+ if not rid:
+ continue
+ sid = f"nb-{rid}"
+ if sid in inv:
+ continue
+ full = str(rec.get("output", "") or "")
+ if not full.strip():
+ continue
+ inv.add(
+ SourceEntry(
+ sid=sid,
+ kind="notebook",
+ name=str(rec.get("title") or rec.get("name") or "Untitled record"),
+ full_text=full,
+ fresh=False,
+ first_seen_turn=turn_ordinal,
+ )
+ )
+
+ # Books — one source per book_id (union of page ranges across all
+ # turns is implicit because we always pull the *current* book reference
+ # to render).
+ for ref in snap.get("bookReferences") or []:
+ book_id = str((ref or {}).get("book_id") or "").strip()
+ if not book_id:
+ continue
+ sid = f"bk-{book_id}"
+ if sid in inv:
+ continue
+ section_text, name = _resolve_book_section(ref)
+ if not section_text.strip():
+ continue
+ inv.add(
+ SourceEntry(
+ sid=sid,
+ kind="book",
+ name=name,
+ full_text=section_text,
+ fresh=False,
+ first_seen_turn=turn_ordinal,
+ )
+ )
+
+ # History sessions — async, one store fetch per id.
+ for raw in snap.get("historyReferences") or []:
+ hs_id = str(raw or "").strip()
+ if not hs_id:
+ continue
+ sid = f"hs-{hs_id}"
+ if sid in inv:
+ continue
+ text, name = await _load_history_session(store, hs_id)
+ if not text:
+ continue
+ inv.add(
+ SourceEntry(
+ sid=sid,
+ kind="history",
+ name=name,
+ full_text=text,
+ fresh=False,
+ first_seen_turn=turn_ordinal,
+ )
+ )
+
+ # Question-bank entries.
+ for raw in snap.get("questionNotebookReferences") or []:
+ try:
+ eid = int(raw)
+ except (TypeError, ValueError):
+ continue
+ sid = f"qb-{eid}"
+ if sid in inv:
+ continue
+ block, stem = await _load_question_entry(store, eid)
+ if not block:
+ continue
+ inv.add(
+ SourceEntry(
+ sid=sid,
+ kind="question",
+ name=stem,
+ full_text=block,
+ fresh=False,
+ first_seen_turn=turn_ordinal,
+ )
+ )
+
+
+# ----- Lineage walker (branch-safe, store-protocol-compatible) ------------
+
+
+async def _load_lineage(
+ store: SessionStoreProtocol,
+ session_id: str,
+ leaf_message_id: int | None,
+) -> list[dict[str, Any]]:
+ """Return the active branch's ancestor user/assistant messages in
+ chronological order. When ``leaf_message_id`` is ``None`` (legacy
+ linear append), returns every message in the session. When it's set
+ (branched edit), walks the ``parent_message_id`` chain up from that
+ leaf so sibling branches are excluded. Uses ``get_messages`` (which
+ every store implements) plus a Python-side parent walk, avoiding a
+ sqlite-only ``get_message_path``.
+ """
+ all_msgs = await store.get_messages(session_id)
+ if leaf_message_id is None:
+ return all_msgs
+ by_id: dict[int, dict[str, Any]] = {}
+ for m in all_msgs:
+ mid = m.get("id")
+ if mid is not None:
+ by_id[int(mid)] = m
+ chain: list[dict[str, Any]] = []
+ current: int | None = int(leaf_message_id)
+ safety = 10_000
+ while current is not None and safety > 0:
+ m = by_id.get(int(current))
+ if m is None:
+ break
+ chain.append(m)
+ parent = m.get("parent_message_id")
+ current = int(parent) if parent is not None else None
+ safety -= 1
+ chain.reverse()
+ return chain
+
+
+# ----- Per-type resolvers shared by fresh + historical paths --------------
+
+
+def _split_book_sections(book_context_text: str) -> list[str]:
+ """Split the output of ``build_book_context`` back into per-book
+ sections. ``build_book_context`` joins sections with ``"\\n\\n---\\n\\n"``;
+ we split on the same separator. Returns an empty list when input is
+ empty."""
+ if not book_context_text.strip():
+ return []
+ return [seg for seg in book_context_text.split("\n\n---\n\n") if seg.strip()]
+
+
+def _extract_book_title(section: str, *, fallback: str) -> str:
+ """``_serialize_book_header`` prefixes every section with
+ ``# Book: <title>`` — extract that here for the manifest's name field."""
+ first_line = section.lstrip().split("\n", 1)[0]
+ prefix = "# Book: "
+ if first_line.startswith(prefix):
+ return first_line[len(prefix):].strip() or fallback
+ return fallback
+
+
+def _resolve_book_section(book_reference: dict[str, Any]) -> tuple[str, str]:
+ """Resolve a single book reference into its serialized section + title.
+
+ Used by the historical-collection path where each past turn's book
+ reference is rendered independently (so the per-book ``bk-{book_id}``
+ source id stays stable). Returns ``("", "")`` on failure.
+ """
+ from deeptutor.book.context import build_book_context
+
+ try:
+ result = build_book_context([book_reference])
+ except Exception:
+ logger.debug("Failed to resolve historical book reference", exc_info=True)
+ return "", ""
+ text = (result.text or "").strip()
+ if not text:
+ return "", ""
+ name = _extract_book_title(
+ text, fallback=f"Book {book_reference.get('book_id', '?')}"
+ )
+ return text, name
+
+
+async def _load_history_session(
+ store: SessionStoreProtocol, history_session_id: str
+) -> tuple[str, str]:
+ """Fetch and serialize a referenced history session into transcript +
+ title. Returns ``("", "")`` when the session is empty or missing.
+ """
+ try:
+ meta = await store.get_session(history_session_id)
+ except Exception:
+ meta = None
+ if not meta:
+ return "", ""
+ try:
+ messages_in_hs = await store.get_messages_for_context(history_session_id)
+ except Exception:
+ messages_in_hs = []
+ transcript_lines = [
+ f"## {str(m.get('role', '')).title()}\n{m.get('content', '')}"
+ for m in messages_in_hs
+ if str(m.get("content", "") or "").strip()
+ ]
+ if not transcript_lines:
+ return "", ""
+ name = str(meta.get("title", "") or "Untitled session")
+ return "\n\n".join(transcript_lines), name
+
+
+async def _load_question_entry(
+ store: SessionStoreProtocol, entry_id: int
+) -> tuple[str, str]:
+ """Fetch and render one question-bank entry into a markdown block +
+ short stem (used as the manifest name). Returns ``("", "")`` on
+ missing entry. Imports the renderer lazily to avoid pulling
+ ``turn_runtime``'s import surface into modules that consume this one."""
+ get_entry = getattr(store, "get_notebook_entry", None)
+ if not callable(get_entry):
+ return "", ""
+ try:
+ entry = await get_entry(entry_id)
+ except Exception:
+ entry = None
+ if not entry:
+ return "", ""
+ # Use the existing turn_runtime helper for consistency with fresh-path
+ # formatting. Imported here to keep this module's static deps minimal.
+ from deeptutor.services.session.turn_runtime import _format_question_bank_entry
+
+ block = _format_question_bank_entry(entry)
+ if not block.strip():
+ return "", ""
+ stem_source = str(entry.get("question", "") or "Untitled question")
+ stem = stem_source[:60].rstrip() or "Untitled question"
+ return block, stem
+
+
+__all__ = [
+ "MANIFEST_PREVIEW_CHARS_FRESH",
+ "SourceEntry",
+ "SourceInventory",
+ "build_inventory",
+ "render_manifest",
+]
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index 9e763e84c..c23fd8fca 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -21,6 +21,18 @@ def _json_dumps(value: Any) -> str:
return json.dumps(value, ensure_ascii=False)
+# Sentinel so ``add_message`` can distinguish "caller wants the legacy
+# auto-pick-latest-message default" from "caller explicitly wants the
+# message attached at the session root (parent = NULL)". Both surface as
+# ``None`` in the public ``parent_message_id`` arg, which is why we need
+# a sentinel separate from None.
+class _Unset:
+ pass
+
+
+_PARENT_AUTO = _Unset()
+
+
def _json_loads(value: str | None, default: Any) -> Any:
if not value:
return default
@@ -109,11 +121,20 @@ class SQLiteSessionStore:
events_json TEXT DEFAULT '',
attachments_json TEXT DEFAULT '',
metadata_json TEXT DEFAULT '{}',
- created_at REAL NOT NULL
+ created_at REAL NOT NULL,
+ -- Edit-branching: NULL for the first message in a session;
+ -- otherwise the immediately preceding message on the path
+ -- this row continues. Siblings (same parent) are alternate
+ -- branches the user can switch between.
+ parent_message_id INTEGER
);
CREATE INDEX IF NOT EXISTS idx_messages_session_created
ON messages(session_id, created_at, id);
+ -- ``idx_messages_parent`` is created after the
+ -- parent_message_id migration runs (see below). Putting it
+ -- in this script would fail on legacy DBs where the column
+ -- gets added by ALTER TABLE further down.
CREATE INDEX IF NOT EXISTS idx_sessions_updated_at
ON sessions(updated_at DESC);
@@ -202,6 +223,34 @@ class SQLiteSessionStore:
}
if "metadata_json" not in message_columns:
conn.execute("ALTER TABLE messages ADD COLUMN metadata_json TEXT DEFAULT '{}'")
+ if "parent_message_id" not in message_columns:
+ conn.execute("ALTER TABLE messages ADD COLUMN parent_message_id INTEGER")
+ # Backfill: for every existing session, treat the message stream
+ # as a single linear path — each row's parent is the previous
+ # row (by id) in the same session. Rows with no predecessor stay
+ # NULL. We do this per session in pure Python to avoid relying
+ # on window functions, which older SQLite builds may not have.
+ sessions_rows = conn.execute("SELECT id FROM sessions").fetchall()
+ for srow in sessions_rows:
+ prev_id: int | None = None
+ msg_rows = conn.execute(
+ "SELECT id FROM messages WHERE session_id = ? ORDER BY id ASC",
+ (srow[0],),
+ ).fetchall()
+ for mrow in msg_rows:
+ if prev_id is not None:
+ conn.execute(
+ "UPDATE messages SET parent_message_id = ? WHERE id = ?",
+ (prev_id, mrow[0]),
+ )
+ prev_id = mrow[0]
+ # Always ensure the parent-lookup index exists — covers both
+ # the legacy-migration case (just added the column) and the
+ # fresh-DB case (created above without the index inline).
+ conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_messages_parent "
+ "ON messages(session_id, parent_message_id)"
+ )
conn.commit()
async def _run(self, fn, *args):
@@ -572,6 +621,7 @@ class SQLiteSessionStore:
events: list[dict[str, Any]] | None = None,
attachments: list[dict[str, Any]] | None = None,
metadata: dict[str, Any] | None = None,
+ parent_message_id: int | None | _Unset = _PARENT_AUTO,
) -> int:
now = time.time()
with self._connect() as conn:
@@ -581,12 +631,29 @@ class SQLiteSessionStore:
if session is None:
raise ValueError(f"Session not found: {session_id}")
+ resolved_parent_id: int | None
+ if isinstance(parent_message_id, _Unset):
+ # Legacy auto-append path: chain off the latest row in the
+ # session so the linear thread stays connected.
+ last_row = conn.execute(
+ "SELECT id FROM messages WHERE session_id = ? ORDER BY id DESC LIMIT 1",
+ (session_id,),
+ ).fetchone()
+ resolved_parent_id = int(last_row["id"]) if last_row is not None else None
+ else:
+ # Caller pinned a parent explicitly — including ``None``,
+ # which means "attach at the session root" (used by edits
+ # of the very first message in a session).
+ resolved_parent_id = (
+ int(parent_message_id) if parent_message_id is not None else None
+ )
+
cur = conn.execute(
"""
INSERT INTO messages (
session_id, role, content, capability, events_json,
- attachments_json, metadata_json, created_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ attachments_json, metadata_json, created_at, parent_message_id
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
session_id,
@@ -597,6 +664,7 @@ class SQLiteSessionStore:
_json_dumps(attachments or []),
_json_dumps(metadata or {}),
now,
+ resolved_parent_id,
),
)
@@ -627,6 +695,7 @@ class SQLiteSessionStore:
events: list[dict[str, Any]] | None = None,
attachments: list[dict[str, Any]] | None = None,
metadata: dict[str, Any] | None = None,
+ parent_message_id: int | None | _Unset = _PARENT_AUTO,
) -> int:
return await self._run(
self._add_message_sync,
@@ -637,6 +706,7 @@ class SQLiteSessionStore:
events,
attachments,
metadata,
+ parent_message_id,
)
def _delete_message_sync(self, message_id: int | str) -> bool:
@@ -775,7 +845,7 @@ class SQLiteSessionStore:
row = conn.execute(
"""
SELECT id, session_id, role, content, capability, events_json,
- attachments_json, metadata_json, created_at
+ attachments_json, metadata_json, created_at, parent_message_id
FROM messages
WHERE session_id = ?
ORDER BY id DESC
@@ -787,7 +857,7 @@ class SQLiteSessionStore:
row = conn.execute(
"""
SELECT id, session_id, role, content, capability, events_json,
- attachments_json, metadata_json, created_at
+ attachments_json, metadata_json, created_at, parent_message_id
FROM messages
WHERE session_id = ? AND role = ?
ORDER BY id DESC
@@ -805,6 +875,8 @@ class SQLiteSessionStore:
return await self._run(self._get_last_message_sync, session_id, role)
def _serialize_message(self, row: sqlite3.Row) -> dict[str, Any]:
+ row_keys = row.keys()
+ parent_id = row["parent_message_id"] if "parent_message_id" in row_keys else None
return {
"id": row["id"],
"session_id": row["session_id"],
@@ -815,6 +887,7 @@ class SQLiteSessionStore:
"attachments": _json_loads(row["attachments_json"], []),
"metadata": _json_loads(row["metadata_json"], {}),
"created_at": row["created_at"],
+ "parent_message_id": int(parent_id) if parent_id is not None else None,
}
def _get_messages_sync(self, session_id: str) -> list[dict[str, Any]]:
@@ -822,7 +895,7 @@ class SQLiteSessionStore:
rows = conn.execute(
"""
SELECT id, session_id, role, content, capability, events_json,
- attachments_json, metadata_json, created_at
+ attachments_json, metadata_json, created_at, parent_message_id
FROM messages
WHERE session_id = ?
ORDER BY id ASC
@@ -831,27 +904,107 @@ class SQLiteSessionStore:
).fetchall()
return [self._serialize_message(row) for row in rows]
+ def _get_message_path_sync(
+ self, session_id: str, leaf_message_id: int
+ ) -> list[dict[str, Any]]:
+ """Return the chain of messages from the session root down to
+ ``leaf_message_id`` (inclusive), in chronological order.
+
+ Used by the turn runtime to build LLM context for a branched
+ re-run: only ancestors of the new user message are included, so
+ sibling branches at any depth are excluded.
+ """
+ with self._connect() as conn:
+ chain: list[dict[str, Any]] = []
+ current: int | None = int(leaf_message_id)
+ # Bound the walk defensively in case of corrupted parent pointers.
+ safety = 10_000
+ while current is not None and safety > 0:
+ row = conn.execute(
+ """
+ SELECT id, session_id, role, content, capability, events_json,
+ attachments_json, metadata_json, created_at, parent_message_id
+ FROM messages
+ WHERE id = ? AND session_id = ?
+ """,
+ (current, session_id),
+ ).fetchone()
+ if row is None:
+ break
+ chain.append(self._serialize_message(row))
+ parent = row["parent_message_id"]
+ current = int(parent) if parent is not None else None
+ safety -= 1
+ chain.reverse()
+ return chain
+
+ async def get_message_path(
+ self, session_id: str, leaf_message_id: int
+ ) -> list[dict[str, Any]]:
+ return await self._run(self._get_message_path_sync, session_id, int(leaf_message_id))
+
async def get_messages(self, session_id: str) -> list[dict[str, Any]]:
return await self._run(self._get_messages_sync, session_id)
- def _get_messages_for_context_sync(self, session_id: str) -> list[dict[str, Any]]:
+ def _get_messages_for_context_sync(
+ self, session_id: str, leaf_message_id: int | None = None
+ ) -> list[dict[str, Any]]:
with self._connect() as conn:
- rows = conn.execute(
- """
- SELECT id, role, content
- FROM messages
- WHERE session_id = ?
- AND role IN ('user', 'assistant', 'system')
- ORDER BY id ASC
- """,
- (session_id,),
- ).fetchall()
- return [
- {"id": row["id"], "role": row["role"], "content": row["content"] or ""} for row in rows
- ]
-
- async def get_messages_for_context(self, session_id: str) -> list[dict[str, Any]]:
- return await self._run(self._get_messages_for_context_sync, session_id)
+ if leaf_message_id is None:
+ rows = conn.execute(
+ """
+ SELECT id, role, content
+ FROM messages
+ WHERE session_id = ?
+ AND role IN ('user', 'assistant', 'system')
+ ORDER BY id ASC
+ """,
+ (session_id,),
+ ).fetchall()
+ return [
+ {
+ "id": row["id"],
+ "role": row["role"],
+ "content": row["content"] or "",
+ }
+ for row in rows
+ ]
+ # Branch-aware path walk: include only ancestors (+ leaf) so
+ # sibling branches at any depth are excluded from LLM context.
+ chain: list[dict[str, Any]] = []
+ current: int | None = int(leaf_message_id)
+ safety = 10_000
+ while current is not None and safety > 0:
+ row = conn.execute(
+ """
+ SELECT id, role, content, parent_message_id
+ FROM messages
+ WHERE id = ? AND session_id = ?
+ AND role IN ('user', 'assistant', 'system')
+ """,
+ (current, session_id),
+ ).fetchone()
+ if row is None:
+ break
+ chain.append(
+ {
+ "id": row["id"],
+ "role": row["role"],
+ "content": row["content"] or "",
+ }
+ )
+ parent = row["parent_message_id"]
+ current = int(parent) if parent is not None else None
+ safety -= 1
+ chain.reverse()
+ return chain
+
+ async def get_messages_for_context(
+ self, session_id: str, leaf_message_id: int | None = None
+ ) -> list[dict[str, Any]]:
+ return await self._run(
+ self._get_messages_for_context_sync, session_id, leaf_message_id
+ )
def _list_sessions_sync(
self,
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index 6e70e36f4..5ed48ddce 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -155,6 +155,44 @@ def _format_question_bank_entry(entry: dict[str, Any]) -> str:
return "\n".join(lines)
+async def _count_branch_user_turns(
+ store: SessionStoreProtocol,
+ session_id: str,
+ leaf_message_id: int | None,
+) -> int:
+ """Count user messages on the active branch's ancestor chain.
+
+ Used by the chat source inventory to assign ``first_seen_turn`` for
+ *fresh* sources (= current turn = past_user_turns + 1). When
+ ``leaf_message_id`` is ``None`` (legacy linear append) all messages
+ in the session are counted; otherwise we walk the
+ ``parent_message_id`` chain so sibling branches don't inflate the
+ count. Kept tiny and protocol-only (``get_messages``) so it stays
+ compatible with every store backend.
+ """
+ all_msgs = await store.get_messages(session_id)
+ if leaf_message_id is None:
+ return sum(1 for m in all_msgs if m.get("role") == "user")
+ by_id: dict[int, dict[str, Any]] = {}
+ for m in all_msgs:
+ mid = m.get("id")
+ if mid is not None:
+ by_id[int(mid)] = m
+ count = 0
+ current: int | None = int(leaf_message_id)
+ safety = 10_000
+ while current is not None and safety > 0:
+ m = by_id.get(int(current))
+ if m is None:
+ break
+ if m.get("role") == "user":
+ count += 1
+ parent = m.get("parent_message_id")
+ current = int(parent) if parent is not None else None
+ safety -= 1
+ return count
+
+
async def _build_question_bank_context(
store: SessionStoreProtocol,
entry_ids: list[Any],
@@ -348,6 +386,9 @@ class _TurnExecution:
payload: dict[str, Any]
task: asyncio.Task[None] | None = None
subscribers: list[_LiveSubscriber] = field(default_factory=list)
+ events: list[dict[str, Any]] = field(default_factory=list)
+ next_seq: int = 1
+ events_flushed: bool = False
class TurnRuntimeManager:
@@ -475,7 +516,7 @@ class TurnRuntimeManager:
session_metadata["superseded_turn_id"] = str(superseded_turn_id)
if runtime_only_config.get("_regenerate"):
session_metadata["regenerate"] = True
- await self._persist_and_publish(
+ await self._publish_live_event(
execution,
StreamEvent(
type=StreamEventType.SESSION,
@@ -624,21 +665,33 @@ class TurnRuntimeManager:
queue: asyncio.Queue[dict[str, Any] | None] = asyncio.Queue()
subscriber = _LiveSubscriber(queue=queue)
execution: _TurnExecution | None = None
+ live_backlog: list[dict[str, Any]] = []
async with self._lock:
execution = self._executions.get(turn_id)
if execution is not None:
execution.subscribers.append(subscriber)
+ live_backlog = [
+ item
+ for item in execution.events
+ if int(item.get("seq") or 0) > last_seq
+ ]
+
+ for item in live_backlog:
+ seq = int(item.get("seq") or 0)
+ if seq <= last_seq:
+ continue
+ last_seq = seq
+ yield item
- catchup = await self.store.get_turn_events(turn_id, after_seq=last_seq)
+ catchup = []
+ if execution is None:
+ catchup = await self.store.get_turn_events(turn_id, after_seq=last_seq)
for item in catchup:
seq = int(item.get("seq") or 0)
if seq <= last_seq:
continue
last_seq = seq
- if execution is None:
- yield item
- else:
- queue.put_nowait(item)
+ yield item
turn = await self.store.get_turn(turn_id)
if execution is None:
@@ -682,6 +735,7 @@ class TurnRuntimeManager:
attachment_records = []
assistant_events: list[dict[str, Any]] = []
assistant_content = ""
+ stream_done_sent = False
llm_scope_token: Token[LLMConfig | None] | None = None
reset_active_llm_selection: Callable[[Token[LLMConfig | None] | None], None] | None = None
@@ -708,6 +762,25 @@ class TurnRuntimeManager:
request_config.pop("_regenerated_from_message_id", None)
request_config.pop("_superseded_turn_id", None)
raw_user_content = str(payload.get("content", "") or "")
+ # Edit-branching tip: when the FE includes ``parent_message_id``
+ # (even as ``null``), the new user message attaches at that
+ # exact parent — creating a sibling of any existing children
+ # and forcing LLM context to come from that parent's ancestor
+ # chain only. When the key is absent (legacy callers), the
+ # store auto-appends to the latest message in the session.
+ branch_parent_explicit = "parent_message_id" in payload
+ branch_parent_raw = payload.get("parent_message_id")
+ branch_parent_id: int | None
+ if branch_parent_explicit:
+ try:
+ branch_parent_id = (
+ int(branch_parent_raw) if branch_parent_raw is not None else None
+ )
+ except (TypeError, ValueError):
+ branch_parent_id = None
+ branch_parent_explicit = False
+ else:
+ branch_parent_id = None
notebook_references = payload.get("notebook_references", []) or []
history_references = payload.get("history_references", []) or []
question_notebook_references = payload.get("question_notebook_references", []) or []
@@ -799,7 +872,9 @@ class TurnRuntimeManager:
]
if followup_question_context:
- existing_messages = await self.store.get_messages_for_context(session_id)
+ existing_messages = await self.store.get_messages_for_context(
+ session_id, leaf_message_id=branch_parent_id
+ )
if not existing_messages:
await self.store.add_message(
session_id=session_id,
@@ -815,13 +890,16 @@ class TurnRuntimeManager:
builder = ContextBuilder(self.store)
async def _emit_context_event(event: StreamEvent) -> None:
- await self._persist_and_publish(execution, event)
+ if event.source in {"context", "context_builder"}:
+ return
+ await self._publish_live_event(execution, event)
history_result = await builder.build(
session_id=session_id,
llm_config=llm_config,
language=payload.get("language", "en"),
on_event=_emit_context_event,
+ leaf_message_id=branch_parent_id,
)
memory_service = get_memory_service()
memory_context = memory_service.build_memory_context(memory_references)
@@ -878,123 +956,175 @@ class TurnRuntimeManager:
user_block = user_skill_service.load_for_context(user_picks)
skills_context = "\n\n".join(part for part in (admin_block, user_block) if part)
- if notebook_references:
- referenced_records = get_notebook_manager().get_records_by_references(
- notebook_references
+ # Chat capability uses the lightweight manifest + read_source
+ # affordance (no upstream LLM call, no wholesale-dump into the
+ # user message). All other capabilities keep the legacy concat
+ # path because their internal pipelines consume the named blocks
+ # (``[Notebook Context]`` etc.) directly.
+ is_chat_capability = (capability_name or "") in {"", "chat"}
+
+ source_manifest_text = ""
+ source_index: dict[str, str] = {}
+
+ if is_chat_capability:
+ from deeptutor.services.session.source_inventory import (
+ build_inventory,
+ render_manifest,
)
- if referenced_records:
- analysis_agent = NotebookAnalysisAgent(
- language=str(payload.get("language", "en") or "en")
- )
- notebook_context = await analysis_agent.analyze(
- user_question=raw_user_content,
- records=referenced_records,
- emit=_emit_context_event,
+
+ resolved_notebook_records = (
+ get_notebook_manager().get_records_by_references(notebook_references)
+ if notebook_references
+ else []
+ )
+ # Current turn ordinal = (#user messages on this branch's
+ # ancestor chain) + 1. ``_count_branch_user_turns`` walks
+ # the same lineage the inventory builder uses, so we agree
+ # on what "turn N" means for the historical labels.
+ current_turn_ordinal = await _count_branch_user_turns(
+ self.store, session_id, branch_parent_id
+ ) + 1
+ inventory = await build_inventory(
+ self.store,
+ session_id=session_id,
+ leaf_message_id=branch_parent_id,
+ current_turn_ordinal=current_turn_ordinal,
+ fresh_attachment_records=attachment_records,
+ fresh_notebook_records=resolved_notebook_records,
+ fresh_book_context_text=book_context,
+ fresh_book_references=book_references,
+ fresh_history_session_ids=history_references,
+ fresh_question_entry_ids=question_notebook_references,
+ )
+ source_manifest_text, source_index = render_manifest(inventory)
+ effective_user_message = raw_user_content
+ else:
+ if notebook_references:
+ referenced_records = get_notebook_manager().get_records_by_references(
+ notebook_references
)
+ if referenced_records:
+ analysis_agent = NotebookAnalysisAgent(
+ language=str(payload.get("language", "en") or "en")
+ )
+ notebook_context = await analysis_agent.analyze(
+ user_question=raw_user_content,
+ records=referenced_records,
+ emit=_emit_context_event,
+ )
- if history_references:
- history_records: list[dict[str, Any]] = []
- for session_ref in history_references:
- history_session_id = str(session_ref or "").strip()
- if not history_session_id:
- continue
-
- history_session = await self.store.get_session(history_session_id)
- if not history_session:
- continue
-
- history_messages = await self.store.get_messages_for_context(history_session_id)
- transcript_lines = [
- f"## {str(message.get('role', '')).title()}\n{message.get('content', '')}"
- for message in history_messages
- if str(message.get("content", "") or "").strip()
- ]
- if not transcript_lines:
- continue
-
- history_summary = str(
- history_session.get("compressed_summary", "") or ""
- ).strip()
- if not history_summary:
- history_summary = _clip_text(
- " ".join(
- str(message.get("content", "") or "").strip()
- for message in history_messages[-4:]
- if str(message.get("content", "") or "").strip()
- ),
- limit=400,
+ if history_references:
+ history_records: list[dict[str, Any]] = []
+ for session_ref in history_references:
+ history_session_id = str(session_ref or "").strip()
+ if not history_session_id:
+ continue
+
+ history_session = await self.store.get_session(history_session_id)
+ if not history_session:
+ continue
+
+ history_messages = await self.store.get_messages_for_context(history_session_id)
+ transcript_lines = [
+ f"## {str(message.get('role', '')).title()}\n{message.get('content', '')}"
+ for message in history_messages
+ if str(message.get("content", "") or "").strip()
+ ]
+ if not transcript_lines:
+ continue
+
+ history_summary = str(
+ history_session.get("compressed_summary", "") or ""
+ ).strip()
+ if not history_summary:
+ history_summary = _clip_text(
+ " ".join(
+ str(message.get("content", "") or "").strip()
+ for message in history_messages[-4:]
+ if str(message.get("content", "") or "").strip()
+ ),
+ limit=400,
+ )
+ if not history_summary:
+ history_summary = f"{len(history_messages)} messages"
+
+ history_records.append(
+ {
+ "id": history_session_id,
+ "notebook_id": "__history__",
+ "notebook_name": "History",
+ "title": str(history_session.get("title", "") or "Untitled session"),
+ "summary": history_summary,
+ "output": "\n\n".join(transcript_lines),
+ "metadata": {
+ "session_id": history_session_id,
+ "source": "history",
+ },
+ }
)
- if not history_summary:
- history_summary = f"{len(history_messages)} messages"
-
- history_records.append(
- {
- "id": history_session_id,
- "notebook_id": "__history__",
- "notebook_name": "History",
- "title": str(history_session.get("title", "") or "Untitled session"),
- "summary": history_summary,
- "output": "\n\n".join(transcript_lines),
- "metadata": {
- "session_id": history_session_id,
- "source": "history",
- },
- }
- )
- if history_records:
- analysis_agent = NotebookAnalysisAgent(
- language=str(payload.get("language", "en") or "en")
- )
- history_context = await analysis_agent.analyze(
- user_question=raw_user_content,
- records=history_records,
- emit=_emit_context_event,
+ if history_records:
+ analysis_agent = NotebookAnalysisAgent(
+ language=str(payload.get("language", "en") or "en")
+ )
+ history_context = await analysis_agent.analyze(
+ user_question=raw_user_content,
+ records=history_records,
+ emit=_emit_context_event,
+ )
+ if not history_context.strip():
+ MAX_FALLBACK_CHARS = 8000
+ parts: list[str] = []
+ total = 0
+ for record in history_records:
+ output = record.get("output")
+ if not output:
+ continue
+ part = f"## Session: {record.get('title', 'Untitled')}\n{output}"
+ if total + len(part) > MAX_FALLBACK_CHARS:
+ remaining = MAX_FALLBACK_CHARS - total
+ if remaining > 100:
+ parts.append(part[:remaining] + "\n...(truncated)")
+ break
+ parts.append(part)
+ total += len(part)
+ history_context = "\n\n".join(parts)
+
+ if question_notebook_references:
+ question_bank_context = await _build_question_bank_context(
+ self.store, question_notebook_references
)
- if not history_context.strip():
- MAX_FALLBACK_CHARS = 8000
- parts: list[str] = []
- total = 0
- for record in history_records:
- output = record.get("output")
- if not output:
- continue
- part = f"## Session: {record.get('title', 'Untitled')}\n{output}"
- if total + len(part) > MAX_FALLBACK_CHARS:
- remaining = MAX_FALLBACK_CHARS - total
- if remaining > 100:
- parts.append(part[:remaining] + "\n...(truncated)")
- break
- parts.append(part)
- total += len(part)
- history_context = "\n\n".join(parts)
-
- if question_notebook_references:
- question_bank_context = await _build_question_bank_context(
- self.store, question_notebook_references
- )
- effective_user_message = raw_user_content
- context_parts: list[str] = []
- if document_texts:
- context_parts.append("[Attached Documents]\n" + "\n\n".join(document_texts))
- if book_context:
- context_parts.append(f"[Book Context]\n{book_context}")
- if notebook_context:
- context_parts.append(f"[Notebook Context]\n{notebook_context}")
- if history_context:
- context_parts.append(f"[History Context]\n{history_context}")
- if question_bank_context:
- context_parts.append(f"[Question Bank Context]\n{question_bank_context}")
- if context_parts:
- context_parts.append(f"[User Question]\n{raw_user_content}")
- effective_user_message = "\n\n".join(context_parts)
+ effective_user_message = raw_user_content
+ context_parts: list[str] = []
+ if document_texts:
+ context_parts.append("[Attached Documents]\n" + "\n\n".join(document_texts))
+ if book_context:
+ context_parts.append(f"[Book Context]\n{book_context}")
+ if notebook_context:
+ context_parts.append(f"[Notebook Context]\n{notebook_context}")
+ if history_context:
+ context_parts.append(f"[History Context]\n{history_context}")
+ if question_bank_context:
+ context_parts.append(f"[Question Bank Context]\n{question_bank_context}")
+ if context_parts:
+ context_parts.append(f"[User Question]\n{raw_user_content}")
+ effective_user_message = "\n\n".join(context_parts)
conversation_history = list(history_result.conversation_history)
conversation_context_text = history_result.context_text
+ new_user_message_id: int | None = None
if persist_user_message:
- await self.store.add_message(
+ # Pass parent explicitly only when the FE pinned it (covers
+ # both branched edits with a positive id and root edits
+ # with explicit null). Otherwise let the store auto-append.
+ parent_kwargs: dict[str, Any] = (
+ {"parent_message_id": branch_parent_id}
+ if branch_parent_explicit
+ else {}
+ )
+ new_user_message_id = await self.store.add_message(
session_id=session_id,
role="user",
content=raw_user_content,
@@ -1014,6 +1144,7 @@ class TurnRuntimeManager:
memory_references=memory_references,
llm_selection=payload.get("llm_selection"),
),
+ **parent_kwargs,
)
context = UnifiedContext(
@@ -1026,10 +1157,9 @@ class TurnRuntimeManager:
attachments=attachments,
config_overrides=request_config,
language=payload.get("language", "en"),
- notebook_context=notebook_context,
- history_context=history_context,
memory_context=memory_context,
skills_context=skills_context,
+ source_manifest=source_manifest_text,
metadata={
"conversation_summary": history_result.conversation_summary,
"conversation_context_text": conversation_context_text,
@@ -1050,6 +1180,11 @@ class TurnRuntimeManager:
"llm_selection": payload.get("llm_selection") or {},
"llm_model": str(getattr(llm_config, "model", "") or ""),
"llm_provider": str(getattr(llm_config, "provider_name", "") or ""),
+ # Per-turn full-text payload for read_source. Empty when
+ # the manifest is empty (non-chat capabilities, or chat
+ # turns with no attached sources). Consumed by the chat
+ # pipeline's tool kwargs injector.
+ "source_index": source_index,
},
)
@@ -1057,19 +1192,46 @@ class TurnRuntimeManager:
async for event in orch.handle(context):
if event.type == StreamEventType.SESSION:
continue
- payload_event = await self._persist_and_publish(execution, event)
+ payload_event = await self._publish_live_event(execution, event)
+ if event.type == StreamEventType.DONE:
+ stream_done_sent = True
if payload_event.get("type") not in {"done", "session"}:
assistant_events.append(payload_event)
if _should_capture_assistant_content(event):
assistant_content += event.content
- await self.store.add_message(
- session_id=session_id,
- role="assistant",
- content=assistant_content,
- capability=capability_name,
- events=assistant_events,
- )
+ # Assistant continues the same branch as the user message it
+ # answers. If we just persisted a new user row we chain off
+ # that; if we did not (regenerate path) and the caller pinned a
+ # parent, we use it; otherwise we let the store auto-append
+ # (legacy behavior).
+ if new_user_message_id is not None:
+ await self.store.add_message(
+ session_id=session_id,
+ role="assistant",
+ content=assistant_content,
+ capability=capability_name,
+ events=assistant_events,
+ parent_message_id=new_user_message_id,
+ )
+ elif branch_parent_explicit:
+ await self.store.add_message(
+ session_id=session_id,
+ role="assistant",
+ content=assistant_content,
+ capability=capability_name,
+ events=assistant_events,
+ parent_message_id=branch_parent_id,
+ )
+ else:
+ await self.store.add_message(
+ session_id=session_id,
+ role="assistant",
+ content=assistant_content,
+ capability=capability_name,
+ events=assistant_events,
+ )
+ await self._flush_buffered_events(execution)
await self.store.update_turn_status(turn_id, "completed")
if not is_regenerate:
try:
@@ -1083,45 +1245,59 @@ class TurnRuntimeManager:
except Exception:
logger.debug("Failed to refresh lightweight memory", exc_info=True)
except asyncio.CancelledError:
+ if not stream_done_sent:
+ await self._publish_live_event(
+ execution,
+ StreamEvent(
+ type=StreamEventType.ERROR,
+ source=capability_name,
+ content="Turn cancelled",
+ metadata={"turn_terminal": True, "status": "cancelled"},
+ ),
+ )
+ await self._publish_live_event(
+ execution,
+ StreamEvent(
+ type=StreamEventType.DONE,
+ source=capability_name,
+ metadata={"status": "cancelled"},
+ ),
+ )
+ await self._flush_buffered_events(execution)
await self.store.update_turn_status(turn_id, "cancelled", "Turn cancelled")
- await self._persist_and_publish(
- execution,
- StreamEvent(
- type=StreamEventType.ERROR,
- source=capability_name,
- content="Turn cancelled",
- metadata={"turn_terminal": True, "status": "cancelled"},
- ),
- )
- await self._persist_and_publish(
- execution,
- StreamEvent(
- type=StreamEventType.DONE,
- source=capability_name,
- metadata={"status": "cancelled"},
- ),
- )
raise
except Exception as exc:
- logger.error("Turn %s failed: %s", turn_id, exc, exc_info=True)
- await self.store.update_turn_status(turn_id, "failed", str(exc))
- await self._persist_and_publish(
- execution,
- StreamEvent(
- type=StreamEventType.ERROR,
- source=capability_name,
- content=str(exc),
- metadata={"turn_terminal": True, "status": "failed"},
- ),
- )
- await self._persist_and_publish(
- execution,
- StreamEvent(
- type=StreamEventType.DONE,
- source=capability_name,
- metadata={"status": "failed"},
- ),
- )
+ if stream_done_sent:
+ logger.error(
+ "Post-stream persistence for turn %s failed: %s",
+ turn_id,
+ exc,
+ exc_info=True,
+ )
+ with contextlib.suppress(Exception):
+ await self._flush_buffered_events(execution)
+ await self.store.update_turn_status(turn_id, "failed", str(exc))
+ else:
+ logger.error("Turn %s failed: %s", turn_id, exc, exc_info=True)
+ await self._publish_live_event(
+ execution,
+ StreamEvent(
+ type=StreamEventType.ERROR,
+ source=capability_name,
+ content=str(exc),
+ metadata={"turn_terminal": True, "status": "failed"},
+ ),
+ )
+ await self._publish_live_event(
+ execution,
+ StreamEvent(
+ type=StreamEventType.DONE,
+ source=capability_name,
+ metadata={"status": "failed"},
+ ),
+ )
+ await self._flush_buffered_events(execution)
+ await self.store.update_turn_status(turn_id, "failed", str(exc))
finally:
if llm_scope_token is not None and reset_active_llm_selection is not None:
reset_active_llm_selection(llm_scope_token)
@@ -1133,7 +1309,7 @@ class TurnRuntimeManager:
subscriber.queue.put_nowait(None)
self._executions.pop(turn_id, None)
- async def _persist_and_publish(
+ async def _publish_live_event(
self,
execution: _TurnExecution,
event: StreamEvent,
@@ -1143,26 +1319,50 @@ class TurnRuntimeManager:
event.session_id = execution.session_id
event.turn_id = execution.turn_id
payload = event.to_dict()
- try:
- persisted = await self.store.append_turn_event(execution.turn_id, payload)
- except ValueError as exc:
- # A turn can disappear when the session is deleted while the turn task
- # is still draining events. Avoid cascading failures in the error path.
- if "Turn not found:" not in str(exc):
- raise
- logger.warning(
- "Skip persisting event for missing turn %s (%s)",
- execution.turn_id,
- event.type.value,
- )
- persisted = payload
- self._mirror_event_to_workspace(execution, persisted)
async with self._lock:
- subscribers = list(self._executions.get(execution.turn_id, execution).subscribers)
+ current = self._executions.get(execution.turn_id, execution)
+ seq = int(payload.get("seq") or 0)
+ if seq <= 0:
+ seq = current.next_seq
+ current.next_seq += 1
+ if current is not execution:
+ execution.next_seq = max(execution.next_seq, current.next_seq)
+ else:
+ current.next_seq = max(current.next_seq, seq + 1)
+ execution.next_seq = max(execution.next_seq, seq + 1)
+ payload["seq"] = seq
+ current.events.append(payload)
+ if current is not execution:
+ execution.events.append(payload)
+ subscribers = list(current.subscribers)
for subscriber in subscribers:
with contextlib.suppress(asyncio.QueueFull):
- subscriber.queue.put_nowait(persisted)
- return persisted
+ subscriber.queue.put_nowait(payload)
+ return payload
+
+ async def _flush_buffered_events(self, execution: _TurnExecution) -> None:
+ """Persist buffered turn events after the live stream has already drained."""
+ async with self._lock:
+ if execution.events_flushed:
+ return
+ execution.events_flushed = True
+ events = list(execution.events)
+
+ for payload in events:
+ try:
+ persisted = await self.store.append_turn_event(execution.turn_id, payload)
+ except ValueError as exc:
+ # A turn can disappear when the session is deleted while the turn task
+ # is draining post-stream persistence. Avoid cascading failures.
+ if "Turn not found:" not in str(exc):
+ raise
+ logger.warning(
+ "Skip persisting event for missing turn %s (%s)",
+ execution.turn_id,
+ payload.get("type", ""),
+ )
+ continue
+ self._mirror_event_to_workspace(execution, persisted)
@staticmethod
def _mirror_event_to_workspace(execution: _TurnExecution, payload: dict[str, Any]) -> None:
diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.py
index 9416db3a5..33656a176 100644
--- a/deeptutor/tools/builtin/__init__.py
+++ b/deeptutor/tools/builtin/__init__.py
@@ -502,6 +502,72 @@ class GeoGebraAnalysisTool(_PromptHintsMixin, BaseTool):
)
+class ReadSourceTool(_PromptHintsMixin, BaseTool):
+ """Load the full text of an attached Space source by its manifest id.
+
+ The chat pipeline auto-enables this tool whenever a turn has any non-image
+ attached source (notebook record, book reference, history session,
+ question-bank entry, or document attachment). The per-turn full-text
+ payload is carried in ``context.metadata["source_index"]`` as
+ ``{source_id: str}`` and injected into the tool call by
+ ``_augment_tool_kwargs``. The tool itself stays stateless.
+ """
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="read_source",
+ description=(
+ "Load the full text of one attached source by id. Use ONLY when "
+ "the preview shown in the Attached Sources manifest is "
+ "insufficient to answer the user's question. The id must be "
+ "copied verbatim from the manifest — do not invent ids. Do not "
+ "call this on every source 'just in case'."
+ ),
+ parameters=[
+ ToolParameter(
+ name="source_id",
+ type="string",
+ description=(
+ "The source identifier from the Attached Sources "
+ "manifest. Begins with one of: nb- (notebook record), "
+ "bk- (book reference), hs- (history session), qb- "
+ "(question-bank entry), at- (document attachment)."
+ ),
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ source_id = str(kwargs.get("source_id") or "").strip()
+ if not source_id:
+ return ToolResult(
+ content="Error: source_id is required.",
+ success=False,
+ )
+ source_index = kwargs.get("source_index")
+ if not isinstance(source_index, dict) or not source_index:
+ return ToolResult(
+ content=(
+ "Error: no attached sources are available for this turn."
+ ),
+ success=False,
+ )
+ full_text = source_index.get(source_id)
+ if not full_text:
+ available = ", ".join(sorted(source_index.keys()))
+ return ToolResult(
+ content=(
+ f"Error: unknown source_id {source_id!r}. "
+ f"Valid ids for this turn: {available or '(none)'}."
+ ),
+ success=False,
+ )
+ return ToolResult(
+ content=str(full_text),
+ metadata={"source_id": source_id, "char_count": len(str(full_text))},
+ )
+
+
BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (
BrainstormTool,
RAGTool,
@@ -510,6 +576,7 @@ BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (
ReasonTool,
PaperSearchToolWrapper,
GeoGebraAnalysisTool,
+ ReadSourceTool,
)
BUILTIN_TOOL_NAMES: tuple[str, ...] = tuple(tool_type().name for tool_type in BUILTIN_TOOL_TYPES)
@@ -531,6 +598,7 @@ __all__ = [
"GeoGebraAnalysisTool",
"PaperSearchToolWrapper",
"RAGTool",
+ "ReadSourceTool",
"ReasonTool",
"WebSearchTool",
]
diff --git a/deeptutor/tools/prompting/__init__.py b/deeptutor/tools/prompting/__init__.py
index 1e4ae7247..8d2b85a29 100644
--- a/deeptutor/tools/prompting/__init__.py
+++ b/deeptutor/tools/prompting/__init__.py
@@ -98,6 +98,28 @@ class ToolPromptComposer:
lines.append(f"- {name}: {hint.short_description}")
return "\n".join(lines)
+ def format_list_with_usage(self, hints: list[ToolHintEntry]) -> str:
+ """Per-tool bullet that includes ``when_to_use`` and ``input_format``.
+
+ Used by the chat persona prompt so the LLM has enough per-tool
+ guidance to decide *whether* to call it, not just *what it is*.
+ Tools without a ``short_description`` are skipped entirely so the
+ block never carries empty bullets.
+ """
+ when_label = "When to use" if self.language != "zh" else "适用场景"
+ input_label = "Input" if self.language != "zh" else "参数格式"
+ blocks: list[str] = []
+ for name, hint in hints:
+ if not hint.short_description:
+ continue
+ entry: list[str] = [f"- `{name}` — {hint.short_description}"]
+ if hint.when_to_use:
+ entry.append(f" {when_label}: {hint.when_to_use}")
+ if hint.input_format:
+ entry.append(f" {input_label}: {hint.input_format}")
+ blocks.append("\n".join(entry))
+ return "\n".join(blocks)
+
def format_table(
self,
hints: list[ToolHintEntry],
diff --git a/deeptutor/tools/prompting/hints/en/read_source.yaml b/deeptutor/tools/prompting/hints/en/read_source.yaml
new file mode 100644
index 000000000..0b84b5692
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/en/read_source.yaml
@@ -0,0 +1,6 @@
+short_description: "Load the full text of an attached source (notebook record, book pages, history session, question-bank entry, document attachment) by its manifest id."
+when_to_use: "Call ONLY when the preview shown in the \"Attached Sources\" manifest is not enough to answer the user's question. Do not re-fetch sources whose preview already covers the question."
+input_format: "{\"source_id\": \"the exact id from the manifest (e.g. nb-... / bk-... / hs-... / qb-... / at-...)\"}."
+guideline: "Copy source_id verbatim from the manifest — never invent or guess one. Load one source per call; issue separate calls if multiple sources are needed."
+note: "When no source is attached, this tool will not appear; do not ask the user to clarify \"which material\"."
+phase: "exploration"
diff --git a/deeptutor/tools/prompting/hints/zh/read_source.yaml b/deeptutor/tools/prompting/hints/zh/read_source.yaml
new file mode 100644
index 000000000..dd6ed79eb
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/zh/read_source.yaml
@@ -0,0 +1,6 @@
+short_description: "按 id 加载已挂载来源(笔记、书页、历史会话、题库条目、附件)的完整文本。"
+when_to_use: "仅当上方 \"Attached Sources\" 清单中某条目的 preview 不足以回答用户问题时才调用;preview 已经包含的内容不要重复调。"
+input_format: "{\"source_id\": \"清单中给出的精确 id(如 nb-... / bk-... / hs-... / qb-... / at-...)\"}。"
+guideline: "source_id 必须照搬清单原文,绝不拼造。一次只能取一个来源,多个来源相关时按需多次调用。"
+note: "如果用户根本没挂任何来源,本工具不会出现;不要凭空询问\"哪份资料\"。"
+phase: "exploration"
diff --git a/deeptutor/tutorbot/providers/openai_compat_provider.py b/deeptutor/tutorbot/providers/openai_compat_provider.py
index 57cb6f37e..851396c5e 100644
--- a/deeptutor/tutorbot/providers/openai_compat_provider.py
+++ b/deeptutor/tutorbot/providers/openai_compat_provider.py
@@ -40,6 +40,9 @@ _DEFAULT_OPENROUTER_HEADERS = {
"HTTP-Referer": "https://github.com/HKUDS/DeepTutor",
"X-OpenRouter-Title": "DeepTutor",
}
+_THINKING_DISABLED_BY_DEFAULT: tuple[tuple[str, str], ...] = (
+ ("deepseek", "deepseek-v4-flash"),
+)
def _short_tool_id() -> str:
@@ -47,6 +50,16 @@ def _short_tool_id() -> str:
return "".join(secrets.choice(_ALNUM) for _ in range(9))
+def _disable_thinking_by_default(spec: ProviderSpec | None, model_name: str) -> bool:
+ if not spec:
+ return False
+ normalized = (model_name or "").strip().lower()
+ return any(
+ spec.name == provider and pattern in normalized
+ for provider, pattern in _THINKING_DISABLED_BY_DEFAULT
+ )
+
+
def _get(obj: Any, key: str) -> Any:
if isinstance(obj, dict):
return obj.get(key)
@@ -276,6 +289,11 @@ class OpenAICompatProvider(LLMProvider):
extra = {"reasoning_split": thinking_enabled}
if extra:
kwargs.setdefault("extra_body", {}).update(extra)
+ elif spec and _disable_thinking_by_default(spec, model_name):
+ if spec.name == "deepseek":
+ kwargs.setdefault("extra_body", {}).update(
+ {"thinking": {"type": "disabled"}}
+ )
# Providers that handle thinking via extra_body don't need a
# top-level reasoning_effort when the intent is to disable thinking.
diff --git a/deeptutor_cli/kb.py b/deeptutor_cli/kb.py
index c431e76c5..bf90fc001 100644
--- a/deeptutor_cli/kb.py
+++ b/deeptutor_cli/kb.py
@@ -175,7 +175,6 @@ def register(app: typer.Typer) -> None:
kb_name=name,
source_files=doc_paths,
base_dir=str(mgr.base_dir),
- skip_extract=True,
)
)
except Exception as exc:
diff --git a/packaging/deeptutor-cli/pyproject.toml b/packaging/deeptutor-cli/pyproject.toml
index 9a56476ac..25ca5a5db 100644
--- a/packaging/deeptutor-cli/pyproject.toml
+++ b/packaging/deeptutor-cli/pyproject.toml
@@ -31,6 +31,7 @@ dependencies = [
"perplexityai>=0.1.0",
"oauth-cli-kit>=0.1.1",
"llama-index>=0.14.12",
+ "llama-index-retrievers-bm25>=0.7.1,<0.8.0",
"PyMuPDF>=1.26.0",
"numpy>=1.24.0,<3.0.0",
"arxiv>=2.0.0",
diff --git a/pyproject.toml b/pyproject.toml
index e369b4ab2..afb79fda8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -36,6 +36,7 @@ dependencies = [
"perplexityai>=0.1.0",
"oauth-cli-kit>=0.1.1",
"llama-index>=0.14.12",
+ "llama-index-retrievers-bm25>=0.7.1,<0.8.0",
"PyMuPDF>=1.26.0",
"numpy>=1.24.0,<3.0.0",
"arxiv>=2.0.0",
@@ -70,6 +71,7 @@ cli = [
"oauth-cli-kit>=0.1.1",
# RAG (LlamaIndex)
"llama-index>=0.14.12",
+ "llama-index-retrievers-bm25>=0.7.1,<0.8.0",
"PyMuPDF>=1.26.0",
"numpy>=1.24.0,<3.0.0",
"arxiv>=2.0.0",
@@ -144,6 +146,13 @@ dev = [
"pre-commit>=3.0.0",
"safety<3.0.0",
"bandit>=1.8.0",
+ # Test fixture builders for document-loader tests. Runtime pulls these via
+ # cli/server, but dev keeps them explicit for pytest collection.
+ "python-docx>=1.1.0",
+ "openpyxl>=3.1.0",
+ "python-pptx>=1.0.0",
+ "pypdf>=4.0.0",
+ "defusedxml>=0.7.1",
]
# Everything: server + tutorbot + non-E2EE matrix + math-animator + dev tools.
diff --git a/requirements/cli.txt b/requirements/cli.txt
index 6f06c0265..ace25ebd3 100644
--- a/requirements/cli.txt
+++ b/requirements/cli.txt
@@ -38,6 +38,7 @@ aiosqlite>=0.19.0
# --- RAG (LlamaIndex) ---
llama-index>=0.14.12
+llama-index-retrievers-bm25>=0.7.1,<0.8.0
PyMuPDF>=1.26.0
numpy>=1.24.0,<3.0.0
arxiv>=2.0.0
diff --git a/requirements/dev.txt b/requirements/dev.txt
index 099f4eee2..e13baeb31 100644
--- a/requirements/dev.txt
+++ b/requirements/dev.txt
@@ -14,3 +14,12 @@ pytest-asyncio>=0.23.0
pre-commit>=3.0.0
safety<3.0.0
bandit>=1.8.0
+
+# --- Test fixture builders for document-loader tests ---
+# These are also pulled by cli.txt at runtime; keep explicit here so dev/test
+# installs have the imports needed during pytest collection.
+python-docx>=1.1.0
+openpyxl>=3.1.0
+python-pptx>=1.0.0
+pypdf>=4.0.0
+defusedxml>=0.7.1
diff --git a/scripts/migrate_kb.py b/scripts/migrate_kb.py
index af482c70f..514d17c11 100644
--- a/scripts/migrate_kb.py
+++ b/scripts/migrate_kb.py
@@ -10,11 +10,10 @@ Features:
- Validate required index files
- Copy/migrate KB to target directory
- Register in kb_config.json
-- Optionally extract numbered items (if content_list exists)
- Run test query to verify migration
Usage:
- python scripts/migrate_kb.py /path/to/kb --name my_kb --test --extract-items
+ python scripts/migrate_kb.py /path/to/kb --name my_kb --test
python scripts/migrate_kb.py /path/to/kb --validate-only
"""
@@ -176,11 +175,9 @@ def validate_kb(kb_path: Path) -> dict:
"needs_reindex": False,
"missing_files": [],
"found_files": [],
- "has_content_list": False,
"has_raw_docs": False,
"has_images": False,
"has_metadata": False,
- "has_numbered_items": False,
}
if not kb_path.exists():
@@ -216,9 +213,6 @@ def validate_kb(kb_path: Path) -> dict:
result["found_files"] = found
# Check optional directories
- content_list_dir = kb_path / "content_list"
- result["has_content_list"] = content_list_dir.exists() and any(content_list_dir.glob("*.json"))
-
raw_dir = kb_path / "raw"
result["has_raw_docs"] = raw_dir.exists() and any(raw_dir.iterdir())
@@ -226,8 +220,6 @@ def validate_kb(kb_path: Path) -> dict:
result["has_images"] = images_dir.exists() and any(images_dir.iterdir())
result["has_metadata"] = (kb_path / "metadata.json").exists()
- result["has_numbered_items"] = (kb_path / "numbered_items.json").exists()
-
return result
@@ -349,21 +341,6 @@ def register_kb(
return True
-async def extract_numbered_items(kb_name: str, kb_base_dir: Path) -> bool:
- """
- Extract numbered items from content_list files.
-
- Args:
- kb_name: Knowledge base name
- kb_base_dir: Base directory for knowledge bases
-
- Returns:
- True if successful
- """
- _ = (kb_name, kb_base_dir)
- print(" ⚠️ Numbered item extraction is deprecated and has been removed. Skipping.")
- return False
-
async def test_kb_search(kb_name: str, query: str = "What is this knowledge base about?") -> bool:
"""
@@ -411,7 +388,6 @@ async def migrate_kb(
target_base_dir: str | None = None,
kb_name: str | None = None,
run_test: bool = False,
- extract_items: bool = False,
validate_only: bool = False,
force: bool = False,
) -> bool:
@@ -423,7 +399,6 @@ async def migrate_kb(
target_base_dir: Target base directory (default: data/knowledge_bases)
kb_name: Name for the migrated KB (default: source directory name)
run_test: Run a test query after migration
- extract_items: Extract numbered items if content_list exists
validate_only: Only validate, don't migrate
force: Overwrite existing KB if exists
@@ -465,7 +440,6 @@ async def migrate_kb(
print(f" Provider: {validation['provider']}")
print(f" Needs reindex: {'Yes' if validation['needs_reindex'] else 'No'}")
print(f" Found files: {', '.join(validation['found_files'][:5])}...")
- print(f" Has content_list: {'Yes' if validation['has_content_list'] else 'No'}")
print(f" Has raw docs: {'Yes' if validation['has_raw_docs'] else 'No'}")
print(f" Has images: {'Yes' if validation['has_images'] else 'No'}")
print()
@@ -506,18 +480,9 @@ async def migrate_kb(
)
print()
- # Step 4: Extract numbered items (optional)
- if extract_items and validation["has_content_list"]:
- print("Step 4: Extracting numbered items...")
- await extract_numbered_items(kb_name, target_base)
- print()
- elif extract_items:
- print("Step 4: Skipping numbered items extraction (no content_list)")
- print()
-
- # Step 5: Test search (optional)
+ # Step 4: Test search (optional)
if run_test:
- print("Step 5: Testing knowledge base...")
+ print("Step 4: Testing knowledge base...")
await test_kb_search(kb_name)
print()
@@ -549,8 +514,6 @@ Examples:
# Migrate and run test query
python scripts/migrate_kb.py /path/to/kb --test
- # Migrate and extract numbered items
- python scripts/migrate_kb.py /path/to/kb --extract-items
# Validate only (don't migrate)
python scripts/migrate_kb.py /path/to/kb --validate-only
@@ -572,12 +535,6 @@ Examples:
parser.add_argument("--test", action="store_true", help="Run a test query after migration")
- parser.add_argument(
- "--extract-items",
- action="store_true",
- help="Extract numbered items from content_list (requires LLM API)",
- )
-
parser.add_argument(
"--validate-only",
action="store_true",
@@ -597,7 +554,6 @@ Examples:
target_base_dir=args.target_dir,
kb_name=args.name,
run_test=args.test,
- extract_items=args.extract_items,
validate_only=args.validate_only,
force=args.force,
)
diff --git a/tests/agents/chat/test_agentic_parallel_tools.py b/tests/agents/chat/test_agentic_parallel_tools.py
index 54f28bf27..2021e332f 100644
--- a/tests/agents/chat/test_agentic_parallel_tools.py
+++ b/tests/agents/chat/test_agentic_parallel_tools.py
@@ -25,144 +25,6 @@ async def _collect_bus_events(bus: StreamBus) -> tuple[list[StreamEvent], asynci
await asyncio.sleep(0)
return events, consumer # type: ignore[return-value]
-
-async def test_native_tool_loop_executes_parallel_tool_calls(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- monkeypatch.setattr(
- "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
- lambda: SimpleNamespace(
- binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
- ),
- )
-
- class FakeRegistry:
- def __init__(self) -> None:
- self.inflight = 0
- self.max_inflight = 0
-
- def build_openai_schemas(self, _enabled_tools):
- return [{"type": "function", "function": {"name": "web_search"}}]
-
- def build_prompt_text(self, enabled_tools, **_kwargs):
- return "\n".join(enabled_tools)
-
- def get_enabled(self, selected):
- return [SimpleNamespace(name=name) for name in selected]
-
- async def execute(self, name: str, **kwargs):
- self.inflight += 1
- self.max_inflight = max(self.max_inflight, self.inflight)
- await asyncio.sleep(0.05)
- self.inflight -= 1
- return ToolResult(
- content=f"{name} => {kwargs.get('query', '') or kwargs.get('context', '')}".strip(),
- sources=[{"tool": name}],
- metadata={"tool": name},
- success=True,
- )
-
- registry = FakeRegistry()
- monkeypatch.setattr(
- "deeptutor.agents.chat.agentic_pipeline.get_tool_registry", lambda: registry
- )
-
- pipeline = AgenticChatPipeline(language="en")
- pipeline.registry = registry
-
- class FakeCreate:
- def __init__(self) -> None:
- self.calls = 0
-
- async def __call__(self, **_kwargs):
- self.calls += 1
- if self.calls == 1:
- return SimpleNamespace(
- choices=[
- SimpleNamespace(
- message=SimpleNamespace(
- content="",
- tool_calls=[
- SimpleNamespace(
- id="tool-call-1",
- function=SimpleNamespace(
- name="web_search",
- arguments='{"query":"first"}',
- ),
- ),
- SimpleNamespace(
- id="tool-call-2",
- function=SimpleNamespace(
- name="reason",
- arguments='{"context":"second"}',
- ),
- ),
- ],
- )
- )
- ]
- )
- return SimpleNamespace(
- choices=[
- SimpleNamespace(
- message=SimpleNamespace(
- content="No more tools needed.",
- tool_calls=[],
- )
- )
- ]
- )
-
- fake_create = FakeCreate()
- monkeypatch.setattr(
- pipeline,
- "_build_openai_client",
- lambda: SimpleNamespace(
- chat=SimpleNamespace(
- completions=SimpleNamespace(create=fake_create),
- )
- ),
- )
-
- bus = StreamBus()
- events, consumer = await _collect_bus_events(bus)
- context = UnifiedContext(
- session_id="session-1",
- user_message="compare two sources",
- enabled_tools=["web_search", "reason"],
- language="en",
- metadata={"turn_id": "turn-1"},
- )
-
- traces = await pipeline._run_native_tool_loop(
- context=context,
- enabled_tools=["web_search", "reason"],
- thinking_text="Need outside evidence and a reasoning cross-check.",
- stream=bus,
- )
- await asyncio.sleep(0)
- await bus.close()
- await consumer
-
- assert fake_create.calls == 1
- assert registry.max_inflight >= 2
- assert [trace.name for trace in traces] == ["web_search", "reason"]
-
- tool_result_events = [event for event in events if event.type.value == "tool_result"]
- assert len(tool_result_events) == 2
- assert tool_result_events[0].metadata["tool_call_id"] == "tool-call-1"
- assert tool_result_events[1].metadata["tool_call_id"] == "tool-call-2"
- assert tool_result_events[0].metadata["tool_index"] == 0
- assert tool_result_events[1].metadata["tool_index"] == 1
- acting_thinking_events = [
- event
- for event in events
- if event.type == StreamEventType.THINKING and event.stage == "acting"
- ]
- assert acting_thinking_events == []
-
-
@pytest.mark.asyncio
async def test_execute_tool_call_streams_retrieve_progress_for_rag(
monkeypatch: pytest.MonkeyPatch,
@@ -223,9 +85,7 @@ async def test_execute_tool_call_streams_retrieve_progress_for_rag(
retrieve_meta = pipeline._retrieve_trace_metadata(
trace_meta,
context=context,
- tool_call_id="tool-call-rag",
tool_name="rag",
- tool_index=0,
tool_args={"query": "transformer model", "kb_name": "demo-kb"},
)
@@ -329,222 +189,3 @@ def test_build_llm_tool_schemas_kb_name_enum_matches_attached() -> None:
assert parameters["required"] == ["query", "kb_name"]
assert parameters["additionalProperties"] is False
-
-async def test_native_rag_call_forwards_llm_chosen_kb_name(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- monkeypatch.setattr(
- "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
- lambda: SimpleNamespace(
- binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
- ),
- )
-
- class FakeRegistry:
- def __init__(self) -> None:
- self.calls: list[dict[str, Any]] = []
-
- def build_openai_schemas(self, _enabled_tools):
- return [
- {
- "type": "function",
- "function": {
- "name": "rag",
- "parameters": {
- "type": "object",
- "properties": {
- "query": {"type": "string"},
- "kb_name": {"type": "string"},
- },
- "required": ["query", "kb_name"],
- },
- },
- }
- ]
-
- def build_prompt_text(self, enabled_tools, **_kwargs):
- return "\n".join(enabled_tools)
-
- async def execute(self, name: str, **kwargs):
- self.calls.append({"name": name, **kwargs})
- return ToolResult(
- content="grounded result",
- sources=[{"tool": name, "kb_name": kwargs.get("kb_name")}],
- metadata={"tool": name},
- success=True,
- )
-
- registry = FakeRegistry()
- monkeypatch.setattr(
- "deeptutor.agents.chat.agentic_pipeline.get_tool_registry", lambda: registry
- )
-
- pipeline = AgenticChatPipeline(language="en")
- pipeline.registry = registry
-
- class FakeCreate:
- def __init__(self) -> None:
- self.tools: list[dict[str, Any]] = []
-
- async def __call__(self, **kwargs):
- self.tools = kwargs.get("tools") or []
- return SimpleNamespace(
- choices=[
- SimpleNamespace(
- message=SimpleNamespace(
- content="",
- tool_calls=[
- SimpleNamespace(
- id="tool-call-rag",
- function=SimpleNamespace(
- name="rag",
- arguments='{"query":"chapter summary","kb_name":"current-kb"}',
- ),
- )
- ],
- )
- )
- ]
- )
-
- fake_create = FakeCreate()
- monkeypatch.setattr(
- pipeline,
- "_build_openai_client",
- lambda: SimpleNamespace(
- chat=SimpleNamespace(completions=SimpleNamespace(create=fake_create)),
- ),
- )
-
- bus = StreamBus()
- events, consumer = await _collect_bus_events(bus)
- context = UnifiedContext(
- session_id="session-1",
- user_message="summarize chapter 3",
- enabled_tools=["rag"],
- knowledge_bases=["current-kb"],
- language="en",
- metadata={"turn_id": "turn-1"},
- )
-
- traces = await pipeline._run_native_tool_loop(
- context=context,
- enabled_tools=["rag"],
- thinking_text="RAG would help.",
- stream=bus,
- )
- await asyncio.sleep(0)
- await bus.close()
- await consumer
-
- rag_properties = fake_create.tools[0]["function"]["parameters"]["properties"]
- assert rag_properties["kb_name"]["enum"] == ["current-kb"]
- assert registry.calls[0]["query"] == "chapter summary"
- assert registry.calls[0]["kb_name"] == "current-kb"
- assert traces[0].arguments["kb_name"] == "current-kb"
-
- tool_call_events = [event for event in events if event.type == StreamEventType.TOOL_CALL]
- assert tool_call_events[0].metadata["tool_name"] == "rag"
- assert tool_call_events[0].content
-
-
-async def test_native_tool_loop_caps_parallel_tool_calls_at_eight(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- monkeypatch.setattr(
- "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
- lambda: SimpleNamespace(
- binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
- ),
- )
-
- class FakeRegistry:
- def __init__(self) -> None:
- self.calls: list[str] = []
-
- def build_openai_schemas(self, _enabled_tools):
- return [{"type": "function", "function": {"name": "web_search"}}]
-
- def build_prompt_text(self, enabled_tools, **_kwargs):
- return "\n".join(enabled_tools)
-
- def get_enabled(self, selected):
- return [SimpleNamespace(name=name) for name in selected]
-
- async def execute(self, name: str, **kwargs):
- self.calls.append(f"{name}:{kwargs.get('query', '')}")
- return ToolResult(
- content=f"{name} => {kwargs.get('query', '')}",
- sources=[{"tool": name}],
- metadata={"tool": name},
- success=True,
- )
-
- registry = FakeRegistry()
- monkeypatch.setattr(
- "deeptutor.agents.chat.agentic_pipeline.get_tool_registry", lambda: registry
- )
-
- pipeline = AgenticChatPipeline(language="en")
- pipeline.registry = registry
-
- tool_calls = [
- SimpleNamespace(
- id=f"tool-call-{index}",
- function=SimpleNamespace(
- name="web_search",
- arguments=f'{{"query":"q{index}"}}',
- ),
- )
- for index in range(10)
- ]
-
- async def fake_create(**_kwargs):
- return SimpleNamespace(
- choices=[
- SimpleNamespace(
- message=SimpleNamespace(
- content="Use multiple tools in parallel.",
- tool_calls=tool_calls,
- )
- )
- ]
- )
-
- monkeypatch.setattr(
- pipeline,
- "_build_openai_client",
- lambda: SimpleNamespace(
- chat=SimpleNamespace(
- completions=SimpleNamespace(create=fake_create),
- )
- ),
- )
-
- bus = StreamBus()
- events, consumer = await _collect_bus_events(bus)
- context = UnifiedContext(
- session_id="session-1",
- user_message="collect broad evidence",
- enabled_tools=["web_search"],
- language="en",
- metadata={"turn_id": "turn-1"},
- )
-
- traces = await pipeline._run_native_tool_loop(
- context=context,
- enabled_tools=["web_search"],
- thinking_text="Need multiple web sources.",
- stream=bus,
- )
- await asyncio.sleep(0)
- await bus.close()
- await consumer
-
- assert len(traces) == 8
- assert len(registry.calls) == 8
- assert registry.calls[-1] == "web_search:q7"
- progress_events = [event.content for event in events if event.type == StreamEventType.PROGRESS]
- assert any("8 can run in parallel" in content for content in progress_events)
diff --git a/tests/agents/chat/test_language_prompts.py b/tests/agents/chat/test_language_prompts.py
index 68c2bde5a..253ae93ef 100644
--- a/tests/agents/chat/test_language_prompts.py
+++ b/tests/agents/chat/test_language_prompts.py
@@ -36,13 +36,21 @@ def test_agentic_chat_final_prompt_uses_selected_language(
lambda: FakeRegistry(),
)
- zh_prompt = AgenticChatPipeline(language="zh")._responding_system_prompt([])
- en_prompt = AgenticChatPipeline(language="en")._responding_system_prompt([])
+ from deeptutor.core.context import UnifiedContext
- assert "你是 DeepTutor 的最终回答阶段" in zh_prompt
+ ctx = UnifiedContext()
+ zh_prompt = AgenticChatPipeline(language="zh")._build_system_prompt([], ctx)
+ en_prompt = AgenticChatPipeline(language="en")._build_system_prompt([], ctx)
+
+ # Single-loop pipeline merged the four stage prompts into one chat
+ # persona; the language directive (append_language_directive) still
+ # runs at the end, so per-language imperatives must surface.
assert "请严格使用中文" in zh_prompt
- assert "You are DeepTutor's final response stage" in en_prompt
assert "Write ALL reader-facing text" in en_prompt
+ # Persona phrasing differs by language so the prompts are not just
+ # English text with a Chinese tail appended.
+ assert "你是 DeepTutor" in zh_prompt
+ assert "You are DeepTutor" in en_prompt
def test_legacy_chat_agent_system_prompt_uses_selected_language() -> None:
diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.py
index 7f9b41a9e..48ed0d7ed 100644
--- a/tests/api/test_knowledge_router.py
+++ b/tests/api/test_knowledge_router.py
@@ -102,7 +102,7 @@ def test_rag_providers_returns_llamaindex_only() -> None:
{
"id": "llamaindex",
"name": "LlamaIndex",
- "description": "Pure vector retrieval, fastest processing speed.",
+ "description": "LlamaIndex retrieval with hybrid BM25/vector fusion when available.",
}
]
}
@@ -119,9 +119,12 @@ def test_supported_file_types_returns_upload_policy() -> None:
assert ".xlsx" in payload["extensions"]
assert ".pptx" in payload["extensions"]
assert ".md" in payload["extensions"]
+ assert ".png" in payload["extensions"]
assert payload["max_file_size_bytes"] > payload["max_pdf_size_bytes"] > 0
assert ".pdf" in payload["accept"]
assert ".docx" in payload["accept"]
+ assert ".png" in payload["accept"]
+ assert "image/png" in payload["accept"]
def test_create_kb_does_not_require_llm_precheck(monkeypatch, tmp_path: Path) -> None:
diff --git a/tests/api/test_unified_ws_turn_runtime.py b/tests/api/test_unified_ws_turn_runtime.py
index 2a7762d82..4afb43078 100644
--- a/tests/api/test_unified_ws_turn_runtime.py
+++ b/tests/api/test_unified_ws_turn_runtime.py
@@ -98,6 +98,7 @@ async def test_turn_runtime_replays_events_and_materializes_messages(
async def handle(self, context):
captured["user_message"] = context.user_message
captured["metadata"] = context.metadata
+ captured["source_manifest"] = context.source_manifest
yield StreamEvent(
type=StreamEventType.CONTENT,
source="chat",
@@ -164,8 +165,20 @@ async def test_turn_runtime_replays_events_and_materializes_messages(
assert detail["messages"][0]["metadata"]["request_snapshot"]["bookReferences"] == [
{"book_id": "book-1", "page_ids": ["page-1"]}
]
- assert "[Book Context]" in str(captured["user_message"])
- assert "A selected page." in str(captured["user_message"])
+ # Chat capability now routes attached sources through the manifest +
+ # ``read_source`` tool instead of inlining ``[Book Context]`` into the
+ # user message. The raw user message stays raw; the book payload
+ # surfaces in ``context.source_manifest`` and ``metadata.source_index``.
+ assert str(captured["user_message"]) == "hello, i'm frank"
+ manifest = str(captured.get("source_manifest") or "")
+ assert "[Attached Sources]" in manifest
+ # Book source id is now per-book (``bk-{book_id}``) so multi-book
+ # sessions can read_source each independently. The mocked book has id
+ # "book-1".
+ assert "bk-book-1" in manifest
+ source_index = (captured.get("metadata") or {}).get("source_index") or {}
+ assert "bk-book-1" in source_index
+ assert "A selected page." in source_index["bk-book-1"]
assert captured["metadata"] and captured["metadata"]["book_references"] == [
{"book_id": "book-1", "page_ids": ["page-1"]}
]
diff --git a/tests/core/test_context.py b/tests/core/test_context.py
index 252393634..291e71cf7 100644
--- a/tests/core/test_context.py
+++ b/tests/core/test_context.py
@@ -62,9 +62,8 @@ class TestUnifiedContext:
assert ctx.attachments == []
assert ctx.config_overrides == {}
assert ctx.language == "en"
- assert ctx.notebook_context == ""
- assert ctx.history_context == ""
assert ctx.memory_context == ""
+ assert ctx.source_manifest == ""
assert ctx.metadata == {}
def test_mutable_defaults_are_independent(self) -> None:
@@ -85,9 +84,8 @@ class TestUnifiedContext:
attachments=[att],
config_overrides={"temperature": 0.5},
language="zh",
- notebook_context="some notes",
- history_context="prior session",
memory_context="user preference",
+ source_manifest="id=nb-1 name=\"Lecture\" type=notebook preview=\"...\"",
metadata={"turn_id": "t1"},
)
assert ctx.session_id == "s1"
diff --git a/tests/services/config/test_chat_params_config.py b/tests/services/config/test_chat_params_config.py
index 717d1faea..279359715 100644
--- a/tests/services/config/test_chat_params_config.py
+++ b/tests/services/config/test_chat_params_config.py
@@ -101,41 +101,41 @@ class TestGetChatParams:
assert params["react_fallback"]["max_tokens"] == 2500
-class TestChatLimitsDataclass:
- """Verify _ChatLimits.from_config gracefully handles malformed input."""
+class TestReadIntHelper:
+ """Verify ``_read_int`` gracefully resolves the two chat token budgets
+ the single-loop pipeline still uses (``responding`` and ``answer_now``).
- def test_from_config_with_empty_dict_uses_fallbacks(self):
- from deeptutor.agents.chat.agentic_pipeline import _ChatLimits
+ The legacy four-stage budgets (``thinking``/``acting``/``observing``/
+ ``react_fallback``) are no longer consumed by the pipeline — they remain
+ valid keys in ``agents.yaml`` for forward/backward compatibility but
+ have no behavioral effect here.
+ """
- limits = _ChatLimits.from_config({})
- assert limits.responding == 8000
- assert limits.answer_now == 8000
- assert limits.thinking == 2000
- assert limits.observing == 2000
- assert limits.acting == 2000
- assert limits.react_fallback == 1500
+ def test_empty_dict_falls_back_to_default(self):
+ from deeptutor.agents.chat.agentic_pipeline import _read_int
- def test_from_config_with_chat_params_defaults(self):
- from deeptutor.agents.chat.agentic_pipeline import _ChatLimits
+ assert _read_int({}, key="max_tokens", default=8000) == 8000
- limits = _ChatLimits.from_config(DEFAULT_CHAT_PARAMS)
- assert limits.responding == 8000
- assert limits.react_fallback == 1500
+ def test_resolves_nested_max_tokens(self):
+ from deeptutor.agents.chat.agentic_pipeline import _read_int
- def test_from_config_coerces_string_numbers(self):
- from deeptutor.agents.chat.agentic_pipeline import _ChatLimits
+ cfg = {"max_tokens": 5000}
+ assert _read_int(cfg, key="max_tokens", default=8000) == 5000
- limits = _ChatLimits.from_config({"responding": {"max_tokens": "5000"}})
- assert limits.responding == 5000
+ def test_coerces_string_numbers(self):
+ from deeptutor.agents.chat.agentic_pipeline import _read_int
- def test_from_config_falls_back_on_garbage(self):
- from deeptutor.agents.chat.agentic_pipeline import _ChatLimits
+ cfg = {"max_tokens": "5000"}
+ assert _read_int(cfg, key="max_tokens", default=8000) == 5000
- limits = _ChatLimits.from_config({"responding": {"max_tokens": "abc"}})
- assert limits.responding == 8000
+ def test_falls_back_on_garbage(self):
+ from deeptutor.agents.chat.agentic_pipeline import _read_int
- def test_from_config_handles_non_dict_stage_value(self):
- from deeptutor.agents.chat.agentic_pipeline import _ChatLimits
+ cfg = {"max_tokens": "abc"}
+ assert _read_int(cfg, key="max_tokens", default=8000) == 8000
- limits = _ChatLimits.from_config({"responding": 12345})
- assert limits.responding == 8000
+ def test_non_dict_input_falls_back(self):
+ from deeptutor.agents.chat.agentic_pipeline import _read_int
+
+ assert _read_int(12345, key="max_tokens", default=8000) == 8000
+ assert _read_int(None, key="max_tokens", default=8000) == 8000
diff --git a/tests/services/config/test_context_window_detection.py b/tests/services/config/test_context_window_detection.py
index dfcf18fe4..ef223c2a0 100644
--- a/tests/services/config/test_context_window_detection.py
+++ b/tests/services/config/test_context_window_detection.py
@@ -56,3 +56,16 @@ def test_detect_context_window_uses_runtime_default_when_metadata_missing(
assert result.context_window == 20000
assert result.source == "default"
+
+
+def test_detect_context_window_uses_known_model_metadata_when_provider_omits_window(
+ monkeypatch,
+) -> None:
+ monkeypatch.setattr(
+ "deeptutor.services.config.context_window_detection._detect_from_models_endpoint",
+ _metadata_none,
+ )
+ result = asyncio.run(detect_context_window(_config(model="deepseek-v4-flash")))
+
+ assert result.context_window == 1_000_000
+ assert result.source == "known_model"
diff --git a/tests/services/config/test_llm_probe_config.py b/tests/services/config/test_llm_probe_config.py
index 1bdcf8ea1..d1f99a4e3 100644
--- a/tests/services/config/test_llm_probe_config.py
+++ b/tests/services/config/test_llm_probe_config.py
@@ -173,6 +173,44 @@ class TestLlmProbeUsesAgentsYaml:
or captured_kwargs.get("max_completion_tokens") == 4096
)
+ @pytest.mark.asyncio
+ async def test_probe_passes_runtime_api_version_and_reasoning_effort(
+ self, monkeypatch
+ ):
+ from deeptutor.services import llm as llm_module
+ from deeptutor.services.config import test_runner as test_runner_module
+ from deeptutor.services.config.test_runner import ConfigTestRunner, TestRun
+
+ captured_kwargs: dict[str, Any] = {}
+
+ async def _fake_llm_complete(**kwargs):
+ captured_kwargs.update(kwargs)
+ return "OK I am a reasoning model"
+
+ monkeypatch.setattr(
+ test_runner_module,
+ "resolve_llm_runtime_config",
+ lambda catalog: _stub_resolved_llm(
+ api_version="2026-05-01",
+ reasoning_effort="high",
+ ),
+ )
+ monkeypatch.setattr(
+ test_runner_module,
+ "detect_context_window",
+ _stub_context_window_detection,
+ )
+ monkeypatch.setattr(llm_module, "get_token_limit_kwargs", _real_get_token_limit_kwargs)
+ monkeypatch.setattr(llm_module, "complete", _fake_llm_complete)
+ monkeypatch.setattr(llm_module, "clear_llm_config_cache", lambda: None)
+
+ runner = ConfigTestRunner()
+ run = TestRun(id="test-llm-probe-runtime-fields", service="llm")
+ await runner._test_llm(run, catalog={})
+
+ assert captured_kwargs["api_version"] == "2026-05-01"
+ assert captured_kwargs["reasoning_effort"] == "high"
+
@pytest.mark.asyncio
async def test_probe_persists_detected_context_window_when_catalog_present(
self, tmp_path, monkeypatch
@@ -259,21 +297,25 @@ class TestLlmProbeUsesAgentsYaml:
# ---------------------------------------------------------------------------
-def _stub_resolved_llm():
+def _stub_resolved_llm(**overrides: Any):
"""Return a minimal resolved LLM config stub."""
from deeptutor.services.config.provider_runtime import ResolvedLLMConfig
+ values = {
+ "model": "gpt-4o-mini",
+ "api_key": "sk-test",
+ "base_url": "https://api.example.com/v1",
+ "effective_url": "https://api.example.com/v1",
+ "binding": "openai",
+ "provider_name": "openai",
+ "provider_mode": "standard",
+ "api_version": "",
+ "extra_headers": {},
+ "reasoning_effort": None,
+ }
+ values.update(overrides)
return ResolvedLLMConfig(
- model="gpt-4o-mini",
- api_key="sk-test",
- base_url="https://api.example.com/v1",
- effective_url="https://api.example.com/v1",
- binding="openai",
- provider_name="openai",
- provider_mode="standard",
- api_version="",
- extra_headers={},
- reasoning_effort=None,
+ **values,
)
diff --git a/tests/services/config/test_test_runner_dim_autofill.py b/tests/services/config/test_test_runner_dim_autofill.py
index 8b6d49af6..da2075747 100644
--- a/tests/services/config/test_test_runner_dim_autofill.py
+++ b/tests/services/config/test_test_runner_dim_autofill.py
@@ -108,6 +108,32 @@ async def test_overwrite_when_catalog_dim_disagrees_unknown_model() -> None:
assert not any(e.get("active_dim_source") for e in warnings)
+async def test_non_numeric_catalog_dim_does_not_block_probe() -> None:
+ """Bad manual catalog values should not stop the smoke probe from detecting
+ and persisting the provider's actual dimension."""
+ runner = ConfigTestRunner()
+ run = _make_run()
+ catalog: dict[str, Any] = {}
+ model: dict[str, Any] = {"dimension": "not-a-number"}
+
+ fake_client = MagicMock()
+ fake_client.embed = AsyncMock(return_value=[[0.5] * 768, [0.6] * 768])
+
+ with (
+ patch(
+ "deeptutor.services.config.test_runner.resolve_embedding_runtime_config",
+ return_value=_resolved_stub(dim=0),
+ ),
+ patch("deeptutor.services.embedding.client.EmbeddingClient", return_value=fake_client),
+ patch.object(runner, "_persist_embedding_dimension", return_value=catalog) as persist_mock,
+ ):
+ await runner._test_embedding(run, model, catalog)
+
+ persist_mock.assert_called_once()
+ assert persist_mock.call_args.args[2] == 768
+
+
@pytest.mark.asyncio
async def test_empty_vector_still_fatal() -> None:
runner = ConfigTestRunner()
diff --git a/tests/services/embedding/test_client_runtime.py b/tests/services/embedding/test_client_runtime.py
index ac8c705bb..cdef6f72c 100644
--- a/tests/services/embedding/test_client_runtime.py
+++ b/tests/services/embedding/test_client_runtime.py
@@ -36,12 +36,18 @@ class _FakeAdapter:
)()
-def _build_config(binding: str, *, send_dimensions: bool | None = None) -> EmbeddingConfig:
+def _build_config(
+ binding: str,
+ *,
+ model: str = "text-embedding-3-small",
+ base_url: str = "https://api.openai.com/v1/embeddings",
+ send_dimensions: bool | None = None,
+) -> EmbeddingConfig:
return EmbeddingConfig(
- model="text-embedding-3-small",
+ model=model,
api_key="sk-test",
- base_url="https://api.openai.com/v1/embeddings",
- effective_url="https://api.openai.com/v1/embeddings",
+ base_url=base_url,
+ effective_url=base_url,
binding=binding,
provider_name=binding,
provider_mode="standard",
@@ -217,3 +223,31 @@ def test_every_registered_provider_has_adapter() -> None:
for name in EMBEDDING_PROVIDERS:
cls = _resolve_adapter_class(name)
assert cls is not None, f"Provider '{name}' has no adapter"
+
+
+def test_embedding_client_multimodal_detection_uses_model_level_metadata() -> None:
+ text_model = EmbeddingClient(
+ _build_config(
+ "siliconflow",
+ model="Qwen/Qwen3-Embedding-8B",
+ base_url="https://api.siliconflow.cn/v1/embeddings",
+ )
+ )
+ vision_model = EmbeddingClient(
+ _build_config(
+ "siliconflow",
+ model="Qwen/Qwen3-VL-Embedding-8B",
+ base_url="https://api.siliconflow.cn/v1/embeddings",
+ )
+ )
+ cohere_v3 = EmbeddingClient(
+ _build_config(
+ "cohere",
+ model="embed-multilingual-v3.0",
+ base_url="https://api.cohere.com/v2/embed",
+ )
+ )
+
+ assert text_model.supports_multimodal_contents() is False
+ assert vision_model.supports_multimodal_contents() is True
+ assert cohere_v3.supports_multimodal_contents() is False
diff --git a/tests/services/embedding/test_multimodal_request.py b/tests/services/embedding/test_multimodal_request.py
index 4d38a3234..67f5cd5f7 100644
--- a/tests/services/embedding/test_multimodal_request.py
+++ b/tests/services/embedding/test_multimodal_request.py
@@ -10,6 +10,7 @@ import pytest
from deeptutor.services.embedding.adapters.base import EmbeddingRequest
from deeptutor.services.embedding.adapters.cohere import CohereEmbeddingAdapter
+from deeptutor.services.embedding.adapters.jina import JinaEmbeddingAdapter
from deeptutor.services.embedding.adapters.ollama import OllamaEmbeddingAdapter
from deeptutor.services.embedding.adapters.openai_compatible import (
OpenAICompatibleEmbeddingAdapter,
@@ -57,6 +58,27 @@ async def test_openai_compat_passes_contents_as_input(monkeypatch: pytest.Monkey
assert captured["json"]["input"] == contents
+async def test_openai_compat_rejects_contents_for_text_embedding_model() -> None:
+ adapter = OpenAICompatibleEmbeddingAdapter(
+ {
+ "api_key": "sk",
+ "base_url": "https://api.openai.com/v1/embeddings",
+ "model": "text-embedding-3-small",
+ "request_timeout": 5,
+ }
+ )
+
+ with pytest.raises(ValueError, match="does not support multimodal"):
+ await adapter.embed(
+ EmbeddingRequest(
+ texts=[],
+ model="text-embedding-3-small",
+ contents=[{"image": "data:image/png;base64,XXX"}],
+ )
+ )
+
+
@pytest.mark.asyncio
async def test_ollama_rejects_multimodal_contents() -> None:
adapter = OllamaEmbeddingAdapter(
@@ -77,6 +99,26 @@ async def test_ollama_rejects_multimodal_contents() -> None:
)
+async def test_jina_v3_rejects_multimodal_contents() -> None:
+ adapter = JinaEmbeddingAdapter(
+ {
+ "api_key": "jina-test",
+ "base_url": "https://api.jina.ai/v1/embeddings",
+ "model": "jina-embeddings-v3",
+ "request_timeout": 5,
+ }
+ )
+ with pytest.raises(ValueError, match="does not support multimodal"):
+ await adapter.embed(
+ EmbeddingRequest(
+ texts=[],
+ model="jina-embeddings-v3",
+ contents=[{"image": "data:image/png;base64,XXX"}],
+ )
+ )
+
+
@pytest.mark.asyncio
async def test_cohere_v2_translates_contents_to_inputs(monkeypatch: pytest.MonkeyPatch) -> None:
captured: dict[str, Any] = {}
@@ -110,3 +152,34 @@ async def test_cohere_v2_translates_contents_to_inputs(monkeypatch: pytest.Monke
assert inputs[1] == {
"content": [{"type": "image_url", "image_url": {"url": "data:image/png;base64,XXX"}}]
}
+
+
+def test_model_info_reports_multimodal_at_model_level() -> None:
+ assert CohereEmbeddingAdapter(
+ {
+ "api_key": "co-test",
+ "base_url": "https://api.cohere.com/v2/embed",
+ "model": "embed-v4.0",
+ }
+ ).get_model_info()["multimodal"] is True
+ assert CohereEmbeddingAdapter(
+ {
+ "api_key": "co-test",
+ "base_url": "https://api.cohere.com/v2/embed",
+ "model": "embed-multilingual-v3.0",
+ }
+ ).get_model_info()["multimodal"] is False
+ assert JinaEmbeddingAdapter(
+ {
+ "api_key": "jina-test",
+ "base_url": "https://api.jina.ai/v1/embeddings",
+ "model": "jina-embeddings-v4",
+ }
+ ).get_model_info()["multimodal"] is True
+ assert OpenAICompatibleEmbeddingAdapter(
+ {
+ "api_key": "sk-sf",
+ "base_url": "https://api.siliconflow.cn/v1/embeddings",
+ "model": "Qwen/Qwen3-Embedding-8B",
+ }
+ ).get_model_info()["multimodal"] is False
diff --git a/tests/services/llm/test_capabilities.py b/tests/services/llm/test_capabilities.py
index e9e02a29e..cc37fae7d 100644
--- a/tests/services/llm/test_capabilities.py
+++ b/tests/services/llm/test_capabilities.py
@@ -60,3 +60,6 @@ def test_moonshot_vision_models() -> None:
def test_qwen_model_override_enables_vision() -> None:
assert supports_vision("dashscope", "qwen-vl-plus") is True
assert supports_vision("openai", "qwen2.5-vl-72b-instruct") is True
+ assert supports_vision("openai", "Qwen/Qwen3-VL-235B-A22B-Instruct") is True
+ assert supports_vision("openai", "qwen-plus") is False
+ assert supports_vision("openai", "Qwen/Qwen3-235B-A22B-Instruct") is False
diff --git a/tests/services/llm/test_client.py b/tests/services/llm/test_client.py
index ac7d87fcf..fbf89f3fd 100644
--- a/tests/services/llm/test_client.py
+++ b/tests/services/llm/test_client.py
@@ -43,6 +43,15 @@ def test_client_complete_sync(monkeypatch: MonkeyPatch) -> None:
assert client.complete_sync("hello") == "ok"
+def test_client_reports_multimodal_image_support() -> None:
+ assert LLMClient(
+ LLMConfig(model="gpt-4o", api_key="key", base_url="https://example.com")
+ ).supports_multimodal_images() is True
+ assert LLMClient(
+ LLMConfig(model="gpt-3.5-turbo", api_key="key", base_url="https://example.com")
+ ).supports_multimodal_images() is False
+
+
@pytest.mark.asyncio
async def test_client_complete_sync_running_loop() -> None:
"""complete_sync should raise when called from a running event loop."""
diff --git a/tests/services/llm/test_openai_compat_reasoning_content.py b/tests/services/llm/test_openai_compat_reasoning_content.py
index 6494cfe68..b9e4320dc 100644
--- a/tests/services/llm/test_openai_compat_reasoning_content.py
+++ b/tests/services/llm/test_openai_compat_reasoning_content.py
@@ -64,9 +64,14 @@ def test_parse_chunks_keeps_reasoning_content_out_of_visible_content(provider_cl
assert response.reasoning_content == "internal reasoning"
-def _build_services_kwargs(provider_name: str, reasoning_effort: str) -> dict:
+def _build_services_kwargs(
+ provider_name: str,
+ reasoning_effort: str | None,
+ *,
+ model: str = "deepseek-v4-pro",
+) -> dict:
provider = ServicesOpenAICompatProvider.__new__(ServicesOpenAICompatProvider)
- provider.default_model = "deepseek-v4-pro"
+ provider.default_model = model
provider._spec = find_service_provider(provider_name)
return provider._build_kwargs(
messages=[{"role": "user", "content": "hello"}],
@@ -79,9 +84,14 @@ def _build_services_kwargs(provider_name: str, reasoning_effort: str) -> dict:
)
-def _build_tutorbot_kwargs(provider_name: str, reasoning_effort: str) -> dict:
+def _build_tutorbot_kwargs(
+ provider_name: str,
+ reasoning_effort: str | None,
+ *,
+ model: str = "deepseek-v4-pro",
+) -> dict:
provider = TutorBotOpenAICompatProvider.__new__(TutorBotOpenAICompatProvider)
- provider.default_model = "deepseek-v4-pro"
+ provider.default_model = model
provider._spec = find_tutorbot_provider(provider_name)
return provider._build_kwargs(
messages=[{"role": "user", "content": "hello"}],
@@ -101,6 +111,24 @@ def test_services_provider_minimal_reasoning_uses_extra_body_only() -> None:
assert kwargs["extra_body"] == {"thinking": {"type": "disabled"}}
+def test_services_deepseek_v4_flash_disables_thinking_by_default() -> None:
+ kwargs = _build_services_kwargs(
+ "deepseek",
+ None,
+ model="deepseek-v4-flash",
+ )
+
+ assert "reasoning_effort" not in kwargs
+ assert kwargs["extra_body"] == {"thinking": {"type": "disabled"}}
+
+
+def test_services_deepseek_v4_pro_enables_thinking_by_default() -> None:
+ kwargs = _build_services_kwargs("deepseek", None)
+
+ assert kwargs["reasoning_effort"] == "high"
+ assert kwargs["extra_body"] == {"thinking": {"type": "enabled"}}
+
+
def test_services_dashscope_minimal_reasoning_uses_enable_thinking_only() -> None:
kwargs = _build_services_kwargs("dashscope", "minimal")
@@ -113,3 +141,14 @@ def test_tutorbot_provider_minimal_reasoning_uses_extra_body_only() -> None:
assert "reasoning_effort" not in kwargs
assert kwargs["extra_body"] == {"thinking": {"type": "disabled"}}
+
+
+def test_tutorbot_deepseek_v4_flash_disables_thinking_by_default() -> None:
+ kwargs = _build_tutorbot_kwargs(
+ "deepseek",
+ None,
+ model="deepseek-v4-flash",
+ )
+
+ assert "reasoning_effort" not in kwargs
+ assert kwargs["extra_body"] == {"thinking": {"type": "disabled"}}
diff --git a/tests/services/rag/test_file_routing.py b/tests/services/rag/test_file_routing.py
index e77a74ee6..7d0dd7ac3 100644
--- a/tests/services/rag/test_file_routing.py
+++ b/tests/services/rag/test_file_routing.py
@@ -66,12 +66,14 @@ class TestClassifyFiles:
)
assert cls.parser_files == [str(pdf), str(docx), str(xlsx), str(pptx)]
assert cls.text_files == [str(txt)]
- assert cls.unsupported == [str(png)]
+ assert cls.image_files == [str(png)]
+ assert cls.unsupported == []
def test_empty_input_yields_empty_groups(self) -> None:
cls = FileTypeRouter.classify_files([])
assert cls.parser_files == []
assert cls.text_files == []
+ assert cls.image_files == []
assert cls.unsupported == []
@@ -84,6 +86,7 @@ class TestSupportedExtensionsAndGlobs:
assert ".pptx" in exts
assert ".md" in exts
assert ".txt" in exts
+ assert ".png" in exts
def test_glob_patterns_match_supported_extensions(self) -> None:
exts = FileTypeRouter.get_supported_extensions()
@@ -103,17 +106,18 @@ class TestSupportedExtensionsAndGlobs:
nested_upper.write_text("nested", encoding="utf-8")
deck = tmp_path / "DECK.PPTX"
deck.write_bytes(b"PK\x03\x04")
- ignored = tmp_path / "image.PNG"
- ignored.write_bytes(b"\x89PNG\r\n")
+ image = tmp_path / "image.PNG"
+ image.write_bytes(b"\x89PNG\r\n")
assert [path.name for path in FileTypeRouter.collect_supported_files(tmp_path)] == [
"DECK.PPTX",
+ "image.PNG",
"notes.md",
"REPORT.PDF",
]
assert [
path.name for path in FileTypeRouter.collect_supported_files(tmp_path, recursive=True)
- ] == ["DECK.PPTX", "README.MD", "notes.md", "REPORT.PDF"]
+ ] == ["DECK.PPTX", "image.PNG", "README.MD", "notes.md", "REPORT.PDF"]
class TestQuickHelpers:
diff --git a/tests/services/rag/test_llamaindex_document_loader.py b/tests/services/rag/test_llamaindex_document_loader.py
index 5eeae61b0..ea4dc1873 100644
--- a/tests/services/rag/test_llamaindex_document_loader.py
+++ b/tests/services/rag/test_llamaindex_document_loader.py
@@ -6,14 +6,11 @@ import asyncio
import io
from pathlib import Path
-from docx import Document as DocxDocument
-from openpyxl import Workbook
-from pptx import Presentation
-from pptx.util import Inches
import pytest
def _make_docx(paragraphs: list[str]) -> bytes:
+ DocxDocument = pytest.importorskip("docx").Document
doc = DocxDocument()
for paragraph in paragraphs:
doc.add_paragraph(paragraph)
@@ -23,6 +20,7 @@ def _make_docx(paragraphs: list[str]) -> bytes:
def _make_xlsx(rows: list[list[object]]) -> bytes:
+ Workbook = pytest.importorskip("openpyxl").Workbook
workbook = Workbook()
sheet = workbook.active
sheet.title = "Data"
@@ -34,6 +32,8 @@ def _make_xlsx(rows: list[list[object]]) -> bytes:
def _make_pptx(texts: list[str]) -> bytes:
+ Presentation = pytest.importorskip("pptx").Presentation
+ Inches = pytest.importorskip("pptx.util").Inches
presentation = Presentation()
slide = presentation.slides.add_slide(presentation.slide_layouts[5])
for index, text in enumerate(texts):
@@ -77,3 +77,139 @@ def test_loader_extracts_chat_supported_office_files(tmp_path: Path) -> None:
assert "42" in all_text
assert "Slide title" in all_text
assert "Slide body" in all_text
+
+
+def test_loader_skips_images_when_embedding_provider_is_text_only(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pytest.importorskip("llama_index.core")
+ from deeptutor.services.rag.pipelines.llamaindex import document_loader as loader_module
+
+ image_path = tmp_path / "photo.png"
+ image_path.write_bytes(b"\x89PNG\r\n")
+
+ class _TextOnlyClient:
+ config = type("Config", (), {"binding": "openai", "model": "text-embedding-3-small"})()
+
+ def supports_multimodal_contents(self) -> bool:
+ return False
+
+ monkeypatch.setattr(loader_module, "get_embedding_client", lambda: _TextOnlyClient())
+
+ documents = asyncio.run(loader_module.LlamaIndexDocumentLoader().load([str(image_path)]))
+
+ assert documents == []
+
+
+def test_loader_embeds_images_when_embedding_provider_is_multimodal(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pytest.importorskip("llama_index.core")
+ from llama_index.core.schema import ImageNode
+
+ from deeptutor.services.rag.pipelines.llamaindex import document_loader as loader_module
+
+ image_path = tmp_path / "photo.png"
+ image_path.write_bytes(b"\x89PNG\r\n")
+ captured: dict[str, object] = {}
+
+ class _MultimodalClient:
+ config = type("Config", (), {"binding": "siliconflow", "model": "qwen3-vl"})()
+
+ def supports_multimodal_contents(self) -> bool:
+ return True
+
+ async def embed_contents(self, contents):
+ captured["contents"] = contents
+ return [[0.1, 0.2, 0.3]]
+
+ class _VisionClient:
+ config = type("Config", (), {"binding": "openai", "model": "gpt-4o"})()
+
+ def supports_multimodal_images(self) -> bool:
+ return True
+
+ async def complete(self, prompt, **kwargs):
+ captured["llm_prompt"] = prompt
+ captured["llm_kwargs"] = kwargs
+ return "A logo image with visible HKU text."
+
+ monkeypatch.setattr(loader_module, "get_embedding_client", lambda: _MultimodalClient())
+ monkeypatch.setattr(loader_module, "get_llm_client", lambda: _VisionClient())
+
+ documents = asyncio.run(loader_module.LlamaIndexDocumentLoader().load([str(image_path)]))
+
+ assert len(documents) == 1
+ assert isinstance(documents[0], ImageNode)
+ assert documents[0].embedding == [0.1, 0.2, 0.3]
+ assert documents[0].metadata["content_type"] == "image"
+ assert documents[0].metadata["image_description"] == "A logo image with visible HKU text."
+ assert "A logo image with visible HKU text." in documents[0].text
+ assert captured["contents"][0]["image"].startswith("data:image/png;base64,")
+ assert captured["llm_kwargs"]["image_mime_type"] == "image/png"
+
+
+def test_loader_skips_images_when_llm_is_text_only(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pytest.importorskip("llama_index.core")
+ from deeptutor.services.rag.pipelines.llamaindex import document_loader as loader_module
+
+ image_path = tmp_path / "photo.png"
+ image_path.write_bytes(b"\x89PNG\r\n")
+
+ class _MultimodalEmbeddingClient:
+ config = type("Config", (), {"binding": "siliconflow", "model": "qwen3-vl"})()
+
+ def supports_multimodal_contents(self) -> bool:
+ return True
+
+ class _TextOnlyLLMClient:
+ config = type("Config", (), {"binding": "openai", "model": "gpt-3.5-turbo"})()
+
+ def supports_multimodal_images(self) -> bool:
+ return False
+
+ monkeypatch.setattr(
+ loader_module, "get_embedding_client", lambda: _MultimodalEmbeddingClient()
+ )
+ monkeypatch.setattr(loader_module, "get_llm_client", lambda: _TextOnlyLLMClient())
+
+ documents = asyncio.run(loader_module.LlamaIndexDocumentLoader().load([str(image_path)]))
+
+ assert documents == []
+
+
+def test_loader_logs_all_missing_multimodal_image_requirements(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ pytest.importorskip("llama_index.core")
+ from deeptutor.services.rag.pipelines.llamaindex import document_loader as loader_module
+
+ image_path = tmp_path / "photo.png"
+ image_path.write_bytes(b"\x89PNG\r\n")
+
+ class _TextOnlyEmbeddingClient:
+ config = type("Config", (), {"binding": "openai", "model": "text-embedding-3-small"})()
+
+ def supports_multimodal_contents(self) -> bool:
+ return False
+
+ class _TextOnlyLLMClient:
+ config = type("Config", (), {"binding": "openai", "model": "gpt-3.5-turbo"})()
+
+ def supports_multimodal_images(self) -> bool:
+ return False
+
+ monkeypatch.setattr(loader_module, "get_embedding_client", lambda: _TextOnlyEmbeddingClient())
+ monkeypatch.setattr(loader_module, "get_llm_client", lambda: _TextOnlyLLMClient())
+
+ with caplog.at_level("WARNING"):
+ documents = asyncio.run(loader_module.LlamaIndexDocumentLoader().load([str(image_path)]))
+
+ assert documents == []
+ assert "requires both multimodal embedding and multimodal LLM support" in caplog.text
+ assert "embedding provider/model does not support multimodal contents" in caplog.text
+ assert "LLM provider/model does not support multimodal image input" in caplog.text
+ assert "text-embedding-3-small" in caplog.text
+ assert "gpt-3.5-turbo" in caplog.text
diff --git a/tests/services/rag/test_llamaindex_storage_layout.py b/tests/services/rag/test_llamaindex_storage_layout.py
index 3a9ab485a..63be6d448 100644
--- a/tests/services/rag/test_llamaindex_storage_layout.py
+++ b/tests/services/rag/test_llamaindex_storage_layout.py
@@ -95,3 +95,128 @@ async def test_incremental_add_migrates_matching_legacy_index_to_flat_version(
assert captured["persist_dir"] == str(flat_storage_dir)
assert (flat_storage_dir / "docstore.json").exists()
assert json.loads((flat_storage_dir / "meta.json").read_text())["signature"] == sig.hash()
+
+
+def test_hybrid_retriever_uses_official_query_fusion_when_bm25_available(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from deeptutor.services.rag.pipelines.llamaindex.config import RetrievalConfig
+ from deeptutor.services.rag.pipelines.llamaindex import retrievers as retriever_module
+
+ captured: dict[str, object] = {}
+
+ class _FakeVectorRetriever:
+ def __init__(self, top_k: int) -> None:
+ self.top_k = top_k
+
+ class _FakeIndex:
+ def as_retriever(self, similarity_top_k: int):
+ captured["vector_top_k"] = similarity_top_k
+ return _FakeVectorRetriever(similarity_top_k)
+
+ class _FakeBM25:
+ @classmethod
+ def from_defaults(cls, index, similarity_top_k: int):
+ captured["bm25_top_k"] = similarity_top_k
+ return cls()
+
+ class _FakeFusion:
+ def __init__(self, retrievers, **kwargs):
+ captured["retrievers"] = retrievers
+ captured["kwargs"] = kwargs
+
+ monkeypatch.setattr(retriever_module, "_import_bm25_retriever", lambda: _FakeBM25)
+ monkeypatch.setattr(retriever_module, "QueryFusionRetriever", _FakeFusion)
+
+ retriever = retriever_module.build_retriever(
+ _FakeIndex(),
+ tmp_path,
+ top_k=4,
+ config=RetrievalConfig(profile="hybrid"),
+ )
+
+ assert isinstance(retriever, _FakeFusion)
+ assert captured["vector_top_k"] == 8
+ assert captured["bm25_top_k"] == 8
+ assert captured["kwargs"]["similarity_top_k"] == 4
+ assert captured["kwargs"]["num_queries"] == 1
+
+
+def test_hybrid_retriever_falls_back_to_vector_when_bm25_missing(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from deeptutor.services.rag.pipelines.llamaindex.config import RetrievalConfig
+ from deeptutor.services.rag.pipelines.llamaindex import retrievers as retriever_module
+
+ calls: list[int] = []
+
+ class _FakeIndex:
+ def as_retriever(self, similarity_top_k: int):
+ calls.append(similarity_top_k)
+ return {"top_k": similarity_top_k}
+
+ monkeypatch.setattr(retriever_module, "_import_bm25_retriever", lambda: None)
+
+ retriever = retriever_module.build_retriever(
+ _FakeIndex(),
+ tmp_path,
+ top_k=4,
+ config=RetrievalConfig(profile="hybrid"),
+ )
+
+ assert retriever == {"top_k": 4}
+ assert calls == [4]
+
+
+def test_bm25_retriever_overrides_persisted_top_k(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from deeptutor.services.rag.pipelines.llamaindex import retrievers as retriever_module
+
+ persist_dir = tmp_path / retriever_module.BM25_PERSIST_DIRNAME
+ persist_dir.mkdir()
+
+ class _FakeBM25:
+ def __init__(self) -> None:
+ self.similarity_top_k = 99
+
+ @classmethod
+ def from_persist_dir(cls, path: str):
+ assert path == str(persist_dir)
+ return cls()
+
+ monkeypatch.setattr(retriever_module, "_import_bm25_retriever", lambda: _FakeBM25)
+
+ retriever = retriever_module.build_bm25_retriever(object(), tmp_path, top_k=6)
+
+ assert retriever.similarity_top_k == 6
+
+
+def test_bm25_persistence_drops_stale_sidecar_on_rebuild_failure(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from deeptutor.services.rag.pipelines.llamaindex import retrievers as retriever_module
+
+ persist_dir = tmp_path / retriever_module.BM25_PERSIST_DIRNAME
+ persist_dir.mkdir()
+ (persist_dir / "old.json").write_text("stale", encoding="utf-8")
+
+ class _FailingBM25:
+ @classmethod
+ def from_defaults(cls, index, similarity_top_k: int):
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(retriever_module, "_import_bm25_retriever", lambda: _FailingBM25)
+
+ assert retriever_module.persist_bm25_retriever(object(), tmp_path, top_k=6) is False
+ assert not persist_dir.exists()
+
+
+def test_retrieval_config_reads_profile_from_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ from deeptutor.services.rag.pipelines.llamaindex import config as config_module
+
+ monkeypatch.setenv("DEEPTUTOR_RAG_RETRIEVAL_PROFILE", " vector ")
+
+ config = config_module.retrieval_config_from_env()
+
+ assert config.profile == config_module.VECTOR_PROFILE
diff --git a/tests/services/session/test_source_inventory.py b/tests/services/session/test_source_inventory.py
new file mode 100644
index 000000000..6dfe5b0bc
--- /dev/null
+++ b/tests/services/session/test_source_inventory.py
@@ -0,0 +1,241 @@
+"""Unit tests for the cumulative source inventory used by the chat capability."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from deeptutor.services.session.source_inventory import (
+ SourceEntry,
+ SourceInventory,
+ build_inventory,
+ render_manifest,
+)
+
+
+class FakeStore:
+ """Minimal store fake covering the protocol methods source_inventory
+ actually calls: get_messages, get_session, get_messages_for_context,
+ get_notebook_entry. Tests inject the data they want via constructor."""
+
+ def __init__(
+ self,
+ *,
+ messages: list[dict[str, Any]] | None = None,
+ sessions: dict[str, dict[str, Any]] | None = None,
+ session_messages: dict[str, list[dict[str, Any]]] | None = None,
+ notebook_entries: dict[int, dict[str, Any]] | None = None,
+ ) -> None:
+ self._messages = messages or []
+ self._sessions = sessions or {}
+ self._session_messages = session_messages or {}
+ self._notebook_entries = notebook_entries or {}
+
+ async def get_messages(self, session_id: str) -> list[dict[str, Any]]:
+ return self._messages
+
+ async def get_session(self, session_id: str) -> dict[str, Any] | None:
+ return self._sessions.get(session_id)
+
+ async def get_messages_for_context(
+ self, session_id: str, leaf_message_id: int | None = None
+ ) -> list[dict[str, Any]]:
+ return self._session_messages.get(session_id, [])
+
+ async def get_notebook_entry(self, entry_id: int) -> dict[str, Any] | None:
+ return self._notebook_entries.get(entry_id)
+
+
+# ---------------------------------------------------------------------------
+# SourceInventory dataclass
+# ---------------------------------------------------------------------------
+
+
+def test_inventory_dedupe_fresh_wins() -> None:
+ inv = SourceInventory()
+ inv.add(SourceEntry(sid="at-foo", kind="attachment", name="old", full_text="old text", fresh=False, first_seen_turn=1))
+ inv.add(SourceEntry(sid="at-foo", kind="attachment", name="fresh", full_text="fresh text", fresh=True, first_seen_turn=2))
+ assert len(inv.entries) == 1
+ assert inv.entries[0].fresh is True
+ assert inv.entries[0].name == "fresh"
+
+
+def test_inventory_skips_empty_text() -> None:
+ inv = SourceInventory()
+ inv.add(SourceEntry(sid="at-foo", kind="attachment", name="empty", full_text=" ", fresh=True, first_seen_turn=1))
+ assert inv.is_empty()
+
+
+def test_inventory_preserves_insertion_order() -> None:
+ inv = SourceInventory()
+ inv.add(SourceEntry(sid="a", kind="attachment", name="A", full_text="A", fresh=True, first_seen_turn=1))
+ inv.add(SourceEntry(sid="b", kind="attachment", name="B", full_text="B", fresh=False, first_seen_turn=1))
+ inv.add(SourceEntry(sid="c", kind="notebook", name="C", full_text="C", fresh=True, first_seen_turn=1))
+ assert [e.sid for e in inv.entries] == ["a", "b", "c"]
+
+
+# ---------------------------------------------------------------------------
+# render_manifest
+# ---------------------------------------------------------------------------
+
+
+def test_render_manifest_empty() -> None:
+ text, idx = render_manifest(SourceInventory())
+ assert text == ""
+ assert idx == {}
+
+
+def test_render_manifest_distinguishes_fresh_vs_historical() -> None:
+ inv = SourceInventory()
+ inv.add(SourceEntry(sid="at-fresh", kind="attachment", name="new.pdf", full_text="hello world", fresh=True, first_seen_turn=3))
+ inv.add(SourceEntry(sid="at-old", kind="attachment", name="old.pdf", full_text="x" * 5000, fresh=False, first_seen_turn=1))
+ text, idx = render_manifest(inv)
+ # Fresh row carries a preview field
+ assert "preview:" in text
+ assert "'hello world'" in text
+ # Historical row carries "previously attached (turn 1)" with no preview
+ assert "previously attached (turn 1)" in text
+ assert "size=" in text
+ # source_index has full text for both
+ assert idx["at-fresh"] == "hello world"
+ assert idx["at-old"] == "x" * 5000
+
+
+# ---------------------------------------------------------------------------
+# build_inventory
+# ---------------------------------------------------------------------------
+
+
+async def test_build_inventory_fresh_attachments_only() -> None:
+ store = FakeStore()
+ inv = await build_inventory(
+ store,
+ session_id="s1",
+ leaf_message_id=None,
+ current_turn_ordinal=1,
+ fresh_attachment_records=[
+ {"id": "a1", "type": "pdf", "filename": "x.pdf", "extracted_text": "PDF body"},
+ {"id": "img", "type": "image", "filename": "p.png", "extracted_text": ""}, # skipped
+ ],
+ fresh_notebook_records=[],
+ fresh_book_context_text="",
+ fresh_book_references=[],
+ fresh_history_session_ids=[],
+ fresh_question_entry_ids=[],
+ )
+ assert [e.sid for e in inv.entries] == ["at-a1"]
+ assert inv.entries[0].fresh is True
+
+
+async def test_build_inventory_historical_attachment_visible_to_next_turn() -> None:
+ """Attachment uploaded in turn 1 must appear as 'previously attached
+ (turn 1)' in turn 2's manifest, even though turn 2's payload is empty."""
+ past = [
+ {
+ "id": 1,
+ "role": "user",
+ "content": "first message",
+ "parent_message_id": None,
+ "attachments": [
+ {"id": "att-1", "filename": "year1-1.pdf", "extracted_text": "lecture notes", "mime_type": "application/pdf"}
+ ],
+ "metadata": {"request_snapshot": {}},
+ },
+ {
+ "id": 2,
+ "role": "assistant",
+ "content": "ok",
+ "parent_message_id": 1,
+ "attachments": [],
+ "metadata": {},
+ },
+ ]
+ store = FakeStore(messages=past)
+ inv = await build_inventory(
+ store,
+ session_id="s1",
+ leaf_message_id=None, # legacy linear; lineage walker returns all
+ current_turn_ordinal=2,
+ fresh_attachment_records=[],
+ fresh_notebook_records=[],
+ fresh_book_context_text="",
+ fresh_book_references=[],
+ fresh_history_session_ids=[],
+ fresh_question_entry_ids=[],
+ )
+ assert [e.sid for e in inv.entries] == ["at-att-1"]
+ e = inv.entries[0]
+ assert e.fresh is False
+ assert e.first_seen_turn == 1
+ assert e.full_text == "lecture notes"
+
+
+async def test_build_inventory_branch_isolated() -> None:
+ """Branch B should not see attachments uploaded in a sibling branch A."""
+ # Layout:
+ # 1 (user, root) → 2 (assistant) → 3 (user, branch A, attaches X.pdf)
+ # → 4 (user, branch B, attaches Y.pdf)
+ # When we ask for branch B (leaf=4), only 1, 2, 4 are in lineage.
+ msgs = [
+ {"id": 1, "role": "user", "content": "q1", "parent_message_id": None,
+ "attachments": [], "metadata": {"request_snapshot": {}}},
+ {"id": 2, "role": "assistant", "content": "a1", "parent_message_id": 1,
+ "attachments": [], "metadata": {}},
+ {"id": 3, "role": "user", "content": "branch A", "parent_message_id": 2,
+ "attachments": [{"id": "X", "filename": "X.pdf", "extracted_text": "branchA only", "mime_type": "application/pdf"}],
+ "metadata": {"request_snapshot": {}}},
+ {"id": 4, "role": "user", "content": "branch B", "parent_message_id": 2,
+ "attachments": [{"id": "Y", "filename": "Y.pdf", "extracted_text": "branchB only", "mime_type": "application/pdf"}],
+ "metadata": {"request_snapshot": {}}},
+ ]
+ store = FakeStore(messages=msgs)
+ # Render branch B's inventory (leaf=4) — should see Y, not X.
+ inv = await build_inventory(
+ store,
+ session_id="s1",
+ leaf_message_id=4,
+ current_turn_ordinal=3,
+ fresh_attachment_records=[],
+ fresh_notebook_records=[],
+ fresh_book_context_text="",
+ fresh_book_references=[],
+ fresh_history_session_ids=[],
+ fresh_question_entry_ids=[],
+ )
+ sids = [e.sid for e in inv.entries]
+ assert "at-Y" in sids, sids
+ assert "at-X" not in sids, sids
+
+
+async def test_build_inventory_fresh_shadows_historical_on_same_sid() -> None:
+ """If a notebook record is referenced both in a past turn and this
+ turn, the manifest shows it as fresh (with preview), not historical."""
+ msgs = [
+ {"id": 1, "role": "user", "content": "earlier",
+ "parent_message_id": None, "attachments": [],
+ "metadata": {"request_snapshot": {}}},
+ ]
+ store = FakeStore(messages=msgs)
+ # Fresh record matching what historical *would have* added if it had
+ # one — but historical lineage has empty snap, so only fresh is added.
+ inv = await build_inventory(
+ store,
+ session_id="s1",
+ leaf_message_id=None,
+ current_turn_ordinal=2,
+ fresh_attachment_records=[
+ {"id": "att-1", "filename": "f.pdf", "extracted_text": "fresh body", "mime_type": "application/pdf"}
+ ],
+ fresh_notebook_records=[],
+ fresh_book_context_text="",
+ fresh_book_references=[],
+ fresh_history_session_ids=[],
+ fresh_question_entry_ids=[],
+ )
+ assert inv.entries[0].fresh is True
+ assert inv.entries[0].full_text == "fresh body"
diff --git a/tests/utils/test_document_validator.py b/tests/utils/test_document_validator.py
index 15b0f7a1e..7e8695cd5 100644
--- a/tests/utils/test_document_validator.py
+++ b/tests/utils/test_document_validator.py
@@ -42,3 +42,13 @@ def test_validate_upload_safety_custom_policy_allows_supported_code_mimes() -> N
)
assert safe_name == "solver.py"
+
+
+def test_validate_upload_safety_custom_policy_allows_images() -> None:
+ safe_name = DocumentValidator.validate_upload_safety(
+ "diagram.PNG",
+ 1024,
+ allowed_extensions=FileTypeRouter.get_supported_extensions(),
+ )
+
+ assert safe_name == "diagram.png"
diff --git a/web/app/(auth)/login/page.tsx b/web/app/(auth)/login/page.tsx
index 2a1244383..50356e356 100644
--- a/web/app/(auth)/login/page.tsx
+++ b/web/app/(auth)/login/page.tsx
@@ -3,9 +3,11 @@
import { Suspense, useState, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
+import { useTranslation } from "react-i18next";
import { login, fetchAuthStatus, checkIsFirstUser } from "@/lib/auth";
function LoginPageContent() {
+ const { t } = useTranslation();
const router = useRouter();
const searchParams = useSearchParams();
const next = searchParams.get("next") ?? "/";
@@ -41,7 +43,7 @@ function LoginPageContent() {
if (result.ok) {
router.replace(next);
} else {
- setError(result.error ?? "Login failed");
+ setError(result.error ?? t("Login failed"));
setLoading(false);
}
}
@@ -54,14 +56,14 @@ function LoginPageContent() {
DeepTutor
</h1>
<p className="mt-1 text-sm text-[var(--muted-foreground)]">
- Sign in to your account
+ {t("Sign in to your account")}
</p>
</div>
{/* Registered success notice */}
{registered && (
<div className="mb-4 rounded-lg border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-600 dark:text-green-400">
- Account created! Sign in to continue.
+ {t("Account created! Sign in to continue.")}
</div>
)}
@@ -74,7 +76,7 @@ function LoginPageContent() {
htmlFor="username"
className="block text-sm font-medium text-[var(--foreground)] mb-1.5"
>
- Email
+ {t("Email")}
</label>
<input
id="username"
@@ -98,7 +100,7 @@ function LoginPageContent() {
htmlFor="password"
className="block text-sm font-medium text-[var(--foreground)] mb-1.5"
>
- Password
+ {t("Password")}
</label>
<input
id="password"
@@ -133,18 +135,18 @@ function LoginPageContent() {
disabled:opacity-50 disabled:cursor-not-allowed
transition-opacity"
>
- {loading ? "Signing in…" : "Sign in"}
+ {loading ? t("Signing in…") : t("Sign in")}
</button>
</form>
</div>
<p className="mt-6 text-center text-sm text-[var(--muted-foreground)]">
- Don&apos;t have an account?{" "}
+ {t("Don't have an account?")}{" "}
<Link
href="/register"
className="text-[var(--primary)] hover:underline font-medium"
>
- Create one
+ {t("Create one")}
</Link>
</p>
diff --git a/web/app/(auth)/register/page.tsx b/web/app/(auth)/register/page.tsx
index 07253283d..ee396ad5a 100644
--- a/web/app/(auth)/register/page.tsx
+++ b/web/app/(auth)/register/page.tsx
@@ -3,9 +3,11 @@
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
+import { useTranslation } from "react-i18next";
import { register, checkIsFirstUser, fetchAuthStatus } from "@/lib/auth";
export default function RegisterPage() {
+ const { t } = useTranslation();
const router = useRouter();
const [username, setUsername] = useState("");
@@ -34,7 +36,7 @@ export default function RegisterPage() {
setError("");
if (password !== confirmPassword) {
- setError("Passwords do not match");
+ setError(t("Passwords do not match"));
return;
}
@@ -44,7 +46,7 @@ export default function RegisterPage() {
if (result.ok) {
router.replace("/login?registered=1");
} else {
- setError(result.error ?? "Registration failed");
+ setError(result.error ?? t("Registration failed"));
setLoading(false);
}
}
@@ -57,15 +59,17 @@ export default function RegisterPage() {
DeepTutor
</h1>
<p className="mt-1 text-sm text-[var(--muted-foreground)]">
- Create your account
+ {t("Create your account")}
</p>
</div>
{/* First-user notice */}
{!checkingFirst && isFirst && (
<div className="mb-4 rounded-lg border border-blue-500/30 bg-blue-500/10 px-4 py-3 text-sm text-blue-600 dark:text-blue-400">
- <strong>First user:</strong> You will be granted admin privileges and
- can manage other users from the admin dashboard.
+ <strong>{t("First user:")}</strong>{" "}
+ {t(
+ "You will be granted admin privileges and can manage other users from the admin dashboard.",
+ )}
</div>
)}
@@ -78,7 +82,7 @@ export default function RegisterPage() {
htmlFor="username"
className="block text-sm font-medium text-[var(--foreground)] mb-1.5"
>
- Email
+ {t("Email")}
</label>
<input
id="username"
@@ -102,7 +106,7 @@ export default function RegisterPage() {
htmlFor="password"
className="block text-sm font-medium text-[var(--foreground)] mb-1.5"
>
- Password
+ {t("Password")}
</label>
<input
id="password"
@@ -119,7 +123,7 @@ export default function RegisterPage() {
placeholder="••••••••"
/>
<p className="mt-1 text-xs text-[var(--muted-foreground)]">
- At least 8 characters
+ {t("At least 8 characters")}
</p>
</div>
@@ -129,7 +133,7 @@ export default function RegisterPage() {
htmlFor="confirmPassword"
className="block text-sm font-medium text-[var(--foreground)] mb-1.5"
>
- Confirm password
+ {t("Confirm password")}
</label>
<input
id="confirmPassword"
@@ -164,18 +168,18 @@ export default function RegisterPage() {
disabled:opacity-50 disabled:cursor-not-allowed
transition-opacity"
>
- {loading ? "Creating account…" : "Create account"}
+ {loading ? t("Creating account…") : t("Create account")}
</button>
</form>
</div>
<p className="mt-6 text-center text-sm text-[var(--muted-foreground)]">
- Already have an account?{" "}
+ {t("Already have an account?")}{" "}
<Link
href="/login"
className="text-[var(--primary)] hover:underline font-medium"
>
- Sign in
+ {t("Sign in")}
</Link>
</p>
diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsx
index 612650d8a..20ce56722 100644
--- a/web/app/(utility)/settings/page.tsx
+++ b/web/app/(utility)/settings/page.tsx
@@ -231,6 +231,7 @@ function formatContextWindowSource(
): string {
if (source === "manual") return t("Manual");
if (source === "metadata") return t("Auto");
+ if (source === "known_model") return t("Known");
if (source === "default") return t("Default");
return t("Unset");
}
@@ -1755,6 +1756,11 @@ function SettingsPageContent() {
? t(
"Detected from the provider during the latest LLM test and saved into model_catalog.json.",
)
+ : activeModel.context_window_source ===
+ "known_model"
+ ? t(
+ "Matched built-in model metadata during the latest LLM test and saved into model_catalog.json.",
+ )
: activeModel.context_window_source ===
"default"
? t(
diff --git a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
index efb090e70..4d7efdd97 100644
--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
@@ -311,6 +311,8 @@ export default function ChatPage() {
cancelStreamingTurn,
regenerateLastMessage,
deleteTurn,
+ editMessage,
+ switchBranch,
newSession,
loadSession,
} = useUnifiedChat();
@@ -1647,6 +1649,9 @@ export default function ChatPage() {
onConfirmOutline={handleConfirmOutline}
onPreviewAttachment={handlePreviewMessageAttachment}
onDeleteTurn={deleteTurn}
+ selectedBranches={state.selectedBranches}
+ onEditMessage={editMessage}
+ onSwitchBranch={switchBranch}
/>
<div ref={messagesEndRef} className="h-px w-full shrink-0" />
</div>
diff --git a/web/app/globals.css b/web/app/globals.css
index c2853bbc7..89b70c650 100644
--- a/web/app/globals.css
+++ b/web/app/globals.css
@@ -673,3 +673,27 @@
opacity: 1;
}
}
+
+/* ─── Reduced motion ──────────────────────────────────────────────────────
+ Honor the OS-level prefers-reduced-motion setting. We don't strip motion
+ entirely — interaction-critical transitions (drawer slide, menu reveal)
+ stay visible but are shortened to a near-imperceptible duration so the
+ UI still communicates state changes without vestibular jitter. Loop
+ animations (breathing, pulse, spin) are removed outright. */
+@media (prefers-reduced-motion: reduce) {
+ *,
+ *::before,
+ *::after {
+ animation-duration: 0.001ms !important;
+ animation-iteration-count: 1 !important;
+ transition-duration: 0.001ms !important;
+ scroll-behavior: auto !important;
+ }
+
+ .dt-breathing-text,
+ .dt-mark-pulse,
+ .session-pulse,
+ .animate-spin {
+ animation: none !important;
+ }
+}
diff --git a/web/app/layout.tsx b/web/app/layout.tsx
index 625959213..216b65db6 100644
--- a/web/app/layout.tsx
+++ b/web/app/layout.tsx
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import { Plus_Jakarta_Sans, Lora } from "next/font/google";
import "./globals.css";
import ThemeScript from "@/components/ThemeScript";
+import ToastViewport from "@/components/common/ToastViewport";
import { AppShellProvider } from "@/context/AppShellContext";
import { I18nClientBridge } from "@/i18n/I18nClientBridge";
@@ -47,6 +48,7 @@ export default function RootLayout({
<body className="font-sans bg-[var(--background)] text-[var(--foreground)]">
<AppShellProvider>
<I18nClientBridge>{children}</I18nClientBridge>
+ <ToastViewport />
</AppShellProvider>
</body>
</html>
diff --git a/web/components/Mermaid.tsx b/web/components/Mermaid.tsx
index 61e66b4c0..68565af98 100644
--- a/web/components/Mermaid.tsx
+++ b/web/components/Mermaid.tsx
@@ -2,6 +2,7 @@
import React, { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
+import { subscribeToThemeChanges } from "@/lib/theme";
interface MermaidProps {
chart: string;
@@ -10,36 +11,58 @@ interface MermaidProps {
let mermaidLoader: Promise<(typeof import("mermaid"))["default"]> | null = null;
+// Read a CSS custom property from :root. We re-derive these on every render
+// so the diagram colors track the active theme rather than freezing to the
+// first-render palette.
+function cssVar(name: string, fallback: string): string {
+ if (typeof window === "undefined") return fallback;
+ const value = getComputedStyle(document.documentElement)
+ .getPropertyValue(name)
+ .trim();
+ return value || fallback;
+}
+
+function themeVariablesFromCss() {
+ // Mermaid expects opaque colors; we pull from the theme's --foreground /
+ // --card / --border / --primary tokens so diagrams blend with the chat
+ // surface in every theme (light, dark, snow, glass).
+ return {
+ primaryColor: cssVar("--card", "#ffffff"),
+ primaryTextColor: cssVar("--foreground", "#1f1d1b"),
+ primaryBorderColor: cssVar("--border", "#dbd4c8"),
+ lineColor: cssVar("--muted-foreground", "#6b655f"),
+ secondaryColor: cssVar("--muted", "#ece7dd"),
+ tertiaryColor: cssVar("--background", "#faf9f6"),
+ textColor: cssVar("--foreground", "#1f1d1b"),
+ mainBkg: cssVar("--card", "#ffffff"),
+ };
+}
+
async function loadMermaid() {
if (!mermaidLoader) {
- mermaidLoader = import("mermaid").then((module) => {
- const mermaid = module.default;
- mermaid.initialize({
- startOnLoad: false,
- theme: "neutral",
- securityLevel: "strict",
- fontFamily: "ui-sans-serif, system-ui, sans-serif",
- flowchart: {
- useMaxWidth: true,
- htmlLabels: false,
- curve: "basis",
- },
- themeVariables: {
- primaryColor: "#6366f1",
- primaryTextColor: "#1e293b",
- primaryBorderColor: "#c7d2fe",
- lineColor: "#94a3b8",
- secondaryColor: "#f1f5f9",
- tertiaryColor: "#f8fafc",
- },
- });
- return mermaid;
- });
+ mermaidLoader = import("mermaid").then((module) => module.default);
}
-
return mermaidLoader;
}
+// Re-applied on every render so theme changes pick up. mermaid.initialize()
+// is idempotent and cheap; the heavy work is the dynamic import which the
+// loader above only runs once.
+function applyMermaidTheme(mermaid: (typeof import("mermaid"))["default"]) {
+ mermaid.initialize({
+ startOnLoad: false,
+ theme: "base",
+ securityLevel: "strict",
+ fontFamily: "ui-sans-serif, system-ui, sans-serif",
+ flowchart: {
+ useMaxWidth: true,
+ htmlLabels: false,
+ curve: "basis",
+ },
+ themeVariables: themeVariablesFromCss(),
+ });
+}
+
function cleanupMermaidOrphans(id: string) {
try {
document.getElementById(id)?.remove();
@@ -60,6 +83,7 @@ export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {
const [error, setError] = useState<string | null>(null);
const [stable, setStable] = useState(false);
const [id] = useState(() => `mermaid-${++mermaidIdCounter}`);
+ const [themeToken, setThemeToken] = useState(0);
const lastChartRef = useRef(chart);
useEffect(() => {
@@ -73,6 +97,13 @@ export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {
return () => window.clearTimeout(timer);
}, [chart]);
+ // Bump a token whenever the app's theme changes so the render effect below
+ // re-runs with fresh theme variables. Without this the diagram would keep
+ // its initial palette across light/dark/glass/snow switches.
+ useEffect(() => {
+ return subscribeToThemeChanges(() => setThemeToken((t) => t + 1));
+ }, []);
+
useEffect(() => {
if (!stable) return;
@@ -82,6 +113,7 @@ export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {
try {
const mermaid = await loadMermaid();
+ applyMermaidTheme(mermaid);
cleanupMermaidOrphans(id);
const { svg: renderedSvg } = await mermaid.render(id, chart.trim());
if (!cancelled) {
@@ -102,7 +134,7 @@ export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {
return () => {
cancelled = true;
};
- }, [stable, chart, id, t]);
+ }, [stable, chart, id, t, themeToken]);
if (error) {
return (
diff --git a/web/components/SessionList.tsx b/web/components/SessionList.tsx
index 131c817e2..9bb80151f 100644
--- a/web/components/SessionList.tsx
+++ b/web/components/SessionList.tsx
@@ -5,6 +5,11 @@ import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { type SessionSummary } from "@/lib/session-api";
import { normalizeMessageContent, truncateText } from "@/lib/message-content";
+import {
+ formatRelativeTime,
+ getDayGroupKey,
+ type DayGroupKey,
+} from "@/lib/relative-time";
type SessionRuntimeStatus =
| "idle"
@@ -80,38 +85,6 @@ function StatusIndicator({ status }: { status?: SessionRuntimeStatus }) {
return null;
}
-function groupLabel(timestamp: number): string {
- const now = new Date();
- const date = new Date(timestamp * 1000);
- const startOfToday = new Date(
- now.getFullYear(),
- now.getMonth(),
- now.getDate(),
- ).getTime();
- const startOfItemDay = new Date(
- date.getFullYear(),
- date.getMonth(),
- date.getDate(),
- ).getTime();
- const diffDays = Math.floor((startOfToday - startOfItemDay) / 86400000);
- if (diffDays <= 0) return "Today";
- if (diffDays === 1) return "Yesterday";
- if (diffDays < 7) return "Last 7 days";
- return "Earlier";
-}
-
-function relativeTime(timestamp: number): string {
- const diffSeconds = Math.round(timestamp - Date.now() / 1000);
- const formatter = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
- const abs = Math.abs(diffSeconds);
- if (abs < 60) return formatter.format(diffSeconds, "second");
- if (abs < 3600)
- return formatter.format(Math.round(diffSeconds / 60), "minute");
- if (abs < 86400)
- return formatter.format(Math.round(diffSeconds / 3600), "hour");
- return formatter.format(Math.round(diffSeconds / 86400), "day");
-}
-
export default function SessionList({
sessions,
activeSessionId,
@@ -121,17 +94,31 @@ export default function SessionList({
onRename,
onDelete,
}: SessionListProps) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
const [editingId, setEditingId] = useState<string | null>(null);
const [draftTitle, setDraftTitle] = useState("");
+ // The group-key tokens are stable across locales; the translated labels
+ // (and their ordering) are built once per language change. Memoizing on
+ // i18n.language so the labels recompute when the user flips the language
+ // switcher.
+ const groupLabels = useMemo<Record<DayGroupKey, string>>(
+ () => ({
+ today: t("Today"),
+ yesterday: t("Yesterday"),
+ last_7_days: t("Last 7 days"),
+ earlier: t("Earlier"),
+ }),
+ [t, i18n.language],
+ );
+
const grouped = useMemo(() => {
- const buckets = new Map<string, SessionSummary[]>();
+ const buckets = new Map<DayGroupKey, SessionSummary[]>();
for (const session of sessions) {
- const label = groupLabel(session.updated_at);
- const current = buckets.get(label) ?? [];
+ const key = getDayGroupKey(session.updated_at);
+ const current = buckets.get(key) ?? [];
current.push(session);
- buckets.set(label, current);
+ buckets.set(key, current);
}
return Array.from(buckets.entries());
}, [sessions]);
@@ -192,13 +179,13 @@ export default function SessionList({
if (compact) {
return (
<div className="ml-5 border-l border-[var(--border)]/30 py-1">
- {grouped.map(([label, items], groupIdx) => (
- <div key={label}>
+ {grouped.map(([key, items], groupIdx) => (
+ <div key={key}>
{groupIdx > 0 && (
<div className="my-1 ml-3 mr-2 border-t border-[var(--border)]/20" />
)}
<div className="px-3 py-0.5 text-[10px] font-medium uppercase tracking-wider text-[var(--muted-foreground)]/40">
- {label}
+ {groupLabels[key]}
</div>
{items.map((session) => {
const active = activeSessionId === session.session_id;
@@ -298,10 +285,10 @@ export default function SessionList({
/* ---- Classic style ---- */
return (
<div className="space-y-4">
- {grouped.map(([label, items]) => (
- <div key={label}>
+ {grouped.map(([key, items]) => (
+ <div key={key}>
<div className="mb-1.5 px-2 text-[11px] font-semibold uppercase tracking-widest text-[var(--muted-foreground)]">
- {label}
+ {groupLabels[key]}
</div>
<div className="divide-y divide-[var(--border)]/45 overflow-hidden rounded-lg border border-[var(--border)]/45 bg-[var(--card)]/50">
{items.map((session) => {
@@ -365,7 +352,11 @@ export default function SessionList({
{truncateText(
normalizeMessageContent(session.last_message),
120,
- ) || relativeTime(session.updated_at)}
+ ) ||
+ formatRelativeTime(
+ session.updated_at,
+ i18n.language,
+ )}
</div>
)}
</div>
diff --git a/web/components/chat/BookReferencePicker.tsx b/web/components/chat/BookReferencePicker.tsx
index c934e727f..282614d61 100644
--- a/web/components/chat/BookReferencePicker.tsx
+++ b/web/components/chat/BookReferencePicker.tsx
@@ -11,6 +11,7 @@ import {
X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
+import PickerShell from "@/components/common/PickerShell";
import { bookApi } from "@/lib/book-api";
import type { Book, BookDetail, Chapter, Page } from "@/lib/book-types";
import type {
@@ -210,10 +211,14 @@ export default function BookReferencePicker({
0,
);
- if (!open) return null;
-
return (
- <div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
+ <PickerShell
+ open={open}
+ onClose={onClose}
+ labelledBy="book-picker-title"
+ className="p-4 backdrop-blur-md"
+ backdropClass="bg-[var(--background)]/65"
+ >
<div className="surface-card flex h-[78vh] w-full max-w-5xl flex-col overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">
<div className="flex items-start justify-between gap-3 border-b border-[var(--border)] px-5 py-4">
<div className="min-w-0">
@@ -221,7 +226,10 @@ export default function BookReferencePicker({
<BookOpen className="h-3 w-3" />
{t("Book Reference")}
</div>
- <h2 className="text-lg font-semibold text-[var(--foreground)]">
+ <h2
+ id="book-picker-title"
+ className="text-lg font-semibold text-[var(--foreground)]"
+ >
{t("Select Book Chapters")}
</h2>
<p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
@@ -439,6 +447,6 @@ export default function BookReferencePicker({
</div>
</div>
</div>
- </div>
+ </PickerShell>
);
}
diff --git a/web/components/chat/HistorySessionPicker.tsx b/web/components/chat/HistorySessionPicker.tsx
index 73dedabb7..4cc8db555 100644
--- a/web/components/chat/HistorySessionPicker.tsx
+++ b/web/components/chat/HistorySessionPicker.tsx
@@ -10,6 +10,7 @@ import {
X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
+import PickerShell from "@/components/common/PickerShell";
import { listSessions, type SessionSummary } from "@/lib/session-api";
import { normalizeMessageContent, truncateText } from "@/lib/message-content";
@@ -102,10 +103,14 @@ export default function HistorySessionPicker({
onClose();
};
- if (!open) return null;
-
return (
- <div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
+ <PickerShell
+ open={open}
+ onClose={onClose}
+ labelledBy="history-picker-title"
+ className="p-4 backdrop-blur-md"
+ backdropClass="bg-[var(--background)]/65"
+ >
<div className="surface-card w-full max-w-4xl overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">
<div className="flex items-start justify-between gap-3 border-b border-[var(--border)] px-5 py-4">
<div className="min-w-0">
@@ -113,7 +118,10 @@ export default function HistorySessionPicker({
<HistoryIcon className="h-3 w-3" />
{t("Chat History Reference")}
</div>
- <h2 className="text-lg font-semibold text-[var(--foreground)]">
+ <h2
+ id="history-picker-title"
+ className="text-lg font-semibold text-[var(--foreground)]"
+ >
{t("Select History Sessions")}
</h2>
<p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
@@ -234,6 +242,6 @@ export default function HistorySessionPicker({
</div>
</div>
</div>
- </div>
+ </PickerShell>
);
}
diff --git a/web/components/chat/MemoryPicker.tsx b/web/components/chat/MemoryPicker.tsx
index 29f83a8c2..8fc10b7c9 100644
--- a/web/components/chat/MemoryPicker.tsx
+++ b/web/components/chat/MemoryPicker.tsx
@@ -4,6 +4,7 @@ import { useEffect, useState } from "react";
import { Brain, Check, FileText, ScrollText, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { LucideIcon } from "lucide-react";
+import PickerShell from "@/components/common/PickerShell";
import type { SpaceMemoryFile } from "@/lib/space-items";
interface MemoryPickerProps {
@@ -70,10 +71,14 @@ export default function MemoryPicker({
onClose();
};
- if (!open) return null;
-
return (
- <div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
+ <PickerShell
+ open={open}
+ onClose={onClose}
+ labelledBy="memory-picker-title"
+ className="p-4 backdrop-blur-md"
+ backdropClass="bg-[var(--background)]/65"
+ >
<div className="surface-card w-full max-w-xl overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">
<div className="flex items-start justify-between gap-3 border-b border-[var(--border)] px-5 py-4">
<div className="min-w-0">
@@ -81,7 +86,10 @@ export default function MemoryPicker({
<Brain className="h-3 w-3" />
{t("Memory Reference")}
</div>
- <h2 className="text-lg font-semibold text-[var(--foreground)]">
+ <h2
+ id="memory-picker-title"
+ className="text-lg font-semibold text-[var(--foreground)]"
+ >
{t("Select Memory")}
</h2>
<p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
@@ -167,6 +175,6 @@ export default function MemoryPicker({
</div>
</div>
</div>
- </div>
+ </PickerShell>
);
}
diff --git a/web/components/chat/QuestionBankPicker.tsx b/web/components/chat/QuestionBankPicker.tsx
index 19d4e608a..33ac870c9 100644
--- a/web/components/chat/QuestionBankPicker.tsx
+++ b/web/components/chat/QuestionBankPicker.tsx
@@ -11,6 +11,7 @@ import {
X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
+import PickerShell from "@/components/common/PickerShell";
import {
listCategories,
listNotebookEntries,
@@ -128,10 +129,14 @@ export default function QuestionBankPicker({
onClose();
};
- if (!open) return null;
-
return (
- <div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
+ <PickerShell
+ open={open}
+ onClose={onClose}
+ labelledBy="question-bank-picker-title"
+ className="p-4 backdrop-blur-md"
+ backdropClass="bg-[var(--background)]/65"
+ >
<div className="surface-card w-full max-w-4xl overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">
<div className="flex items-start justify-between gap-3 border-b border-[var(--border)] px-5 py-4">
<div className="min-w-0">
@@ -139,7 +144,10 @@ export default function QuestionBankPicker({
<ClipboardList className="h-3 w-3" />
{t("Question Bank Reference")}
</div>
- <h2 className="text-lg font-semibold text-[var(--foreground)]">
+ <h2
+ id="question-bank-picker-title"
+ className="text-lg font-semibold text-[var(--foreground)]"
+ >
{t("Select Question Bank Entries")}
</h2>
<p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
@@ -323,6 +331,6 @@ export default function QuestionBankPicker({
</div>
</div>
</div>
- </div>
+ </PickerShell>
);
}
diff --git a/web/components/chat/SkillsPicker.tsx b/web/components/chat/SkillsPicker.tsx
index 4915c144e..169c33106 100644
--- a/web/components/chat/SkillsPicker.tsx
+++ b/web/components/chat/SkillsPicker.tsx
@@ -3,6 +3,7 @@
import { useEffect, useMemo, useState } from "react";
import { Check, Loader2, Search, Sparkles, Wand2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
+import PickerShell from "@/components/common/PickerShell";
import { listSkills, type SkillInfo } from "@/lib/skills-api";
export interface SkillsPickerSelection {
@@ -111,12 +112,16 @@ export default function SkillsPicker({
setSelected([]);
};
- if (!open) return null;
-
const totalCount = auto ? 1 : selected.length;
return (
- <div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
+ <PickerShell
+ open={open}
+ onClose={onClose}
+ labelledBy="skills-picker-title"
+ className="p-4 backdrop-blur-md"
+ backdropClass="bg-[var(--background)]/65"
+ >
<div className="surface-card w-full max-w-3xl overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">
<div className="flex items-start justify-between gap-3 border-b border-[var(--border)] px-5 py-4">
<div className="min-w-0">
@@ -124,7 +129,10 @@ export default function SkillsPicker({
<Wand2 className="h-3 w-3" />
{t("Skills Reference")}
</div>
- <h2 className="text-lg font-semibold text-[var(--foreground)]">
+ <h2
+ id="skills-picker-title"
+ className="text-lg font-semibold text-[var(--foreground)]"
+ >
{t("Select Skills")}
</h2>
<p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
@@ -280,6 +288,6 @@ export default function SkillsPicker({
</div>
</div>
</div>
- </div>
+ </PickerShell>
);
}
diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsx
index b46b6afcf..f3475be82 100644
--- a/web/components/chat/home/ChatComposer.tsx
+++ b/web/components/chat/home/ChatComposer.tsx
@@ -312,8 +312,6 @@ export default memo(function ChatComposer({
[onAddFiles],
);
- const activeCapabilityKey = activeCap.value || "chat";
-
useEffect(() => {
if (!hasMessages) textareaRef.current?.focus();
}, [hasMessages]);
@@ -456,7 +454,6 @@ export default memo(function ChatComposer({
<ComposerInput
ref={inputHandleRef}
textareaRef={textareaRef}
- activeCapabilityKey={activeCapabilityKey}
isMathAnimatorMode={isMathAnimatorMode}
isVisualizeMode={isVisualizeMode}
canSendEmpty={hasReferences}
@@ -998,7 +995,7 @@ export default memo(function ChatComposer({
<button
type="button"
onClick={onCancelStreaming}
- className="group relative inline-flex h-[29px] w-[29px] shrink-0 items-center justify-center rounded-full bg-[var(--primary)] text-white shadow-[0_4px_12px_rgba(195,90,44,0.18)] transition-[background-color,box-shadow] hover:bg-[var(--primary)]/90 hover:shadow-[0_6px_16px_rgba(195,90,44,0.28)]"
+ className="group relative inline-flex h-[29px] w-[29px] shrink-0 items-center justify-center rounded-full bg-[var(--primary)] text-white shadow-[0_4px_12px_color-mix(in_srgb,var(--primary)_18%,transparent)] transition-[background-color,box-shadow] hover:bg-[var(--primary)]/90 hover:shadow-[0_6px_16px_color-mix(in_srgb,var(--primary)_28%,transparent)]"
aria-label={t("Stop generating")}
title={t("Stop generating")}
>
@@ -1033,10 +1030,10 @@ export default memo(function ChatComposer({
: undefined
}
aria-disabled={!canSend}
- className={`rounded-full p-[7px] shadow-[0_4px_12px_rgba(195,90,44,0.15)] transition-[transform,opacity,box-shadow] disabled:opacity-25 disabled:shadow-none ${
+ className={`rounded-full p-[7px] shadow-[0_4px_12px_color-mix(in_srgb,var(--primary)_15%,transparent)] transition-[transform,opacity,box-shadow] disabled:opacity-25 disabled:shadow-none ${
isConfigBlocked
? "bg-[var(--muted-foreground)]/30 text-white hover:bg-[var(--muted-foreground)]/45"
- : "bg-[var(--primary)] text-white hover:shadow-[0_6px_16px_rgba(195,90,44,0.22)]"
+ : "bg-[var(--primary)] text-white hover:shadow-[0_6px_16px_color-mix(in_srgb,var(--primary)_22%,transparent)]"
}`}
aria-label={t("Send")}
>
diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsx
index a26eddfd6..9b0aedcb3 100644
--- a/web/components/chat/home/ChatMessages.tsx
+++ b/web/components/chat/home/ChatMessages.tsx
@@ -5,10 +5,13 @@ import { memo, useCallback, useMemo, useState } from "react";
import {
BookOpen,
Brain,
+ ChevronLeft,
+ ChevronRight,
ClipboardList,
Coins,
Copy,
MessageSquare,
+ Pencil,
RefreshCcw,
Wand2,
X,
@@ -32,6 +35,10 @@ import { extractVisualizeResult } from "@/lib/visualize-types";
import type { StreamEvent } from "@/lib/unified-ws";
import { hasVisibleMarkdownContent } from "@/lib/markdown-display";
import type { SelectedBookReference } from "@/lib/book-references";
+import {
+ buildVisiblePath,
+ type SiblingInfo,
+} from "@/lib/message-branches";
import type { SpaceMemoryFile } from "@/lib/space-items";
import AutoModeAssistantMessage from "./AutoModeAssistantMessage";
import { TraceSurface } from "./TracePanels";
@@ -60,6 +67,7 @@ interface ChatMessageItem {
events?: StreamEvent[];
attachments?: MessageAttachment[];
requestSnapshot?: MessageRequestSnapshot;
+ parentMessageId?: number | null;
}
interface NotebookReferenceGroup {
@@ -334,61 +342,137 @@ function RoughActionButton({
);
}
+function BranchNavigator({
+ info,
+ onSwitch,
+}: {
+ info: SiblingInfo;
+ onSwitch: (childId: number) => void;
+}) {
+ const { t } = useTranslation();
+ const prevIdx = info.index - 2; // 0-based prev index
+ const nextIdx = info.index; // 0-based next index
+ const prevId = prevIdx >= 0 ? info.siblingIds[prevIdx] : null;
+ const nextId =
+ nextIdx < info.siblingIds.length ? info.siblingIds[nextIdx] : null;
+ return (
+ <div className="inline-flex items-center gap-0.5 text-[10.5px] text-[var(--muted-foreground)]">
+ <button
+ type="button"
+ onClick={() => prevId !== null && onSwitch(prevId)}
+ disabled={prevId === null}
+ aria-label={t("Previous branch")}
+ className="rounded p-0.5 transition-colors hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-30"
+ >
+ <ChevronLeft size={12} strokeWidth={1.8} />
+ </button>
+ <span className="select-none tabular-nums">
+ {info.index} / {info.total}
+ </span>
+ <button
+ type="button"
+ onClick={() => nextId !== null && onSwitch(nextId)}
+ disabled={nextId === null}
+ aria-label={t("Next branch")}
+ className="rounded p-0.5 transition-colors hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-30"
+ >
+ <ChevronRight size={12} strokeWidth={1.8} />
+ </button>
+ </div>
+ );
+}
+
+function DeleteTurnButton({ onDelete }: { onDelete: () => void }) {
+ const { t } = useTranslation();
+ const [confirm, setConfirm] = useState(false);
+ if (!confirm) {
+ return (
+ <RoughActionButton
+ icon={Trash2}
+ label={t("Delete")}
+ onClick={() => setConfirm(true)}
+ />
+ );
+ }
+ return (
+ <div className="inline-flex items-center gap-1.5 text-[11px]">
+ <span className="text-[var(--muted-foreground)]">
+ {t("Delete this turn?")}
+ </span>
+ <button
+ type="button"
+ onClick={() => {
+ onDelete();
+ setConfirm(false);
+ }}
+ className="rounded-md px-1.5 py-0.5 font-medium text-[var(--destructive)] hover:bg-[var(--destructive)]/10"
+ >
+ {t("Delete")}
+ </button>
+ <button
+ type="button"
+ onClick={() => setConfirm(false)}
+ className="rounded-md px-1.5 py-0.5 font-medium text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40"
+ >
+ {t("Cancel")}
+ </button>
+ </div>
+ );
+}
+
const UserMessage = memo(function UserMessage({
msg,
index,
onPreviewAttachment,
- onDeleteTurn,
+ onCopy,
+ onEdit,
+ editDisabled,
+ siblingInfo,
+ onSwitchBranch,
}: {
msg: ChatMessageItem;
index: number;
onPreviewAttachment?: (attachment: MessageAttachment) => void;
- onDeleteTurn?: (messageId: number) => void;
+ onCopy?: (content: string) => void | Promise<void>;
+ onEdit?: (messageId: number, newContent: string) => void;
+ editDisabled?: boolean;
+ siblingInfo?: SiblingInfo;
+ onSwitchBranch?: (parentMessageId: number | null, childId: number) => void;
}) {
const { t } = useTranslation();
- const [confirmDelete, setConfirmDelete] = useState(false);
+ const [editing, setEditing] = useState(false);
+ const [draft, setDraft] = useState(msg.content);
if (msg.content.startsWith("[Quiz Performance]")) return null;
+ // ``msg.id`` can be a negative client-side sentinel for optimistic
+ // (just-sent, not yet reconciled with the server) rows. We still allow
+ // the Edit button to surface — ``editMessage`` in the context handles
+ // the optimistic case by triggering a session reload to resolve the
+ // real id before submitting the branch.
+ const canEdit =
+ Boolean(onEdit) && typeof msg.id === "number" && !editDisabled;
+ const startEdit = () => {
+ if (!canEdit) return;
+ setDraft(msg.content);
+ setEditing(true);
+ };
+ const cancelEdit = () => {
+ setEditing(false);
+ setDraft(msg.content);
+ };
+ const submitEdit = () => {
+ const trimmed = draft.trim();
+ if (!trimmed || trimmed === msg.content) {
+ cancelEdit();
+ return;
+ }
+ if (typeof msg.id !== "number") return;
+ onEdit?.(msg.id, trimmed);
+ setEditing(false);
+ };
return (
<div key={`${msg.role}-${index}`} className="group flex justify-end">
- <div className="max-w-[75%] space-y-1.5">
- <div className="flex justify-end">
- <div className="relative">
- {!confirmDelete ? (
- <button
- type="button"
- onClick={() => setConfirmDelete(true)}
- className="rounded-md p-1 text-[var(--muted-foreground)] opacity-0 transition-opacity group-hover:opacity-100 hover:text-[var(--destructive)]"
- title={t("Delete")}
- >
- <Trash2 size={14} strokeWidth={1.5} />
- </button>
- ) : (
- <div className="flex items-center gap-1.5 text-[12px]">
- <span className="text-[var(--muted-foreground)]">
- {t("Delete this turn?")}
- </span>
- <button
- type="button"
- onClick={() => {
- if (msg.id != null) onDeleteTurn?.(msg.id);
- setConfirmDelete(false);
- }}
- className="rounded-md px-2 py-0.5 font-medium text-[var(--destructive)] hover:bg-[var(--destructive)]/10"
- >
- {t("Delete")}
- </button>
- <button
- type="button"
- onClick={() => setConfirmDelete(false)}
- className="rounded-md px-2 py-0.5 font-medium text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40"
- >
- {t("Cancel")}
- </button>
- </div>
- )}
- </div>
- </div>
+ <div className="flex max-w-[75%] flex-col items-end gap-1.5">
<div className="flex justify-end pr-1">
<span className="text-[10px] tracking-wide text-[var(--muted-foreground)]">
{t(getModeBadgeLabel(msg.capability))}
@@ -454,6 +538,48 @@ const UserMessage = memo(function UserMessage({
})}
</div>
)}
+ {editing ? (
+ <div className="w-[min(620px,75vw)] rounded-2xl border border-[var(--primary)]/40 bg-[var(--secondary)] px-3 py-2.5 text-[14px] leading-relaxed text-[var(--foreground)] shadow-sm">
+ <textarea
+ autoFocus
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ cancelEdit();
+ } else if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ submitEdit();
+ }
+ }}
+ rows={Math.min(8, Math.max(2, draft.split("\n").length))}
+ className="w-full resize-none border-0 bg-transparent text-[14px] leading-relaxed text-[var(--foreground)] outline-none focus:outline-none"
+ />
+ <div className="mt-1 flex items-center justify-between gap-2">
+ <span className="text-[10.5px] text-[var(--muted-foreground)]/80">
+ {t("Use the arrows below to switch between branches.")}
+ </span>
+ <div className="flex shrink-0 items-center gap-1.5">
+ <button
+ type="button"
+ onClick={cancelEdit}
+ className="rounded-md px-2 py-0.5 text-[11px] font-medium text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40"
+ >
+ {t("Cancel")}
+ </button>
+ <button
+ type="button"
+ onClick={submitEdit}
+ disabled={!draft.trim() || draft.trim() === msg.content}
+ className="rounded-md bg-[var(--primary)] px-2.5 py-0.5 text-[11px] font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ {t("Send")}
+ </button>
+ </div>
+ </div>
+ </div>
+ ) : (
<div className="rounded-2xl bg-[var(--secondary)] px-4 py-2.5 text-[14px] leading-relaxed text-[var(--foreground)] shadow-sm">
{(() => {
const snap = msg.requestSnapshot;
@@ -534,6 +660,33 @@ const UserMessage = memo(function UserMessage({
})()}
<div className="whitespace-pre-wrap">{msg.content}</div>
</div>
+ )}
+ {!editing && (onCopy || canEdit || siblingInfo) && msg.content && (
+ <div className="flex h-5 items-center justify-end gap-2 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100">
+ {siblingInfo && siblingInfo.total > 1 && (
+ <BranchNavigator
+ info={siblingInfo}
+ onSwitch={(childId) =>
+ onSwitchBranch?.(siblingInfo.parentId, childId)
+ }
+ />
+ )}
+ {onCopy && (
+ <RoughActionButton
+ icon={Copy}
+ label={t("Copy")}
+ onClick={() => void onCopy(msg.content)}
+ />
+ )}
+ {canEdit && (
+ <RoughActionButton
+ icon={Pencil}
+ label={t("Edit")}
+ onClick={startEdit}
+ />
+ )}
+ </div>
+ )}
</div>
</div>
);
@@ -729,6 +882,9 @@ export const ChatMessageList = memo(function ChatMessageList({
onPreviewAttachment,
onSwitchToManualMode,
onDeleteTurn,
+ selectedBranches,
+ onEditMessage,
+ onSwitchBranch,
}: {
messages: ChatMessageItem[];
isStreaming: boolean;
@@ -751,24 +907,36 @@ export const ChatMessageList = memo(function ChatMessageList({
// have to wire it.
onSwitchToManualMode?: () => void;
onDeleteTurn?: (messageId: number) => void;
+ /** Edit-branching: selected sibling at each branch point. */
+ selectedBranches?: Record<string, number>;
+ onEditMessage?: (messageId: number, newContent: string) => void;
+ onSwitchBranch?: (parentMessageId: number | null, childId: number) => void;
}) {
const { t } = useTranslation();
+ // Visible path: when no branching has happened the result is identical
+ // to the input. After an edit, sibling branches are filtered out so the
+ // UI shows exactly one continuous thread, with arrow nav exposed on the
+ // user message where branching diverges.
+ const { messages: visibleMessages, siblingsByMessageId } = useMemo(
+ () => buildVisiblePath(messages, selectedBranches),
+ [messages, selectedBranches],
+ );
const outlineStatusByIndex = useMemo(() => {
const map = new Map<number, "editing" | "researching" | "done">();
- for (let i = 0; i < messages.length; i++) {
- const msg = messages[i];
+ for (let i = 0; i < visibleMessages.length; i++) {
+ const msg = visibleMessages[i];
if (msg.role !== "assistant" || msg.capability !== "deep_research")
continue;
const resultEv = msg.events?.find((e) => e.type === "result");
const meta = resultEv?.metadata as Record<string, unknown> | undefined;
if (!meta?.outline_preview) continue;
- const hasFollowup = messages
+ const hasFollowup = visibleMessages
.slice(i + 1)
.some(
(m) => m.role === "assistant" && m.capability === "deep_research",
);
if (hasFollowup) {
- const followup = messages
+ const followup = visibleMessages
.slice(i + 1)
.find(
(m) => m.role === "assistant" && m.capability === "deep_research",
@@ -784,13 +952,13 @@ export const ChatMessageList = memo(function ChatMessageList({
}
}
return map;
- }, [messages, isStreaming]);
+ }, [visibleMessages, isStreaming]);
const messageRows = useMemo(() => {
// System messages are backend grounding (e.g. quiz follow-up context) and
// must never be rendered as a chat bubble. Filter them out defensively in
// addition to the hydration-time filter in UnifiedChatContext.
- return messages
+ return visibleMessages
.map((msg, index) => ({ msg, originalIndex: index }))
.filter(({ msg }) => msg.role !== "system")
.map(({ msg, originalIndex }) => {
@@ -802,37 +970,44 @@ export const ChatMessageList = memo(function ChatMessageList({
};
}
const pairedUserMessage =
- [...messages.slice(0, originalIndex)]
+ [...visibleMessages.slice(0, originalIndex)]
.reverse()
.find((previous) => previous.role === "user") ?? null;
return { msg, originalIndex, pairedUserMessage };
});
- }, [messages]);
+ }, [visibleMessages]);
const lastAssistantIndex = useMemo(() => {
- for (let idx = messages.length - 1; idx >= 0; idx -= 1) {
- if (messages[idx].role === "assistant") return idx;
+ for (let idx = visibleMessages.length - 1; idx >= 0; idx -= 1) {
+ if (visibleMessages[idx].role === "assistant") return idx;
}
return -1;
- }, [messages]);
+ }, [visibleMessages]);
return (
<>
{messageRows.map(({ msg, originalIndex, pairedUserMessage }) => {
const i = originalIndex;
if (msg.role === "user") {
+ const sib =
+ msg.id !== undefined ? siblingsByMessageId.get(msg.id) : undefined;
return (
<UserMessage
key={`${msg.role}-${i}`}
msg={msg}
index={i}
onPreviewAttachment={onPreviewAttachment}
- onDeleteTurn={onDeleteTurn}
+ onCopy={onCopyAssistantMessage}
+ onEdit={onEditMessage}
+ editDisabled={isStreaming}
+ siblingInfo={sib}
+ onSwitchBranch={onSwitchBranch}
/>
);
}
- const isActiveAssistant = isStreaming && i === messages.length - 1;
+ const isActiveAssistant =
+ isStreaming && i === visibleMessages.length - 1;
const msgDone = !isActiveAssistant;
const showActions = msgDone && hasVisibleMarkdownContent(msg.content);
const isLastAssistant = i === lastAssistantIndex;
@@ -843,6 +1018,11 @@ export const ChatMessageList = memo(function ChatMessageList({
Boolean(pairedUserMessage) &&
(!pairedUserMessage?.capability ||
pairedUserMessage?.capability === "chat");
+ const deletableTurnUserId =
+ msgDone && pairedUserMessage?.id != null && onDeleteTurn
+ ? pairedUserMessage.id
+ : null;
+ const showDelete = deletableTurnUserId != null;
// The "Answer now" affordance lives inside the trace panel for the
// currently-streaming assistant turn. We hand the panel a thin
@@ -887,22 +1067,29 @@ export const ChatMessageList = memo(function ChatMessageList({
onRetry={onRegenerateMessage}
onSwitchToManual={onSwitchToManualMode}
/>
- {(showActions || costSummary) && (
+ {(showActions || costSummary || showDelete) && (
<div className="mt-2 flex items-center">
- {showActions && (
- <div className="flex gap-2">
- <RoughActionButton
- icon={Copy}
- label={t("Copy")}
- onClick={() => void onCopyAssistantMessage(msg.content)}
- />
- {showRegenerate && (
+ {(showActions || showDelete) && (
+ <div className="flex items-center gap-2">
+ {showActions && (
+ <RoughActionButton
+ icon={Copy}
+ label={t("Copy")}
+ onClick={() => void onCopyAssistantMessage(msg.content)}
+ />
+ )}
+ {showActions && showRegenerate && (
<RoughActionButton
icon={RefreshCcw}
label={t("Regenerate")}
onClick={() => onRegenerateMessage()}
/>
)}
+ {showDelete && (
+ <DeleteTurnButton
+ onDelete={() => onDeleteTurn?.(deletableTurnUserId)}
+ />
+ )}
</div>
)}
{costSummary && (
diff --git a/web/components/chat/home/ComposerInput.tsx b/web/components/chat/home/ComposerInput.tsx
index b66f5c5f7..6094fc37d 100644
--- a/web/components/chat/home/ComposerInput.tsx
+++ b/web/components/chat/home/ComposerInput.tsx
@@ -4,8 +4,8 @@ import {
forwardRef,
memo,
useCallback,
+ useEffect,
useImperativeHandle,
- useLayoutEffect,
useRef,
useState,
type RefObject,
@@ -15,10 +15,10 @@ import ChatSpaceMenu, {
type ChatSpaceSelectionCounts,
} from "@/components/chat/space/ChatSpaceMenu";
import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";
+import { useAutoSizedTextarea } from "@/lib/use-auto-sized-textarea";
interface ComposerInputProps {
textareaRef: RefObject<HTMLTextAreaElement | null>;
- activeCapabilityKey: string;
isMathAnimatorMode: boolean;
isVisualizeMode: boolean;
// When true, parent has attachments/references queued and will accept a
@@ -55,7 +55,6 @@ export const ComposerInput = memo(
forwardRef<ComposerInputHandle, ComposerInputProps>(function ComposerInput(
{
textareaRef,
- activeCapabilityKey,
isMathAnimatorMode,
isVisualizeMode,
canSendEmpty,
@@ -101,15 +100,7 @@ export const ComposerInput = memo(
[setInputBoth, onInputChange],
);
- useLayoutEffect(() => {
- const el = textareaRef.current;
- if (!el) return;
- el.style.height = "28px";
- const next = Math.max(el.scrollHeight, 28);
- const bounded = Math.min(next, 200);
- el.style.height = `${bounded}px`;
- el.style.overflowY = next > 200 ? "auto" : "hidden";
- }, [input, activeCapabilityKey, textareaRef]);
+ useAutoSizedTextarea(textareaRef, input, { min: 28, max: 200 });
const handleInputChange = useCallback(
(e: React.ChangeEvent<HTMLTextAreaElement>) => {
@@ -207,10 +198,31 @@ export const ComposerInput = memo(
],
);
+ // Close the @-popup on outside click. Without this, clicking anywhere
+ // outside the popup or textarea left the menu hovering indefinitely.
+ // We bind on mousedown so the close fires before a synthetic click on
+ // a sibling button (e.g. the Tools menu) can re-open something else.
+ const popupRef = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ if (!showAtPopup) return;
+ const handler = (e: MouseEvent) => {
+ const target = e.target as Node | null;
+ if (!target) return;
+ if (popupRef.current?.contains(target)) return;
+ if (textareaRef.current?.contains(target)) return;
+ setShowAtPopup(false);
+ };
+ document.addEventListener("mousedown", handler);
+ return () => document.removeEventListener("mousedown", handler);
+ }, [showAtPopup, textareaRef]);
+
return (
<div className="px-4 pt-3.5 pb-2">
{showAtPopup && (
- <div className="absolute bottom-full left-0 z-[70] mb-2">
+ <div
+ ref={popupRef}
+ className="absolute bottom-full left-0 z-[70] mb-2"
+ >
<ChatSpaceMenu
variant="mention"
selectedCounts={selectedCounts}
@@ -228,6 +240,12 @@ export const ComposerInput = memo(
onClick={handleTextareaClick}
onPaste={onPaste}
rows={1}
+ // Cap input at 32k chars. A bigger paste (e.g. an entire textbook
+ // dumped via Cmd+V) would force a layout reflow on every keystroke
+ // and lock the page; the cap is a defensive guard, not a real
+ // product limit. Users hit by this cap should be using the
+ // attachment path, not the composer body.
+ maxLength={32000}
suppressHydrationWarning
placeholder={
isMathAnimatorMode
diff --git a/web/components/chat/home/SimpleComposerInput.tsx b/web/components/chat/home/SimpleComposerInput.tsx
index a0c625d76..e893ede21 100644
--- a/web/components/chat/home/SimpleComposerInput.tsx
+++ b/web/components/chat/home/SimpleComposerInput.tsx
@@ -3,13 +3,13 @@
import {
memo,
useCallback,
- useLayoutEffect,
useRef,
useState,
type RefObject,
} from "react";
import { useTranslation } from "react-i18next";
import { shouldSubmitOnEnter } from "@/lib/composer-keyboard";
+import { useAutoSizedTextarea } from "@/lib/use-auto-sized-textarea";
interface SimpleComposerInputProps {
textareaRef: RefObject<HTMLTextAreaElement | null>;
@@ -26,13 +26,7 @@ export const SimpleComposerInput = memo(function SimpleComposerInput({
const [input, setInput] = useState("");
const isComposingRef = useRef(false);
- useLayoutEffect(() => {
- const el = textareaRef.current;
- if (!el) return;
- el.style.height = "auto";
- const next = Math.max(el.scrollHeight, 42);
- el.style.height = `${Math.min(next, 200)}px`;
- }, [input, textareaRef]);
+ useAutoSizedTextarea(textareaRef, input, { min: 42, max: 200 });
const handleInputChange = useCallback(
(e: React.ChangeEvent<HTMLTextAreaElement>) => {
@@ -77,6 +71,9 @@ export const SimpleComposerInput = memo(function SimpleComposerInput({
onCompositionEnd={handleCompositionEnd}
placeholder={t("Type a message...")}
rows={1}
+ // Defensive cap — see ComposerInput for the same guard. Anything beyond
+ // this size belongs in an attachment, not in the textarea body.
+ maxLength={32000}
disabled={disabled}
className="flex-1 resize-none rounded-xl border border-[var(--border)] bg-transparent px-4 py-2.5 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] disabled:opacity-50 placeholder:text-[var(--muted-foreground)]/40"
style={{ minHeight: 42 }}
diff --git a/web/components/chat/home/TracePanels.tsx b/web/components/chat/home/TracePanels.tsx
index 3627cdf85..ccad24c7c 100644
--- a/web/components/chat/home/TracePanels.tsx
+++ b/web/components/chat/home/TracePanels.tsx
@@ -20,6 +20,10 @@ import {
} from "lucide-react";
import { useTranslation } from "react-i18next";
import MarkdownRenderer from "@/components/common/MarkdownRenderer";
+import {
+ formatTurnDuration,
+ getTurnDurationSeconds,
+} from "@/lib/trace-timing";
import type { StreamEvent } from "@/lib/unified-ws";
type TraceMetadata = {
@@ -32,6 +36,10 @@ type TraceMetadata = {
trace_kind?: string;
trace_id?: string;
call_state?: string;
+ // 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."
+ absorbed_into_final?: boolean;
step_id?: string;
round?: number;
query?: string;
@@ -142,37 +150,6 @@ function getTraceGroup(events: StreamEvent[]) {
return "";
}
-function getTraceDurationLabel(events: StreamEvent[]) {
- let start: number | null = null;
- let end: number | null = null;
- for (const event of events) {
- const state = String(getTraceMeta(event).call_state || "");
- if (state === "running" && start === null) start = event.timestamp;
- if ((state === "complete" || state === "error") && end === null)
- end = event.timestamp;
- }
- if (start === null || end === null) return "";
- const seconds = Math.max(1, Math.round(end - start));
- return `${seconds}s`;
-}
-
-function getTraceStartTimestamp(events: StreamEvent[]) {
- for (const event of events) {
- const state = String(getTraceMeta(event).call_state || "");
- if (state === "running") return event.timestamp;
- }
- return null;
-}
-
-function getActiveTraceDurationSeconds(
- events: StreamEvent[],
- nowSeconds: number,
-) {
- const start = getTraceStartTimestamp(events);
- if (start === null) return null;
- return Math.max(1, Math.round(nowSeconds - start));
-}
-
function isTracePending(events: StreamEvent[]) {
let hasRunning = false;
let hasTerminal = false;
@@ -186,7 +163,6 @@ function isTracePending(events: StreamEvent[]) {
function getTraceHeader(
events: StreamEvent[],
- nowSeconds?: number,
nested?: boolean,
t: (key: string, opts?: Record<string, unknown>) => string = (k) => k,
) {
@@ -195,10 +171,6 @@ function getTraceHeader(
const group = getTraceGroup(events);
const kind = getTraceCallKind(events);
const meta = getTraceMeta(events[0]);
- const duration =
- kind === "math_render_output" && isTracePending(events) && nowSeconds
- ? `${getActiveTraceDurationSeconds(events, nowSeconds) ?? 1}s`
- : getTraceDurationLabel(events);
let title = label;
if (
@@ -244,9 +216,7 @@ function getTraceHeader(
}
}
- return duration
- ? t("{{title}} for {{duration}}", { title, duration })
- : title;
+ return title;
}
function getTraceText(
@@ -302,6 +272,14 @@ function buildDisplayItems(traceGroups: TraceItem[]): DisplayItem[] {
const kind = getTraceCallKind(group.events);
if (kind === "llm_final_response") continue;
+ // The chat pipeline streams the final iteration's prose as ``thinking``
+ // events into a sub-trace AND re-emits it as a ``llm_final_response``
+ // content event. The sub-trace itself is tagged ``absorbed_into_final``
+ // on its terminal progress event so we drop it here — otherwise the
+ // final answer would appear twice (once in the trace box, once in the
+ // body).
+ if (group.events.some((e) => getTraceMeta(e).absorbed_into_final === true))
+ continue;
if (groupType === "react_round" && stepId) {
if (stepId_ === stepId) {
@@ -322,25 +300,6 @@ function buildDisplayItems(traceGroups: TraceItem[]): DisplayItem[] {
return items;
}
-function getStepGroupDuration(traces: TraceItem[]): string {
- let start: number | null = null;
- let end: number | null = null;
- for (const trace of traces) {
- for (const event of trace.events) {
- const state = String(getTraceMeta(event).call_state || "");
- if (state === "running" && (start === null || event.timestamp < start))
- start = event.timestamp;
- if (
- (state === "complete" || state === "error") &&
- (end === null || event.timestamp > end)
- )
- end = event.timestamp;
- }
- }
- if (start === null || end === null) return "";
- return `${Math.max(1, Math.round(end - start))}s`;
-}
-
/* ------------------------------------------------------------------ */
/* Primitive UI pieces */
/* ------------------------------------------------------------------ */
@@ -714,7 +673,6 @@ export function CallTracePanel({
nested?: boolean;
}) {
const { t } = useTranslation();
- const [nowSeconds, setNowSeconds] = useState(() => Date.now() / 1000);
// Sticky-bottom auto-scroll for the outer trace card. While the user is
// pinned near the bottom we keep them there as new trace events stream in;
@@ -740,15 +698,6 @@ export function CallTracePanel({
stickRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 30;
}, []);
- useEffect(() => {
- if (!isStreaming) return;
- const timer = window.setInterval(
- () => setNowSeconds(Date.now() / 1000),
- 1000,
- );
- return () => window.clearInterval(timer);
- }, [isStreaming]);
-
const traceGroups = useMemo(() => {
const groups: TraceItem[] = [];
const indexById = new Map<string, number>();
@@ -773,7 +722,12 @@ export function CallTracePanel({
[traceGroups],
);
- if (!traceGroups.length) return null;
+ // Hide the outer container entirely when no sub-trace ends up being
+ // rendered. ``traceGroups`` can be non-empty even when every group is
+ // filtered out by ``buildDisplayItems`` (final-response groups and groups
+ // tagged ``absorbed_into_final``) — in that case we used to draw an
+ // empty bordered box. Check the materialised displayItems instead.
+ if (!displayItems.length) return null;
function renderTraceRow(
{ callId, events: callEvents }: TraceItem,
@@ -786,7 +740,7 @@ export function CallTracePanel({
const role = getTraceRole(callEvents);
const group = getTraceGroup(callEvents);
const kind = getTraceCallKind(callEvents);
- const header = getTraceHeader(callEvents, nowSeconds, nested, t);
+ const header = getTraceHeader(callEvents, nested, t);
const active =
Boolean(isStreaming) && isGloballyLast && isTracePending(callEvents);
const isFinalResponse = kind === "llm_final_response";
@@ -876,9 +830,6 @@ export function CallTracePanel({
Boolean(isStreaming) &&
isLastDisplayItem &&
isTracePending(lastTrace.events);
- const stepDuration = isActiveStep
- ? ""
- : getStepGroupDuration(item.traces);
return (
<ExpandableDetails
@@ -891,10 +842,9 @@ export function CallTracePanel({
className="shrink-0 transition-transform group-open/step:rotate-180"
/>
<Sparkles size={12} strokeWidth={1.6} className="shrink-0" />
- <span>Step {item.stepId}</span>
+ <span>{t("Step {{n}}", { n: item.stepId })}</span>
<span className="text-[11px] opacity-60">
- {roundCount} {roundCount === 1 ? "round" : "rounds"}
- {stepDuration ? ` · ${stepDuration}` : ""}
+ {t("{{count}} round", { count: roundCount })}
</span>
{isActiveStep && (
<Loader2 size={11} className="animate-spin" />
@@ -917,7 +867,6 @@ export function CallTracePanel({
if (trGroup === "react_round") {
const roundNum = trMeta.round;
- const duration = getTraceDurationLabel(trace.events);
const thoughtText = getTraceText(trace.events, [
"thinking",
]);
@@ -942,13 +891,8 @@ export function CallTracePanel({
)}
<div className="mb-1 flex items-center gap-1.5 not-italic text-[11px]">
<span className="font-bold uppercase tracking-[0.08em] text-[var(--muted-foreground)]">
- Round {roundNum}
+ {t("Round {{n}}", { n: roundNum })}
</span>
- {duration && (
- <span className="font-normal text-[var(--muted-foreground)]/40">
- {duration}
- </span>
- )}
{roundActive && (
<Loader2 size={10} className="animate-spin" />
)}
@@ -1018,12 +962,7 @@ export function CallTracePanel({
}
/* Non-round trace (retrieve, tool, etc.) — inline within the step */
- const inlineHeader = getTraceHeader(
- trace.events,
- nowSeconds,
- true,
- t,
- );
+ const inlineHeader = getTraceHeader(trace.events, true, t);
const progressEvts = trace.events.filter(
(e) =>
e.type === "progress" &&
@@ -1287,6 +1226,16 @@ export function StreamingStatus({
}) {
const { t } = useTranslation();
const hasFinalContent = Boolean(content && content.trim().length > 0);
+ const [nowSeconds, setNowSeconds] = useState(() => Date.now() / 1000);
+ useEffect(() => {
+ if (!isStreaming) return;
+ const timer = window.setInterval(
+ () => setNowSeconds(Date.now() / 1000),
+ 1000,
+ );
+ return () => window.clearInterval(timer);
+ }, [isStreaming]);
+
// Only render once we either have a streaming turn OR a completed turn that
// produced visible content — empty placeholders (e.g. system message
// shells) shouldn't show a status row.
@@ -1305,6 +1254,18 @@ export function StreamingStatus({
: mode === "responded"
? t("DeepTutor responded.")
: t("DeepTutor reasoning…");
+
+ // Single turn-level clock. Ticks every second while the turn is in
+ // flight and freezes on the final elapsed time once the answer ends —
+ // replaces the per-sub-trace duration chips that used to live inside
+ // the trace card.
+ const turnSeconds = getTurnDurationSeconds(
+ events,
+ nowSeconds,
+ Boolean(isStreaming),
+ );
+ const durationLabel =
+ turnSeconds != null ? formatTurnDuration(turnSeconds) : null;
// Static label after the answer is done — no breathing animation. The other
// three states are live so they pulse to signal ongoing work. The icon also
// stretches/contracts on its own cycle (out of phase with the opacity fade)
@@ -1332,6 +1293,11 @@ export function StreamingStatus({
className={`${breathingClass} ${markPulseClass} shrink-0 text-[var(--primary)]/90`}
/>
<span className={breathingClass}>{label}</span>
+ {durationLabel ? (
+ <span className="text-[12px] font-medium tabular-nums text-[var(--muted-foreground)]/55">
+ · {durationLabel}
+ </span>
+ ) : null}
{collapsible ? (
<ChevronDown
size={14}
@@ -1344,12 +1310,19 @@ export function StreamingStatus({
</>
);
+ // role="status" + aria-live="polite" surfaces mode transitions
+ // (reasoning → tool using → responding → responded) to screen readers
+ // without barging in on the user. aria-atomic="false" so only the changed
+ // label is announced rather than the whole row each tick.
if (collapsible && onToggle) {
return (
<button
type="button"
onClick={onToggle}
aria-expanded={expanded ? "true" : "false"}
+ role="status"
+ aria-live="polite"
+ aria-atomic="false"
className={`mb-3 -ml-1 flex items-center gap-2.5 rounded-md px-1 py-0.5 text-[14px] font-semibold leading-none transition-colors hover:bg-[var(--muted)]/40 ${textColor}`}
>
{rowContent}
@@ -1359,6 +1332,9 @@ export function StreamingStatus({
return (
<div
+ role="status"
+ aria-live="polite"
+ aria-atomic="false"
className={`mb-3 flex items-center gap-2.5 text-[14px] font-semibold leading-none ${textColor}`}
>
{rowContent}
@@ -1381,10 +1357,27 @@ export function TraceSurface({
isStreaming?: boolean;
content?: string;
}) {
- const hasCallTrace = useMemo(
- () => events.some((event) => Boolean(event.metadata?.call_id)),
- [events],
- );
+ // ``hasCallTrace`` decides whether the status row gets a clickable
+ // chevron AND whether the trace panel below is mounted. We must filter
+ // out groups that CallTracePanel itself would discard — otherwise the
+ // chevron toggles a panel that's intentionally empty (final-response
+ // only, or all reasoning sub-traces absorbed into the final answer).
+ const hasCallTrace = useMemo(() => {
+ const seen = new Map<string, { hasFinal: boolean; hasAbsorbed: boolean }>();
+ for (const event of events) {
+ const meta = (event.metadata ?? {}) as Record<string, unknown>;
+ const cid = String(meta.call_id || "");
+ if (!cid) continue;
+ const entry = seen.get(cid) ?? { hasFinal: false, hasAbsorbed: false };
+ if (meta.call_kind === "llm_final_response") entry.hasFinal = true;
+ if (meta.absorbed_into_final === true) entry.hasAbsorbed = true;
+ seen.set(cid, entry);
+ }
+ for (const { hasFinal, hasAbsorbed } of seen.values()) {
+ if (!hasFinal && !hasAbsorbed) return true;
+ }
+ return false;
+ }, [events]);
const [expanded, setExpanded] = useState(true);
const toggle = useCallback(() => setExpanded((prev) => !prev), []);
diff --git a/web/components/chat/space/ChatSpaceMenu.tsx b/web/components/chat/space/ChatSpaceMenu.tsx
index 4e4382e9d..190e8ebdc 100644
--- a/web/components/chat/space/ChatSpaceMenu.tsx
+++ b/web/components/chat/space/ChatSpaceMenu.tsx
@@ -1,6 +1,6 @@
"use client";
-import { memo } from "react";
+import { memo, useEffect, useRef, useState } from "react";
import { BookOpen } from "lucide-react";
import { useTranslation } from "react-i18next";
import { SPACE_ITEMS } from "@/lib/space-items";
@@ -66,6 +66,7 @@ export default memo(function ChatSpaceMenu({
}: ChatSpaceMenuProps) {
const { t } = useTranslation();
const compact = variant === "toolbar";
+ const isMention = variant === "mention";
// Render the items in a fixed, hand-tuned order so the menu always reads
// the same regardless of how SPACE_ITEMS may be reordered for navigation.
@@ -80,21 +81,81 @@ export default memo(function ChatSpaceMenu({
: SPACE_ITEMS.find((it) => it.key === key)!,
).filter(Boolean);
+ // Active row index for keyboard navigation. Only meaningful in the
+ // mention variant — the toolbar variant is mouse/click driven.
+ const [activeIdx, setActiveIdx] = useState(0);
+ // The keydown handler closes over `activeIdx`/`items`/`onSelectItem`;
+ // stash them in refs so the document-level listener identity stays
+ // stable and we don't re-attach it on every render. Refs are synced
+ // in an effect (not during render) to satisfy `react-hooks/refs`.
+ const activeIdxRef = useRef(activeIdx);
+ const itemsRef = useRef(items);
+ const onSelectItemRef = useRef(onSelectItem);
+ useEffect(() => {
+ activeIdxRef.current = activeIdx;
+ }, [activeIdx]);
+ useEffect(() => {
+ itemsRef.current = items;
+ }, [items]);
+ useEffect(() => {
+ onSelectItemRef.current = onSelectItem;
+ }, [onSelectItem]);
+
+ // Reset to the top whenever the menu first mounts (i.e. user typed `@`
+ // and the popup appeared). The parent unmounts/remounts this component
+ // on each open, so a fresh `useState(0)` initial value already gives us
+ // the right behavior — no extra effect needed.
+
+ // Attach a document-level keydown so Arrow/Enter while the textarea
+ // still has focus drive the menu. The textarea's own handleKeyDown
+ // continues to handle Escape and submit.
+ useEffect(() => {
+ if (!isMention) return;
+ const handler = (e: KeyboardEvent) => {
+ const list = itemsRef.current;
+ if (list.length === 0) return;
+ if (e.key === "ArrowDown") {
+ e.preventDefault();
+ setActiveIdx((i) => (i + 1) % list.length);
+ } else if (e.key === "ArrowUp") {
+ e.preventDefault();
+ setActiveIdx((i) => (i - 1 + list.length) % list.length);
+ } else if (e.key === "Enter") {
+ const item = list[activeIdxRef.current];
+ if (!item) return;
+ e.preventDefault();
+ onSelectItemRef.current(item.key as SelectableSpaceKey);
+ }
+ };
+ document.addEventListener("keydown", handler);
+ return () => document.removeEventListener("keydown", handler);
+ }, [isMention]);
+
return (
<div
+ role={isMention ? "listbox" : undefined}
+ aria-label={isMention ? t("Reference space") : undefined}
className={`rounded-xl border border-[var(--border)] bg-[var(--popover)] shadow-lg backdrop-blur-md ${
compact ? "w-[260px] py-1.5" : "w-64 p-2"
}`}
>
<div className={compact ? "space-y-0.5" : "space-y-1"}>
- {items.map(({ key, label, description, icon: Icon }) => {
+ {items.map(({ key, label, description, icon: Icon }, idx) => {
const count = countFor(key as SelectableSpaceKey, selectedCounts);
+ const isActive = isMention && idx === activeIdx;
return (
<button
key={key}
type="button"
+ role={isMention ? "option" : undefined}
+ aria-selected={isMention ? isActive : undefined}
+ onMouseEnter={
+ isMention ? () => setActiveIdx(idx) : undefined
+ }
onClick={() => onSelectItem(key as SelectableSpaceKey)}
- className={`flex w-full items-center gap-2.5 text-left transition-colors hover:bg-[var(--muted)]/40 ${
+ className={`flex w-full items-center gap-2.5 text-left transition-colors ${
+ isActive ? "bg-[var(--muted)]/60" : "hover:bg-[var(--muted)]/40"
+ } ${
compact
? "px-3 py-1.5 text-[12px]"
: "rounded-xl px-3 py-2.5 text-[13px]"
diff --git a/web/components/common/AssistantResponse.tsx b/web/components/common/AssistantResponse.tsx
index 5d39b2c31..a0ae5ec5e 100644
--- a/web/components/common/AssistantResponse.tsx
+++ b/web/components/common/AssistantResponse.tsx
@@ -34,8 +34,18 @@ export default function AssistantResponse({
if (!hasRenderableSegment) return null;
+ // role="article" lets screen-reader users locate each assistant turn as a
+ // structured landmark. aria-live="polite" + aria-atomic="false" announces
+ // streamed-in content as the user pauses, without re-reading the whole
+ // bubble each token. Together this is the minimal pattern that turns a
+ // silent stream into an audible one.
return (
- <div className={className}>
+ <div
+ role="article"
+ aria-live="polite"
+ aria-atomic="false"
+ className={className}
+ >
{segments.map((segment, index) => {
if (segment.kind === "think") {
return (
diff --git a/web/components/common/MarkdownRenderer.tsx b/web/components/common/MarkdownRenderer.tsx
index 061832645..25dfe62ed 100644
--- a/web/components/common/MarkdownRenderer.tsx
+++ b/web/components/common/MarkdownRenderer.tsx
@@ -23,8 +23,15 @@ export interface MarkdownRendererProps {
trackSourceLines?: boolean;
}
+// Detection during streaming has a subtle correctness requirement: it must
+// be monotonic. Once `true`, it should stay `true` as more tokens arrive so
+// the renderer never downgrades from Rich back to Simple (which would cause
+// a full subtree remount and a visible flash). The patterns below match
+// *opening* tokens — `$$`, `\(`, `\[`, ` ``` ` — rather than requiring a
+// matched close. A partial fence still gets the rich treatment, then the
+// closer arriving later is just more append-only content with no swap.
function detectMathContent(content: string): boolean {
- if (/(^|[^\\])\$\$[\s\S]+?\$\$/.test(content)) return true;
+ if (/(^|[^\\])\$\$/.test(content)) return true;
if (/\\\(|\\\[/.test(content)) return true;
// Single-dollar inline math containing LaTeX commands (\cmd) or math operators ({}_^)
if (
@@ -37,7 +44,10 @@ function detectMathContent(content: string): boolean {
}
function detectCodeContent(content: string): boolean {
- return /```[A-Za-z0-9_+#.-]+/.test(content);
+ // Match any opening triple-backtick, even before the language identifier
+ // arrives. Otherwise streaming flips Simple→Rich the moment the language
+ // tag lands a few tokens after the fence.
+ return /```/.test(content);
}
function detectMermaidContent(content: string): boolean {
@@ -65,6 +75,11 @@ export default function MarkdownRenderer({
const resolvedEnableCode = enableCode ?? detectCodeContent(content);
const resolvedEnableMermaid = enableMermaid ?? detectMermaidContent(content);
const resolvedAllowHtml = allowHtml ?? detectHtmlContent(content);
+ // Detection above is intentionally monotonic — once any of the rich
+ // triggers fire, more tokens never un-fire them. Combined with the
+ // append-only nature of streaming content this gives us a stable
+ // Simple→Rich one-way transition (the Rich subtree mounts once and
+ // stays). No additional lock state is needed.
const shouldUseRich =
variant !== "trace" &&
(trackSourceLines ||
diff --git a/web/components/common/Modal.tsx b/web/components/common/Modal.tsx
index 56065de36..abf245f8f 100644
--- a/web/components/common/Modal.tsx
+++ b/web/components/common/Modal.tsx
@@ -1,7 +1,8 @@
"use client";
-import { useEffect, useCallback } from "react";
+import { useEffect, useId, useRef } from "react";
import { X } from "lucide-react";
+import { useTranslation } from "react-i18next";
interface ModalProps {
isOpen: boolean;
@@ -23,8 +24,18 @@ const widthClasses = {
xl: "w-[800px]",
};
+const FOCUSABLE_SELECTOR =
+ 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, [tabindex]:not([tabindex="-1"]), [contenteditable="true"]';
+
/**
- * Shared Modal base component
+ * Shared Modal base component.
+ *
+ * Provides the full dialog-behavior contract: Escape close, optional
+ * backdrop click close, body scroll lock, role=dialog + aria-modal, initial
+ * focus into the dialog, focus restoration on close, and a focus trap that
+ * keeps Tab cycling inside the dialog. The contract matches PickerShell so
+ * Modal and the picker overlays behave the same way from an a11y / keyboard
+ * perspective.
*/
export default function Modal({
isOpen,
@@ -38,54 +49,114 @@ export default function Modal({
closeOnEscape = true,
showCloseButton = true,
}: ModalProps) {
- // Handle escape key
- const handleEscape = useCallback(
- (e: KeyboardEvent) => {
- if (closeOnEscape && e.key === "Escape") {
- onClose();
- }
- },
- [closeOnEscape, onClose],
- );
+ const { t } = useTranslation();
+ const dialogRef = useRef<HTMLDivElement>(null);
+ const previouslyFocusedRef = useRef<HTMLElement | null>(null);
+ const titleId = useId();
+ // Body scroll lock + remember trigger for focus restoration on close.
useEffect(() => {
- if (isOpen) {
- document.addEventListener("keydown", handleEscape);
- // Prevent body scroll when modal is open
- document.body.style.overflow = "hidden";
- }
+ if (!isOpen) return;
+ previouslyFocusedRef.current =
+ (document.activeElement as HTMLElement | null) ?? null;
+ const prev = document.body.style.overflow;
+ document.body.style.overflow = "hidden";
return () => {
- document.removeEventListener("keydown", handleEscape);
- document.body.style.overflow = "";
+ document.body.style.overflow = prev;
};
- }, [isOpen, handleEscape]);
+ }, [isOpen]);
+
+ // Initial focus on the next frame so the dialog DOM is settled.
+ useEffect(() => {
+ if (!isOpen) return;
+ const id = window.requestAnimationFrame(() => {
+ const node = dialogRef.current;
+ if (!node) return;
+ const explicit = node.querySelector<HTMLElement>("[data-autofocus]");
+ const target =
+ explicit ?? node.querySelector<HTMLElement>(FOCUSABLE_SELECTOR);
+ target?.focus();
+ });
+ return () => window.cancelAnimationFrame(id);
+ }, [isOpen]);
+
+ // Restore focus to the trigger on close.
+ useEffect(() => {
+ if (isOpen) return;
+ const trigger = previouslyFocusedRef.current;
+ if (trigger && document.contains(trigger)) {
+ trigger.focus();
+ }
+ previouslyFocusedRef.current = null;
+ }, [isOpen]);
if (!isOpen) return null;
- const handleBackdropClick = (e: React.MouseEvent) => {
+ const handleKeyDown = (e: React.KeyboardEvent) => {
+ if (closeOnEscape && e.key === "Escape") {
+ e.stopPropagation();
+ onClose();
+ return;
+ }
+ if (e.key !== "Tab") return;
+ const node = dialogRef.current;
+ if (!node) return;
+ const focusables = Array.from(
+ node.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
+ );
+ if (focusables.length === 0) return;
+ const first = focusables[0];
+ const last = focusables[focusables.length - 1];
+ const active = document.activeElement as HTMLElement | null;
+ if (e.shiftKey && active === first) {
+ e.preventDefault();
+ last.focus();
+ } else if (!e.shiftKey && active === last) {
+ e.preventDefault();
+ first.focus();
+ }
+ };
+
+ const handleBackdropMouseDown = (e: React.MouseEvent) => {
if (closeOnBackdrop && e.target === e.currentTarget) {
onClose();
}
};
+ const hasTitle = !!title || !!titleIcon;
+
return (
<div
+ // mousedown rather than click so dragging out of an input doesn't
+ // accidentally close on mouseup.
+ onMouseDown={handleBackdropMouseDown}
className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 animate-in fade-in"
- onClick={handleBackdropClick}
>
<div
+ ref={dialogRef}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={hasTitle ? titleId : undefined}
+ aria-label={hasTitle ? undefined : (title ?? t("Dialog"))}
+ onKeyDown={handleKeyDown}
+ onMouseDown={(e) => e.stopPropagation()}
className={`bg-[var(--card)] border border-[var(--border)] rounded-2xl shadow-2xl ${widthClasses[width]} max-h-[90vh] flex flex-col animate-in zoom-in-95`}
>
{/* Header */}
- {(title || titleIcon || showCloseButton) && (
+ {(hasTitle || showCloseButton) && (
<div className="p-4 border-b border-[var(--border)] flex items-center justify-between shrink-0">
- <h3 className="font-bold text-[var(--foreground)] flex items-center gap-2">
+ <h3
+ id={titleId}
+ className="font-bold text-[var(--foreground)] flex items-center gap-2"
+ >
{titleIcon}
{title}
</h3>
{showCloseButton ? (
<button
+ type="button"
onClick={onClose}
+ aria-label={t("Close")}
className="p-1 hover:bg-[var(--muted)] rounded-lg transition-colors"
>
<X className="w-5 h-5 text-[var(--muted-foreground)]" />
diff --git a/web/components/common/PickerShell.tsx b/web/components/common/PickerShell.tsx
new file mode 100644
index 000000000..c2ded8387
--- /dev/null
+++ b/web/components/common/PickerShell.tsx
@@ -0,0 +1,198 @@
+"use client";
+
+import { useCallback, useEffect, useRef } from "react";
+
+/**
+ * Behavioral wrapper for fullscreen pickers (NotebookRecordPicker,
+ * HistorySessionPicker, MemoryPicker, QuestionBankPicker, SkillsPicker,
+ * BookReferencePicker, SaveToNotebookModal, …). Each of those was rolled
+ * by hand and skipped the basic dialog-behavior contract — Escape, backdrop
+ * click, body scroll lock, focus trap, ARIA roles. This component lifts
+ * that contract into one place so the pickers themselves only have to
+ * render their *content*.
+ *
+ * Design notes:
+ * - The shell renders the centered backdrop. Callers render the picker
+ * card as `children` — they keep full control over the card's chrome,
+ * width, padding, etc. (see existing pickers).
+ * - `onClose` fires on Escape, on backdrop click, and is reachable
+ * programmatically (e.g. a Cancel button inside the card).
+ * - Focus management: on open we move focus to the first focusable element
+ * inside the dialog (typically the search input). On close we restore
+ * focus to wherever it was when the picker opened. This is what users
+ * expect from a modal but every hand-rolled picker had skipped it.
+ * - Focus trap: Tab from the last focusable element wraps to the first,
+ * Shift+Tab from the first wraps to the last. The dialog is the only
+ * thing screen-reader / keyboard users can interact with while open.
+ */
+export interface PickerShellProps {
+ open: boolean;
+ onClose: () => void;
+ children: React.ReactNode;
+ /**
+ * id of an element inside `children` that names the dialog. Required for
+ * proper `aria-labelledby`. If the picker has no visible title, pass an
+ * `aria-label` instead via `ariaLabel`.
+ */
+ labelledBy?: string;
+ ariaLabel?: string;
+ /**
+ * Z-index for the backdrop. Defaults to 85 to match the existing
+ * picker convention; raise it if stacking under another picker.
+ */
+ zIndex?: number;
+ /**
+ * Outer container layout. Most pickers center their card; some use a
+ * full-bleed layout. Defaults to centered.
+ */
+ align?: "center" | "start";
+ /**
+ * Extra classes applied to the inner backdrop wrapper. Allows pickers
+ * to opt out of the default `flex items-center justify-center` for
+ * bespoke layouts.
+ */
+ className?: string;
+ /**
+ * Override the default `bg-black/40` backdrop. Pass any opacity / blur /
+ * tint combo. Useful for pickers that want a frosted-glass look or a
+ * lighter scrim.
+ */
+ backdropClass?: string;
+}
+
+const FOCUSABLE_SELECTOR =
+ 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, [tabindex]:not([tabindex="-1"]), [contenteditable="true"]';
+
+export default function PickerShell({
+ open,
+ onClose,
+ children,
+ labelledBy,
+ ariaLabel,
+ zIndex = 85,
+ align = "center",
+ className,
+ backdropClass = "bg-black/40",
+}: PickerShellProps) {
+ const dialogRef = useRef<HTMLDivElement>(null);
+ const previouslyFocusedRef = useRef<HTMLElement | null>(null);
+
+ // Stash the focused element when the picker opens so we can return focus
+ // there on close. Reset on every open so reopening returns to the latest
+ // trigger.
+ useEffect(() => {
+ if (!open) return;
+ previouslyFocusedRef.current =
+ (document.activeElement as HTMLElement | null) ?? null;
+ }, [open]);
+
+ // Body scroll lock. Preserve the user's prior overflow so we don't trample
+ // a parent that already had a lock in place.
+ useEffect(() => {
+ if (!open) return;
+ const prev = document.body.style.overflow;
+ document.body.style.overflow = "hidden";
+ return () => {
+ document.body.style.overflow = prev;
+ };
+ }, [open]);
+
+ // Move initial focus into the dialog on open. We defer to the next frame
+ // so the rendered card has measured + focusable elements are in the DOM.
+ useEffect(() => {
+ if (!open) return;
+ const id = window.requestAnimationFrame(() => {
+ const node = dialogRef.current;
+ if (!node) return;
+ // Prefer an explicit autofocus marker, then the first focusable child.
+ const explicit = node.querySelector<HTMLElement>("[data-autofocus]");
+ const target =
+ explicit ?? node.querySelector<HTMLElement>(FOCUSABLE_SELECTOR);
+ target?.focus();
+ });
+ return () => window.cancelAnimationFrame(id);
+ }, [open]);
+
+ // Restore focus to the trigger on close. Guarded by document.contains so
+ // we never call focus() on a detached element (e.g. the trigger was
+ // unmounted while the picker was open).
+ useEffect(() => {
+ if (open) return;
+ const trigger = previouslyFocusedRef.current;
+ if (trigger && document.contains(trigger)) {
+ trigger.focus();
+ }
+ previouslyFocusedRef.current = null;
+ }, [open]);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (e.key === "Escape") {
+ e.stopPropagation();
+ onClose();
+ return;
+ }
+ if (e.key !== "Tab") return;
+ // Focus trap. Cycle within the dialog so Tab can never escape into
+ // the page chrome behind us.
+ const node = dialogRef.current;
+ if (!node) return;
+ const focusables = Array.from(
+ node.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
+ ).filter((el) => !el.hasAttribute("data-focus-skip"));
+ if (focusables.length === 0) return;
+ const first = focusables[0];
+ const last = focusables[focusables.length - 1];
+ const active = document.activeElement as HTMLElement | null;
+ if (e.shiftKey && active === first) {
+ e.preventDefault();
+ last.focus();
+ } else if (!e.shiftKey && active === last) {
+ e.preventDefault();
+ first.focus();
+ }
+ },
+ [onClose],
+ );
+
+ const handleBackdropMouseDown = useCallback(
+ (e: React.MouseEvent) => {
+ if (e.target === e.currentTarget) {
+ onClose();
+ }
+ },
+ [onClose],
+ );
+
+ if (!open) return null;
+
+ const alignmentClass =
+ align === "center" ? "items-center justify-center" : "items-start";
+
+ return (
+ <div
+ // Backdrop. mousedown rather than click so dragging out of a search
+ // input doesn't dismiss the picker on the eventual mouseup.
+ onMouseDown={handleBackdropMouseDown}
+ className={`fixed inset-0 flex ${backdropClass} ${alignmentClass} ${
+ className ?? ""
+ }`}
+ style={{ zIndex }}
+ >
+ <div
+ ref={dialogRef}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={labelledBy}
+ aria-label={labelledBy ? undefined : ariaLabel}
+ onKeyDown={handleKeyDown}
+ // Stop propagation so a click *inside* the dialog never reaches the
+ // backdrop's mousedown handler above. Width/layout decisions stay
+ // with the picker that renders the card inside.
+ onMouseDown={(e) => e.stopPropagation()}
+ >
+ {children}
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/common/SimpleMarkdownRenderer.tsx b/web/components/common/SimpleMarkdownRenderer.tsx
index 1a9f286c8..b4786cb81 100644
--- a/web/components/common/SimpleMarkdownRenderer.tsx
+++ b/web/components/common/SimpleMarkdownRenderer.tsx
@@ -310,11 +310,15 @@ export default function SimpleMarkdownRenderer({
const raw = String(children).replace(/\n$/, "");
if (raw.includes("\n")) {
+ // Use the same #1f2937 / #e5e7eb palette as RichMarkdownRenderer and
+ // RichCodeBlock so any stream-time fallback from Rich → Simple (or
+ // first-paint via Simple before the rich lock engages) looks visually
+ // identical to its rich counterpart.
return (
<div
- className={`md-code-block ${gap} overflow-hidden rounded-xl border border-[var(--border)] bg-[#292524]`}
+ className={`md-code-block ${gap} overflow-hidden rounded-xl border border-[var(--border)] bg-[#1f2937]`}
>
- <pre className="overflow-x-auto p-4 text-sm leading-relaxed text-[#D6D3D1]">
+ <pre className="overflow-x-auto p-4 text-sm leading-relaxed text-[#e5e7eb]">
<code className="md-code-block__code" {...props}>
{raw}
</code>
diff --git a/web/components/common/ToastViewport.tsx b/web/components/common/ToastViewport.tsx
new file mode 100644
index 000000000..bc567eb78
--- /dev/null
+++ b/web/components/common/ToastViewport.tsx
@@ -0,0 +1,81 @@
+"use client";
+
+import { X } from "lucide-react";
+import { useEffect, useState } from "react";
+import {
+ subscribeNotifications,
+ type Notification,
+} from "@/lib/notifications";
+
+/**
+ * Renders the toast stack in the bottom-right. Mounted once at the
+ * workspace layout level — every call to `notify()` from anywhere in the
+ * app appears here.
+ *
+ * Each toast lives for its own `durationMs`, then auto-dismisses. Users
+ * can also dismiss manually via the X button. The viewport itself is
+ * `aria-live="polite"` so assistive tech announces new toasts as they
+ * arrive, without barging in on whatever the user was reading.
+ */
+export default function ToastViewport() {
+ const [toasts, setToasts] = useState<Notification[]>([]);
+
+ useEffect(() => {
+ return subscribeNotifications((toast) => {
+ setToasts((prev) => [...prev, toast]);
+ const timer = window.setTimeout(() => {
+ setToasts((prev) => prev.filter((t) => t.id !== toast.id));
+ }, toast.durationMs);
+ // No cleanup needed — listener stays alive for the component's life;
+ // individual setTimeouts are GC'd after they fire.
+ void timer;
+ });
+ }, []);
+
+ const dismiss = (id: number) => {
+ setToasts((prev) => prev.filter((t) => t.id !== id));
+ };
+
+ if (toasts.length === 0) return null;
+
+ return (
+ <div
+ role="status"
+ aria-live="polite"
+ aria-atomic="false"
+ className="pointer-events-none fixed bottom-6 right-6 z-[200] flex flex-col gap-2"
+ >
+ {toasts.map((toast) => (
+ <div
+ key={toast.id}
+ className={`pointer-events-auto flex max-w-sm items-start gap-3 rounded-xl border px-4 py-3 shadow-lg backdrop-blur-md ${toneClass(
+ toast.tone,
+ )}`}
+ >
+ <span className="flex-1 text-[13px] leading-relaxed">
+ {toast.message}
+ </span>
+ <button
+ type="button"
+ onClick={() => dismiss(toast.id)}
+ className="rounded p-0.5 opacity-60 transition-opacity hover:opacity-100"
+ aria-label="Dismiss"
+ >
+ <X size={14} strokeWidth={1.8} />
+ </button>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+function toneClass(tone: Notification["tone"]): string {
+ switch (tone) {
+ case "error":
+ return "border-[var(--destructive)]/30 bg-[var(--destructive)]/10 text-[var(--destructive)]";
+ case "success":
+ return "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300";
+ default:
+ return "border-[var(--border)] bg-[var(--card)]/95 text-[var(--foreground)]";
+ }
+}
diff --git a/web/components/notebook/NotebookRecordPicker.tsx b/web/components/notebook/NotebookRecordPicker.tsx
index 7213c203a..6cff94dc7 100644
--- a/web/components/notebook/NotebookRecordPicker.tsx
+++ b/web/components/notebook/NotebookRecordPicker.tsx
@@ -3,6 +3,7 @@
import { useEffect } from "react";
import { Layers, X } from "lucide-react";
import { useTranslation } from "react-i18next";
+import PickerShell from "@/components/common/PickerShell";
import NotebookSelector from "@/components/notebook/NotebookSelector";
import { useNotebookSelection } from "@/components/notebook/useNotebookSelection";
import type { SelectedRecord } from "@/lib/notebook-selection-types";
@@ -41,10 +42,14 @@ export default function NotebookRecordPicker({
void fetchNotebooks();
}, [fetchNotebooks, open]);
- if (!open) return null;
-
return (
- <div className="fixed inset-0 z-[85] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
+ <PickerShell
+ open={open}
+ onClose={onClose}
+ labelledBy="notebook-picker-title"
+ className="p-4 backdrop-blur-md"
+ backdropClass="bg-[var(--background)]/65"
+ >
<div className="surface-card w-full max-w-4xl overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">
<div className="flex items-start justify-between gap-3 border-b border-[var(--border)] px-5 py-4">
<div className="min-w-0">
@@ -52,7 +57,10 @@ export default function NotebookRecordPicker({
<Layers className="h-3 w-3" />
{t("Notebook Reference")}
</div>
- <h2 className="text-lg font-semibold text-[var(--foreground)]">
+ <h2
+ id="notebook-picker-title"
+ className="text-lg font-semibold text-[var(--foreground)]"
+ >
{t("Select Notebook Records")}
</h2>
<p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
@@ -91,6 +99,6 @@ export default function NotebookRecordPicker({
/>
</div>
</div>
- </div>
+ </PickerShell>
);
}
diff --git a/web/components/notebook/SaveToNotebookModal.tsx b/web/components/notebook/SaveToNotebookModal.tsx
index 6139f7633..75d16f555 100644
--- a/web/components/notebook/SaveToNotebookModal.tsx
+++ b/web/components/notebook/SaveToNotebookModal.tsx
@@ -11,6 +11,7 @@ import {
X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
+import PickerShell from "@/components/common/PickerShell";
import { apiFetch, apiUrl } from "@/lib/api";
import {
listNotebooks,
@@ -369,7 +370,9 @@ export default function SaveToNotebookModal({
}
};
- if (!open || !payload) return null;
+ // payload may be null while the parent is preparing the save context.
+ // Treat that as "not open" so the shell never renders without content.
+ const isOpen = open && !!payload;
const totalMessages = messages?.length ?? 0;
const selectedMessageCount = selectedMessageIdx.size;
@@ -377,14 +380,24 @@ export default function SaveToNotebookModal({
totalMessages > 0 && selectedMessageCount === totalMessages;
return (
- <div className="fixed inset-0 z-[80] flex items-center justify-center bg-[var(--background)]/65 p-4 backdrop-blur-md">
+ <PickerShell
+ open={isOpen}
+ onClose={onClose}
+ labelledBy="save-to-notebook-title"
+ zIndex={80}
+ className="p-4 backdrop-blur-md"
+ backdropClass="bg-[var(--background)]/65"
+ >
<div className="surface-card flex max-h-[90vh] w-full max-w-2xl flex-col overflow-hidden rounded-2xl border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)] shadow-[0_22px_70px_rgba(0,0,0,0.18)]">
<div className="flex items-start justify-between gap-3 border-b border-[var(--border)] px-5 py-4">
<div className="min-w-0">
<div className="mb-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-[var(--primary)]">
{t("Notebook Output")}
</div>
- <h2 className="text-lg font-semibold text-[var(--foreground)]">
+ <h2
+ id="save-to-notebook-title"
+ className="text-lg font-semibold text-[var(--foreground)]"
+ >
{t("Save to Notebook")}
</h2>
<p className="mt-0.5 text-sm text-[var(--muted-foreground)]">
@@ -635,6 +648,6 @@ export default function SaveToNotebookModal({
</button>
</div>
</div>
- </div>
+ </PickerShell>
);
}
diff --git a/web/components/sidebar/BookRecent.tsx b/web/components/sidebar/BookRecent.tsx
index 782c71677..2540fdfa2 100644
--- a/web/components/sidebar/BookRecent.tsx
+++ b/web/components/sidebar/BookRecent.tsx
@@ -2,7 +2,9 @@
import Link from "next/link";
import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
import { apiFetch, apiUrl } from "@/lib/api";
+import { formatRelativeTime } from "@/lib/relative-time";
interface RecentBook {
id: string;
@@ -24,24 +26,13 @@ const STATUS_DOT: Record<string, string> = {
error: "bg-rose-400",
};
-function relativeTime(seconds: number): string {
- if (!seconds || Number.isNaN(seconds)) return "";
- const diff = Date.now() / 1000 - seconds;
- if (diff < 60) return "now";
- const mins = Math.floor(diff / 60);
- if (mins < 60) return `${mins}m`;
- const hrs = Math.floor(mins / 60);
- if (hrs < 24) return `${hrs}h`;
- const days = Math.floor(hrs / 24);
- return `${days}d`;
-}
-
interface BookRecentProps {
collapsed?: boolean;
limit?: number;
}
export function BookRecent({ collapsed = false, limit = 4 }: BookRecentProps) {
+ const { i18n } = useTranslation();
const [books, setBooks] = useState<RecentBook[]>([]);
useEffect(() => {
@@ -89,7 +80,10 @@ export function BookRecent({ collapsed = false, limit = 4 }: BookRecentProps) {
{book.title || "Untitled book"}
</span>
<span className="shrink-0 text-[10px] tabular-nums text-[var(--muted-foreground)]/40">
- {relativeTime(Number(book.updated_at) || 0)}
+ {formatRelativeTime(
+ Number(book.updated_at) || 0,
+ i18n.language,
+ )}
</span>
</Link>
);
diff --git a/web/components/sidebar/CoWriterRecent.tsx b/web/components/sidebar/CoWriterRecent.tsx
index bb5d6d208..3c4a9bb38 100644
--- a/web/components/sidebar/CoWriterRecent.tsx
+++ b/web/components/sidebar/CoWriterRecent.tsx
@@ -3,23 +3,13 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useCallback, useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
import {
listCoWriterDocuments,
type CoWriterDocumentSummary,
} from "@/lib/co-writer-api";
import { subscribeCoWriterChanges } from "@/lib/co-writer-events";
-
-function relativeTime(seconds: number): string {
- if (!seconds || Number.isNaN(seconds)) return "";
- const diff = Date.now() / 1000 - seconds;
- if (diff < 60) return "now";
- const mins = Math.floor(diff / 60);
- if (mins < 60) return `${mins}m`;
- const hrs = Math.floor(mins / 60);
- if (hrs < 24) return `${hrs}h`;
- const days = Math.floor(hrs / 24);
- return `${days}d`;
-}
+import { formatRelativeTime } from "@/lib/relative-time";
interface CoWriterRecentProps {
collapsed?: boolean;
@@ -30,6 +20,7 @@ export function CoWriterRecent({
collapsed = false,
limit = 4,
}: CoWriterRecentProps) {
+ const { i18n } = useTranslation();
const [docs, setDocs] = useState<CoWriterDocumentSummary[]>([]);
const pathname = usePathname();
const limitRef = useRef(limit);
@@ -71,7 +62,10 @@ export function CoWriterRecent({
{doc.title || "Untitled draft"}
</span>
<span className="shrink-0 text-[10px] tabular-nums text-[var(--muted-foreground)]/40">
- {relativeTime(Number(doc.updated_at) || 0)}
+ {formatRelativeTime(
+ Number(doc.updated_at) || 0,
+ i18n.language,
+ )}
</span>
</Link>
))}
diff --git a/web/components/sidebar/TutorBotRecent.tsx b/web/components/sidebar/TutorBotRecent.tsx
index e9c9478d4..608e76393 100644
--- a/web/components/sidebar/TutorBotRecent.tsx
+++ b/web/components/sidebar/TutorBotRecent.tsx
@@ -2,7 +2,9 @@
import Link from "next/link";
import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
import { apiFetch, apiUrl } from "@/lib/api";
+import { formatRelativeTime } from "@/lib/relative-time";
interface RecentBot {
bot_id: string;
@@ -12,18 +14,8 @@ interface RecentBot {
updated_at: string;
}
-function relativeTime(iso: string): string {
- const diff = Date.now() - new Date(iso).getTime();
- const mins = Math.floor(diff / 60000);
- if (mins < 1) return "just now";
- if (mins < 60) return `${mins}m`;
- const hrs = Math.floor(mins / 60);
- if (hrs < 24) return `${hrs}h`;
- const days = Math.floor(hrs / 24);
- return `${days}d`;
-}
-
export function TutorBotRecent({ collapsed = false }: { collapsed?: boolean }) {
+ const { i18n } = useTranslation();
const [bots, setBots] = useState<RecentBot[]>([]);
useEffect(() => {
@@ -66,7 +58,10 @@ export function TutorBotRecent({ collapsed = false }: { collapsed?: boolean }) {
{bot.name}
</span>
<span className="shrink-0 text-[10px] tabular-nums text-[var(--muted-foreground)]/40">
- {relativeTime(bot.updated_at)}
+ {formatRelativeTime(
+ Math.floor(new Date(bot.updated_at).getTime() / 1000),
+ i18n.language,
+ )}
</span>
</Link>
))}
diff --git a/web/components/visualize/VisualizationViewer.tsx b/web/components/visualize/VisualizationViewer.tsx
index 12d89521c..7d12f418b 100644
--- a/web/components/visualize/VisualizationViewer.tsx
+++ b/web/components/visualize/VisualizationViewer.tsx
@@ -115,7 +115,7 @@ function HtmlRenderer({ html }: { html: string }) {
ref={iframeRef}
title="HTML visualization"
sandbox="allow-scripts"
- className="w-full rounded-lg border border-[var(--border)] bg-white"
+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)]"
style={{ minHeight: 480, height: 560 }}
/>
</div>
@@ -269,13 +269,15 @@ export default function VisualizationViewer({
</span>
</div>
- {/* Code panel */}
+ {/* Code panel — matches the always-dark .md-code-block style used by the
+ markdown renderers so a "Show code" toggle inside a chart message
+ looks identical to a fenced code block in the assistant response. */}
{showCode && (
- <div className="overflow-hidden rounded-xl border border-[var(--border)] bg-[#1f2937]">
+ <div className="md-code-block overflow-hidden rounded-xl border border-[var(--border)] bg-[#1f2937]">
<div className="border-b border-white/10 px-3 py-2 text-[11px] font-medium uppercase tracking-wider text-[#9ca3af]">
{result.code.language}
</div>
- <pre className="max-h-80 overflow-auto p-4 text-[13px] leading-relaxed text-[#d1d5db]">
+ <pre className="max-h-80 overflow-auto p-4 text-[13px] leading-relaxed text-[#e5e7eb]">
<code>{result.code.content}</code>
</pre>
</div>
@@ -316,7 +318,7 @@ export default function VisualizationViewer({
</button>
</div>
<div
- className="flex flex-1 items-center justify-center overflow-auto rounded-xl bg-white p-6 shadow-2xl"
+ className="flex flex-1 items-center justify-center overflow-auto rounded-xl bg-[var(--card)] p-6 shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="w-full max-w-[1600px]">
diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsx
index 8652cb11f..f9ec319fd 100644
--- a/web/context/UnifiedChatContext.tsx
+++ b/web/context/UnifiedChatContext.tsx
@@ -22,11 +22,15 @@ import { UnifiedWSClient } from "@/lib/unified-ws";
import {
getSession,
deleteMessage,
+ updateBranchSelection,
type SessionMessage,
} from "@/lib/session-api";
import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";
import { normalizeMessageContent } from "@/lib/message-content";
+import { buildVisiblePath, tipMessageId } from "@/lib/message-branches";
import { shouldAppendEventContent } from "@/lib/stream";
+import { notify } from "@/lib/notifications";
+import i18n from "i18next";
import {
normalizeBookReferences,
type BookReferencePayload,
@@ -64,6 +68,10 @@ export interface SendMessageOptions {
persistUserMessage?: boolean;
requestSnapshotOverride?: MessageRequestSnapshot;
bookReferences?: BookReferencePayload[];
+ /** Edit-branching: when set, the new user message is inserted as a
+ * sibling under this parent rather than appended to the session tail.
+ * ``null`` means "explicitly attach to the session root". */
+ parentMessageId?: number | null;
// Surface that originated the turn. The backend stamps this onto the
// session row when ``ensure_session`` first creates it, then it never
// changes. Callers from /co-learn must pass ``"co_learn"`` so the auto
@@ -81,6 +89,9 @@ export interface ChatState {
isStreaming: boolean;
currentStage: string;
language: string;
+ /** Edit-branching: keyed by stringified parent_message_id (or "null"
+ * for the root). Empty means "default to latest sibling everywhere". */
+ selectedBranches: Record<string, number>;
}
interface SessionStatusSnapshot {
@@ -128,6 +139,8 @@ export interface MessageItem {
events?: StreamEvent[];
attachments?: MessageAttachment[];
requestSnapshot?: MessageRequestSnapshot;
+ /** Edit-branching: id of the message this row continues. */
+ parentMessageId?: number | null;
}
interface SessionEntry extends ChatState {
@@ -136,6 +149,9 @@ interface SessionEntry extends ChatState {
activeTurnId: string | null;
lastSeq: number;
updatedAt: number;
+ /** Edit-branching: maps a parent_message_id (stringified, or "null" for
+ * the session root) to the chosen child id at that branch point. */
+ selectedBranches: Record<string, number>;
}
interface ProviderState {
@@ -157,6 +173,7 @@ type Action =
capability?: string | null;
attachments?: MessageAttachment[];
requestSnapshot?: MessageRequestSnapshot;
+ parentMessageId?: number | null;
}
| { type: "POP_LAST_ASSISTANT"; key: string }
| { type: "RESTORE_ASSISTANT"; key: string; message: MessageItem }
@@ -186,9 +203,21 @@ type Action =
knowledgeBases?: string[];
llmSelection?: LLMSelection | null;
language?: string;
+ selectedBranches?: Record<string, number>;
}
| { type: "DELETE_TURN"; key: string; messageId: number }
- | { type: "NEW_SESSION"; key: string };
+ | { type: "NEW_SESSION"; key: string }
+ | {
+ type: "SET_SELECTED_BRANCH";
+ key: string;
+ parentKey: string;
+ childId: number;
+ }
+ | {
+ type: "REPLACE_SELECTED_BRANCHES";
+ key: string;
+ selectedBranches: Record<string, number>;
+ };
function createSessionEntry(
key: string,
@@ -209,6 +238,7 @@ function createSessionEntry(
activeTurnId: null,
lastSeq: 0,
updatedAt: Date.now(),
+ selectedBranches: {},
};
}
@@ -279,6 +309,10 @@ function reducer(state: ProviderState, action: Action): ProviderState {
role: "user",
content: action.content,
capability: action.capability || "",
+ parentMessageId:
+ action.parentMessageId === undefined
+ ? null
+ : action.parentMessageId,
...(action.attachments?.length
? { attachments: action.attachments }
: {}),
@@ -338,34 +372,46 @@ function reducer(state: ProviderState, action: Action): ProviderState {
},
};
}
- case "STREAM_START":
+ case "STREAM_START": {
+ const session =
+ state.sessions[action.key] ?? createSessionEntry(action.key);
+ const existing = session.messages ?? [];
+ // Chain the placeholder assistant onto whatever message currently
+ // sits at the tip — this is normally the user row just added by
+ // ADD_USER_MSG (possibly an optimistic negative id during an edit).
+ const tip = existing.length > 0 ? existing[existing.length - 1] : null;
return {
...state,
sessions: {
...state.sessions,
[action.key]: {
- ...(state.sessions[action.key] ?? createSessionEntry(action.key)),
+ ...session,
isStreaming: true,
status: "running",
messages: [
- ...(state.sessions[action.key]?.messages ?? []),
+ ...existing,
{
id: -Date.now(),
role: "assistant",
content: "",
events: [],
- capability:
- (state.sessions[action.key] ?? createSessionEntry(action.key))
- .activeCapability || "",
+ capability: session.activeCapability || "",
+ parentMessageId: tip?.id ?? null,
},
],
updatedAt: Date.now(),
},
},
};
+ }
case "STREAM_EVENT": {
- const session =
- state.sessions[action.key] ?? createSessionEntry(action.key);
+ // If the session entry has been removed (e.g., BIND_SERVER_SESSION
+ // just renamed ``draft_X`` to a real id but a stray event still
+ // targets the old key), drop the event rather than synthesise an
+ // orphan session with no user message — that would scrub the
+ // user's just-sent bubble from view.
+ if (!state.sessions[action.key]) return state;
+ const session = state.sessions[action.key];
const msgs = [...session.messages];
let last = msgs[msgs.length - 1];
if (last?.role !== "assistant") {
@@ -375,6 +421,7 @@ function reducer(state: ProviderState, action: Action): ProviderState {
content: "",
events: [],
capability: session.activeCapability || "",
+ parentMessageId: last?.id ?? null,
});
last = msgs[msgs.length - 1];
}
@@ -484,6 +531,41 @@ function reducer(state: ProviderState, action: Action): ProviderState {
activeTurnId: action.activeTurnId || null,
status: action.status || "idle",
language: action.language ?? existing.language,
+ selectedBranches:
+ action.selectedBranches ?? existing.selectedBranches,
+ updatedAt: Date.now(),
+ },
+ },
+ };
+ }
+ case "SET_SELECTED_BRANCH": {
+ const session = state.sessions[action.key];
+ if (!session) return state;
+ return {
+ ...state,
+ sessions: {
+ ...state.sessions,
+ [action.key]: {
+ ...session,
+ selectedBranches: {
+ ...session.selectedBranches,
+ [action.parentKey]: action.childId,
+ },
+ updatedAt: Date.now(),
+ },
+ },
+ };
+ }
+ case "REPLACE_SELECTED_BRANCHES": {
+ const session = state.sessions[action.key];
+ if (!session) return state;
+ return {
+ ...state,
+ sessions: {
+ ...state.sessions,
+ [action.key]: {
+ ...session,
+ selectedBranches: { ...action.selectedBranches },
updatedAt: Date.now(),
},
},
@@ -577,6 +659,13 @@ interface ChatContextValue {
cancelStreamingTurn: () => void;
regenerateLastMessage: () => void;
deleteTurn: (messageId: number) => Promise<void>;
+ /** Re-send a user message under a new branch (sibling of the original).
+ * Uses the composer's current capability / refs — only the text is
+ * taken from ``newContent``. Re-runs the turn from the original's
+ * parent context. */
+ editMessage: (messageId: number, newContent: string) => Promise<void>;
+ /** Switch which sibling is currently visible at a branch point. */
+ switchBranch: (parentMessageId: number | null, childId: number) => void;
newSession: () => void;
loadSession: (sessionId: string) => Promise<void>;
selectedSessionId: string | null;
@@ -627,6 +716,16 @@ function asLLMSelection(value: unknown): LLMSelection | null {
: null;
}
+function normalizeSelectedBranches(value: unknown): Record<string, number> {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
+ const result: Record<string, number> = {};
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
+ const n = typeof v === "number" ? v : Number(v);
+ if (Number.isInteger(n) && n > 0) result[k] = n;
+ }
+ return result;
+}
+
function asMemoryReferences(value: unknown): MemoryReferencePayload {
return asStringArray(value).filter(
(item): item is "summary" | "profile" =>
@@ -727,6 +826,12 @@ export function UnifiedChatProvider({
// assistant message if the server rejects the request (e.g. ``regenerate_busy``
// or ``nothing_to_regenerate``). Keyed by session entry key.
const pendingRegenerateRef = useRef<Map<string, MessageItem>>(new Map());
+ // Forward-declared so ``handleRunnerEvent`` (created above
+ // ``loadSession`` in source order) can trigger a server refresh after
+ // a turn finishes without taking a stale closure of ``loadSession``.
+ const loadSessionRef = useRef<((sessionId: string) => Promise<void>) | null>(
+ null,
+ );
useLayoutEffect(() => {
stateRef.current = state;
@@ -769,6 +874,10 @@ export function UnifiedChatProvider({
capability: message.capability || "",
events: Array.isArray(message.events) ? message.events : [],
attachments,
+ parentMessageId:
+ message.parent_message_id === undefined
+ ? null
+ : message.parent_message_id,
...(requestSnapshot ? { requestSnapshot } : {}),
};
});
@@ -824,6 +933,21 @@ export function UnifiedChatProvider({
const runner = runnersRef.current.get(effectiveKey);
runner?.client.disconnect();
runnersRef.current.delete(effectiveKey);
+ // Reconcile optimistic client-side message ids with the
+ // server's real ids after the turn finishes. Without this the
+ // Edit button (which needs a real id to attach the new branch
+ // under) and branch navigation (which keys off real ids) would
+ // stay disabled until the user navigates away and back.
+ if (status === "completed") {
+ const finishedSession =
+ stateRef.current.sessions[effectiveKey];
+ const sessionId = finishedSession?.sessionId;
+ if (sessionId) {
+ loadSessionRef.current?.(sessionId).catch(() => {
+ /* non-fatal — local state remains usable */
+ });
+ }
+ }
return;
}
dispatch({ type: "STREAM_EVENT", key: effectiveKey, event });
@@ -892,6 +1016,15 @@ export function UnifiedChatProvider({
key: record.key,
status: "failed",
});
+ // Surface the disconnect to the user. The WS client already
+ // logs to console — we add a toast so non-debugging users
+ // don't see streaming silently flatline.
+ notify(
+ i18n.t(
+ "Connection lost while generating. Please retry your message.",
+ ),
+ { tone: "error", durationMs: 6000 },
+ );
}
},
),
@@ -910,6 +1043,15 @@ export function UnifiedChatProvider({
if (attempt >= 10) {
console.error("WebSocket failed to connect after retries");
dispatch({ type: "STREAM_END", key, status: "failed" });
+ // Surfaces the dead-after-N-retries case (different code path
+ // from the close-while-streaming handler above). Same user
+ // mental model, so same toast copy.
+ notify(
+ i18n.t(
+ "Couldn't reach the server. Please check your connection and retry.",
+ ),
+ { tone: "error", durationMs: 6000 },
+ );
return;
}
const timerId = setTimeout(() => {
@@ -951,6 +1093,9 @@ export function UnifiedChatProvider({
// have stale persisted preferences, so new turns follow the current
// app language rather than the language saved when the session began.
language: readStoredLanguage(),
+ selectedBranches: normalizeSelectedBranches(
+ session.preferences?.selected_branches,
+ ),
});
if (activeTurn?.turn_id || activeTurn?.id) {
const key = session.session_id || session.id;
@@ -964,6 +1109,10 @@ export function UnifiedChatProvider({
[hydrateMessages, sendThroughRunner],
);
+ useLayoutEffect(() => {
+ loadSessionRef.current = loadSession;
+ }, [loadSession]);
+
useEffect(() => {
if (typeof window === "undefined") return;
const current = state.selectedKey
@@ -1111,6 +1260,27 @@ export function UnifiedChatProvider({
? { llmSelection: effectiveLLMSelection }
: {}),
};
+ // Default the new message's parent to the tip of the currently-
+ // visible path so the local chat tree stays connected during
+ // streaming. The wire-level ``parent_message_id`` is computed
+ // separately further down: only persisted (positive) ids or an
+ // explicit ``null`` (root edit) are sent — optimistic negative ids
+ // would be meaningless to the server.
+ const visible = buildVisiblePath(
+ session.messages,
+ session.selectedBranches,
+ ).messages;
+ const tipId = tipMessageId(visible);
+ const localParentId =
+ options?.parentMessageId !== undefined
+ ? options.parentMessageId
+ : tipId;
+ const wireParentId: number | null | undefined =
+ options?.parentMessageId !== undefined
+ ? options.parentMessageId
+ : tipId !== null && tipId > 0
+ ? tipId
+ : undefined;
if (options?.displayUserMessage !== false) {
dispatch({
type: "ADD_USER_MSG",
@@ -1119,6 +1289,7 @@ export function UnifiedChatProvider({
capability: effectiveCapability,
attachments: msgAttachments,
requestSnapshot,
+ parentMessageId: localParentId,
});
}
dispatch({ type: "STREAM_START", key });
@@ -1158,6 +1329,15 @@ export function UnifiedChatProvider({
...(effectiveConfig && Object.keys(effectiveConfig).length > 0
? { config: effectiveConfig }
: {}),
+ // Send ``parent_message_id`` only when we have a real (positive)
+ // server id to chain under, or when the caller explicitly pinned
+ // a parent (incl. ``null`` for editing the session's first
+ // message). When the visible tip is still an optimistic
+ // negative id, omit the key and let the backend auto-append to
+ // the latest persisted row.
+ ...(wireParentId !== undefined
+ ? { parent_message_id: wireParentId }
+ : {}),
});
},
[makeDraftKey, sendThroughRunner],
@@ -1222,6 +1402,7 @@ export function UnifiedChatProvider({
isStreaming: current.isStreaming,
currentStage: current.currentStage,
language: current.language,
+ selectedBranches: current.selectedBranches,
};
}, [state]);
@@ -1263,6 +1444,93 @@ export function UnifiedChatProvider({
dispatch({ type: "NEW_SESSION", key: makeDraftKey() });
}, [makeDraftKey]);
+ const editMessage = useCallback(
+ async (messageId: number, newContent: string) => {
+ const trimmed = newContent.trim();
+ if (!trimmed) return;
+ const currentState = stateRef.current;
+ const key = currentState.selectedKey;
+ if (!key) return;
+ const session = currentState.sessions[key];
+ if (!session) return;
+ // Edits create a new branch via a fresh turn — block while one is
+ // already running so we don't queue against an in-flight stream
+ // (matches the delete-turn guard).
+ if (session.isStreaming) return;
+ const idx = session.messages.findIndex(
+ (m) => m.id === messageId && m.role === "user",
+ );
+ if (idx === -1) return;
+ let original = session.messages[idx];
+ // Optimistic in-flight rows have a negative client-side id — we
+ // need a real server id to hang the new sibling under. Refresh
+ // from the server, then re-resolve the row by its position in the
+ // (now-persisted) thread before continuing.
+ if (typeof original.id === "number" && original.id < 0) {
+ if (!session.sessionId) return;
+ try {
+ await loadSession(session.sessionId);
+ } catch {
+ return;
+ }
+ const refreshed = stateRef.current.sessions[key];
+ const candidate = refreshed?.messages[idx];
+ if (
+ !candidate ||
+ candidate.role !== "user" ||
+ typeof candidate.id !== "number" ||
+ candidate.id < 0
+ ) {
+ return;
+ }
+ original = candidate;
+ }
+ if (typeof original.id !== "number" || original.id < 0) return;
+ const parentId = original.parentMessageId ?? null;
+ sendMessage(
+ trimmed,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ { parentMessageId: parentId },
+ undefined,
+ undefined,
+ undefined,
+ );
+ },
+ [loadSession, sendMessage],
+ );
+
+ const switchBranch = useCallback(
+ (parentMessageId: number | null, childId: number) => {
+ const currentState = stateRef.current;
+ const key = currentState.selectedKey;
+ if (!key) return;
+ const session = currentState.sessions[key];
+ if (!session) return;
+ const parentKey = parentMessageId == null ? "null" : String(parentMessageId);
+ dispatch({
+ type: "SET_SELECTED_BRANCH",
+ key,
+ parentKey,
+ childId,
+ });
+ const sessionId = session.sessionId;
+ if (!sessionId) return;
+ const nextSelections = {
+ ...session.selectedBranches,
+ [parentKey]: childId,
+ };
+ // Fire-and-forget — local state is the source of truth for the UI;
+ // the server copy only matters for reload-time hydration.
+ updateBranchSelection(sessionId, nextSelections).catch((err) => {
+ console.warn("Failed to persist branch selection:", err);
+ });
+ },
+ [],
+ );
+
const deleteTurn = useCallback(
async (messageId: number) => {
const currentState = stateRef.current;
@@ -1295,23 +1563,52 @@ export function UnifiedChatProvider({
[loadSession],
);
- const value: ChatContextValue = {
- state: derivedState,
- setTools,
- setCapability,
- setKBs,
- setLLMSelection,
- setLanguage,
- sendMessage,
- cancelStreamingTurn,
- regenerateLastMessage,
- deleteTurn,
- newSession,
- loadSession,
- selectedSessionId: derivedState.sessionId,
- sessionStatuses,
- sidebarRefreshToken: state.sidebarRefreshToken,
- };
+ // Memoize the context value so consumers don't re-render on every render of
+ // this provider. Without this wrap, every stream-event-driven reducer
+ // dispatch produced a fresh object identity, cascading a re-render through
+ // every `useUnifiedChat()` consumer (chat page, composer, sidebar) on each
+ // token. The callbacks below are already stable via useCallback; the only
+ // things that should change identity are derivedState, sessionStatuses,
+ // and sidebarRefreshToken.
+ const value = useMemo<ChatContextValue>(
+ () => ({
+ state: derivedState,
+ setTools,
+ setCapability,
+ setKBs,
+ setLLMSelection,
+ setLanguage,
+ sendMessage,
+ cancelStreamingTurn,
+ regenerateLastMessage,
+ deleteTurn,
+ editMessage,
+ switchBranch,
+ newSession,
+ loadSession,
+ selectedSessionId: derivedState.sessionId,
+ sessionStatuses,
+ sidebarRefreshToken: state.sidebarRefreshToken,
+ }),
+ [
+ derivedState,
+ setTools,
+ setCapability,
+ setKBs,
+ setLLMSelection,
+ setLanguage,
+ sendMessage,
+ cancelStreamingTurn,
+ regenerateLastMessage,
+ deleteTurn,
+ editMessage,
+ switchBranch,
+ newSession,
+ loadSession,
+ sessionStatuses,
+ state.sidebarRefreshToken,
+ ],
+ );
return <ChatCtx.Provider value={value}>{children}</ChatCtx.Provider>;
}
diff --git a/web/hooks/useChatAutoScroll.ts b/web/hooks/useChatAutoScroll.ts
index 5b5c01008..3ec9fe2ba 100644
--- a/web/hooks/useChatAutoScroll.ts
+++ b/web/hooks/useChatAutoScroll.ts
@@ -90,9 +90,14 @@ export function useChatAutoScroll({
// After streaming ends, dynamically-loaded components (e.g. MathAnimatorViewer
// via next/dynamic) may render and grow the content height. Detect that and
// scroll to bottom so the user can see the full result.
- // hasMessages is in deps so the observer attaches once the messages
- // container mounts on session reopen — without it, the container ref is null
- // on initial mount and the observer is never set up.
+ //
+ // This observer used to run for the entire lifetime of the conversation,
+ // which meant any post-stream DOM change — including the user expanding a
+ // trace `<details>` row to read it — was treated as "new content arrived"
+ // and pulled the user back to the bottom. We now gate it to a short window
+ // right after `isStreaming` flips false, which is when late-mounting
+ // dynamic components actually settle.
+ const POST_STREAM_AUTOSCROLL_WINDOW_MS = 4000;
useEffect(() => {
if (isStreaming) return;
if (!hasMessages) return;
@@ -102,11 +107,13 @@ export function useChatAutoScroll({
let prevHeight = container.scrollHeight;
let rafId = 0;
+ const deadline = performance.now() + POST_STREAM_AUTOSCROLL_WINDOW_MS;
const check = () => {
if (rafId) return;
rafId = requestAnimationFrame(() => {
rafId = 0;
+ if (performance.now() > deadline) return;
const curHeight = container.scrollHeight;
if (curHeight > prevHeight && shouldAutoScrollRef.current) {
scrollToBottom("instant");
@@ -117,8 +124,13 @@ export function useChatAutoScroll({
const mo = new MutationObserver(check);
mo.observe(container, { childList: true, subtree: true });
+ const stopTimer = window.setTimeout(() => {
+ mo.disconnect();
+ if (rafId) cancelAnimationFrame(rafId);
+ }, POST_STREAM_AUTOSCROLL_WINDOW_MS);
return () => {
+ window.clearTimeout(stopTimer);
mo.disconnect();
if (rafId) cancelAnimationFrame(rafId);
};
diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.ts
index fe162882a..e7520413a 100644
--- a/web/lib/knowledge-api.ts
+++ b/web/lib/knowledge-api.ts
@@ -39,6 +39,59 @@ export interface KnowledgeBaseFile {
mime_type?: string | null;
}
+const IMAGE_UPLOAD_EXTENSIONS = [
+ ".bmp",
+ ".gif",
+ ".jpeg",
+ ".jpg",
+ ".png",
+ ".tif",
+ ".tiff",
+ ".webp",
+];
+
+const IMAGE_UPLOAD_MIME_TYPES = [
+ "image/bmp",
+ "image/gif",
+ "image/jpeg",
+ "image/png",
+ "image/tiff",
+ "image/webp",
+];
+
+function normalizeUploadPolicy(data: unknown): KnowledgeUploadPolicy {
+ const payload = data as Partial<KnowledgeUploadPolicy> | null | undefined;
+ const extensions = Array.from(
+ new Set([
+ ...(Array.isArray(payload?.extensions) ? payload.extensions : []),
+ ...IMAGE_UPLOAD_EXTENSIONS,
+ ]),
+ ).sort();
+ const serverAccept =
+ typeof payload?.accept === "string"
+ ? payload.accept
+ .split(",")
+ .map((item) => item.trim())
+ .filter(Boolean)
+ : [];
+ const accept = Array.from(
+ new Set([...serverAccept, ...extensions, ...IMAGE_UPLOAD_MIME_TYPES]),
+ ).join(",");
+
+ return {
+ extensions,
+ accept,
+ max_file_size_bytes:
+ typeof payload?.max_file_size_bytes === "number"
+ ? payload.max_file_size_bytes
+ : 100 * 1024 * 1024,
+ max_pdf_size_bytes:
+ typeof payload?.max_pdf_size_bytes === "number"
+ ? payload.max_pdf_size_bytes
+ : 50 * 1024 * 1024,
+ };
+}
+
export async function listKnowledgeBases(options?: { force?: boolean }) {
return withClientCache<KnowledgeBaseSummary[]>(
`${KNOWLEDGE_CACHE_PREFIX}list`,
@@ -89,18 +142,7 @@ export async function getKnowledgeUploadPolicy(options?: { force?: boolean }) {
},
);
const data = await response.json();
- return {
- extensions: Array.isArray(data?.extensions) ? data.extensions : [],
- accept: typeof data?.accept === "string" ? data.accept : "",
- max_file_size_bytes:
- typeof data?.max_file_size_bytes === "number"
- ? data.max_file_size_bytes
- : 100 * 1024 * 1024,
- max_pdf_size_bytes:
- typeof data?.max_pdf_size_bytes === "number"
- ? data.max_pdf_size_bytes
- : 50 * 1024 * 1024,
- };
+ return normalizeUploadPolicy(data);
},
{
force: options?.force,
diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.ts
index ac6bf16f5..dc90dabf5 100644
--- a/web/lib/knowledge-helpers.ts
+++ b/web/lib/knowledge-helpers.ts
@@ -160,7 +160,6 @@ const LIVE_PROGRESS_STAGES = new Set([
"starting",
"processing_documents",
"processing_file",
- "extracting_items",
]);
export const kbHasLiveProgress = (kb: KnowledgeBase): boolean => {
diff --git a/web/lib/message-branches.ts b/web/lib/message-branches.ts
new file mode 100644
index 000000000..56dc2da76
--- /dev/null
+++ b/web/lib/message-branches.ts
@@ -0,0 +1,159 @@
+/**
+ * Edit-branching tree helpers.
+ *
+ * The server stores all messages as a flat list per session, with
+ * ``parent_message_id`` pointers — siblings share the same parent and
+ * represent alternative continuations created by editing a user message.
+ *
+ * The UI shows a single linear path at a time. ``buildVisiblePath`` picks
+ * that path from the flat list: starting at the root (parent = null), at
+ * every branch point it follows ``selectedBranches[parent_id]`` if set,
+ * otherwise it falls back to the latest-created child (the one most
+ * recently added — including the still-in-flight optimistic message which
+ * uses a negative client-side id and is treated as newer than any
+ * persisted positive id).
+ */
+
+import type { MessageItem } from "@/context/UnifiedChatContext";
+
+const ROOT_KEY = "null";
+
+function parentKey(id: number | null | undefined): string {
+ return id == null ? ROOT_KEY : String(id);
+}
+
+// Large offset that pushes every optimistic (negative-id) sibling above
+// every persisted (positive-id) sibling without overflowing safe-integer
+// arithmetic. ``Date.now()`` lives around 1.7e12 today, so 1e15 leaves
+// ample headroom and stays well under ``Number.MAX_SAFE_INTEGER``.
+const OPTIMISTIC_RANK_OFFSET = 1e15;
+
+function siblingRank(message: MessageItem): number {
+ // Optimistic, in-flight messages get a negative ``id`` on the client
+ // (``-Date.now()``) and must be treated as the freshest sibling so the
+ // bubble the user just submitted stays visible. Among optimistic rows,
+ // the *more recent* one (more negative id) must rank higher so that a
+ // second optimistic send doesn't get hidden by the first. Persisted
+ // messages keep their natural id-ordered rank.
+ const id = message.id ?? 0;
+ return id < 0 ? OPTIMISTIC_RANK_OFFSET - id : id;
+}
+
+export interface SiblingInfo {
+ /** Number of alternative branches at this point, including this one. */
+ total: number;
+ /** 1-based index of the current branch in chronological order. */
+ index: number;
+ /** All sibling message ids in chronological (creation) order. */
+ siblingIds: number[];
+ /** Parent message id (``null`` if at the session root). */
+ parentId: number | null;
+}
+
+export interface VisiblePathResult {
+ /** The flat message list to render, in chronological order. */
+ messages: MessageItem[];
+ /** Sibling info keyed by message id. Only present for messages whose
+ * parent has more than one child (i.e. branching points). */
+ siblingsByMessageId: Map<number, SiblingInfo>;
+}
+
+export function buildVisiblePath(
+ allMessages: MessageItem[],
+ selectedBranches: Record<string, number> | undefined,
+): VisiblePathResult {
+ // Group by parent.
+ const childrenByParent = new Map<string, MessageItem[]>();
+ for (const msg of allMessages) {
+ if (msg.id === undefined) continue;
+ const key = parentKey(msg.parentMessageId);
+ const arr = childrenByParent.get(key);
+ if (arr) arr.push(msg);
+ else childrenByParent.set(key, [msg]);
+ }
+ for (const arr of childrenByParent.values()) {
+ arr.sort((a, b) => siblingRank(a) - siblingRank(b));
+ }
+
+ const selection = selectedBranches ?? {};
+ const visible: MessageItem[] = [];
+ const siblingsByMessageId = new Map<number, SiblingInfo>();
+ const guard = new Set<string>();
+ let currentParent = ROOT_KEY;
+ // Bound the walk defensively against pathological data (loops).
+ let safety = 10_000;
+ while (safety > 0) {
+ safety -= 1;
+ if (guard.has(currentParent)) break;
+ guard.add(currentParent);
+ const children = childrenByParent.get(currentParent);
+ if (!children || children.length === 0) break;
+
+ let chosen: MessageItem;
+ if (children.length === 1) {
+ chosen = children[0];
+ } else {
+ const selectedId = selection[currentParent];
+ chosen =
+ (selectedId !== undefined &&
+ children.find((c) => c.id === selectedId)) ||
+ children[children.length - 1];
+ }
+ visible.push(chosen);
+
+ if (children.length > 1 && chosen.id !== undefined) {
+ const idx = children.findIndex((c) => c.id === chosen.id);
+ siblingsByMessageId.set(chosen.id, {
+ total: children.length,
+ index: idx + 1,
+ siblingIds: children.map((c) => c.id!).filter((id) => id !== undefined),
+ parentId: chosen.parentMessageId ?? null,
+ });
+ }
+
+ if (chosen.id === undefined) break;
+ currentParent = String(chosen.id);
+ }
+
+ return { messages: visible, siblingsByMessageId };
+}
+
+/**
+ * Find the most recent child id under ``parentId`` from a flat message
+ * list. Used after an edit to auto-select the freshly persisted sibling.
+ * Persisted (positive-id) rows only — optimistic in-flight rows aren't
+ * useful as a persisted selection target.
+ */
+export function latestChildId(
+ allMessages: MessageItem[],
+ parentId: number | null,
+): number | null {
+ const key = parentKey(parentId);
+ let best: number | null = null;
+ let bestId = 0;
+ for (const m of allMessages) {
+ if (parentKey(m.parentMessageId) !== key) continue;
+ if (m.id === undefined || m.id <= 0) continue;
+ if (m.id > bestId) {
+ bestId = m.id;
+ best = m.id;
+ }
+ }
+ return best;
+}
+
+/**
+ * Compute the parent id of the next message a user would send right now
+ * given the currently-visible path. Returns the last visible message's
+ * id (incl. optimistic in-flight rows whose ``id`` is a negative client
+ * sentinel) so a follow-up message chains under the active branch even
+ * when no server reload has reconciled real ids yet. ``null`` for an
+ * empty session.
+ */
+export function tipMessageId(visible: MessageItem[]): number | null {
+ for (let i = visible.length - 1; i >= 0; i -= 1) {
+ const id = visible[i].id;
+ if (id !== undefined) return id;
+ }
+ return null;
+}
diff --git a/web/lib/notifications.ts b/web/lib/notifications.ts
new file mode 100644
index 000000000..4b313184a
--- /dev/null
+++ b/web/lib/notifications.ts
@@ -0,0 +1,56 @@
+/**
+ * Tiny app-wide notification pub-sub. A single ToastViewport (mounted in
+ * the workspace layout) subscribes and renders any toast emitted by
+ * `notify()`.
+ *
+ * Why pub-sub instead of a context: emitters can be outside React (WS
+ * handlers, fetch wrappers, plain utility code). Coupling a context would
+ * force every non-React caller into a hook-friendly shape it doesn't need.
+ * Pub-sub lets us emit from anywhere and render in one place.
+ *
+ * Replaces three hand-rolled toasts that lived inside individual pages
+ * (agents, settings, MemorySection) — each with their own state and
+ * styling. New code should call `notify()` rather than start a fourth.
+ */
+
+export type NotificationTone = "info" | "success" | "error";
+
+export interface Notification {
+ id: number;
+ message: string;
+ tone: NotificationTone;
+ durationMs: number;
+}
+
+type Listener = (n: Notification) => void;
+
+const listeners = new Set<Listener>();
+let counter = 0;
+
+export function notify(
+ message: string,
+ options: { tone?: NotificationTone; durationMs?: number } = {},
+): void {
+ if (!message) return;
+ counter += 1;
+ const notification: Notification = {
+ id: counter,
+ message,
+ tone: options.tone ?? "info",
+ durationMs: options.durationMs ?? 4000,
+ };
+ for (const listener of Array.from(listeners)) {
+ try {
+ listener(notification);
+ } catch {
+ /* a misbehaving listener should not break siblings */
+ }
+ }
+}
+
+export function subscribeNotifications(listener: Listener): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
diff --git a/web/lib/relative-time.ts b/web/lib/relative-time.ts
new file mode 100644
index 000000000..6a158ebbe
--- /dev/null
+++ b/web/lib/relative-time.ts
@@ -0,0 +1,51 @@
+/**
+ * Shared locale-aware time helpers for sidebar / session lists.
+ *
+ * Two pieces:
+ *
+ * 1. `getDayGroupKey(ts)` — returns a stable token (`today` / `yesterday` /
+ * `last_7_days` / `earlier`) for grouping. Callers map that token to a
+ * translated label via i18next so the same grouping logic works across
+ * locales.
+ *
+ * 2. `formatRelativeTime(ts, locale)` — wraps `Intl.RelativeTimeFormat` with
+ * the caller's active locale instead of the previously-hardcoded `"en"`.
+ * Falls back to `"en"` on unsupported locales to match Intl's own
+ * behaviour rather than throwing.
+ */
+
+export type DayGroupKey = "today" | "yesterday" | "last_7_days" | "earlier";
+
+export function getDayGroupKey(timestamp: number): DayGroupKey {
+ const now = new Date();
+ const date = new Date(timestamp * 1000);
+ const startOfToday = new Date(
+ now.getFullYear(),
+ now.getMonth(),
+ now.getDate(),
+ ).getTime();
+ const startOfItemDay = new Date(
+ date.getFullYear(),
+ date.getMonth(),
+ date.getDate(),
+ ).getTime();
+ const diffDays = Math.floor((startOfToday - startOfItemDay) / 86400000);
+ if (diffDays <= 0) return "today";
+ if (diffDays === 1) return "yesterday";
+ if (diffDays < 7) return "last_7_days";
+ return "earlier";
+}
+
+export function formatRelativeTime(timestamp: number, locale: string): string {
+ const diffSeconds = Math.round(timestamp - Date.now() / 1000);
+ const formatter = new Intl.RelativeTimeFormat(locale || "en", {
+ numeric: "auto",
+ });
+ const abs = Math.abs(diffSeconds);
+ if (abs < 60) return formatter.format(diffSeconds, "second");
+ if (abs < 3600)
+ return formatter.format(Math.round(diffSeconds / 60), "minute");
+ if (abs < 86400)
+ return formatter.format(Math.round(diffSeconds / 3600), "hour");
+ return formatter.format(Math.round(diffSeconds / 86400), "day");
+}
diff --git a/web/lib/session-api.ts b/web/lib/session-api.ts
index 02aa0326d..b8c2a2e8e 100644
--- a/web/lib/session-api.ts
+++ b/web/lib/session-api.ts
@@ -21,6 +21,9 @@ export interface SessionMessage {
}>;
metadata?: Record<string, unknown>;
created_at: number;
+ /** Edit-branching: id of the message this row continues. `null` for the
+ * first message in a session. Siblings share the same parent. */
+ parent_message_id?: number | null;
}
export interface SessionSummary {
@@ -47,6 +50,10 @@ export interface SessionSummary {
knowledge_bases?: string[];
language?: string;
llm_selection?: LLMSelection | null;
+ /** Edit-branching: maps a parent_message_id → the child id currently
+ * shown at that branch point. Missing keys default to the latest
+ * sibling (most recently created child). */
+ selected_branches?: Record<string, number>;
};
}
@@ -85,6 +92,10 @@ export interface SessionDetail {
knowledge_bases?: string[];
language?: string;
llm_selection?: LLMSelection | null;
+ /** Edit-branching: maps a parent_message_id → the child id currently
+ * shown at that branch point. Missing keys default to the latest
+ * sibling (most recently created child). */
+ selected_branches?: Record<string, number>;
};
messages: SessionMessage[];
active_turns?: ActiveTurnSummary[];
@@ -200,3 +211,18 @@ export async function deleteMessage(
);
await expectJson<{ deleted: boolean }>(response);
}
+
+export async function updateBranchSelection(
+ sessionId: string,
+ selectedBranches: Record<string, number>,
+): Promise<void> {
+ const response = await apiFetch(
+ apiUrl(`/api/v1/sessions/${sessionId}/branch-selection`),
+ {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ selected_branches: selectedBranches }),
+ },
+ );
+ await expectJson<{ selected_branches: Record<string, number> }>(response);
+}
diff --git a/web/lib/trace-timing.ts b/web/lib/trace-timing.ts
new file mode 100644
index 000000000..c33e14751
--- /dev/null
+++ b/web/lib/trace-timing.ts
@@ -0,0 +1,61 @@
+/**
+ * Turn-level timing for the chat status header.
+ *
+ * Each assistant turn used to surface a duration label on every
+ * sub-trace ("Plan for 5s", "Round 3 · 8s", …). That made the
+ * trace card noisy and made it hard to tell at a glance how long
+ * the whole answer took. The current design hoists timing to the
+ * single ``DeepTutor reasoning…`` status row at the top of the
+ * answer: one number, ticking up while the turn is in flight and
+ * frozen once the turn is done.
+ *
+ * The clock derives its bounds from the event stream so reconnects
+ * keep the duration coherent — we never depend on a transient React
+ * state that resets on remount.
+ */
+
+import type { StreamEvent } from "@/lib/unified-ws";
+
+/**
+ * Elapsed seconds for the turn the ``events`` belong to.
+ *
+ * Returns ``null`` when the stream has not produced any timestamped
+ * event yet (e.g. the optimistic assistant placeholder before the
+ * first server frame arrives).
+ *
+ * While ``isStreaming`` is true the upper bound floats to
+ * ``nowSeconds`` so the label ticks up in real time; once streaming
+ * ends the bound collapses to the latest event timestamp and the
+ * duration freezes.
+ */
+export function getTurnDurationSeconds(
+ events: StreamEvent[],
+ nowSeconds: number,
+ isStreaming: boolean,
+): number | null {
+ let min = Number.POSITIVE_INFINITY;
+ let max = 0;
+ for (const event of events) {
+ const ts = event.timestamp;
+ if (typeof ts !== "number") continue;
+ if (ts < min) min = ts;
+ if (ts > max) max = ts;
+ }
+ if (!Number.isFinite(min)) return null;
+ const end = isStreaming ? Math.max(nowSeconds, max) : max;
+ return Math.max(0, end - min);
+}
+
+/** Compact human-readable duration: ``"12s"``, ``"1m 4s"``, ``"1h 2m"``. */
+export function formatTurnDuration(seconds: number): string {
+ const total = Math.max(0, Math.round(seconds));
+ if (total < 60) return `${total}s`;
+ const minutes = Math.floor(total / 60);
+ const remSeconds = total % 60;
+ if (minutes < 60) {
+ return remSeconds === 0 ? `${minutes}m` : `${minutes}m ${remSeconds}s`;
+ }
+ const hours = Math.floor(minutes / 60);
+ const remMinutes = minutes % 60;
+ return remMinutes === 0 ? `${hours}h` : `${hours}h ${remMinutes}m`;
+}
diff --git a/web/lib/unified-ws.ts b/web/lib/unified-ws.ts
index 3be8bd4b9..ce5520154 100644
--- a/web/lib/unified-ws.ts
+++ b/web/lib/unified-ws.ts
@@ -86,6 +86,10 @@ export interface StartTurnMessage {
}[];
skills?: string[];
llm_selection?: LLMSelection | null;
+ /** Edit-branching: when present (even as ``null``) the new user message
+ * attaches at this exact parent — creating a sibling rather than
+ * appending to the session tail. */
+ parent_message_id?: number | null;
}
export interface SubscribeTurnMessage {
diff --git a/web/lib/use-auto-sized-textarea.ts b/web/lib/use-auto-sized-textarea.ts
new file mode 100644
index 000000000..f2a64e113
--- /dev/null
+++ b/web/lib/use-auto-sized-textarea.ts
@@ -0,0 +1,37 @@
+/**
+ * Auto-grow a controlled textarea so it fits its content from a single
+ * line up to a fixed maximum, after which it scrolls. Sharing one hook
+ * across composers keeps their sizing behavior identical — divergent
+ * imperative implementations have previously caused subtle keystroke
+ * bugs (e.g. height not shrinking after Backspace on a Shift+Enter
+ * line).
+ *
+ * The reset uses ``height: auto`` (not a fixed minimum) so the browser
+ * recomputes ``scrollHeight`` from the actual content rather than from
+ * a stale clipped value — that was the source of the prior shrink bug.
+ */
+
+import { useLayoutEffect, type RefObject } from "react";
+
+export interface AutoSizedTextareaOptions {
+ /** Minimum height in pixels (clamps ``scrollHeight`` from below). */
+ min?: number;
+ /** Maximum height in pixels; beyond this the textarea scrolls. */
+ max?: number;
+}
+
+export function useAutoSizedTextarea(
+ ref: RefObject<HTMLTextAreaElement | null>,
+ value: string,
+ { min = 0, max = Number.POSITIVE_INFINITY }: AutoSizedTextareaOptions = {},
+): void {
+ useLayoutEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ el.style.height = "auto";
+ const natural = el.scrollHeight;
+ const bounded = Math.min(Math.max(natural, min), max);
+ el.style.height = `${bounded}px`;
+ el.style.overflowY = natural > max ? "auto" : "hidden";
+ }, [ref, value, min, max]);
+}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 2873eb370..3c69a8595 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -179,6 +179,7 @@
"Test": "Test",
"Edit": "Edit",
"Delete": "Delete",
+ "Use the arrows below to switch between branches.": "Use the arrows below to switch between branches.",
"No configurations found. Add one to get started.": "No configurations found. Add one to get started.",
"Are you sure you want to delete this configuration?": "Are you sure you want to delete this configuration?",
"Connection test failed": "Connection test failed",
@@ -343,8 +344,35 @@
"Solver History": "Solver History",
"All Activities": "All Activities",
"Filter by type": "Filter by type",
+ "Previous branch": "Previous branch",
+ "Next branch": "Next branch",
+ "Dialog": "Dialog",
+ "Reference space": "Reference space",
+ "Connection lost while generating. Please retry your message.": "Connection lost while generating. Please retry your message.",
+ "Couldn't reach the server. Please check your connection and retry.": "Couldn't reach the server. Please check your connection and retry.",
"Today": "Today",
"Yesterday": "Yesterday",
+ "Last 7 days": "Last 7 days",
+ "Earlier": "Earlier",
+ "Sign in": "Sign in",
+ "Sign in to your account": "Sign in to your account",
+ "Signing in…": "Signing in…",
+ "Login failed": "Login failed",
+ "Email": "Email",
+ "Password": "Password",
+ "Don't have an account?": "Don't have an account?",
+ "Create one": "Create one",
+ "Account created! Sign in to continue.": "Account created! Sign in to continue.",
+ "Create your account": "Create your account",
+ "Create account": "Create account",
+ "Creating account…": "Creating account…",
+ "Confirm password": "Confirm password",
+ "Passwords do not match": "Passwords do not match",
+ "Registration failed": "Registration failed",
+ "Already have an account?": "Already have an account?",
+ "At least 8 characters": "At least 8 characters",
+ "First user:": "First user:",
+ "You will be granted admin privileges and can manage other users from the admin dashboard.": "You will be granted admin privileges and can manage other users from the admin dashboard.",
"session": "session",
"sessions": "sessions",
"Chat": "Chat",
@@ -690,7 +718,9 @@
"Context Window": "Context Window",
"Detected at": "Detected at",
"Unset": "Unset",
+ "Known": "Known",
"Detected from the provider during the latest LLM test and saved into model_catalog.json.": "Detected from the provider during the latest LLM test and saved into model_catalog.json.",
+ "Matched built-in model metadata during the latest LLM test and saved into model_catalog.json.": "Matched built-in model metadata during the latest LLM test and saved into model_catalog.json.",
"The provider did not expose a context window, so the runtime fallback was saved during the latest LLM test.": "The provider did not expose a context window, so the runtime fallback was saved during the latest LLM test.",
"Manual override from Settings. Save Draft to persist your edit.": "Manual override from Settings. Save Draft to persist your edit.",
"Run the LLM test to auto-fill this field, or enter a value manually.": "Run the LLM test to auto-fill this field, or enter a value manually.",
@@ -1017,9 +1047,10 @@
"Manual": "Manual",
"Round {{n}}": "Round {{n}}",
"Step {{n}}": "Step {{n}}",
+ "{{count}} round_one": "{{count}} round",
+ "{{count}} round_other": "{{count}} rounds",
"Generating {{label}}": "Generating {{label}}",
"Writing {{label}}": "Writing {{label}}",
- "{{title}} for {{duration}}": "{{title}} for {{duration}}",
"Question {{n}}": "Question {{n}}",
"research.stage.understand.title": "Understand the question",
"research.stage.understand.hint": "Clarify the topic and research goal first.",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 3a2d61984..095ed8514 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -179,6 +179,7 @@
"Test": "测试",
"Edit": "编辑",
"Delete": "删除",
+ "Use the arrows below to switch between branches.": "通过下方的箭头按钮切换分支。",
"No configurations found. Add one to get started.": "未找到任何配置。请先添加一个配置。",
"Are you sure you want to delete this configuration?": "确定要删除此配置吗?",
"Connection test failed": "连接测试失败",
@@ -343,8 +344,35 @@
"Solver History": "解题历史",
"All Activities": "所有活动",
"Filter by type": "按类型筛选",
+ "Previous branch": "上一个分支",
+ "Next branch": "下一个分支",
+ "Dialog": "对话框",
+ "Reference space": "引用空间",
+ "Connection lost while generating. Please retry your message.": "生成过程中连接已断开,请重新发送消息。",
+ "Couldn't reach the server. Please check your connection and retry.": "无法连接到服务器,请检查网络后重试。",
"Today": "今天",
"Yesterday": "昨天",
+ "Last 7 days": "最近 7 天",
+ "Earlier": "更早",
+ "Sign in": "登录",
+ "Sign in to your account": "登录到你的账户",
+ "Signing in…": "登录中…",
+ "Login failed": "登录失败",
+ "Email": "邮箱",
+ "Password": "密码",
+ "Don't have an account?": "还没有账户?",
+ "Create one": "注册一个",
+ "Account created! Sign in to continue.": "账户创建成功!请登录以继续。",
+ "Create your account": "创建你的账户",
+ "Create account": "创建账户",
+ "Creating account…": "创建账户中…",
+ "Confirm password": "确认密码",
+ "Passwords do not match": "两次输入的密码不一致",
+ "Registration failed": "注册失败",
+ "Already have an account?": "已经有账户了?",
+ "At least 8 characters": "至少 8 个字符",
+ "First user:": "首位用户:",
+ "You will be granted admin privileges and can manage other users from the admin dashboard.": "你将获得管理员权限,可以在管理后台管理其他用户。",
"session": "个会话",
"sessions": "个会话",
"Chat": "聊天",
@@ -690,7 +718,9 @@
"Context Window": "上下文窗口",
"Detected at": "识别时间",
"Unset": "未设置",
+ "Known": "内置识别",
"Detected from the provider during the latest LLM test and saved into model_catalog.json.": "已在最近一次 LLM 测试中从提供商识别出上下文窗口,并写入 model_catalog.json。",
+ "Matched built-in model metadata during the latest LLM test and saved into model_catalog.json.": "已在最近一次 LLM 测试中匹配到内置模型上下文窗口信息,并写入 model_catalog.json。",
"The provider did not expose a context window, so the runtime fallback was saved during the latest LLM test.": "提供商没有暴露上下文窗口信息,因此在最近一次 LLM 测试中写入了运行时默认窗口。",
"Manual override from Settings. Save Draft to persist your edit.": "这是你在设置页中的手动覆盖值。点击“保存草稿”后会持久化。",
"Run the LLM test to auto-fill this field, or enter a value manually.": "运行一次 LLM 测试来自动填充这个字段,或者手动输入。",
@@ -1017,9 +1047,10 @@
"Manual": "手动",
"Round {{n}}": "第 {{n}} 轮",
"Step {{n}}": "第 {{n}} 步",
+ "{{count}} round_one": "{{count}} 轮",
+ "{{count}} round_other": "{{count}} 轮",
"Generating {{label}}": "正在生成 {{label}}",
"Writing {{label}}": "正在撰写 {{label}}",
- "{{title}} for {{duration}}": "{{title}} · 用时 {{duration}}",
"Question {{n}}": "问题 {{n}}",
"research.stage.understand.title": "理解问题",
"research.stage.understand.hint": "先澄清主题与研究目标。",