Skip to content

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

improve chat

Bingxi Zhao (Frank)3d5c3a1eb548
diff --git a/.github/workflows/docker-release.yml b/.github/workflows/docker-release.yml
index c87324ff0..005e88856 100644
--- a/.github/workflows/docker-release.yml
+++ b/.github/workflows/docker-release.yml
@@ -64,10 +64,6 @@ jobs:
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
- # Pass the release tag (e.g. "v1.2.3") into the Next.js build so the
- # sidebar version badge can show the running version at runtime.
- build-args: |
- APP_VERSION=${{ github.ref_name }}
# Use GitHub Actions cache to speed up repeated builds
# mode=max caches all intermediate layers (frontend-builder and python-base are expensive)
cache-from: type=gha
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index c561caaf1..58b2acf5f 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -30,10 +30,15 @@ jobs:
import-check:
name: Import Check (Python ${{ matrix.python-version }})
runs-on: ubuntu-latest
+ continue-on-error: ${{ matrix.experimental == true }}
strategy:
fail-fast: false
matrix:
python-version: ["3.11", "3.12", "3.13"]
+ experimental: [false]
+ include:
+ - python-version: "3.14"
+ experimental: true
steps:
- name: Checkout code
@@ -74,10 +79,15 @@ jobs:
name: Smoke Tests (Python ${{ matrix.python-version }})
runs-on: ubuntu-latest
needs: import-check
+ continue-on-error: ${{ matrix.experimental == true }}
strategy:
fail-fast: false
matrix:
python-version: ["3.11", "3.12", "3.13"]
+ experimental: [false]
+ include:
+ - python-version: "3.14"
+ experimental: true
steps:
- name: Checkout code
@@ -140,8 +150,8 @@ jobs:
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Check | Status |" >> $GITHUB_STEP_SUMMARY
echo "|-------|--------|" >> $GITHUB_STEP_SUMMARY
- echo "| Import check (3.11/3.12/3.13) | ${{ needs.import-check.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
- echo "| Smoke tests (3.11/3.12/3.13) | ${{ needs.smoke-tests.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
+ echo "| Import check (3.11/3.12/3.13; 3.14 best-effort) | ${{ needs.import-check.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
+ echo "| Smoke tests (3.11/3.12/3.13; 3.14 best-effort) | ${{ needs.smoke-tests.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
- name: Fail if tests failed
if: needs.import-check.result == 'failure' || needs.smoke-tests.result == 'failure'
diff --git a/Dockerfile b/Dockerfile
index 5341cdcad..bfa722738 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -24,12 +24,6 @@ FROM --platform=$BUILDPLATFORM node:22-slim AS frontend-builder
WORKDIR /app/web
-# Application version (e.g. "v1.2.3"). Passed by CI from the release tag
-# and inlined into the Next.js bundle via NEXT_PUBLIC_APP_VERSION so the
-# sidebar version badge can compare it with the latest GitHub release.
-ARG APP_VERSION=""
-ENV APP_VERSION=$APP_VERSION
-
# Copy package files first for better caching
COPY web/package.json web/package-lock.json* ./
@@ -41,6 +35,10 @@ RUN npm config set fetch-timeout 600000 && \
# Copy frontend source code
COPY web/ ./
+# Provide the single source of truth for the app version so next.config.js
+# can read it during ``npm run build`` and inline it into the bundle.
+COPY deeptutor/__version__.py /app/deeptutor/__version__.py
+
# Create .env.local with placeholders that will be replaced at runtime.
RUN printf '%s\n' \
'NEXT_PUBLIC_API_BASE=__NEXT_PUBLIC_API_BASE_PLACEHOLDER__' \
@@ -104,20 +102,15 @@ RUN pip install --upgrade pip && \
# ============================================
FROM python:3.11-slim AS production
-ARG APP_VERSION=""
-
# Labels
LABEL maintainer="DeepTutor Team" \
- description="DeepTutor: AI-Powered Personalized Learning Assistant" \
- version="1.0.0"
+ description="DeepTutor: AI-Powered Personalized Learning Assistant"
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PYTHONIOENCODING=utf-8 \
NODE_ENV=production \
- APP_VERSION=${APP_VERSION} \
- NEXT_PUBLIC_APP_VERSION=${APP_VERSION} \
DEEPTUTOR_IGNORE_PROCESS_ENV_OVERRIDES=1
WORKDIR /app
diff --git a/deeptutor/__version__.py b/deeptutor/__version__.py
new file mode 100644
index 000000000..c82d232df
--- /dev/null
+++ b/deeptutor/__version__.py
@@ -0,0 +1,11 @@
+"""Single source of truth for the DeepTutor version.
+
+To cut a release, bump ``__version__`` here, commit, and tag the commit with
+``v<__version__>`` (e.g. ``v1.4.0``). CI verifies the tag matches this value
+before publishing to PyPI; the web sidebar badge and CLI banner read from this
+file directly.
+"""
+
+__version__ = "1.4.0"
+
+__all__ = ("__version__",)
diff --git a/deeptutor/agents/auto/__init__.py b/deeptutor/agents/auto/__init__.py
new file mode 100644
index 000000000..fde70b711
--- /dev/null
+++ b/deeptutor/agents/auto/__init__.py
@@ -0,0 +1,5 @@
+"""Auto routing pipeline — agent loop that delegates to other capabilities."""
+
+from deeptutor.agents.auto.auto_pipeline import AutoPipeline
+
+__all__ = ["AutoPipeline"]
diff --git a/deeptutor/agents/auto/auto_pipeline.py b/deeptutor/agents/auto/auto_pipeline.py
new file mode 100644
index 000000000..c7c6abdb8
--- /dev/null
+++ b/deeptutor/agents/auto/auto_pipeline.py
@@ -0,0 +1,1017 @@
+"""Auto pipeline: three-stage agent loop that routes between capabilities.
+
+Stages
+------
+1. **ANALYZING** — one LLM call (no tools) that acknowledges the user's intent.
+ Streamed as THINKING events.
+2. **DELEGATING LOOP** — up to ``max_iterations`` iterations. Each iteration:
+ * Call the router LLM with capability + atomic tool schemas. Retries on
+ transient API/format errors up to ``max_retries_per_step`` (using the
+ ``router_llm_retries`` budget). Streams thinking inline.
+ * If the LLM returns plain text → that's the final answer, break.
+ * If it returns ``tool_call``(s) → dispatch each sequentially:
+ - ``delegate_to_<cap>``: validate args, enforce same_cap quota (max
+ ``max_same_capability_calls``), run sub-capability with per-step
+ retry (``per_delegation_retries`` budget). The error of a failed
+ delegation is fed back to the router as the tool result so the loop
+ continues.
+ - atomic tool name: dispatch via ToolRegistry with kb_name auto-inject.
+3. **SYNTHESIZING** — if the loop exited via natural text we emit that.
+ Otherwise (loop ran out of iterations) we make one synthesizer LLM call to
+ produce a final inline answer from the accumulated trace.
+
+Failure semantics
+-----------------
+* Three independent retry budgets, all defaulting to 3 (configurable via
+ ``AutoRequestConfig.max_retries_per_step``): ``router_llm_retries`` (API/
+ network), ``per_delegation_retries`` (sub-capability raise / ERROR event).
+ Args-validation errors are NOT counted — the router gets the validation
+ message back and self-corrects on the next iteration.
+* ``same_cap_calls`` only increments on a successfully completed delegation.
+* Cancellation propagates via ``asyncio.CancelledError`` — every awaited
+ sub-task lives under ``run()`` so cleanup is automatic.
+* ``answer_now`` triggers a fast-path: skip analyzing + delegating and produce
+ an immediate inline message.
+
+Conversation-history non-pollution
+----------------------------------
+Sub-capability events flow through ``delegation.forward_events`` which injects
+``metadata.call_id`` on every CONTENT event. The existing
+``_should_capture_assistant_content`` filter in turn_runtime drops those.
+Auto's own synthesis CONTENT is emitted **without** ``call_id`` (or with
+``call_kind="llm_final_response"``) so it alone reaches conversation_history.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from collections import defaultdict
+from dataclasses import dataclass, field
+import json
+import logging
+from typing import Any
+
+import httpx
+from openai import APIError, AsyncAzureOpenAI, AsyncOpenAI
+
+from deeptutor.agents.auto.delegation import (
+ AtomicToolResult,
+ DelegationResult,
+ delegate_with_retry,
+ execute_atomic_tool,
+)
+from deeptutor.agents.auto.prompts import (
+ analyzer_system_prompt,
+ pick_language,
+ router_system_prompt,
+ synthesizer_system_prompt,
+)
+from deeptutor.agents.auto.schemas import (
+ build_all_tool_schemas,
+ extract_capability_name,
+ is_delegate_tool,
+)
+from deeptutor.capabilities._answer_now import extract_answer_now_context
+from deeptutor.capabilities.request_contracts import (
+ AutoRequestConfig,
+ validate_auto_request_config,
+ validate_capability_config,
+)
+from deeptutor.core.context import UnifiedContext
+from deeptutor.core.stream_bus import StreamBus
+from deeptutor.core.trace import build_trace_metadata, new_call_id
+from deeptutor.runtime.registry.capability_registry import get_capability_registry
+from deeptutor.runtime.registry.tool_registry import get_tool_registry
+from deeptutor.services.config import load_system_settings
+from deeptutor.services.llm import get_llm_config, get_token_limit_kwargs
+
+logger = logging.getLogger(__name__)
+
+ROUTER_MAX_TOKENS = 2000
+ANALYZER_MAX_TOKENS = 400
+SYNTHESIZER_MAX_TOKENS = 800
+
+_ROUTER_TRANSIENT_EXCEPTIONS: tuple[type[BaseException], ...] = (APIError, asyncio.TimeoutError)
+
+
+# --------------------------------------------------------------------------- #
+# Loop state #
+# --------------------------------------------------------------------------- #
+
+
+@dataclass
+class _LoopState:
+ """State carried through the delegating loop.
+
+ Keeping it in a single dataclass makes it easy to test and to pass to the
+ synthesizer, and removes the need to thread half a dozen parameters
+ through every helper.
+ """
+
+ messages: list[dict[str, Any]] = field(default_factory=list)
+ same_cap_calls: dict[str, int] = field(default_factory=lambda: defaultdict(int))
+ delegations: list[DelegationResult] = field(default_factory=list)
+ atomic_results: list[AtomicToolResult] = field(default_factory=list)
+ router_llm_retries: int = 0
+ iteration: int = 0
+ final_text: str | None = None
+ terminal_failure_reason: str | None = None
+
+ def increment_iteration(self) -> int:
+ self.iteration += 1
+ return self.iteration
+
+
+# --------------------------------------------------------------------------- #
+# AutoPipeline #
+# --------------------------------------------------------------------------- #
+
+
+class AutoPipeline:
+ """Three-stage agent loop for the ``auto`` capability."""
+
+ def __init__(self, language: str = "en") -> None:
+ self.language = pick_language(language)
+ self.llm_config = get_llm_config()
+ self.binding = getattr(self.llm_config, "binding", None) or "openai"
+ self.model = getattr(self.llm_config, "model", None)
+ self.api_key = getattr(self.llm_config, "api_key", None)
+ self.base_url = getattr(self.llm_config, "base_url", None)
+ self.api_version = getattr(self.llm_config, "api_version", None)
+ self.extra_headers = getattr(self.llm_config, "extra_headers", None) or {}
+ self.cap_registry = get_capability_registry()
+ self.tool_registry = get_tool_registry()
+
+ # ====================================================================== #
+ # Entry point #
+ # ====================================================================== #
+
+ async def run(self, context: UnifiedContext, stream: StreamBus) -> None:
+ auto_config = validate_auto_request_config(_strip_runtime_keys(context.config_overrides))
+
+ # Fast-path: user clicked "Answer Now" mid-turn.
+ answer_now_payload = extract_answer_now_context(context)
+ if answer_now_payload is not None:
+ await self._run_answer_now(context, stream, answer_now_payload)
+ return
+
+ await self._stage_analyzing(context, stream)
+ loop_state = await self._stage_delegating(context, stream, auto_config)
+ await self._stage_synthesizing(context, stream, loop_state, auto_config)
+
+ # ====================================================================== #
+ # Stage 1: ANALYZING #
+ # ====================================================================== #
+
+ async def _stage_analyzing(self, context: UnifiedContext, stream: StreamBus) -> None:
+ trace_meta = build_trace_metadata(
+ call_id=new_call_id("auto-analyzing"),
+ phase="analyzing",
+ label="Analyzing request",
+ call_kind="llm_analysis",
+ trace_id="auto-analyzing",
+ trace_role="auto",
+ trace_group="auto_analyzer",
+ )
+ async with stream.stage("analyzing", source="auto"):
+ await stream.progress(
+ "Analyzing request",
+ source="auto",
+ stage="analyzing",
+ metadata={**trace_meta, "trace_kind": "call_status", "call_state": "running"},
+ )
+ messages = [
+ {"role": "system", "content": analyzer_system_prompt(self.language)},
+ {"role": "user", "content": context.user_message or ""},
+ ]
+ # ``_call_llm_text`` already streams each delta as a THINKING event
+ # so the user sees the analyzer's text live. We deliberately do NOT
+ # re-emit a "consolidated" THINKING after the stream — that would
+ # double the text in the UI's thought block.
+ await self._call_llm_text(
+ messages=messages,
+ max_tokens=ANALYZER_MAX_TOKENS,
+ stream=stream,
+ stage="analyzing",
+ trace_meta=trace_meta,
+ )
+ await stream.progress(
+ "",
+ source="auto",
+ stage="analyzing",
+ metadata={**trace_meta, "trace_kind": "call_status", "call_state": "complete"},
+ )
+
+ # ====================================================================== #
+ # Stage 2: DELEGATING LOOP #
+ # ====================================================================== #
+
+ async def _stage_delegating(
+ self,
+ context: UnifiedContext,
+ stream: StreamBus,
+ auto_config: AutoRequestConfig,
+ ) -> _LoopState:
+ state = _LoopState()
+ state.messages = self._build_initial_router_messages(context)
+ tool_schemas = build_all_tool_schemas(
+ self.cap_registry,
+ self.tool_registry,
+ enabled_capabilities=auto_config.enabled_capabilities or None,
+ enabled_tools_hint=context.enabled_tools,
+ )
+
+ while state.iteration < auto_config.max_iterations:
+ iter_no = state.increment_iteration()
+ async with stream.stage(
+ "delegating",
+ source="auto",
+ metadata={"iteration": iter_no},
+ ):
+ router_outcome = await self._router_call_with_retry(
+ messages=state.messages,
+ tool_schemas=tool_schemas,
+ stream=stream,
+ state=state,
+ max_retries=auto_config.max_retries_per_step,
+ iteration=iter_no,
+ )
+ if router_outcome.terminal_failure:
+ state.terminal_failure_reason = "router_llm_exhausted"
+ return state
+
+ # Append the assistant turn (whether it had text, tool_calls, or both)
+ # so subsequent iterations see the full history.
+ state.messages.append(router_outcome.assistant_message)
+
+ if not router_outcome.tool_calls:
+ state.final_text = router_outcome.assistant_text
+ return state
+
+ await self._dispatch_tool_calls(
+ context=context,
+ stream=stream,
+ state=state,
+ tool_calls=router_outcome.tool_calls,
+ auto_config=auto_config,
+ )
+
+ return state
+
+ def _build_initial_router_messages(self, context: UnifiedContext) -> list[dict[str, Any]]:
+ """Compose the initial system + history + user messages for the router."""
+ system_msgs: list[dict[str, Any]] = [
+ {"role": "system", "content": router_system_prompt(self.language)},
+ ]
+ history = list(context.conversation_history or [])
+ user_blob = context.user_message or ""
+ hints = self._render_context_hints(context)
+ if hints:
+ user_blob = f"{user_blob}\n\n[available context]\n{hints}"
+ return [*system_msgs, *history, {"role": "user", "content": user_blob}]
+
+ def _render_context_hints(self, context: UnifiedContext) -> str:
+ parts: list[str] = []
+ if context.knowledge_bases:
+ parts.append(f"User-selected KB(s): {', '.join(context.knowledge_bases)}")
+ if context.enabled_tools:
+ parts.append(f"User-selected tool(s): {', '.join(context.enabled_tools)}")
+ if context.attachments:
+ atts = [f"{a.type}:{a.filename or '(unnamed)'}" for a in context.attachments]
+ parts.append(f"Attachments: {', '.join(atts)}")
+ return "\n".join(parts)
+
+ # --- Router LLM call with retry on transient errors ------------------- #
+
+ async def _router_call_with_retry(
+ self,
+ *,
+ messages: list[dict[str, Any]],
+ tool_schemas: list[dict[str, Any]],
+ stream: StreamBus,
+ state: _LoopState,
+ max_retries: int,
+ iteration: int,
+ ) -> _RouterOutcome:
+ """Call the router LLM, retrying up to ``max_retries - state.router_llm_retries`` times.
+
+ Retries consume the ``router_llm_retries`` budget. When the budget is
+ exhausted we return ``terminal_failure=True`` and the caller bails out
+ with a visible ERROR event.
+ """
+ local_messages = list(messages)
+ while True:
+ remaining = max_retries - state.router_llm_retries
+ if remaining <= 0:
+ await stream.error(
+ f"Auto routing failed: router LLM exhausted {max_retries} retries.",
+ source="auto",
+ stage="delegating",
+ metadata={
+ "terminal": True,
+ "failure_reason": "router_llm_exhausted",
+ "iteration": iteration,
+ },
+ )
+ return _RouterOutcome.terminal_failure_outcome()
+ try:
+ outcome = await self._router_call_once(
+ messages=local_messages,
+ tool_schemas=tool_schemas,
+ stream=stream,
+ iteration=iteration,
+ )
+ return outcome
+ except asyncio.CancelledError:
+ raise
+ except _RouterFormatError as exc:
+ # The LLM returned something we couldn't parse (bad JSON in
+ # tool_call arguments etc). Feed the error back and retry.
+ state.router_llm_retries += 1
+ await stream.error(
+ f"Router output unparseable: {exc}",
+ source="auto",
+ stage="delegating",
+ metadata={
+ "trace_kind": "router_format_error",
+ "retry_count": state.router_llm_retries,
+ "max_retries": max_retries,
+ },
+ )
+ local_messages = local_messages + [
+ {
+ "role": "user",
+ "content": (
+ f"Your previous response could not be parsed: {exc}. "
+ "Please try again, ensuring tool call arguments are valid JSON."
+ ),
+ }
+ ]
+ except _ROUTER_TRANSIENT_EXCEPTIONS as exc:
+ state.router_llm_retries += 1
+ await stream.error(
+ f"Router LLM error (attempt {state.router_llm_retries}/{max_retries}): {exc}",
+ source="auto",
+ stage="delegating",
+ metadata={
+ "trace_kind": "router_api_error",
+ "retry_count": state.router_llm_retries,
+ "max_retries": max_retries,
+ },
+ )
+ local_messages = local_messages + [
+ {
+ "role": "user",
+ "content": (
+ f"The previous LLM call failed transiently: {exc}. "
+ "Please retry the same decision."
+ ),
+ }
+ ]
+
+ async def _router_call_once(
+ self,
+ *,
+ messages: list[dict[str, Any]],
+ tool_schemas: list[dict[str, Any]],
+ stream: StreamBus,
+ iteration: int,
+ ) -> _RouterOutcome:
+ """One non-retrying router LLM call. Streams thinking; parses tool_calls.
+
+ Raises ``_RouterFormatError`` on malformed tool_call arguments so the
+ caller can decide to retry.
+ """
+ trace_meta = build_trace_metadata(
+ call_id=new_call_id("auto-routing"),
+ phase="delegating",
+ label="Auto routing",
+ call_kind="tool_planning",
+ trace_id="auto-routing",
+ trace_role="tool",
+ trace_group="auto_routing",
+ iteration=iteration,
+ )
+ await stream.progress(
+ "Auto routing",
+ source="auto",
+ stage="delegating",
+ metadata={**trace_meta, "trace_kind": "call_status", "call_state": "running"},
+ )
+
+ text, tool_calls_raw = await self._stream_router_completion(
+ messages=messages,
+ tool_schemas=tool_schemas,
+ stream=stream,
+ trace_meta=trace_meta,
+ )
+
+ await stream.progress(
+ "",
+ source="auto",
+ stage="delegating",
+ metadata={**trace_meta, "trace_kind": "call_status", "call_state": "complete"},
+ )
+
+ # Parse tool_calls.
+ parsed_calls: list[_ParsedToolCall] = []
+ for entry in tool_calls_raw:
+ name = entry.get("name") or ""
+ args_str = entry.get("arguments") or "{}"
+ try:
+ args = json.loads(args_str) if args_str.strip() else {}
+ except json.JSONDecodeError as exc:
+ raise _RouterFormatError(
+ f"tool_call '{name}' has invalid JSON arguments: {exc}"
+ ) from exc
+ if not isinstance(args, dict):
+ args = {}
+ parsed_calls.append(
+ _ParsedToolCall(id=entry.get("id") or "", name=name, args=args, raw_args=args_str)
+ )
+
+ # Build the assistant message we'll re-feed in the next iteration.
+ assistant_message: dict[str, Any] = {
+ "role": "assistant",
+ "content": text or None,
+ }
+ if parsed_calls:
+ assistant_message["tool_calls"] = [
+ {
+ "id": tc.id,
+ "type": "function",
+ "function": {"name": tc.name, "arguments": tc.raw_args},
+ }
+ for tc in parsed_calls
+ ]
+
+ return _RouterOutcome(
+ assistant_text=text,
+ tool_calls=parsed_calls,
+ assistant_message=assistant_message,
+ )
+
+ async def _stream_router_completion(
+ self,
+ *,
+ messages: list[dict[str, Any]],
+ tool_schemas: list[dict[str, Any]],
+ stream: StreamBus,
+ trace_meta: dict[str, Any],
+ ) -> tuple[str, list[dict[str, Any]]]:
+ """Make the streaming LLM call and accumulate content + tool_calls.
+
+ Emits each text chunk as a THINKING event so the user sees router
+ reasoning live. Tool_call deltas are accumulated silently (streaming
+ partial JSON args is noisy and not user-meaningful).
+ """
+ client = self._build_openai_client()
+ api_stream = await client.chat.completions.create(
+ model=self.model,
+ messages=messages,
+ tools=tool_schemas or None,
+ tool_choice="auto" if tool_schemas else None,
+ stream=True,
+ **self._completion_kwargs(ROUTER_MAX_TOKENS),
+ )
+
+ content_chunks: list[str] = []
+ tool_calls_accum: dict[int, dict[str, str]] = {}
+
+ async for chunk in api_stream:
+ choices = getattr(chunk, "choices", None)
+ if not choices:
+ continue
+ delta = getattr(choices[0], "delta", None)
+ if delta is None:
+ continue
+
+ delta_content = getattr(delta, "content", None)
+ if delta_content:
+ content_chunks.append(delta_content)
+ await stream.thinking(
+ delta_content,
+ source="auto",
+ stage="delegating",
+ metadata={**trace_meta, "trace_kind": "llm_chunk"},
+ )
+
+ delta_tool_calls = getattr(delta, "tool_calls", None) or []
+ for tc in delta_tool_calls:
+ idx = getattr(tc, "index", 0) or 0
+ bucket = tool_calls_accum.setdefault(
+ idx, {"id": "", "name": "", "arguments": ""}
+ )
+ if getattr(tc, "id", None):
+ bucket["id"] = tc.id
+ func = getattr(tc, "function", None)
+ if func is not None:
+ if getattr(func, "name", None):
+ bucket["name"] += func.name
+ if getattr(func, "arguments", None):
+ bucket["arguments"] += func.arguments
+
+ full_text = "".join(content_chunks).strip()
+ tool_calls_ordered = [tool_calls_accum[idx] for idx in sorted(tool_calls_accum.keys())]
+ return full_text, tool_calls_ordered
+
+ # --- Tool-call dispatch ----------------------------------------------- #
+
+ async def _dispatch_tool_calls(
+ self,
+ *,
+ context: UnifiedContext,
+ stream: StreamBus,
+ state: _LoopState,
+ tool_calls: list[_ParsedToolCall],
+ auto_config: AutoRequestConfig,
+ ) -> None:
+ for call in tool_calls:
+ tool_message = await self._handle_one_tool_call(
+ context=context,
+ stream=stream,
+ state=state,
+ call=call,
+ auto_config=auto_config,
+ )
+ state.messages.append(tool_message)
+
+ async def _handle_one_tool_call(
+ self,
+ *,
+ context: UnifiedContext,
+ stream: StreamBus,
+ state: _LoopState,
+ call: _ParsedToolCall,
+ auto_config: AutoRequestConfig,
+ ) -> dict[str, Any]:
+ """Dispatch a single tool_call. Returns the OpenAI ``role=tool`` reply message."""
+ if is_delegate_tool(call.name):
+ cap_name = extract_capability_name(call.name) or ""
+ return await self._handle_capability_delegation(
+ context=context,
+ stream=stream,
+ state=state,
+ call=call,
+ cap_name=cap_name,
+ auto_config=auto_config,
+ )
+ # Atomic tool path.
+ result = await execute_atomic_tool(
+ tool_name=call.name,
+ raw_args=call.args,
+ parent_context=context,
+ parent_stream=stream,
+ tool_registry=self.tool_registry,
+ )
+ state.atomic_results.append(result)
+ if result.succeeded:
+ payload = result.content or "(empty result)"
+ else:
+ payload = f"Atomic tool {call.name} failed: {result.error_message}"
+ return {
+ "role": "tool",
+ "tool_call_id": call.id,
+ "name": call.name,
+ "content": payload,
+ }
+
+ async def _handle_capability_delegation(
+ self,
+ *,
+ context: UnifiedContext,
+ stream: StreamBus,
+ state: _LoopState,
+ call: _ParsedToolCall,
+ cap_name: str,
+ auto_config: AutoRequestConfig,
+ ) -> dict[str, Any]:
+ """Validate args, enforce quotas, run sub-cap with retry. Returns tool-role message."""
+ # Same-capability quota: only counts successful completions.
+ if state.same_cap_calls[cap_name] >= auto_config.max_same_capability_calls:
+ payload = (
+ f"Cannot call {cap_name} again — already used "
+ f"{auto_config.max_same_capability_calls}/"
+ f"{auto_config.max_same_capability_calls} allowed times. "
+ "Choose a different capability or finalize a text answer."
+ )
+ await stream.error(
+ payload,
+ source="auto",
+ stage="delegating",
+ metadata={
+ "trace_kind": "same_cap_exhausted",
+ "delegated_capability": cap_name,
+ },
+ )
+ return {"role": "tool", "tool_call_id": call.id, "name": call.name, "content": payload}
+
+ # Args validation: NOT counted against per_delegation_retries; the
+ # router sees the error and self-corrects.
+ config_payload = call.args.get("config") if isinstance(call.args.get("config"), dict) else {}
+ try:
+ validated_config = validate_capability_config(cap_name, config_payload)
+ except ValueError as exc:
+ await stream.error(
+ f"Invalid args for {cap_name}: {exc}",
+ source="auto",
+ stage="delegating",
+ metadata={
+ "trace_kind": "validation_error",
+ "delegated_capability": cap_name,
+ },
+ )
+ payload = (
+ f"Invalid args for {cap_name}: {exc}. "
+ "Re-issue the call with corrected arguments."
+ )
+ return {"role": "tool", "tool_call_id": call.id, "name": call.name, "content": payload}
+
+ # Allow the LLM to override per-delegation tool/KB scope.
+ enabled_tools_override = _coerce_str_list(call.args.get("enabled_tools"))
+ kbs_override = _coerce_str_list(call.args.get("knowledge_bases"))
+
+ result = await delegate_with_retry(
+ cap_name=cap_name,
+ config=validated_config,
+ parent_context=context,
+ parent_stream=stream,
+ max_retries=auto_config.max_retries_per_step,
+ enabled_tools=enabled_tools_override,
+ knowledge_bases=kbs_override,
+ )
+ state.delegations.append(result)
+ # Count BOTH successes and failures toward the same-cap quota.
+ # Otherwise a buggy capability can be retried indefinitely by the
+ # router (each "retry" being a fresh router decision that costs
+ # latency / tokens / sub-cap attempts).
+ state.same_cap_calls[cap_name] += 1
+ if result.succeeded:
+ summary = _summarize_delegation_success(cap_name, result)
+ else:
+ summary = (
+ f"Sub-capability {cap_name} failed after {auto_config.max_retries_per_step} "
+ f"retries: {result.error_message or 'unknown error'}. "
+ "Pick a different capability or finalize a text answer."
+ )
+ return {"role": "tool", "tool_call_id": call.id, "name": call.name, "content": summary}
+
+ # ====================================================================== #
+ # Stage 3: SYNTHESIZING #
+ # ====================================================================== #
+
+ async def _stage_synthesizing(
+ self,
+ context: UnifiedContext,
+ stream: StreamBus,
+ state: _LoopState,
+ auto_config: AutoRequestConfig,
+ ) -> None:
+ trace_meta = build_trace_metadata(
+ call_id=new_call_id("auto-synthesizing"),
+ phase="synthesizing",
+ label="Final synthesis",
+ call_kind="llm_final_response",
+ trace_id="auto-synthesizing",
+ trace_role="auto",
+ trace_group="auto_synthesizer",
+ )
+ async with stream.stage("synthesizing", source="auto"):
+ if state.terminal_failure_reason:
+ # Don't make another LLM call after a terminal failure; emit a
+ # short factual message + result envelope.
+ fail_text = self._terminal_failure_text(state.terminal_failure_reason)
+ await stream.content(
+ fail_text,
+ source="auto",
+ stage="synthesizing",
+ metadata={"call_kind": "llm_final_response"},
+ )
+ await stream.result(
+ {
+ "response": fail_text,
+ "auto_summary": _build_auto_summary(state),
+ },
+ source="auto",
+ )
+ return
+
+ if state.final_text is not None and state.final_text.strip():
+ # The router gave us a finished text reply; use it verbatim.
+ text = state.final_text.strip()
+ else:
+ # Loop ran out of iterations or only made tool calls. Compose
+ # one final synthesis from the trace.
+ text = await self._call_llm_text(
+ messages=[
+ {"role": "system", "content": synthesizer_system_prompt(self.language)},
+ {
+ "role": "user",
+ "content": _render_synthesizer_user_blob(context, state),
+ },
+ ],
+ max_tokens=SYNTHESIZER_MAX_TOKENS,
+ stream=stream,
+ stage="synthesizing",
+ trace_meta=trace_meta,
+ )
+ if not text:
+ text = self._fallback_text(state)
+
+ await stream.content(
+ text,
+ source="auto",
+ stage="synthesizing",
+ metadata={"call_kind": "llm_final_response"},
+ )
+ await stream.result(
+ {
+ "response": text,
+ "auto_summary": _build_auto_summary(state),
+ },
+ source="auto",
+ )
+
+ def _terminal_failure_text(self, reason: str) -> str:
+ if self.language == "zh":
+ return (
+ "Auto 路由失败,已经多次重试仍未恢复。"
+ "建议切到 Manual 模式手动选择 capability,或重试当前消息。"
+ )
+ return (
+ "Auto routing failed after exhausting retries. "
+ "Switch to Manual mode and pick a capability, or try the message again."
+ )
+
+ def _fallback_text(self, state: _LoopState) -> str:
+ if not state.delegations and not state.atomic_results:
+ return self._t(
+ en="I couldn't decide on a tool to use. Try rephrasing the question.",
+ zh="无法判断该用哪个工具。请尝试换个说法。",
+ )
+ bits: list[str] = []
+ for d in state.delegations:
+ if d.succeeded:
+ bits.append(f"`{d.capability}` ran successfully")
+ else:
+ bits.append(f"`{d.capability}` failed")
+ if state.atomic_results:
+ bits.append(f"{len(state.atomic_results)} atomic tool call(s) ran")
+ joined = "; ".join(bits)
+ return self._t(
+ en=f"Done: {joined}.",
+ zh=f"已完成:{joined}。",
+ )
+
+ # ====================================================================== #
+ # Answer Now fast-path #
+ # ====================================================================== #
+
+ async def _run_answer_now(
+ self,
+ context: UnifiedContext,
+ stream: StreamBus,
+ payload: dict[str, Any],
+ ) -> None:
+ """Fast-path when the user clicks 'Answer Now' mid-turn.
+
+ We don't try to re-run any sub-capabilities — just emit a brief inline
+ message based on whatever the frontend already has. The cancelled
+ sub-task in the previous attempt (if any) will be GC'd; this turn is
+ independent.
+ """
+ async with stream.stage(
+ "synthesizing",
+ source="auto",
+ metadata={"trace_kind": "auto_answer_now"},
+ ):
+ original = str(payload.get("original_user_message") or "").strip()
+ partial = str(payload.get("partial_response") or "").strip()
+ text = self._answer_now_text(original=original, partial=partial)
+ await stream.content(
+ text,
+ source="auto",
+ stage="synthesizing",
+ metadata={"call_kind": "llm_final_response", "answer_now": True},
+ )
+ await stream.result(
+ {
+ "response": text,
+ "metadata": {"answer_now": True},
+ "auto_summary": {
+ "iterations": 0,
+ "delegations": [],
+ "router_retries": 0,
+ "terminal_failure_reason": None,
+ "final_path": "answer_now",
+ },
+ },
+ source="auto",
+ )
+
+ def _answer_now_text(self, *, original: str, partial: str) -> str:
+ if partial:
+ return self._t(
+ en=(
+ f"You requested an immediate answer. Here's what I have so far based on "
+ f"the partial trace: {partial}"
+ ),
+ zh=f"已根据当前进度生成回答:{partial}",
+ )
+ if self.language == "zh":
+ return (
+ "已停止 Auto 路由。请切到 Manual 模式直接选择 capability "
+ "或重新发送消息以获得更完整的结果。"
+ )
+ return (
+ "Auto routing was interrupted before any result was produced. Switch to Manual "
+ "and pick a capability, or resend the message for a fresh attempt."
+ )
+
+ # ====================================================================== #
+ # LLM plumbing #
+ # ====================================================================== #
+
+ async def _call_llm_text(
+ self,
+ *,
+ messages: list[dict[str, Any]],
+ max_tokens: int,
+ stream: StreamBus,
+ stage: str,
+ trace_meta: dict[str, Any],
+ ) -> str:
+ """Streaming LLM call with no tools. Emits THINKING chunks; returns full text."""
+ client = self._build_openai_client()
+ api_stream = await client.chat.completions.create(
+ model=self.model,
+ messages=messages,
+ stream=True,
+ **self._completion_kwargs(max_tokens),
+ )
+ chunks: list[str] = []
+ async for chunk in api_stream:
+ choices = getattr(chunk, "choices", None)
+ if not choices:
+ continue
+ delta = getattr(choices[0], "delta", None)
+ if delta is None:
+ continue
+ delta_content = getattr(delta, "content", None)
+ if delta_content:
+ chunks.append(delta_content)
+ await stream.thinking(
+ delta_content,
+ source="auto",
+ stage=stage,
+ metadata={**trace_meta, "trace_kind": "llm_chunk"},
+ )
+ return "".join(chunks).strip()
+
+ 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": 0.2}
+ if self.model:
+ kwargs.update(get_token_limit_kwargs(self.model, max_tokens))
+ return kwargs
+
+ def _t(self, *, en: str, zh: str) -> str:
+ return zh if self.language == "zh" else en
+
+
+# --------------------------------------------------------------------------- #
+# Module-level helpers #
+# --------------------------------------------------------------------------- #
+
+
+class _RouterFormatError(Exception):
+ """Raised when the router LLM emits a tool_call we can't parse."""
+
+
+@dataclass
+class _ParsedToolCall:
+ id: str
+ name: str
+ args: dict[str, Any]
+ raw_args: str
+
+
+@dataclass
+class _RouterOutcome:
+ assistant_text: str = ""
+ tool_calls: list[_ParsedToolCall] = field(default_factory=list)
+ assistant_message: dict[str, Any] = field(default_factory=dict)
+ terminal_failure: bool = False
+
+ @classmethod
+ def terminal_failure_outcome(cls) -> _RouterOutcome:
+ return cls(terminal_failure=True)
+
+
+def _coerce_str_list(value: Any) -> list[str] | None:
+ if value is None:
+ return None
+ if isinstance(value, list):
+ out = [str(v) for v in value if isinstance(v, (str, int)) and str(v)]
+ return out or None
+ return None
+
+
+def _strip_runtime_keys(config_overrides: dict[str, Any] | None) -> dict[str, Any]:
+ """Strip keys that belong on the runtime side, not on AutoRequestConfig itself."""
+ if not isinstance(config_overrides, dict):
+ return {}
+ cleaned = dict(config_overrides)
+ cleaned.pop("answer_now_context", None)
+ return cleaned
+
+
+def _summarize_delegation_success(cap_name: str, result: DelegationResult) -> str:
+ """Compact summary fed to the router as the tool-role result."""
+ meta = result.result_metadata or {}
+ response_snippet = str(meta.get("response") or "").strip()
+ if response_snippet:
+ clipped = response_snippet[:600] + ("..." if len(response_snippet) > 600 else "")
+ return (
+ f"`{cap_name}` completed successfully. Result preview: {clipped}. "
+ "The user can see the full output above; you do not need to repeat it."
+ )
+ return f"`{cap_name}` completed successfully."
+
+
+def _render_synthesizer_user_blob(context: UnifiedContext, state: _LoopState) -> str:
+ """Compose the user-message blob for the synthesizer LLM call."""
+ parts: list[str] = []
+ parts.append(f"Original request: {context.user_message or ''}")
+ if state.delegations:
+ lines = []
+ for d in state.delegations:
+ status = "OK" if d.succeeded else f"FAIL ({d.error_message})"
+ lines.append(f"- {d.capability}: {status}")
+ parts.append("Capability calls:\n" + "\n".join(lines))
+ if state.atomic_results:
+ lines = []
+ for r in state.atomic_results:
+ status = "OK" if r.succeeded else f"FAIL ({r.error_message})"
+ lines.append(f"- {r.tool_name}: {status}")
+ parts.append("Atomic tool calls:\n" + "\n".join(lines))
+ if state.iteration:
+ parts.append(f"Iterations used: {state.iteration}")
+ return "\n\n".join(parts)
+
+
+def _build_auto_summary(state: _LoopState) -> dict[str, Any]:
+ """Telemetry payload attached to the final RESULT event.
+
+ Stable shape — frontend / analytics consumers depend on these keys.
+ """
+ final_path: str
+ if state.terminal_failure_reason:
+ final_path = "terminal_error"
+ elif state.final_text is not None:
+ final_path = "text_response"
+ else:
+ final_path = "synthesis"
+ return {
+ "iterations": state.iteration,
+ "delegations": [
+ {
+ "capability": d.capability,
+ "attempts": d.attempt,
+ "succeeded": d.succeeded,
+ "error": d.error_message,
+ }
+ for d in state.delegations
+ ],
+ "atomic_calls": [
+ {
+ "tool": r.tool_name,
+ "succeeded": r.succeeded,
+ "error": r.error_message,
+ }
+ for r in state.atomic_results
+ ],
+ "router_retries": state.router_llm_retries,
+ "terminal_failure_reason": state.terminal_failure_reason,
+ "final_path": final_path,
+ }
diff --git a/deeptutor/agents/auto/delegation.py b/deeptutor/agents/auto/delegation.py
new file mode 100644
index 000000000..edb1b59c9
--- /dev/null
+++ b/deeptutor/agents/auto/delegation.py
@@ -0,0 +1,408 @@
+"""Sub-capability delegation + atomic tool dispatch for the Auto pipeline.
+
+The Auto pipeline is the first place in the codebase where one capability
+invokes another in-process. All complexity of (1) constructing a child
+``UnifiedContext``, (2) running the sub-capability against a child
+``StreamBus``, (3) forwarding child events to the parent stream with proper
+metadata, and (4) retrying transient failures lives here.
+
+Conversation-history non-pollution invariant: every CONTENT event forwarded
+from a sub-capability gets ``metadata.call_id`` injected (if absent) so the
+existing ``_should_capture_assistant_content`` filter in turn_runtime drops it
+from persisted assistant content. Auto's own final synthesis emits CONTENT
+without ``call_id`` (or with ``call_kind="llm_final_response"``), so it alone
+reaches conversation_history.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass, field, replace
+import logging
+from typing import Any
+
+from deeptutor.core.context import UnifiedContext
+from deeptutor.core.stream import StreamEvent, StreamEventType
+from deeptutor.core.stream_bus import StreamBus
+from deeptutor.core.trace import merge_trace_metadata, new_call_id
+from deeptutor.runtime.registry.capability_registry import get_capability_registry
+from deeptutor.runtime.registry.tool_registry import ToolRegistry
+
+logger = logging.getLogger(__name__)
+
+
+# --------------------------------------------------------------------------- #
+# Result types #
+# --------------------------------------------------------------------------- #
+
+
+@dataclass
+class DelegationResult:
+ """Outcome of a single sub-capability invocation."""
+
+ capability: str
+ delegation_call_id: str
+ attempt: int
+ succeeded: bool
+ error_message: str | None = None
+ # Last RESULT event metadata emitted by the sub-capability, if any.
+ # The router consumes this as the "observation" of what happened.
+ result_metadata: dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass
+class AtomicToolResult:
+ """Outcome of executing an atomic tool via ToolRegistry."""
+
+ tool_name: str
+ succeeded: bool
+ content: str = ""
+ error_message: str | None = None
+ sources: list[dict[str, Any]] = field(default_factory=list)
+ metadata: dict[str, Any] = field(default_factory=dict)
+
+
+# --------------------------------------------------------------------------- #
+# Child-context construction #
+# --------------------------------------------------------------------------- #
+
+
+def build_child_context(
+ parent: UnifiedContext,
+ *,
+ cap_name: str,
+ config: dict[str, Any],
+ delegation_call_id: str,
+ enabled_tools: list[str] | None = None,
+ knowledge_bases: list[str] | None = None,
+) -> UnifiedContext:
+ """Derive an immutable child context for a sub-capability invocation.
+
+ Uses ``dataclasses.replace`` so the parent context is never mutated. Adds
+ ``is_sub_invocation`` and ``parent_delegation_call_id`` to ``metadata`` so
+ sub-capabilities can recognize they're being invoked by Auto.
+ """
+ child_metadata = {
+ **(parent.metadata or {}),
+ "is_sub_invocation": True,
+ "parent_delegation_call_id": delegation_call_id,
+ }
+ return replace(
+ parent,
+ active_capability=cap_name,
+ config_overrides=dict(config or {}),
+ enabled_tools=(
+ list(enabled_tools)
+ if enabled_tools is not None
+ else (list(parent.enabled_tools) if parent.enabled_tools is not None else None)
+ ),
+ knowledge_bases=(
+ list(knowledge_bases) if knowledge_bases else list(parent.knowledge_bases or [])
+ ),
+ metadata=child_metadata,
+ )
+
+
+# --------------------------------------------------------------------------- #
+# Event forwarding #
+# --------------------------------------------------------------------------- #
+
+
+async def _forward_one(
+ event: StreamEvent,
+ parent_stream: StreamBus,
+ *,
+ cap_name: str,
+ delegation_call_id: str,
+ attempt: int,
+) -> None:
+ injected: dict[str, Any] = {
+ "parent_call_id": delegation_call_id,
+ "delegated_capability": cap_name,
+ "delegated_from": "auto",
+ "delegation_attempt": attempt,
+ }
+ # CONTENT events without call_id would pollute conversation_history. Inject
+ # one so turn_runtime's _should_capture_assistant_content filter drops them.
+ if event.type == StreamEventType.CONTENT:
+ existing_meta = event.metadata or {}
+ if not existing_meta.get("call_id"):
+ injected["call_id"] = delegation_call_id
+
+ merged = merge_trace_metadata(event.metadata, injected)
+ await parent_stream.emit(
+ StreamEvent(
+ type=event.type,
+ source=event.source or cap_name,
+ stage=event.stage,
+ content=event.content,
+ metadata=merged,
+ session_id=event.session_id,
+ turn_id=event.turn_id,
+ seq=event.seq,
+ timestamp=event.timestamp,
+ )
+ )
+
+
+# --------------------------------------------------------------------------- #
+# Single-attempt capability delegation #
+# --------------------------------------------------------------------------- #
+
+
+async def _run_one_attempt(
+ *,
+ cap_name: str,
+ config: dict[str, Any],
+ parent_context: UnifiedContext,
+ parent_stream: StreamBus,
+ enabled_tools: list[str] | None = None,
+ knowledge_bases: list[str] | None = None,
+ attempt: int = 1,
+) -> DelegationResult:
+ """Run a sub-capability once and forward its events.
+
+ No retry. Caller decides whether to call again on failure. Always returns
+ a DelegationResult; never raises on sub-capability error (except for
+ ``CancelledError``, which propagates).
+ """
+ delegation_call_id = new_call_id("auto-delegation")
+ registry = get_capability_registry()
+ capability = registry.get(cap_name)
+ if capability is None:
+ await parent_stream.error(
+ f"Unknown capability for auto delegation: {cap_name}",
+ source="auto",
+ stage="delegating",
+ metadata={
+ "delegated_capability": cap_name,
+ "delegation_call_id": delegation_call_id,
+ "delegation_attempt": attempt,
+ },
+ )
+ return DelegationResult(
+ capability=cap_name,
+ delegation_call_id=delegation_call_id,
+ attempt=attempt,
+ succeeded=False,
+ error_message=f"unknown_capability: {cap_name}",
+ )
+
+ child_context = build_child_context(
+ parent_context,
+ cap_name=cap_name,
+ config=config,
+ delegation_call_id=delegation_call_id,
+ enabled_tools=enabled_tools,
+ knowledge_bases=knowledge_bases,
+ )
+ child_bus = StreamBus()
+
+ async def _runner() -> Exception | None:
+ try:
+ await capability.run(child_context, child_bus)
+ return None
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # noqa: BLE001 -- we report the error verbatim
+ logger.exception("Auto delegation to %s raised", cap_name)
+ return exc
+ finally:
+ await child_bus.close()
+
+ last_result_metadata: dict[str, Any] = {}
+ saw_error_event = False
+
+ async def _forwarder() -> None:
+ nonlocal last_result_metadata, saw_error_event
+ async for event in child_bus.subscribe():
+ if event.type == StreamEventType.RESULT:
+ last_result_metadata = dict(event.metadata or {})
+ elif event.type == StreamEventType.ERROR:
+ saw_error_event = True
+ await _forward_one(
+ event,
+ parent_stream,
+ cap_name=cap_name,
+ delegation_call_id=delegation_call_id,
+ attempt=attempt,
+ )
+
+ runner_task = asyncio.create_task(_runner())
+ forwarder_task = asyncio.create_task(_forwarder())
+ runner_exc, _ = await asyncio.gather(runner_task, forwarder_task)
+
+ if runner_exc is not None:
+ return DelegationResult(
+ capability=cap_name,
+ delegation_call_id=delegation_call_id,
+ attempt=attempt,
+ succeeded=False,
+ error_message=f"{type(runner_exc).__name__}: {runner_exc}",
+ result_metadata=last_result_metadata,
+ )
+ if saw_error_event:
+ return DelegationResult(
+ capability=cap_name,
+ delegation_call_id=delegation_call_id,
+ attempt=attempt,
+ succeeded=False,
+ error_message="sub_capability_emitted_error",
+ result_metadata=last_result_metadata,
+ )
+ return DelegationResult(
+ capability=cap_name,
+ delegation_call_id=delegation_call_id,
+ attempt=attempt,
+ succeeded=True,
+ result_metadata=last_result_metadata,
+ )
+
+
+# Public alias for callers who only want one attempt (e.g. PR 1 tests).
+delegate_to_capability = _run_one_attempt
+
+
+async def delegate_with_retry(
+ *,
+ cap_name: str,
+ config: dict[str, Any],
+ parent_context: UnifiedContext,
+ parent_stream: StreamBus,
+ max_retries: int = 3,
+ enabled_tools: list[str] | None = None,
+ knowledge_bases: list[str] | None = None,
+) -> DelegationResult:
+ """Run a sub-capability with up to ``max_retries`` attempts.
+
+ Attempts are numbered 1..max_retries. Between attempts we emit a visible
+ retry-marker ERROR event so the frontend can render a "Retry K/N" badge.
+ Returns the final DelegationResult (success on first ok attempt, or the
+ last failure if all attempts fail). Never raises except on cancellation.
+ """
+ last: DelegationResult | None = None
+ for attempt in range(1, max_retries + 1):
+ result = await _run_one_attempt(
+ cap_name=cap_name,
+ config=config,
+ parent_context=parent_context,
+ parent_stream=parent_stream,
+ enabled_tools=enabled_tools,
+ knowledge_bases=knowledge_bases,
+ attempt=attempt,
+ )
+ last = result
+ if result.succeeded:
+ return result
+ # Failure: emit a retry-marker so the UI can render "🔄 Retry K/N".
+ # Only emit when more attempts remain.
+ if attempt < max_retries:
+ await parent_stream.error(
+ f"{cap_name} attempt {attempt}/{max_retries} failed: "
+ f"{result.error_message or 'unknown error'}",
+ source="auto",
+ stage="delegating",
+ metadata={
+ "delegated_capability": cap_name,
+ "delegation_call_id": result.delegation_call_id,
+ "retry_count": attempt,
+ "max_retries": max_retries,
+ "trace_kind": "delegation_retry",
+ },
+ )
+ # ``last`` is guaranteed non-None because max_retries >= 1.
+ assert last is not None
+ return last
+
+
+# --------------------------------------------------------------------------- #
+# Atomic tool dispatch #
+# --------------------------------------------------------------------------- #
+
+
+def _augment_atomic_args(
+ tool_name: str,
+ args: dict[str, Any],
+ parent_context: UnifiedContext,
+) -> dict[str, Any]:
+ """Inject trusted UI/session values that the LLM does not see.
+
+ Currently only RAG: ``kb_name`` is a server-side value chosen by the user,
+ not an LLM argument. Mirrors AgenticChatPipeline's _augment_tool_kwargs.
+ """
+ augmented = dict(args or {})
+ if tool_name == "rag":
+ if parent_context.knowledge_bases:
+ augmented.setdefault("kb_name", parent_context.knowledge_bases[0])
+ return augmented
+
+
+async def execute_atomic_tool(
+ tool_name: str,
+ raw_args: dict[str, Any],
+ parent_context: UnifiedContext,
+ parent_stream: StreamBus,
+ tool_registry: ToolRegistry,
+ *,
+ call_id: str | None = None,
+) -> AtomicToolResult:
+ """Execute one atomic tool and emit corresponding stream events.
+
+ The router LLM calls these by name (e.g. ``rag``, ``web_search``). On
+ failure we return a structured result instead of raising — the caller
+ feeds the error back to the router as a tool message so it can recover.
+ """
+ call_id = call_id or new_call_id("auto-atomic")
+ metadata_base = {
+ "delegated_from": "auto",
+ "call_id": call_id,
+ "tool_kind": "atomic",
+ }
+
+ await parent_stream.tool_call(
+ tool_name=tool_name,
+ args=raw_args,
+ source="auto",
+ stage="delegating",
+ metadata=metadata_base,
+ )
+
+ augmented = _augment_atomic_args(tool_name, raw_args, parent_context)
+ try:
+ result = await tool_registry.execute(tool_name, **augmented)
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # noqa: BLE001
+ logger.exception("Atomic tool %s raised", tool_name)
+ await parent_stream.error(
+ f"Atomic tool {tool_name} failed: {exc}",
+ source="auto",
+ stage="delegating",
+ metadata={**metadata_base, "trace_kind": "atomic_tool_error"},
+ )
+ return AtomicToolResult(
+ tool_name=tool_name,
+ succeeded=False,
+ error_message=f"{type(exc).__name__}: {exc}",
+ )
+
+ success = bool(getattr(result, "success", True))
+ content = str(getattr(result, "content", "") or "")
+ sources = list(getattr(result, "sources", []) or [])
+ meta = dict(getattr(result, "metadata", {}) or {})
+
+ await parent_stream.tool_result(
+ tool_name=tool_name,
+ result=content,
+ source="auto",
+ stage="delegating",
+ metadata={**metadata_base, "success": success},
+ )
+ return AtomicToolResult(
+ tool_name=tool_name,
+ succeeded=success,
+ content=content,
+ error_message=None if success else "tool_reported_failure",
+ sources=sources,
+ metadata=meta,
+ )
diff --git a/deeptutor/agents/auto/prompts.py b/deeptutor/agents/auto/prompts.py
new file mode 100644
index 000000000..655dec9cc
--- /dev/null
+++ b/deeptutor/agents/auto/prompts.py
@@ -0,0 +1,139 @@
+"""Fixed system prompts for the Auto routing pipeline.
+
+All prompts are production text; nothing here is user-configurable. The router
+prompt is intentionally short — the tool schemas carry most of the structural
+information, and we want the model to read them rather than re-decide based on
+prose. The behaviour we DO encode in prose is the cross-cutting stuff that
+isn't expressible in schemas: when to delegate vs answer directly, what to do
+when a tool result reports an error, and when to stop the loop.
+"""
+
+from __future__ import annotations
+
+
+def pick_language(language: str) -> str:
+ """Normalize language code to 'zh' or 'en'."""
+ return "zh" if (language or "en").lower().startswith("zh") else "en"
+
+
+# --------------------------------------------------------------------------- #
+# Analyzer — emits a short acknowledgement so the user knows their request is #
+# understood. Runs once, before the loop. Streamed inline as THINKING. #
+# --------------------------------------------------------------------------- #
+
+
+ANALYZER_SYSTEM_EN = (
+ "You are the Auto Routing assistant. Acknowledge the user's request in one "
+ "short sentence so they know you understood it. Be specific (mention what they "
+ "are asking about), but do not attempt to solve the problem here — a "
+ "specialized capability will handle the work next."
+)
+ANALYZER_SYSTEM_ZH = (
+ "你是 Auto 路由助手。用一句简短的话复述并确认用户的需求(要具体、点出他们问的内容)。"
+ "不要直接回答问题——下一步会有专门的 capability 处理。"
+)
+
+
+def analyzer_system_prompt(language: str) -> str:
+ return ANALYZER_SYSTEM_ZH if pick_language(language) == "zh" else ANALYZER_SYSTEM_EN
+
+
+# --------------------------------------------------------------------------- #
+# Router — the system prompt that drives each iteration of the delegating #
+# loop. The router sees the capabilities + atomic tools as functions in the #
+# OpenAI tool schema; this prompt covers the cross-cutting decision rules. #
+# --------------------------------------------------------------------------- #
+
+
+ROUTER_SYSTEM_EN = """\
+You are the Auto Routing assistant. Your job is to fulfill the user's request by:
+
+1. Picking the most appropriate capability or atomic tool from the available functions, OR
+2. Answering directly with plain text when the request is trivially answerable
+ without specialized capabilities (greetings, definitions you can give in 1-2
+ sentences, follow-up clarifications).
+
+ROUTING PRINCIPLES
+- Capabilities (delegate_to_*) handle multi-step work: solving problems, generating quizzes,
+ doing research, producing visualizations or math animations. Prefer these when the user's
+ request maps cleanly to one of them.
+- Atomic tools (rag, web_search, paper_search, code_execution, reason, brainstorm) are
+ cheaper and faster. Use them when you only need to fetch a fact, run a quick computation,
+ or do a single reasoning step before answering.
+- When the user has uploaded attachments or selected knowledge bases, factor that into
+ your choice — e.g. a quiz request alongside a PDF often means "mimic this paper's style".
+- For deep_research, you MUST generate the `confirmed_outline` yourself (3-5 sub-topics,
+ each with a one-line `overview`) so the research pipeline can skip the user-confirmation
+ step. Do not call delegate_to_deep_research without it.
+
+ERROR RECOVERY
+- If a previous tool message reports an error ("Invalid args for X: ..." or
+ "Sub-capability failed: ..."), READ the error carefully. Then either:
+ (a) call the same tool again with corrected arguments, or
+ (b) pick a different capability/tool, or
+ (c) give up and produce a plain-text answer summarizing what is known.
+- Do NOT silently retry without fixing the underlying issue.
+
+TERMINATION
+- As soon as you have enough information to answer the user, respond with plain text
+ (no tool call). The loop will stop and the text becomes the final answer.
+- Do not call tools speculatively — every call costs latency and money.
+"""
+
+ROUTER_SYSTEM_ZH = """\
+你是 Auto 路由助手。你的任务是处理用户的请求,方式有两种:
+
+1. 从可用的函数(capability / 原子工具)中选择最合适的一个调用,或者
+2. 当请求可以无需特化能力就直接回答时(打招呼、1-2 句能说清的定义、follow-up 澄清),
+ 直接用纯文本回答。
+
+路由原则
+- delegate_to_* 是多步骤能力:解题、出题、做研究报告、生成可视化、生成数学动画。
+ 用户需求能干净映射到其中一个时优先选它。
+- 原子工具(rag, web_search, paper_search, code_execution, reason, brainstorm)便宜更快。
+ 只需取个事实、跑一次计算、做一次推理就够时选它们。
+- 当用户上传了附件或选了知识库时,要考虑这些上下文 —— 比如带 PDF 的出题请求往往意味着
+ "按这篇论文的风格仿写"。
+- 对 deep_research,你必须自己生成 `confirmed_outline`(3-5 个子主题,每个一行
+ `overview`),让研究流水线跳过用户确认环节。不要不带 confirmed_outline 调用
+ delegate_to_deep_research。
+
+错误恢复
+- 如果之前的 tool 消息报告了错误("Invalid args for X: ..." 或
+ "Sub-capability failed: ..."),仔细阅读错误信息。然后:
+ (a) 用修正后的参数再调一次同一个工具,或
+ (b) 换一个 capability / 工具,或
+ (c) 放弃,用纯文本总结现有信息回答。
+- 不要在没修正根本问题的情况下盲目重试。
+
+终止
+- 一旦你能直接回答用户,请直接用纯文本回复(不调工具)。loop 会停止,文本即为最终回答。
+- 不要"猜测性"调用工具 —— 每次调用都有延迟和成本。
+"""
+
+
+def router_system_prompt(language: str) -> str:
+ return ROUTER_SYSTEM_ZH if pick_language(language) == "zh" else ROUTER_SYSTEM_EN
+
+
+# --------------------------------------------------------------------------- #
+# Synthesizer — runs at the end if the router did not produce final text #
+# directly. Composes a final inline message based on what happened. #
+# --------------------------------------------------------------------------- #
+
+
+SYNTHESIZER_SYSTEM_EN = (
+ "You are the Auto Routing assistant. Based on the trace of tool calls and "
+ "results below, write a concise final reply (2-4 sentences) for the user. "
+ "Acknowledge what was produced (the user can see the full result above). "
+ "If important results were missing or some steps failed, say so plainly."
+)
+SYNTHESIZER_SYSTEM_ZH = (
+ "你是 Auto 路由助手。基于下方工具调用和结果的 trace,给用户写一个简短的最终回复"
+ "(2-4 句话)。承认已经产出了什么(完整结果用户能直接在上方看到)。"
+ "如果有重要结果缺失或某些步骤失败,请明确说明。"
+)
+
+
+def synthesizer_system_prompt(language: str) -> str:
+ return SYNTHESIZER_SYSTEM_ZH if pick_language(language) == "zh" else SYNTHESIZER_SYSTEM_EN
diff --git a/deeptutor/agents/auto/schemas.py b/deeptutor/agents/auto/schemas.py
new file mode 100644
index 000000000..7f18bb020
--- /dev/null
+++ b/deeptutor/agents/auto/schemas.py
@@ -0,0 +1,153 @@
+"""Construct OpenAI tool schemas for the Auto router LLM.
+
+The router LLM sees two kinds of tools:
+
+* ``delegate_to_<capability>`` — one per enabled capability. Parameters wrap
+ the capability's own ``request_schema`` under a ``config`` field plus a
+ free-form ``rationale`` string.
+* Atomic tools (``rag``, ``web_search``, ``code_execution``, ``reason``,
+ ``brainstorm``, ``paper_search``) — exposed verbatim from
+ ``ToolRegistry.build_openai_schemas`` with the same RAG ``kb_name`` stripping
+ that the chat pipeline already applies.
+
+Auto never offers itself, ``chat``, or ``geogebra_analysis`` to the router.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from deeptutor.runtime.registry.capability_registry import CapabilityRegistry
+from deeptutor.runtime.registry.tool_registry import ToolRegistry
+
+# Auto must not recurse into itself; chat is a generic tool-using capability
+# whose value-add (autonomous tool selection) is already what the router does,
+# so excluding it avoids redundant LLM hops.
+EXCLUDED_CAPABILITIES = {"auto", "chat"}
+
+# Mirrors AgenticChatPipeline.CHAT_EXCLUDED_TOOLS — geogebra_analysis is a
+# vision-pipeline tool that needs a specific UI surface.
+EXCLUDED_ATOMIC_TOOLS = {"geogebra_analysis"}
+
+_DELEGATE_PREFIX = "delegate_to_"
+
+
+def _capability_tool_name(cap_name: str) -> str:
+ return f"{_DELEGATE_PREFIX}{cap_name}"
+
+
+def _ensure_object_schema(schema: dict[str, Any] | None) -> dict[str, Any]:
+ """Coerce a possibly-empty pydantic schema into a valid JSON Schema object."""
+ if not isinstance(schema, dict):
+ return {"type": "object", "properties": {}}
+ cleaned = dict(schema)
+ cleaned.setdefault("type", "object")
+ cleaned.setdefault("properties", {})
+ cleaned.pop("title", None)
+ return cleaned
+
+
+def _wrap_capability_params(request_schema: dict[str, Any]) -> dict[str, Any]:
+ """Wrap a capability's request_schema as the parameters of delegate_to_*."""
+ return {
+ "type": "object",
+ "properties": {
+ "config": _ensure_object_schema(request_schema),
+ "rationale": {
+ "type": "string",
+ "description": (
+ "One short sentence explaining why this capability is the best "
+ "fit for the user's request."
+ ),
+ },
+ },
+ "required": ["config"],
+ "additionalProperties": False,
+ }
+
+
+def build_capability_tool_schemas(
+ registry: CapabilityRegistry,
+ enabled_capabilities: list[str] | None,
+) -> list[dict[str, Any]]:
+ """Build ``delegate_to_<cap>`` function schemas for enabled capabilities.
+
+ Empty/None ``enabled_capabilities`` means "all registered capabilities".
+ """
+ candidate_names = enabled_capabilities or registry.list_capabilities()
+ schemas: list[dict[str, Any]] = []
+ for cap_name in candidate_names:
+ if cap_name in EXCLUDED_CAPABILITIES:
+ continue
+ capability = registry.get(cap_name)
+ if capability is None:
+ continue
+ manifest = capability.manifest
+ schemas.append(
+ {
+ "type": "function",
+ "function": {
+ "name": _capability_tool_name(cap_name),
+ "description": manifest.description,
+ "parameters": _wrap_capability_params(manifest.request_schema),
+ },
+ }
+ )
+ return schemas
+
+
+def build_atomic_tool_schemas(
+ tool_registry: ToolRegistry,
+ enabled_tools: list[str] | None,
+) -> list[dict[str, Any]]:
+ """Expose atomic tools to the router LLM.
+
+ ``enabled_tools`` is a hint from the user's manual-mode selection. If
+ provided, only those tools are exposed; otherwise all builtin tools
+ (minus ``EXCLUDED_ATOMIC_TOOLS``) are. The RAG schema has ``kb_name``
+ stripped because that's a server-side / trusted UI value, not an LLM arg.
+ """
+ candidate_names: list[str] = list(enabled_tools) if enabled_tools else [
+ name for name in tool_registry.list_tools() if name not in EXCLUDED_ATOMIC_TOOLS
+ ]
+ candidate_names = [n for n in candidate_names if n not in EXCLUDED_ATOMIC_TOOLS]
+ schemas = tool_registry.build_openai_schemas(candidate_names)
+ for schema in schemas:
+ function = schema.get("function") if isinstance(schema, dict) else None
+ if not isinstance(function, dict) or function.get("name") != "rag":
+ continue
+ params = function.get("parameters")
+ if not isinstance(params, dict):
+ continue
+ properties = params.get("properties")
+ if isinstance(properties, dict):
+ properties.pop("kb_name", None)
+ required = params.get("required")
+ if isinstance(required, list):
+ params["required"] = [name for name in required if name != "kb_name"]
+ params["additionalProperties"] = False
+ return schemas
+
+
+def build_all_tool_schemas(
+ capability_registry: CapabilityRegistry,
+ tool_registry: ToolRegistry,
+ enabled_capabilities: list[str] | None,
+ enabled_tools_hint: list[str] | None,
+) -> list[dict[str, Any]]:
+ """Build the full list of tools the router LLM sees in one call."""
+ return [
+ *build_capability_tool_schemas(capability_registry, enabled_capabilities),
+ *build_atomic_tool_schemas(tool_registry, enabled_tools_hint),
+ ]
+
+
+def extract_capability_name(tool_name: str) -> str | None:
+ """Reverse of ``_capability_tool_name``; returns None if not a delegate tool."""
+ if tool_name.startswith(_DELEGATE_PREFIX):
+ return tool_name[len(_DELEGATE_PREFIX):] or None
+ return None
+
+
+def is_delegate_tool(tool_name: str) -> bool:
+ return tool_name.startswith(_DELEGATE_PREFIX)
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index 8262400ac..6a2849e04 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -179,15 +179,7 @@ class AgenticChatPipeline:
await stream.result(result_payload, source="chat")
return
- requested_tools = self._normalize_enabled_tools(context.enabled_tools)
- enabled_tools = self._drop_rag_without_selected_kb(requested_tools, context)
- if "rag" in requested_tools and "rag" not in enabled_tools:
- await stream.progress(
- self._rag_without_kb_message(),
- source="chat",
- stage="thinking",
- metadata={"reason": "rag_without_kb"},
- )
+ 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,
@@ -586,7 +578,7 @@ class AgenticChatPipeline:
thinking_text: str,
stream: StreamBus,
) -> list[ToolTrace]:
- tool_schemas = self._build_llm_tool_schemas(enabled_tools)
+ 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),
@@ -676,16 +668,13 @@ class AgenticChatPipeline:
)
if not isinstance(tool_args, dict):
tool_args = {}
- display_args = self._llm_visible_tool_args(tool_name, tool_args)
execution_args = self._augment_tool_kwargs(
tool_name,
- display_args,
+ tool_args,
context,
thinking_text,
)
- if tool_name == "rag":
- display_args = self._llm_visible_tool_args(tool_name, execution_args)
- pending_calls.append((tool_call.id, tool_name, display_args, execution_args))
+ 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
@@ -814,7 +803,7 @@ class AgenticChatPipeline:
),
)
_fb_prompt = self._acting_user_prompt(context, thinking_text)
- _fb_system = self._react_fallback_system_prompt(tool_table)
+ _fb_system = self._react_fallback_system_prompt(tool_table, context)
_chunks: list[str] = []
async for _c in llm_stream(
prompt=_fb_prompt,
@@ -851,6 +840,13 @@ class AgenticChatPipeline:
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:
@@ -877,10 +873,8 @@ class AgenticChatPipeline:
)
return tool_traces
- display_args = self._llm_visible_tool_args(action, action_input)
- tool_args = self._augment_tool_kwargs(action, display_args, context, thinking_text)
- if action == "rag":
- display_args = self._llm_visible_tool_args(action, tool_args)
+ tool_args = self._augment_tool_kwargs(action, action_input, context, thinking_text)
+ display_args = dict(tool_args)
if response:
await stream.thinking(
response,
@@ -963,9 +957,6 @@ class AgenticChatPipeline:
user_content: str,
) -> list[dict[str, Any]]:
system_parts = [system_prompt]
- kb_note = self._current_kb_system_note(context)
- if kb_note:
- system_parts.append(kb_note)
if context.memory_context:
system_parts.append(context.memory_context)
if context.skills_context:
@@ -1060,22 +1051,36 @@ class AgenticChatPipeline:
"llama_cpp",
}
- def _normalize_enabled_tools(self, enabled_tools: list[str] | None) -> list[str]:
- selected = enabled_tools or []
- return [
+ 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.
+ """
+ requested = [tool for tool in (context.enabled_tools or []) if tool != "rag"]
+ normalized = [
tool.name
- for tool in self.registry.get_enabled(selected)
+ for tool in self.registry.get_enabled(requested)
if tool.name not in CHAT_EXCLUDED_TOOLS
]
+ if self._selected_kbs(context):
+ normalized.append("rag")
+ return normalized
- def _build_llm_tool_schemas(self, enabled_tools: list[str]) -> list[dict[str, Any]]:
- """Return tool schemas for the acting LLM.
+ def _build_llm_tool_schemas(
+ self,
+ enabled_tools: list[str],
+ context: UnifiedContext,
+ ) -> list[dict[str, Any]]:
+ """Return per-turn OpenAI tool schemas.
- RAG's knowledge-base choice is a trusted UI/session value, not an LLM
- argument. The model only sees whether it can call ``rag`` and what
- retrieval query to send.
+ 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.
"""
schemas = self.registry.build_openai_schemas(enabled_tools)
+ kb_choices = self._selected_kbs(context)
for schema in schemas:
function = schema.get("function") if isinstance(schema, dict) else None
if not isinstance(function, dict) or function.get("name") != "rag":
@@ -1085,23 +1090,15 @@ class AgenticChatPipeline:
continue
properties = parameters.get("properties")
if isinstance(properties, dict):
- properties.pop("kb_name", None)
query_schema = properties.get("query")
if isinstance(query_schema, dict):
query_schema.setdefault("minLength", 1)
- required = parameters.get("required")
- if isinstance(required, list):
- parameters["required"] = [name for name in required if name != "kb_name"]
+ kb_schema = properties.get("kb_name")
+ if isinstance(kb_schema, dict):
+ kb_schema["enum"] = kb_choices
parameters["additionalProperties"] = False
return schemas
- @staticmethod
- def _llm_visible_tool_args(tool_name: str, args: dict[str, Any]) -> dict[str, Any]:
- if tool_name != "rag":
- return dict(args)
- query = str(args.get("query") or "").strip()
- return {"query": query} if query else {}
-
@staticmethod
def _extract_answer_now_context(context: UnifiedContext) -> dict[str, Any] | None:
# Delegate to the shared helper so every capability uses the
@@ -1136,27 +1133,6 @@ class AgenticChatPipeline:
),
)
- if tool_name == "rag" and not str(tool_args.get("kb_name") or "").strip():
- message = self._rag_without_kb_message()
- if stream is not None and retrieve_meta is not None:
- await stream.progress(
- message,
- source="chat",
- stage="acting",
- metadata=derive_trace_metadata(
- retrieve_meta,
- trace_kind="call_status",
- call_state="skipped",
- reason="no_kb_selected",
- ),
- )
- return {
- "result_text": message,
- "success": True,
- "sources": [],
- "metadata": {"status": "skipped", "reason": "no_kb_selected"},
- }
-
if stream is not None and retrieve_meta is not None:
query = str(retrieve_meta.get("query") or tool_args.get("query") or "").strip()
await stream.progress(
@@ -1279,12 +1255,6 @@ class AgenticChatPipeline:
if turn_id:
task_dir = get_path_service().get_task_workspace("chat", turn_id)
if tool_name == "rag":
- selected_kbs = self._selected_kbs(context)
- if not str(kwargs.get("query") or "").strip():
- fallback_query = self._fallback_rag_query(context)
- if fallback_query:
- kwargs["query"] = fallback_query
- kwargs["kb_name"] = selected_kbs[0] if selected_kbs else ""
kwargs.setdefault("mode", "hybrid")
elif tool_name == "code_execution":
kwargs.setdefault("intent", context.user_message)
@@ -1306,21 +1276,11 @@ class AgenticChatPipeline:
kwargs.setdefault("output_dir", str(task_dir / "web_search"))
return kwargs
- @staticmethod
- def _fallback_rag_query(context: UnifiedContext) -> str:
- message = str(context.user_message or "")
- marker = "[User Question]\n"
- if marker in message:
- message = message.rsplit(marker, 1)[-1]
- return " ".join(message.split())[:800]
-
def _acting_system_prompt(self, enabled_tools: list[str], context: UnifiedContext) -> str:
- kb_name = context.knowledge_bases[0] if context.knowledge_bases else ""
tool_list = self.registry.build_prompt_text(
enabled_tools,
format="list",
language=self.language,
- kb_name=kb_name,
)
tool_aliases = self.registry.build_prompt_text(
enabled_tools,
@@ -1332,60 +1292,41 @@ class AgenticChatPipeline:
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) -> str:
- return self._t("react_fallback.system", tool_table=tool_table)
+ 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:
- kb_name = context.knowledge_bases[0] if context.knowledge_bases else ""
tool_list = self.registry.build_prompt_text(
enabled_tools,
format="list",
language=self.language,
- kb_name=kb_name,
)
- has_kb = "rag" in enabled_tools and bool(context.knowledge_bases)
- kb_hint = self._t("thinking.kb_hint") if has_kb else ""
return self._t(
"thinking.system",
tool_list=tool_list or self._fallback_empty_tool_list(),
- kb_hint=kb_hint,
+ kb_note=self._kb_system_note(context),
)
def _selected_kbs(self, context: UnifiedContext) -> list[str]:
return [str(kb).strip() for kb in context.knowledge_bases if str(kb).strip()]
- def _drop_rag_without_selected_kb(
- self,
- enabled_tools: list[str],
- context: UnifiedContext,
- ) -> list[str]:
- if "rag" not in enabled_tools or self._selected_kbs(context):
- return enabled_tools
- return [tool for tool in enabled_tools if tool != "rag"]
-
- def _current_kb_system_note(self, context: UnifiedContext) -> str:
- if not self._selected_kbs(context):
+ 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":
- return (
- "本轮已有系统态选中的知识库。如果需要知识库检索,只需调用 RAG 并提供非空 query;"
- "不要输出、猜测或沿用任何知识库名称,也不要传 kb_name。系统会把 query 发到当前选中的知识库。"
- )
- return (
- "A knowledge base is selected in system state for this turn. "
- "If retrieval is useful, call RAG with only a non-empty query; do not output, "
- "guess, reuse, or pass any knowledge-base name. The system will route "
- "the query to the currently selected knowledge base."
- )
-
- def _rag_without_kb_message(self) -> str:
- if getattr(self, "language", "en") == "zh":
- return "已启用 RAG,但当前没有选择知识库;本轮将跳过知识库检索。"
+ return f"用户已挂载知识库:{joined}。调用 rag 时,kb_name 必须从其中选一个。"
return (
- "RAG is enabled, but no knowledge base is selected; "
- "skipping KB retrieval for this turn."
+ 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:
diff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
index 15e82c873..7103cb89c 100644
--- a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
+++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
@@ -31,12 +31,10 @@ thinking:
- 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_hint}
+
+ {kb_note}
Enabled tools:
{tool_list}
- # Injected at {kb_hint} when RAG is enabled and a knowledge base is selected
- kb_hint: |-
- - A knowledge base is active (RAG). The question may benefit from retrieval. Assess whether KB retrieval would help and plan accordingly — avoid premature conclusions from memory alone.
user: |-
[User request]
{user_message}
@@ -55,11 +53,12 @@ acting:
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, you MUST provide a non-empty query field. The query should be a natural-language retrieval sentence extracted or rewritten from the user request or thinking. Do not pass an empty object, an empty string, or kb_name.
+ 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}
@@ -139,7 +138,8 @@ react_fallback:
Available actions:
{tool_table}
- 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 be {{"query": "non-empty retrieval query"}}; do not pass an empty object, an empty string, or kb_name. If no tool is needed, set action=done.
+ {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."
diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
index 4c12bbea6..68a5d1bd9 100644
--- a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
+++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
@@ -31,12 +31,10 @@ thinking:
- 你只输出内部分析备忘,不要给出面向用户的回答、结论或解题过程。
- 可以提及预计使用哪些工具,但不要真正调用工具。
- 保持简洁,不超过 200 字。
- {kb_hint}
+
+ {kb_note}
当前启用工具:
{tool_list}
- # 当 RAG 工具启用且有知识库时,会插入到 system 的 {kb_hint} 占位处
- kb_hint: |-
- - 用户已启用知识库检索(RAG),其问题可能需要从知识库中获取答案。请评估问题是否适合通过检索来回答,并据此规划检索策略,避免过早从记忆中得出结论。
user: |-
[用户问题]
{user_message}
@@ -55,11 +53,12 @@ acting:
2. 对于需要定义、事实核验、外部资料、论文、计算、推理等不同信息面的复杂问题,优先并行调用多个互补工具来覆盖这些信息面。
3. 只调用真正有帮助的工具,但只要工具能显著提升答案质量,就应充分调用。
4. 参数要具体、可执行,优先使用用户原问题中的关键信息,必要时针对不同工具改写成最适合它的查询。
- 5. 调用 RAG 时,必须提供非空的 query 字段;query 应是从用户问题或 thinking 中抽取/改写出的自然语言检索句。不要传空对象、空字符串或 kb_name。
+ 5. 调用 rag 时,query 必须是非空的自然语言检索句,kb_name 必须从已挂载的知识库中选一个。如果要查多个知识库,请在同一轮内对每个 kb_name 各发起一次 rag 调用。
6. 如果信息已经足够,可以不调用工具。
7. 不要输出最终回答给学生;这里只负责工具选择与调用。
8. 单轮最多并行调用 {max_parallel_tools} 个工具;如果有多个互补工具都相关,优先在同一轮一起调用。
+ {kb_note}
当前可用工具:
{tool_list}
@@ -139,7 +138,8 @@ react_fallback:
可选动作如下:
{tool_table}
- 先基于用户问题和可用工具列表判断是否真的需要工具;若需要,请选择最能补足关键信息缺口的那个工具。如果调用 rag,action_input 必须是 {{"query": "非空检索句"}},不要传空对象、空字符串或 kb_name。如果不需要工具,请输出 action=done。
+ {kb_note}
+ 先基于用户问题和可用工具列表判断是否真的需要工具;若需要,请选择最能补足关键信息缺口的那个工具。如果调用 rag,action_input 中 query 必须是非空检索句。如果不需要工具,请输出 action=done。
done_when_to_use: "当已有信息足够,且不需要继续调用工具时使用。"
done_input_format: "空字符串。"
diff --git a/deeptutor/agents/research/agents/note_agent.py b/deeptutor/agents/research/agents/note_agent.py
index 9245d5fb5..5c5c0aeb2 100644
--- a/deeptutor/agents/research/agents/note_agent.py
+++ b/deeptutor/agents/research/agents/note_agent.py
@@ -164,6 +164,16 @@ class NoteAgent(BaseAgent):
data = parse_json_response(raw_answer, fallback=None)
if data is None:
return ""
+ # Some tools (notably ``paper_search``) return a JSON list at the top
+ # level rather than an object. Wrap it in a sensible envelope so the
+ # downstream ``data.get(...)`` calls don't blow up with an
+ # ``AttributeError: 'list' object has no attribute 'get'``.
+ if isinstance(data, list):
+ data = {"results": data, "papers": data, "search_results": data}
+ if not isinstance(data, dict):
+ # Truly unparseable shape (number, string, etc.) — just truncate
+ # the raw answer and bail.
+ return self._truncate_text(raw_answer)
tool_type = (tool_type or "").lower()
diff --git a/deeptutor/agents/research/research_pipeline.py b/deeptutor/agents/research/research_pipeline.py
index 96d092be8..e8033506e 100644
--- a/deeptutor/agents/research/research_pipeline.py
+++ b/deeptutor/agents/research/research_pipeline.py
@@ -250,7 +250,7 @@ class ResearchPipeline:
# For sync functions, run in executor
import functools
- loop = asyncio.get_event_loop()
+ loop = asyncio.get_running_loop()
result = await asyncio.wait_for(
loop.run_in_executor(None, functools.partial(tool_func, *args, **kwargs)),
timeout=timeout,
diff --git a/deeptutor/agents/solve/main_solver.py b/deeptutor/agents/solve/main_solver.py
index a139096ab..884914b14 100644
--- a/deeptutor/agents/solve/main_solver.py
+++ b/deeptutor/agents/solve/main_solver.py
@@ -187,7 +187,9 @@ class MainSolver:
from deeptutor.services.llm import is_local_llm_server
if not api_key and not is_local_llm_server(base_url):
- raise ValueError("API key not set. Configure the active LLM profile in Settings > Catalog")
+ raise ValueError(
+ "API key not set. Configure the active LLM profile in Settings > Catalog"
+ )
if not api_key and is_local_llm_server(base_url):
api_key = "sk-no-key-required"
diff --git a/deeptutor/api/main.py b/deeptutor/api/main.py
index f6c43e31f..bbb07f080 100644
--- a/deeptutor/api/main.py
+++ b/deeptutor/api/main.py
@@ -37,6 +37,8 @@ CONFIG_DRIFT_ERROR_TEMPLATE = (
"registered in the runtime tool registry. Register the missing tools or "
"remove the stale tool names from the capability manifests."
)
+
+
class SafeOutputStaticFiles(StaticFiles):
"""Static file mount that only exposes explicitly whitelisted artifacts."""
diff --git a/deeptutor/api/routers/sessions.py b/deeptutor/api/routers/sessions.py
index 8a1ee4378..0d1787d8a 100644
--- a/deeptutor/api/routers/sessions.py
+++ b/deeptutor/api/routers/sessions.py
@@ -68,9 +68,16 @@ def _format_quiz_results_message(answers: list[QuizResultItem]) -> str:
async def list_sessions(
limit: int = Query(default=50, ge=1, le=200),
offset: int = Query(default=0, ge=0),
+ kind: str | None = Query(
+ default=None,
+ description=(
+ "Filter by session surface: 'chat' (manual /chat page) or "
+ "'co_learn' (auto routing /co-learn page). Omit to return all."
+ ),
+ ),
):
store = get_session_store()
- sessions = await store.list_sessions(limit=limit, offset=offset)
+ sessions = await store.list_sessions(limit=limit, offset=offset, kind=kind)
return {"sessions": sessions}
diff --git a/deeptutor/api/routers/unified_ws.py b/deeptutor/api/routers/unified_ws.py
index 8827af415..09aea17a8 100644
--- a/deeptutor/api/routers/unified_ws.py
+++ b/deeptutor/api/routers/unified_ws.py
@@ -139,6 +139,14 @@ async def unified_websocket(ws: WebSocket) -> None:
await subscribe_turn(turn["id"], after_seq=0)
continue
+ if msg_type == "ping":
+ # Client-side heartbeat. Respond with a lightweight pong so
+ # the client knows the socket is alive; the client never
+ # consumes pong as a user-visible event (see unified-ws.ts
+ # filter below) but does refresh ``lastReceivedAt`` from it.
+ await safe_send({"type": "pong"})
+ continue
+
if msg_type == "subscribe_turn":
turn_id = str(msg.get("turn_id") or "").strip()
if not turn_id:
diff --git a/deeptutor/book/storage.py b/deeptutor/book/storage.py
index 8a0b1c30b..f894bed29 100644
--- a/deeptutor/book/storage.py
+++ b/deeptutor/book/storage.py
@@ -21,7 +21,7 @@ Layout (relative to ``data/user/workspace/book/``)::
from __future__ import annotations
import asyncio
-from datetime import datetime
+from datetime import datetime, timezone
import json
import logging
import os
@@ -247,7 +247,7 @@ class BookStorage:
def append_log(self, book_id: str, message: str, *, op: str = "info") -> None:
path = self.path_service.get_book_log_file(book_id)
path.parent.mkdir(parents=True, exist_ok=True)
- ts = datetime.utcnow().isoformat(timespec="seconds")
+ ts = datetime.now(timezone.utc).replace(tzinfo=None).isoformat(timespec="seconds")
line = f"- `{ts}Z` **{op}** — {message.strip()}\n"
with open(path, "a", encoding="utf-8") as f:
f.write(line)
diff --git a/deeptutor/capabilities/auto.py b/deeptutor/capabilities/auto.py
new file mode 100644
index 000000000..5c41c2a1d
--- /dev/null
+++ b/deeptutor/capabilities/auto.py
@@ -0,0 +1,36 @@
+"""Auto capability — agent loop that routes between other capabilities.
+
+Thin wrapper that hands off to ``AutoPipeline``. See
+``deeptutor/agents/auto/auto_pipeline.py`` for the loop body.
+"""
+
+from __future__ import annotations
+
+from deeptutor.capabilities.request_contracts import get_capability_request_schema
+from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest
+from deeptutor.core.context import UnifiedContext
+from deeptutor.core.stream_bus import StreamBus
+
+
+class AutoCapability(BaseCapability):
+ manifest = CapabilityManifest(
+ name="auto",
+ description=(
+ "Agentic router: analyzes intent, autonomously delegates to the best "
+ "matching capability (deep_solve, deep_question, deep_research, "
+ "math_animator, visualize), and synthesizes the final response. Use "
+ "when you want the system to pick the right mode for you."
+ ),
+ stages=["analyzing", "delegating", "synthesizing"],
+ tools_used=[],
+ cli_aliases=["auto"],
+ request_schema=get_capability_request_schema("auto"),
+ )
+
+ async def run(self, context: UnifiedContext, stream: StreamBus) -> None:
+ # Local import keeps capability registration cheap (registry boot only
+ # imports the class; the heavy pipeline imports happen at first run).
+ from deeptutor.agents.auto.auto_pipeline import AutoPipeline
+
+ pipeline = AutoPipeline(language=context.language)
+ await pipeline.run(context, stream)
diff --git a/deeptutor/capabilities/deep_question.py b/deeptutor/capabilities/deep_question.py
index 739708ba2..4a2c9b2ec 100644
--- a/deeptutor/capabilities/deep_question.py
+++ b/deeptutor/capabilities/deep_question.py
@@ -92,8 +92,10 @@ class DeepQuestionCapability(BaseCapability):
enabled_tools = set(
self.manifest.tools_used if context.enabled_tools is None else context.enabled_tools
)
+ # rag is gated on attached knowledge bases, not on a separate flag.
+ rag_available = bool(kb_name)
tool_flags_override = {
- "rag": "rag" in enabled_tools,
+ "rag": rag_available,
"web_search": "web_search" in enabled_tools,
"code_execution": "code_execution" in enabled_tools,
}
@@ -106,7 +108,7 @@ class DeepQuestionCapability(BaseCapability):
language=context.language,
output_dir=str(output_dir),
tool_flags_override=tool_flags_override,
- enable_idea_rag="rag" in enabled_tools,
+ enable_idea_rag=rag_available,
)
_trace_bridge = self._build_trace_bridge(stream)
diff --git a/deeptutor/capabilities/deep_solve.py b/deeptutor/capabilities/deep_solve.py
index 891838250..fe15bb077 100644
--- a/deeptutor/capabilities/deep_solve.py
+++ b/deeptutor/capabilities/deep_solve.py
@@ -45,27 +45,15 @@ class DeepSolveCapability(BaseCapability):
llm_config = get_llm_config()
detailed = context.config_overrides.get("detailed_answer", True)
- enabled_tools = list(
+ # Attached knowledge bases are the single source of truth for whether
+ # rag should be available — there is no separate "enable rag" toggle.
+ kb_name = context.knowledge_bases[0] if context.knowledge_bases else None
+ requested = list(
self.manifest.tools_used if context.enabled_tools is None else context.enabled_tools
)
- rag_enabled = "rag" in enabled_tools
- kb_name = context.knowledge_bases[0] if rag_enabled and context.knowledge_bases else None
-
- # Consistency normalization: if rag is requested but no KB is
- # actually available, strip "rag" from the enabled tool set so the
- # ReAct loop never exposes an action that would fail at runtime.
- if rag_enabled and not kb_name:
- enabled_tools = [tool for tool in enabled_tools if tool != "rag"]
- rag_enabled = False
- await stream.progress(
- message=(
- "RAG was enabled but no knowledge base is selected; "
- "the rag tool is disabled for this turn."
- ),
- source=self.name,
- stage="planning",
- metadata={"trace_kind": "warning", "reason": "rag_without_kb"},
- )
+ enabled_tools = [tool for tool in requested if tool != "rag"]
+ if kb_name:
+ enabled_tools.append("rag")
solver = MainSolver(
api_key=llm_config.api_key,
@@ -74,7 +62,7 @@ class DeepSolveCapability(BaseCapability):
kb_name=kb_name,
language=context.language,
enabled_tools=enabled_tools,
- disable_planner_retrieve=not (rag_enabled and kb_name),
+ disable_planner_retrieve=kb_name is None,
)
await solver.ainit()
diff --git a/deeptutor/capabilities/request_contracts.py b/deeptutor/capabilities/request_contracts.py
index d13f03968..1b75a97e5 100644
--- a/deeptutor/capabilities/request_contracts.py
+++ b/deeptutor/capabilities/request_contracts.py
@@ -55,6 +55,15 @@ class VisualizeRequestConfig(BaseModel):
render_mode: Literal["auto", "svg", "chartjs", "mermaid", "html"] = "auto"
+class AutoRequestConfig(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ enabled_capabilities: list[str] = Field(default_factory=list)
+ max_iterations: int = Field(default=4, ge=1, le=8)
+ max_retries_per_step: int = Field(default=3, ge=1, le=5)
+ max_same_capability_calls: int = Field(default=2, ge=1, le=4)
+
+
def _clean_public_config(raw_config: dict[str, Any] | None) -> dict[str, Any]:
if raw_config is None:
return {}
@@ -105,6 +114,12 @@ def validate_visualize_request_config(
return _validate_model(VisualizeRequestConfig, raw_config, label="visualize")
+def validate_auto_request_config(
+ raw_config: dict[str, Any] | None,
+) -> AutoRequestConfig:
+ return _validate_model(AutoRequestConfig, raw_config, label="auto")
+
+
def build_request_schema(model_type: type[BaseModel]) -> dict[str, Any]:
return model_type.model_json_schema(mode="validation")
@@ -116,6 +131,7 @@ CAPABILITY_CONFIG_VALIDATORS: dict[str, Callable[[dict[str, Any] | None], Any]]
"deep_research": validate_research_request_config,
"math_animator": validate_math_animator_request_config,
"visualize": validate_visualize_request_config,
+ "auto": validate_auto_request_config,
}
CAPABILITY_REQUEST_SCHEMAS: dict[str, dict[str, Any]] = {
@@ -125,6 +141,7 @@ CAPABILITY_REQUEST_SCHEMAS: dict[str, dict[str, Any]] = {
"deep_research": build_request_schema(DeepResearchRequestConfig),
"math_animator": build_request_schema(MathAnimatorRequestConfig),
"visualize": build_request_schema(VisualizeRequestConfig),
+ "auto": build_request_schema(AutoRequestConfig),
}
@@ -145,6 +162,7 @@ def get_capability_request_schema(capability: str) -> dict[str, Any]:
__all__ = [
+ "AutoRequestConfig",
"CAPABILITY_CONFIG_VALIDATORS",
"CAPABILITY_REQUEST_SCHEMAS",
"ChatRequestConfig",
@@ -153,6 +171,7 @@ __all__ = [
"VisualizeRequestConfig",
"build_request_schema",
"get_capability_request_schema",
+ "validate_auto_request_config",
"validate_capability_config",
"validate_chat_request_config",
"validate_deep_question_request_config",
diff --git a/deeptutor/knowledge/initializer.py b/deeptutor/knowledge/initializer.py
index d56e1c2ed..4018d3764 100644
--- a/deeptutor/knowledge/initializer.py
+++ b/deeptutor/knowledge/initializer.py
@@ -14,10 +14,10 @@ from typing import Optional
from deeptutor.knowledge.naming import validate_knowledge_base_name
from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker
+from deeptutor.services.config import resolve_llm_runtime_config
from deeptutor.services.rag.factory import DEFAULT_PROVIDER
from deeptutor.services.rag.file_routing import FileTypeRouter
from deeptutor.services.rag.service import RAGService
-from deeptutor.services.config import resolve_llm_runtime_config
logger = logging.getLogger(__name__)
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index 470e2ac5f..31218eb15 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -6,7 +6,7 @@ Manages multiple knowledge bases and provides utilities for accessing them.
"""
from contextlib import contextmanager
-from datetime import datetime
+from datetime import datetime, timedelta
import hashlib
import json
import logging
@@ -23,6 +23,32 @@ from deeptutor.services.rag.file_routing import FileTypeRouter
logger = logging.getLogger(__name__)
+# How long an entry can be missing its KB directory before ``list_knowledge_bases``
+# treats it as a stale orphan. The KB create flow writes the "initializing"
+# config entry before the on-disk folder is created, so a too-short grace would
+# let a list-call mid-creation racy-delete the entry. 60s is comfortably longer
+# than the create handshake while still keeping multi-day zombies out.
+_ORPHAN_PRUNE_GRACE_SECONDS = 60
+
+
+def _entry_updated_after(kb_entry: dict | None, cutoff: datetime) -> bool:
+ """Return True when the entry's ``updated_at`` is strictly after ``cutoff``.
+
+ Entries without a parseable timestamp are treated as old (return False) —
+ a long-stuck orphan that crashed before recording a timestamp should still
+ get pruned.
+ """
+ if not isinstance(kb_entry, dict):
+ return False
+ raw = kb_entry.get("updated_at")
+ if not isinstance(raw, str):
+ return False
+ try:
+ return datetime.fromisoformat(raw) > cutoff
+ except ValueError:
+ return False
+
+
# Cross-platform file locking
@contextmanager
def file_lock_shared(file_handle):
@@ -423,20 +449,51 @@ class KnowledgeBaseManager:
This method:
1. Loads registered KBs from kb_config.json
- 2. Scans the directory for existing KBs not yet registered
- 3. Auto-registers discovered KBs with valid raw/index structure
+ 2. Drops registered entries whose on-disk directory no longer exists
+ (orphans from failed inits or manual ``rm -rf`` of a KB folder).
+ 3. Scans the directory for existing KBs not yet registered
+ 4. Auto-registers discovered KBs with valid raw/index structure
"""
# Always reload config from file to ensure we have the latest data
self.config = self._load_config()
- # Read knowledge base list from config file
config_kbs = self.config.get("knowledge_bases", {})
- kb_list = set(config_kbs.keys())
+ kb_list: set[str] = set()
+ config_changed = False
+
+ # Filter out orphan entries whose KB directory is gone. The on-disk
+ # folder is the source of truth for existence — without it the KB
+ # has no documents, no index, and surfacing it in the UI just shows
+ # zombies that the user can't act on.
+ #
+ # Grace period: a freshly-created KB writes its config entry before
+ # ``create_directory_structure`` mkdir-s the folder (so the UI can
+ # render the "initializing" row immediately). If ``list`` races into
+ # that window we'd prune a perfectly healthy in-flight KB. Skip the
+ # prune when ``updated_at`` is recent enough that an init could still
+ # be wiring things up.
+ base_exists = self.base_dir.exists()
+ grace_cutoff = datetime.now() - timedelta(seconds=_ORPHAN_PRUNE_GRACE_SECONDS)
+ for kb_name, kb_entry in list(config_kbs.items()):
+ rel_path = (kb_entry or {}).get("path", kb_name)
+ kb_dir = self.base_dir / rel_path
+ if base_exists and not kb_dir.exists():
+ if _entry_updated_after(kb_entry, grace_cutoff):
+ kb_list.add(kb_name)
+ continue
+ logger.warning(
+ "Pruning orphaned KB entry '%s': directory %s no longer exists.",
+ kb_name,
+ kb_dir,
+ )
+ del config_kbs[kb_name]
+ config_changed = True
+ continue
+ kb_list.add(kb_name)
# Also scan directory for KBs that may not be registered yet
# This ensures backward compatibility and auto-discovery
- if self.base_dir.exists():
- config_changed = False
+ if base_exists:
for item in self.base_dir.iterdir():
if not item.is_dir() or item.name.startswith(("__", ".")):
continue
@@ -459,9 +516,9 @@ class KnowledgeBaseManager:
self._auto_register_kb(item.name)
config_changed = True
- # Save config if we registered new KBs
- if config_changed:
- self._save_config()
+ # Save config if we pruned orphans or registered new KBs
+ if config_changed:
+ self._save_config()
return sorted(kb_list)
@@ -856,7 +913,13 @@ class KnowledgeBaseManager:
Returns:
True if deleted successfully
"""
- if name not in self.list_knowledge_bases():
+ # Look up against the raw config rather than ``list_knowledge_bases``:
+ # the latter prunes orphan entries (dir missing) as a side effect, so
+ # calling it here would race-delete the entry we are about to clean up
+ # and then raise "not found" on the now-empty config.
+ self.config = self._load_config()
+ config_kbs = self.config.get("knowledge_bases", {})
+ if name not in config_kbs and not (self.base_dir / name).exists():
raise ValueError(f"Knowledge base not found: {name}")
# Resolve the directory directly to stay idempotent: if the on-disk
diff --git a/deeptutor/knowledge/progress_tracker.py b/deeptutor/knowledge/progress_tracker.py
index 9ee9446c9..a1c1b712b 100644
--- a/deeptutor/knowledge/progress_tracker.py
+++ b/deeptutor/knowledge/progress_tracker.py
@@ -62,15 +62,10 @@ class ProgressTracker:
broadcaster = ProgressBroadcaster.get_instance()
try:
- asyncio.get_running_loop()
- asyncio.create_task(broadcaster.broadcast(self.kb_name, progress))
+ loop = asyncio.get_running_loop()
+ loop.create_task(broadcaster.broadcast(self.kb_name, progress))
except RuntimeError:
- try:
- loop = asyncio.get_event_loop()
- if loop.is_running():
- asyncio.create_task(broadcaster.broadcast(self.kb_name, progress))
- except RuntimeError:
- pass
+ pass
except (ImportError, Exception):
pass
diff --git a/deeptutor/runtime/banner.py b/deeptutor/runtime/banner.py
new file mode 100644
index 000000000..53b4d1845
--- /dev/null
+++ b/deeptutor/runtime/banner.py
@@ -0,0 +1,196 @@
+"""Branded banner + localized labels for ``deeptutor start`` / ``deeptutor init``.
+
+Both commands read the user's language preference from
+``data/user/settings/interface.json`` (default ``en``) so their startup
+output matches the UI language the user has chosen.
+"""
+
+from __future__ import annotations
+
+from rich.align import Align
+from rich.console import Console
+from rich.panel import Panel
+from rich.text import Text
+
+from deeptutor.__version__ import __version__
+
+_ASCII_LOGO = r""" ____ _____ _
+| _ \ ___ ___ _ __ |_ _| _| |_ ___ _ __
+| | | |/ _ \/ _ \ '_ \ | || | | | __/ _ \| '__|
+| |_| | __/ __/ |_) | | || |_| | || (_) | |
+|____/ \___|\___| .__/ |_| \__,_|\__\___/|_|
+ |_|"""
+
+
+LABELS: dict[str, dict[str, str]] = {
+ "en": {
+ "tagline": "Agent-Native Personalized Tutoring",
+ "lab": "Data Intelligence Lab @ HKU",
+ # init
+ "init.mode": "Workspace initializer",
+ "init.workspace": "Workspace",
+ "init.note_settings_dir": "Settings will be written under data/user/settings.",
+ "init.backend_port": "Backend port",
+ "init.frontend_port": "Frontend port",
+ "init.llm_section": "LLM provider",
+ "init.binding": "Binding",
+ "init.base_url": "Base URL",
+ "init.api_key": "API key",
+ "init.model": "Model",
+ "init.confirm_embedding": "Configure embedding for Knowledge Base/RAG now?",
+ "init.embedding_section": "Embedding provider",
+ "init.embedding_endpoint": "Embedding endpoint URL",
+ "init.embedding_api_key": "Embedding API key",
+ "init.embedding_model": "Embedding model",
+ "init.embedding_dimension": "Embedding dimension (blank for auto)",
+ "init.saved": "Settings saved. You can edit them later in the Web Settings page or data/user/settings/.",
+ # start (launcher)
+ "start.mode": "Launching backend + frontend",
+ "start.backend": "Backend",
+ "start.browser_api": "Browser API",
+ "start.frontend": "Frontend",
+ "start.workspace": "Workspace",
+ "start.frontend_runtime": "Frontend runtime",
+ "start.press_ctrl_c": "Press Ctrl+C to stop.",
+ "start.starting_backend": "Starting backend ...",
+ "start.starting_frontend": "Starting frontend ...",
+ "start.waiting_for": "Waiting for {name} at {url} ...",
+ "start.ready": "{name} is ready.",
+ "start.open_in_browser": "Open {url} in your browser.",
+ "start.received_signal": "Received {signal}; shutting down ...",
+ "start.stopping": "Stopping {name} (PID {pid})",
+ "start.exited": "{name} exited with code {code}",
+ "start.not_ready": "{name} did not become ready within {timeout}s",
+ "start.port_in_use": (
+ "DeepTutor cannot start because port(s) already in use: {ports}. "
+ "Stop the existing process or change data/user/settings/system.json."
+ ),
+ },
+ "zh": {
+ "tagline": "智能体原生的个性化辅导",
+ "lab": "香港大学数据智能实验室",
+ # init
+ "init.mode": "工作目录初始化",
+ "init.workspace": "工作目录",
+ "init.note_settings_dir": "配置文件将写入 data/user/settings 目录。",
+ "init.backend_port": "后端端口",
+ "init.frontend_port": "前端端口",
+ "init.llm_section": "大模型服务",
+ "init.binding": "服务类型",
+ "init.base_url": "Base URL",
+ "init.api_key": "API Key",
+ "init.model": "模型",
+ "init.confirm_embedding": "现在配置知识库 / RAG 所用的向量模型?",
+ "init.embedding_section": "向量模型服务",
+ "init.embedding_endpoint": "向量服务地址",
+ "init.embedding_api_key": "向量服务 API Key",
+ "init.embedding_model": "向量模型",
+ "init.embedding_dimension": "向量维度 (留空自动检测)",
+ "init.saved": "配置已保存。后续可在 Web 设置页或 data/user/settings/ 中修改。",
+ # start (launcher)
+ "start.mode": "启动后端 + 前端",
+ "start.backend": "后端",
+ "start.browser_api": "前端 API",
+ "start.frontend": "前端",
+ "start.workspace": "工作目录",
+ "start.frontend_runtime": "前端运行模式",
+ "start.press_ctrl_c": "按 Ctrl+C 停止。",
+ "start.starting_backend": "正在启动后端服务 ...",
+ "start.starting_frontend": "正在启动前端服务 ...",
+ "start.waiting_for": "正在等待 {name} ({url}) ...",
+ "start.ready": "{name} 已就绪。",
+ "start.open_in_browser": "请在浏览器中打开 {url}。",
+ "start.received_signal": "收到 {signal} 信号,正在关闭 ...",
+ "start.stopping": "正在停止 {name} (PID {pid})",
+ "start.exited": "{name} 已退出 (退出码 {code})",
+ "start.not_ready": "{name} 在 {timeout} 秒内未就绪",
+ "start.port_in_use": (
+ "无法启动 DeepTutor,端口已被占用: {ports}。"
+ "请先停止占用进程,或修改 data/user/settings/system.json 中的端口设置。"
+ ),
+ },
+}
+
+
+def _pick_language(language: str | None) -> str:
+ if not language:
+ return "en"
+ code = str(language).lower().strip()
+ if code in {"zh", "zh-cn", "zh-hans", "chinese", "cn"}:
+ return "zh"
+ return "en"
+
+
+def resolve_language(default: str = "en") -> str:
+ """Read the saved UI language, falling back to ``default``.
+
+ Safe to call before the runtime is fully initialized; any failure
+ silently falls back to the default.
+ """
+ try:
+ from deeptutor.services.settings.interface_settings import get_ui_language
+
+ return _pick_language(get_ui_language(default))
+ except Exception:
+ return _pick_language(default)
+
+
+def labels_for(language: str | None) -> dict[str, str]:
+ return LABELS[_pick_language(language)]
+
+
+def render_banner(language: str | None, *, mode_key: str | None = None) -> Panel:
+ """Build the branded banner panel.
+
+ Parameters
+ ----------
+ language:
+ Language code (``"en"``/``"zh"``). Unknown values fall back to English.
+ mode_key:
+ Optional key into ``LABELS[lang]`` to display under the tagline
+ (e.g. ``"start.mode"``, ``"init.mode"``).
+ """
+
+ lang = _pick_language(language)
+ strings = LABELS[lang]
+
+ logo = Text(_ASCII_LOGO, style="bold bright_cyan")
+ tagline_line = f"{strings['tagline']} · v{__version__}"
+
+ body = Text()
+ body.append(logo)
+ body.append("\n\n")
+ body.append(tagline_line, style="bold white")
+ body.append("\n")
+ body.append(strings["lab"], style="dim")
+ if mode_key and mode_key in strings:
+ body.append("\n")
+ body.append(strings[mode_key], style="italic bright_magenta")
+
+ return Panel(
+ Align.left(body),
+ title="[bold bright_cyan]DeepTutor[/]",
+ border_style="bright_cyan",
+ padding=(1, 2),
+ )
+
+
+def print_banner(
+ console: Console | None = None,
+ *,
+ language: str | None = None,
+ mode_key: str | None = None,
+) -> None:
+ """Print the branded banner to ``console`` (creates one if omitted)."""
+
+ target = console or Console()
+ target.print(render_banner(language, mode_key=mode_key))
+
+
+__all__: tuple[str, ...] = (
+ "LABELS",
+ "labels_for",
+ "print_banner",
+ "render_banner",
+ "resolve_language",
+)
diff --git a/deeptutor/runtime/bootstrap/builtin_capabilities.py b/deeptutor/runtime/bootstrap/builtin_capabilities.py
index dac0174f6..352b01d74 100644
--- a/deeptutor/runtime/bootstrap/builtin_capabilities.py
+++ b/deeptutor/runtime/bootstrap/builtin_capabilities.py
@@ -7,4 +7,5 @@ BUILTIN_CAPABILITY_CLASSES: dict[str, str] = {
"deep_research": "deeptutor.capabilities.deep_research:DeepResearchCapability",
"math_animator": "deeptutor.capabilities.math_animator:MathAnimatorCapability",
"visualize": "deeptutor.capabilities.visualize:VisualizeCapability",
+ "auto": "deeptutor.capabilities.auto:AutoCapability",
}
diff --git a/deeptutor/runtime/launcher.py b/deeptutor/runtime/launcher.py
index cfa7e8b46..f1b7a2bff 100644
--- a/deeptutor/runtime/launcher.py
+++ b/deeptutor/runtime/launcher.py
@@ -18,6 +18,7 @@ from typing import Callable
from urllib import error as urlerror
from urllib import request as urlrequest
+from deeptutor.runtime.banner import labels_for, print_banner, resolve_language
from deeptutor.runtime.home import DEEPTUTOR_HOME_ENV, PACKAGE_ROOT, get_runtime_home
BACKEND_READY_TIMEOUT = 60
@@ -25,6 +26,20 @@ FRONTEND_READY_TIMEOUT = 120
KILL_SIGNAL = getattr(signal, "SIGKILL", signal.SIGTERM)
WEB_CACHE_DIR = Path("data") / "user" / "runtime" / "web"
+# Mutable holder so module-level helpers can format messages in the active
+# UI language without threading the labels through every function.
+_ACTIVE_LABELS: dict[str, str] = labels_for("en")
+
+
+def _t(key: str, **kwargs: object) -> str:
+ template = _ACTIVE_LABELS.get(key) or labels_for("en").get(key, key)
+ if not kwargs:
+ return template
+ try:
+ return template.format(**kwargs)
+ except (KeyError, IndexError):
+ return template
+
@dataclass(slots=True)
class ManagedProcess:
@@ -103,7 +118,7 @@ def _send_tree_signal(pid: int | None, pgid: int | None, sig: signal.Signals | i
def _terminate(proc: ManagedProcess | None) -> None:
if proc is None or proc.process.poll() is not None:
return
- _log(f"Stopping {proc.name} (PID {proc.process.pid})")
+ _log(_t("start.stopping", name=proc.name, pid=proc.process.pid))
try:
_send_tree_signal(proc.process.pid, proc.pgid, signal.SIGTERM)
except Exception:
@@ -138,7 +153,7 @@ def _spawn(command: list[str], *, cwd: Path, env: dict[str, str], name: str) ->
kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined]
else:
kwargs["start_new_session"] = True
- process = subprocess.Popen(command, **kwargs) # type: ignore[arg-type]
+ process = subprocess.Popen(command, **kwargs) # type: ignore[arg-type,call-overload]
thread = threading.Thread(target=_stream_output, args=(name, process), daemon=True)
thread.start()
return ManagedProcess(name=name, process=process, pgid=_get_pgid(process.pid))
@@ -156,10 +171,7 @@ def _ensure_ports_available(*ports: int) -> None:
occupied = [port for port in ports if _port_accepts_connection(port)]
if occupied:
joined = ", ".join(str(port) for port in occupied)
- raise SystemExit(
- f"DeepTutor cannot start because port(s) already in use: {joined}. "
- "Stop the existing process or change data/user/settings/system.json."
- )
+ raise SystemExit(_t("start.port_in_use", ports=joined))
def _wait_for_http(
@@ -170,20 +182,20 @@ def _wait_for_http(
timeout: int,
should_stop: Callable[[], bool],
) -> None:
- _log(f"Waiting for {name} at {url} ...")
+ _log(_t("start.waiting_for", name=name, url=url))
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if should_stop():
return
if process.process.poll() is not None:
- raise RuntimeError(f"{name} exited with code {process.process.returncode}")
+ raise RuntimeError(_t("start.exited", name=name, code=process.process.returncode))
try:
- with urlrequest.urlopen(url, timeout=1):
- _log(f"{name} is ready.")
+ with urlrequest.urlopen(url, timeout=1): # noqa: S310 # nosec B310 - http(s) health-check URL constructed by caller
+ _log(_t("start.ready", name=name))
return
except (urlerror.URLError, TimeoutError, OSError):
time.sleep(0.5)
- raise RuntimeError(f"{name} did not become ready within {timeout}s")
+ raise RuntimeError(_t("start.not_ready", name=name, timeout=timeout))
def _packaged_web_dir() -> Path | None:
@@ -297,8 +309,12 @@ def _resolve_frontend(
if source is not None:
npm = shutil.which("npm")
if not npm:
- raise SystemExit("npm not found. Source installs require Node.js/npm and `cd web && npm install`.")
- return FrontendRuntime("source", [npm, "run", "dev", "--", "--port", str(frontend_port)], source)
+ raise SystemExit(
+ "npm not found. Source installs require Node.js/npm and `cd web && npm install`."
+ )
+ return FrontendRuntime(
+ "source", [npm, "run", "dev", "--", "--port", str(frontend_port)], source
+ )
raise SystemExit(
"DeepTutor Web assets are not installed. Install the full app with `pip install -U deeptutor`, "
@@ -344,6 +360,10 @@ def start(home: str | Path | None = None) -> None:
runtime_env = export_runtime_settings_to_env(overwrite=True)
auth_enabled = bool(load_auth_settings()["enabled"])
+ global _ACTIVE_LABELS
+ language = resolve_language()
+ _ACTIVE_LABELS = labels_for(language)
+
backend_port = settings.backend_port
frontend_port = settings.frontend_port
backend_url = f"http://localhost:{backend_port}"
@@ -359,16 +379,14 @@ def start(home: str | Path | None = None) -> None:
auth_enabled=auth_enabled,
)
- _log("============================================")
- _log("DeepTutor")
- _log(f"Backend {backend_url}")
+ print_banner(language=language, mode_key="start.mode")
+ _log(f"{_t('start.backend'):<10} {backend_url}")
if api_base != backend_url:
- _log(f"Browser API {api_base}")
- _log(f"Frontend http://localhost:{frontend_port}")
- _log(f"Workspace {runtime_home}")
- _log(f"Frontend runtime: {frontend.kind}")
- _log("Press Ctrl+C to stop.")
- _log("============================================")
+ _log(f"{_t('start.browser_api'):<10} {api_base}")
+ _log(f"{_t('start.frontend'):<10} http://localhost:{frontend_port}")
+ _log(f"{_t('start.workspace'):<10} {runtime_home}")
+ _log(f"{_t('start.frontend_runtime')}: {frontend.kind}")
+ _log(_t("start.press_ctrl_c"))
_ensure_ports_available(backend_port, frontend_port)
@@ -410,7 +428,7 @@ def start(home: str | Path | None = None) -> None:
return
shutdown_requested = True
if signal_name:
- _log(f"Received {signal_name}; shutting down ...")
+ _log(_t("start.received_signal", signal=signal_name))
def cleanup() -> None:
nonlocal cleanup_started
@@ -424,33 +442,33 @@ def start(home: str | Path | None = None) -> None:
atexit.register(cleanup)
try:
- _log("Starting backend ...")
+ _log(_t("start.starting_backend"))
backend = _spawn(backend_cmd, cwd=runtime_home, env=common_env, name="backend")
processes.append(backend)
_wait_for_http(
- name="Backend",
+ name=_t("start.backend"),
url=f"http://127.0.0.1:{backend_port}/",
process=backend,
timeout=BACKEND_READY_TIMEOUT,
should_stop=lambda: shutdown_requested,
)
- _log("Starting frontend ...")
+ _log(_t("start.starting_frontend"))
web = _spawn(frontend.command, cwd=frontend.cwd, env=common_env, name="frontend")
processes.append(web)
_wait_for_http(
- name="Frontend",
+ name=_t("start.frontend"),
url=f"http://127.0.0.1:{frontend_port}/",
process=web,
timeout=FRONTEND_READY_TIMEOUT,
should_stop=lambda: shutdown_requested,
)
- _log(f"Open http://localhost:{frontend_port} in your browser.")
+ _log(_t("start.open_in_browser", url=f"http://localhost:{frontend_port}"))
while not shutdown_requested:
for proc in processes:
if proc.process.poll() is not None:
- _log(f"{proc.name} exited with code {proc.process.returncode}")
+ _log(_t("start.exited", name=proc.name, code=proc.process.returncode))
exit_code = 1
shutdown_requested = True
break
diff --git a/deeptutor/runtime/registry/tool_registry.py b/deeptutor/runtime/registry/tool_registry.py
index 3a8720e4d..14f7ff181 100644
--- a/deeptutor/runtime/registry/tool_registry.py
+++ b/deeptutor/runtime/registry/tool_registry.py
@@ -112,7 +112,7 @@ class ToolRegistry:
composer = ToolPromptComposer(language=language)
hints = self.get_prompt_hints(names, language=language)
if format == "list":
- return composer.format_list(hints, kb_name=opts.get("kb_name", ""))
+ return composer.format_list(hints)
if format == "table":
return composer.format_table(
hints,
diff --git a/deeptutor/services/config/knowledge_base_config.py b/deeptutor/services/config/knowledge_base_config.py
index d29660933..df335a572 100644
--- a/deeptutor/services/config/knowledge_base_config.py
+++ b/deeptutor/services/config/knowledge_base_config.py
@@ -95,6 +95,16 @@ class KnowledgeBaseConfigService:
with open(self.config_path, "w", encoding="utf-8") as handle:
json.dump(self._config, handle, indent=2, ensure_ascii=False)
+ def _refresh(self) -> None:
+ """Re-read kb_config.json so this singleton sees changes made by
+ ``KnowledgeBaseManager`` (orphan pruning, new KB registrations).
+
+ Without this, every mutating call would rewrite the file from the
+ in-memory snapshot taken at process start and undo any external
+ cleanup. Read-modify-write keeps the two writers consistent.
+ """
+ self._config = self._load_config()
+
def _ensure_kb(self, kb_name: str) -> dict[str, Any]:
knowledge_bases = self._config.setdefault("knowledge_bases", {})
if kb_name not in knowledge_bases:
@@ -105,6 +115,7 @@ class KnowledgeBaseConfigService:
return knowledge_bases[kb_name]
def get_kb_config(self, kb_name: str) -> dict[str, Any]:
+ self._refresh()
defaults = dict(self._config.get("defaults", {}))
kb_config = dict(self._config.get("knowledge_bases", {}).get(kb_name, {}))
merged = {
@@ -118,6 +129,7 @@ class KnowledgeBaseConfigService:
return merged
def set_kb_config(self, kb_name: str, config: dict[str, Any]) -> None:
+ self._refresh()
entry = self._ensure_kb(kb_name)
entry.update(config)
self._save()
@@ -135,24 +147,29 @@ class KnowledgeBaseConfigService:
self.set_kb_config(kb_name, {"search_mode": mode})
def delete_kb_config(self, kb_name: str) -> None:
+ self._refresh()
knowledge_bases = self._config.get("knowledge_bases", {})
if kb_name in knowledge_bases:
del knowledge_bases[kb_name]
self._save()
def get_all_configs(self) -> dict[str, Any]:
+ self._refresh()
return self._config
def set_global_defaults(self, defaults: dict[str, Any]) -> None:
+ self._refresh()
current = self._config.setdefault("defaults", _default_payload()["defaults"])
current.update(defaults)
self._save()
def set_default_kb(self, kb_name: str | None) -> None:
+ self._refresh()
self._config.setdefault("defaults", _default_payload()["defaults"])["default_kb"] = kb_name
self._save()
def get_default_kb(self) -> str | None:
+ self._refresh()
return self._config.get("defaults", {}).get("default_kb")
def sync_from_metadata(self, kb_name: str, kb_base_dir: Path) -> None:
diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.py
index dba37cdfd..bb314c297 100644
--- a/deeptutor/services/config/provider_runtime.py
+++ b/deeptutor/services/config/provider_runtime.py
@@ -551,7 +551,6 @@ def _resolve_embedding_provider(
return "openai"
-
def resolve_embedding_runtime_config(
catalog: dict[str, Any] | None = None,
*,
@@ -653,7 +652,6 @@ def _resolve_search_max_results(catalog: dict[str, Any], default: int = 5) -> in
return default
-
def resolve_search_runtime_config(
catalog: dict[str, Any] | None = None,
*,
diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.py
index 7e829f822..c51928907 100644
--- a/deeptutor/services/config/runtime_settings.py
+++ b/deeptutor/services/config/runtime_settings.py
@@ -334,9 +334,7 @@ class RuntimeSettingsService:
"version": 1,
"backend_port": _coerce_port(settings.get("backend_port"), 8001),
"frontend_port": _coerce_port(settings.get("frontend_port"), 3782),
- "next_public_api_base_external": _string(
- settings.get("next_public_api_base_external")
- ),
+ "next_public_api_base_external": _string(settings.get("next_public_api_base_external")),
"next_public_api_base": _string(settings.get("next_public_api_base")),
"cors_origin": _string(settings.get("cors_origin")),
"cors_origins": _coerce_origins(settings.get("cors_origins")),
@@ -359,9 +357,7 @@ class RuntimeSettingsService:
"version": 1,
"pocketbase_url": _string(settings.get("pocketbase_url")).rstrip("/"),
"pocketbase_port": _coerce_port(settings.get("pocketbase_port"), 8090),
- "pocketbase_external_url": _string(settings.get("pocketbase_external_url")).rstrip(
- "/"
- ),
+ "pocketbase_external_url": _string(settings.get("pocketbase_external_url")).rstrip("/"),
"pocketbase_admin_email": _string(settings.get("pocketbase_admin_email")),
"pocketbase_admin_password": _string(settings.get("pocketbase_admin_password")),
}
diff --git a/deeptutor/services/embedding/client.py b/deeptutor/services/embedding/client.py
index 1615c4f03..86283505a 100644
--- a/deeptutor/services/embedding/client.py
+++ b/deeptutor/services/embedding/client.py
@@ -155,17 +155,16 @@ class EmbeddingClient:
import asyncio
try:
- loop = asyncio.get_event_loop()
- if loop.is_running():
- import concurrent.futures
-
- with concurrent.futures.ThreadPoolExecutor() as executor:
- future = executor.submit(asyncio.run, self.embed(texts))
- return future.result()
- return loop.run_until_complete(self.embed(texts))
+ asyncio.get_running_loop()
except RuntimeError:
return asyncio.run(self.embed(texts))
+ import concurrent.futures
+
+ with concurrent.futures.ThreadPoolExecutor() as executor:
+ future = executor.submit(asyncio.run, self.embed(texts))
+ return future.result()
+
def get_embedding_func(self):
async def embedding_wrapper(texts: List[str]) -> List[List[float]]:
return await self.embed(texts)
diff --git a/deeptutor/services/llm/cloud_provider.py b/deeptutor/services/llm/cloud_provider.py
index d1bceb4c5..d98fbe865 100644
--- a/deeptutor/services/llm/cloud_provider.py
+++ b/deeptutor/services/llm/cloud_provider.py
@@ -8,7 +8,6 @@ Provides both complete() and stream() methods.
from collections.abc import AsyncGenerator, Mapping
import logging
-import os
import threading
from typing import cast
diff --git a/deeptutor/services/rag/index_versioning.py b/deeptutor/services/rag/index_versioning.py
index 0de6763d6..b6d24606a 100644
--- a/deeptutor/services/rag/index_versioning.py
+++ b/deeptutor/services/rag/index_versioning.py
@@ -25,7 +25,7 @@ go to flat ``version-N`` directories:
from __future__ import annotations
from dataclasses import asdict, dataclass
-from datetime import datetime
+from datetime import datetime, timezone
import hashlib
import json
import logging
@@ -271,7 +271,7 @@ def write_version_meta(
"signature": signature.hash(),
**asdict(signature),
"layout": "flat" if target.parent == kb_dir else "nested_legacy",
- "created_at": datetime.utcnow().isoformat() + "Z",
+ "created_at": datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z",
}
with open(target / META_FILENAME, "w", encoding="utf-8") as handle:
json.dump(payload, handle, indent=2, ensure_ascii=False)
diff --git a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py b/deeptutor/services/rag/pipelines/llamaindex/pipeline.py
index 54f41c9e6..216caefb0 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/pipeline.py
@@ -7,10 +7,9 @@ import json
import logging
from pathlib import Path
import traceback
-
-from deeptutor.runtime.home import get_runtime_data_root
from typing import Any, Callable, Dict, List, Optional
+from deeptutor.runtime.home import get_runtime_data_root
from deeptutor.services.embedding import get_embedding_config
from deeptutor.services.rag.embedding_signature import signature_from_embedding_config
from deeptutor.services.rag.index_versioning import (
@@ -29,9 +28,7 @@ from .embedding_adapter import (
)
from .errors import search_error_result
-DEFAULT_KB_BASE_DIR = str(
- get_runtime_data_root() / "knowledge_bases"
-)
+DEFAULT_KB_BASE_DIR = str(get_runtime_data_root() / "knowledge_bases")
SignatureProvider = Callable[[], EmbeddingSignature | None]
@@ -100,7 +97,7 @@ class LlamaIndexPipeline:
if progress_callback:
set_progress_callback(progress_callback)
- loop = asyncio.get_event_loop()
+ loop = asyncio.get_running_loop()
await loop.run_in_executor(
None,
lambda: storage.create_index(documents, storage_dir, show_progress=True),
@@ -155,7 +152,7 @@ class LlamaIndexPipeline:
embedding_mismatch_warning = self._embedding_mismatch_warning(kb_name)
try:
- loop = asyncio.get_event_loop()
+ loop = asyncio.get_running_loop()
top_k = kwargs.get("top_k", 5)
nodes = await loop.run_in_executor(
None,
@@ -243,7 +240,7 @@ class LlamaIndexPipeline:
self.logger.warning("No valid documents to add")
return False
- loop = asyncio.get_event_loop()
+ loop = asyncio.get_running_loop()
if plan.existing_storage is not None:
self.logger.info(f"Loading existing index from {plan.existing_storage}...")
diff --git a/deeptutor/services/rag/service.py b/deeptutor/services/rag/service.py
index 1baa7a4c4..8aba9fd70 100644
--- a/deeptutor/services/rag/service.py
+++ b/deeptutor/services/rag/service.py
@@ -6,15 +6,13 @@ import logging
import os
from pathlib import Path
import shutil
+from typing import Any, Dict, List, Optional
from deeptutor.runtime.home import get_runtime_data_root
-from typing import Any, Dict, List, Optional
from .factory import DEFAULT_PROVIDER, get_pipeline, list_pipelines
-DEFAULT_KB_BASE_DIR = str(
- get_runtime_data_root() / "knowledge_bases"
-)
+DEFAULT_KB_BASE_DIR = str(get_runtime_data_root() / "knowledge_bases")
class RAGService:
diff --git a/deeptutor/services/search/__init__.py b/deeptutor/services/search/__init__.py
index e23712a30..83c6fe284 100644
--- a/deeptutor/services/search/__init__.py
+++ b/deeptutor/services/search/__init__.py
@@ -30,6 +30,7 @@ from .types import Citation, SearchResult, WebSearchResponse
_logger = logging.getLogger(__name__)
+
def _get_web_search_config() -> dict[str, Any]:
try:
config = load_config_with_main("main.yaml", PROJECT_ROOT)
diff --git a/deeptutor/services/search/base.py b/deeptutor/services/search/base.py
index b1723d90a..4475c78ff 100644
--- a/deeptutor/services/search/base.py
+++ b/deeptutor/services/search/base.py
@@ -52,9 +52,7 @@ class BaseSearchProvider(ABC):
if resolved.provider == self.name or resolved.requested_provider == self.name:
key = resolved.api_key
if self.requires_api_key and not key:
- raise ValueError(
- f"{self.name} requires an api_key in Settings > Catalog > Search."
- )
+ raise ValueError(f"{self.name} requires an api_key in Settings > Catalog > Search.")
return key
@abstractmethod
diff --git a/deeptutor/services/session/pocketbase_store.py b/deeptutor/services/session/pocketbase_store.py
index 60f4896e7..a2741086a 100644
--- a/deeptutor/services/session/pocketbase_store.py
+++ b/deeptutor/services/session/pocketbase_store.py
@@ -67,10 +67,12 @@ class PocketBaseSessionStore:
self,
title: str | None = None,
session_id: str | None = None,
+ kind: str = "chat",
) -> dict[str, Any]:
now = time.time()
resolved_id = session_id or f"unified_{int(now * 1000)}_{uuid.uuid4().hex[:8]}"
resolved_title = (title or "New conversation").strip() or "New conversation"
+ resolved_kind = (kind or "chat").strip() or "chat"
def _create():
return (
@@ -85,12 +87,15 @@ class PocketBaseSessionStore:
"preferences_json": {},
"capability": "",
"status": "idle",
+ "kind": resolved_kind,
}
)
)
record = await asyncio.to_thread(_create)
- return self._session_record_to_dict(record, resolved_id, resolved_title, now)
+ result = self._session_record_to_dict(record, resolved_id, resolved_title, now)
+ result.setdefault("kind", resolved_kind)
+ return result
async def get_session(self, session_id: str) -> dict[str, Any] | None:
def _get():
@@ -109,12 +114,16 @@ class PocketBaseSessionStore:
return None
return self._session_record_to_dict(record)
- async def ensure_session(self, session_id: str | None = None) -> dict[str, Any]:
+ async def ensure_session(
+ self,
+ session_id: str | None = None,
+ kind: str = "chat",
+ ) -> dict[str, Any]:
if session_id:
session = await self.get_session(session_id)
if session is not None:
return session
- return await self.create_session()
+ return await self.create_session(kind=kind)
def _session_record_to_dict(
self,
@@ -140,6 +149,7 @@ class PocketBaseSessionStore:
"capability": getattr(record, "capability", "") or "",
"status": getattr(record, "status", "idle") or "idle",
"active_turn_id": "",
+ "kind": getattr(record, "kind", "") or "chat",
}
async def update_session_title(self, session_id: str, title: str) -> bool:
@@ -180,19 +190,25 @@ class PocketBaseSessionStore:
logger.warning(f"delete_session failed: {exc}")
return False
- async def list_sessions(self, limit: int = 50, offset: int = 0) -> list[dict[str, Any]]:
+ async def list_sessions(
+ self,
+ limit: int = 50,
+ offset: int = 0,
+ kind: str | None = None,
+ ) -> list[dict[str, Any]]:
page = (offset // limit) + 1
+ filter_kind = (kind or "").strip()
def _list():
- return (
- _pb()
- .collection("sessions")
- .get_list(
- page,
- limit,
- query_params={"sort": "-updated"},
- )
- )
+ query_params: dict[str, Any] = {"sort": "-updated"}
+ if filter_kind:
+ # PocketBase filter syntax. Existing records without ``kind`` set
+ # are treated as ``chat`` for backward compatibility.
+ if filter_kind == "chat":
+ query_params["filter"] = 'kind="chat" || kind=""'
+ else:
+ query_params["filter"] = f'kind="{filter_kind}"'
+ return _pb().collection("sessions").get_list(page, limit, query_params=query_params)
try:
result = await asyncio.to_thread(_list)
diff --git a/deeptutor/services/session/protocol.py b/deeptutor/services/session/protocol.py
index 0746d67d0..3ede58974 100644
--- a/deeptutor/services/session/protocol.py
+++ b/deeptutor/services/session/protocol.py
@@ -16,11 +16,16 @@ class SessionStoreProtocol(Protocol):
self,
title: str | None = None,
session_id: str | None = None,
+ kind: str = "chat",
) -> dict[str, Any]: ...
async def get_session(self, session_id: str) -> dict[str, Any] | None: ...
- async def ensure_session(self, session_id: str | None = None) -> dict[str, Any]: ...
+ async def ensure_session(
+ self,
+ session_id: str | None = None,
+ kind: str = "chat",
+ ) -> dict[str, Any]: ...
async def create_turn(self, session_id: str, capability: str = "") -> dict[str, Any]: ...
@@ -61,7 +66,12 @@ class SessionStoreProtocol(Protocol):
async def get_messages_for_context(self, session_id: str) -> list[dict[str, Any]]: ...
- async def list_sessions(self, limit: int = 50, offset: int = 0) -> list[dict[str, Any]]: ...
+ async def list_sessions(
+ self,
+ limit: int = 50,
+ offset: int = 0,
+ kind: str | None = None,
+ ) -> list[dict[str, Any]]: ...
async def update_summary(self, session_id: str, summary: str, up_to_msg_id: int) -> bool: ...
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index c18682a9d..27c39574b 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -92,7 +92,12 @@ class SQLiteSessionStore:
updated_at REAL NOT NULL,
compressed_summary TEXT DEFAULT '',
summary_up_to_msg_id INTEGER DEFAULT 0,
- preferences_json TEXT DEFAULT '{}'
+ preferences_json TEXT DEFAULT '{}',
+ -- Surface that produced this session. ``chat`` (manual /chat
+ -- page) and ``co_learn`` (auto-routing /co-learn page) live
+ -- under the same row schema but are listed and persisted
+ -- separately so neither surface shows the other's history.
+ kind TEXT NOT NULL DEFAULT 'chat'
);
CREATE TABLE IF NOT EXISTS messages (
@@ -188,6 +193,10 @@ class SQLiteSessionStore:
columns = {row[1] for row in conn.execute("PRAGMA table_info(sessions)").fetchall()}
if "preferences_json" not in columns:
conn.execute("ALTER TABLE sessions ADD COLUMN preferences_json TEXT DEFAULT '{}'")
+ if "kind" not in columns:
+ # Existing rows belong to the legacy ``/chat`` surface; default
+ # is safe.
+ conn.execute("ALTER TABLE sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'chat'")
message_columns = {
row[1] for row in conn.execute("PRAGMA table_info(messages)").fetchall()
}
@@ -206,18 +215,25 @@ class SQLiteSessionStore:
return conn
def _create_session_sync(
- self, title: str | None = None, session_id: str | None = None
+ self,
+ title: str | None = None,
+ session_id: str | None = None,
+ kind: str = "chat",
) -> dict[str, Any]:
now = time.time()
resolved_id = session_id or f"unified_{int(now * 1000)}_{uuid.uuid4().hex[:8]}"
resolved_title = (title or "New conversation").strip() or "New conversation"
+ resolved_kind = (kind or "chat").strip() or "chat"
with self._connect() as conn:
conn.execute(
"""
- INSERT INTO sessions (id, title, created_at, updated_at, compressed_summary, summary_up_to_msg_id)
- VALUES (?, ?, ?, ?, '', 0)
+ INSERT INTO sessions (
+ id, title, created_at, updated_at,
+ compressed_summary, summary_up_to_msg_id, kind
+ )
+ VALUES (?, ?, ?, ?, '', 0, ?)
""",
- (resolved_id, resolved_title[:100], now, now),
+ (resolved_id, resolved_title[:100], now, now, resolved_kind),
)
conn.commit()
return {
@@ -228,12 +244,16 @@ class SQLiteSessionStore:
"updated_at": now,
"compressed_summary": "",
"summary_up_to_msg_id": 0,
+ "kind": resolved_kind,
}
async def create_session(
- self, title: str | None = None, session_id: str | None = None
+ self,
+ title: str | None = None,
+ session_id: str | None = None,
+ kind: str = "chat",
) -> dict[str, Any]:
- return await self._run(self._create_session_sync, title, session_id)
+ return await self._run(self._create_session_sync, title, session_id, kind)
def _get_session_sync(self, session_id: str) -> dict[str, Any] | None:
with self._connect() as conn:
@@ -247,6 +267,7 @@ class SQLiteSessionStore:
s.compressed_summary,
s.summary_up_to_msg_id,
s.preferences_json,
+ s.kind,
COALESCE(
(
SELECT t.status
@@ -293,12 +314,16 @@ class SQLiteSessionStore:
async def get_session(self, session_id: str) -> dict[str, Any] | None:
return await self._run(self._get_session_sync, session_id)
- async def ensure_session(self, session_id: str | None = None) -> dict[str, Any]:
+ async def ensure_session(
+ self,
+ session_id: str | None = None,
+ kind: str = "chat",
+ ) -> dict[str, Any]:
if session_id:
session = await self.get_session(session_id)
if session is not None:
return session
- return await self.create_session()
+ return await self.create_session(kind=kind)
@staticmethod
def _serialize_turn(row: sqlite3.Row) -> dict[str, Any]:
@@ -709,10 +734,24 @@ class SQLiteSessionStore:
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)
- def _list_sessions_sync(self, limit: int = 50, offset: int = 0) -> list[dict[str, Any]]:
+ def _list_sessions_sync(
+ self,
+ limit: int = 50,
+ offset: int = 0,
+ kind: str | None = None,
+ ) -> list[dict[str, Any]]:
+ # Filtering by ``kind`` is the mechanism that keeps ``/chat`` and
+ # ``/co-learn`` history isolated. ``None`` means "all kinds" (used by
+ # admin / dashboard pages that aggregate across surfaces).
with self._connect() as conn:
+ where_sql = ""
+ params: list[Any] = []
+ if kind is not None:
+ where_sql = "WHERE s.kind = ?"
+ params.append(kind)
+ params.extend([limit, offset])
rows = conn.execute(
- """
+ f"""
SELECT
s.id,
s.title,
@@ -721,6 +760,7 @@ class SQLiteSessionStore:
s.compressed_summary,
s.summary_up_to_msg_id,
s.preferences_json,
+ s.kind,
COUNT(m.id) AS message_count,
COALESCE(
(
@@ -765,11 +805,12 @@ class SQLiteSessionStore:
) AS last_message
FROM sessions s
LEFT JOIN messages m ON m.session_id = s.id
+ {where_sql}
GROUP BY s.id
ORDER BY s.updated_at DESC
LIMIT ? OFFSET ?
- """,
- (limit, offset),
+ """, # nosec B608 - where_sql is a fixed literal selected from constants
+ params,
).fetchall()
sessions = []
for row in rows:
@@ -779,8 +820,13 @@ class SQLiteSessionStore:
sessions.append(payload)
return sessions
- async def list_sessions(self, limit: int = 50, offset: int = 0) -> list[dict[str, Any]]:
- return await self._run(self._list_sessions_sync, limit, offset)
+ async def list_sessions(
+ self,
+ limit: int = 50,
+ offset: int = 0,
+ kind: str | None = None,
+ ) -> list[dict[str, Any]]:
+ return await self._run(self._list_sessions_sync, limit, offset, kind)
def _update_summary_sync(self, session_id: str, summary: str, up_to_msg_id: int) -> bool:
with self._connect() as conn:
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index 6b2f59c40..6e70e36f4 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -385,7 +385,15 @@ class TurnRuntimeManager:
"capability": capability,
"config": {**validated_public_config, **runtime_only_config},
}
- session = await self.store.ensure_session(payload.get("session_id"))
+ # ``kind`` tags the surface that originated this turn so /chat and
+ # /co-learn never list each other's sessions. Existing sessions
+ # preserve their original kind (ensure_session is a no-op if it
+ # already exists).
+ session_kind = str(payload.get("kind") or "chat").strip() or "chat"
+ session = await self.store.ensure_session(
+ payload.get("session_id"),
+ kind=session_kind,
+ )
preferences = session.get("preferences") or {}
raw_llm_selection = payload.get("llm_selection")
if raw_llm_selection is None:
diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.py
index 86e26dc8c..9416db3a5 100644
--- a/deeptutor/tools/builtin/__init__.py
+++ b/deeptutor/tools/builtin/__init__.py
@@ -60,16 +60,16 @@ class RAGTool(_PromptHintsMixin, BaseTool):
return ToolDefinition(
name="rag",
description=(
- "Search a knowledge base using Retrieval-Augmented Generation. "
- "Returns relevant passages and an LLM-synthesised answer."
+ "Retrieve relevant passages from one of the knowledge bases the "
+ "user attached to this turn. Call once per knowledge base you "
+ "want to consult; the system runs them in parallel."
),
parameters=[
ToolParameter(name="query", type="string", description="Search query."),
ToolParameter(
name="kb_name",
type="string",
- description="Knowledge base to search.",
- required=False,
+ description="Knowledge base to search. Must be one of the attached knowledge bases.",
),
],
)
@@ -80,7 +80,9 @@ class RAGTool(_PromptHintsMixin, BaseTool):
query = str(kwargs.get("query") or "").strip()
if not query:
raise ValueError("RAG query must be a non-empty string.")
- kb_name = kwargs.get("kb_name")
+ kb_name = str(kwargs.get("kb_name") or "").strip()
+ if not kb_name:
+ raise ValueError("RAG requires an explicit kb_name.")
event_sink = kwargs.get("event_sink")
extra_kwargs = {
key: value
diff --git a/deeptutor/tools/prompting/__init__.py b/deeptutor/tools/prompting/__init__.py
index 7c4b06c05..1e4ae7247 100644
--- a/deeptutor/tools/prompting/__init__.py
+++ b/deeptutor/tools/prompting/__init__.py
@@ -91,12 +91,11 @@ class ToolPromptComposer:
def __init__(self, language: str = "en") -> None:
self.language = _normalize_language(language)
- def format_list(self, hints: list[ToolHintEntry], kb_name: str = "") -> str:
+ def format_list(self, hints: list[ToolHintEntry]) -> str:
lines: list[str] = []
for name, hint in hints:
- description = self._apply_kb_name(hint.short_description, kb_name)
- if description:
- lines.append(f"- {name}: {description}")
+ if hint.short_description:
+ lines.append(f"- {name}: {hint.short_description}")
return "\n".join(lines)
def format_table(
@@ -177,12 +176,5 @@ class ToolPromptComposer:
sections.append(f"**{label}**\n" + "\n".join(items))
return "\n\n".join(sections)
- @staticmethod
- def _apply_kb_name(text: str, kb_name: str) -> str:
- if not kb_name or not text:
- return text
- updated = text.replace("the uploaded knowledge base", f'the knowledge base "{kb_name}"')
- return updated.replace("已上传知识库", f'知识库 "{kb_name}"')
-
__all__ = ["ToolPromptComposer", "load_prompt_hints"]
diff --git a/deeptutor/tools/prompting/hints/en/rag.yaml b/deeptutor/tools/prompting/hints/en/rag.yaml
index bfd4cfa1b..242a122ad 100644
--- a/deeptutor/tools/prompting/hints/en/rag.yaml
+++ b/deeptutor/tools/prompting/hints/en/rag.yaml
@@ -1,6 +1,6 @@
-short_description: "Search the knowledge base for relevant passages and grounded answers."
-when_to_use: "Use when the answer is likely covered by the uploaded knowledge base, such as definitions, formulas, concepts, or textbook explanations."
-input_format: "{\"query\": \"non-empty natural-language query\"}. Do not pass an empty query or kb_name."
-guideline: "Prefer RAG before external search when the task is course-aligned or knowledge-base-specific."
-note: "The query must be non-empty; if the first retrieval is weak, revise the query from another angle instead of giving up immediately."
+short_description: "Retrieve relevant passages from one of the attached knowledge bases."
+when_to_use: "Use when the answer is likely covered by the attached knowledge bases — definitions, formulas, concepts, or textbook explanations."
+input_format: "{\"query\": \"non-empty natural-language query\", \"kb_name\": \"one of the attached knowledge base names\"}."
+guideline: "Prefer RAG before external search when the task is course-aligned. To consult multiple knowledge bases, call rag once per kb_name (the system runs them in parallel)."
+note: "The query must be non-empty; if the first retrieval is weak, revise the query from another angle before giving up."
phase: "exploration"
diff --git a/deeptutor/tools/prompting/hints/zh/rag.yaml b/deeptutor/tools/prompting/hints/zh/rag.yaml
index 950acdbd5..ccca5b479 100644
--- a/deeptutor/tools/prompting/hints/zh/rag.yaml
+++ b/deeptutor/tools/prompting/hints/zh/rag.yaml
@@ -1,6 +1,6 @@
-short_description: "在知识库中检索相关内容,并生成有依据的回答。"
-when_to_use: "当答案大概率来自已上传知识库,例如定义、公式、概念解释或教材内容时使用。"
-input_format: "{\"query\": \"非空自然语言查询\"}。不要传空 query 或 kb_name。"
-guideline: "如果任务与课程材料强相关,优先使用 RAG,而不是直接转向外部搜索。"
-note: "query 不能为空;若第一次检索效果不佳,应先换一个查询角度再判断是否无结果。"
+short_description: "在用户挂载的某个知识库中检索相关内容。"
+when_to_use: "当答案大概率来自用户挂载的知识库(定义、公式、概念解释、教材内容)时使用。"
+input_format: "{\"query\": \"非空自然语言查询\", \"kb_name\": \"挂载的某个知识库名称\"}。"
+guideline: "课程材料相关的问题优先用 RAG。需要查多个知识库时,按 kb_name 分别多次调用(系统会并行执行)。"
+note: "query 不能为空;如果第一次检索效果不佳,换个查询角度再判断是否无结果。"
phase: "exploration"
diff --git a/deeptutor/tools/question/question_extractor.py b/deeptutor/tools/question/question_extractor.py
index 07d2c734a..032cda6e8 100644
--- a/deeptutor/tools/question/question_extractor.py
+++ b/deeptutor/tools/question/question_extractor.py
@@ -205,30 +205,26 @@ Please analyze the above exam paper content, extract all question information, a
llm_kwargs["response_format"] = {"type": "json_object"}
try:
- # Call LLM via unified Factory (async, so we need to run in event loop)
- loop = asyncio.get_event_loop()
- if loop.is_running():
- # We're in an existing event loop, run in a thread
- import concurrent.futures
-
- with concurrent.futures.ThreadPoolExecutor() as executor:
- future = executor.submit(
- asyncio.run,
- llm_complete(
- prompt=user_prompt,
- system_prompt=system_prompt,
- model=model,
- api_key=api_key,
- base_url=base_url,
- api_version=api_version,
- binding=binding,
- **llm_kwargs,
- ),
- )
- result_text = future.result()
- else:
- # No running loop, use run_until_complete
- result_text = loop.run_until_complete(
+ asyncio.get_running_loop()
+ except RuntimeError:
+ result_text = asyncio.run(
+ llm_complete(
+ prompt=user_prompt,
+ system_prompt=system_prompt,
+ model=model,
+ api_key=api_key,
+ base_url=base_url,
+ api_version=api_version,
+ binding=binding,
+ **llm_kwargs,
+ )
+ )
+ else:
+ import concurrent.futures
+
+ with concurrent.futures.ThreadPoolExecutor() as executor:
+ future = executor.submit(
+ asyncio.run,
llm_complete(
prompt=user_prompt,
system_prompt=system_prompt,
@@ -238,30 +234,9 @@ Please analyze the above exam paper content, extract all question information, a
api_version=api_version,
binding=binding,
**llm_kwargs,
- )
+ ),
)
- except RuntimeError as e:
- if "already running" in str(e):
- # Fallback: use asyncio.run in a thread
- import concurrent.futures
-
- with concurrent.futures.ThreadPoolExecutor() as executor:
- future = executor.submit(
- asyncio.run,
- llm_complete(
- prompt=user_prompt,
- system_prompt=system_prompt,
- model=model,
- api_key=api_key,
- base_url=base_url,
- api_version=api_version,
- binding=binding,
- **llm_kwargs,
- ),
- )
- result_text = future.result()
- else:
- raise
+ result_text = future.result()
# Parse JSON response
try:
@@ -350,9 +325,7 @@ def extract_questions_from_paper(paper_dir: str, output_dir: str | None = None)
llm_config = get_llm_config()
except ValueError as e:
print(f"✗ {e!s}")
- print(
- "Tip: Configure an active LLM profile in Settings > Catalog"
- )
+ print("Tip: Configure an active LLM profile in Settings > Catalog")
return False
questions = extract_questions_with_llm(
diff --git a/deeptutor/tools/rag_tool.py b/deeptutor/tools/rag_tool.py
index 160bba84c..a50a946e4 100644
--- a/deeptutor/tools/rag_tool.py
+++ b/deeptutor/tools/rag_tool.py
@@ -1,114 +1,54 @@
-#!/usr/bin/env python
-"""
-RAG Query Tool - Pure tool wrapper for RAG operations
+"""RAG query tool — thin wrapper around :class:`RAGService`.
-This module provides simple function wrappers for RAG operations.
-All logic is delegated to RAGService in deeptutor/services/rag/service.py.
+The chat pipeline always passes an explicit ``kb_name`` selected by the user;
+this module therefore never resolves aliases or falls back to a default KB.
"""
+from __future__ import annotations
+
import asyncio
from typing import Dict, List, Optional
-# Import RAGService as the single entry point
-from deeptutor.services.rag.service import DEFAULT_KB_BASE_DIR, RAGService
-
-DEFAULT_KB_ALIASES = {"", "default", "current", "selected", "默认", "默认知识库", "当前知识库"}
-
-
-def _resolve_kb_name(kb_name: Optional[str], kb_base_dir: Optional[str] = None) -> Optional[str]:
- """Resolve generic/default KB aliases to the configured default KB."""
- requested = str(kb_name or "").strip()
- try:
- from deeptutor.knowledge.manager import KnowledgeBaseManager
-
- manager = KnowledgeBaseManager(base_dir=kb_base_dir or DEFAULT_KB_BASE_DIR)
- kb_names = manager.list_knowledge_bases()
- if requested and requested in kb_names:
- return requested
- if requested.lower() in DEFAULT_KB_ALIASES:
- default_kb = manager.get_default()
- if default_kb:
- return default_kb
- except Exception:
- # Keep tool startup lightweight; the service will surface a concrete
- # retrieval error if the KB cannot be resolved from disk.
- pass
- return requested or None
+from deeptutor.services.rag.service import RAGService
async def rag_search(
query: str,
- kb_name: Optional[str] = None,
+ kb_name: str,
provider: Optional[str] = None,
kb_base_dir: Optional[str] = None,
event_sink=None,
**kwargs,
) -> dict:
+ """Retrieve passages from ``kb_name`` and synthesise an answer.
+
+ ``kb_name`` must match a knowledge base the current user can access;
+ multi-user routing is delegated to :func:`resolve_for_rag` when no
+ explicit ``kb_base_dir`` is given.
"""
- Query knowledge base using LlamaIndex RAG pipeline.
-
- Args:
- query: Query question
- kb_name: Knowledge base name (optional, defaults to default knowledge base)
- provider: RAG pipeline to use (defaults to configured provider or "llamaindex")
- kb_base_dir: Base directory for knowledge bases (for testing)
- **kwargs: Additional parameters passed to the RAG pipeline
-
- Returns:
- dict: Dictionary containing query results
- {
- "query": str,
- "answer": str,
- "content": str,
- "sources": list,
- "provider": str
- }
- """
- query = str(query or "").strip()
+ query = query.strip() if isinstance(query, str) else ""
+ kb_name = kb_name.strip() if isinstance(kb_name, str) else ""
if not query:
raise ValueError("RAG query must be a non-empty string.")
+ if not kb_name:
+ raise ValueError("RAG requires an explicit kb_name.")
if kb_base_dir is None:
- try:
- from deeptutor.multi_user.context import get_current_user
- from deeptutor.multi_user.knowledge_access import resolve_for_rag
-
- resource = resolve_for_rag(kb_name)
- if resource is not None:
- kb_base_dir = str(resource.base_dir)
- kb_name = resource.name
- elif not get_current_user().is_admin:
- # Non-admin users must never silently fall back to admin's KB
- # directory. ``resolve_for_rag`` returning ``None`` means the
- # caller passed no kb_name at all — surface that as a
- # configuration error instead of leaking admin KBs.
- raise ValueError(
- "No knowledge base selected. Pass kb_name explicitly or set a default."
- )
- except ValueError:
- raise
- except Exception as exc:
- if getattr(exc, "status_code", None) in {403, 404}:
- raise
- # Fall back to the legacy resolver so CLI/local single-user remains
- # tolerant when no request context exists. This branch only runs
- # for admin / single-user mode (the non-admin path raised above).
- pass
+ from deeptutor.multi_user.knowledge_access import resolve_for_rag
+
+ resource = resolve_for_rag(kb_name)
+ if resource is None:
+ raise ValueError(f"Knowledge base '{kb_name}' is not accessible.")
+ kb_base_dir = str(resource.base_dir)
+ kb_name = resource.name
service = RAGService(kb_base_dir=kb_base_dir, provider=provider)
- resolved_kb_name = _resolve_kb_name(kb_name, kb_base_dir=kb_base_dir)
- if not resolved_kb_name:
- raise ValueError("No knowledge base selected and no default knowledge base is configured.")
-
- try:
- return await service.search(
- query=query,
- kb_name=resolved_kb_name,
- event_sink=event_sink,
- **kwargs,
- )
- except Exception as e:
- raise Exception(f"RAG search failed: {e}")
+ return await service.search(
+ query=query,
+ kb_name=kb_name,
+ event_sink=event_sink,
+ **kwargs,
+ )
async def initialize_rag(
@@ -118,23 +58,7 @@ async def initialize_rag(
kb_base_dir: Optional[str] = None,
**kwargs,
) -> bool:
- """
- Initialize RAG with documents.
-
- Args:
- kb_name: Knowledge base name
- documents: List of document file paths to index
- provider: RAG pipeline to use (defaults to configured provider)
- kb_base_dir: Base directory for knowledge bases (for testing)
- **kwargs: Additional arguments passed to pipeline
-
- Returns:
- True if successful
-
- Example:
- documents = ["doc1.pdf", "doc2.txt"]
- success = await initialize_rag("my_kb", documents)
- """
+ """Index ``documents`` into ``kb_name`` using the configured RAG pipeline."""
service = RAGService(kb_base_dir=kb_base_dir, provider=provider)
return await service.initialize(kb_name=kb_name, file_paths=documents, **kwargs)
@@ -144,45 +68,20 @@ async def delete_rag(
provider: Optional[str] = None,
kb_base_dir: Optional[str] = None,
) -> bool:
- """
- Delete a knowledge base.
-
- Args:
- kb_name: Knowledge base name
- provider: RAG pipeline to use (defaults to configured provider)
- kb_base_dir: Base directory for knowledge bases (for testing)
-
- Returns:
- True if successful
-
- Example:
- success = await delete_rag("old_kb")
- """
+ """Delete the knowledge base ``kb_name``."""
service = RAGService(kb_base_dir=kb_base_dir, provider=provider)
return await service.delete(kb_name=kb_name)
def get_available_providers() -> List[Dict]:
- """
- Get list of available RAG pipelines.
-
- Returns:
- List of pipeline information dictionaries
-
- Example:
- providers = get_available_providers()
- for p in providers:
- print(f"{p['name']}: {p['description']}")
- """
return RAGService.list_providers()
def get_current_provider() -> str:
- """Get the currently configured RAG provider"""
return RAGService.get_current_provider()
-# Backward compatibility aliases
+# Backward-compat aliases used by a few callers / tests
get_available_plugins = get_available_providers
list_providers = RAGService.list_providers
@@ -195,20 +94,17 @@ if __name__ == "__main__":
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
- # List available providers
print("Available RAG Pipelines:")
for provider in get_available_providers():
print(f" - {provider['id']}: {provider['description']}")
print(f"\nCurrent provider: {get_current_provider()}\n")
- # Test search (requires existing knowledge base)
result = asyncio.run(
rag_search(
"What is the lookup table (LUT) in FPGA?",
kb_name="DE-all",
)
)
-
print(f"Query: {result['query']}")
print(f"Answer: {result['answer']}")
print(f"Provider: {result.get('provider', 'unknown')}")
diff --git a/deeptutor/tutorbot/agent/tools/registry.py b/deeptutor/tutorbot/agent/tools/registry.py
index 0e6b33eee..7630649e9 100644
--- a/deeptutor/tutorbot/agent/tools/registry.py
+++ b/deeptutor/tutorbot/agent/tools/registry.py
@@ -106,5 +106,5 @@ def build_base_tools(
)
)
tools.register(WebSearchTool(config=web_search_config, proxy=web_proxy))
- tools.register(WebFetchTool(proxy=web_proxy))
+ tools.register(WebFetchTool(proxy=web_proxy, config=web_search_config))
return tools
diff --git a/deeptutor/tutorbot/agent/tools/web.py b/deeptutor/tutorbot/agent/tools/web.py
index 88bf4cce5..3cab86dbd 100644
--- a/deeptutor/tutorbot/agent/tools/web.py
+++ b/deeptutor/tutorbot/agent/tools/web.py
@@ -236,9 +236,17 @@ class WebFetchTool(Tool):
"required": ["url"],
}
- def __init__(self, max_chars: int = 50000, proxy: str | None = None):
+ def __init__(
+ self,
+ max_chars: int = 50000,
+ proxy: str | None = None,
+ config: WebSearchConfig | None = None,
+ ):
+ from deeptutor.tutorbot.config.schema import WebSearchConfig as _WebSearchConfig
+
self.max_chars = max_chars
self.proxy = proxy
+ self.config = config if config is not None else _WebSearchConfig()
async def execute( # type: ignore[override]
self, url: str, extractMode: str = "markdown", maxChars: int | None = None, **kwargs: Any
diff --git a/deeptutor/tutorbot/channels/mochat.py b/deeptutor/tutorbot/channels/mochat.py
index 2984d2158..a583eec07 100644
--- a/deeptutor/tutorbot/channels/mochat.py
+++ b/deeptutor/tutorbot/channels/mochat.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import asyncio
from collections import deque
from dataclasses import dataclass, field
-from datetime import datetime
+from datetime import datetime, timezone
import json
from typing import Any
@@ -116,7 +116,7 @@ def _make_synthetic_event(
payload["authorInfo"] = _safe_dict(author_info)
return {
"type": "message.add",
- "timestamp": timestamp or datetime.utcnow().isoformat(),
+ "timestamp": timestamp or datetime.now(timezone.utc).replace(tzinfo=None).isoformat(),
"payload": payload,
}
@@ -997,7 +997,7 @@ class MochatChannel(BaseChannel):
json.dumps(
{
"schemaVersion": 1,
- "updatedAt": datetime.utcnow().isoformat(),
+ "updatedAt": datetime.now(timezone.utc).replace(tzinfo=None).isoformat(),
"cursors": self._session_cursor,
},
ensure_ascii=False,
diff --git a/deeptutor_cli/bot.py b/deeptutor_cli/bot.py
index a5148fb15..6aac94521 100644
--- a/deeptutor_cli/bot.py
+++ b/deeptutor_cli/bot.py
@@ -51,7 +51,7 @@ def register(app: typer.Typer) -> None:
mgr = get_tutorbot_manager()
try:
- instance = asyncio.get_event_loop().run_until_complete(mgr.start_bot(name))
+ instance = asyncio.run(mgr.start_bot(name))
console.print(f"[green]Started TutorBot '{instance.config.name}' ({name})[/]")
except RuntimeError as e:
console.print(f"[red]Failed to start: {e}[/]")
@@ -65,7 +65,7 @@ def register(app: typer.Typer) -> None:
from deeptutor.services.tutorbot import get_tutorbot_manager
mgr = get_tutorbot_manager()
- stopped = asyncio.get_event_loop().run_until_complete(mgr.stop_bot(name))
+ stopped = asyncio.run(mgr.stop_bot(name))
if stopped:
console.print(f"[green]Stopped TutorBot '{name}'[/]")
else:
@@ -89,7 +89,7 @@ def register(app: typer.Typer) -> None:
)
mgr = get_tutorbot_manager()
try:
- instance = asyncio.get_event_loop().run_until_complete(mgr.start_bot(name, config))
+ instance = asyncio.run(mgr.start_bot(name, config))
console.print(
f"[green]Created and started TutorBot '{instance.config.name}' ({name})[/]"
)
diff --git a/deeptutor_cli/config_cmd.py b/deeptutor_cli/config_cmd.py
index 4ab239b04..8b6903fd9 100644
--- a/deeptutor_cli/config_cmd.py
+++ b/deeptutor_cli/config_cmd.py
@@ -20,8 +20,8 @@ def register(app: typer.Typer) -> None:
import json
from deeptutor.services.config import (
- load_system_settings,
load_config_with_main,
+ load_system_settings,
resolve_embedding_runtime_config,
resolve_llm_runtime_config,
resolve_search_runtime_config,
diff --git a/deeptutor_cli/init_cmd.py b/deeptutor_cli/init_cmd.py
index 0a524d1b8..455deee89 100644
--- a/deeptutor_cli/init_cmd.py
+++ b/deeptutor_cli/init_cmd.py
@@ -42,11 +42,15 @@ def _ensure_model_service(catalog: dict, service_name: str, profile_id: str, mod
{"active_profile_id": profile_id, "active_model_id": model_id, "profiles": []},
)
profiles = service.setdefault("profiles", [])
- profile = next((item for item in profiles if item.get("id") == service.get("active_profile_id")), None)
+ profile = next(
+ (item for item in profiles if item.get("id") == service.get("active_profile_id")), None
+ )
if profile is None:
profile = {
"id": profile_id,
- "name": "Default LLM Endpoint" if service_name == "llm" else "Default Embedding Endpoint",
+ "name": "Default LLM Endpoint"
+ if service_name == "llm"
+ else "Default Embedding Endpoint",
"binding": "openai",
"base_url": "",
"api_key": "",
@@ -57,7 +61,9 @@ def _ensure_model_service(catalog: dict, service_name: str, profile_id: str, mod
profiles.append(profile)
service["active_profile_id"] = profile_id
models = profile.setdefault("models", [])
- model = next((item for item in models if item.get("id") == service.get("active_model_id")), None)
+ model = next(
+ (item for item in models if item.get("id") == service.get("active_model_id")), None
+ )
if model is None:
model = {"id": model_id, "name": "Default Model", "model": ""}
models.append(model)
@@ -73,19 +79,28 @@ def run_init(*, cli_only: bool = False, home: str | Path | None = None) -> None:
os.environ[DEEPTUTOR_HOME_ENV] = str(runtime_home)
_reset_runtime_singletons()
+ from deeptutor.runtime.banner import labels_for, print_banner, resolve_language
from deeptutor.services.config import get_model_catalog_service, get_runtime_settings_service
from deeptutor.services.setup import init_user_directories
init_user_directories(runtime_home)
- typer.echo(f"DeepTutor workspace: {runtime_home}")
- typer.echo("Settings will be written under data/user/settings.")
+ language = resolve_language()
+ strings = labels_for(language)
+
+ print_banner(language=language, mode_key="init.mode")
+ typer.echo(f"{strings['init.workspace']}: {runtime_home}")
+ typer.echo(strings["init.note_settings_dir"])
runtime = get_runtime_settings_service()
system = runtime.load_system(include_process_overrides=False)
if not cli_only:
- system["backend_port"] = int(_prompt(str(system.get("backend_port") or 8001), "Backend port"))
- system["frontend_port"] = int(_prompt(str(system.get("frontend_port") or 3782), "Frontend port"))
+ system["backend_port"] = int(
+ _prompt(str(system.get("backend_port") or 8001), strings["init.backend_port"])
+ )
+ system["frontend_port"] = int(
+ _prompt(str(system.get("frontend_port") or 3782), strings["init.frontend_port"])
+ )
runtime.save_system(system)
catalog_service = get_model_catalog_service()
@@ -96,33 +111,53 @@ def run_init(*, cli_only: bool = False, home: str | Path | None = None) -> None:
"llm-profile-default",
"llm-model-default",
)
- typer.echo("\nLLM provider")
- llm_profile["binding"] = _prompt(str(llm_profile.get("binding") or "openai"), "Binding")
- llm_profile["base_url"] = _prompt(str(llm_profile.get("base_url") or "https://api.openai.com/v1"), "Base URL")
- llm_profile["api_key"] = _prompt(str(llm_profile.get("api_key") or ""), "API key", hide=True)
- llm_model["model"] = _prompt(str(llm_model.get("model") or "gpt-4o-mini"), "Model")
+ typer.echo(f"\n{strings['init.llm_section']}")
+ llm_profile["binding"] = _prompt(
+ str(llm_profile.get("binding") or "openai"), strings["init.binding"]
+ )
+ llm_profile["base_url"] = _prompt(
+ str(llm_profile.get("base_url") or "https://api.openai.com/v1"),
+ strings["init.base_url"],
+ )
+ llm_profile["api_key"] = _prompt(
+ str(llm_profile.get("api_key") or ""), strings["init.api_key"], hide=True
+ )
+ llm_model["model"] = _prompt(
+ str(llm_model.get("model") or "gpt-4o-mini"), strings["init.model"]
+ )
llm_model["name"] = llm_model["model"] or "Default Model"
- if typer.confirm("Configure embedding for Knowledge Base/RAG now?", default=not cli_only):
+ if typer.confirm(strings["init.confirm_embedding"], default=not cli_only):
emb_profile, emb_model = _ensure_model_service(
catalog,
"embedding",
"embedding-profile-default",
"embedding-model-default",
)
- typer.echo("\nEmbedding provider")
- emb_profile["binding"] = _prompt(str(emb_profile.get("binding") or "openai"), "Binding")
+ typer.echo(f"\n{strings['init.embedding_section']}")
+ emb_profile["binding"] = _prompt(
+ str(emb_profile.get("binding") or "openai"), strings["init.binding"]
+ )
emb_profile["base_url"] = _prompt(
str(emb_profile.get("base_url") or "https://api.openai.com/v1/embeddings"),
- "Embedding endpoint URL",
+ strings["init.embedding_endpoint"],
+ )
+ emb_profile["api_key"] = _prompt(
+ str(emb_profile.get("api_key") or ""),
+ strings["init.embedding_api_key"],
+ hide=True,
+ )
+ emb_model["model"] = _prompt(
+ str(emb_model.get("model") or "text-embedding-3-large"),
+ strings["init.embedding_model"],
)
- emb_profile["api_key"] = _prompt(str(emb_profile.get("api_key") or ""), "Embedding API key", hide=True)
- emb_model["model"] = _prompt(str(emb_model.get("model") or "text-embedding-3-large"), "Embedding model")
emb_model["name"] = emb_model["model"] or "Default Embedding Model"
- emb_model["dimension"] = _prompt(str(emb_model.get("dimension") or ""), "Embedding dimension (blank for auto)")
+ emb_model["dimension"] = _prompt(
+ str(emb_model.get("dimension") or ""), strings["init.embedding_dimension"]
+ )
catalog_service.save(catalog)
- typer.echo("\nSettings saved. You can edit them later in the Web Settings page or data/user/settings/.")
+ typer.echo(f"\n{strings['init.saved']}")
def register(app: typer.Typer) -> None:
diff --git a/packaging/deeptutor-cli/pyproject.toml b/packaging/deeptutor-cli/pyproject.toml
index 826268e50..9a56476ac 100644
--- a/packaging/deeptutor-cli/pyproject.toml
+++ b/packaging/deeptutor-cli/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "deeptutor-cli"
-version = "1.0.0"
+dynamic = ["version"]
description = "CLI-only distribution for DeepTutor"
requires-python = ">=3.11"
readme = "README.md"
@@ -29,7 +29,7 @@ dependencies = [
"anthropic>=0.30.0",
"dashscope>=1.14.0",
"perplexityai>=0.1.0",
- "oauth-cli-kit>=0.1.1; python_version >= '3.11'",
+ "oauth-cli-kit>=0.1.1",
"llama-index>=0.14.12",
"PyMuPDF>=1.26.0",
"numpy>=1.24.0,<3.0.0",
@@ -48,6 +48,9 @@ deeptutor = "deeptutor_cli.main:main"
package-dir = {"" = "../.."}
include-package-data = false
+[tool.setuptools.dynamic]
+version = {attr = "deeptutor.__version__.__version__"}
+
[tool.setuptools.packages.find]
where = ["../.."]
include = ["deeptutor*", "deeptutor_cli*"]
diff --git a/pyproject.toml b/pyproject.toml
index cec0fa6a2..e369b4ab2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "deeptutor"
-version = "1.0.0"
+dynamic = ["version"]
description = "An agent-native intelligent learning companion with multi-agent collaboration and RAG"
requires-python = ">=3.11"
readme = "README.md"
@@ -34,7 +34,7 @@ dependencies = [
"anthropic>=0.30.0",
"dashscope>=1.14.0",
"perplexityai>=0.1.0",
- "oauth-cli-kit>=0.1.1; python_version >= '3.11'",
+ "oauth-cli-kit>=0.1.1",
"llama-index>=0.14.12",
"PyMuPDF>=1.26.0",
"numpy>=1.24.0,<3.0.0",
@@ -67,7 +67,7 @@ cli = [
"anthropic>=0.30.0",
"dashscope>=1.14.0",
"perplexityai>=0.1.0",
- "oauth-cli-kit>=0.1.1; python_version >= '3.11'",
+ "oauth-cli-kit>=0.1.1",
# RAG (LlamaIndex)
"llama-index>=0.14.12",
"PyMuPDF>=1.26.0",
@@ -157,6 +157,9 @@ all = [
[tool.setuptools]
include-package-data = true
+[tool.setuptools.dynamic]
+version = {attr = "deeptutor.__version__.__version__"}
+
[tool.setuptools.packages.find]
where = ["."]
include = ["deeptutor*", "deeptutor_cli*"]
@@ -169,7 +172,7 @@ deeptutor_web = ["**/*", ".next/**/*"]
# ============================================
[tool.black]
line-length = 100
-target-version = ['py311', 'py312']
+target-version = ['py311', 'py312', 'py313', 'py314']
include = '\.pyi?$'
extend-exclude = '''
/(
diff --git a/scripts/check_install.py b/scripts/check_install.py
index 7265225cb..5ead6f0af 100644
--- a/scripts/check_install.py
+++ b/scripts/check_install.py
@@ -86,10 +86,10 @@ def check_python_environment() -> bool:
py_version = sys.version_info
print_info(f"Python version: {py_version.major}.{py_version.minor}.{py_version.micro}")
- if py_version >= (3, 10):
- print_success(f"Python {py_version.major}.{py_version.minor} meets requirement (>=3.10)")
+ if py_version >= (3, 11):
+ print_success(f"Python {py_version.major}.{py_version.minor} meets requirement (>=3.11)")
else:
- print_error(f"Python {py_version.major}.{py_version.minor} is below requirement (>=3.10)")
+ print_error(f"Python {py_version.major}.{py_version.minor} is below requirement (>=3.11)")
all_ok = False
# Python executable
diff --git a/scripts/test_embedding.py b/scripts/test_embedding.py
index d07f1677d..e3aee3ab9 100644
--- a/scripts/test_embedding.py
+++ b/scripts/test_embedding.py
@@ -22,6 +22,7 @@ PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
+
def _load_embedding_services():
from deeptutor.services.embedding.client import get_embedding_client, reset_embedding_client
from deeptutor.services.embedding.config import get_embedding_config
diff --git a/scripts/test_llm_api.py b/scripts/test_llm_api.py
index 83ef9ae72..33abc97dc 100644
--- a/scripts/test_llm_api.py
+++ b/scripts/test_llm_api.py
@@ -22,6 +22,7 @@ PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
+
def _load_llm_services():
from deeptutor.services.llm import factory
from deeptutor.services.llm.config import clear_llm_config_cache, get_llm_config
diff --git a/scripts/update.py b/scripts/update.py
index 1efcb41fa..b069c756e 100644
--- a/scripts/update.py
+++ b/scripts/update.py
@@ -332,9 +332,7 @@ def ensure_safe_to_update(gap: BranchGap) -> None:
def dependency_hints(changed_files: list[str]) -> list[str]:
hints: list[str] = []
if any(path == "pyproject.toml" or path.startswith("requirements/") for path in changed_files):
- hints.append(
- 'Backend dependencies changed: consider running python -m pip install -e .'
- )
+ hints.append("Backend dependencies changed: consider running python -m pip install -e .")
if any(
path in {"web/package.json", "web/package-lock.json", "web/pnpm-lock.yaml"}
or path == "web/yarn.lock"
diff --git a/tests/agents/auto/__init__.py b/tests/agents/auto/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/tests/agents/auto/test_delegation.py b/tests/agents/auto/test_delegation.py
new file mode 100644
index 000000000..7835c2b52
--- /dev/null
+++ b/tests/agents/auto/test_delegation.py
@@ -0,0 +1,298 @@
+"""Unit tests for ``deeptutor/agents/auto/delegation.py``.
+
+Covers:
+* ``build_child_context`` correctly derives a child UnifiedContext via
+ ``dataclasses.replace`` without mutating the parent (assumption A1).
+* ``forward_events`` injects required metadata fields and protects
+ conversation_history from sub-capability CONTENT pollution by ensuring
+ every forwarded CONTENT carries a ``call_id`` (assumption A3 integration).
+* ``delegate_to_capability`` happy path + raise/error-event paths.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from unittest.mock import patch
+
+import pytest
+
+from deeptutor.agents.auto.delegation import (
+ build_child_context,
+ delegate_to_capability,
+)
+from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest
+from deeptutor.core.context import Attachment, UnifiedContext
+from deeptutor.core.stream import StreamEvent, StreamEventType
+from deeptutor.core.stream_bus import StreamBus
+
+# --------------------------------------------------------------------------- #
+# Test fixtures #
+# --------------------------------------------------------------------------- #
+
+
+class _FakeCapability(BaseCapability):
+ """Configurable fake capability for delegation tests."""
+
+ def __init__(
+ self,
+ name: str = "fake",
+ events: list[StreamEvent] | None = None,
+ raise_exc: Exception | None = None,
+ ) -> None:
+ self.manifest = CapabilityManifest(
+ name=name,
+ description="fake test capability",
+ stages=["only"],
+ )
+ self._scripted_events = events or []
+ self._raise = raise_exc
+ self.received_context: UnifiedContext | None = None
+
+ async def run(self, context: UnifiedContext, stream: StreamBus) -> None:
+ self.received_context = context
+ for event in self._scripted_events:
+ await stream.emit(event)
+ if self._raise is not None:
+ raise self._raise
+
+
+def _ctx(**overrides: Any) -> UnifiedContext:
+ return UnifiedContext(
+ session_id="sess-1",
+ user_message="hello",
+ knowledge_bases=["kb-a"],
+ enabled_tools=["rag"],
+ attachments=[Attachment(type="pdf", filename="paper.pdf")],
+ metadata={"shared": "x"},
+ **overrides,
+ )
+
+
+# --------------------------------------------------------------------------- #
+# build_child_context #
+# --------------------------------------------------------------------------- #
+
+
+def test_build_child_context_overrides_capability_and_config():
+ parent = _ctx()
+ child = build_child_context(
+ parent,
+ cap_name="deep_solve",
+ config={"detailed_answer": False},
+ delegation_call_id="del-1",
+ )
+ assert child.active_capability == "deep_solve"
+ assert child.config_overrides == {"detailed_answer": False}
+ assert child.metadata["is_sub_invocation"] is True
+ assert child.metadata["parent_delegation_call_id"] == "del-1"
+ # Shared metadata key is preserved.
+ assert child.metadata["shared"] == "x"
+
+
+def test_build_child_context_does_not_mutate_parent():
+ parent = _ctx()
+ parent_metadata_before = dict(parent.metadata)
+ parent_kbs_before = list(parent.knowledge_bases)
+
+ build_child_context(
+ parent,
+ cap_name="deep_solve",
+ config={},
+ delegation_call_id="del-2",
+ knowledge_bases=["kb-other"],
+ enabled_tools=["web_search"],
+ )
+
+ # Parent fields unchanged.
+ assert parent.metadata == parent_metadata_before
+ assert parent.knowledge_bases == parent_kbs_before
+ assert parent.active_capability is None
+
+
+def test_build_child_context_inherits_when_args_missing():
+ parent = _ctx()
+ child = build_child_context(
+ parent,
+ cap_name="deep_solve",
+ config={},
+ delegation_call_id="del-3",
+ enabled_tools=None,
+ knowledge_bases=None,
+ )
+ assert child.enabled_tools == ["rag"]
+ assert child.knowledge_bases == ["kb-a"]
+ assert child.attachments == parent.attachments # passed through
+
+
+def test_build_child_context_accepts_explicit_overrides():
+ parent = _ctx()
+ child = build_child_context(
+ parent,
+ cap_name="visualize",
+ config={"render_mode": "svg"},
+ delegation_call_id="del-4",
+ enabled_tools=["code_execution"],
+ knowledge_bases=["kb-other"],
+ )
+ assert child.enabled_tools == ["code_execution"]
+ assert child.knowledge_bases == ["kb-other"]
+
+
+# --------------------------------------------------------------------------- #
+# delegate_to_capability — full forwarder + runner flow #
+# --------------------------------------------------------------------------- #
+
+
+def _evt(
+ event_type: StreamEventType,
+ *,
+ content: str = "",
+ metadata: dict[str, Any] | None = None,
+) -> StreamEvent:
+ return StreamEvent(
+ type=event_type,
+ source="fake",
+ stage="only",
+ content=content,
+ metadata=metadata or {},
+ )
+
+
+def _collect_events(parent_bus: StreamBus) -> list[StreamEvent]:
+ return list(parent_bus._history)
+
+
+async def test_delegate_happy_path_forwards_events_with_metadata():
+ parent_bus = StreamBus()
+ fake = _FakeCapability(
+ name="visualize",
+ events=[
+ _evt(StreamEventType.THINKING, content="thinking..."),
+ _evt(StreamEventType.CONTENT, content="result body"),
+ _evt(StreamEventType.RESULT, metadata={"response": "ok"}),
+ ],
+ )
+ with patch(
+ "deeptutor.agents.auto.delegation.get_capability_registry"
+ ) as mock_get_reg:
+ mock_get_reg.return_value.get.return_value = fake
+
+ result = await delegate_to_capability(
+ cap_name="visualize",
+ config={"render_mode": "svg"},
+ parent_context=_ctx(),
+ parent_stream=parent_bus,
+ )
+
+ assert result.succeeded is True
+ assert result.capability == "visualize"
+ assert result.delegation_call_id.startswith("auto-delegation-")
+ assert result.result_metadata == {"response": "ok"}
+
+ events = _collect_events(parent_bus)
+ # All forwarded events should have the auto metadata stamped.
+ assert len(events) == 3
+ for ev in events:
+ assert ev.metadata["delegated_capability"] == "visualize"
+ assert ev.metadata["delegated_from"] == "auto"
+ assert ev.metadata["parent_call_id"] == result.delegation_call_id
+ assert ev.metadata["delegation_attempt"] == 1
+
+
+async def test_delegate_injects_call_id_into_content_without_one():
+ """Critical: prevents sub-capability CONTENT from polluting history."""
+ parent_bus = StreamBus()
+ fake = _FakeCapability(
+ name="deep_solve",
+ events=[
+ # CONTENT without any call_id — this is the dangerous case.
+ _evt(StreamEventType.CONTENT, content="body 1"),
+ # CONTENT with an existing call_id — should be preserved as-is.
+ _evt(
+ StreamEventType.CONTENT,
+ content="body 2",
+ metadata={"call_id": "existing-call", "call_kind": "intermediate"},
+ ),
+ ],
+ )
+ with patch(
+ "deeptutor.agents.auto.delegation.get_capability_registry"
+ ) as mock_get_reg:
+ mock_get_reg.return_value.get.return_value = fake
+ result = await delegate_to_capability(
+ cap_name="deep_solve",
+ config={},
+ parent_context=_ctx(),
+ parent_stream=parent_bus,
+ )
+
+ forwarded = _collect_events(parent_bus)
+ assert len(forwarded) == 2
+
+ # First event got an injected call_id.
+ assert forwarded[0].metadata.get("call_id") == result.delegation_call_id
+
+ # Second event preserved its original call_id.
+ assert forwarded[1].metadata.get("call_id") == "existing-call"
+
+
+async def test_delegate_captures_raise_as_failure():
+ parent_bus = StreamBus()
+ fake = _FakeCapability(name="boom", raise_exc=RuntimeError("kaboom"))
+ with patch(
+ "deeptutor.agents.auto.delegation.get_capability_registry"
+ ) as mock_get_reg:
+ mock_get_reg.return_value.get.return_value = fake
+ result = await delegate_to_capability(
+ cap_name="boom",
+ config={},
+ parent_context=_ctx(),
+ parent_stream=parent_bus,
+ )
+
+ assert result.succeeded is False
+ assert result.error_message and "kaboom" in result.error_message
+
+
+async def test_delegate_marks_failure_on_error_event():
+ """A capability that emits ERROR (instead of raising) should count as failure."""
+ parent_bus = StreamBus()
+ fake = _FakeCapability(
+ name="errorful",
+ events=[_evt(StreamEventType.ERROR, content="problem")],
+ )
+ with patch(
+ "deeptutor.agents.auto.delegation.get_capability_registry"
+ ) as mock_get_reg:
+ mock_get_reg.return_value.get.return_value = fake
+ result = await delegate_to_capability(
+ cap_name="errorful",
+ config={},
+ parent_context=_ctx(),
+ parent_stream=parent_bus,
+ )
+
+ assert result.succeeded is False
+ assert result.error_message == "sub_capability_emitted_error"
+
+
+async def test_delegate_unknown_capability_returns_failure():
+ parent_bus = StreamBus()
+ with patch(
+ "deeptutor.agents.auto.delegation.get_capability_registry"
+ ) as mock_get_reg:
+ mock_get_reg.return_value.get.return_value = None
+ result = await delegate_to_capability(
+ cap_name="nonexistent",
+ config={},
+ parent_context=_ctx(),
+ parent_stream=parent_bus,
+ )
+
+ assert result.succeeded is False
+ assert result.error_message and "unknown_capability" in result.error_message
diff --git a/tests/agents/chat/test_agentic_parallel_tools.py b/tests/agents/chat/test_agentic_parallel_tools.py
index 76516fc6a..54f28bf27 100644
--- a/tests/agents/chat/test_agentic_parallel_tools.py
+++ b/tests/agents/chat/test_agentic_parallel_tools.py
@@ -253,116 +253,47 @@ async def test_execute_tool_call_streams_retrieve_progress_for_rag(
]
-def test_rag_tool_args_replace_default_alias_with_selected_kb() -> None:
+def test_compose_enabled_tools_injects_rag_when_kb_selected() -> None:
pipeline = AgenticChatPipeline.__new__(AgenticChatPipeline)
- context = UnifiedContext(
- session_id="session-1",
- user_message="summarize the default knowledge base",
- enabled_tools=["rag"],
- knowledge_bases=["西方修辞思想史"],
- language="zh",
+ pipeline.registry = SimpleNamespace(
+ get_enabled=lambda selected: [SimpleNamespace(name=n) for n in selected]
)
-
- args = pipeline._augment_tool_kwargs(
- "rag",
- {"query": "Habermas public sphere", "kb_name": "default"},
- context,
- thinking_text="Use the selected knowledge base.",
- )
-
- assert args["kb_name"] == "西方修辞思想史"
- assert args["mode"] == "hybrid"
-
-
-def test_rag_tool_args_replace_hallucinated_kb_with_selected_kb() -> None:
- pipeline = AgenticChatPipeline.__new__(AgenticChatPipeline)
context = UnifiedContext(
- session_id="session-1",
- user_message="summarize the selected knowledge base",
- enabled_tools=["rag"],
- knowledge_bases=["demo-kb"],
- language="en",
- )
-
- args = pipeline._augment_tool_kwargs(
- "rag",
- {"query": "chapter summary", "kb_name": "made-up-kb"},
- context,
- thinking_text="Use RAG.",
+ user_message="hi",
+ enabled_tools=["web_search"],
+ knowledge_bases=["kb-a"],
)
-
- assert args["kb_name"] == "demo-kb"
+ assert pipeline._compose_enabled_tools(context) == ["web_search", "rag"]
-def test_rag_tool_args_ignore_llm_kb_name_and_use_current_selection() -> None:
+def test_compose_enabled_tools_omits_rag_when_no_kb() -> None:
pipeline = AgenticChatPipeline.__new__(AgenticChatPipeline)
- context = UnifiedContext(
- session_id="session-1",
- user_message="use the current selected KB",
- enabled_tools=["rag"],
- knowledge_bases=["actual-kb", "default"],
- language="en",
- )
-
- args = pipeline._augment_tool_kwargs(
- "rag",
- {"query": "chapter summary", "kb_name": "default"},
- context,
- thinking_text="Use RAG.",
+ pipeline.registry = SimpleNamespace(
+ get_enabled=lambda selected: [SimpleNamespace(name=n) for n in selected]
)
-
- assert args["kb_name"] == "actual-kb"
-
-
-def test_rag_tool_args_clear_old_kb_when_no_kb_selected() -> None:
- pipeline = AgenticChatPipeline.__new__(AgenticChatPipeline)
+ # Legacy callers may still send "rag" in enabled_tools — it gets stripped.
context = UnifiedContext(
- session_id="session-1",
- user_message="answer without a knowledge base",
- enabled_tools=["rag"],
+ user_message="hi",
+ enabled_tools=["rag", "web_search"],
knowledge_bases=[],
- language="en",
)
+ assert pipeline._compose_enabled_tools(context) == ["web_search"]
- args = pipeline._augment_tool_kwargs(
- "rag",
- {"query": "chapter summary", "kb_name": "old-kb"},
- context,
- thinking_text="No selected KB is available.",
- )
-
- assert args["kb_name"] == ""
- assert args["mode"] == "hybrid"
-
-def test_chat_messages_tell_llm_to_call_rag_without_kb_name() -> None:
+def test_kb_note_lists_attached_knowledge_bases() -> None:
pipeline = AgenticChatPipeline.__new__(AgenticChatPipeline)
pipeline.language = "en"
context = UnifiedContext(
- session_id="session-1",
- user_message="use the current KB",
- conversation_history=[
- {"role": "user", "content": "Use knowledge base old-kb."},
- {"role": "assistant", "content": "Retrieved from old-kb."},
- ],
+ user_message="hi",
enabled_tools=["rag"],
- knowledge_bases=["new-kb"],
- language="en",
- )
-
- messages = pipeline._build_messages(
- context=context,
- system_prompt="System prompt.",
- user_content="User prompt.",
+ knowledge_bases=["kb-a", "kb-b"],
)
+ note = pipeline._kb_system_note(context)
+ assert "kb-a" in note and "kb-b" in note
+ assert "kb_name must" in note
- system_content = messages[0]["content"]
- assert "call RAG with only a non-empty query" in system_content
- assert "currently selected knowledge base" in system_content
- assert "new-kb" not in system_content
-
-def test_chat_rag_schema_exposes_only_query_to_llm() -> None:
+def test_build_llm_tool_schemas_kb_name_enum_matches_attached() -> None:
pipeline = AgenticChatPipeline.__new__(AgenticChatPipeline)
class FakeRegistry:
@@ -372,7 +303,6 @@ def test_chat_rag_schema_exposes_only_query_to_llm() -> None:
"type": "function",
"function": {
"name": "rag",
- "description": "Search the selected knowledge base.",
"parameters": {
"type": "object",
"properties": {
@@ -387,16 +317,21 @@ def test_chat_rag_schema_exposes_only_query_to_llm() -> None:
pipeline.registry = FakeRegistry()
- [schema] = pipeline._build_llm_tool_schemas(["rag"])
+ context = UnifiedContext(
+ user_message="hi",
+ enabled_tools=["rag"],
+ knowledge_bases=["kb-a", "kb-b"],
+ )
+ [schema] = pipeline._build_llm_tool_schemas(["rag"], context)
parameters = schema["function"]["parameters"]
-
- assert parameters["properties"] == {"query": {"type": "string", "minLength": 1}}
- assert parameters["required"] == ["query"]
+ assert parameters["properties"]["kb_name"]["enum"] == ["kb-a", "kb-b"]
+ assert parameters["properties"]["query"].get("minLength") == 1
+ assert parameters["required"] == ["query", "kb_name"]
assert parameters["additionalProperties"] is False
@pytest.mark.asyncio
-async def test_native_rag_call_uses_system_selected_kb_not_llm_args(
+async def test_native_rag_call_forwards_llm_chosen_kb_name(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
@@ -464,7 +399,7 @@ async def test_native_rag_call_uses_system_selected_kb_not_llm_args(
id="tool-call-rag",
function=SimpleNamespace(
name="rag",
- arguments='{"query":"chapter summary","kb_name":"old-kb"}',
+ arguments='{"query":"chapter summary","kb_name":"current-kb"}',
),
)
],
@@ -504,116 +439,16 @@ async def test_native_rag_call_uses_system_selected_kb_not_llm_args(
await consumer
rag_properties = fake_create.tools[0]["function"]["parameters"]["properties"]
- assert "kb_name" not in rag_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 == {"query": "chapter summary"}
+ 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].metadata.get("args", {}) == {"query": "chapter summary"}
assert tool_call_events[0].content
-async def test_native_rag_call_falls_back_to_user_message_when_query_is_empty(
- 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"}},
- "required": ["query"],
- },
- },
- }
- ]
-
- 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", metadata={}, success=True)
-
- registry = FakeRegistry()
- monkeypatch.setattr(
- "deeptutor.agents.chat.agentic_pipeline.get_tool_registry", lambda: registry
- )
-
- pipeline = AgenticChatPipeline(language="en")
- pipeline.registry = registry
-
- async def fake_create(**_kwargs):
- return SimpleNamespace(
- choices=[
- SimpleNamespace(
- message=SimpleNamespace(
- content="",
- tool_calls=[
- SimpleNamespace(
- id="tool-call-rag",
- function=SimpleNamespace(name="rag", arguments="{}"),
- )
- ],
- )
- )
- ]
- )
-
- 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 from the selected knowledge base.",
- enabled_tools=["rag"],
- knowledge_bases=["current-kb"],
- language="en",
- )
-
- 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
-
- expected_query = "Summarize chapter 3 from the selected knowledge base."
- assert registry.calls[0]["query"] == expected_query
- assert registry.calls[0]["kb_name"] == "current-kb"
- assert traces[0].arguments == {"query": expected_query}
-
- tool_call_events = [event for event in events if event.type == StreamEventType.TOOL_CALL]
- assert tool_call_events[0].metadata.get("args", {}) == {"query": expected_query}
-
-
@pytest.mark.asyncio
async def test_native_tool_loop_caps_parallel_tool_calls_at_eight(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.py
index b895a58d6..388b710f7 100644
--- a/tests/api/test_settings_router.py
+++ b/tests/api/test_settings_router.py
@@ -37,7 +37,10 @@ class _FakeCatalogService:
def apply(self, catalog: dict[str, Any]) -> dict[str, Any]:
current = self.save(catalog)
- return {"catalog_path": "memory://model_catalog.json", "services": list(current["services"])}
+ return {
+ "catalog_path": "memory://model_catalog.json",
+ "services": list(current["services"]),
+ }
def _build_catalog(
diff --git a/tests/capabilities/test_auto_capability.py b/tests/capabilities/test_auto_capability.py
new file mode 100644
index 000000000..c7890c416
--- /dev/null
+++ b/tests/capabilities/test_auto_capability.py
@@ -0,0 +1,884 @@
+"""Integration tests for the ``auto`` capability.
+
+End-to-end tests of ``AutoPipeline`` with the OpenAI client mocked. They cover:
+
+PR 1
+* ``auto`` registered in capability registry, ``AutoRequestConfig`` validates
+* Happy path: router picks one capability, pipeline delegates, events stamped
+* Plain-text router response → no delegation, text becomes the final answer
+* ``enabled_capabilities`` filter restricts what the router sees
+* ``_should_capture_assistant_content`` filters sub-cap CONTENT correctly
+
+PR 2
+* Router LLM API error retried up to ``max_retries_per_step`` then terminates
+* Sub-capability raise retried then succeeds
+* Sub-capability fails all retries → loop continues with error observation
+* Same-capability quota enforced
+* Iteration cap triggers synthesizer fallback
+* Atomic tool dispatch (rag with kb_name auto-injection)
+* Cancellation propagates from parent into in-flight sub-cap
+* ``answer_now`` payload triggers fast-path synthesis
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from deeptutor.capabilities.auto import AutoCapability
+from deeptutor.capabilities.request_contracts import (
+ AutoRequestConfig,
+ validate_auto_request_config,
+)
+from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest
+from deeptutor.core.context import UnifiedContext
+from deeptutor.core.stream import StreamEvent, StreamEventType
+from deeptutor.core.stream_bus import StreamBus
+from deeptutor.runtime.registry.capability_registry import get_capability_registry
+from deeptutor.services.session.turn_runtime import _should_capture_assistant_content
+
+# =========================================================================== #
+# Streaming-response helpers #
+# =========================================================================== #
+
+
+def _chunk(
+ *,
+ content: str | None = None,
+ tool_calls: list[dict[str, Any]] | None = None,
+) -> SimpleNamespace:
+ """Build a single ChatCompletionChunk-shaped object."""
+ delta_fields: dict[str, Any] = {"content": content}
+ if tool_calls is not None:
+ delta_fields["tool_calls"] = [
+ SimpleNamespace(
+ index=tc.get("index", i),
+ id=tc.get("id"),
+ function=SimpleNamespace(
+ name=tc.get("name"),
+ arguments=tc.get("arguments"),
+ ),
+ )
+ for i, tc in enumerate(tool_calls)
+ ]
+ else:
+ delta_fields["tool_calls"] = None
+ return SimpleNamespace(
+ choices=[SimpleNamespace(delta=SimpleNamespace(**delta_fields))]
+ )
+
+
+async def _async_iter(chunks: list[SimpleNamespace]):
+ for chunk in chunks:
+ yield chunk
+
+
+def _stream_for_text(text: str) -> list[SimpleNamespace]:
+ """Stream that emits a single text response, no tool calls."""
+ return [_chunk(content=text)]
+
+
+def _stream_for_tool_call(cap_name: str, config: dict[str, Any]) -> list[SimpleNamespace]:
+ """Stream that yields one complete tool_call (delegate_to_<cap>)."""
+ return [
+ _chunk(
+ tool_calls=[
+ {
+ "index": 0,
+ "id": "call-1",
+ "name": f"delegate_to_{cap_name}",
+ "arguments": json.dumps({"config": config, "rationale": "test"}),
+ }
+ ]
+ )
+ ]
+
+
+def _stream_for_atomic_tool(tool_name: str, args: dict[str, Any]) -> list[SimpleNamespace]:
+ return [
+ _chunk(
+ tool_calls=[
+ {
+ "index": 0,
+ "id": "call-atomic",
+ "name": tool_name,
+ "arguments": json.dumps(args),
+ }
+ ]
+ )
+ ]
+
+
+class _ScriptedClient:
+ """Mock OpenAI client whose ``chat.completions.create`` returns a scripted
+
+ sequence of streaming responses. Each call consumes the next entry; if the
+ entry is an Exception subclass instance, it is raised instead of returned.
+ """
+
+ def __init__(self, scripted: list[Any]) -> None:
+ self._script: list[Any] = list(scripted)
+ self.call_count = 0
+ self.last_kwargs: dict[str, Any] | None = None
+
+ class _Completions:
+ def __init__(self, parent: _ScriptedClient) -> None:
+ self.parent = parent
+
+ async def create(self, **kwargs): # noqa: D401
+ self.parent.last_kwargs = kwargs
+ self.parent.call_count += 1
+ if not self.parent._script:
+ raise RuntimeError("Scripted client exhausted")
+ item = self.parent._script.pop(0)
+ if isinstance(item, BaseException):
+ raise item
+ # item is a list of chunks for streaming.
+ return _async_iter(item)
+
+ class _Chat:
+ def __init__(self, parent: _ScriptedClient) -> None:
+ self.completions = _Completions(parent)
+
+ self.chat = _Chat(self)
+
+
+def _fake_llm_config() -> MagicMock:
+ cfg = MagicMock()
+ cfg.binding = "openai"
+ cfg.model = "gpt-4o-mini"
+ cfg.api_key = "sk-test"
+ cfg.base_url = None
+ cfg.api_version = None
+ cfg.extra_headers = None
+ return cfg
+
+
+class _StubSubCapability(BaseCapability):
+ """Configurable fake sub-capability for integration tests."""
+
+ def __init__(
+ self,
+ name: str,
+ response_text: str = "sub-output",
+ raise_on_attempts: tuple[int, ...] = (),
+ ) -> None:
+ self.manifest = CapabilityManifest(
+ name=name,
+ description=f"stub for {name}",
+ stages=["go"],
+ request_schema={"type": "object", "properties": {}},
+ )
+ self.response_text = response_text
+ self.run_count = 0
+ self._raise_on = set(raise_on_attempts)
+ self.received_contexts: list[UnifiedContext] = []
+
+ async def run(self, context: UnifiedContext, stream: StreamBus) -> None:
+ self.run_count += 1
+ self.received_contexts.append(context)
+ if self.run_count in self._raise_on:
+ raise RuntimeError(f"{self.name} fail attempt {self.run_count}")
+ await stream.thinking("sub-thinking", source=self.name, stage="go")
+ await stream.content(f"{self.response_text} (run {self.run_count})", source=self.name, stage="go")
+ await stream.result(
+ {"response": f"{self.response_text} (run {self.run_count})"},
+ source=self.name,
+ )
+
+
+def fake_registry():
+ """Fresh CapabilityRegistry preloaded with builtins; tests register stubs."""
+ from deeptutor.runtime.registry.capability_registry import CapabilityRegistry
+
+ reg = CapabilityRegistry()
+ reg.load_builtins()
+ return reg
+
+
+def mock_llm():
+ """Patch get_llm_config + LLM client at the AutoPipeline level."""
+ with patch(
+ "deeptutor.agents.auto.auto_pipeline.get_llm_config",
+ return_value=_fake_llm_config(),
+ ):
+ yield
+
+
+def _drained_events(bus: StreamBus) -> list[StreamEvent]:
+ return list(bus._history)
+
+
+def _install_scripted_client(client: _ScriptedClient):
+ return patch.object(
+ __import__("deeptutor.agents.auto.auto_pipeline", fromlist=["AutoPipeline"]).AutoPipeline,
+ "_build_openai_client",
+ return_value=client,
+ )
+
+
+# =========================================================================== #
+# Smoke / config tests #
+# =========================================================================== #
+
+
+def test_auto_capability_is_registered():
+ reg = get_capability_registry()
+ assert "auto" in reg.list_capabilities()
+ cap = reg.get("auto")
+ assert isinstance(cap, AutoCapability)
+ assert cap.manifest.stages == ["analyzing", "delegating", "synthesizing"]
+
+
+def test_auto_request_config_defaults():
+ cfg = validate_auto_request_config(None)
+ assert isinstance(cfg, AutoRequestConfig)
+ assert cfg.max_iterations == 4
+ assert cfg.max_retries_per_step == 3
+ assert cfg.max_same_capability_calls == 2
+ assert cfg.enabled_capabilities == []
+
+
+def test_auto_request_config_rejects_unknown_field():
+ with pytest.raises(ValueError):
+ validate_auto_request_config({"not_a_field": 1})
+
+
+def test_auto_request_config_enforces_bounds():
+ with pytest.raises(ValueError):
+ validate_auto_request_config({"max_iterations": 99})
+
+
+def test_history_capture_filter_drops_subcap_content():
+ """Sub-cap CONTENT with call_id is filtered; auto's final synth is kept."""
+ sub_event = StreamEvent(
+ type=StreamEventType.CONTENT,
+ content="from sub-capability",
+ metadata={"call_id": "auto-delegation-abc"},
+ )
+ auto_final = StreamEvent(
+ type=StreamEventType.CONTENT,
+ content="final synthesis",
+ metadata={"call_kind": "llm_final_response"},
+ )
+ auto_plain = StreamEvent(
+ type=StreamEventType.CONTENT,
+ content="plain content with no metadata",
+ metadata={},
+ )
+
+ assert _should_capture_assistant_content(sub_event) is False
+ assert _should_capture_assistant_content(auto_final) is True
+ assert _should_capture_assistant_content(auto_plain) is True
+
+
+# =========================================================================== #
+# Full-pipeline integration tests #
+# =========================================================================== #
+
+
+async def test_single_delegation_happy_path(fake_registry, mock_llm):
+ """Router picks deep_question; pipeline delegates; events stamped; final synthesis emitted."""
+ stub = _StubSubCapability("deep_question", response_text="generated 5 quizzes")
+ fake_registry.register(stub)
+ auto_cap = fake_registry.get("auto")
+
+ context = UnifiedContext(
+ session_id="s1",
+ user_message="make 5 linear algebra MCQs",
+ config_overrides={},
+ language="en",
+ )
+ bus = StreamBus()
+
+ # Script: analyzer text, router picks deep_question, synth not needed
+ # because the router never gave a text response — but we DID delegate and
+ # the router will be re-called for the next iteration. To exit cleanly we
+ # script the second router call to give a plain-text answer.
+ client = _ScriptedClient(
+ [
+ _stream_for_text("Acknowledging your quiz request."), # analyzer
+ _stream_for_tool_call(
+ "deep_question",
+ {"num_questions": 5, "topic": "linear algebra"},
+ ),
+ _stream_for_text("Generated your quiz."), # iteration-2 router final text
+ ]
+ )
+
+ with (
+ _install_scripted_client(client),
+ patch(
+ "deeptutor.agents.auto.auto_pipeline.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ patch(
+ "deeptutor.agents.auto.delegation.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ ):
+ await auto_cap.run(context, bus)
+
+ events = _drained_events(bus)
+
+ # Three LLM calls: analyzer, router-iter1 (tool_call), router-iter2 (text).
+ assert client.call_count == 3
+
+ # The sub-capability ran and saw is_sub_invocation=True.
+ assert stub.run_count == 1
+ assert stub.received_contexts[0].metadata.get("is_sub_invocation") is True
+ assert stub.received_contexts[0].active_capability == "deep_question"
+ assert stub.received_contexts[0].config_overrides.get("num_questions") == 5
+ assert stub.received_contexts[0].config_overrides.get("topic") == "linear algebra"
+
+ # Sub-events tagged with delegation metadata.
+ sub_events = [ev for ev in events if ev.metadata.get("delegated_capability") == "deep_question"]
+ assert len(sub_events) >= 2
+ for ev in sub_events:
+ assert ev.metadata.get("delegated_from") == "auto"
+ assert ev.metadata.get("parent_call_id", "").startswith("auto-delegation-")
+
+ # Sub-cap CONTENT carries call_id (prevents history pollution).
+ sub_content = [ev for ev in sub_events if ev.type == StreamEventType.CONTENT]
+ assert all(ev.metadata.get("call_id") for ev in sub_content)
+
+ # Auto's final synthesis CONTENT has llm_final_response marker.
+ final_events = [
+ ev
+ for ev in events
+ if ev.type == StreamEventType.CONTENT
+ and ev.metadata.get("call_kind") == "llm_final_response"
+ ]
+ assert len(final_events) == 1
+ assert final_events[0].content == "Generated your quiz."
+
+ result_events = [ev for ev in events if ev.type == StreamEventType.RESULT and ev.source == "auto"]
+ summary = result_events[0].metadata.get("auto_summary")
+ assert summary["delegations"][0]["capability"] == "deep_question"
+ assert summary["delegations"][0]["succeeded"] is True
+
+
+async def test_router_text_response_no_delegation(fake_registry, mock_llm):
+ auto_cap = fake_registry.get("auto")
+ context = UnifiedContext(session_id="s2", user_message="hi", language="en")
+ bus = StreamBus()
+ client = _ScriptedClient(
+ [
+ _stream_for_text("Acknowledging."),
+ _stream_for_text("Hello! How can I help?"),
+ ]
+ )
+ with (
+ _install_scripted_client(client),
+ patch(
+ "deeptutor.agents.auto.auto_pipeline.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ ):
+ await auto_cap.run(context, bus)
+
+ events = _drained_events(bus)
+ final_events = [
+ ev
+ for ev in events
+ if ev.type == StreamEventType.CONTENT
+ and ev.metadata.get("call_kind") == "llm_final_response"
+ ]
+ assert len(final_events) == 1
+ assert final_events[0].content == "Hello! How can I help?"
+
+ # No sub-capability events.
+ sub_events = [ev for ev in events if ev.metadata.get("delegated_from") == "auto"]
+ assert sub_events == []
+
+ result_events = [ev for ev in events if ev.type == StreamEventType.RESULT and ev.source == "auto"]
+ assert result_events[0].metadata["auto_summary"]["final_path"] == "text_response"
+
+
+async def test_enabled_capabilities_filter_visible_to_router(fake_registry, mock_llm):
+ auto_cap = fake_registry.get("auto")
+ context = UnifiedContext(
+ session_id="s3",
+ user_message="anything",
+ config_overrides={"enabled_capabilities": ["visualize"]},
+ language="en",
+ )
+ bus = StreamBus()
+ client = _ScriptedClient(
+ [
+ _stream_for_text("Analyzer ack."),
+ _stream_for_text("Final text."),
+ ]
+ )
+ with (
+ _install_scripted_client(client),
+ patch(
+ "deeptutor.agents.auto.auto_pipeline.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ ):
+ await auto_cap.run(context, bus)
+
+ # The second LLM call is the router; we want to inspect the tools list.
+ # The scripted client recorded last_kwargs of the LAST call (synthesizer is
+ # not invoked because router gave text). The last call IS the router.
+ tools = client.last_kwargs["tools"]
+ cap_tools = [t["function"]["name"] for t in tools if t["function"]["name"].startswith("delegate_to_")]
+ assert cap_tools == ["delegate_to_visualize"]
+
+
+# =========================================================================== #
+# PR 2 — retry, quotas, iteration cap, atomic tools #
+# =========================================================================== #
+
+
+async def test_router_api_error_retry_then_success(fake_registry, mock_llm):
+ """Router LLM transient error → retried (state.router_llm_retries++) → eventual success."""
+ from openai import APIError
+
+ auto_cap = fake_registry.get("auto")
+ context = UnifiedContext(session_id="s4", user_message="hello", language="en")
+ bus = StreamBus()
+
+ transient = APIError(message="transient", request=MagicMock(), body=None)
+ client = _ScriptedClient(
+ [
+ _stream_for_text("ack"), # analyzer
+ transient, # router iter 1 fails
+ _stream_for_text("Hi!"), # router iter 1 retry succeeds (text)
+ ]
+ )
+ with (
+ _install_scripted_client(client),
+ patch(
+ "deeptutor.agents.auto.auto_pipeline.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ ):
+ await auto_cap.run(context, bus)
+
+ events = _drained_events(bus)
+ result = [ev for ev in events if ev.type == StreamEventType.RESULT and ev.source == "auto"][0]
+ summary = result.metadata["auto_summary"]
+ assert summary["router_retries"] == 1
+ assert summary["final_path"] == "text_response"
+
+
+async def test_router_api_error_max_retries_terminates(fake_registry, mock_llm):
+ """3 consecutive transient errors → terminal failure, no fallback to chat."""
+ from openai import APIError
+
+ auto_cap = fake_registry.get("auto")
+ context = UnifiedContext(
+ session_id="s5",
+ user_message="hello",
+ config_overrides={"max_retries_per_step": 3},
+ language="en",
+ )
+ bus = StreamBus()
+
+ def _transient_error() -> APIError:
+ return APIError(message="boom", request=MagicMock(), body=None)
+
+ client = _ScriptedClient(
+ [
+ _stream_for_text("ack"), # analyzer
+ _transient_error(), # router fail 1
+ _transient_error(), # router fail 2
+ _transient_error(), # router fail 3 -> terminal
+ ]
+ )
+ with (
+ _install_scripted_client(client),
+ patch(
+ "deeptutor.agents.auto.auto_pipeline.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ ):
+ await auto_cap.run(context, bus)
+
+ events = _drained_events(bus)
+ error_events = [ev for ev in events if ev.type == StreamEventType.ERROR]
+ terminal = [ev for ev in error_events if ev.metadata.get("terminal") is True]
+ assert len(terminal) == 1
+ assert terminal[0].metadata.get("failure_reason") == "router_llm_exhausted"
+
+ result = [ev for ev in events if ev.type == StreamEventType.RESULT and ev.source == "auto"][0]
+ assert result.metadata["auto_summary"]["final_path"] == "terminal_error"
+
+
+async def test_subcap_raises_then_succeeds_on_retry(fake_registry, mock_llm):
+ """Sub-cap fails first attempt, succeeds second."""
+ stub = _StubSubCapability("deep_question", raise_on_attempts=(1,))
+ fake_registry.register(stub)
+ auto_cap = fake_registry.get("auto")
+
+ context = UnifiedContext(
+ session_id="s6",
+ user_message="quiz me",
+ config_overrides={"max_retries_per_step": 3},
+ language="en",
+ )
+ bus = StreamBus()
+ client = _ScriptedClient(
+ [
+ _stream_for_text("ack"), # analyzer
+ _stream_for_tool_call("deep_question", {"num_questions": 1}),
+ _stream_for_text("Done."), # iter 2 final text
+ ]
+ )
+ with (
+ _install_scripted_client(client),
+ patch(
+ "deeptutor.agents.auto.auto_pipeline.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ patch(
+ "deeptutor.agents.auto.delegation.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ ):
+ await auto_cap.run(context, bus)
+
+ # Sub-cap ran twice (1st raised, 2nd succeeded).
+ assert stub.run_count == 2
+
+ events = _drained_events(bus)
+ # A retry-marker error should be present (attempt 1 fail visible).
+ retry_events = [
+ ev
+ for ev in events
+ if ev.type == StreamEventType.ERROR
+ and ev.metadata.get("trace_kind") == "delegation_retry"
+ ]
+ assert len(retry_events) >= 1
+
+
+async def test_subcap_fails_all_retries_loop_continues(fake_registry, mock_llm):
+ """3 sub-cap failures → loop continues, router pivots to text response."""
+ stub = _StubSubCapability("deep_question", raise_on_attempts=(1, 2, 3))
+ fake_registry.register(stub)
+ auto_cap = fake_registry.get("auto")
+
+ context = UnifiedContext(
+ session_id="s7",
+ user_message="quiz me",
+ config_overrides={"max_retries_per_step": 3},
+ language="en",
+ )
+ bus = StreamBus()
+ client = _ScriptedClient(
+ [
+ _stream_for_text("ack"), # analyzer
+ _stream_for_tool_call("deep_question", {}), # router iter 1 — fails all 3
+ _stream_for_text("Sorry, that capability is unavailable."), # iter 2 final
+ ]
+ )
+ with (
+ _install_scripted_client(client),
+ patch(
+ "deeptutor.agents.auto.auto_pipeline.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ patch(
+ "deeptutor.agents.auto.delegation.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ ):
+ await auto_cap.run(context, bus)
+
+ assert stub.run_count == 3
+
+ events = _drained_events(bus)
+ result = [ev for ev in events if ev.type == StreamEventType.RESULT and ev.source == "auto"][0]
+ summary = result.metadata["auto_summary"]
+ # Loop did NOT terminate; final path is text_response from iter 2.
+ assert summary["final_path"] == "text_response"
+ assert summary["delegations"][0]["succeeded"] is False
+ assert summary["delegations"][0]["attempts"] == 3
+
+
+async def test_same_capability_limit_enforced(fake_registry, mock_llm):
+ """Same cap called twice (allowed), third call rejected with quota message."""
+ stub = _StubSubCapability("visualize")
+ fake_registry.register(stub)
+ auto_cap = fake_registry.get("auto")
+
+ context = UnifiedContext(
+ session_id="s8",
+ user_message="visualize",
+ config_overrides={"max_same_capability_calls": 2, "max_iterations": 5},
+ language="en",
+ )
+ bus = StreamBus()
+ client = _ScriptedClient(
+ [
+ _stream_for_text("ack"), # analyzer
+ _stream_for_tool_call("visualize", {"render_mode": "svg"}), # iter 1 ok
+ _stream_for_tool_call("visualize", {"render_mode": "svg"}), # iter 2 ok
+ _stream_for_tool_call("visualize", {"render_mode": "svg"}), # iter 3 rejected
+ _stream_for_text("Final."), # iter 4 text
+ ]
+ )
+ with (
+ _install_scripted_client(client),
+ patch(
+ "deeptutor.agents.auto.auto_pipeline.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ patch(
+ "deeptutor.agents.auto.delegation.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ ):
+ await auto_cap.run(context, bus)
+
+ # Only 2 actual runs (3rd call was rejected before delegation).
+ assert stub.run_count == 2
+
+ events = _drained_events(bus)
+ quota_errors = [
+ ev
+ for ev in events
+ if ev.type == StreamEventType.ERROR
+ and ev.metadata.get("trace_kind") == "same_cap_exhausted"
+ ]
+ assert len(quota_errors) == 1
+
+
+async def test_iteration_cap_falls_to_synthesizer(fake_registry, mock_llm):
+ """Loop hits max_iterations without natural text → synthesizer composes final."""
+ stub = _StubSubCapability("visualize")
+ fake_registry.register(stub)
+ auto_cap = fake_registry.get("auto")
+
+ context = UnifiedContext(
+ session_id="s9",
+ user_message="visualize",
+ config_overrides={"max_iterations": 2, "max_same_capability_calls": 4},
+ language="en",
+ )
+ bus = StreamBus()
+ client = _ScriptedClient(
+ [
+ _stream_for_text("ack"), # analyzer
+ _stream_for_tool_call("visualize", {}), # iter 1
+ _stream_for_tool_call("visualize", {}), # iter 2 — hits cap
+ _stream_for_text("Wrapping up."), # synthesizer
+ ]
+ )
+ with (
+ _install_scripted_client(client),
+ patch(
+ "deeptutor.agents.auto.auto_pipeline.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ patch(
+ "deeptutor.agents.auto.delegation.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ ):
+ await auto_cap.run(context, bus)
+
+ events = _drained_events(bus)
+ final = [
+ ev
+ for ev in events
+ if ev.type == StreamEventType.CONTENT
+ and ev.metadata.get("call_kind") == "llm_final_response"
+ ]
+ assert len(final) == 1
+ assert final[0].content == "Wrapping up."
+
+ result = [ev for ev in events if ev.type == StreamEventType.RESULT and ev.source == "auto"][0]
+ assert result.metadata["auto_summary"]["final_path"] == "synthesis"
+ assert result.metadata["auto_summary"]["iterations"] == 2
+
+
+async def test_atomic_tool_dispatch_with_rag_kb_injection(fake_registry, mock_llm):
+ """Router calls atomic rag → kb_name is injected from context."""
+ auto_cap = fake_registry.get("auto")
+ context = UnifiedContext(
+ session_id="s10",
+ user_message="what does the doc say about gradients?",
+ knowledge_bases=["my-kb"],
+ language="en",
+ )
+ bus = StreamBus()
+
+ captured_kwargs: dict[str, Any] = {}
+
+ async def _fake_execute(name: str, **kwargs: Any):
+ captured_kwargs.update(kwargs)
+ return SimpleNamespace(
+ content="rag-snippet",
+ success=True,
+ sources=[],
+ metadata={},
+ )
+
+ client = _ScriptedClient(
+ [
+ _stream_for_text("ack"),
+ _stream_for_atomic_tool("rag", {"query": "gradients"}),
+ _stream_for_text("Based on the docs, gradients ..."),
+ ]
+ )
+
+ mock_tool_registry = SimpleNamespace(
+ execute=_fake_execute,
+ list_tools=lambda: ["rag"],
+ build_openai_schemas=lambda names=None: [
+ {
+ "type": "function",
+ "function": {
+ "name": "rag",
+ "description": "rag",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string"},
+ "kb_name": {"type": "string"},
+ },
+ "required": ["query", "kb_name"],
+ },
+ },
+ }
+ ],
+ )
+
+ with (
+ _install_scripted_client(client),
+ patch(
+ "deeptutor.agents.auto.auto_pipeline.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ patch(
+ "deeptutor.agents.auto.auto_pipeline.get_tool_registry",
+ return_value=mock_tool_registry,
+ ),
+ ):
+ await auto_cap.run(context, bus)
+
+ assert captured_kwargs.get("kb_name") == "my-kb"
+ assert captured_kwargs.get("query") == "gradients"
+
+
+async def test_answer_now_fast_path(fake_registry, mock_llm):
+ """answer_now_context in config triggers fast-path with no LLM call."""
+ auto_cap = fake_registry.get("auto")
+ context = UnifiedContext(
+ session_id="s11",
+ user_message="anything",
+ config_overrides={
+ "answer_now_context": {
+ "original_user_message": "what is X",
+ "partial_response": "some partial work",
+ "events": [],
+ }
+ },
+ language="en",
+ )
+ bus = StreamBus()
+ # Empty script — no LLM call should happen.
+ client = _ScriptedClient([])
+ with (
+ _install_scripted_client(client),
+ patch(
+ "deeptutor.agents.auto.auto_pipeline.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ ):
+ await auto_cap.run(context, bus)
+
+ assert client.call_count == 0
+
+ events = _drained_events(bus)
+ final = [
+ ev
+ for ev in events
+ if ev.type == StreamEventType.CONTENT
+ and ev.metadata.get("call_kind") == "llm_final_response"
+ ]
+ assert len(final) == 1
+ assert final[0].metadata.get("answer_now") is True
+
+ result = [ev for ev in events if ev.type == StreamEventType.RESULT and ev.source == "auto"][0]
+ assert result.metadata["auto_summary"]["final_path"] == "answer_now"
+
+
+async def test_cancel_propagates_into_subcap(fake_registry, mock_llm):
+ """asyncio.CancelledError from parent propagates into sub-capability."""
+
+ class _SlowCapability(BaseCapability):
+ def __init__(self) -> None:
+ self.manifest = CapabilityManifest(
+ name="slowcap",
+ description="slow",
+ stages=["wait"],
+ request_schema={"type": "object", "properties": {}},
+ )
+ self.cancelled_during_run = False
+
+ async def run(self, context: UnifiedContext, stream: StreamBus) -> None:
+ try:
+ await asyncio.sleep(10)
+ except asyncio.CancelledError:
+ self.cancelled_during_run = True
+ raise
+
+ slow = _SlowCapability()
+ fake_registry.register(slow)
+ auto_cap = fake_registry.get("auto")
+
+ context = UnifiedContext(
+ session_id="s12",
+ user_message="x",
+ config_overrides={"enabled_capabilities": ["slowcap"]},
+ language="en",
+ )
+ bus = StreamBus()
+ client = _ScriptedClient(
+ [
+ _stream_for_text("ack"),
+ _stream_for_tool_call("slowcap", {}),
+ ]
+ )
+
+ with (
+ _install_scripted_client(client),
+ patch(
+ "deeptutor.agents.auto.auto_pipeline.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ patch(
+ "deeptutor.agents.auto.delegation.get_capability_registry",
+ return_value=fake_registry,
+ ),
+ ):
+ task = asyncio.create_task(auto_cap.run(context, bus))
+ await asyncio.sleep(0.05) # let it start
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert slow.cancelled_during_run is True
diff --git a/tests/capabilities/test_rag_consistency.py b/tests/capabilities/test_rag_consistency.py
index 96a12e781..4c9fb4251 100644
--- a/tests/capabilities/test_rag_consistency.py
+++ b/tests/capabilities/test_rag_consistency.py
@@ -1,23 +1,21 @@
-"""
-Tests for RAG/KB consistency normalization at the capability layer.
+"""Tests for RAG/KB consistency at the capability layer.
+After the refactor, RAG is no longer a user-selectable tool — its availability
+is derived from whether any knowledge bases are attached for the turn.
These tests pin the contract that:
-* ``deep_solve`` strips ``rag`` from the effective tool set when no
- knowledge base is attached, and emits a warning so the UI can surface
- the mismatch.
-* ``deep_research`` strips ``kb`` from the effective sources list when
- no knowledge base is attached, and surfaces a clear error if all
- sources end up empty.
-
-Both behaviours guarantee that no downstream agent or pipeline ever
-attempts a RAG call against a missing/placeholder knowledge base.
+* ``deep_solve`` *adds* ``rag`` to the effective tool set iff a knowledge
+ base is attached, and disables planner-side retrieval otherwise.
+* ``deep_research`` still strips ``kb`` from the user-selected sources list
+ when no knowledge base is attached (its sources picker is a separate,
+ research-specific concept), and surfaces a clear error if every source is
+ unusable.
"""
from __future__ import annotations
from typing import Any
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import MagicMock, patch
import pytest
@@ -41,12 +39,12 @@ def _fake_llm_config() -> MagicMock:
# ---------------------------------------------------------------------------
-# deep_solve: rag without KB → tool stripped, warning emitted
+# deep_solve: rag presence is keyed on attached KB
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
-async def test_deep_solve_strips_rag_when_no_knowledge_base() -> None:
+async def test_deep_solve_omits_rag_when_no_knowledge_base() -> None:
from deeptutor.capabilities.deep_solve import DeepSolveCapability
captured_kwargs: dict[str, Any] = {}
@@ -69,8 +67,9 @@ async def test_deep_solve_strips_rag_when_no_knowledge_base() -> None:
context = UnifiedContext(
user_message="solve x^2 = 4",
active_capability="deep_solve",
+ # A legacy caller passing "rag" should be ignored — KBs are the signal.
enabled_tools=["rag", "web_search"],
- knowledge_bases=[], # explicitly empty
+ knowledge_bases=[],
language="en",
)
@@ -84,26 +83,16 @@ async def test_deep_solve_strips_rag_when_no_knowledge_base() -> None:
return_value=_fake_llm_config(),
),
):
- events = await _drain(bus, capability.run(context, bus))
+ await _drain(bus, capability.run(context, bus))
- # rag must NOT be in the enabled_tools we forwarded to MainSolver
assert "rag" not in captured_kwargs["enabled_tools"]
assert "web_search" in captured_kwargs["enabled_tools"]
assert captured_kwargs["kb_name"] is None
assert captured_kwargs["disable_planner_retrieve"] is True
- # And a warning progress event should have been emitted
- warnings = [
- e
- for e in events
- if e.type == StreamEventType.PROGRESS
- and (e.metadata or {}).get("reason") == "rag_without_kb"
- ]
- assert warnings, "expected a rag_without_kb warning event"
-
@pytest.mark.asyncio
-async def test_deep_solve_keeps_rag_when_knowledge_base_attached() -> None:
+async def test_deep_solve_adds_rag_when_knowledge_base_attached() -> None:
from deeptutor.capabilities.deep_solve import DeepSolveCapability
captured_kwargs: dict[str, Any] = {}
@@ -126,7 +115,7 @@ async def test_deep_solve_keeps_rag_when_knowledge_base_attached() -> None:
context = UnifiedContext(
user_message="solve x^2 = 4",
active_capability="deep_solve",
- enabled_tools=["rag", "web_search"],
+ enabled_tools=["web_search"],
knowledge_bases=["my-kb"],
language="en",
)
@@ -168,12 +157,12 @@ async def test_deep_research_drops_kb_source_when_no_knowledge_base() -> None:
context = UnifiedContext(
user_message="A topic to research",
active_capability="deep_research",
- enabled_tools=["rag", "web_search"],
+ enabled_tools=["web_search"],
knowledge_bases=[],
config_overrides={
"mode": "report",
"depth": "standard",
- "sources": ["kb", "web"], # kb requested but no KB attached
+ "sources": ["kb", "web"],
},
language="en",
)
@@ -195,14 +184,11 @@ async def test_deep_research_drops_kb_source_when_no_knowledge_base() -> None:
):
events = await _drain(bus, capability.run(context, bus))
- # The runtime config must NOT enable RAG, but must still allow web.
researching = captured_config.get("researching", {})
assert researching.get("enable_rag") is False
assert researching.get("enable_web_search") is True
- # rag intent stripped from request_config sources
assert captured_config["intent"]["sources"] == ["web"]
- # A warning progress event must be present
warnings = [
e
for e in events
@@ -221,12 +207,12 @@ async def test_deep_research_errors_when_only_kb_source_and_no_knowledge_base()
context = UnifiedContext(
user_message="topic",
active_capability="deep_research",
- enabled_tools=["rag"],
+ enabled_tools=[],
knowledge_bases=[],
config_overrides={
"mode": "report",
"depth": "standard",
- "sources": ["kb"], # ONLY kb, and no KB attached
+ "sources": ["kb"],
},
language="en",
)
diff --git a/tests/core/test_capabilities_runtime.py b/tests/core/test_capabilities_runtime.py
index bb28f5382..6e6709505 100644
--- a/tests/core/test_capabilities_runtime.py
+++ b/tests/core/test_capabilities_runtime.py
@@ -119,9 +119,12 @@ async def test_chat_capability_streams_content_and_geogebra_context(
@pytest.mark.parametrize(
("enabled_tools", "knowledge_bases", "expected_tools", "expected_kb", "expected_disable"),
[
- (["rag", "code_execution"], ["algebra"], ["rag", "code_execution"], "algebra", False),
- (None, ["algebra"], list(DeepSolveCapability.manifest.tools_used), "algebra", False),
- ([], ["algebra"], [], None, True),
+ # Non-rag tools + attached KB → rag auto-appended.
+ (["code_execution"], ["algebra"], ["code_execution", "rag"], "algebra", False),
+ # Default tool set (manifest) is normalised, then rag is appended last.
+ (None, ["algebra"], ["web_search", "code_execution", "reason", "rag"], "algebra", False),
+ # Legacy callers that still pass "rag" without attaching a KB get rag stripped.
+ (["rag", "web_search"], [], ["web_search"], None, True),
],
)
async def test_deep_solve_capability_bridges_solver_output(
diff --git a/tests/knowledge/test_manager_list.py b/tests/knowledge/test_manager_list.py
new file mode 100644
index 000000000..c1f9dfeed
--- /dev/null
+++ b/tests/knowledge/test_manager_list.py
@@ -0,0 +1,73 @@
+"""Tests for KnowledgeBaseManager.list_knowledge_bases() orphan pruning.
+
+When a KB entry remains in ``kb_config.json`` but its on-disk directory has
+been removed (failed init, manual ``rm -rf``, etc.), the entry must be
+pruned from the list — and from the persisted config — so the UI does not
+keep surfacing zombie KBs the user cannot act on.
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+from datetime import datetime
+from pathlib import Path
+
+from deeptutor.knowledge.manager import KnowledgeBaseManager
+
+
+def _seed_kb(manager: KnowledgeBaseManager, name: str) -> Path:
+ kb_dir = manager.base_dir / name
+ (kb_dir / "raw").mkdir(parents=True, exist_ok=True)
+ (kb_dir / "version-1").mkdir(parents=True, exist_ok=True)
+ (kb_dir / "version-1" / "docstore.json").write_text("{}", encoding="utf-8")
+ manager.config.setdefault("knowledge_bases", {})[name] = {
+ "path": name,
+ "description": "",
+ "status": "ready",
+ }
+ manager._save_config()
+ return kb_dir
+
+
+def _read_config(path: Path) -> dict:
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def test_list_prunes_orphan_config_entries(tmp_path: Path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))
+ _seed_kb(manager, "alive")
+ _seed_kb(manager, "ghost")
+ shutil.rmtree(manager.base_dir / "ghost")
+
+ listed = manager.list_knowledge_bases()
+
+ assert listed == ["alive"]
+ persisted = _read_config(manager.config_file).get("knowledge_bases", {})
+ assert "ghost" not in persisted
+ assert "alive" in persisted
+
+
+def test_list_keeps_entries_when_directory_present(tmp_path: Path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))
+ _seed_kb(manager, "kept")
+
+ assert manager.list_knowledge_bases() == ["kept"]
+ assert "kept" in _read_config(manager.config_file).get("knowledge_bases", {})
+
+
+def test_list_keeps_recent_entry_with_missing_dir(tmp_path: Path) -> None:
+ """During KB creation the config entry is written before the directory
+ exists. A concurrent ``list`` must not delete that in-flight entry —
+ a recent ``updated_at`` keeps it in the list.
+ """
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))
+ manager.config.setdefault("knowledge_bases", {})["in-flight"] = {
+ "path": "in-flight",
+ "status": "initializing",
+ "updated_at": datetime.now().isoformat(),
+ }
+ manager._save_config()
+
+ assert manager.list_knowledge_bases() == ["in-flight"]
+ assert "in-flight" in _read_config(manager.config_file).get("knowledge_bases", {})
diff --git a/tests/multi_user/test_rag_tool_no_kb_fallback.py b/tests/multi_user/test_rag_tool_no_kb_fallback.py
index 530c4739b..76c6f7173 100644
--- a/tests/multi_user/test_rag_tool_no_kb_fallback.py
+++ b/tests/multi_user/test_rag_tool_no_kb_fallback.py
@@ -1,48 +1,37 @@
-"""M4 regression — non-admin rag_search without kb_name must NOT hit admin KBs."""
+"""rag_search no longer accepts an implicit/default KB.
+
+The chat composer always sends an explicit ``kb_name`` selected from the
+user's attached knowledge bases, so the tool fails fast when called without
+one. Multi-user routing is verified separately in
+``test_grants_and_settings.py``.
+"""
from __future__ import annotations
import asyncio
-
-import pytest
+import importlib
-def test_rag_search_no_kb_non_admin_raises(mu_isolated_root, as_user):
- from deeptutor.tools import rag_tool
+def _rag_search():
+ # Bypass parent-attribute pollution from earlier tests' fake modules:
+ # ``importlib.import_module`` reads ``sys.modules`` directly, which is
+ # properly reverted by ``monkeypatch``.
+ return importlib.import_module("deeptutor.tools.rag_tool").rag_search
- with as_user("u_alice", role="user"):
- with pytest.raises(ValueError, match="No knowledge base selected"):
- asyncio.run(rag_tool.rag_search(query="hi", kb_name=None))
+def test_rag_search_no_kb_raises_value_error(mu_isolated_root, as_user):
+ import pytest
-def test_rag_search_no_kb_admin_does_not_raise_for_missing_kb(
- mu_isolated_root, as_user, monkeypatch
-):
- """Admin path keeps the legacy single-user fallback semantics."""
- from deeptutor.tools import rag_tool
-
- sentinel = object()
+ rag_search = _rag_search()
+ with as_user("u_alice", role="user"):
+ with pytest.raises(ValueError, match="kb_name"):
+ asyncio.run(rag_search(query="hi", kb_name=""))
- async def _stub_search(self, *, query, kb_name, event_sink=None, **kwargs):
- return {"answer": "stubbed", "kb_name": kb_name, "kb_base_dir": self.kb_base_dir}
- monkeypatch.setattr(
- "deeptutor.services.rag.service.RAGService.search",
- _stub_search,
- )
+def test_rag_search_admin_also_requires_kb_name(mu_isolated_root, as_user):
+ import pytest
+ rag_search = _rag_search()
with as_user("u_admin", role="admin"):
- # Admin / single-user mode passes through the legacy resolver, which
- # raises a different, KB-resolution error (no admin KBs in the temp
- # workspace) — the important thing is we do NOT raise the M4 guard.
- try:
- asyncio.run(rag_tool.rag_search(query="hi", kb_name=None))
- except ValueError as exc:
- assert "No knowledge base selected" not in str(exc)
- except Exception:
- # Any other failure mode is fine — we only assert that the
- # non-admin "deny by default" guard didn't fire.
- pass
-
- # Reference sentinel to silence ruff if assertions short-circuit.
- assert sentinel is not None
+ with pytest.raises(ValueError, match="kb_name"):
+ asyncio.run(rag_search(query="hi", kb_name=""))
diff --git a/tests/runtime/test_launcher.py b/tests/runtime/test_launcher.py
index 7a9df69b6..3fe1fb5e0 100644
--- a/tests/runtime/test_launcher.py
+++ b/tests/runtime/test_launcher.py
@@ -27,9 +27,7 @@ def test_packaged_web_cache_replaces_next_public_placeholders(tmp_path: Path) ->
assert (runtime / "server.js").read_text(encoding="utf-8") == (
"const api='http://localhost:8001';"
)
- assert "auth='true'" in (runtime / ".next" / "static" / "app.js").read_text(
- encoding="utf-8"
- )
+ assert "auth='true'" in (runtime / ".next" / "static" / "app.js").read_text(encoding="utf-8")
def test_packaged_web_cache_refreshes_when_public_settings_change(tmp_path: Path) -> None:
diff --git a/tests/services/config/test_embedding_runtime.py b/tests/services/config/test_embedding_runtime.py
index b67c12260..640d22998 100644
--- a/tests/services/config/test_embedding_runtime.py
+++ b/tests/services/config/test_embedding_runtime.py
@@ -9,6 +9,7 @@ from deeptutor.services.config.provider_runtime import (
resolve_embedding_runtime_config,
)
+
def _build_catalog(
*,
embedding_profile: dict | None = None,
@@ -42,6 +43,7 @@ def _build_catalog(
},
}
+
def test_embedding_explicit_binding_and_headers() -> None:
catalog = _build_catalog(
embedding_profile={
@@ -69,6 +71,7 @@ def test_embedding_explicit_binding_and_headers() -> None:
assert resolved.extra_headers == {"X-App": "demo"}
assert resolved.dimension == 1024
+
def test_embedding_alias_canonicalization_google_to_gemini() -> None:
catalog = _build_catalog(
embedding_profile={
@@ -86,6 +89,7 @@ def test_embedding_alias_canonicalization_google_to_gemini() -> None:
assert resolved.provider_name == "gemini"
assert resolved.binding == "gemini"
+
def test_embedding_gemini_default_base_and_profile_key() -> None:
catalog = _build_catalog(
embedding_profile={
@@ -108,6 +112,7 @@ def test_embedding_gemini_default_base_and_profile_key() -> None:
== "https://generativelanguage.googleapis.com/v1beta/openai/embeddings"
)
+
def test_embedding_local_fallback_from_base_url() -> None:
catalog = _build_catalog(
embedding_profile={
@@ -126,6 +131,7 @@ def test_embedding_local_fallback_from_base_url() -> None:
assert resolved.provider_mode == "local"
assert resolved.api_key == ""
+
def test_embedding_local_vllm_uses_profile_key() -> None:
catalog = _build_catalog(
embedding_profile={
@@ -144,6 +150,7 @@ def test_embedding_local_vllm_uses_profile_key() -> None:
assert resolved.provider_mode == "local"
assert resolved.api_key == "local-secret"
+
def test_embedding_openai_default_base_injected() -> None:
catalog = _build_catalog(
embedding_profile={
@@ -162,6 +169,7 @@ def test_embedding_openai_default_base_injected() -> None:
# v1.3.0: provider defaults are full embedding endpoint URLs.
assert resolved.effective_url == "https://api.openai.com/v1/embeddings"
+
def test_embedding_send_dimensions_default_is_none() -> None:
"""Catalogs without the field should resolve to ``None`` (Auto behaviour)."""
catalog = _build_catalog() # default model has no `send_dimensions`
@@ -182,7 +190,6 @@ def test_embedding_send_dimensions_default_is_none() -> None:
("garbage", None),
],
)
-
def test_embedding_send_dimensions_parsed_from_catalog(
catalog_value: object,
expected: bool | None,
@@ -199,11 +206,13 @@ def test_embedding_send_dimensions_parsed_from_catalog(
resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.send_dimensions is expected
+
def test_embedding_send_dimensions_catalog_unset_stays_auto() -> None:
catalog = _build_catalog()
resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.send_dimensions is None
+
def test_embedding_send_dimensions_resolves_from_catalog() -> None:
catalog = _build_catalog(
embedding_model={
@@ -217,6 +226,7 @@ def test_embedding_send_dimensions_resolves_from_catalog() -> None:
resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.send_dimensions is True
+
def test_embedding_custom_openai_sdk_uses_user_supplied_base_url() -> None:
"""Legacy `custom_openai_sdk` configs still resolve for backwards compatibility."""
catalog = _build_catalog(
@@ -244,6 +254,7 @@ def test_embedding_custom_openai_sdk_uses_user_supplied_base_url() -> None:
assert resolved.effective_url == "https://my-proxy.example.com/v1"
assert resolved.api_key == "sk-custom"
+
def test_embedding_openrouter_default_base_url_injected() -> None:
"""When no base URL is set, the OpenRouter spec's default fills in."""
catalog = _build_catalog(
@@ -270,6 +281,7 @@ def test_embedding_openrouter_default_base_url_injected() -> None:
assert resolved.effective_url == "https://openrouter.ai/api/v1/embeddings"
assert EMBEDDING_PROVIDERS["openrouter"].adapter == "openai_compat"
+
def test_embedding_openrouter_profile_key() -> None:
catalog = _build_catalog(
embedding_profile={
@@ -287,6 +299,7 @@ def test_embedding_openrouter_profile_key() -> None:
assert resolved.provider_name == "openrouter"
assert resolved.api_key == "sk-or-from-profile"
+
def test_embedding_provider_profile_key() -> None:
catalog = _build_catalog(
embedding_profile={
diff --git a/tests/services/config/test_knowledge_base_config.py b/tests/services/config/test_knowledge_base_config.py
index 0891d2a88..241338cf0 100644
--- a/tests/services/config/test_knowledge_base_config.py
+++ b/tests/services/config/test_knowledge_base_config.py
@@ -137,6 +137,40 @@ class TestPersistence:
assert on_disk["knowledge_bases"]["new-kb"]["rag_provider"] == "llamaindex"
assert on_disk["knowledge_bases"]["new-kb"]["description"] == "x"
+ def test_set_kb_config_does_not_resurrect_externally_removed_kbs(
+ self, tmp_path: Path
+ ) -> None:
+ """Regression: the service used to cache ``self._config`` at construction
+ and ``_save()`` wrote that snapshot back wholesale. If
+ ``KnowledgeBaseManager`` pruned an orphan KB from disk in between, the
+ next ``set_kb_config`` call would resurrect it. Fix: refresh from disk
+ before any write so the two writers share a consistent view.
+ """
+ config_path = tmp_path / "kb_config.json"
+ _write_kb_config(
+ config_path,
+ {
+ "defaults": {"rag_provider": "llamaindex"},
+ "knowledge_bases": {
+ "orphan": {"path": "orphan", "rag_provider": "llamaindex"},
+ "kept": {"path": "kept", "rag_provider": "llamaindex"},
+ },
+ },
+ )
+ service = KnowledgeBaseConfigService(config_path=config_path)
+
+ # External writer (e.g. KnowledgeBaseManager) prunes the orphan entry.
+ external = json.loads(config_path.read_text(encoding="utf-8"))
+ del external["knowledge_bases"]["orphan"]
+ config_path.write_text(json.dumps(external), encoding="utf-8")
+
+ # Service writes an unrelated update. The orphan must NOT come back.
+ service.set_kb_config("kept", {"description": "still here"})
+
+ on_disk = json.loads(config_path.read_text(encoding="utf-8"))
+ assert "orphan" not in on_disk["knowledge_bases"]
+ assert on_disk["knowledge_bases"]["kept"]["description"] == "still here"
+
def test_search_mode_is_preserved(self, fresh_service) -> None:
fresh_service.set_search_mode("kb", "naive")
assert fresh_service.get_search_mode("kb") == "naive"
diff --git a/tests/services/config/test_provider_runtime.py b/tests/services/config/test_provider_runtime.py
index f72c0e729..30dcf55dc 100644
--- a/tests/services/config/test_provider_runtime.py
+++ b/tests/services/config/test_provider_runtime.py
@@ -7,6 +7,7 @@ from deeptutor.services.config.provider_runtime import (
resolve_search_runtime_config,
)
+
def _build_catalog(
*,
llm_profile: dict | None = None,
@@ -53,6 +54,7 @@ def _build_catalog(
},
}
+
def test_llm_explicit_binding_and_headers() -> None:
catalog = _build_catalog(
llm_profile={
@@ -72,6 +74,7 @@ def test_llm_explicit_binding_and_headers() -> None:
assert resolved.effective_url == "https://dashscope.aliyuncs.com/compatible-mode/v1"
assert resolved.extra_headers == {"APP-Code": "abc"}
+
def test_llm_api_key_prefix_gateway() -> None:
catalog = _build_catalog(
llm_profile={
@@ -90,6 +93,7 @@ def test_llm_api_key_prefix_gateway() -> None:
assert resolved.provider_mode == "gateway"
assert resolved.effective_url == "https://openrouter.ai/api/v1"
+
def test_llm_api_base_keyword_gateway() -> None:
catalog = _build_catalog(
llm_profile={
@@ -109,6 +113,7 @@ def test_llm_api_base_keyword_gateway() -> None:
assert resolved.effective_url == "https://api.aihubmix.com/v1"
assert resolved.extra_headers == {"APP-Code": "x"}
+
def test_llm_local_fallback() -> None:
catalog = _build_catalog(
llm_profile={
@@ -127,6 +132,7 @@ def test_llm_local_fallback() -> None:
assert resolved.provider_mode == "local"
assert resolved.api_key == "sk-no-key-required"
+
def test_llm_minimax_binding_uses_minimaxi_endpoint() -> None:
catalog = _build_catalog(
llm_profile={
@@ -145,6 +151,7 @@ def test_llm_minimax_binding_uses_minimaxi_endpoint() -> None:
assert resolved.provider_mode == "standard"
assert resolved.effective_url == "https://api.minimaxi.com/v1"
+
def test_llm_minimax_anthropic_binding_uses_anthropic_endpoint() -> None:
catalog = _build_catalog(
llm_profile={
@@ -163,6 +170,7 @@ def test_llm_minimax_anthropic_binding_uses_anthropic_endpoint() -> None:
assert resolved.provider_mode == "standard"
assert resolved.effective_url == "https://api.minimaxi.com/anthropic"
+
def test_llm_custom_anthropic_binding_stays_direct() -> None:
catalog = _build_catalog(
llm_profile={
@@ -183,6 +191,7 @@ def test_llm_custom_anthropic_binding_stays_direct() -> None:
assert resolved.effective_url == "https://claude-proxy.example/v1/messages"
assert resolved.extra_headers == {"x-tenant": "lab"}
+
def test_llm_lm_studio_alias_resolves_to_local_provider() -> None:
catalog = _build_catalog(
llm_profile={
@@ -202,6 +211,7 @@ def test_llm_lm_studio_alias_resolves_to_local_provider() -> None:
assert resolved.effective_url == "http://localhost:1234/v1"
assert resolved.api_key == "sk-no-key-required"
+
def test_llm_context_window_passes_through_from_catalog() -> None:
catalog = _build_catalog(
llm_profile={
@@ -225,6 +235,7 @@ def test_llm_context_window_passes_through_from_catalog() -> None:
resolved = resolve_llm_runtime_config(catalog=catalog)
assert resolved.context_window == 128000
+
def test_llm_selection_overrides_active_model_without_mutating_catalog() -> None:
profile_a = {
"id": "p-a",
@@ -266,6 +277,7 @@ def test_llm_selection_overrides_active_model_without_mutating_catalog() -> None
assert catalog["services"]["llm"]["active_profile_id"] == "p-a"
assert catalog["services"]["llm"]["active_model_id"] == "m-a"
+
def test_llm_reasoning_effort_resolves_from_catalog() -> None:
catalog = _build_catalog(
llm_profile={
@@ -289,6 +301,7 @@ def test_llm_reasoning_effort_resolves_from_catalog() -> None:
resolved = resolve_llm_runtime_config(catalog=catalog)
assert resolved.reasoning_effort == "high"
+
def test_search_fallback_to_duckduckgo_without_key() -> None:
catalog = _build_catalog(
search_profile={
@@ -307,6 +320,7 @@ def test_search_fallback_to_duckduckgo_without_key() -> None:
assert resolved.fallback_reason is not None
assert resolved.proxy == "http://127.0.0.1:7890"
+
def test_search_none_disables_runtime_provider() -> None:
catalog = _build_catalog(
search_profile={
@@ -324,6 +338,7 @@ def test_search_none_disables_runtime_provider() -> None:
assert resolved.requested_provider == "none"
assert resolved.status == "ok"
+
def test_search_marks_deprecated_provider() -> None:
catalog = _build_catalog(
search_profile={
@@ -341,6 +356,7 @@ def test_search_marks_deprecated_provider() -> None:
assert resolved.deprecated_provider is True
assert resolved.provider == "exa"
+
def test_search_perplexity_missing_credentials() -> None:
catalog = _build_catalog(
search_profile={
@@ -359,6 +375,7 @@ def test_search_perplexity_missing_credentials() -> None:
assert resolved.deprecated_provider is False
assert resolved.missing_credentials is True
+
def test_search_serper_missing_credentials() -> None:
catalog = _build_catalog(
search_profile={
@@ -377,6 +394,7 @@ def test_search_serper_missing_credentials() -> None:
assert resolved.deprecated_provider is False
assert resolved.missing_credentials is True
+
def test_search_searxng_without_url_fallback() -> None:
catalog = _build_catalog(
search_profile={
diff --git a/tests/services/config/test_runtime_settings.py b/tests/services/config/test_runtime_settings.py
index f525ba239..4cc84625e 100644
--- a/tests/services/config/test_runtime_settings.py
+++ b/tests/services/config/test_runtime_settings.py
@@ -55,6 +55,7 @@ def test_runtime_settings_creates_defaults_without_reading_dotenv(tmp_path: Path
assert _read_json(service.path_for("system"))["backend_port"] == 8001
assert _read_json(service.path_for("auth"))["enabled"] is False
+
def test_runtime_process_env_is_explicit_override(tmp_path: Path) -> None:
service = RuntimeSettingsService(
tmp_path / "settings",
@@ -108,9 +109,7 @@ def test_render_environment_uses_json_backed_runtime_names(monkeypatch, tmp_path
assert "AUTH_SECRET" not in env
-def test_exported_environment_does_not_become_runtime_override(
- monkeypatch, tmp_path: Path
-) -> None:
+def test_exported_environment_does_not_become_runtime_override(monkeypatch, tmp_path: Path) -> None:
_clear_runtime_env(monkeypatch)
service = RuntimeSettingsService(tmp_path / "settings")
@@ -175,7 +174,6 @@ def test_startup_ensure_creates_missing_runtime_jsons_with_defaults(
}
-
def test_runtime_settings_can_ignore_process_overrides(tmp_path: Path) -> None:
service = RuntimeSettingsService(
tmp_path / "settings",
diff --git a/tests/services/llm/test_config_module.py b/tests/services/llm/test_config_module.py
index 9e21d33c2..2d3af363e 100644
--- a/tests/services/llm/test_config_module.py
+++ b/tests/services/llm/test_config_module.py
@@ -147,6 +147,7 @@ def test_initialize_environment_skips_openai_env_for_custom_anthropic(monkeypatc
assert "OPENAI_API_KEY" not in os.environ
assert "OPENAI_BASE_URL" not in os.environ
+
def test_resolver_missing_model_raises(monkeypatch) -> None:
_reset_config_cache()
diff --git a/tests/services/test_model_catalog.py b/tests/services/test_model_catalog.py
index 75df7138a..e29a96f82 100644
--- a/tests/services/test_model_catalog.py
+++ b/tests/services/test_model_catalog.py
@@ -18,6 +18,7 @@ def test_load_creates_empty_catalog_without_dotenv_hydration(tmp_path: Path):
assert catalog["services"]["embedding"]["profiles"] == []
assert catalog["services"]["search"]["profiles"] == []
+
def test_load_does_not_sync_existing_active_profiles_from_dotenv(tmp_path: Path):
(tmp_path / ".env").write_text(
"LLM_MODEL=qwen3.5-plus\nEMBEDDING_MODEL=text-embedding-v4\n",
@@ -108,7 +109,6 @@ def test_load_recovers_invalid_catalog_with_defaults(tmp_path: Path):
assert set(saved["services"]) == {"llm", "embedding", "search"}
-
def test_load_persists_normalized_active_ids(tmp_path: Path):
catalog_path = tmp_path / "model_catalog.json"
catalog_path.write_text(
diff --git a/tests/tools/test_rag_tool.py b/tests/tools/test_rag_tool.py
index 58ae9f9a6..17a12f150 100644
--- a/tests/tools/test_rag_tool.py
+++ b/tests/tools/test_rag_tool.py
@@ -12,7 +12,6 @@ from deeptutor.services.rag.factory import (
)
from deeptutor.tools.rag_tool import (
RAGService,
- _resolve_kb_name,
get_available_providers,
get_current_provider,
)
@@ -87,28 +86,18 @@ class TestToolLayerExports:
def test_get_available_providers_matches_class_method(self) -> None:
assert get_available_providers() == RAGService.list_providers()
- def test_resolve_default_alias_to_configured_default(self, tmp_path) -> None:
- from deeptutor.knowledge.manager import KnowledgeBaseManager
+ def test_rag_search_requires_kb_name(self) -> None:
+ import asyncio
- base_dir = tmp_path / "knowledge_bases"
- manager = KnowledgeBaseManager(base_dir=str(base_dir))
- manager.config["knowledge_bases"]["actual-kb"] = {
- "path": "actual-kb",
- "status": "ready",
- }
- manager._save_config()
+ from deeptutor.tools.rag_tool import rag_search
- assert _resolve_kb_name("default", kb_base_dir=str(base_dir)) == "actual-kb"
+ with pytest.raises(ValueError, match="kb_name"):
+ asyncio.run(rag_search(query="hi", kb_name=""))
- def test_resolve_exact_kb_named_default_before_alias(self, tmp_path) -> None:
- from deeptutor.knowledge.manager import KnowledgeBaseManager
+ def test_rag_search_requires_query(self) -> None:
+ import asyncio
- base_dir = tmp_path / "knowledge_bases"
- manager = KnowledgeBaseManager(base_dir=str(base_dir))
- manager.config["knowledge_bases"] = {
- "default": {"path": "default", "status": "ready"},
- "z-kb": {"path": "z-kb", "status": "ready"},
- }
- manager._save_config()
+ from deeptutor.tools.rag_tool import rag_search
- assert _resolve_kb_name("default", kb_base_dir=str(base_dir)) == "default"
+ with pytest.raises(ValueError, match="non-empty"):
+ asyncio.run(rag_search(query="", kb_name="any"))
diff --git a/web/app/(utility)/space/co-learn-history/page.tsx b/web/app/(utility)/space/co-learn-history/page.tsx
new file mode 100644
index 000000000..95e460fb9
--- /dev/null
+++ b/web/app/(utility)/space/co-learn-history/page.tsx
@@ -0,0 +1,19 @@
+"use client";
+
+import { Sparkles } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import ChatHistorySection from "@/components/space/ChatHistorySection";
+
+export default function SpaceCoLearnHistoryPage() {
+ const { t } = useTranslation();
+ return (
+ <ChatHistorySection
+ kind="co_learn"
+ icon={Sparkles}
+ title={t("Co-Learn History")}
+ description={t(
+ "Past auto-routed Co-Learn sessions. Reopen any to continue where the agent left off.",
+ )}
+ />
+ );
+}
diff --git a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
index 11ac875ad..02af2acbe 100644
--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx
@@ -29,6 +29,19 @@ import { ChatMessageList } from "@/components/chat/home/ChatMessages";
// clicking a chip becomes a single CSS class flip, no chunk fetch + double
// render. The heavy renderers inside still load lazily.
import FilePreviewDrawer from "@/components/chat/preview/FilePreviewDrawer";
+import SessionActivityPanel, {
+ buildSessionActivity,
+} from "@/components/chat/home/SessionActivityPanel";
+import SessionViewerPanel, {
+ type SessionViewerPanelHandle,
+} from "@/components/chat/home/SessionViewerPanel";
+import {
+ BookmarkPlus,
+ BookOpen,
+ Download,
+ PanelRight,
+ SquarePen,
+} from "lucide-react";
import {
useUnifiedChat,
type MessageAttachment,
@@ -122,6 +135,29 @@ const SaveToNotebookModal = dynamic(
ssr: false,
},
);
+// Activity-panel config card hosts the capability-specific form (Quiz /
+// Animator / Visualize / Research). Lazy-loaded so capabilities that
+// don't need a form (Chat / Solve) don't ship the form JS.
+const CapabilityConfigCard = dynamic(
+ () => import("@/components/chat/home/CapabilityConfigCard"),
+ { ssr: false },
+);
+const QuizConfigPanel = dynamic(
+ () => import("@/components/quiz/QuizConfigPanel"),
+ { ssr: false },
+);
+const MathAnimatorConfigPanel = dynamic(
+ () => import("@/components/math-animator/MathAnimatorConfigPanel"),
+ { ssr: false },
+);
+const VisualizeConfigPanel = dynamic(
+ () => import("@/components/visualize/VisualizeConfigPanel"),
+ { ssr: false },
+);
+const ResearchConfigPanel = dynamic(
+ () => import("@/components/research/ResearchConfigPanel"),
+ { ssr: false },
+);
/* ------------------------------------------------------------------ */
/* Type & data definitions */
@@ -129,7 +165,6 @@ const SaveToNotebookModal = dynamic(
type ToolName =
| "brainstorm"
- | "rag"
| "web_search"
| "code_execution"
| "reason"
@@ -149,7 +184,6 @@ interface ResearchSourceDef {
const ALL_TOOLS: ToolDef[] = [
{ name: "brainstorm", label: "Brainstorm", icon: Lightbulb },
- { name: "rag", label: "RAG", icon: Database },
{ name: "web_search", label: "Web Search", icon: Globe },
{ name: "code_execution", label: "Code", icon: Code2 },
{ name: "reason", label: "Reason", icon: Sparkles },
@@ -179,7 +213,6 @@ const CAPABILITIES: CapabilityDef[] = [
icon: MessageSquare,
allowedTools: [
"brainstorm",
- "rag",
"web_search",
"code_execution",
"reason",
@@ -189,23 +222,23 @@ const CAPABILITIES: CapabilityDef[] = [
},
{
value: "deep_solve",
- label: "Deep Solve",
+ label: "Solve",
description: "Multi-step reasoning & problem solving",
icon: BrainCircuit,
- allowedTools: ["rag", "web_search", "code_execution", "reason"],
- defaultTools: ["rag", "web_search", "code_execution", "reason"],
+ allowedTools: ["web_search", "code_execution", "reason"],
+ defaultTools: ["web_search", "code_execution", "reason"],
},
{
value: "deep_question",
- label: "Quiz Generation",
+ label: "Quiz",
description: "Auto-validated question generation",
icon: PenLine,
- allowedTools: ["rag", "web_search", "code_execution"],
- defaultTools: ["rag", "web_search", "code_execution"],
+ allowedTools: ["web_search", "code_execution"],
+ defaultTools: ["web_search", "code_execution"],
},
{
value: "deep_research",
- label: "Deep Research",
+ label: "Research",
description: "Comprehensive multi-agent research",
icon: Microscope,
allowedTools: [],
@@ -213,7 +246,7 @@ const CAPABILITIES: CapabilityDef[] = [
},
{
value: "math_animator",
- label: "Math Animator",
+ label: "Animator",
description: "Generate math videos or storyboard images",
icon: Clapperboard,
allowedTools: [],
@@ -247,6 +280,12 @@ interface PendingAttachment {
/* Helpers */
/* ------------------------------------------------------------------ */
+// ChatComposer still accepts isAutoMode/autoEnabledCaps/onToggleAutoCap so that
+// the same component can also be reused by the /co-learn page. Manual chat
+// always passes these dummies — the auto multi-select popover is never shown.
+const EMPTY_SET = new Set<string>();
+const noopToggleAutoCap = (_cap: string) => undefined;
+
function getCapability(value: string | null): CapabilityDef {
return CAPABILITIES.find((c) => c.value === (value || "")) ?? CAPABILITIES[0];
}
@@ -290,6 +329,104 @@ export default function ChatPage() {
const [previewSource, setPreviewSource] = useState<FilePreviewSource | null>(
null,
);
+ // When the chat column squeezes (e.g. the Viewer panel opens), the header
+ // action labels can collide. We measure the actual header width and flip
+ // to icon-only buttons below a threshold so the row never overflows.
+ // Important: read full border-box width via getBoundingClientRect — the
+ // ResizeObserverEntry.contentRect excludes the header's px-6 padding
+ // (48 px), which makes a "naive" threshold land 48 px below where labels
+ // actually start colliding.
+ const headerRef = useRef<HTMLDivElement | null>(null);
+ const [headerMeasuredWidth, setHeaderMeasuredWidth] = useState<number>(
+ Number.POSITIVE_INFINITY,
+ );
+ useEffect(() => {
+ const el = headerRef.current;
+ if (!el || typeof ResizeObserver === "undefined") return;
+ setHeaderMeasuredWidth(el.getBoundingClientRect().width);
+ const observer = new ResizeObserver(() => {
+ // entry.contentRect drops padding; the visual collision happens at
+ // border-box width, so read it directly off the element.
+ if (headerRef.current) {
+ setHeaderMeasuredWidth(
+ headerRef.current.getBoundingClientRect().width,
+ );
+ }
+ });
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, []);
+ // Right-side panels — Activity (floating cards) and Viewer (full sidebar
+ // with tabs for file previews + web pages). Each independently togglable
+ // and persisted across reloads.
+ //
+ // We initialise both to `false` so the SSR-rendered HTML matches the
+ // first client render exactly (no hydration mismatch). The persisted
+ // preference is then applied in a post-mount effect below.
+ const [activityPanelOpen, setActivityPanelOpen] = useState(false);
+ const [viewerPanelOpen, setViewerPanelOpen] = useState(false);
+ useEffect(() => {
+ if (typeof window === "undefined") return;
+ if (window.localStorage.getItem("dt:chat:activity-panel") === "1") {
+ setActivityPanelOpen(true);
+ }
+ if (window.localStorage.getItem("dt:chat:viewer-panel") === "1") {
+ setViewerPanelOpen(true);
+ }
+ }, []);
+ const toggleActivityPanel = useCallback(() => {
+ setActivityPanelOpen((prev) => {
+ const next = !prev;
+ if (typeof window !== "undefined") {
+ window.localStorage.setItem(
+ "dt:chat:activity-panel",
+ next ? "1" : "0",
+ );
+ }
+ return next;
+ });
+ }, []);
+ /**
+ * Force the Activity panel open. Used by the send-gate when the user
+ * tries to send while the active capability still needs its config
+ * confirmed — we surface the right-side panel so the Confirm button is
+ * visible. Persisted to localStorage so subsequent reloads remember the
+ * preference. Also used by the capability-switch auto-open effect below.
+ */
+ const ensureActivityPanelOpen = useCallback(() => {
+ setActivityPanelOpen((prev) => {
+ if (prev) return prev;
+ if (typeof window !== "undefined") {
+ window.localStorage.setItem("dt:chat:activity-panel", "1");
+ }
+ return true;
+ });
+ }, []);
+ const setViewerOpen = useCallback((next: boolean) => {
+ setViewerPanelOpen(next);
+ if (typeof window !== "undefined") {
+ window.localStorage.setItem("dt:chat:viewer-panel", next ? "1" : "0");
+ }
+ }, []);
+ const toggleViewerPanel = useCallback(() => {
+ setViewerPanelOpen((prev) => {
+ const next = !prev;
+ if (typeof window !== "undefined") {
+ window.localStorage.setItem(
+ "dt:chat:viewer-panel",
+ next ? "1" : "0",
+ );
+ }
+ return next;
+ });
+ }, []);
+ // The header's five labelled actions ("Save to Notebook" / "Download
+ // Markdown" / "New chat" / "Activity" / "Viewer") need roughly 720 px
+ // (label widths + gaps + the capability title) to fit on one row without
+ // colliding. Below that we collapse all five to icon-only. We also
+ // force-collapse whenever the Viewer panel is open — its squeeze is
+ // aggressive enough that labels are guaranteed to overflow.
+ const headerCompact = viewerPanelOpen || headerMeasuredWidth < 720;
const attachmentErrorTimer = useRef<ReturnType<typeof setTimeout> | null>(
null,
);
@@ -308,10 +445,15 @@ export default function ChatPage() {
const [researchConfig, setResearchConfig] = useState<DeepResearchFormConfig>(
createEmptyResearchConfig(),
);
- // Unified collapse state for the capability-specific config panel
- // (Quiz / Math Animator / Visualize / Deep Research). Default collapsed so
- // a fresh Chat / Deep Solve session has the shortest possible composer.
- const [panelCollapsed, setPanelCollapsed] = useState(true);
+ // Capability-config confirmation gate.
+ //
+ // For capabilities that need explicit configuration (Quiz, Animator,
+ // Visualize, Research), the user must click *Confirm* in the right-side
+ // Activity panel before sending. Any subsequent edit to the underlying
+ // config invalidates the confirmation, so the user re-confirms once
+ // they've adjusted settings. Capability switches also reset this flag.
+ const [capabilityConfigConfirmed, setCapabilityConfigConfirmed] =
+ useState(false);
const [showSaveModal, setShowSaveModal] = useState(false);
const [showNotebookPicker, setShowNotebookPicker] = useState(false);
const [showBookPicker, setShowBookPicker] = useState(false);
@@ -321,6 +463,7 @@ export default function ChatPage() {
const [showMemoryPicker, setShowMemoryPicker] = useState(false);
const [toolMenuOpen, setToolMenuOpen] = useState(false);
const [spaceMenuOpen, setSpaceMenuOpen] = useState(false);
+ const [kbMenuOpen, setKbMenuOpen] = useState(false);
const [selectedNotebookRecords, setSelectedNotebookRecords] = useState<
SelectedRecord[]
>([]);
@@ -345,6 +488,8 @@ export default function ChatPage() {
const toolBtnRef = useRef<HTMLButtonElement>(null);
const spaceMenuRef = useRef<HTMLDivElement>(null);
const spaceBtnRef = useRef<HTMLButtonElement>(null);
+ const kbMenuRef = useRef<HTMLDivElement>(null);
+ const kbBtnRef = useRef<HTMLButtonElement>(null);
const initialLoadRef = useRef(false);
const activeCap = useMemo(
@@ -355,13 +500,72 @@ export default function ChatPage() {
const isMathAnimatorMode = activeCap.value === "math_animator";
const isVisualizeMode = activeCap.value === "visualize";
const isResearchMode = activeCap.value === "deep_research";
+ const capabilityNeedsConfig =
+ isQuizMode || isMathAnimatorMode || isVisualizeMode || isResearchMode;
+
+ // Edit-invalidates-confirm wrappers — flipping any field after the user
+ // hit *Confirm* should restore the gate so they re-confirm intentionally.
+ // `useCallback` keeps identities stable so the memoized ChatComposer /
+ // CapabilityConfigCard don't churn on every keystroke.
+ const handleChangeQuizConfig = useCallback(
+ (next: DeepQuestionFormConfig) => {
+ setQuizConfig(next);
+ setCapabilityConfigConfirmed(false);
+ },
+ [],
+ );
+ const handleUploadQuizPdf = useCallback((file: File | null) => {
+ setQuizPdf(file);
+ setCapabilityConfigConfirmed(false);
+ }, []);
+ const handleChangeMathAnimatorConfig = useCallback(
+ (next: MathAnimatorFormConfig) => {
+ setMathAnimatorConfig(next);
+ setCapabilityConfigConfirmed(false);
+ },
+ [],
+ );
+ const handleChangeVisualizeConfig = useCallback(
+ (next: VisualizeFormConfig) => {
+ setVisualizeConfig(next);
+ setCapabilityConfigConfirmed(false);
+ },
+ [],
+ );
+ const handleChangeResearchConfig = useCallback(
+ (next: DeepResearchFormConfig) => {
+ setResearchConfig(next);
+ setCapabilityConfigConfirmed(false);
+ },
+ [],
+ );
+ const handleConfirmCapabilityConfig = useCallback(() => {
+ setCapabilityConfigConfirmed(true);
+ }, []);
+
+ /**
+ * Auto-open the right-side Activity panel when the user switches into a
+ * capability that requires manual configuration (Quiz / Animator /
+ * Visualize / Research). We only fire on the transition from "doesn't
+ * need config" → "needs config" so we don't fight the user if they
+ * close the panel themselves while still in a config-needing mode.
+ *
+ * Tracking via a ref (instead of deps) avoids re-firing whenever the
+ * panel toggles — the open-state flip should be one-shot per cap
+ * transition.
+ */
+ const lastCapabilityNeedsConfigRef = useRef(capabilityNeedsConfig);
+ useEffect(() => {
+ const prev = lastCapabilityNeedsConfigRef.current;
+ lastCapabilityNeedsConfigRef.current = capabilityNeedsConfig;
+ if (!prev && capabilityNeedsConfig) {
+ ensureActivityPanelOpen();
+ }
+ }, [capabilityNeedsConfig, ensureActivityPanelOpen]);
const selectedTools = useMemo(
() => new Set(state.enabledTools),
[state.enabledTools],
);
- const ragActive = isResearchMode
- ? researchConfig.sources.includes("kb")
- : selectedTools.has("rag");
const hasMessages = state.messages.length > 0;
const { ref: composerRef, height: composerHeight } =
useMeasuredHeight<HTMLDivElement>();
@@ -577,15 +781,11 @@ export default function ChatPage() {
try {
const list = await listKnowledgeBases({ force: options?.force });
setKnowledgeBases(list);
- if (!state.knowledgeBases.length && list.length) {
- const def = list.find((k: KnowledgeBase) => k.is_default);
- setKBs([def?.name || list[0].name]);
- }
} catch {
setKnowledgeBases([]);
}
},
- [setKBs, state.knowledgeBases.length],
+ [],
);
/* Load KBs */
@@ -681,6 +881,13 @@ export default function ChatPage() {
!spaceBtnRef.current.contains(t)
)
setSpaceMenuOpen(false);
+ if (
+ kbMenuRef.current &&
+ !kbMenuRef.current.contains(t) &&
+ kbBtnRef.current &&
+ !kbBtnRef.current.contains(t)
+ )
+ setKbMenuOpen(false);
};
document.addEventListener("mousedown", handler);
return () => document.removeEventListener("mousedown", handler);
@@ -712,12 +919,10 @@ export default function ChatPage() {
? [...config.enabledTools]
: [...cap.defaultTools],
);
- if (config.enabledTools.includes("rag") && config.knowledgeBase)
- setKBs([config.knowledgeBase]);
- // Default-expand the per-capability settings panel right after a
- // capability switch so users immediately see the form. Sending a
- // message later will auto-collapse it (see handleSend).
- setPanelCollapsed(false);
+ if (config.knowledgeBase) setKBs([config.knowledgeBase]);
+ // Switching capability invalidates any prior config confirmation —
+ // the new capability has its own form that needs explicit confirm.
+ setCapabilityConfigConfirmed(false);
setCapMenuOpen(false);
},
[capabilityConfigs, setCapability, setKBs, setTools],
@@ -742,6 +947,9 @@ export default function ChatPage() {
? current.sources.filter((item) => item !== source)
: [...current.sources, source],
}));
+ // Toggling sources is part of the Research config — invalidate the
+ // confirm so the user can re-verify before sending.
+ setCapabilityConfigConfirmed(false);
}, []);
const fileToAttachment = useCallback(
@@ -857,16 +1065,142 @@ export default function ChatPage() {
[attachments],
);
- const handlePreviewMessageAttachment = useCallback((a: MessageAttachment) => {
- setPreviewSource({
- filename: a.filename || "",
- mimeType: a.mime_type,
- type: a.type,
- url: a.url,
- base64: a.base64,
- extractedText: a.extracted_text,
- id: a.id,
- });
+ // Fold all messages once per state.messages change to power the
+ // SessionActivityPanel on the right (tools, KBs, space refs, attachments).
+ const sessionActivity = useMemo(
+ () => buildSessionActivity(state.messages),
+ [state.messages],
+ );
+
+ /**
+ * Capability-config card rendered at the bottom of the Activity panel.
+ *
+ * Returns null for capabilities that don't need explicit configuration
+ * (Chat / Solve) — the Activity panel falls back to its standard
+ * sections (tools, KBs, space, attachments) plus the empty-state card.
+ *
+ * For Quiz / Animator / Visualize / Research, we wrap the matching bare
+ * ConfigPanel in a `CapabilityConfigCard` that provides the header,
+ * Confirm button, and validation-error display. The Confirm gate is
+ * wired through `capabilityConfigConfirmed` / `handleConfirmCapabilityConfig`.
+ */
+ const capabilityConfigSection = useMemo(() => {
+ if (!capabilityNeedsConfig) return null;
+ if (isQuizMode) {
+ return (
+ <CapabilityConfigCard
+ capability="deep_question"
+ confirmed={capabilityConfigConfirmed}
+ canConfirm
+ onConfirm={handleConfirmCapabilityConfig}
+ >
+ <QuizConfigPanel
+ value={quizConfig}
+ onChange={handleChangeQuizConfig}
+ uploadedPdf={quizPdf}
+ onUploadPdf={handleUploadQuizPdf}
+ />
+ </CapabilityConfigCard>
+ );
+ }
+ if (isMathAnimatorMode) {
+ return (
+ <CapabilityConfigCard
+ capability="math_animator"
+ confirmed={capabilityConfigConfirmed}
+ canConfirm
+ onConfirm={handleConfirmCapabilityConfig}
+ >
+ <MathAnimatorConfigPanel
+ value={mathAnimatorConfig}
+ onChange={handleChangeMathAnimatorConfig}
+ />
+ </CapabilityConfigCard>
+ );
+ }
+ if (isVisualizeMode) {
+ return (
+ <CapabilityConfigCard
+ capability="visualize"
+ confirmed={capabilityConfigConfirmed}
+ canConfirm
+ onConfirm={handleConfirmCapabilityConfig}
+ >
+ <VisualizeConfigPanel
+ value={visualizeConfig}
+ onChange={handleChangeVisualizeConfig}
+ />
+ </CapabilityConfigCard>
+ );
+ }
+ // Research: forward validation errors so the user sees what's missing
+ // before they hit Confirm. `canConfirm` only flips false when there's
+ // an actual error (e.g. mode/depth not selected).
+ const researchErrorMessages = Object.values(researchValidation.errors);
+ return (
+ <CapabilityConfigCard
+ capability="deep_research"
+ confirmed={capabilityConfigConfirmed}
+ canConfirm={researchErrorMessages.length === 0}
+ validationErrors={researchErrorMessages}
+ onConfirm={handleConfirmCapabilityConfig}
+ >
+ <ResearchConfigPanel
+ value={researchConfig}
+ errors={researchValidation.errors}
+ onChange={handleChangeResearchConfig}
+ />
+ </CapabilityConfigCard>
+ );
+ }, [
+ capabilityNeedsConfig,
+ isQuizMode,
+ isMathAnimatorMode,
+ isVisualizeMode,
+ capabilityConfigConfirmed,
+ handleConfirmCapabilityConfig,
+ quizConfig,
+ quizPdf,
+ handleChangeQuizConfig,
+ handleUploadQuizPdf,
+ mathAnimatorConfig,
+ handleChangeMathAnimatorConfig,
+ visualizeConfig,
+ handleChangeVisualizeConfig,
+ researchConfig,
+ researchValidation.errors,
+ handleChangeResearchConfig,
+ ]);
+
+ const viewerPanelRef = useRef<SessionViewerPanelHandle | null>(null);
+ // Clicking an attachment (from the Activity panel or from a chat message)
+ // routes into the Viewer panel as a new file tab. The viewer auto-opens
+ // and the preference is persisted so a follow-up click feels instant.
+ const handlePreviewMessageAttachment = useCallback(
+ (a: MessageAttachment) => {
+ viewerPanelRef.current?.openFileTab(a);
+ },
+ [],
+ );
+
+ // Event-delegated link interception inside the messages container. When
+ // the user clicks an http(s) link in an assistant message, we open it as
+ // a Viewer tab instead of letting the browser navigate / open a new tab.
+ // Cmd/ctrl/shift + click keep their standard meaning (open in browser).
+ const handleMessagesClick = useCallback((event: React.MouseEvent) => {
+ if (event.defaultPrevented) return;
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
+ return;
+ if (event.button !== 0) return;
+ const target = event.target as HTMLElement | null;
+ if (!target) return;
+ const anchor = target.closest<HTMLAnchorElement>("a[href]");
+ if (!anchor) return;
+ const href = anchor.getAttribute("href");
+ if (!href) return;
+ if (!/^https?:\/\//i.test(href)) return;
+ event.preventDefault();
+ viewerPanelRef.current?.openWebTab(href);
}, []);
const handleClosePreview = useCallback(() => {
@@ -995,9 +1329,6 @@ export default function ChatPage() {
memoryPayload,
);
shouldAutoScrollRef.current = true;
- // Auto-collapse the per-capability settings panel after sending so the
- // composer stays compact during conversation.
- setPanelCollapsed(true);
setAttachments([]);
setSelectedBookReferences([]);
setSelectedNotebookRecords([]);
@@ -1064,11 +1395,16 @@ export default function ChatPage() {
regenerateLastMessage();
}, [regenerateLastMessage]);
- const handleSetKB = useCallback(
- (kb: string) => {
- setKBs(kb ? [kb] : []);
+ const handleToggleKB = useCallback(
+ (name: string) => {
+ const current = state.knowledgeBases;
+ setKBs(
+ current.includes(name)
+ ? current.filter((kb) => kb !== name)
+ : [...current, name],
+ );
},
- [setKBs],
+ [setKBs, state.knowledgeBases],
);
const handleSelectNotebookPicker = useCallback(() => {
setShowNotebookPicker(true);
@@ -1128,9 +1464,6 @@ export default function ChatPage() {
);
}, []);
- const handleTogglePanelCollapsed = useCallback(() => {
- setPanelCollapsed((prev) => !prev);
- }, []);
const handleCloseNotebookPicker = useCallback(() => {
setShowNotebookPicker(false);
}, []);
@@ -1211,34 +1544,55 @@ export default function ChatPage() {
// transition lives in `chat-preview-shell` (globals.css) so we can
// hand-tune it without fighting Tailwind's arbitrary-value parser.
data-preview-open={previewSource ? "true" : "false"}
+ data-activity-open={activityPanelOpen ? "true" : "false"}
+ data-viewer-open={viewerPanelOpen ? "true" : "false"}
className="chat-preview-shell flex h-full flex-col overflow-hidden bg-[var(--background)]"
>
- <div className="mx-auto flex w-full max-w-[960px] items-center justify-between px-6 pt-3 pb-0">
- <span className="text-[15px] font-semibold tracking-[-0.01em] text-[var(--foreground)]">
+ <div
+ ref={headerRef}
+ className="mx-auto flex w-full max-w-[960px] flex-wrap items-center justify-between gap-x-3 gap-y-1.5 px-6 pt-3 pb-0"
+ >
+ <span className="min-w-0 flex-1 truncate text-[15px] font-semibold tracking-[-0.01em] text-[var(--foreground)]">
{t(activeCap.label)}
</span>
- <div className="flex items-center gap-2">
- <button
+ <div className="flex shrink-0 flex-wrap items-center gap-1.5">
+ <HeaderActionButton
+ compact={headerCompact}
onClick={() => setShowSaveModal(true)}
disabled={!chatSavePayload}
- className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-[var(--border)]/50 disabled:hover:text-[var(--muted-foreground)]"
- >
- {t("Save to Notebook")}
- </button>
- <button
+ icon={BookmarkPlus}
+ label={t("Save to Notebook")}
+ />
+ <HeaderActionButton
+ compact={headerCompact}
onClick={handleDownloadMarkdown}
disabled={!state.messages.length}
+ icon={Download}
+ label={t("Download Markdown")}
title={t("Download chat history as Markdown")}
- className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-[var(--border)]/50 disabled:hover:text-[var(--muted-foreground)]"
- >
- {t("Download Markdown")}
- </button>
- <button
+ />
+ <HeaderActionButton
+ compact={headerCompact}
onClick={handleNewChat}
- className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"
- >
- {t("New chat")}
- </button>
+ icon={SquarePen}
+ label={t("New chat")}
+ />
+ <HeaderActionButton
+ compact={headerCompact}
+ onClick={toggleActivityPanel}
+ active={activityPanelOpen}
+ icon={PanelRight}
+ label={t("Activity")}
+ title={t("Session activity")}
+ />
+ <HeaderActionButton
+ compact={headerCompact}
+ onClick={toggleViewerPanel}
+ active={viewerPanelOpen}
+ icon={BookOpen}
+ label={t("Viewer")}
+ title={t("Open viewer")}
+ />
</div>
</div>
<div className="mx-auto flex w-full max-w-[960px] flex-1 min-h-0 flex-col overflow-hidden px-6">
@@ -1258,14 +1612,22 @@ export default function ChatPage() {
ref={messagesContainerRef}
data-chat-scroll-root="true"
onScroll={handleMessagesScroll}
- className={`mx-auto w-full flex-1 min-h-0 space-y-7 overflow-y-auto pr-4 [scrollbar-gutter:stable] ${hasMessages ? "pt-0" : "pt-2 pb-6"}`}
+ onClick={handleMessagesClick}
+ className={`mx-auto w-full flex-1 min-h-0 space-y-7 overflow-y-auto pr-4 [scrollbar-gutter:stable] ${hasMessages ? "pt-6" : "pt-2 pb-6"}`}
style={
hasMessages
? (() => {
+ // The bottom 40 px of the messages area fades to
+ // transparent so content "dissolves" into the composer
+ // gutter. Without enough bottom padding, the fade
+ // overlaps the last assistant paragraph and looks like
+ // a stuck scroll — the user reaches scrollHeight but
+ // can still see only a faded sliver of text. paddingBottom
+ // is sized so the fade falls over empty space.
const maskImage =
"linear-gradient(to bottom, transparent 0px, #000 32px, #000 calc(100% - 40px), transparent 100%)";
return {
- paddingBottom: "4px",
+ paddingBottom: "48px",
WebkitMaskImage: maskImage,
maskImage,
};
@@ -1296,18 +1658,20 @@ export default function ChatPage() {
toolBtnRef={toolBtnRef}
spaceMenuRef={spaceMenuRef}
spaceBtnRef={spaceBtnRef}
+ kbMenuRef={kbMenuRef}
+ kbBtnRef={kbBtnRef}
dragCounter={dragCounter}
dragging={dragging}
capMenuOpen={capMenuOpen}
toolMenuOpen={toolMenuOpen}
spaceMenuOpen={spaceMenuOpen}
+ kbMenuOpen={kbMenuOpen}
hasMessages={hasMessages}
attachments={attachments}
attachmentError={attachmentError}
activeCap={activeCap}
visibleTools={visibleTools}
selectedTools={selectedTools}
- ragActive={ragActive}
knowledgeBases={knowledgeBases}
llmOptions={llmOptions}
activeLLMDefault={activeLLMDefault}
@@ -1322,25 +1686,25 @@ export default function ChatPage() {
selectedSkills={selectedSkills}
skillsAutoMode={skillsAutoMode}
selectedMemoryFiles={selectedMemoryFiles}
- stateKnowledgeBase={state.knowledgeBases[0] || ""}
+ selectedKnowledgeBases={state.knowledgeBases}
isStreaming={state.isStreaming}
isResearchMode={isResearchMode}
- isQuizMode={isQuizMode}
isMathAnimatorMode={isMathAnimatorMode}
isVisualizeMode={isVisualizeMode}
- quizConfig={quizConfig}
- quizPdf={quizPdf}
- mathAnimatorConfig={mathAnimatorConfig}
- visualizeConfig={visualizeConfig}
- researchConfig={researchConfig}
- researchValidationErrors={researchValidation.errors}
- panelCollapsed={panelCollapsed}
+ isAutoMode={false}
+ autoEnabledCaps={EMPTY_SET}
+ researchConfigSources={researchConfig.sources}
+ capabilityNeedsConfig={capabilityNeedsConfig}
+ capabilityConfigConfirmed={capabilityConfigConfirmed}
+ onRequestConfigConfirm={ensureActivityPanelOpen}
capabilities={CAPABILITIES}
researchSources={RESEARCH_SOURCES}
onSetCapMenuOpen={setCapMenuOpen}
onSetToolMenuOpen={setToolMenuOpen}
onSetSpaceMenuOpen={setSpaceMenuOpen}
- onSetKB={handleSetKB}
+ onSetKbMenuOpen={setKbMenuOpen}
+ onToggleAutoCap={noopToggleAutoCap}
+ onToggleKB={handleToggleKB}
onSelectLLM={setLLMSelection}
onSelectNotebookPicker={handleSelectNotebookPicker}
onSelectBookPicker={handleSelectBookPicker}
@@ -1368,12 +1732,6 @@ export default function ChatPage() {
onAddFiles={handleAddFiles}
onSelectCapability={handleSelectCapability}
onCancelStreaming={cancelStreamingTurn}
- onChangeQuizConfig={setQuizConfig}
- onUploadQuizPdf={setQuizPdf}
- onChangeMathAnimatorConfig={setMathAnimatorConfig}
- onChangeVisualizeConfig={setVisualizeConfig}
- onChangeResearchConfig={setResearchConfig}
- onTogglePanelCollapsed={handleTogglePanelCollapsed}
/>
</div>
<NotebookRecordPicker
@@ -1421,6 +1779,64 @@ export default function ChatPage() {
source={previewSource}
onClose={handleClosePreview}
/>
+ <SessionActivityPanel
+ open={activityPanelOpen && previewSource === null && !viewerPanelOpen}
+ activity={sessionActivity}
+ onOpenAttachment={handlePreviewMessageAttachment}
+ configSection={capabilityConfigSection}
+ />
+ <SessionViewerPanel
+ ref={viewerPanelRef}
+ open={viewerPanelOpen && previewSource === null}
+ sessionId={state.sessionId}
+ onClose={() => setViewerOpen(false)}
+ onAutoOpen={() => setViewerOpen(true)}
+ />
</div>
);
}
+
+/**
+ * Header action button that auto-collapses to icon-only when the chat
+ * column gets squeezed (Viewer panel open, narrow viewport, etc.). The
+ * label stays as the button's `title` so hovering an icon still reveals
+ * what it does. Optional `active` flag paints the button with a primary
+ * tint, used by the panel-toggle buttons to surface their on/off state.
+ */
+function HeaderActionButton({
+ compact,
+ onClick,
+ disabled,
+ active,
+ icon: Icon,
+ label,
+ title,
+}: {
+ compact: boolean;
+ onClick: () => void;
+ disabled?: boolean;
+ active?: boolean;
+ icon: LucideIcon;
+ label: string;
+ title?: string;
+}) {
+ return (
+ <button
+ onClick={onClick}
+ disabled={disabled}
+ title={title ?? label}
+ aria-label={label}
+ aria-pressed={active}
+ className={`inline-flex shrink-0 items-center gap-1.5 rounded-lg border text-[12px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-40 ${
+ compact ? "px-2 py-1.5" : "px-3 py-1.5"
+ } ${
+ active
+ ? "border-[var(--primary)]/40 bg-[color-mix(in_srgb,var(--primary)_8%,var(--card))] text-[var(--primary)] hover:border-[var(--primary)]/55"
+ : "border-[var(--border)]/50 text-[var(--muted-foreground)] hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:hover:border-[var(--border)]/50 disabled:hover:text-[var(--muted-foreground)]"
+ }`}
+ >
+ <Icon size={14} strokeWidth={1.7} className="shrink-0" />
+ {compact ? null : <span>{label}</span>}
+ </button>
+ );
+}
diff --git a/web/app/(workspace)/co-learn/[[...sessionId]]/page.tsx b/web/app/(workspace)/co-learn/[[...sessionId]]/page.tsx
new file mode 100644
index 000000000..30dea7875
--- /dev/null
+++ b/web/app/(workspace)/co-learn/[[...sessionId]]/page.tsx
@@ -0,0 +1,756 @@
+"use client";
+
+import {
+ BarChart3,
+ BrainCircuit,
+ Clapperboard,
+ Microscope,
+ PenLine,
+ type LucideIcon,
+} from "lucide-react";
+import { useParams, useRouter } from "next/navigation";
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { useTranslation } from "react-i18next";
+
+import ChatComposer from "@/components/chat/home/ChatComposer";
+import { ChatMessageList } from "@/components/chat/home/ChatMessages";
+import FilePreviewDrawer from "@/components/chat/preview/FilePreviewDrawer";
+import type { FilePreviewSource } from "@/components/chat/preview/previewerFor";
+import { useAppShell } from "@/context/AppShellContext";
+import {
+ type MessageAttachment,
+ type MessageRequestSnapshot,
+ useUnifiedChat,
+} from "@/context/UnifiedChatContext";
+import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";
+import { useMeasuredHeight } from "@/hooks/useMeasuredHeight";
+import {
+ MAX_ATTACHMENT_BYTES,
+ MAX_TOTAL_ATTACHMENT_BYTES,
+ classifyFile,
+ isSvgFilename,
+} from "@/lib/doc-attachments";
+import {
+ extractBase64FromDataUrl,
+ readFileAsDataUrl,
+} from "@/lib/file-attachments";
+import { listKnowledgeBases } from "@/lib/knowledge-api";
+import { listLLMOptions, type LLMOption } from "@/lib/llm-options";
+import { SURFACES } from "@/lib/session-surfaces";
+import {
+ DEFAULT_MATH_ANIMATOR_CONFIG,
+ type MathAnimatorFormConfig,
+} from "@/lib/math-animator-types";
+import {
+ DEFAULT_QUIZ_CONFIG,
+ type DeepQuestionFormConfig,
+} from "@/lib/quiz-types";
+import {
+ createEmptyResearchConfig,
+ type DeepResearchFormConfig,
+ type ResearchSource,
+} from "@/lib/research-types";
+import type { LLMSelection } from "@/lib/unified-ws";
+import {
+ DEFAULT_VISUALIZE_CONFIG,
+ type VisualizeFormConfig,
+} from "@/lib/visualize-types";
+
+/* -------------------------------------------------------------------------- */
+/* Module-level constants */
+/* -------------------------------------------------------------------------- */
+
+interface CoLearnCapability {
+ value: string;
+ label: string;
+ description: string;
+ icon: LucideIcon;
+ /** Tools the router *may* enable per-sub-capability. Pure UI hint. */
+ allowedTools: string[];
+}
+
+/**
+ * Sub-capabilities the Auto router is allowed to delegate to. Order here is
+ * how they appear in the multi-select popover. The "auto" capability itself
+ * and the bare "chat" mode are intentionally excluded — auto routes to
+ * specialized capabilities or atomic tools.
+ */
+const CO_LEARN_CAPABILITIES: CoLearnCapability[] = [
+ {
+ value: "deep_solve",
+ label: "Deep Solve",
+ description: "Multi-step reasoning & problem solving",
+ icon: BrainCircuit,
+ allowedTools: ["rag", "web_search", "code_execution", "reason"],
+ },
+ {
+ value: "deep_question",
+ label: "Quiz Generation",
+ description: "Auto-validated question generation",
+ icon: PenLine,
+ allowedTools: ["rag", "web_search", "code_execution"],
+ },
+ {
+ value: "deep_research",
+ label: "Deep Research",
+ description: "Comprehensive multi-agent research",
+ icon: Microscope,
+ allowedTools: [],
+ },
+ {
+ value: "math_animator",
+ label: "Math Animator",
+ description: "Generate math videos or storyboard images",
+ icon: Clapperboard,
+ allowedTools: [],
+ },
+ {
+ value: "visualize",
+ label: "Visualize",
+ description: "Generate SVG, Chart.js, or Mermaid visualizations",
+ icon: BarChart3,
+ allowedTools: [],
+ },
+];
+
+const DEFAULT_AUTO_ENABLED = new Set(
+ CO_LEARN_CAPABILITIES.map((c) => c.value),
+);
+
+interface PendingAttachment {
+ type: string;
+ filename: string;
+ base64?: string;
+ previewUrl?: string;
+ size?: number;
+ mimeType?: string;
+}
+
+interface KnowledgeBase {
+ name: string;
+ is_default?: boolean;
+}
+
+// Empty constants passed to ChatComposer for picker/skill props the lean
+// /co-learn surface intentionally does not expose. Keeping them stable (top-level
+// constants) prevents unnecessary ChatComposer re-renders.
+const EMPTY_NOTEBOOKS: never[] = [];
+const EMPTY_BOOKS: never[] = [];
+const EMPTY_HISTORY: never[] = [];
+const EMPTY_QUESTIONS: never[] = [];
+const EMPTY_SKILLS: string[] = [];
+const EMPTY_MEMORY: never[] = [];
+const EMPTY_TOOL_SET = new Set<string>();
+const EMPTY_NOTEBOOK_GROUPS: never[] = [];
+const EMPTY_RESEARCH_SOURCES: { name: ResearchSource; label: string; icon: LucideIcon }[] = [];
+const EMPTY_RESEARCH_SOURCE_LIST: ResearchSource[] = [];
+const NOOP = () => undefined;
+const NOOP_ASYNC = async () => undefined;
+
+/* -------------------------------------------------------------------------- */
+/* Page */
+/* -------------------------------------------------------------------------- */
+
+export default function CoLearnPage() {
+ const params = useParams<{ sessionId?: string[] }>();
+ const router = useRouter();
+ const { t } = useTranslation();
+ const sessionIdParam = params.sessionId?.[0] ?? null;
+ const { setActiveSessionId, language: appLanguage } = useAppShell();
+
+ const {
+ state,
+ setCapability,
+ setKBs,
+ setLLMSelection,
+ sendMessage,
+ cancelStreamingTurn,
+ regenerateLastMessage,
+ newSession,
+ loadSession,
+ } = useUnifiedChat();
+
+ /* ---------------- Local state ---------------- */
+
+ const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
+ const [llmOptions, setLLMOptions] = useState<LLMOption[]>([]);
+ const [activeLLMDefault, setActiveLLMDefault] = useState<LLMSelection | null>(
+ null,
+ );
+ const [llmOptionsLoading, setLLMOptionsLoading] = useState(true);
+ const [llmOptionsError, setLLMOptionsError] = useState(false);
+ const [attachments, setAttachments] = useState<PendingAttachment[]>([]);
+ const [dragging, setDragging] = useState(false);
+ const [attachmentError, setAttachmentError] = useState<string | null>(null);
+ const [previewSource, setPreviewSource] = useState<FilePreviewSource | null>(
+ null,
+ );
+ const attachmentErrorTimer = useRef<ReturnType<typeof setTimeout> | null>(
+ null,
+ );
+
+ const [autoEnabledCaps, setAutoEnabledCaps] = useState<Set<string>>(
+ () => new Set(DEFAULT_AUTO_ENABLED),
+ );
+
+ // Capability popover (multi-select for auto-enabled caps)
+ const [capMenuOpen, setCapMenuOpen] = useState(false);
+ const [kbMenuOpen, setKbMenuOpen] = useState(false);
+
+ /* ---------------- Refs ---------------- */
+
+ const dragCounter = useRef(0);
+ const capMenuRef = useRef<HTMLDivElement>(null);
+ const capBtnRef = useRef<HTMLButtonElement>(null);
+ const toolMenuRef = useRef<HTMLDivElement>(null);
+ const toolBtnRef = useRef<HTMLButtonElement>(null);
+ const spaceMenuRef = useRef<HTMLDivElement>(null);
+ const spaceBtnRef = useRef<HTMLButtonElement>(null);
+ const kbMenuRef = useRef<HTMLDivElement>(null);
+ const kbBtnRef = useRef<HTMLButtonElement>(null);
+ const initialLoadRef = useRef(false);
+
+ /* ---------------- Composed values ---------------- */
+
+ const hasMessages = state.messages.length > 0;
+ const { ref: composerRef } = useMeasuredHeight<HTMLDivElement>();
+
+ // ``activeCap`` is just a placeholder for ChatComposer's prop schema; the
+ // composer never renders it in auto mode (capability label area is replaced
+ // by the multi-select trigger).
+ const activeCap = useMemo<CoLearnCapability>(
+ () => ({
+ value: "auto",
+ label: "Auto",
+ description: "Auto routing",
+ icon: PenLine,
+ allowedTools: [],
+ }),
+ [],
+ );
+
+ /* ---------------- Session bootstrap ---------------- */
+
+ // Force capability="auto" once on mount and keep it pinned. Co-learn is a
+ // single-capability surface; the user never picks a manual capability here.
+ useEffect(() => {
+ setCapability("auto");
+ }, [setCapability]);
+
+ useEffect(() => {
+ setActiveSessionId(sessionIdParam);
+ }, [sessionIdParam, setActiveSessionId]);
+
+ useEffect(() => {
+ if (initialLoadRef.current) return;
+ initialLoadRef.current = true;
+ if (sessionIdParam) {
+ void loadSession(sessionIdParam);
+ } else {
+ newSession();
+ }
+ }, [loadSession, newSession, sessionIdParam]);
+
+ /* ---------------- KB load ---------------- */
+
+ const loadKBs = useCallback(async (options?: { force?: boolean }) => {
+ try {
+ const list = await listKnowledgeBases({ force: options?.force });
+ const mapped: KnowledgeBase[] = list.map((kb) => ({
+ name: kb.name,
+ is_default: kb.is_default,
+ }));
+ setKnowledgeBases(mapped);
+ if (state.knowledgeBases.length === 0 && mapped.length > 0) {
+ const def = mapped.find((kb) => kb.is_default) ?? mapped[0];
+ setKBs([def.name]);
+ }
+ } catch (err) {
+ console.error("Failed to load knowledge bases", err);
+ }
+ }, [setKBs, state.knowledgeBases.length]);
+
+ useEffect(() => {
+ void loadKBs();
+ }, [loadKBs]);
+
+ /* ---------------- LLM options ---------------- */
+
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ setLLMOptionsLoading(true);
+ try {
+ const payload = await listLLMOptions();
+ if (cancelled) return;
+ setLLMOptions(payload.options);
+ setActiveLLMDefault(payload.active);
+ setLLMOptionsError(false);
+ } catch (err) {
+ if (cancelled) return;
+ console.error("Failed to load LLM options", err);
+ setLLMOptions([]);
+ setActiveLLMDefault(null);
+ setLLMOptionsError(true);
+ } finally {
+ if (!cancelled) setLLMOptionsLoading(false);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ /* ---------------- Auto scroll ---------------- */
+
+ const lastMsg = state.messages[state.messages.length - 1];
+ const {
+ containerRef: messagesContainerRef,
+ endRef: messagesEndRef,
+ shouldAutoScrollRef,
+ handleScroll: handleMessagesScroll,
+ } = useChatAutoScroll({
+ hasMessages,
+ isStreaming: state.isStreaming,
+ composerHeight: 0,
+ messageCount: state.messages.length,
+ lastMessageContent: lastMsg?.content,
+ lastEventCount: lastMsg?.events?.length,
+ });
+
+ /* ---------------- Attachment helpers ---------------- */
+
+ const flashAttachmentError = useCallback((msg: string) => {
+ setAttachmentError(msg);
+ if (attachmentErrorTimer.current) {
+ clearTimeout(attachmentErrorTimer.current);
+ }
+ attachmentErrorTimer.current = setTimeout(() => {
+ setAttachmentError(null);
+ }, 4000);
+ }, []);
+
+ // Mirrors the chat page's filter + classify logic (see fileToAttachment in
+ // app/(workspace)/chat/.../page.tsx). Kept compact: we only need it for the
+ // composer's drag/drop/paste paths.
+ const fileToAttachment = useCallback(
+ (f: File): Promise<PendingAttachment> =>
+ new Promise((resolve, reject) => {
+ readFileAsDataUrl(f)
+ .then((raw) => {
+ const svg = isSvgFilename(f.name) || f.type === "image/svg+xml";
+ const isImage = !svg && f.type.startsWith("image/");
+ resolve({
+ type: isImage ? "image" : "file",
+ filename: f.name,
+ base64: extractBase64FromDataUrl(raw),
+ previewUrl: isImage || svg ? raw : undefined,
+ size: f.size,
+ mimeType: f.type || undefined,
+ });
+ })
+ .catch(reject);
+ }),
+ [],
+ );
+
+ const filterFiles = useCallback(
+ (files: File[]): File[] => {
+ let running = attachments.reduce((s, a) => s + (a.size ?? 0), 0);
+ const accepted: File[] = [];
+ let firstReject: { name: string; reason: "unsupported" | "too_large" | "quota" } | null = null;
+ for (const f of files) {
+ if (!classifyFile(f)) {
+ if (!firstReject) firstReject = { name: f.name, reason: "unsupported" };
+ continue;
+ }
+ if (f.size > MAX_ATTACHMENT_BYTES) {
+ if (!firstReject) firstReject = { name: f.name, reason: "too_large" };
+ continue;
+ }
+ if (running + f.size > MAX_TOTAL_ATTACHMENT_BYTES) {
+ if (!firstReject) firstReject = { name: f.name, reason: "quota" };
+ break;
+ }
+ running += f.size;
+ accepted.push(f);
+ }
+ if (firstReject) {
+ const msg =
+ firstReject.reason === "too_large"
+ ? t("File too large: {{name}}", { name: firstReject.name })
+ : firstReject.reason === "quota"
+ ? t("Too many files, skipped some")
+ : t("Unsupported file type: {{name}}", { name: firstReject.name });
+ flashAttachmentError(msg);
+ }
+ return accepted;
+ },
+ [attachments, flashAttachmentError, t],
+ );
+
+ const handleAddFiles = useCallback(
+ async (files: File[]) => {
+ const accepted = filterFiles(files);
+ if (!accepted.length) return;
+ const next = await Promise.all(accepted.map(fileToAttachment));
+ setAttachments((prev) => [...prev, ...next]);
+ },
+ [filterFiles, fileToAttachment],
+ );
+
+ const removeAttachment = useCallback((index: number) => {
+ setAttachments((prev) => prev.filter((_, i) => i !== index));
+ }, []);
+
+ /* ---------------- Drag/drop/paste ---------------- */
+
+ const handleDragEnter = useCallback((event: React.DragEvent) => {
+ if (event.dataTransfer.types.includes("Files")) {
+ event.preventDefault();
+ dragCounter.current += 1;
+ setDragging(true);
+ }
+ }, []);
+ const handleDragLeave = useCallback((event: React.DragEvent) => {
+ event.preventDefault();
+ dragCounter.current = Math.max(0, dragCounter.current - 1);
+ if (dragCounter.current === 0) setDragging(false);
+ }, []);
+ const handleDragOver = useCallback((event: React.DragEvent) => {
+ event.preventDefault();
+ }, []);
+ const handleDrop = useCallback(
+ (event: React.DragEvent) => {
+ event.preventDefault();
+ dragCounter.current = 0;
+ setDragging(false);
+ const files = Array.from(event.dataTransfer.files || []);
+ if (files.length) void handleAddFiles(files);
+ },
+ [handleAddFiles],
+ );
+ const handlePaste = useCallback(
+ (event: React.ClipboardEvent) => {
+ const files = Array.from(event.clipboardData?.files || []);
+ if (files.length) {
+ event.preventDefault();
+ void handleAddFiles(files);
+ }
+ },
+ [handleAddFiles],
+ );
+
+ /* ---------------- KB select ---------------- */
+
+ const handleToggleKB = useCallback(
+ (name: string) => {
+ const current = state.knowledgeBases;
+ setKBs(
+ current.includes(name)
+ ? current.filter((kb) => kb !== name)
+ : [...current, name],
+ );
+ },
+ [setKBs, state.knowledgeBases],
+ );
+
+ /* ---------------- Capability multi-select ---------------- */
+
+ const handleToggleAutoCap = useCallback((cap: string) => {
+ setAutoEnabledCaps((current) => {
+ const next = new Set(current);
+ if (next.has(cap)) {
+ next.delete(cap);
+ } else {
+ next.add(cap);
+ }
+ return next;
+ });
+ }, []);
+
+ /* ---------------- Send ---------------- */
+
+ const handleSend = useCallback(
+ async (content: string) => {
+ if ((!content && !attachments.length) || state.isStreaming) return;
+ const extraAttachments = attachments.map((a) => ({
+ type: a.type,
+ filename: a.filename,
+ base64: a.base64,
+ mime_type: a.mimeType,
+ }));
+ const config: Record<string, unknown> = {
+ enabled_capabilities: Array.from(autoEnabledCaps),
+ };
+ const messageContent =
+ content ||
+ (attachments.some((a) => a.type === "image")
+ ? t("Please analyze the attached image(s).")
+ : "");
+ // ``kind: "co_learn"`` tags the backend session row so the chat sidebar
+ // / history page never mixes auto-routing sessions into the /chat view.
+ // Only matters on the first send (when ``ensure_session`` creates the
+ // row); subsequent sends in the same session are no-ops kind-wise.
+ sendMessage(
+ messageContent,
+ extraAttachments,
+ config,
+ undefined,
+ undefined,
+ { kind: "co_learn" },
+ );
+ shouldAutoScrollRef.current = true;
+ setAttachments([]);
+ },
+ [
+ attachments,
+ autoEnabledCaps,
+ sendMessage,
+ shouldAutoScrollRef,
+ state.isStreaming,
+ t,
+ ],
+ );
+
+ /* ---------------- Preview / answer-now / copy / regenerate ---------------- */
+
+ const handlePreviewMessageAttachment = useCallback((a: MessageAttachment) => {
+ setPreviewSource({
+ filename: a.filename || "",
+ mimeType: a.mime_type,
+ type: a.type,
+ url: a.url,
+ base64: a.base64,
+ });
+ }, []);
+ const handlePreviewPendingAttachment = useCallback(
+ (index: number) => {
+ const att = attachments[index];
+ if (!att) return;
+ setPreviewSource({
+ filename: att.filename,
+ mimeType: att.mimeType,
+ type: att.type,
+ base64: att.base64,
+ size: att.size,
+ });
+ },
+ [attachments],
+ );
+ const handleClosePreview = useCallback(() => setPreviewSource(null), []);
+
+ const copyAssistantMessage = useCallback(async (content: string) => {
+ try {
+ await navigator.clipboard.writeText(content);
+ } catch (e) {
+ console.warn("Copy failed", e);
+ }
+ }, []);
+
+ const handleAnswerNow = useCallback(
+ (
+ snapshot?: MessageRequestSnapshot,
+ assistantMsg?: { content: string; events?: unknown[] },
+ ) => {
+ if (!snapshot) {
+ cancelStreamingTurn();
+ return;
+ }
+ cancelStreamingTurn();
+ // Re-send same request with answer_now_context to trigger fast-path.
+ sendMessage(
+ snapshot.content,
+ snapshot.attachments,
+ {
+ ...(snapshot.config ?? {}),
+ answer_now_context: {
+ original_user_message: snapshot.content,
+ partial_response: assistantMsg?.content ?? "",
+ events: assistantMsg?.events ?? [],
+ },
+ },
+ snapshot.notebookReferences,
+ snapshot.historyReferences,
+ { bookReferences: snapshot.bookReferences },
+ snapshot.questionNotebookReferences,
+ snapshot.skills,
+ snapshot.memoryReferences,
+ );
+ },
+ [cancelStreamingTurn, sendMessage],
+ );
+
+ const handleRegenerateMessage = useCallback(() => {
+ regenerateLastMessage();
+ }, [regenerateLastMessage]);
+
+ /* ---------------- Outside-click close popovers ---------------- */
+
+ useEffect(() => {
+ const handler = (e: MouseEvent) => {
+ const t = e.target as Node;
+ if (
+ capMenuRef.current &&
+ !capMenuRef.current.contains(t) &&
+ capBtnRef.current &&
+ !capBtnRef.current.contains(t)
+ )
+ setCapMenuOpen(false);
+ if (
+ kbMenuRef.current &&
+ !kbMenuRef.current.contains(t) &&
+ kbBtnRef.current &&
+ !kbBtnRef.current.contains(t)
+ )
+ setKbMenuOpen(false);
+ };
+ document.addEventListener("mousedown", handler);
+ return () => document.removeEventListener("mousedown", handler);
+ }, []);
+
+ /* ---------------- Render ---------------- */
+
+ return (
+ <div className="flex h-full flex-col overflow-hidden">
+ <div className="mx-auto flex w-full max-w-[960px] flex-1 min-h-0 flex-col overflow-hidden px-6">
+ {!hasMessages ? (
+ <div className="flex flex-1 min-h-0 flex-col items-center justify-center animate-fade-in">
+ <div className="text-center">
+ <h1 className="font-serif text-[36px] font-medium tracking-[-0.01em] text-[var(--foreground)]">
+ {t("Co-Learn")}
+ </h1>
+ <p className="mt-4 text-[15px] text-[var(--muted-foreground)]">
+ {t(
+ "Just ask — I'll pick the right tool for the job and walk you through it.",
+ )}
+ </p>
+ </div>
+ </div>
+ ) : (
+ <div
+ ref={messagesContainerRef}
+ data-chat-scroll-root="true"
+ onScroll={handleMessagesScroll}
+ className="mx-auto w-full flex-1 min-h-0 space-y-7 overflow-y-auto pr-4 [scrollbar-gutter:stable] pt-0"
+ style={{
+ paddingBottom: "4px",
+ WebkitMaskImage:
+ "linear-gradient(to bottom, transparent 0px, #000 32px, #000 calc(100% - 40px), transparent 100%)",
+ maskImage:
+ "linear-gradient(to bottom, transparent 0px, #000 32px, #000 calc(100% - 40px), transparent 100%)",
+ }}
+ >
+ <ChatMessageList
+ messages={state.messages}
+ isStreaming={state.isStreaming}
+ sessionId={state.sessionId}
+ language={state.language ?? appLanguage}
+ onAnswerNow={handleAnswerNow}
+ onCopyAssistantMessage={copyAssistantMessage}
+ onRegenerateMessage={handleRegenerateMessage}
+ onPreviewAttachment={handlePreviewMessageAttachment}
+ onSwitchToManualMode={() => router.push(SURFACES.chat.basePath)}
+ />
+ <div ref={messagesEndRef} className="h-px w-full shrink-0" />
+ </div>
+ )}
+
+ <ChatComposer
+ composerRef={composerRef}
+ capMenuRef={capMenuRef}
+ capBtnRef={capBtnRef}
+ toolMenuRef={toolMenuRef}
+ toolBtnRef={toolBtnRef}
+ spaceMenuRef={spaceMenuRef}
+ spaceBtnRef={spaceBtnRef}
+ kbMenuRef={kbMenuRef}
+ kbBtnRef={kbBtnRef}
+ dragCounter={dragCounter}
+ dragging={dragging}
+ capMenuOpen={capMenuOpen}
+ toolMenuOpen={false}
+ spaceMenuOpen={false}
+ kbMenuOpen={kbMenuOpen}
+ hasMessages={hasMessages}
+ attachments={attachments}
+ attachmentError={attachmentError}
+ activeCap={activeCap}
+ visibleTools={[]}
+ selectedTools={EMPTY_TOOL_SET}
+ knowledgeBases={knowledgeBases}
+ llmOptions={llmOptions}
+ activeLLMDefault={activeLLMDefault}
+ llmSelection={state.llmSelection}
+ llmOptionsLoading={llmOptionsLoading}
+ llmOptionsError={llmOptionsError}
+ selectedBookReferences={EMPTY_BOOKS}
+ selectedNotebookRecords={EMPTY_NOTEBOOKS}
+ selectedHistorySessions={EMPTY_HISTORY}
+ selectedQuestionEntries={EMPTY_QUESTIONS}
+ notebookReferenceGroups={EMPTY_NOTEBOOK_GROUPS}
+ selectedSkills={EMPTY_SKILLS}
+ skillsAutoMode={false}
+ selectedMemoryFiles={EMPTY_MEMORY}
+ selectedKnowledgeBases={state.knowledgeBases}
+ isStreaming={state.isStreaming}
+ isResearchMode={false}
+ isMathAnimatorMode={false}
+ isVisualizeMode={false}
+ isAutoMode={true}
+ autoEnabledCaps={autoEnabledCaps}
+ researchConfigSources={EMPTY_RESEARCH_SOURCE_LIST}
+ capabilityNeedsConfig={false}
+ capabilityConfigConfirmed={true}
+ onRequestConfigConfirm={NOOP}
+ capabilities={CO_LEARN_CAPABILITIES}
+ researchSources={EMPTY_RESEARCH_SOURCES}
+ onSetCapMenuOpen={setCapMenuOpen}
+ onSetToolMenuOpen={NOOP}
+ onSetSpaceMenuOpen={NOOP}
+ onSetKbMenuOpen={setKbMenuOpen}
+ onToggleAutoCap={handleToggleAutoCap}
+ onToggleKB={handleToggleKB}
+ onSelectLLM={setLLMSelection}
+ onSelectNotebookPicker={NOOP}
+ onSelectBookPicker={NOOP}
+ onSelectHistoryPicker={NOOP}
+ onSelectQuestionBankPicker={NOOP}
+ onSelectSkillsPicker={NOOP}
+ onSelectMemoryPicker={NOOP}
+ onToggleTool={NOOP}
+ onToggleSkill={NOOP}
+ onSetSkillsAuto={NOOP}
+ onToggleMemoryFile={NOOP}
+ onToggleResearchSource={NOOP}
+ onSend={handleSend}
+ onRemoveAttachment={removeAttachment}
+ onPreviewAttachment={handlePreviewPendingAttachment}
+ onRemoveHistory={NOOP}
+ onRemoveBookReference={NOOP}
+ onRemoveNotebook={NOOP}
+ onRemoveQuestion={NOOP}
+ onDragEnter={handleDragEnter}
+ onDragLeave={handleDragLeave}
+ onDragOver={handleDragOver}
+ onDrop={handleDrop}
+ onPaste={handlePaste}
+ onAddFiles={(files) => void handleAddFiles(files)}
+ onSelectCapability={NOOP}
+ onCancelStreaming={cancelStreamingTurn}
+ />
+ </div>
+ <FilePreviewDrawer
+ open={previewSource !== null}
+ source={previewSource}
+ onClose={handleClosePreview}
+ />
+ </div>
+ );
+}
diff --git a/web/app/api/version/route.ts b/web/app/api/version/route.ts
deleted file mode 100644
index e7e27b4d0..000000000
--- a/web/app/api/version/route.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-import { NextResponse } from "next/server";
-import { execFileSync } from "node:child_process";
-import {
- parseBuild,
- unknownBuild,
- type ParsedBuild,
- type VersionSource,
-} from "@/lib/version";
-
-/**
- * Returns both:
- * - current: the version of the code that is actually running
- * - latest: the latest GitHub release for update awareness
- *
- * The route itself stays dynamic so current git metadata is not frozen into
- * the client bundle. The GitHub release lookup is cached separately below.
- */
-
-export const dynamic = "force-dynamic";
-export const runtime = "nodejs";
-
-// Refresh the remote release lookup at most once per hour. Tune via env if needed.
-const LATEST_REVALIDATE_SECONDS = 3600;
-const LATEST_FALLBACK_CACHE_SECONDS = 300;
-
-const DEFAULT_REPO = "HKUDS/DeepTutor";
-
-interface GithubRelease {
- tag_name: string;
- html_url: string;
- name: string | null;
- published_at: string | null;
- prerelease: boolean;
- draft: boolean;
-}
-
-interface LatestVersionPayload {
- tag: string | null;
- name: string | null;
- url: string | null;
- publishedAt: string | null;
- source: "github" | "fallback";
-}
-
-interface CurrentVersionPayload extends ParsedBuild {
- source: VersionSource;
- detectedAt: string;
-}
-
-interface VersionPayload extends LatestVersionPayload {
- current: CurrentVersionPayload;
- latest: LatestVersionPayload;
-}
-
-const FALLBACK_LATEST: LatestVersionPayload = {
- tag: null,
- name: null,
- url: `https://github.com/${DEFAULT_REPO}/releases`,
- publishedAt: null,
- source: "fallback",
-};
-
-let latestCache: {
- repo: string;
- expiresAt: number;
- payload: LatestVersionPayload;
-} | null = null;
-
-function readGitDescribe(): string | null {
- try {
- return execFileSync(
- "git",
- ["describe", "--tags", "--always", "--dirty=-dev"],
- {
- cwd: process.cwd(),
- encoding: "utf8",
- stdio: ["ignore", "pipe", "ignore"],
- timeout: 2000,
- },
- ).trim();
- } catch {
- return null;
- }
-}
-
-function detectCurrentVersion(): CurrentVersionPayload {
- const detectedAt = new Date().toISOString();
- const gitRaw = readGitDescribe();
- const envRaw =
- process.env.APP_VERSION || process.env.NEXT_PUBLIC_APP_VERSION || "";
- const raw = gitRaw || envRaw;
- const parsed = parseBuild(raw) ?? unknownBuild(raw);
-
- return {
- ...parsed,
- source: gitRaw ? "git" : envRaw ? "env" : "unknown",
- detectedAt,
- };
-}
-
-function rememberLatest(
- repo: string,
- payload: LatestVersionPayload,
- ttlSeconds: number,
-): LatestVersionPayload {
- latestCache = {
- repo,
- expiresAt: Date.now() + ttlSeconds * 1000,
- payload,
- };
- return payload;
-}
-
-async function fetchLatestRelease(
- repo: string,
- forceRefresh: boolean,
-): Promise<LatestVersionPayload> {
- const now = Date.now();
- if (
- !forceRefresh &&
- latestCache &&
- latestCache.repo === repo &&
- latestCache.expiresAt > now
- ) {
- return latestCache.payload;
- }
-
- const url = `https://api.github.com/repos/${repo}/releases/latest`;
-
- const headers: Record<string, string> = {
- Accept: "application/vnd.github+json",
- "X-GitHub-Api-Version": "2022-11-28",
- "User-Agent": "deeptutor-web",
- };
- if (process.env.GITHUB_TOKEN) {
- headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`;
- }
-
- try {
- const res = await fetch(url, {
- headers,
- cache: "no-store",
- signal: AbortSignal.timeout(2500),
- });
- if (!res.ok) {
- return rememberLatest(
- repo,
- { ...FALLBACK_LATEST, url: `https://github.com/${repo}/releases` },
- LATEST_FALLBACK_CACHE_SECONDS,
- );
- }
- const data = (await res.json()) as GithubRelease;
- const payload: LatestVersionPayload = {
- tag: data.tag_name ?? null,
- name: data.name ?? null,
- url: data.html_url ?? `https://github.com/${repo}/releases`,
- publishedAt: data.published_at ?? null,
- source: "github",
- };
- return rememberLatest(repo, payload, LATEST_REVALIDATE_SECONDS);
- } catch {
- return rememberLatest(
- repo,
- { ...FALLBACK_LATEST, url: `https://github.com/${repo}/releases` },
- LATEST_FALLBACK_CACHE_SECONDS,
- );
- }
-}
-
-export async function GET(request: Request) {
- const repo = process.env.NEXT_PUBLIC_GITHUB_REPO || DEFAULT_REPO;
- const { searchParams } = new URL(request.url);
- const forceRefresh = searchParams.get("refresh") === "1";
-
- const current = detectCurrentVersion();
- const latest = await fetchLatestRelease(repo, forceRefresh);
-
- return NextResponse.json(
- {
- ...latest,
- current,
- latest,
- } satisfies VersionPayload,
- {
- status: 200,
- headers: {
- // The running version is dynamic; callers should not reuse stale payloads.
- "Cache-Control": "no-store",
- },
- },
- );
-}
diff --git a/web/app/globals.css b/web/app/globals.css
index 3772d5d3e..c2853bbc7 100644
--- a/web/app/globals.css
+++ b/web/app/globals.css
@@ -536,6 +536,64 @@
animation: fade-in 0.35s ease-out forwards;
}
+/* Streaming "breathing" label — used above the trace panel to surface that
+ the assistant is still working. Cycles between full and dim opacity with
+ a slow ease, mirroring Claude desktop's reasoning indicator. */
+@keyframes dt-breathing {
+ 0%,
+ 100% {
+ opacity: 0.45;
+ }
+ 50% {
+ opacity: 1;
+ }
+}
+
+.dt-breathing-text {
+ animation: dt-breathing 1.8s cubic-bezier(0.4, 0, 0.6, 1) infinite;
+}
+
+/* Icon-only stretch/contract on top of the opacity breathing. Slightly
+ different period (2.4s vs 1.8s) so the scale and opacity cycles drift
+ in and out of phase, giving the mark a hand-drawn, "alive" feel rather
+ than a single mechanical pulse. */
+@keyframes dt-mark-pulse {
+ 0%,
+ 100% {
+ transform: scale(0.9);
+ }
+ 50% {
+ transform: scale(1.08);
+ }
+}
+
+.dt-mark-pulse {
+ animation: dt-mark-pulse 2.4s cubic-bezier(0.4, 0, 0.6, 1) infinite;
+ transform-origin: center;
+ transform-box: fill-box;
+ will-change: transform;
+}
+
+/* Capability menu pop-up — the dropdown blooms out of the chip itself
+ rather than fading in from above the composer. Origin at bottom-left so
+ the menu visually "unfurls" from the chevron corner of the chip. */
+@keyframes dt-popup-up {
+ from {
+ opacity: 0;
+ transform: translateY(6px) scale(0.96);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0) scale(1);
+ }
+}
+
+.dt-popup-up {
+ animation: dt-popup-up 180ms cubic-bezier(0.16, 1, 0.3, 1) forwards;
+ transform-origin: bottom left;
+ will-change: opacity, transform;
+}
+
/* Session status pulse */
@keyframes session-pulse {
0%,
@@ -563,9 +621,22 @@
padding-right: 0;
}
@media (min-width: 1024px) {
+ /* The wider composer-side preview drawer (pre-send attachment peek)
+ gets the largest squeeze. */
.chat-preview-shell[data-preview-open="true"] {
padding-right: min(560px, 92vw);
}
+ /* Viewer panel (tabbed file/web preview, opened from message attachments
+ or assistant links) is next-widest. Wins over the activity panel when
+ both are open. */
+ .chat-preview-shell[data-preview-open="false"][data-viewer-open="true"] {
+ padding-right: min(620px, 92vw);
+ }
+ /* Activity panel — floating cards on the right. Smaller squeeze so the
+ chat column doesn't get crushed when only the activity is open. */
+ .chat-preview-shell[data-preview-open="false"][data-viewer-open="false"][data-activity-open="true"] {
+ padding-right: min(320px, 92vw);
+ }
}
/* Sidebar tooltip */
diff --git a/web/components/chat/home/AutoErrorBlock.tsx b/web/components/chat/home/AutoErrorBlock.tsx
new file mode 100644
index 000000000..ecbf29cdd
--- /dev/null
+++ b/web/components/chat/home/AutoErrorBlock.tsx
@@ -0,0 +1,109 @@
+"use client";
+
+import { AlertTriangle, RefreshCcw, SlidersHorizontal } from "lucide-react";
+import { memo } from "react";
+import { useTranslation } from "react-i18next";
+
+interface AutoErrorBlockProps {
+ reason: string;
+ failureMessage?: string;
+ iteration?: number;
+ routerRetries?: number;
+ onRetry?: () => void;
+ onSwitchToManual?: () => void;
+}
+
+/**
+ * Prominent terminal-error block for auto-mode turns.
+ *
+ * Shown when the auto pipeline gave up after exhausting all retries. It
+ * surfaces:
+ * - the failure reason (router LLM exhausted, terminal error, etc.)
+ * - the failure location (iteration, retry counts)
+ * - two recovery actions: switch to manual mode, or retry the message
+ *
+ * Partial successes (capability calls that completed before the failure) are
+ * still rendered in the regular ``AutoModeAssistantMessage`` blocks above this
+ * one — we deliberately do not duplicate them here.
+ */
+const AutoErrorBlock = memo(function AutoErrorBlock({
+ reason,
+ failureMessage,
+ iteration,
+ routerRetries,
+ onRetry,
+ onSwitchToManual,
+}: AutoErrorBlockProps) {
+ const { t } = useTranslation();
+ const headline = (() => {
+ if (reason === "router_llm_exhausted") {
+ return t("Auto routing failed: router LLM exhausted retries.");
+ }
+ return t("Auto routing failed: {{reason}}", { reason });
+ })();
+
+ const subtitle = (() => {
+ const parts: string[] = [];
+ if (iteration != null) {
+ parts.push(t("at iteration {{n}}", { n: iteration }));
+ }
+ if (routerRetries != null) {
+ parts.push(t("after {{n}} router retries", { n: routerRetries }));
+ }
+ return parts.join(" · ");
+ })();
+
+ return (
+ <div className="mt-3 overflow-hidden rounded-xl border-2 border-red-300/70 bg-red-50/60 text-[13px] shadow-sm dark:border-red-500/40 dark:bg-red-950/30">
+ <div className="flex items-start gap-2.5 px-4 pt-3">
+ <AlertTriangle
+ size={16}
+ strokeWidth={2}
+ className="mt-0.5 shrink-0 text-red-600 dark:text-red-400"
+ />
+ <div className="min-w-0 flex-1">
+ <div className="font-semibold text-red-700 dark:text-red-300">
+ {headline}
+ </div>
+ {subtitle ? (
+ <div className="mt-0.5 text-[11px] text-red-700/80 dark:text-red-300/80">
+ {subtitle}
+ </div>
+ ) : null}
+ {failureMessage ? (
+ <div className="mt-2 whitespace-pre-wrap text-[12px] text-red-900/85 dark:text-red-200/85">
+ {failureMessage}
+ </div>
+ ) : null}
+ </div>
+ </div>
+
+ <div className="mt-3 flex flex-wrap items-center gap-2 border-t border-red-200/60 bg-red-100/40 px-4 py-2 dark:border-red-500/25 dark:bg-red-900/20">
+ {onSwitchToManual ? (
+ <button
+ type="button"
+ onClick={onSwitchToManual}
+ className="inline-flex items-center gap-1.5 rounded-md border border-red-300/60 bg-white px-2.5 py-1 text-[12px] font-medium text-red-700 transition-colors hover:bg-red-50 dark:border-red-500/40 dark:bg-red-950/40 dark:text-red-200 dark:hover:bg-red-900/40"
+ >
+ <SlidersHorizontal size={12} strokeWidth={1.8} />
+ {t("Switch to Manual")}
+ </button>
+ ) : null}
+ {onRetry ? (
+ <button
+ type="button"
+ onClick={onRetry}
+ className="inline-flex items-center gap-1.5 rounded-md border border-red-300/60 bg-white px-2.5 py-1 text-[12px] font-medium text-red-700 transition-colors hover:bg-red-50 dark:border-red-500/40 dark:bg-red-950/40 dark:text-red-200 dark:hover:bg-red-900/40"
+ >
+ <RefreshCcw size={12} strokeWidth={1.8} />
+ {t("Try Again")}
+ </button>
+ ) : null}
+ </div>
+ </div>
+ );
+});
+
+AutoErrorBlock.displayName = "AutoErrorBlock";
+
+export default AutoErrorBlock;
diff --git a/web/components/chat/home/AutoModeAssistantMessage.tsx b/web/components/chat/home/AutoModeAssistantMessage.tsx
new file mode 100644
index 000000000..c455cf796
--- /dev/null
+++ b/web/components/chat/home/AutoModeAssistantMessage.tsx
@@ -0,0 +1,468 @@
+"use client";
+
+import dynamic from "next/dynamic";
+import { memo, useMemo } from "react";
+import {
+ ChevronRight,
+ CircleCheck,
+ CircleX,
+ Loader2,
+ RotateCcw,
+ type LucideIcon,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import AssistantResponse from "@/components/common/AssistantResponse";
+import { extractMathAnimatorResult } from "@/lib/math-animator-types";
+import { extractQuizQuestions } from "@/lib/quiz-types";
+import type { StreamEvent } from "@/lib/unified-ws";
+import { extractVisualizeResult } from "@/lib/visualize-types";
+import AutoErrorBlock from "./AutoErrorBlock";
+import { CallTracePanel } from "./TracePanels";
+
+const MathAnimatorViewer = dynamic(
+ () => import("@/components/math-animator/MathAnimatorViewer"),
+ { ssr: false },
+);
+const QuizViewer = dynamic(() => import("@/components/quiz/QuizViewer"), {
+ ssr: false,
+});
+const VisualizationViewer = dynamic(
+ () => import("@/components/visualize/VisualizationViewer"),
+ { ssr: false },
+);
+
+/* -------------------------------------------------------------------------- */
+/* Event partitioning */
+/* -------------------------------------------------------------------------- */
+
+/**
+ * Layout block as it appears in the rendered message, top to bottom.
+ *
+ * Auto turns interleave three streams of events on the wire:
+ * - Top-level THINKING (router reasoning before/between/after delegations)
+ * - Sub-capability events (everything with a ``parent_call_id`` from the
+ * delegation forwarder)
+ * - Auto's final CONTENT and RESULT (no ``parent_call_id``)
+ *
+ * The frontend renders them as:
+ * - Inline ``thought`` blocks between collapsible delegation cards
+ * - Collapsible ``delegation`` cards (one per sub-capability invocation)
+ * - A prominent final synthesis block at the bottom
+ * - An ``AutoErrorBlock`` if the turn ended in a terminal failure
+ */
+
+type Block =
+ | { kind: "thought"; text: string }
+ | {
+ kind: "delegation";
+ callId: string;
+ capability: string;
+ events: StreamEvent[];
+ }
+ | { kind: "final"; text: string };
+
+/**
+ * ``trace_kind``s we treat as internal retry / pivot markers, NOT as
+ * user-visible errors. Anything else surfaces in the error list so a
+ * silent backend failure (orchestrator-level exception, etc.) can't leave
+ * the chat stuck on an empty user bubble.
+ */
+const TRANSIENT_ERROR_TRACE_KINDS = new Set([
+ "router_api_error",
+ "router_format_error",
+ "delegation_retry",
+ "same_cap_exhausted",
+ "validation_error",
+ "atomic_tool_error",
+]);
+
+interface PartitionResult {
+ blocks: Block[];
+ terminalError: {
+ failureReason: string;
+ failureMessage: string;
+ iteration?: number;
+ routerRetries?: number;
+ } | null;
+ /** Non-terminal top-level error messages (e.g. an uncaught capability
+ * exception bubbled up by the orchestrator). Always rendered. */
+ surfacedErrors: string[];
+ /** True while events for a delegation are still arriving. */
+ hasOpenDelegation: boolean;
+}
+
+function partitionEvents(events: StreamEvent[]): PartitionResult {
+ const blocks: Block[] = [];
+ let terminalError: PartitionResult["terminalError"] = null;
+ const surfacedErrors: string[] = [];
+ let routerRetries = 0;
+ const knownDelegations = new Map<string, Block & { kind: "delegation" }>();
+ let openDelegationId: string | null = null;
+ let thoughtBuffer: string[] = [];
+
+ const flushThought = () => {
+ if (thoughtBuffer.length === 0) return;
+ const text = thoughtBuffer.join("").trim();
+ thoughtBuffer = [];
+ if (text) blocks.push({ kind: "thought", text });
+ };
+
+ for (const event of events) {
+ const meta = event.metadata ?? {};
+ const parentCallId = meta.parent_call_id as string | undefined;
+
+ // Sub-capability event: route into its delegation card.
+ if (parentCallId) {
+ flushThought();
+ let card = knownDelegations.get(parentCallId);
+ if (!card) {
+ const capName = (meta.delegated_capability as string | undefined) ?? "";
+ card = {
+ kind: "delegation",
+ callId: parentCallId,
+ capability: capName,
+ events: [],
+ };
+ knownDelegations.set(parentCallId, card);
+ blocks.push(card);
+ openDelegationId = parentCallId;
+ }
+ card.events.push(event);
+ // A RESULT event signals the delegation finished.
+ if (event.type === "result") {
+ openDelegationId = null;
+ }
+ continue;
+ }
+
+ // Top-level event.
+ if (event.type === "error" && meta.terminal === true) {
+ terminalError = {
+ failureReason: String(meta.failure_reason ?? "unknown"),
+ failureMessage: event.content || "",
+ iteration: meta.iteration as number | undefined,
+ routerRetries,
+ };
+ continue;
+ }
+
+ if (event.type === "error") {
+ // Router retry counters live in error metadata on transient failures.
+ if (
+ typeof meta.retry_count === "number" &&
+ meta.trace_kind === "router_api_error"
+ ) {
+ routerRetries = Math.max(routerRetries, meta.retry_count as number);
+ }
+ // Any error that is NOT an expected internal retry/pivot marker must be
+ // surfaced — otherwise an uncaught backend exception (or a misconfigured
+ // LLM) leaves the user staring at a silent chat bubble forever.
+ const traceKind = typeof meta.trace_kind === "string" ? meta.trace_kind : "";
+ if (!traceKind || !TRANSIENT_ERROR_TRACE_KINDS.has(traceKind)) {
+ const msg = (event.content || "").trim();
+ if (msg) surfacedErrors.push(msg);
+ }
+ continue;
+ }
+
+ // Auto's final synthesis CONTENT (with call_kind="llm_final_response").
+ if (
+ event.type === "content" &&
+ meta.call_kind === "llm_final_response"
+ ) {
+ flushThought();
+ const text = event.content || "";
+ if (text) blocks.push({ kind: "final", text });
+ continue;
+ }
+
+ // Inline thinking / observation text that should appear between blocks.
+ // We deliberately skip ``stage === "synthesizing"`` events: the
+ // synthesizer streams its chunks as THINKING for live-progress UX, but
+ // the same text is then emitted as the prominent final CONTENT block
+ // immediately after. Without this skip the user sees the synthesis twice
+ // (once muted/italic, once prominent).
+ if (event.type === "thinking" || event.type === "observation") {
+ if (event.stage === "synthesizing") continue;
+ const text = event.content || "";
+ if (text) thoughtBuffer.push(text);
+ continue;
+ }
+ // Other top-level event types (progress, stage markers) are silent for the
+ // user-facing layout but still useful for CallTracePanel debugging — we
+ // don't render them here.
+ }
+ flushThought();
+
+ if (terminalError) {
+ terminalError.routerRetries = routerRetries;
+ }
+
+ return {
+ blocks,
+ terminalError,
+ surfacedErrors,
+ hasOpenDelegation: openDelegationId !== null,
+ };
+}
+
+/* -------------------------------------------------------------------------- */
+/* Delegation card */
+/* -------------------------------------------------------------------------- */
+
+interface DelegationCardProps {
+ capability: string;
+ events: StreamEvent[];
+ isStreaming?: boolean;
+ sessionId?: string | null;
+ language?: string;
+}
+
+function delegationStatus(events: StreamEvent[]): {
+ label: "running" | "success" | "failed" | "retried";
+ icon: LucideIcon;
+ className: string;
+} {
+ const hasError = events.some((e) => e.type === "error");
+ const hasResult = events.some((e) => e.type === "result");
+ const hasRetry = events.some(
+ (e) => e.metadata?.trace_kind === "delegation_retry",
+ );
+ if (!hasResult && !hasError) {
+ return { label: "running", icon: Loader2, className: "text-amber-500 animate-spin" };
+ }
+ if (hasResult && !hasError) {
+ return { label: "success", icon: CircleCheck, className: "text-emerald-500" };
+ }
+ if (hasResult && hasRetry) {
+ return { label: "retried", icon: RotateCcw, className: "text-amber-500" };
+ }
+ return { label: "failed", icon: CircleX, className: "text-red-500" };
+}
+
+const DelegationCard = memo(function DelegationCard({
+ capability,
+ events,
+ isStreaming,
+ sessionId,
+ language,
+}: DelegationCardProps) {
+ const { t } = useTranslation();
+ const status = delegationStatus(events);
+ const StatusIcon = status.icon;
+
+ // The final RESULT event holds the rich payload we feed the per-capability
+ // viewer. We render the typed viewer (QuizViewer / MathAnimatorViewer / ...)
+ // inside the collapsed panel so the user can inspect the actual output.
+ const resultEvent = useMemo(
+ () => events.find((e) => e.type === "result") ?? null,
+ [events],
+ );
+
+ const quizQuestions = useMemo(() => {
+ if (capability !== "deep_question" || !resultEvent) return null;
+ return extractQuizQuestions(resultEvent.metadata);
+ }, [capability, resultEvent]);
+ const mathAnimatorResult = useMemo(() => {
+ if (capability !== "math_animator" || !resultEvent) return null;
+ return extractMathAnimatorResult(resultEvent.metadata);
+ }, [capability, resultEvent]);
+ const visualizeResult = useMemo(() => {
+ if (capability !== "visualize" || !resultEvent) return null;
+ return extractVisualizeResult(resultEvent.metadata);
+ }, [capability, resultEvent]);
+
+ // Markdown content from sub-capabilities that ship a final ``response``
+ // string (deep_solve, deep_research) is rendered as plain assistant text.
+ const markdownContent = useMemo(() => {
+ if (!resultEvent) return "";
+ if (quizQuestions || mathAnimatorResult || visualizeResult) return "";
+ const meta = resultEvent.metadata as Record<string, unknown> | undefined;
+ const response = meta?.response;
+ return typeof response === "string" ? response : "";
+ }, [resultEvent, quizQuestions, mathAnimatorResult, visualizeResult]);
+
+ // Only the sub-capability's *internal* progress/thinking events belong in
+ // the trace panel. CONTENT and RESULT are the user-facing payload — they
+ // already render via the dedicated viewer / markdown below. Including them
+ // would cause big code blocks to appear twice (once in the trace card, once
+ // in the viewer).
+ const traceableEvents = useMemo(
+ () =>
+ events.filter(
+ (e) => e.type !== "content" && e.type !== "result",
+ ),
+ [events],
+ );
+ const hasNestedTrace = useMemo(
+ () => traceableEvents.some((e) => Boolean(e.metadata?.call_id)),
+ [traceableEvents],
+ );
+
+ return (
+ <details
+ // ``open`` defaults to false (collapsed). User clicks the summary to
+ // expand. We do NOT auto-open while streaming so the chat stays compact.
+ className="group mt-2 rounded-lg border border-[var(--border)]/55 bg-[var(--muted)]/30 transition-colors"
+ >
+ <summary className="flex cursor-pointer items-center gap-2 px-3 py-2 text-[12px] text-[var(--foreground)] outline-none [&::-webkit-details-marker]:hidden">
+ <ChevronRight
+ size={12}
+ strokeWidth={2}
+ className="shrink-0 text-[var(--muted-foreground)] transition-transform group-open:rotate-90"
+ />
+ <StatusIcon size={13} strokeWidth={1.8} className={status.className} />
+ <span className="font-medium">{capability || t("(unknown)")}</span>
+ <span className="text-[11px] text-[var(--muted-foreground)]">
+ {status.label === "running"
+ ? t("running…")
+ : status.label === "retried"
+ ? t("retried")
+ : status.label === "failed"
+ ? t("failed")
+ : t("done")}
+ </span>
+ </summary>
+ <div className="space-y-2 border-t border-[var(--border)]/40 px-3 py-3">
+ {/* Sub-capability's internal trace (planning / reasoning / writing /
+ tool calls / etc.). Rendered with ``nested`` so it doesn't clash
+ with the parent shell. This is where the user can drill into the
+ sub-capability's progress instead of seeing it scattered at the
+ top of the auto turn. */}
+ {hasNestedTrace ? (
+ <CallTracePanel
+ events={traceableEvents}
+ isStreaming={isStreaming}
+ nested
+ />
+ ) : null}
+
+ {/* The sub-capability's final user-facing output. Typed viewer when
+ we recognize the result shape, otherwise plain markdown. */}
+ {quizQuestions && quizQuestions.length > 0 ? (
+ <QuizViewer
+ questions={quizQuestions}
+ sessionId={sessionId}
+ language={language}
+ />
+ ) : mathAnimatorResult ? (
+ <MathAnimatorViewer result={mathAnimatorResult} />
+ ) : visualizeResult ? (
+ <VisualizationViewer result={visualizeResult} />
+ ) : markdownContent ? (
+ <AssistantResponse content={markdownContent} />
+ ) : isStreaming ? (
+ <div className="text-[12px] text-[var(--muted-foreground)]">
+ {t("Working…")}
+ </div>
+ ) : null}
+ </div>
+ </details>
+ );
+});
+
+DelegationCard.displayName = "DelegationCard";
+
+/* -------------------------------------------------------------------------- */
+/* AutoModeAssistantMessage */
+/* -------------------------------------------------------------------------- */
+
+interface AutoModeAssistantMessageProps {
+ msg: { content: string; capability?: string; events?: StreamEvent[] };
+ isStreaming?: boolean;
+ sessionId?: string | null;
+ language?: string;
+ onRetry?: () => void;
+ onSwitchToManual?: () => void;
+}
+
+const AutoModeAssistantMessage = memo(function AutoModeAssistantMessage({
+ msg,
+ isStreaming,
+ sessionId,
+ language,
+ onRetry,
+ onSwitchToManual,
+}: AutoModeAssistantMessageProps) {
+ const { t } = useTranslation();
+ const events = useMemo(() => msg.events ?? [], [msg.events]);
+ const partition = useMemo(() => partitionEvents(events), [events]);
+
+ return (
+ <div className="space-y-1.5">
+ {partition.blocks.map((block, idx) => {
+ if (block.kind === "thought") {
+ // Inline reasoning between delegations. Use a subtle left accent
+ // instead of a boxed/italic treatment so it reads as prose, not
+ // as a trace-metadata chunk.
+ return (
+ <div
+ key={`t-${idx}`}
+ className="whitespace-pre-wrap border-l-2 border-[var(--primary)]/25 pl-3 py-0.5 text-[13px] leading-relaxed text-[var(--muted-foreground)]"
+ >
+ {block.text}
+ </div>
+ );
+ }
+ if (block.kind === "delegation") {
+ return (
+ <DelegationCard
+ key={block.callId}
+ capability={block.capability}
+ events={block.events}
+ isStreaming={isStreaming && partition.hasOpenDelegation}
+ sessionId={sessionId}
+ language={language}
+ />
+ );
+ }
+ // Final synthesis — rendered prominently as the canonical reply.
+ return <AssistantResponse key={`f-${idx}`} content={block.text} />;
+ })}
+
+ {/* Non-terminal but user-visible errors (typically an uncaught
+ orchestrator exception). Don't suppress these — without them the
+ user sees nothing when the backend fails silently. */}
+ {partition.surfacedErrors.length > 0 ? (
+ <div className="space-y-1.5">
+ {partition.surfacedErrors.map((msg, idx) => (
+ <div
+ key={`err-${idx}`}
+ className="whitespace-pre-wrap rounded-md border border-red-300/60 bg-red-50/60 px-3 py-2 text-[12.5px] text-red-700 dark:border-red-500/40 dark:bg-red-950/30 dark:text-red-200"
+ >
+ ✗ {msg}
+ </div>
+ ))}
+ </div>
+ ) : null}
+
+ {/* Streaming placeholder: while the turn is in flight but the backend
+ has not emitted anything user-visible yet, render a subtle
+ "thinking" dot so the message bubble doesn't look frozen. */}
+ {isStreaming &&
+ partition.blocks.length === 0 &&
+ partition.surfacedErrors.length === 0 &&
+ !partition.terminalError ? (
+ <div className="flex items-center gap-2 px-3 py-2 text-[12.5px] text-[var(--muted-foreground)]">
+ <span className="inline-flex h-2 w-2 animate-pulse rounded-full bg-[var(--primary)]/60" />
+ <span>{t("Thinking…")}</span>
+ </div>
+ ) : null}
+
+ {partition.terminalError ? (
+ <AutoErrorBlock
+ reason={partition.terminalError.failureReason}
+ failureMessage={partition.terminalError.failureMessage}
+ iteration={partition.terminalError.iteration}
+ routerRetries={partition.terminalError.routerRetries}
+ onRetry={onRetry}
+ onSwitchToManual={onSwitchToManual}
+ />
+ ) : null}
+ </div>
+ );
+});
+
+AutoModeAssistantMessage.displayName = "AutoModeAssistantMessage";
+
+export default AutoModeAssistantMessage;
diff --git a/web/components/chat/home/CapabilityConfigCard.tsx b/web/components/chat/home/CapabilityConfigCard.tsx
new file mode 100644
index 000000000..fd4e3b726
--- /dev/null
+++ b/web/components/chat/home/CapabilityConfigCard.tsx
@@ -0,0 +1,123 @@
+"use client";
+
+/**
+ * CapabilityConfigCard — section card hosted at the bottom of the chat
+ * Activity panel that holds the configuration form for the active
+ * capability (Quiz / Animator / Visualize / Research).
+ *
+ * The body (the actual form) is provided by the parent as children so this
+ * card stays agnostic of which fields the capability collects. The card
+ * provides the chrome: header (capability icon + label) and a confirm
+ * footer that gates message sending.
+ *
+ * Sending a message is allowed only after the user clicks *Confirm*. Any
+ * subsequent field edit invalidates the confirmation upstream (see
+ * page.tsx), restoring the Confirm button.
+ */
+
+import { memo, type ReactNode } from "react";
+import {
+ BarChart3,
+ Check,
+ Clapperboard,
+ Microscope,
+ PenLine,
+ type LucideIcon,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+export type ConfigurableCapability =
+ | "deep_question"
+ | "math_animator"
+ | "visualize"
+ | "deep_research";
+
+interface CapabilityChrome {
+ icon: LucideIcon;
+ label: string;
+}
+
+const CAPABILITY_CHROME: Record<ConfigurableCapability, CapabilityChrome> = {
+ deep_question: { icon: PenLine, label: "Quiz settings" },
+ math_animator: { icon: Clapperboard, label: "Animator settings" },
+ visualize: { icon: BarChart3, label: "Visualize settings" },
+ deep_research: { icon: Microscope, label: "Research settings" },
+};
+
+interface CapabilityConfigCardProps {
+ capability: ConfigurableCapability;
+ confirmed: boolean;
+ canConfirm: boolean;
+ validationErrors?: string[];
+ onConfirm: () => void;
+ children: ReactNode;
+}
+
+function CapabilityConfigCardInner({
+ capability,
+ confirmed,
+ canConfirm,
+ validationErrors,
+ onConfirm,
+ children,
+}: CapabilityConfigCardProps) {
+ const { t } = useTranslation();
+ const { icon: Icon, label } = CAPABILITY_CHROME[capability];
+ const hasErrors = !!validationErrors?.length;
+
+ return (
+ <section className="overflow-hidden rounded-xl border border-[var(--border)]/55 bg-[var(--card)] shadow-[0_1px_2px_color-mix(in_srgb,var(--foreground)_5%,transparent),0_4px_14px_color-mix(in_srgb,var(--foreground)_5%,transparent)]">
+ <header className="flex items-center gap-2 border-b border-[var(--border)]/35 px-3.5 py-2.5">
+ <Icon
+ size={13}
+ strokeWidth={1.8}
+ className="shrink-0 text-[var(--muted-foreground)]"
+ />
+ <span className="flex-1 text-[12px] font-semibold tracking-[0.005em] text-[var(--foreground)]">
+ {t(label)}
+ </span>
+ {confirmed ? (
+ <span className="inline-flex shrink-0 items-center gap-1 rounded-full bg-[color-mix(in_srgb,var(--primary)_12%,transparent)] px-2 py-[2px] text-[10px] font-semibold text-[var(--primary)]">
+ <Check size={10} strokeWidth={2.5} />
+ {t("Confirmed")}
+ </span>
+ ) : (
+ <span className="shrink-0 rounded-full bg-[var(--muted)]/55 px-1.5 py-[1px] text-[10px] font-semibold text-[var(--muted-foreground)]">
+ {t("Required")}
+ </span>
+ )}
+ </header>
+ {/* The form body provided by the parent (a bare ConfigPanel). */}
+ <div>{children}</div>
+ {hasErrors ? (
+ <ul className="space-y-0.5 border-t border-[var(--border)]/30 bg-[color-mix(in_srgb,var(--destructive)_8%,transparent)] px-3.5 py-2 text-[11px] text-[var(--destructive)]">
+ {validationErrors!.map((err, i) => (
+ <li key={i}>• {err}</li>
+ ))}
+ </ul>
+ ) : null}
+ <footer className="flex items-center justify-between gap-2 border-t border-[var(--border)]/35 bg-[var(--background)]/40 px-3.5 py-2">
+ <span className="min-w-0 flex-1 truncate text-[10.5px] text-[var(--muted-foreground)]/75">
+ {confirmed
+ ? t("Edit any field to update settings.")
+ : t("Confirm settings to enable sending.")}
+ </span>
+ <button
+ type="button"
+ onClick={onConfirm}
+ disabled={confirmed || !canConfirm}
+ className={`shrink-0 rounded-md px-2.5 py-1 text-[11px] font-semibold transition-[background-color,box-shadow,opacity] disabled:cursor-not-allowed ${
+ confirmed
+ ? "bg-transparent text-[var(--muted-foreground)]/45"
+ : "bg-[var(--primary)] text-white shadow-[0_2px_6px_rgba(195,90,44,0.18)] hover:shadow-[0_4px_10px_rgba(195,90,44,0.28)] disabled:bg-[var(--muted-foreground)]/15 disabled:text-[var(--muted-foreground)]/40 disabled:shadow-none"
+ }`}
+ >
+ {confirmed ? t("Confirmed") : t("Confirm")}
+ </button>
+ </footer>
+ </section>
+ );
+}
+
+const CapabilityConfigCard = memo(CapabilityConfigCardInner);
+export default CapabilityConfigCard;
diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsx
index da2381a97..b46b6afcf 100644
--- a/web/components/chat/home/ChatComposer.tsx
+++ b/web/components/chat/home/ChatComposer.tsx
@@ -1,6 +1,5 @@
"use client";
-import dynamic from "next/dynamic";
import {
memo,
useCallback,
@@ -15,10 +14,12 @@ import {
ArrowUp,
AtSign,
ChevronDown,
+ Database,
Layers,
Paperclip,
Sparkles,
Square,
+ Wrench,
X,
type LucideIcon,
} from "lucide-react";
@@ -32,15 +33,9 @@ import { useTranslation } from "react-i18next";
import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";
import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";
import type { SelectedRecord } from "@/lib/notebook-selection-types";
-import type { DeepQuestionFormConfig } from "@/lib/quiz-types";
-import type { MathAnimatorFormConfig } from "@/lib/math-animator-types";
-import type { VisualizeFormConfig } from "@/lib/visualize-types";
import type { LLMSelection } from "@/lib/unified-ws";
import type { LLMOption } from "@/lib/llm-options";
-import type {
- DeepResearchFormConfig,
- ResearchSource,
-} from "@/lib/research-types";
+import type { ResearchSource } from "@/lib/research-types";
import ChatSpaceMenu from "@/components/chat/space/ChatSpaceMenu";
import type { SpaceMemoryFile } from "@/lib/space-items";
import type { SelectedBookReference } from "@/lib/book-references";
@@ -57,25 +52,6 @@ type SpaceSelectionCounts = {
import { SpaceContextChips } from "./ChatMessages";
import { ComposerInput, type ComposerInputHandle } from "./ComposerInput";
-const QuizConfigPanel = dynamic(
- () => import("@/components/quiz/QuizConfigPanel"),
- {
- ssr: false,
- },
-);
-const MathAnimatorConfigPanel = dynamic(
- () => import("@/components/math-animator/MathAnimatorConfigPanel"),
- { ssr: false },
-);
-const ResearchConfigPanel = dynamic(
- () => import("@/components/research/ResearchConfigPanel"),
- { ssr: false },
-);
-const VisualizeConfigPanel = dynamic(
- () => import("@/components/visualize/VisualizeConfigPanel"),
- { ssr: false },
-);
-
interface PendingAttachment {
type: string;
filename: string;
@@ -117,18 +93,20 @@ export default memo(function ChatComposer({
toolBtnRef,
spaceMenuRef,
spaceBtnRef,
+ kbMenuRef,
+ kbBtnRef,
dragCounter,
dragging,
capMenuOpen,
toolMenuOpen,
spaceMenuOpen,
+ kbMenuOpen,
hasMessages,
attachments,
attachmentError,
activeCap,
visibleTools,
selectedTools,
- ragActive,
knowledgeBases,
llmOptions,
activeLLMDefault,
@@ -143,25 +121,25 @@ export default memo(function ChatComposer({
selectedSkills,
skillsAutoMode,
selectedMemoryFiles,
- stateKnowledgeBase,
+ selectedKnowledgeBases,
isStreaming,
isResearchMode,
- isQuizMode,
isMathAnimatorMode,
isVisualizeMode,
- quizConfig,
- quizPdf,
- mathAnimatorConfig,
- visualizeConfig,
- researchConfig,
- researchValidationErrors,
- panelCollapsed,
+ isAutoMode,
+ autoEnabledCaps,
+ researchConfigSources,
+ capabilityNeedsConfig,
+ capabilityConfigConfirmed,
+ onRequestConfigConfirm,
capabilities,
researchSources,
onSetCapMenuOpen,
onSetToolMenuOpen,
onSetSpaceMenuOpen,
- onSetKB,
+ onSetKbMenuOpen,
+ onToggleAutoCap,
+ onToggleKB,
onSelectLLM,
onSelectNotebookPicker,
onSelectBookPicker,
@@ -189,12 +167,6 @@ export default memo(function ChatComposer({
onAddFiles,
onSelectCapability,
onCancelStreaming,
- onChangeQuizConfig,
- onUploadQuizPdf,
- onChangeMathAnimatorConfig,
- onChangeVisualizeConfig,
- onChangeResearchConfig,
- onTogglePanelCollapsed,
}: {
composerRef: RefObject<HTMLDivElement | null>;
capMenuRef: RefObject<HTMLDivElement | null>;
@@ -203,18 +175,20 @@ export default memo(function ChatComposer({
toolBtnRef: RefObject<HTMLButtonElement | null>;
spaceMenuRef: RefObject<HTMLDivElement | null>;
spaceBtnRef: RefObject<HTMLButtonElement | null>;
+ kbMenuRef: RefObject<HTMLDivElement | null>;
+ kbBtnRef: RefObject<HTMLButtonElement | null>;
dragCounter: RefObject<number>;
dragging: boolean;
capMenuOpen: boolean;
toolMenuOpen: boolean;
spaceMenuOpen: boolean;
+ kbMenuOpen: boolean;
hasMessages: boolean;
attachments: PendingAttachment[];
attachmentError: string | null;
activeCap: CapabilityDef;
visibleTools: ToolDef[];
selectedTools: Set<string>;
- ragActive: boolean;
knowledgeBases: KnowledgeBase[];
llmOptions: LLMOption[];
activeLLMDefault: LLMSelection | null;
@@ -233,25 +207,39 @@ export default memo(function ChatComposer({
selectedSkills: string[];
skillsAutoMode: boolean;
selectedMemoryFiles: SpaceMemoryFile[];
- stateKnowledgeBase: string;
+ selectedKnowledgeBases: string[];
isStreaming: boolean;
isResearchMode: boolean;
- isQuizMode: boolean;
isMathAnimatorMode: boolean;
isVisualizeMode: boolean;
- quizConfig: DeepQuestionFormConfig;
- quizPdf: File | null;
- mathAnimatorConfig: MathAnimatorFormConfig;
- visualizeConfig: VisualizeFormConfig;
- researchConfig: DeepResearchFormConfig;
- researchValidationErrors: Record<string, string>;
- panelCollapsed: boolean;
+ isAutoMode: boolean;
+ autoEnabledCaps: Set<string>;
+ /** Sources currently selected for Research mode — rendered as inline
+ * chips next to the composer's Sources toggle. The full Research form
+ * (mode / depth / manual params) now lives in the Activity-panel config
+ * card and is not surfaced here. */
+ researchConfigSources: ResearchSource[];
+ /**
+ * True when the active capability (e.g. Quiz / Animator / Visualize /
+ * Research) requires explicit configuration before sending. When true,
+ * `canSend` is gated on `capabilityConfigConfirmed`.
+ */
+ capabilityNeedsConfig: boolean;
+ capabilityConfigConfirmed: boolean;
+ /**
+ * Called when the user clicks the send button while config is required
+ * but not yet confirmed. The page uses this to surface the config card
+ * (open the Activity panel, scroll to it, etc.).
+ */
+ onRequestConfigConfirm: () => void;
capabilities: CapabilityDef[];
researchSources: ResearchSourceDef[];
onSetCapMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;
onSetToolMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;
onSetSpaceMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;
- onSetKB: (kb: string) => void;
+ onSetKbMenuOpen: (open: boolean | ((prev: boolean) => boolean)) => void;
+ onToggleAutoCap: (cap: string) => void;
+ onToggleKB: (name: string) => void;
onSelectLLM: (selection: LLMSelection | null) => void;
onSelectNotebookPicker: () => void;
onSelectBookPicker: () => void;
@@ -279,12 +267,6 @@ export default memo(function ChatComposer({
onAddFiles: (files: File[]) => void;
onSelectCapability: (value: string) => void;
onCancelStreaming: () => void;
- onChangeQuizConfig: (next: DeepQuestionFormConfig) => void;
- onUploadQuizPdf: (file: File | null) => void;
- onChangeMathAnimatorConfig: (next: MathAnimatorFormConfig) => void;
- onChangeVisualizeConfig: (next: VisualizeFormConfig) => void;
- onChangeResearchConfig: (next: DeepResearchFormConfig) => void;
- onTogglePanelCollapsed: () => void;
}) {
const { t } = useTranslation();
const CapIcon = activeCap.icon;
@@ -294,6 +276,28 @@ export default memo(function ChatComposer({
const inputHandleRef = useRef<ComposerInputHandle>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
+ // Composer-row compaction: when the available width drops below ~620 px
+ // (e.g. the Viewer panel is open or the user is on a narrow viewport),
+ // the cap chip + Tools/Attach/Space labels collide. We measure the
+ // composer itself and flip those labels to icon-only below the
+ // threshold. Count-badges stay visible so users still see how many
+ // things are selected.
+ const [composerCompact, setComposerCompact] = useState(false);
+ useEffect(() => {
+ const el = composerRef.current;
+ if (!el || typeof ResizeObserver === "undefined") return;
+ setComposerCompact(el.getBoundingClientRect().width < 620);
+ const observer = new ResizeObserver(() => {
+ if (composerRef.current) {
+ setComposerCompact(
+ composerRef.current.getBoundingClientRect().width < 620,
+ );
+ }
+ });
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [composerRef]);
+
const handlePickFiles = useCallback(() => {
fileInputRef.current?.click();
}, []);
@@ -341,10 +345,14 @@ export default memo(function ChatComposer({
skillsAutoMode ||
!!selectedMemoryFiles.length;
+ // `capabilityNeedsConfig && !capabilityConfigConfirmed` blocks send so the
+ // user has to click *Confirm* in the right-side Activity panel first.
+ // Clicking the send button while in this state surfaces the config card
+ // (via `onRequestConfigConfirm`) instead of silently doing nothing.
+ const isConfigBlocked =
+ capabilityNeedsConfig && !capabilityConfigConfirmed;
const canSend =
- (hasContent || hasReferences) &&
- !isStreaming &&
- !(isResearchMode && Object.keys(researchValidationErrors).length > 0);
+ (hasContent || hasReferences) && !isStreaming && !isConfigBlocked;
const skillsCount = skillsAutoMode ? 1 : selectedSkills.length;
const spaceSelectionCounts: SpaceSelectionCounts = {
@@ -367,10 +375,16 @@ export default memo(function ChatComposer({
spaceSelectionCounts.memory;
const handleManualSend = useCallback(() => {
+ if (isConfigBlocked) {
+ // Don't silently fail — surface the config card so the user knows
+ // they need to confirm settings first.
+ onRequestConfigConfirm();
+ return;
+ }
if (!canSend) return;
const content = inputHandleRef.current?.getValue() || "";
doSend(content);
- }, [canSend, doSend]);
+ }, [canSend, doSend, isConfigBlocked, onRequestConfigConfirm]);
return (
<div
@@ -381,50 +395,6 @@ export default memo(function ChatComposer({
<div className="pointer-events-none absolute inset-x-0 top-0 h-6 bg-gradient-to-b from-transparent to-[var(--background)]/72" />
)}
- {capMenuOpen && (
- <div
- ref={capMenuRef}
- className="absolute bottom-full left-0 right-0 z-50 mb-1"
- >
- <div className="mx-auto">
- <div className="w-[280px] rounded-xl border border-[var(--border)] bg-[var(--popover)] py-1.5 shadow-lg backdrop-blur-md">
- {capabilities.map((cap) => {
- const Icon = cap.icon;
- const selected = activeCap.value === cap.value;
- return (
- <button
- key={cap.value}
- onClick={() => onSelectCapability(cap.value)}
- className={`flex w-full items-center gap-3 px-3.5 py-2 text-left transition-colors ${
- selected
- ? "bg-[var(--muted)]"
- : "hover:bg-[var(--muted)]/50"
- }`}
- >
- <Icon
- size={16}
- strokeWidth={1.6}
- className={`shrink-0 ${selected ? "text-[var(--primary)]" : "text-[var(--muted-foreground)]"}`}
- />
- <div className="min-w-0 flex-1">
- <div className="text-[13px] font-medium text-[var(--foreground)]">
- {t(cap.label)}
- </div>
- <div className="truncate text-[11px] text-[var(--muted-foreground)]">
- {t(cap.description)}
- </div>
- </div>
- {selected && (
- <div className="h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--primary)]" />
- )}
- </button>
- );
- })}
- </div>
- </div>
- </div>
- )}
-
<div className="relative">
<div
className={`relative rounded-2xl border bg-[var(--card)] shadow-[0_1px_8px_rgba(0,0,0,0.03)] transition-colors ${
@@ -634,24 +604,121 @@ export default memo(function ChatComposer({
<div className="border-t border-[var(--border)]/35 px-3 py-2">
<div className="flex items-center gap-2">
- <button
- ref={capBtnRef}
- onClick={() => onSetCapMenuOpen((v) => !v)}
- className={`inline-flex shrink-0 items-center gap-1.5 py-1.5 px-1 text-[12px] transition-colors ${
- capMenuOpen
- ? "text-[var(--foreground)]"
- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
- }`}
- >
- <CapIcon size={14} strokeWidth={1.6} />
- <span className="font-medium">{t(activeCap.label)}</span>
- <ChevronDown
- size={11}
- className={`transition-transform ${capMenuOpen ? "rotate-180" : ""}`}
- />
- </button>
+ <div className="relative">
+ <button
+ ref={capBtnRef}
+ onClick={() => onSetCapMenuOpen((v) => !v)}
+ className={`inline-flex ${composerCompact ? "" : "min-w-[118px]"} shrink-0 items-center justify-between gap-1.5 rounded-full border bg-[var(--card)] px-3 py-[6px] text-[13px] font-medium text-[var(--foreground)] shadow-[0_1px_2px_color-mix(in_srgb,var(--foreground)_4%,transparent)] transition-[background-color,border-color,color,box-shadow] duration-150 ${
+ capMenuOpen
+ ? "border-[var(--primary)]/45 bg-[color-mix(in_srgb,var(--primary)_7%,var(--card))] text-[var(--primary)] shadow-[0_4px_14px_color-mix(in_srgb,var(--primary)_22%,transparent)]"
+ : "border-[var(--border)]/65 hover:border-[var(--primary)]/30 hover:bg-[color-mix(in_srgb,var(--primary)_3%,var(--card))] hover:text-[var(--primary)]"
+ }`}
+ >
+ <span className="flex min-w-0 items-center gap-1.5">
+ {isAutoMode ? (
+ <>
+ <Sparkles size={15} strokeWidth={1.7} className="shrink-0" />
+ {composerCompact ? null : (
+ <span className="truncate">
+ {t("Auto Capabilities")} ({autoEnabledCaps.size})
+ </span>
+ )}
+ </>
+ ) : (
+ <>
+ <CapIcon size={15} strokeWidth={1.7} className="shrink-0" />
+ {composerCompact ? null : (
+ <span className="truncate">{t(activeCap.label)}</span>
+ )}
+ </>
+ )}
+ </span>
+ <ChevronDown
+ size={12}
+ strokeWidth={2}
+ className={`-mr-0.5 shrink-0 transition-transform duration-200 ${capMenuOpen ? "rotate-180" : ""}`}
+ />
+ </button>
- <div className="h-3.5 w-px bg-[var(--border)]/30" />
+ {capMenuOpen && (
+ <div
+ ref={capMenuRef}
+ className="dt-popup-up absolute bottom-full left-0 z-50 mb-2 w-[280px] rounded-2xl border border-[var(--border)]/70 bg-[var(--popover)] py-1.5 shadow-[0_8px_30px_color-mix(in_srgb,var(--foreground)_18%,transparent)] backdrop-blur-md"
+ >
+ {isAutoMode ? (
+ <div className="px-3.5 py-1.5 text-[11px] uppercase tracking-wide text-[var(--muted-foreground)]">
+ {t("Capabilities Auto May Use")}
+ </div>
+ ) : null}
+ {capabilities
+ .filter((cap) => (isAutoMode ? cap.value !== "" : true))
+ .map((cap) => {
+ const Icon = cap.icon;
+ const selected = isAutoMode
+ ? autoEnabledCaps.has(cap.value)
+ : activeCap.value === cap.value;
+ return (
+ <button
+ key={cap.value}
+ onClick={() =>
+ isAutoMode
+ ? onToggleAutoCap(cap.value)
+ : onSelectCapability(cap.value)
+ }
+ className={`flex w-full items-center gap-3 px-3.5 py-2 text-left transition-colors ${
+ selected && !isAutoMode
+ ? "bg-[var(--muted)]"
+ : "hover:bg-[var(--muted)]/50"
+ }`}
+ >
+ <Icon
+ size={16}
+ strokeWidth={1.6}
+ className={`shrink-0 ${selected ? "text-[var(--primary)]" : "text-[var(--muted-foreground)]"}`}
+ />
+ <div className="min-w-0 flex-1">
+ <div className="text-[13px] font-medium text-[var(--foreground)]">
+ {t(cap.label)}
+ </div>
+ <div className="truncate text-[11px] text-[var(--muted-foreground)]">
+ {t(cap.description)}
+ </div>
+ </div>
+ {isAutoMode ? (
+ <div
+ className={`flex h-4 w-4 shrink-0 items-center justify-center rounded border ${
+ selected
+ ? "border-[var(--primary)] bg-[var(--primary)]"
+ : "border-[var(--border)]"
+ }`}
+ >
+ {selected ? (
+ <svg
+ width="10"
+ height="10"
+ viewBox="0 0 10 10"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M1.5 5L4 7.5L8.5 2.5"
+ stroke="white"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ ) : null}
+ </div>
+ ) : selected ? (
+ <div className="h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--primary)]" />
+ ) : null}
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
<div className="flex min-w-0 flex-1 items-center gap-1">
{isResearchMode ? (
@@ -659,20 +726,22 @@ export default memo(function ChatComposer({
<button
ref={toolBtnRef}
onClick={() => onSetToolMenuOpen((v) => !v)}
+ title={t("Sources")}
+ aria-label={t("Sources")}
className="inline-flex shrink-0 items-center gap-1 py-1 px-1.5 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
>
<Layers size={12} strokeWidth={1.7} />
- {t("Sources")}
+ {composerCompact ? null : t("Sources")}
<ChevronDown
size={10}
className={`transition-transform ${toolMenuOpen ? "rotate-180" : ""}`}
/>
</button>
- {researchConfig.sources.length > 0 && (
+ {researchConfigSources.length > 0 && (
<div className="flex items-center gap-[3px] overflow-hidden">
{researchSources
.filter((rs) =>
- researchConfig.sources.includes(rs.name),
+ researchConfigSources.includes(rs.name),
)
.map((rs, i) => (
<span
@@ -695,7 +764,7 @@ export default memo(function ChatComposer({
className="absolute bottom-full left-0 z-50 mb-1.5 min-w-[180px] rounded-lg border border-[var(--border)] bg-[var(--popover)] py-1 shadow-lg backdrop-blur-md"
>
{researchSources.map((source) => {
- const active = researchConfig.sources.includes(
+ const active = researchConfigSources.includes(
source.name,
);
const Icon = source.icon;
@@ -729,34 +798,30 @@ export default memo(function ChatComposer({
<button
ref={toolBtnRef}
onClick={() => onSetToolMenuOpen((v) => !v)}
+ title={t("Tools")}
+ aria-label={t("Tools")}
className="inline-flex shrink-0 items-center gap-1 py-1 px-1.5 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
>
- <Sparkles size={12} strokeWidth={1.7} />
- {t("Tools")}
+ <Wrench size={12} strokeWidth={1.7} />
+ <span className="inline-flex items-baseline">
+ {composerCompact ? null : t("Tools")}
+ {selectedTools.size > 0 && (
+ // Active-count badge attached to the bottom-right of
+ // the "Tools" label. Inline-flow + a small downward
+ // translate sits the pill at the label's baseline
+ // rather than centred on it, so the characters of
+ // "Tools" stay fully visible while the badge still
+ // reads as "anchored to the word".
+ <span className="ml-1 flex h-[13px] min-w-[13px] translate-y-[3px] items-center justify-center rounded-full bg-[var(--primary)] px-[3px] text-[8px] font-semibold leading-none text-white shadow-[0_1px_3px_color-mix(in_srgb,var(--primary)_35%,transparent)] ring-[1.5px] ring-[var(--card)]">
+ {selectedTools.size}
+ </span>
+ )}
+ </span>
<ChevronDown
size={10}
className={`transition-transform ${toolMenuOpen ? "rotate-180" : ""}`}
/>
</button>
- {selectedTools.size > 0 && (
- <div className="flex items-center gap-[3px] overflow-hidden">
- {visibleTools
- .filter((vt) => selectedTools.has(vt.name))
- .map((vt, i) => (
- <span
- key={vt.name}
- className="shrink-0 text-[10px] text-[var(--muted-foreground)]/35"
- >
- {i > 0 && (
- <span className="text-[12px] leading-none">
- ·
- </span>
- )}
- {t(vt.label)}
- </span>
- ))}
- </div>
- )}
{toolMenuOpen && (
<div
ref={toolMenuRef}
@@ -798,28 +863,102 @@ export default memo(function ChatComposer({
className="inline-flex shrink-0 items-center gap-1 py-1 px-1.5 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
>
<Paperclip size={12} strokeWidth={1.7} />
- {t("Attach")}
+ <span className="inline-flex items-baseline">
+ {composerCompact ? null : t("Attach")}
+ {attachments.length > 0 && (
+ <span className="ml-1 flex h-[13px] min-w-[13px] translate-y-[3px] items-center justify-center rounded-full bg-[var(--primary)] px-[3px] text-[8px] font-semibold leading-none text-white shadow-[0_1px_3px_color-mix(in_srgb,var(--primary)_35%,transparent)] ring-[1.5px] ring-[var(--card)]">
+ {attachments.length}
+ </span>
+ )}
+ </span>
</button>
+ <div className="relative flex items-center gap-0.5">
+ <button
+ ref={kbBtnRef}
+ type="button"
+ onClick={() => onSetKbMenuOpen((v) => !v)}
+ disabled={knowledgeBases.length === 0}
+ title={
+ knowledgeBases.length === 0
+ ? t("No knowledge bases available")
+ : t("Attach knowledge bases")
+ }
+ className={`inline-flex shrink-0 items-center gap-1 py-1 px-1.5 text-[11px] font-medium transition-colors ${
+ knowledgeBases.length === 0
+ ? "cursor-not-allowed text-[var(--border)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ <Database size={12} strokeWidth={1.7} />
+ <span className="inline-flex items-baseline">
+ {composerCompact ? null : t("Knowledge")}
+ {selectedKnowledgeBases.length > 0 && (
+ <span className="ml-1 flex h-[13px] min-w-[13px] translate-y-[3px] items-center justify-center rounded-full bg-[var(--primary)] px-[3px] text-[8px] font-semibold leading-none text-white shadow-[0_1px_3px_color-mix(in_srgb,var(--primary)_35%,transparent)] ring-[1.5px] ring-[var(--card)]">
+ {selectedKnowledgeBases.length}
+ </span>
+ )}
+ </span>
+ <ChevronDown
+ size={10}
+ className={`transition-transform ${kbMenuOpen ? "rotate-180" : ""}`}
+ />
+ </button>
+ {kbMenuOpen && knowledgeBases.length > 0 && (
+ <div
+ ref={kbMenuRef}
+ className="absolute bottom-full left-0 z-50 mb-1.5 max-h-[260px] min-w-[200px] max-w-[280px] overflow-y-auto rounded-lg border border-[var(--border)] bg-[var(--popover)] py-1 shadow-lg backdrop-blur-md"
+ >
+ {knowledgeBases.map((kb) => {
+ const active = selectedKnowledgeBases.includes(kb.name);
+ return (
+ <button
+ key={kb.name}
+ type="button"
+ onClick={() => onToggleKB(kb.name)}
+ className={`flex w-full items-center gap-2.5 px-3 py-1.5 text-left text-[12px] transition-colors ${
+ active
+ ? "text-[var(--primary)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ } hover:bg-[var(--muted)]/40`}
+ >
+ <Database size={13} strokeWidth={1.7} />
+ <span className="flex-1 truncate font-medium">
+ {kb.name}
+ </span>
+ {active && (
+ <div className="h-1.5 w-1.5 rounded-full bg-[var(--primary)]" />
+ )}
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
+
<div className="relative flex items-center gap-0.5">
<button
ref={spaceBtnRef}
type="button"
onClick={() => onSetSpaceMenuOpen((v) => !v)}
+ title={t("Space")}
+ aria-label={t("Space")}
className="inline-flex shrink-0 items-center gap-1 py-1 px-1.5 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
>
<AtSign size={12} strokeWidth={1.7} />
- {t("Space")}
+ <span className="inline-flex items-baseline">
+ {composerCompact ? null : t("Space")}
+ {spaceSelectionCount > 0 && (
+ <span className="ml-1 flex h-[13px] min-w-[13px] translate-y-[3px] items-center justify-center rounded-full bg-[var(--primary)] px-[3px] text-[8px] font-semibold leading-none text-white shadow-[0_1px_3px_color-mix(in_srgb,var(--primary)_35%,transparent)] ring-[1.5px] ring-[var(--card)]">
+ {spaceSelectionCount}
+ </span>
+ )}
+ </span>
<ChevronDown
size={10}
className={`transition-transform ${spaceMenuOpen ? "rotate-180" : ""}`}
/>
</button>
- {spaceSelectionCount > 0 && (
- <span className="shrink-0 rounded-full bg-[var(--primary)]/10 px-1.5 py-px text-[9px] font-semibold text-[var(--primary)]">
- {spaceSelectionCount}
- </span>
- )}
{spaceMenuOpen && (
<div
ref={spaceMenuRef}
@@ -855,36 +994,6 @@ export default memo(function ChatComposer({
onChange={onSelectLLM}
/>
- <select
- value={stateKnowledgeBase}
- onChange={(e) => onSetKB(e.target.value)}
- disabled={!ragActive}
- title={
- ragActive
- ? t("Select Knowledge Base")
- : t("Enable Knowledge Base source first")
- }
- className={`h-[28px] appearance-none rounded-full border bg-transparent py-0 pl-2.5 pr-5 text-[11px] outline-none transition-colors ${
- ragActive
- ? "cursor-pointer border-[var(--border)]/40 text-[var(--muted-foreground)] hover:border-[var(--border)] hover:text-[var(--foreground)]"
- : "cursor-not-allowed border-transparent text-[var(--border)]"
- }`}
- style={{
- backgroundImage: ragActive
- ? "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 24 24' fill='none' stroke='%239ca3af' stroke-width='2'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E\")"
- : "none",
- backgroundRepeat: "no-repeat",
- backgroundPosition: "right 6px center",
- }}
- >
- <option value="">{ragActive ? t("No KB") : "—"}</option>
- {knowledgeBases.map((kb) => (
- <option key={kb.name} value={kb.name}>
- {kb.name}
- </option>
- ))}
- </select>
-
{isStreaming ? (
<button
type="button"
@@ -905,11 +1014,30 @@ export default memo(function ChatComposer({
/>
</button>
) : (
+ // When the active capability needs an unconfirmed config,
+ // we keep the button clickable (so a click can surface
+ // the Activity-panel config card via
+ // `onRequestConfigConfirm`) but only once the user has
+ // *intent* (typed text or queued references). Without
+ // intent, the button stays disabled so an empty-state
+ // composer doesn't have a "live" send button.
<button
type="button"
onClick={handleManualSend}
- disabled={!canSend}
- className="rounded-full bg-[var(--primary)] p-[7px] text-white shadow-[0_4px_12px_rgba(195,90,44,0.15)] transition-[transform,opacity,box-shadow] hover:shadow-[0_6px_16px_rgba(195,90,44,0.22)] disabled:opacity-25 disabled:shadow-none"
+ disabled={
+ !(hasContent || hasReferences) || isStreaming
+ }
+ title={
+ isConfigBlocked
+ ? t("Confirm settings on the right to send.")
+ : 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 ${
+ 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)]"
+ }`}
aria-label={t("Send")}
>
<ArrowUp size={15} strokeWidth={2.5} />
@@ -918,46 +1046,6 @@ export default memo(function ChatComposer({
</div>
</div>
</div>
-
- {(isQuizMode ||
- isMathAnimatorMode ||
- isVisualizeMode ||
- isResearchMode) && (
- <div className="border-t border-[var(--border)]/15">
- {isQuizMode ? (
- <QuizConfigPanel
- value={quizConfig}
- onChange={onChangeQuizConfig}
- uploadedPdf={quizPdf}
- onUploadPdf={onUploadQuizPdf}
- collapsed={panelCollapsed}
- onToggleCollapsed={onTogglePanelCollapsed}
- />
- ) : isMathAnimatorMode ? (
- <MathAnimatorConfigPanel
- value={mathAnimatorConfig}
- onChange={onChangeMathAnimatorConfig}
- collapsed={panelCollapsed}
- onToggleCollapsed={onTogglePanelCollapsed}
- />
- ) : isVisualizeMode ? (
- <VisualizeConfigPanel
- value={visualizeConfig}
- onChange={onChangeVisualizeConfig}
- collapsed={panelCollapsed}
- onToggleCollapsed={onTogglePanelCollapsed}
- />
- ) : (
- <ResearchConfigPanel
- value={researchConfig}
- errors={researchValidationErrors}
- collapsed={panelCollapsed}
- onChange={onChangeResearchConfig}
- onToggleCollapsed={onTogglePanelCollapsed}
- />
- )}
- </div>
- )}
</div>
</div>
</div>
diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsx
index cbb9b9a59..d8bb3d797 100644
--- a/web/components/chat/home/ChatMessages.tsx
+++ b/web/components/chat/home/ChatMessages.tsx
@@ -32,7 +32,8 @@ import type { StreamEvent } from "@/lib/unified-ws";
import { hasVisibleMarkdownContent } from "@/lib/markdown-display";
import type { SelectedBookReference } from "@/lib/book-references";
import type { SpaceMemoryFile } from "@/lib/space-items";
-import { CallTracePanel } from "./TracePanels";
+import AutoModeAssistantMessage from "./AutoModeAssistantMessage";
+import { TraceSurface } from "./TracePanels";
const MathAnimatorViewer = dynamic(
() => import("@/components/math-animator/MathAnimatorViewer"),
@@ -103,6 +104,8 @@ const AssistantMessage = memo(function AssistantMessage({
language,
onConfirmOutline,
onAnswerNow,
+ onRetry,
+ onSwitchToManual,
}: {
msg: { content: string; capability?: string; events?: StreamEvent[] };
isStreaming?: boolean;
@@ -115,12 +118,11 @@ const AssistantMessage = memo(function AssistantMessage({
researchConfig?: Record<string, unknown> | null,
) => void;
onAnswerNow?: () => void;
+ onRetry?: () => void;
+ onSwitchToManual?: () => void;
}) {
+ const isAutoTurn = msg.capability === "auto";
const events = useMemo(() => msg.events ?? [], [msg.events]);
- const hasCallTrace = useMemo(
- () => events.some((event) => Boolean(event.metadata?.call_id)),
- [events],
- );
const resultEvent = useMemo(
() => msg.events?.find((event) => event.type === "result") ?? null,
[msg.events],
@@ -158,11 +160,38 @@ const AssistantMessage = memo(function AssistantMessage({
return extractVisualizeResult(resultEvent.metadata);
}, [msg.capability, resultEvent]);
+ // Auto turns have a fundamentally different layout (interleaved
+ // thinking + collapsed delegation cards + final synthesis). Each sub-
+ // capability's internal trace is rendered INSIDE its delegation card —
+ // we deliberately do NOT show a top-level CallTracePanel here, because
+ // grouping by ``call_id`` would mix auto-level routing trace with each
+ // sub-capability's stages and produce the visual noise this layout was
+ // meant to avoid.
+ if (isAutoTurn) {
+ return (
+ <>
+ {isStreaming && onAnswerNow ? (
+ <AnswerNowRow onAnswerNow={onAnswerNow} />
+ ) : null}
+ <AutoModeAssistantMessage
+ msg={msg}
+ isStreaming={isStreaming}
+ sessionId={sessionId}
+ language={language}
+ onRetry={onRetry}
+ onSwitchToManual={onSwitchToManual}
+ />
+ </>
+ );
+ }
+
return (
<>
- {hasCallTrace ? (
- <CallTracePanel events={events} isStreaming={isStreaming} />
- ) : null}
+ <TraceSurface
+ events={events}
+ isStreaming={isStreaming}
+ content={msg.content}
+ />
{isStreaming && onAnswerNow ? (
<AnswerNowRow onAnswerNow={onAnswerNow} />
) : null}
@@ -656,6 +685,7 @@ export const ChatMessageList = memo(function ChatMessageList({
onRegenerateMessage,
onConfirmOutline,
onPreviewAttachment,
+ onSwitchToManualMode,
}: {
messages: ChatMessageItem[];
isStreaming: boolean;
@@ -673,6 +703,10 @@ export const ChatMessageList = memo(function ChatMessageList({
researchConfig?: Record<string, unknown> | null,
) => void;
onPreviewAttachment?: (attachment: MessageAttachment) => void;
+ // Only used by auto-turn ``AutoErrorBlock`` to surface a "back to manual"
+ // button after a terminal failure. Optional so non-auto chat surfaces don't
+ // have to wire it.
+ onSwitchToManualMode?: () => void;
}) {
const { t } = useTranslation();
const outlineStatusByIndex = useMemo(() => {
@@ -805,6 +839,8 @@ export const ChatMessageList = memo(function ChatMessageList({
language={language}
onConfirmOutline={onConfirmOutline}
onAnswerNow={handleTraceAnswerNow}
+ onRetry={onRegenerateMessage}
+ onSwitchToManual={onSwitchToManualMode}
/>
{(showActions || costSummary) && (
<div className="mt-2 flex items-center">
diff --git a/web/components/chat/home/SessionActivityPanel.tsx b/web/components/chat/home/SessionActivityPanel.tsx
new file mode 100644
index 000000000..7232766fc
--- /dev/null
+++ b/web/components/chat/home/SessionActivityPanel.tsx
@@ -0,0 +1,666 @@
+"use client";
+
+/**
+ * SessionActivityPanel — right-side column of *floating cards* recording
+ * the conversation's tools, knowledge bases, Space refs, and attachments.
+ *
+ * Design notes
+ * ────────────
+ * • The panel itself has **no background** — cards float over the page so
+ * the chat surface still bleeds through. Each card carries its own border
+ * + faint shadow so it reads as a discrete block.
+ * • Clicking an attachment row fires `onOpenAttachment(att)` upward; the
+ * parent routes it into the SessionViewerPanel as a new file tab.
+ * • Section content is suppressed entirely when empty — no skeleton cards
+ * for tools/KBs/Space/attachments that never showed up in this session.
+ */
+
+import {
+ memo,
+ useEffect,
+ useState,
+ type ReactNode,
+} from "react";
+import Link from "next/link";
+import {
+ AtSign,
+ BookOpen,
+ Brain,
+ ClipboardList,
+ Database,
+ ExternalLink,
+ History,
+ NotebookPen,
+ Paperclip,
+ Wand2,
+ Wrench,
+ type LucideIcon,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { docIconFor, isSvgFilename } from "@/lib/doc-attachments";
+import type {
+ MessageAttachment,
+ MessageItem,
+ MessageRequestSnapshot,
+} from "@/context/UnifiedChatContext";
+import type { StreamEvent } from "@/lib/unified-ws";
+import { listSessions, type SessionSummary } from "@/lib/session-api";
+import { listNotebooks, type NotebookSummary } from "@/lib/notebook-api";
+import { bookApi } from "@/lib/book-api";
+import type { Book } from "@/lib/book-types";
+
+/* ------------------------------------------------------------------ */
+/* Aggregator */
+/* ------------------------------------------------------------------ */
+
+export interface ToolUsage {
+ name: string;
+ count: number;
+}
+
+export interface AttachmentWithOrigin {
+ messageIndex: number;
+ attachment: MessageAttachment;
+}
+
+export interface SpaceReferenceSummary {
+ historySessionIds: string[];
+ bookPageCount: number;
+ bookIds: string[];
+ bookPages: Map<string, string[]>;
+ notebookRecordCount: number;
+ notebookIds: string[];
+ questionEntryIds: number[];
+ skills: string[];
+ memoryKinds: Array<"summary" | "profile">;
+}
+
+export interface SessionActivity {
+ tools: ToolUsage[];
+ knowledgeBases: string[];
+ space: SpaceReferenceSummary;
+ attachments: AttachmentWithOrigin[];
+ isEmpty: boolean;
+}
+
+export function buildSessionActivity(messages: MessageItem[]): SessionActivity {
+ const toolCounts = new Map<string, number>();
+ const kbs = new Set<string>();
+ const historySessionIds = new Set<string>();
+ const bookIds = new Set<string>();
+ const bookPages = new Map<string, string[]>();
+ let bookPageCount = 0;
+ const notebookIds = new Set<string>();
+ let notebookRecordCount = 0;
+ const questionEntryIds = new Set<number>();
+ const skills = new Set<string>();
+ const memoryKinds = new Set<"summary" | "profile">();
+ const attachments: AttachmentWithOrigin[] = [];
+
+ messages.forEach((msg, idx) => {
+ msg.events?.forEach((event: StreamEvent) => {
+ if (event.type !== "tool_call") return;
+ const name =
+ String((event.metadata as { tool?: string } | undefined)?.tool || "") ||
+ event.content?.trim() ||
+ "tool";
+ toolCounts.set(name, (toolCounts.get(name) ?? 0) + 1);
+ });
+
+ msg.attachments?.forEach((a) => {
+ attachments.push({ messageIndex: idx, attachment: a });
+ });
+
+ const snap: MessageRequestSnapshot | undefined = msg.requestSnapshot;
+ if (snap) {
+ snap.knowledgeBases?.forEach((k) => kbs.add(k));
+ snap.historyReferences?.forEach((s) => historySessionIds.add(s));
+ snap.bookReferences?.forEach((b) => {
+ bookIds.add(b.book_id);
+ bookPageCount += b.page_ids?.length ?? 0;
+ const existing = bookPages.get(b.book_id) ?? [];
+ bookPages.set(b.book_id, [...existing, ...(b.page_ids ?? [])]);
+ });
+ snap.notebookReferences?.forEach((n) => {
+ notebookIds.add(n.notebook_id);
+ notebookRecordCount += n.record_ids?.length ?? 0;
+ });
+ snap.questionNotebookReferences?.forEach((q) => questionEntryIds.add(q));
+ snap.skills?.forEach((s) => skills.add(s));
+ snap.memoryReferences?.forEach((k) => memoryKinds.add(k));
+ }
+ });
+
+ const tools = Array.from(toolCounts.entries())
+ .map(([name, count]) => ({ name, count }))
+ .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
+
+ const space: SpaceReferenceSummary = {
+ historySessionIds: Array.from(historySessionIds),
+ bookPageCount,
+ bookIds: Array.from(bookIds),
+ bookPages,
+ notebookRecordCount,
+ notebookIds: Array.from(notebookIds),
+ questionEntryIds: Array.from(questionEntryIds),
+ skills: Array.from(skills),
+ memoryKinds: Array.from(memoryKinds),
+ };
+
+ const isEmpty =
+ tools.length === 0 &&
+ kbs.size === 0 &&
+ attachments.length === 0 &&
+ space.historySessionIds.length === 0 &&
+ space.bookIds.length === 0 &&
+ space.notebookIds.length === 0 &&
+ space.questionEntryIds.length === 0 &&
+ space.skills.length === 0 &&
+ space.memoryKinds.length === 0;
+
+ return {
+ tools,
+ knowledgeBases: Array.from(kbs),
+ space,
+ attachments,
+ isEmpty,
+ };
+}
+
+/* ------------------------------------------------------------------ */
+/* Title resolver — lazy id -> title for Space items */
+/* ------------------------------------------------------------------ */
+
+interface ResolvedTitles {
+ sessions: Map<string, string>;
+ notebooks: Map<string, string>;
+ books: Map<string, string>;
+}
+
+function useResolvedTitles(
+ activity: SessionActivity,
+ open: boolean,
+): ResolvedTitles {
+ const [sessions, setSessions] = useState<Map<string, string>>(new Map());
+ const [notebooks, setNotebooks] = useState<Map<string, string>>(new Map());
+ const [books, setBooks] = useState<Map<string, string>>(new Map());
+
+ const needsSessions = activity.space.historySessionIds.length > 0;
+ const needsNotebooks = activity.space.notebookIds.length > 0;
+ const needsBooks = activity.space.bookIds.length > 0;
+
+ useEffect(() => {
+ if (!open || !needsSessions || sessions.size > 0) return;
+ let cancelled = false;
+ listSessions(200)
+ .then((rows: SessionSummary[]) => {
+ if (cancelled) return;
+ const map = new Map<string, string>();
+ rows.forEach((r) => map.set(r.session_id, r.title || r.session_id));
+ setSessions(map);
+ })
+ .catch(() => {});
+ return () => {
+ cancelled = true;
+ };
+ }, [open, needsSessions, sessions.size]);
+
+ useEffect(() => {
+ if (!open || !needsNotebooks || notebooks.size > 0) return;
+ let cancelled = false;
+ listNotebooks()
+ .then((rows: NotebookSummary[]) => {
+ if (cancelled) return;
+ const map = new Map<string, string>();
+ rows.forEach((r) => map.set(r.id, r.name || r.id));
+ setNotebooks(map);
+ })
+ .catch(() => {});
+ return () => {
+ cancelled = true;
+ };
+ }, [open, needsNotebooks, notebooks.size]);
+
+ useEffect(() => {
+ if (!open || !needsBooks || books.size > 0) return;
+ let cancelled = false;
+ bookApi
+ .list()
+ .then(({ books: rows }: { books: Book[] }) => {
+ if (cancelled) return;
+ const map = new Map<string, string>();
+ rows.forEach((r) => map.set(r.id, r.title || r.id));
+ setBooks(map);
+ })
+ .catch(() => {});
+ return () => {
+ cancelled = true;
+ };
+ }, [open, needsBooks, books.size]);
+
+ return { sessions, notebooks, books };
+}
+
+/* ------------------------------------------------------------------ */
+/* Panel shell */
+/* ------------------------------------------------------------------ */
+
+interface SessionActivityPanelProps {
+ open: boolean;
+ activity: SessionActivity;
+ onOpenAttachment: (a: MessageAttachment) => void;
+ /**
+ * Optional capability-config card (Quiz / Animator / Visualize / Research
+ * settings) appended below the standard activity sections. Built by the
+ * page when the active capability requires manual configuration before
+ * sending. See `CapabilityConfigCard` and `page.tsx`.
+ */
+ configSection?: ReactNode;
+}
+
+function SessionActivityPanelInner({
+ open,
+ activity,
+ onOpenAttachment,
+ configSection,
+}: SessionActivityPanelProps) {
+ return (
+ <aside
+ aria-hidden={!open}
+ className={`pointer-events-none fixed inset-y-0 right-0 z-[25] flex w-full max-w-[320px] flex-col overflow-hidden transition-transform duration-[220ms] ease-out ${
+ open ? "translate-x-0" : "translate-x-full"
+ }`}
+ >
+ <div
+ className={`pointer-events-auto h-full overflow-y-auto pl-3 pr-3 pt-3 pb-6 ${
+ open ? "" : "pointer-events-none"
+ }`}
+ >
+ <ActivityBody
+ activity={activity}
+ open={open}
+ onOpenAttachment={onOpenAttachment}
+ configSection={configSection}
+ />
+ </div>
+ </aside>
+ );
+}
+
+const SessionActivityPanel = memo(SessionActivityPanelInner);
+export default SessionActivityPanel;
+
+/* ------------------------------------------------------------------ */
+/* Activity body */
+/* ------------------------------------------------------------------ */
+
+interface SpaceCategoryDef {
+ key: string;
+ href: string;
+ label: string;
+ icon: LucideIcon;
+}
+
+const SPACE_CATEGORIES: Record<string, SpaceCategoryDef> = {
+ chat_history: {
+ key: "chat_history",
+ href: "/space/chat-history",
+ label: "Chat history",
+ icon: History,
+ },
+ books: {
+ key: "books",
+ href: "/space/books",
+ label: "Books",
+ icon: BookOpen,
+ },
+ notebooks: {
+ key: "notebooks",
+ href: "/space/notebooks",
+ label: "Notebooks",
+ icon: NotebookPen,
+ },
+ question_bank: {
+ key: "question_bank",
+ href: "/space/questions",
+ label: "Question bank",
+ icon: ClipboardList,
+ },
+ skills: {
+ key: "skills",
+ href: "/space/skills",
+ label: "Skills",
+ icon: Wand2,
+ },
+ memory: {
+ key: "memory",
+ href: "/space/memory",
+ label: "Memory",
+ icon: Brain,
+ },
+};
+
+function ActivityBody({
+ activity,
+ open,
+ onOpenAttachment,
+ configSection,
+}: {
+ activity: SessionActivity;
+ open: boolean;
+ onOpenAttachment: (a: MessageAttachment) => void;
+ configSection?: ReactNode;
+}) {
+ const { t } = useTranslation();
+ const { tools, knowledgeBases, space, attachments } = activity;
+ const { sessions, notebooks, books } = useResolvedTitles(activity, open);
+
+ const spaceSubsections: ReactNode[] = [];
+ if (space.historySessionIds.length > 0) {
+ spaceSubsections.push(
+ <SpaceSubsection
+ key="chat_history"
+ category={SPACE_CATEGORIES.chat_history}
+ count={space.historySessionIds.length}
+ >
+ {space.historySessionIds.map((id) => (
+ <SpaceItemRow
+ key={id}
+ title={sessions.get(id) ?? id}
+ subtitle={id.slice(0, 8)}
+ />
+ ))}
+ </SpaceSubsection>,
+ );
+ }
+ if (space.bookIds.length > 0) {
+ spaceSubsections.push(
+ <SpaceSubsection
+ key="books"
+ category={SPACE_CATEGORIES.books}
+ count={space.bookIds.length}
+ >
+ {space.bookIds.map((id) => {
+ const pages = space.bookPages.get(id)?.length ?? 0;
+ return (
+ <SpaceItemRow
+ key={id}
+ title={books.get(id) ?? id}
+ subtitle={t("{{n}} page(s)", { n: pages })}
+ />
+ );
+ })}
+ </SpaceSubsection>,
+ );
+ }
+ if (space.notebookIds.length > 0) {
+ spaceSubsections.push(
+ <SpaceSubsection
+ key="notebooks"
+ category={SPACE_CATEGORIES.notebooks}
+ count={space.notebookIds.length}
+ >
+ {space.notebookIds.map((id) => (
+ <SpaceItemRow key={id} title={notebooks.get(id) ?? id} />
+ ))}
+ </SpaceSubsection>,
+ );
+ }
+ if (space.questionEntryIds.length > 0) {
+ spaceSubsections.push(
+ <SpaceSubsection
+ key="question_bank"
+ category={SPACE_CATEGORIES.question_bank}
+ count={space.questionEntryIds.length}
+ >
+ {space.questionEntryIds.map((id) => (
+ <SpaceItemRow key={id} title={t("Question #{{n}}", { n: id })} />
+ ))}
+ </SpaceSubsection>,
+ );
+ }
+ if (space.skills.length > 0) {
+ spaceSubsections.push(
+ <SpaceSubsection
+ key="skills"
+ category={SPACE_CATEGORIES.skills}
+ count={space.skills.length}
+ >
+ {space.skills.map((skill) => (
+ <SpaceItemRow key={skill} title={skill} />
+ ))}
+ </SpaceSubsection>,
+ );
+ }
+ if (space.memoryKinds.length > 0) {
+ spaceSubsections.push(
+ <SpaceSubsection
+ key="memory"
+ category={SPACE_CATEGORIES.memory}
+ count={space.memoryKinds.length}
+ >
+ {space.memoryKinds.map((kind) => (
+ <SpaceItemRow key={kind} title={kind} />
+ ))}
+ </SpaceSubsection>,
+ );
+ }
+
+ if (activity.isEmpty && !configSection) {
+ return (
+ <SectionCard icon={Wrench} title={t("Session activity")}>
+ <div className="px-3.5 py-5 text-center text-[12px] italic text-[var(--muted-foreground)]/80">
+ {t(
+ "As you chat, the tools, references and attachments you use will appear here.",
+ )}
+ </div>
+ </SectionCard>
+ );
+ }
+
+ return (
+ <div className="space-y-2.5">
+ {tools.length > 0 ? (
+ <SectionCard
+ icon={Wrench}
+ title={t("Tools used")}
+ count={tools.length}
+ >
+ <ul className="space-y-0.5 p-1.5">
+ {tools.map((tool) => (
+ <li
+ key={tool.name}
+ className="flex items-center justify-between gap-2 rounded-md px-2 py-1.5 text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/35"
+ >
+ <span className="truncate font-medium">{tool.name}</span>
+ <span className="shrink-0 rounded-full bg-[var(--muted)]/55 px-1.5 py-[1px] text-[10px] font-semibold text-[var(--muted-foreground)]">
+ ×{tool.count}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </SectionCard>
+ ) : null}
+
+ {knowledgeBases.length > 0 ? (
+ <SectionCard
+ icon={Database}
+ title={t("Knowledge bases")}
+ count={knowledgeBases.length}
+ >
+ <ul className="space-y-0.5 p-1.5">
+ {knowledgeBases.map((kb) => (
+ <li
+ key={kb}
+ className="truncate rounded-md px-2 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/35"
+ >
+ {kb}
+ </li>
+ ))}
+ </ul>
+ </SectionCard>
+ ) : null}
+
+ {spaceSubsections.length > 0 ? (
+ <SectionCard icon={AtSign} title={t("Space")}>
+ <div className="space-y-1.5 p-1.5">{spaceSubsections}</div>
+ </SectionCard>
+ ) : null}
+
+ {attachments.length > 0 ? (
+ <SectionCard
+ icon={Paperclip}
+ title={t("Attachments")}
+ count={attachments.length}
+ >
+ <ul className="space-y-0.5 p-1.5">
+ {attachments.map(({ attachment, messageIndex }, i) => (
+ <AttachmentRow
+ key={`${attachment.id ?? attachment.filename ?? i}-${messageIndex}`}
+ attachment={attachment}
+ onOpen={() => onOpenAttachment(attachment)}
+ />
+ ))}
+ </ul>
+ </SectionCard>
+ ) : null}
+
+ {configSection}
+ </div>
+ );
+}
+
+/* ------------------------------------------------------------------ */
+/* Card primitives */
+/* ------------------------------------------------------------------ */
+
+function SectionCard({
+ icon: Icon,
+ title,
+ count,
+ children,
+}: {
+ icon: LucideIcon;
+ title: string;
+ count?: number;
+ children: ReactNode;
+}) {
+ return (
+ <section className="overflow-hidden rounded-xl border border-[var(--border)]/55 bg-[var(--card)] shadow-[0_1px_2px_color-mix(in_srgb,var(--foreground)_5%,transparent),0_4px_14px_color-mix(in_srgb,var(--foreground)_5%,transparent)]">
+ <header className="flex items-center gap-2 border-b border-[var(--border)]/35 px-3.5 py-2.5">
+ <Icon
+ size={13}
+ strokeWidth={1.8}
+ className="shrink-0 text-[var(--muted-foreground)]"
+ />
+ <span className="flex-1 text-[12px] font-semibold tracking-[0.005em] text-[var(--foreground)]">
+ {title}
+ </span>
+ {count !== undefined && count > 0 ? (
+ <span className="shrink-0 rounded-full bg-[var(--muted)]/55 px-1.5 py-[1px] text-[10px] font-semibold text-[var(--muted-foreground)]">
+ {count}
+ </span>
+ ) : null}
+ </header>
+ {children}
+ </section>
+ );
+}
+
+function SpaceSubsection({
+ category,
+ count,
+ children,
+}: {
+ category: SpaceCategoryDef;
+ count: number;
+ children: ReactNode;
+}) {
+ const Icon = category.icon;
+ return (
+ <div>
+ <Link
+ href={category.href}
+ className="group flex items-center gap-2 rounded-md px-2 py-1 transition-colors hover:bg-[var(--muted)]/40"
+ >
+ <Icon
+ size={12}
+ strokeWidth={1.8}
+ className="shrink-0 text-[var(--muted-foreground)]"
+ />
+ <span className="flex-1 truncate text-[10.5px] font-semibold uppercase tracking-[0.06em] text-[var(--muted-foreground)] transition-colors group-hover:text-[var(--primary)]">
+ {category.label}
+ </span>
+ <span className="rounded-full bg-[var(--muted)]/55 px-1.5 py-[1px] text-[10px] font-semibold text-[var(--muted-foreground)]">
+ {count}
+ </span>
+ <ExternalLink
+ size={10}
+ strokeWidth={2}
+ className="shrink-0 text-[var(--muted-foreground)] opacity-0 transition-opacity group-hover:opacity-100"
+ />
+ </Link>
+ <ul className="mt-0.5 space-y-px pl-5">{children}</ul>
+ </div>
+ );
+}
+
+function SpaceItemRow({
+ title,
+ subtitle,
+}: {
+ title: string;
+ subtitle?: string;
+}) {
+ return (
+ <li className="flex items-center gap-2 rounded-md px-2 py-1 text-[12px] transition-colors hover:bg-[var(--muted)]/35">
+ <span className="block min-w-0 flex-1 truncate font-medium text-[var(--foreground)]">
+ {title}
+ </span>
+ {subtitle ? (
+ <span className="shrink-0 text-[10px] text-[var(--muted-foreground)]">
+ {subtitle}
+ </span>
+ ) : null}
+ </li>
+ );
+}
+
+function AttachmentRow({
+ attachment,
+ onOpen,
+}: {
+ attachment: MessageAttachment;
+ onOpen: () => void;
+}) {
+ const filename = attachment.filename || "untitled";
+ const spec = docIconFor(filename);
+ const Icon = spec.Icon;
+ const isImage = attachment.type === "image" || isSvgFilename(filename);
+
+ return (
+ <li>
+ <button
+ type="button"
+ onClick={onOpen}
+ className="flex w-full items-center gap-2.5 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-[var(--muted)]/35"
+ >
+ <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-[var(--muted)]/55">
+ <Icon
+ size={13}
+ strokeWidth={1.6}
+ className={isImage ? "text-[var(--muted-foreground)]" : spec.tint}
+ />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[12px] font-medium text-[var(--foreground)]">
+ {filename}
+ </span>
+ <span className="block truncate text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">
+ {spec.label}
+ </span>
+ </span>
+ </button>
+ </li>
+ );
+}
diff --git a/web/components/chat/home/SessionViewerPanel.tsx b/web/components/chat/home/SessionViewerPanel.tsx
new file mode 100644
index 000000000..3fd740318
--- /dev/null
+++ b/web/components/chat/home/SessionViewerPanel.tsx
@@ -0,0 +1,678 @@
+"use client";
+
+/**
+ * SessionViewerPanel — full right-side sidebar with browser-style tabs that
+ * can hold (a) attachment previews and (b) embedded web pages clicked from
+ * assistant messages.
+ *
+ * - Tabs across the top of the panel; each closeable.
+ * - File tabs use the same lazy previewer set as FilePreviewDrawer.
+ * - Web tabs render an iframe of the URL. Cross-origin frames may refuse
+ * to load — we expose an "Open in browser" affordance so the user can
+ * always fall back. The user's network ultimately decides what loads.
+ * - Imperative API via ref: openFileTab(att), openWebTab(url).
+ */
+
+import {
+ forwardRef,
+ memo,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import dynamic from "next/dynamic";
+import {
+ AlertCircle,
+ ArrowRight,
+ ExternalLink,
+ FileUp,
+ Globe,
+ Loader2,
+ Paperclip,
+ X,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import {
+ previewKindFor,
+ resolveSourceUrl,
+ type FilePreviewSource,
+} from "@/components/chat/preview/previewerFor";
+import { apiUrl } from "@/lib/api";
+import { docIconFor } from "@/lib/doc-attachments";
+import type { MessageAttachment } from "@/context/UnifiedChatContext";
+
+const PdfPreview = dynamic(() => import("@/components/chat/preview/previewers/PdfPreview"));
+const ImagePreview = dynamic(() => import("@/components/chat/preview/previewers/ImagePreview"));
+const SvgPreview = dynamic(() => import("@/components/chat/preview/previewers/SvgPreview"));
+const MarkdownPreview = dynamic(() => import("@/components/chat/preview/previewers/MarkdownPreview"));
+const TextPreview = dynamic(() => import("@/components/chat/preview/previewers/TextPreview"));
+const OfficeTextPreview = dynamic(() => import("@/components/chat/preview/previewers/OfficeTextPreview"));
+const FallbackPreview = dynamic(() => import("@/components/chat/preview/previewers/FallbackPreview"));
+
+const ANIM_MS = 220;
+
+/* ------------------------------------------------------------------ */
+/* Tab types */
+/* ------------------------------------------------------------------ */
+
+type ViewerTab =
+ | { kind: "file"; id: string; label: string; source: FilePreviewSource }
+ | { kind: "web"; id: string; label: string; url: string };
+
+export interface SessionViewerPanelHandle {
+ openFileTab(a: MessageAttachment): void;
+ openWebTab(url: string): void;
+}
+
+interface SessionViewerPanelProps {
+ open: boolean;
+ sessionId: string | null;
+ onClose: () => void;
+ onAutoOpen: () => void;
+}
+
+function fileTabIdFor(a: MessageAttachment, fallback: number): string {
+ return `file:${a.id ?? a.filename ?? `idx-${fallback}`}`;
+}
+
+function webTabIdFor(url: string): string {
+ return `web:${url}`;
+}
+
+function hostnameFor(url: string): string {
+ try {
+ return new URL(url).hostname.replace(/^www\./, "");
+ } catch {
+ return url.slice(0, 32);
+ }
+}
+
+function attachmentToPreviewSource(a: MessageAttachment): FilePreviewSource {
+ return {
+ filename: a.filename || "",
+ mimeType: a.mime_type,
+ type: a.type,
+ url: a.url,
+ base64: a.base64,
+ extractedText: a.extracted_text,
+ id: a.id,
+ };
+}
+
+/* ------------------------------------------------------------------ */
+/* Panel */
+/* ------------------------------------------------------------------ */
+
+function SessionViewerPanelInner(
+ { open, sessionId, onClose, onAutoOpen }: SessionViewerPanelProps,
+ ref: React.Ref<SessionViewerPanelHandle>,
+) {
+ const { t } = useTranslation();
+ const [tabs, setTabs] = useState<ViewerTab[]>([]);
+ const [activeTabId, setActiveTabId] = useState<string | null>(null);
+
+ // Wipe tabs whenever the session changes — preview/web state belongs to
+ // the conversation that triggered it.
+ const [trackedSessionId, setTrackedSessionId] = useState<string | null>(
+ sessionId,
+ );
+ if (trackedSessionId !== sessionId) {
+ setTrackedSessionId(sessionId);
+ setTabs([]);
+ setActiveTabId(null);
+ }
+
+ const openFileTab = useCallback(
+ (a: MessageAttachment) => {
+ setTabs((prev) => {
+ const id = fileTabIdFor(a, prev.length);
+ const existingIdx = prev.findIndex((tab) => tab.id === id);
+ if (existingIdx >= 0) {
+ setActiveTabId(id);
+ return prev;
+ }
+ const label = a.filename || "Attachment";
+ const next: ViewerTab = {
+ kind: "file",
+ id,
+ label,
+ source: attachmentToPreviewSource(a),
+ };
+ setActiveTabId(id);
+ return [...prev, next];
+ });
+ onAutoOpen();
+ },
+ [onAutoOpen],
+ );
+
+ const openWebTab = useCallback(
+ (url: string) => {
+ setTabs((prev) => {
+ const id = webTabIdFor(url);
+ const existingIdx = prev.findIndex((tab) => tab.id === id);
+ if (existingIdx >= 0) {
+ setActiveTabId(id);
+ return prev;
+ }
+ const next: ViewerTab = {
+ kind: "web",
+ id,
+ label: hostnameFor(url),
+ url,
+ };
+ setActiveTabId(id);
+ return [...prev, next];
+ });
+ onAutoOpen();
+ },
+ [onAutoOpen],
+ );
+
+ useImperativeHandle(
+ ref,
+ () => ({ openFileTab, openWebTab }),
+ [openFileTab, openWebTab],
+ );
+
+ const closeTab = useCallback(
+ (id: string) => {
+ setTabs((prev) => {
+ const idx = prev.findIndex((tab) => tab.id === id);
+ if (idx === -1) return prev;
+ const next = prev.filter((tab) => tab.id !== id);
+ if (activeTabId === id) {
+ if (next.length === 0) {
+ setActiveTabId(null);
+ // Closing the last tab also closes the panel — there's nothing
+ // useful left to look at.
+ onClose();
+ } else {
+ const fallback = next[Math.max(0, idx - 1)] ?? next[0];
+ setActiveTabId(fallback.id);
+ }
+ }
+ return next;
+ });
+ },
+ [activeTabId, onClose],
+ );
+
+ // ESC closes the panel.
+ useEffect(() => {
+ if (!open) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") {
+ e.stopPropagation();
+ onClose();
+ }
+ };
+ document.addEventListener("keydown", onKey);
+ return () => document.removeEventListener("keydown", onKey);
+ }, [open, onClose]);
+
+ // The viewer is visible whenever it's open — even with no tabs. The
+ // tabs.length === 0 case renders a "Landing" page where the user can
+ // paste a URL or pick a local file to open as the first tab.
+ const visible = open;
+ const activeTab = tabs.find((tab) => tab.id === activeTabId) ?? null;
+
+ const openLocalFile = useCallback(
+ (file: File) => {
+ const url = URL.createObjectURL(file);
+ openFileTab({
+ type: file.type.startsWith("image/") ? "image" : "file",
+ filename: file.name,
+ mime_type: file.type,
+ url,
+ });
+ },
+ [openFileTab],
+ );
+
+ return (
+ <div
+ role="dialog"
+ aria-hidden={!visible}
+ className={`fixed right-0 top-0 z-[30] flex h-full w-[min(620px,92vw)] flex-col border-l border-[var(--border)] bg-[var(--card)] shadow-2xl transition-transform ease-out ${
+ visible ? "translate-x-0" : "translate-x-full"
+ }`}
+ style={{
+ willChange: "transform",
+ transitionDuration: `${ANIM_MS}ms`,
+ pointerEvents: visible ? "auto" : "none",
+ }}
+ >
+ <TabBar
+ tabs={tabs}
+ activeTabId={activeTabId}
+ onSelect={setActiveTabId}
+ onCloseTab={closeTab}
+ onClosePanel={onClose}
+ />
+ <div className="relative flex-1 overflow-hidden bg-[var(--card)]">
+ {activeTab?.kind === "file" ? (
+ <FileTabBody source={activeTab.source} />
+ ) : activeTab?.kind === "web" ? (
+ <WebTabBody url={activeTab.url} />
+ ) : (
+ <ViewerLanding
+ onOpenWebTab={openWebTab}
+ onOpenLocalFile={openLocalFile}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
+
+const SessionViewerPanel = memo(forwardRef(SessionViewerPanelInner));
+export default SessionViewerPanel;
+
+/* ------------------------------------------------------------------ */
+/* Tab bar */
+/* ------------------------------------------------------------------ */
+
+/**
+ * Chrome-style tab bar. The strip itself is a muted band; the active tab
+ * "lifts" out of it in the page-body colour with rounded top corners — so
+ * the active tab and the body underneath read as one continuous surface,
+ * exactly like a browser tab. No coloured top stripe; inactive tabs stay
+ * transparent over the strip.
+ */
+function TabBar({
+ tabs,
+ activeTabId,
+ onSelect,
+ onCloseTab,
+ onClosePanel,
+}: {
+ tabs: ViewerTab[];
+ activeTabId: string | null;
+ onSelect: (id: string) => void;
+ onCloseTab: (id: string) => void;
+ onClosePanel: () => void;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div className="flex shrink-0 items-end gap-2 bg-[color-mix(in_srgb,var(--muted)_40%,var(--background))] px-2 pt-2 pb-0">
+ <div className="flex min-w-0 flex-1 items-end gap-[2px] overflow-x-auto">
+ {tabs.map((tab) => {
+ const active = tab.id === activeTabId;
+ const Icon = tab.kind === "web" ? Globe : Paperclip;
+ return (
+ <button
+ key={tab.id}
+ type="button"
+ onClick={() => onSelect(tab.id)}
+ className={`group inline-flex max-w-[180px] shrink-0 items-center gap-1.5 rounded-t-md px-2.5 py-1.5 text-[11.5px] font-medium transition-colors ${
+ active
+ ? "bg-[var(--card)] text-[var(--foreground)]"
+ : "bg-transparent text-[var(--muted-foreground)] hover:bg-[color-mix(in_srgb,var(--card)_70%,transparent)] hover:text-[var(--foreground)]"
+ }`}
+ title={tab.label}
+ >
+ <Icon size={11} strokeWidth={1.9} className="shrink-0" />
+ <span className="truncate">{tab.label}</span>
+ <span
+ role="button"
+ tabIndex={-1}
+ onClick={(e) => {
+ e.stopPropagation();
+ onCloseTab(tab.id);
+ }}
+ className="-mr-0.5 ml-0.5 rounded-sm p-[1px] text-[var(--muted-foreground)] opacity-60 transition-opacity hover:bg-[var(--muted)]/70 hover:text-[var(--foreground)] hover:opacity-100"
+ aria-label={t("Close tab")}
+ >
+ <X size={10} />
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ <button
+ type="button"
+ onClick={onClosePanel}
+ className="mb-1 shrink-0 rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/45 hover:text-[var(--foreground)]"
+ aria-label={t("Close viewer")}
+ title={t("Close viewer")}
+ >
+ <X size={14} />
+ </button>
+ </div>
+ );
+}
+
+/* ------------------------------------------------------------------ */
+/* Landing state — shown when no tabs are open */
+/* ------------------------------------------------------------------ */
+
+function ViewerLanding({
+ onOpenWebTab,
+ onOpenLocalFile,
+}: {
+ onOpenWebTab: (url: string) => void;
+ onOpenLocalFile: (file: File) => void;
+}) {
+ const { t } = useTranslation();
+ const [urlInput, setUrlInput] = useState("");
+ const fileInputRef = useRef<HTMLInputElement>(null);
+
+ const submitUrl = useCallback(() => {
+ const trimmed = urlInput.trim();
+ if (!trimmed) return;
+ const href = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
+ onOpenWebTab(href);
+ setUrlInput("");
+ }, [urlInput, onOpenWebTab]);
+
+ const handleFileSelect = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (file) onOpenLocalFile(file);
+ e.target.value = "";
+ },
+ [onOpenLocalFile],
+ );
+
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-6 px-8 py-10">
+ <div className="text-center">
+ <h2 className="text-[15px] font-semibold tracking-[-0.005em] text-[var(--foreground)]">
+ {t("Viewer")}
+ </h2>
+ <p className="mt-1.5 text-[12px] text-[var(--muted-foreground)]">
+ {t(
+ "Paste a URL or open a local file. Attachments from chat will also land here.",
+ )}
+ </p>
+ </div>
+
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ submitUrl();
+ }}
+ className="flex w-full max-w-[420px] items-center gap-2 rounded-full border border-[var(--border)]/55 bg-[var(--background)] px-3 py-1.5 transition-colors focus-within:border-[var(--primary)]/40"
+ >
+ <Globe
+ size={14}
+ strokeWidth={1.8}
+ className="shrink-0 text-[var(--muted-foreground)]"
+ />
+ <input
+ type="text"
+ value={urlInput}
+ onChange={(e) => setUrlInput(e.target.value)}
+ placeholder={t("https://example.com")}
+ className="min-w-0 flex-1 bg-transparent text-[13px] text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]/60"
+ />
+ <button
+ type="submit"
+ disabled={!urlInput.trim()}
+ className="inline-flex shrink-0 items-center gap-1 rounded-full bg-[var(--primary)] px-3 py-1 text-[11px] font-medium text-white transition-opacity disabled:opacity-30"
+ aria-label={t("Open URL")}
+ >
+ <ArrowRight size={11} strokeWidth={2.2} />
+ </button>
+ </form>
+
+ <div className="flex items-center gap-2 text-[11px] text-[var(--muted-foreground)]/70">
+ <span className="h-px w-12 bg-[var(--border)]/50" />
+ <span>{t("or")}</span>
+ <span className="h-px w-12 bg-[var(--border)]/50" />
+ </div>
+
+ <button
+ type="button"
+ onClick={() => fileInputRef.current?.click()}
+ className="inline-flex items-center gap-2 rounded-lg border border-[var(--border)]/55 bg-[var(--background)] px-3.5 py-2 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--primary)]/35 hover:text-[var(--primary)]"
+ >
+ <FileUp size={13} strokeWidth={1.8} />
+ {t("Open a local file")}
+ </button>
+ <input
+ ref={fileInputRef}
+ type="file"
+ className="hidden"
+ onChange={handleFileSelect}
+ aria-hidden="true"
+ tabIndex={-1}
+ />
+ </div>
+ );
+}
+
+/* ------------------------------------------------------------------ */
+/* File tab body */
+/* ------------------------------------------------------------------ */
+
+function FileTabBody({ source }: { source: FilePreviewSource }) {
+ const { t } = useTranslation();
+ const previewUrl = useMemo(
+ () => resolveSourceUrl(source, apiUrl),
+ [source],
+ );
+ const kind = previewKindFor(source);
+ const filename = source.filename || t("Attachment");
+ const spec = docIconFor(filename);
+
+ const openInBrowser = useCallback(() => {
+ if (previewUrl) {
+ window.open(previewUrl, "_blank", "noopener,noreferrer");
+ return;
+ }
+ if (source.base64) {
+ const mime = source.mimeType || "application/octet-stream";
+ const url = `data:${mime};base64,${source.base64}`;
+ window.open(url, "_blank", "noopener,noreferrer");
+ }
+ }, [previewUrl, source]);
+
+ return (
+ <div className="flex h-full flex-col">
+ <div className="flex shrink-0 items-center gap-2 border-b border-[var(--border)]/40 bg-[var(--card)] px-4 py-2.5">
+ <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-[var(--muted)]/55">
+ <spec.Icon size={14} strokeWidth={1.6} className={spec.tint} />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[12.5px] font-semibold text-[var(--foreground)]">
+ {filename}
+ </div>
+ <div className="truncate text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">
+ {spec.label}
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={openInBrowser}
+ className="inline-flex shrink-0 items-center gap-1 rounded-md border border-[var(--border)]/55 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--primary)]/35 hover:text-[var(--primary)]"
+ >
+ <ExternalLink size={11} strokeWidth={1.8} />
+ {t("Open in browser")}
+ </button>
+ </div>
+ <div className="relative flex-1 overflow-hidden">
+ <PreviewBody source={source} previewUrl={previewUrl} kind={kind} />
+ </div>
+ </div>
+ );
+}
+
+const PreviewBody = memo(function PreviewBody({
+ source,
+ previewUrl,
+ kind,
+}: {
+ source: FilePreviewSource;
+ previewUrl: string | null;
+ kind: ReturnType<typeof previewKindFor> | null;
+}) {
+ const filename = source.filename;
+
+ if (kind === "office-text") {
+ return (
+ <OfficeTextPreview
+ filename={filename}
+ extractedText={source.extractedText}
+ url={previewUrl}
+ />
+ );
+ }
+
+ if (!previewUrl) {
+ return <FallbackPreview filename={filename} url={null} reason="legacy" />;
+ }
+
+ switch (kind) {
+ case "pdf":
+ return <PdfPreview url={previewUrl} filename={filename} />;
+ case "image":
+ return <ImagePreview url={previewUrl} filename={filename} />;
+ case "svg":
+ return <SvgPreview url={previewUrl} filename={filename} />;
+ case "markdown":
+ return (
+ <div className="h-full overflow-y-auto">
+ <MarkdownPreview url={previewUrl} />
+ </div>
+ );
+ case "code":
+ case "text":
+ return (
+ <div className="h-full overflow-y-auto">
+ <TextPreview url={previewUrl} filename={filename} />
+ </div>
+ );
+ case "fallback":
+ default:
+ return <FallbackPreview filename={filename} url={previewUrl} />;
+ }
+});
+
+/* ------------------------------------------------------------------ */
+/* Web tab body — iframe with safety fallback */
+/* ------------------------------------------------------------------ */
+
+/**
+ * Web preview tab. Many sites set `X-Frame-Options: DENY` or a CSP
+ * `frame-ancestors` directive that flat-out refuses iframe embedding — a
+ * browser-enforced anti-clickjacking measure we can't bypass from the
+ * frontend. We can't *detect* the failure reliably either (cross-origin
+ * iframes are opaque to JS), so we lean on UX honesty:
+ *
+ * • A persistent info banner at the top tells the user upfront that some
+ * sites won't load, and exposes "Open in browser" as a big primary
+ * action right next to it.
+ * • A loading spinner is overlaid until either `onLoad` fires or a soft
+ * timeout (4.5 s) elapses. After the timeout we switch the banner copy
+ * to a more explicit "site likely refused embedding" warning so the
+ * user knows the spinner isn't a real load-in-progress.
+ */
+function WebTabBody({ url }: { url: string }) {
+ const { t } = useTranslation();
+ const [loaded, setLoaded] = useState(false);
+ const [timedOut, setTimedOut] = useState(false);
+ const host = hostnameFor(url);
+
+ const openInBrowser = useCallback(() => {
+ window.open(url, "_blank", "noopener,noreferrer");
+ }, [url]);
+
+ useEffect(() => {
+ setLoaded(false);
+ setTimedOut(false);
+ const timer = window.setTimeout(() => setTimedOut(true), 4500);
+ return () => window.clearTimeout(timer);
+ }, [url]);
+
+ const blocked = timedOut && !loaded;
+
+ return (
+ <div className="flex h-full flex-col">
+ <div className="flex shrink-0 items-center gap-2 border-b border-[var(--border)]/40 bg-[var(--card)] px-4 py-2.5">
+ <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-[var(--muted)]/55">
+ <Globe
+ size={14}
+ strokeWidth={1.7}
+ className="text-[var(--muted-foreground)]"
+ />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[12.5px] font-semibold text-[var(--foreground)]">
+ {host}
+ </div>
+ <div className="truncate text-[10px] text-[var(--muted-foreground)]">
+ {url}
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={openInBrowser}
+ className={`inline-flex shrink-0 items-center gap-1 rounded-md px-2.5 py-1 text-[11px] font-semibold transition-colors ${
+ blocked
+ ? "bg-[var(--primary)] text-white hover:bg-[var(--primary)]/90"
+ : "border border-[var(--border)]/55 text-[var(--muted-foreground)] hover:border-[var(--primary)]/35 hover:text-[var(--primary)]"
+ }`}
+ >
+ <ExternalLink size={11} strokeWidth={1.9} />
+ {t("Open in browser")}
+ </button>
+ </div>
+
+ {/* Persistent info banner — explains the iframe limitation. Swaps to
+ a louder warning once we suspect the site has refused to embed. */}
+ <div
+ className={`flex shrink-0 items-start gap-2 border-b border-[var(--border)]/30 px-4 py-2 text-[11px] leading-snug ${
+ blocked
+ ? "bg-[color-mix(in_srgb,var(--primary)_8%,var(--card))] text-[var(--foreground)]"
+ : "bg-[color-mix(in_srgb,var(--muted)_45%,var(--card))] text-[var(--muted-foreground)]"
+ }`}
+ >
+ <AlertCircle
+ size={12}
+ strokeWidth={1.9}
+ className={`mt-[1px] shrink-0 ${
+ blocked
+ ? "text-[var(--primary)]"
+ : "text-[var(--muted-foreground)]"
+ }`}
+ />
+ <span>
+ {blocked
+ ? t(
+ "This site looks like it refused to embed (its security headers block iframes). Use “Open in browser” to view it in a real tab.",
+ )
+ : t(
+ "Many sites refuse to embed for security reasons. If the page below stays blank, use “Open in browser”.",
+ )}
+ </span>
+ </div>
+
+ <div className="relative flex-1 overflow-hidden bg-[var(--background)]">
+ <iframe
+ key={url}
+ src={url}
+ title={host}
+ onLoad={() => setLoaded(true)}
+ className="h-full w-full border-0"
+ sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
+ referrerPolicy="no-referrer"
+ />
+ {!loaded && !timedOut ? (
+ <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-2 bg-[var(--card)]/70 text-[12px] text-[var(--muted-foreground)] backdrop-blur-sm">
+ <Loader2
+ size={18}
+ strokeWidth={1.7}
+ className="animate-spin text-[var(--primary)]/80"
+ />
+ <span>{t("Loading {{host}}…", { host })}</span>
+ </div>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/web/components/chat/home/TracePanels.tsx b/web/components/chat/home/TracePanels.tsx
index f75cace9d..3627cdf85 100644
--- a/web/components/chat/home/TracePanels.tsx
+++ b/web/components/chat/home/TracePanels.tsx
@@ -1,6 +1,13 @@
"use client";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
import {
BrainCircuit,
ChevronDown,
@@ -373,6 +380,37 @@ function ScrollableTraceBody({
);
}
+/**
+ * Persistently-expanded ``<details>`` wrapper. Initialises ``open`` to
+ * ``true`` so the panel renders expanded from the first paint, and tracks
+ * subsequent toggles purely from user clicks — we never re-close it as a
+ * side-effect of the trace finishing (per product direction: all traces stay
+ * open by default).
+ */
+function ExpandableDetails({
+ summary,
+ className,
+ children,
+}: {
+ summary: ReactNode;
+ className?: string;
+ children: ReactNode;
+}) {
+ const [open, setOpen] = useState(true);
+ return (
+ <details
+ open={open}
+ onToggle={(event) => setOpen((event.target as HTMLDetailsElement).open)}
+ className={className}
+ >
+ <summary className="list-none cursor-pointer hover:text-[var(--foreground)] [&::-webkit-details-marker]:hidden">
+ {summary}
+ </summary>
+ {children}
+ </details>
+ );
+}
+
function TraceIcon({ kind, phase }: { kind: string; phase: string }) {
const Icon =
kind === "rag_retrieval"
@@ -666,13 +704,42 @@ function hasExpandableContent(
export function CallTracePanel({
events,
isStreaming,
+ nested = false,
}: {
events: StreamEvent[];
isStreaming?: boolean;
+ // When the panel is rendered inside another shell that already supplies its
+ // own framing (e.g. the auto-mode DelegationCard), pass ``nested`` to skip
+ // the card wrapper so we don't end up with card-in-card visuals.
+ 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;
+ // the moment they scroll up we release the stick so they can browse earlier
+ // trace rows without being yanked back. New streaming turns re-arm the
+ // stick so the next assistant response starts pinned at the bottom again.
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const stickRef = useRef(true);
+
+ useEffect(() => {
+ if (!isStreaming || nested || !stickRef.current) return;
+ const el = scrollRef.current;
+ if (el) el.scrollTop = el.scrollHeight;
+ });
+
+ useEffect(() => {
+ if (isStreaming) stickRef.current = true;
+ }, [isStreaming]);
+
+ const handleOuterScroll = useCallback(() => {
+ const el = scrollRef.current;
+ if (!el) return;
+ stickRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 30;
+ }, []);
+
useEffect(() => {
if (!isStreaming) return;
const timer = window.setInterval(
@@ -737,7 +804,12 @@ export function CallTracePanel({
className="shrink-0 transition-transform group-open:rotate-180"
/>
) : (
- <span className="w-3 shrink-0" />
+ // Pending row with no content yet — a faint dot preserves the
+ // chevron's column width and keeps the icon + label from sliding
+ // left every time a trace starts.
+ <span className="flex w-3 shrink-0 items-center justify-center">
+ <span className="h-[3px] w-[3px] rounded-full bg-current opacity-45" />
+ </span>
)}
<TraceIcon kind={kind} phase={phase} />
<span>{header}</span>
@@ -750,10 +822,7 @@ export function CallTracePanel({
}
return (
- <details key={callId} open={active} className="group">
- <summary className="list-none cursor-pointer hover:text-[var(--foreground)] [&::-webkit-details-marker]:hidden">
- {summaryRow}
- </summary>
+ <ExpandableDetails key={callId} className="group" summary={summaryRow}>
{nested ? (
<div className="ml-5 mr-3 mt-0.5 px-3 py-1">
<TraceRowBody
@@ -777,12 +846,24 @@ export function CallTracePanel({
/>
</ScrollableTraceBody>
)}
- </details>
+ </ExpandableDetails>
);
}
+ // Cap the trace card height so a long sequence of expanded traces becomes
+ // a self-contained scroll region instead of pushing the rest of the page
+ // (and the composer) off-screen. Nested panels live inside their parent's
+ // own scroll area, so we only constrain the standalone card.
+ const rootClassName = nested
+ ? "mb-3 space-y-0.5"
+ : "mb-3 max-h-[240px] space-y-0.5 overflow-y-auto rounded-xl border border-[var(--border)]/50 bg-[var(--card)]/50 px-3 py-2";
+
return (
- <div className="mb-3 space-y-0.5">
+ <div
+ ref={nested ? undefined : scrollRef}
+ onScroll={nested ? undefined : handleOuterScroll}
+ className={rootClassName}
+ >
{displayItems.map((item, displayIdx) => {
const isLastDisplayItem = displayIdx === displayItems.length - 1;
@@ -800,12 +881,10 @@ export function CallTracePanel({
: getStepGroupDuration(item.traces);
return (
- <details
+ <ExpandableDetails
key={item.stepId}
- open={isActiveStep || undefined}
className="group/step"
- >
- <summary className="list-none cursor-pointer hover:text-[var(--foreground)] [&::-webkit-details-marker]:hidden">
+ summary={
<div className="flex items-center gap-2 py-0.5 not-italic text-[12px] font-medium text-[var(--muted-foreground)]">
<ChevronDown
size={12}
@@ -821,7 +900,8 @@ export function CallTracePanel({
<Loader2 size={11} className="animate-spin" />
)}
</div>
- </summary>
+ }
+ >
<ScrollableTraceBody
autoScroll={isActiveStep}
className="ml-5 mr-3 mt-0.5 max-h-[280px] overflow-y-auto px-3 py-1"
@@ -1032,7 +1112,7 @@ export function CallTracePanel({
})}
</div>
</ScrollableTraceBody>
- </details>
+ </ExpandableDetails>
);
}
@@ -1042,6 +1122,289 @@ export function CallTracePanel({
);
}
+/* ------------------------------------------------------------------ */
+/* StreamingStatus — breathing "reasoning" / "tool using" indicator */
+/* ------------------------------------------------------------------ */
+
+type MarkProps = {
+ size?: number;
+ className?: string;
+ strokeWidth?: number;
+};
+
+function MarkSvg({
+ size = 16,
+ className,
+ strokeWidth = 1.5,
+ children,
+}: MarkProps & { children: ReactNode }) {
+ return (
+ <svg
+ viewBox="0 0 24 24"
+ width={size}
+ height={size}
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={strokeWidth}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className={className}
+ aria-hidden="true"
+ >
+ {children}
+ </svg>
+ );
+}
+
+/**
+ * Reasoning — asymmetric 12-ray radial burst. Tilted ~12° so it reads as
+ * hand-sketched rather than geometric; long cardinal rays + medium diagonals
+ * + short accent rays in between for an organic sparkle.
+ */
+function ReasoningMark(props: MarkProps) {
+ return (
+ <MarkSvg {...props}>
+ <g transform="rotate(12 12 12)">
+ <path d="M12 2 L12 7.5" />
+ <path d="M12 22 L12 16.5" />
+ <path d="M2 12 L7.5 12" />
+ <path d="M22 12 L16.5 12" />
+ <path d="M4.6 4.6 L8.4 8.4" />
+ <path d="M19.4 19.4 L15.6 15.6" />
+ <path d="M4.2 19.8 L8.2 15.8" />
+ <path d="M19.8 4.2 L15.8 8.2" />
+ <path d="M7.6 2.3 L9 5.8" />
+ <path d="M16.4 2.3 L15 5.8" />
+ <path d="M7.6 21.7 L9 18.2" />
+ <path d="M16.4 21.7 L15 18.2" />
+ </g>
+ </MarkSvg>
+ );
+}
+
+/**
+ * Tool using — an off-axis orbital motif: a soft elliptical orbit arc with
+ * a small filled satellite riding it and two stray sparks. Reads as something
+ * "in motion / being operated" without being a literal wrench.
+ */
+function ToolMark(props: MarkProps) {
+ return (
+ <MarkSvg {...props}>
+ {/* Central node */}
+ <circle cx="12" cy="13" r="2.4" />
+ {/* Open orbital arc on a slight tilt */}
+ <path d="M3.5 9.5 A 10.5 8 -18 0 1 20.5 14" />
+ {/* Filled satellite riding the orbit */}
+ <circle cx="20.5" cy="14" r="1.5" fill="currentColor" stroke="none" />
+ {/* Stray accent sparks */}
+ <path d="M5 19 L7.2 17.5" />
+ <path d="M18 4 L19.5 6" />
+ </MarkSvg>
+ );
+}
+
+/**
+ * Responding — a flowing ink-stroke that swoops up to the right, terminating
+ * in a small dot, like a quill marking paper. Suggests "writing out an
+ * answer" without being a literal pen icon.
+ */
+function RespondingMark(props: MarkProps) {
+ return (
+ <MarkSvg {...props}>
+ {/* Sweeping brush curve */}
+ <path d="M3 18 Q 8 7 14 11 T 21 6.5" />
+ {/* Quill tip — short tick + filled dot */}
+ <circle cx="21" cy="6.5" r="1.4" fill="currentColor" stroke="none" />
+ {/* Ink drop accent below */}
+ <circle cx="5.5" cy="20.5" r="0.9" fill="currentColor" stroke="none" />
+ </MarkSvg>
+ );
+}
+
+/**
+ * Responded — a settled, slightly softer mark: a compact 4-ray bloom with
+ * a filled inner dot. Conveys "thought captured, complete" without echoing
+ * the reasoning burst.
+ */
+function RespondedMark(props: MarkProps) {
+ return (
+ <MarkSvg {...props}>
+ <g transform="rotate(8 12 12)">
+ {/* Inner anchor */}
+ <circle cx="12" cy="12" r="1.8" fill="currentColor" stroke="none" />
+ {/* 4 short cardinal rays */}
+ <path d="M12 4.5 L12 8" />
+ <path d="M12 19.5 L12 16" />
+ <path d="M4.5 12 L8 12" />
+ <path d="M19.5 12 L16 12" />
+ {/* 2 longer diagonal accents — asymmetric for character */}
+ <path d="M6 6 L8.6 8.6" />
+ <path d="M18 18 L15.4 15.4" />
+ </g>
+ </MarkSvg>
+ );
+}
+
+type StreamingMode = "reasoning" | "tool_using" | "responding" | "responded";
+
+/**
+ * Picks the status label shown above the trace card. We scan in reverse so a
+ * tool finishing mid-turn cleanly flips the label back to reasoning for the
+ * next LLM round. Final-answer streaming is detected by user-visible content
+ * arriving on the assistant message itself — ``content`` is non-empty.
+ */
+function detectStreamingMode(
+ events: StreamEvent[],
+ hasFinalContent: boolean,
+ isStreaming: boolean,
+): StreamingMode {
+ if (!isStreaming) return "responded";
+ if (hasFinalContent) return "responding";
+ for (let idx = events.length - 1; idx >= 0; idx -= 1) {
+ const event = events[idx];
+ if (event.type === "tool_result") return "reasoning";
+ if (event.type === "tool_call") return "tool_using";
+ }
+ return "reasoning";
+}
+
+export function StreamingStatus({
+ events,
+ isStreaming,
+ content,
+ collapsible,
+ expanded,
+ onToggle,
+}: {
+ events: StreamEvent[];
+ isStreaming?: boolean;
+ content?: string;
+ // When set, the status row becomes a clickable toggle for the trace card
+ // sibling below. ``expanded`` controls the chevron rotation.
+ collapsible?: boolean;
+ expanded?: boolean;
+ onToggle?: () => void;
+}) {
+ const { t } = useTranslation();
+ const hasFinalContent = Boolean(content && content.trim().length > 0);
+ // 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.
+ if (!isStreaming && !hasFinalContent) return null;
+ const mode = detectStreamingMode(
+ events,
+ hasFinalContent,
+ Boolean(isStreaming),
+ );
+
+ const label =
+ mode === "tool_using"
+ ? t("Tool using…")
+ : mode === "responding"
+ ? t("DeepTutor responding…")
+ : mode === "responded"
+ ? t("DeepTutor responded.")
+ : t("DeepTutor reasoning…");
+ // 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)
+ // so the mark feels alive rather than just dimming with the label.
+ const breathingClass = mode === "responded" ? "" : "dt-breathing-text";
+ const markPulseClass = mode === "responded" ? "" : "dt-mark-pulse";
+ const textColor =
+ mode === "responded"
+ ? "text-[var(--muted-foreground)]/70"
+ : "text-[var(--muted-foreground)]";
+ const Mark =
+ mode === "tool_using"
+ ? ToolMark
+ : mode === "responding"
+ ? RespondingMark
+ : mode === "responded"
+ ? RespondedMark
+ : ReasoningMark;
+
+ const rowContent = (
+ <>
+ <Mark
+ size={22}
+ strokeWidth={1.5}
+ className={`${breathingClass} ${markPulseClass} shrink-0 text-[var(--primary)]/90`}
+ />
+ <span className={breathingClass}>{label}</span>
+ {collapsible ? (
+ <ChevronDown
+ size={14}
+ strokeWidth={2}
+ className={`ml-1 shrink-0 opacity-60 transition-transform ${
+ expanded ? "" : "-rotate-90"
+ }`}
+ />
+ ) : null}
+ </>
+ );
+
+ if (collapsible && onToggle) {
+ return (
+ <button
+ type="button"
+ onClick={onToggle}
+ aria-expanded={expanded ? "true" : "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}
+ </button>
+ );
+ }
+
+ return (
+ <div
+ className={`mb-3 flex items-center gap-2.5 text-[14px] font-semibold leading-none ${textColor}`}
+ >
+ {rowContent}
+ </div>
+ );
+}
+
+/**
+ * Combined surface that renders the streaming-status row above a collapsible
+ * trace card. The chevron on the status row folds the card while leaving the
+ * status itself (and the assistant response below it) untouched. Defaults to
+ * open per product direction; user toggles persist across event updates.
+ */
+export function TraceSurface({
+ events,
+ isStreaming,
+ content,
+}: {
+ events: StreamEvent[];
+ isStreaming?: boolean;
+ content?: string;
+}) {
+ const hasCallTrace = useMemo(
+ () => events.some((event) => Boolean(event.metadata?.call_id)),
+ [events],
+ );
+ const [expanded, setExpanded] = useState(true);
+ const toggle = useCallback(() => setExpanded((prev) => !prev), []);
+
+ return (
+ <>
+ <StreamingStatus
+ events={events}
+ isStreaming={isStreaming}
+ content={content}
+ collapsible={hasCallTrace}
+ expanded={expanded}
+ onToggle={toggle}
+ />
+ {hasCallTrace && expanded ? (
+ <CallTracePanel events={events} isStreaming={isStreaming} />
+ ) : null}
+ </>
+ );
+}
+
/* ------------------------------------------------------------------ */
/* ResearchStagePanel */
/* ------------------------------------------------------------------ */
diff --git a/web/components/chat/preview/FilePreviewDrawer.tsx b/web/components/chat/preview/FilePreviewDrawer.tsx
index 6059087b3..7e41ec1ff 100644
--- a/web/components/chat/preview/FilePreviewDrawer.tsx
+++ b/web/components/chat/preview/FilePreviewDrawer.tsx
@@ -156,7 +156,7 @@ export default function FilePreviewDrawer({
role="dialog"
aria-hidden={!visible}
aria-label={t("File preview: {{name}}", { name: filename })}
- className={`fixed right-0 top-0 z-[90] flex h-full w-[min(560px,92vw)] flex-col border-l border-[var(--border)] bg-[var(--card)] shadow-2xl transition-transform ease-out ${
+ className={`fixed right-0 top-0 z-[30] flex h-full w-[min(560px,92vw)] flex-col border-l border-[var(--border)] bg-[var(--card)] shadow-2xl transition-transform ease-out ${
visible ? "translate-x-0" : "translate-x-full"
}`}
style={{
diff --git a/web/components/math-animator/MathAnimatorConfigPanel.tsx b/web/components/math-animator/MathAnimatorConfigPanel.tsx
index 7816a4b51..d57f6a7a5 100644
--- a/web/components/math-animator/MathAnimatorConfigPanel.tsx
+++ b/web/components/math-animator/MathAnimatorConfigPanel.tsx
@@ -15,8 +15,12 @@ import {
interface MathAnimatorConfigPanelProps {
value: MathAnimatorFormConfig;
onChange: (next: MathAnimatorFormConfig) => void;
- collapsed: boolean;
- onToggleCollapsed: () => void;
+ /**
+ * When provided, the panel is wrapped in a `CollapsibleConfigSection`.
+ * Omit both to render bare for the chat Activity panel.
+ */
+ collapsed?: boolean;
+ onToggleCollapsed?: () => void;
}
export default memo(function MathAnimatorConfigPanel({
@@ -31,13 +35,8 @@ export default memo(function MathAnimatorConfigPanel({
val: MathAnimatorFormConfig[K],
) => onChange({ ...value, [key]: val });
- return (
- <CollapsibleConfigSection
- collapsed={collapsed}
- summary={summarizeMathAnimatorConfig(value, t)}
- onToggleCollapsed={onToggleCollapsed}
- bodyClassName="flex flex-wrap items-end gap-x-3 gap-y-2 px-3.5 pb-2.5"
- >
+ const body = (
+ <>
<Field label={t("Output")} width="w-[100px]">
<select
value={value.output_mode}
@@ -80,6 +79,25 @@ export default memo(function MathAnimatorConfigPanel({
className={`${INPUT_CLS} w-full`}
/>
</Field>
+ </>
+ );
+
+ if (collapsed === undefined) {
+ return (
+ <div className="flex flex-wrap items-end gap-x-3 gap-y-2 px-3.5 py-2.5">
+ {body}
+ </div>
+ );
+ }
+
+ return (
+ <CollapsibleConfigSection
+ collapsed={collapsed}
+ summary={summarizeMathAnimatorConfig(value, t)}
+ onToggleCollapsed={onToggleCollapsed ?? (() => undefined)}
+ bodyClassName="flex flex-wrap items-end gap-x-3 gap-y-2 px-3.5 pb-2.5"
+ >
+ {body}
</CollapsibleConfigSection>
);
});
diff --git a/web/components/quiz/QuizConfigPanel.tsx b/web/components/quiz/QuizConfigPanel.tsx
index e9e89ad31..ddce98268 100644
--- a/web/components/quiz/QuizConfigPanel.tsx
+++ b/web/components/quiz/QuizConfigPanel.tsx
@@ -19,8 +19,14 @@ interface QuizConfigPanelProps {
onChange: (next: DeepQuestionFormConfig) => void;
uploadedPdf: File | null;
onUploadPdf: (file: File | null) => void;
- collapsed: boolean;
- onToggleCollapsed: () => void;
+ /**
+ * When provided, the panel is wrapped in a `CollapsibleConfigSection` (used
+ * by /playground). Omit both to render the bare form — used inside the
+ * chat's right-side Activity panel where the parent card supplies its own
+ * header.
+ */
+ collapsed?: boolean;
+ onToggleCollapsed?: () => void;
}
export default memo(function QuizConfigPanel({
@@ -42,13 +48,8 @@ export default memo(function QuizConfigPanel({
const setMode = (m: DeepQuestionMode) => update("mode", m);
- return (
- <CollapsibleConfigSection
- collapsed={collapsed}
- summary={summarizeQuizConfig(value, t)}
- onToggleCollapsed={onToggleCollapsed}
- bodyClassName="px-3.5 pb-2.5 space-y-2.5"
- >
+ const body = (
+ <>
<div className="inline-flex rounded-lg border border-[var(--border)]/25 p-0.5">
{(["custom", "mimic"] as const).map((m) => (
<button
@@ -213,6 +214,21 @@ export default memo(function QuizConfigPanel({
</Field>
</div>
)}
+ </>
+ );
+
+ if (collapsed === undefined) {
+ return <div className="space-y-2.5 px-3.5 py-2.5">{body}</div>;
+ }
+
+ return (
+ <CollapsibleConfigSection
+ collapsed={collapsed}
+ summary={summarizeQuizConfig(value, t)}
+ onToggleCollapsed={onToggleCollapsed ?? (() => undefined)}
+ bodyClassName="px-3.5 pb-2.5 space-y-2.5"
+ >
+ {body}
</CollapsibleConfigSection>
);
});
diff --git a/web/components/research/ResearchConfigPanel.tsx b/web/components/research/ResearchConfigPanel.tsx
index acccd74f9..723b4504d 100644
--- a/web/components/research/ResearchConfigPanel.tsx
+++ b/web/components/research/ResearchConfigPanel.tsx
@@ -17,9 +17,13 @@ import {
interface ResearchConfigPanelProps {
value: DeepResearchFormConfig;
errors: Record<string, string>;
- collapsed: boolean;
+ /**
+ * When provided, the panel is wrapped in a `CollapsibleConfigSection`.
+ * Omit both to render bare for the chat Activity panel.
+ */
+ collapsed?: boolean;
onChange: (next: DeepResearchFormConfig) => void;
- onToggleCollapsed: () => void;
+ onToggleCollapsed?: () => void;
}
// Note: `label` values are i18n keys resolved via `t(...)` at render time so
@@ -93,13 +97,8 @@ export default memo(function ResearchConfigPanel({
const summary =
rawSummary === t("Incomplete settings") ? undefined : rawSummary;
- return (
- <CollapsibleConfigSection
- collapsed={collapsed}
- summary={summary}
- onToggleCollapsed={onToggleCollapsed}
- bodyClassName="space-y-2 px-3.5 pb-2.5"
- >
+ const body = (
+ <>
<div className="flex flex-wrap items-end gap-x-3 gap-y-2">
<Field label={t("Mode")} width="min-w-[130px] flex-1">
<select
@@ -148,6 +147,21 @@ export default memo(function ResearchConfigPanel({
/>
</div>
)}
+ </>
+ );
+
+ if (collapsed === undefined) {
+ return <div className="space-y-2 px-3.5 py-2.5">{body}</div>;
+ }
+
+ return (
+ <CollapsibleConfigSection
+ collapsed={collapsed}
+ summary={summary}
+ onToggleCollapsed={onToggleCollapsed ?? (() => undefined)}
+ bodyClassName="space-y-2 px-3.5 pb-2.5"
+ >
+ {body}
</CollapsibleConfigSection>
);
});
diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsx
index 305dab4a9..547f8c073 100644
--- a/web/components/sidebar/SidebarShell.tsx
+++ b/web/components/sidebar/SidebarShell.tsx
@@ -17,10 +17,12 @@ import {
PenLine,
Plus,
Settings,
+ Sparkles,
type LucideIcon,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import SessionList from "@/components/SessionList";
+import { surfaceForPath } from "@/lib/session-surfaces";
import { TutorBotRecent } from "@/components/sidebar/TutorBotRecent";
import { VersionBadge } from "@/components/sidebar/VersionBadge";
import type { SessionSummary } from "@/lib/session-api";
@@ -40,6 +42,12 @@ const PRIMARY_NAV: NavEntry[] = [
icon: MessageSquare,
tooltipKey: "Chat tooltip",
},
+ {
+ href: "/co-learn",
+ label: "Co-Learn",
+ icon: Sparkles,
+ tooltipKey: "Co-Learn tooltip",
+ },
{
href: "/agents",
label: "TutorBot",
@@ -268,8 +276,11 @@ export function SidebarShell({
{PRIMARY_NAV.map((item) => {
const active = pathname.startsWith(item.href);
+ // Sessions hang under whichever surface entry owns the current
+ // URL. Single source of truth: ``lib/session-surfaces``.
+ const sessionsOwnerHref = surfaceForPath(pathname).basePath;
const hasSessionsBelow =
- item.href === "/chat" &&
+ item.href === sessionsOwnerHref &&
showSessions &&
onSelectSession &&
onRenameSession &&
diff --git a/web/components/sidebar/UtilitySidebar.tsx b/web/components/sidebar/UtilitySidebar.tsx
index face711a3..908ac54ba 100644
--- a/web/components/sidebar/UtilitySidebar.tsx
+++ b/web/components/sidebar/UtilitySidebar.tsx
@@ -1,7 +1,7 @@
"use client";
-import { useCallback, useEffect, useRef, useState } from "react";
-import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { usePathname, useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import { SidebarShell } from "@/components/sidebar/SidebarShell";
import { LogoutButton } from "@/components/auth/LogoutButton";
@@ -13,10 +13,13 @@ import {
updateSessionTitle,
type SessionSummary,
} from "@/lib/session-api";
+import { surfaceForPath } from "@/lib/session-surfaces";
export default function UtilitySidebar() {
const { t } = useTranslation();
const router = useRouter();
+ const pathname = usePathname();
+ const surface = useMemo(() => surfaceForPath(pathname), [pathname]);
const { activeSessionId, setActiveSessionId } = useAppShell();
const [sessions, setSessions] = useState<SessionSummary[]>([]);
const [loadingSessions, setLoadingSessions] = useState(false);
@@ -27,30 +30,35 @@ export default function UtilitySidebar() {
setLoadingSessions(true);
}
try {
- setSessions(await listSessions(50, 0, { force: true }));
+ setSessions(
+ await listSessions(50, 0, { force: true, kind: surface.kind }),
+ );
hasLoadedSessionsRef.current = true;
} catch (error) {
console.error("Failed to load sessions", error);
} finally {
setLoadingSessions(false);
}
- }, []);
+ }, [surface.kind]);
+ // Re-fetch whenever the user crosses surfaces (chat ↔ co-learn) so the
+ // sidebar's session list matches the page they just opened.
useEffect(() => {
+ hasLoadedSessionsRef.current = false;
void refreshSessions();
- }, [refreshSessions]);
+ }, [refreshSessions, surface.kind]);
const handleNewChat = useCallback(() => {
setActiveSessionId(null);
- router.push("/chat");
- }, [router, setActiveSessionId]);
+ router.push(surface.basePath);
+ }, [router, setActiveSessionId, surface.basePath]);
const handleSelectSession = useCallback(
async (sessionId: string) => {
setActiveSessionId(sessionId);
- router.push(`/chat/${sessionId}`);
+ router.push(`${surface.basePath}/${sessionId}`);
},
- [router, setActiveSessionId],
+ [router, setActiveSessionId, surface.basePath],
);
const handleRenameSession = useCallback(
@@ -82,7 +90,7 @@ export default function UtilitySidebar() {
setActiveSessionId(null);
}
},
- [activeSessionId, setActiveSessionId],
+ [activeSessionId, setActiveSessionId, t],
);
return (
diff --git a/web/components/sidebar/VersionBadge.tsx b/web/components/sidebar/VersionBadge.tsx
index 5b5b20fea..10e0b4811 100644
--- a/web/components/sidebar/VersionBadge.tsx
+++ b/web/components/sidebar/VersionBadge.tsx
@@ -1,155 +1,31 @@
"use client";
-import { useEffect, useMemo, useState } from "react";
-import { useTranslation } from "react-i18next";
-import {
- normalizeVersionTag,
- parseBuild,
- type ParsedBuild,
-} from "@/lib/version";
-
-interface LatestVersionPayload {
- tag: string | null;
- name: string | null;
- url: string | null;
- publishedAt: string | null;
- source: "github" | "fallback";
-}
-
-interface CurrentVersionPayload extends ParsedBuild {
- source: "git" | "env" | "unknown";
- detectedAt: string;
-}
-
-interface VersionPayload extends LatestVersionPayload {
- current?: CurrentVersionPayload;
- latest?: LatestVersionPayload;
-}
+import { normalizeVersionTag } from "@/lib/version";
interface VersionBadgeProps {
/** Render the compact variant for the collapsed sidebar (currently hidden). */
collapsed?: boolean;
}
-let _cache: VersionPayload | null = null;
-let _cacheAt = 0;
-let _inflight: Promise<VersionPayload | null> | null = null;
-const CACHE_TTL_MS = 60_000;
-
-async function loadVersion(): Promise<VersionPayload | null> {
- if (_cache && Date.now() - _cacheAt < CACHE_TTL_MS) return _cache;
- if (_inflight) return _inflight;
- _inflight = (async () => {
- try {
- const res = await fetch("/api/version", { cache: "no-store" });
- if (!res.ok) return null;
- const data = (await res.json()) as VersionPayload;
- _cache = data;
- _cacheAt = Date.now();
- return data;
- } catch {
- return null;
- } finally {
- _inflight = null;
- }
- })();
- return _inflight;
-}
-
-type Status = "latest" | "outdated" | "dev" | "unknown";
+const RELEASES_URL = "https://github.com/HKUDS/DeepTutor/releases";
export function VersionBadge({ collapsed = false }: VersionBadgeProps) {
- const { t } = useTranslation();
- const [data, setData] = useState<VersionPayload | null>(_cache);
-
- useEffect(() => {
- let cancelled = false;
- const refresh = () => {
- loadVersion().then((v) => {
- if (!cancelled) setData(v);
- });
- };
- refresh();
- const interval = window.setInterval(refresh, CACHE_TTL_MS);
- return () => {
- cancelled = true;
- window.clearInterval(interval);
- };
- }, []);
-
- const fallbackBuild = parseBuild(process.env.NEXT_PUBLIC_APP_VERSION || "");
- const build = data?.current?.raw ? data.current : fallbackBuild;
- const latest = data?.latest ?? data;
- const latestNorm = normalizeVersionTag(latest?.tag);
-
- const { status, displayTag, href, tooltip } = useMemo(() => {
- let status: Status = "unknown";
- if (build?.tag && latestNorm) {
- status =
- build.tag === latestNorm
- ? build.isDev
- ? "dev"
- : "latest"
- : "outdated";
- } else if (build?.isDev) {
- status = "dev";
- }
-
- // Display: prefer the running build (most accurate), fall back to the
- // latest GitHub release as an informational placeholder.
- const displayTag = build?.display ?? latestNorm ?? null;
-
- const href =
- latest?.url ??
- (latestNorm
- ? `https://github.com/HKUDS/DeepTutor/releases/tag/${latestNorm}`
- : "https://github.com/HKUDS/DeepTutor/releases");
-
- let tooltip: string;
- if (status === "latest" && displayTag) {
- tooltip = `${displayTag} · ${t("Up to date")}`;
- } else if (status === "outdated" && displayTag && latestNorm) {
- tooltip = `${displayTag} · ${t("Update available")}: ${latestNorm}`;
- } else if (status === "dev") {
- const base = `${t("Development build")}: ${build?.raw ?? ""}`;
- tooltip = latestNorm
- ? `${base} · ${t("Latest release")}: ${latestNorm}`
- : base;
- } else if (displayTag) {
- tooltip = `${t("Latest release")}: ${displayTag}`;
- } else {
- tooltip = t("Loading...");
- }
-
- return { status, displayTag, href, tooltip };
- }, [build, latestNorm, latest?.url, t]);
-
// Keep the collapsed sidebar entirely free of version chrome.
if (collapsed) return null;
- const dotClass =
- status === "latest"
- ? "bg-emerald-500/45"
- : status === "outdated"
- ? "bg-amber-500/55"
- : status === "dev"
- ? "bg-sky-500/45"
- : "bg-[var(--muted-foreground)]/25";
+ const tag = normalizeVersionTag(process.env.NEXT_PUBLIC_APP_VERSION || "");
+ const displayTag = tag ?? "—";
return (
<a
- href={href}
+ href={RELEASES_URL}
target="_blank"
rel="noreferrer noopener"
- title={tooltip}
- className="group/ver flex min-w-0 flex-1 items-center gap-2 rounded-lg px-3 py-1.5 text-[11px] font-mono tabular-nums tracking-tight text-[var(--muted-foreground)]/55 transition-colors hover:bg-[var(--background)]/50 hover:text-[var(--muted-foreground)]"
+ title={displayTag}
+ className="group/ver flex min-w-0 flex-1 items-center rounded-lg px-3 py-1.5 text-[11px] font-mono tabular-nums tracking-tight text-[var(--muted-foreground)]/55 transition-colors hover:bg-[var(--background)]/50 hover:text-[var(--muted-foreground)]"
>
- <span
- className={`h-1.5 w-1.5 shrink-0 rounded-full transition-colors ${dotClass}`}
- aria-hidden="true"
- />
<span className="truncate leading-none decoration-[var(--muted-foreground)]/40 decoration-dotted underline-offset-[3px] group-hover/ver:underline">
- {displayTag ?? "—"}
+ {displayTag}
</span>
</a>
);
diff --git a/web/components/sidebar/WorkspaceSidebar.tsx b/web/components/sidebar/WorkspaceSidebar.tsx
index d61f913c2..5d254dc14 100644
--- a/web/components/sidebar/WorkspaceSidebar.tsx
+++ b/web/components/sidebar/WorkspaceSidebar.tsx
@@ -1,7 +1,7 @@
"use client";
-import { useCallback, useEffect, useRef, useState } from "react";
-import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { usePathname, useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import { SidebarShell } from "@/components/sidebar/SidebarShell";
import { LogoutButton } from "@/components/auth/LogoutButton";
@@ -13,10 +13,13 @@ import {
updateSessionTitle,
type SessionSummary,
} from "@/lib/session-api";
+import { surfaceForPath } from "@/lib/session-surfaces";
export default function WorkspaceSidebar() {
const { t } = useTranslation();
const router = useRouter();
+ const pathname = usePathname();
+ const surface = useMemo(() => surfaceForPath(pathname), [pathname]);
const {
newSession,
selectedSessionId,
@@ -32,18 +35,23 @@ export default function WorkspaceSidebar() {
setLoadingSessions(true);
}
try {
- setSessions(await listSessions(50, 0, { force: true }));
+ setSessions(
+ await listSessions(50, 0, { force: true, kind: surface.kind }),
+ );
hasLoadedSessionsRef.current = true;
} catch (error) {
console.error("Failed to load sessions", error);
} finally {
setLoadingSessions(false);
}
- }, []);
+ }, [surface.kind]);
+ // Re-load when the user navigates between /chat and /co-learn so the
+ // sidebar only ever shows sessions for the active surface.
useEffect(() => {
+ hasLoadedSessionsRef.current = false;
void refreshSessions();
- }, [refreshSessions, sidebarRefreshToken]);
+ }, [refreshSessions, sidebarRefreshToken, surface.kind]);
const orderedSessions = sessions
.map((session, index) => {
@@ -69,14 +77,14 @@ export default function WorkspaceSidebar() {
const handleNewChat = () => {
newSession();
- router.push("/chat");
+ router.push(surface.basePath);
};
const handleSelectSession = useCallback(
async (sessionId: string) => {
- router.push(`/chat/${sessionId}`);
+ router.push(`${surface.basePath}/${sessionId}`);
},
- [router],
+ [router, surface.basePath],
);
const handleRenameSession = useCallback(
@@ -106,10 +114,10 @@ export default function WorkspaceSidebar() {
);
if (selectedSessionId === sessionId) {
newSession();
- router.push("/chat");
+ router.push(surface.basePath);
}
},
- [newSession, router, selectedSessionId, t],
+ [newSession, router, selectedSessionId, surface.basePath, t],
);
return (
diff --git a/web/components/space/ChatHistorySection.tsx b/web/components/space/ChatHistorySection.tsx
index ce8f882f4..52af6d287 100644
--- a/web/components/space/ChatHistorySection.tsx
+++ b/web/components/space/ChatHistorySection.tsx
@@ -2,7 +2,13 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
-import { History, Loader2, RefreshCw, Search } from "lucide-react";
+import {
+ History,
+ Loader2,
+ RefreshCw,
+ Search,
+ type LucideIcon,
+} from "lucide-react";
import { useTranslation } from "react-i18next";
import SessionList from "@/components/SessionList";
import SpaceSectionHeader from "@/components/space/SpaceSectionHeader";
@@ -13,8 +19,29 @@ import {
updateSessionTitle,
type SessionSummary,
} from "@/lib/session-api";
+import { SURFACES, type SurfaceKind } from "@/lib/session-surfaces";
+
+/**
+ * Sessions list filtered by ``kind``. ``/space/chat-history`` renders this
+ * with the default ``"chat"`` filter; ``/space/co-learn-history`` mounts
+ * another instance with ``kind="co_learn"``. The route prefix used to reopen
+ * a session is derived from ``kind`` via ``SURFACES`` — callers no longer
+ * have to keep ``kind`` and ``basePath`` in sync by hand.
+ */
+export interface ChatHistorySectionProps {
+ kind?: SurfaceKind;
+ icon?: LucideIcon;
+ title?: string;
+ description?: string;
+}
-export default function ChatHistorySection() {
+export default function ChatHistorySection({
+ kind = "chat",
+ icon,
+ title,
+ description,
+}: ChatHistorySectionProps = {}) {
+ const basePath = SURFACES[kind].basePath;
const { t } = useTranslation();
const router = useRouter();
const { activeSessionId, setActiveSessionId } = useAppShell();
@@ -22,14 +49,17 @@ export default function ChatHistorySection() {
const [loading, setLoading] = useState(true);
const [query, setQuery] = useState("");
- const load = useCallback(async (force = false) => {
- setLoading(true);
- try {
- setSessions(await listSessions(200, 0, { force }));
- } finally {
- setLoading(false);
- }
- }, []);
+ const load = useCallback(
+ async (force = false) => {
+ setLoading(true);
+ try {
+ setSessions(await listSessions(200, 0, { force, kind }));
+ } finally {
+ setLoading(false);
+ }
+ },
+ [kind],
+ );
useEffect(() => {
void load(true);
@@ -48,9 +78,9 @@ export default function ChatHistorySection() {
const handleSelect = useCallback(
(sessionId: string) => {
setActiveSessionId(sessionId);
- router.push(`/chat/${sessionId}`);
+ router.push(`${basePath}/${sessionId}`);
},
- [router, setActiveSessionId],
+ [basePath, router, setActiveSessionId],
);
const handleRename = useCallback(
@@ -73,14 +103,20 @@ export default function ChatHistorySection() {
[activeSessionId, setActiveSessionId, t],
);
+ const HeaderIcon = icon ?? History;
+ const headerTitle = title ?? t("Chat History");
+ const headerDescription =
+ description ??
+ t(
+ "Browse, rename, delete, and reopen previous conversations from your learning space.",
+ );
+
return (
<div className="space-y-6">
<SpaceSectionHeader
- icon={History}
- title={t("Chat History")}
- description={t(
- "Browse, rename, delete, and reopen previous conversations from your learning space.",
- )}
+ icon={HeaderIcon}
+ title={headerTitle}
+ description={headerDescription}
meta={
<span className="rounded-full border border-[var(--border)] bg-[var(--card)] px-2 py-0.5 text-[10.5px] font-medium text-[var(--muted-foreground)]">
{sessions.length} {t("conversations")}
diff --git a/web/components/visualize/VisualizeConfigPanel.tsx b/web/components/visualize/VisualizeConfigPanel.tsx
index 6e890606e..12574d741 100644
--- a/web/components/visualize/VisualizeConfigPanel.tsx
+++ b/web/components/visualize/VisualizeConfigPanel.tsx
@@ -15,8 +15,12 @@ import {
interface VisualizeConfigPanelProps {
value: VisualizeFormConfig;
onChange: (next: VisualizeFormConfig) => void;
- collapsed: boolean;
- onToggleCollapsed: () => void;
+ /**
+ * When provided, the panel is wrapped in a `CollapsibleConfigSection`.
+ * Omit both to render bare for the chat Activity panel.
+ */
+ collapsed?: boolean;
+ onToggleCollapsed?: () => void;
}
export default memo(function VisualizeConfigPanel({
@@ -27,31 +31,43 @@ export default memo(function VisualizeConfigPanel({
}: VisualizeConfigPanelProps) {
const { t } = useTranslation();
+ const body = (
+ <Field label={t("Render Mode")} width="w-[120px]">
+ <select
+ value={value.render_mode}
+ onChange={(e) =>
+ onChange({
+ ...value,
+ render_mode: e.target.value as VisualizeFormConfig["render_mode"],
+ })
+ }
+ className={`${INPUT_CLS} w-full`}
+ >
+ <option value="auto">{t("Auto")}</option>
+ <option value="chartjs">{t("Chart.js")}</option>
+ <option value="svg">{t("SVG")}</option>
+ <option value="mermaid">{t("Mermaid")}</option>
+ <option value="html">{t("HTML")}</option>
+ </select>
+ </Field>
+ );
+
+ if (collapsed === undefined) {
+ return (
+ <div className="flex flex-wrap items-end gap-x-3 gap-y-2 px-3.5 py-2.5">
+ {body}
+ </div>
+ );
+ }
+
return (
<CollapsibleConfigSection
collapsed={collapsed}
summary={summarizeVisualizeConfig(value, t)}
- onToggleCollapsed={onToggleCollapsed}
+ onToggleCollapsed={onToggleCollapsed ?? (() => undefined)}
bodyClassName="flex flex-wrap items-end gap-x-3 gap-y-2 px-3.5 pb-2.5"
>
- <Field label={t("Render Mode")} width="w-[120px]">
- <select
- value={value.render_mode}
- onChange={(e) =>
- onChange({
- ...value,
- render_mode: e.target.value as VisualizeFormConfig["render_mode"],
- })
- }
- className={`${INPUT_CLS} w-full`}
- >
- <option value="auto">{t("Auto")}</option>
- <option value="chartjs">{t("Chart.js")}</option>
- <option value="svg">{t("SVG")}</option>
- <option value="mermaid">{t("Mermaid")}</option>
- <option value="html">{t("HTML")}</option>
- </select>
- </Field>
+ {body}
</CollapsibleConfigSection>
);
});
diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsx
index 4de77e30e..cb5ad05d4 100644
--- a/web/context/UnifiedChatContext.tsx
+++ b/web/context/UnifiedChatContext.tsx
@@ -60,6 +60,11 @@ export interface SendMessageOptions {
persistUserMessage?: boolean;
requestSnapshotOverride?: MessageRequestSnapshot;
bookReferences?: BookReferencePayload[];
+ // 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
+ // routing surface doesn't leak into /chat's history.
+ kind?: import("@/lib/unified-ws").SessionKind;
}
export interface ChatState {
@@ -1028,15 +1033,6 @@ export function UnifiedChatProvider({
: session.llmSelection;
const effectiveLanguage =
replaySnapshot?.language ?? readStoredLanguage();
- const researchSources = Array.isArray(config?.sources)
- ? config.sources.filter(
- (value): value is string => typeof value === "string",
- )
- : [];
- const shouldSendKnowledgeBases =
- effectiveTools.includes("rag") ||
- (effectiveCapability === "deep_research" &&
- researchSources.includes("kb"));
const effectiveSkills = replaySnapshot?.skills ?? skills;
const effectiveMemoryReferences =
replaySnapshot?.memoryReferences ?? memoryReferences;
@@ -1046,9 +1042,7 @@ export function UnifiedChatProvider({
content,
capability: effectiveCapability,
enabledTools: [...effectiveTools],
- knowledgeBases: shouldSendKnowledgeBases
- ? [...effectiveKnowledgeBases]
- : [],
+ knowledgeBases: [...effectiveKnowledgeBases],
language: effectiveLanguage,
...(msgAttachments?.length ? { attachments: msgAttachments } : {}),
...(config && Object.keys(config).length > 0 ? { config } : {}),
@@ -1090,10 +1084,9 @@ export function UnifiedChatProvider({
content,
tools: effectiveTools,
capability: effectiveCapability,
- knowledge_bases: shouldSendKnowledgeBases
- ? effectiveKnowledgeBases
- : [],
+ knowledge_bases: effectiveKnowledgeBases,
session_id: session.sessionId,
+ ...(options?.kind ? { kind: options.kind } : {}),
attachments,
language: effectiveLanguage,
...(notebookReferences?.length
diff --git a/web/lib/session-api.ts b/web/lib/session-api.ts
index dc1916f5f..8c4f7bc3c 100644
--- a/web/lib/session-api.ts
+++ b/web/lib/session-api.ts
@@ -1,6 +1,7 @@
-import type { LLMSelection, StreamEvent } from "@/lib/unified-ws";
import { apiUrl } from "@/lib/api";
import { invalidateClientCache, withClientCache } from "@/lib/client-cache";
+import type { SurfaceKind } from "@/lib/session-surfaces";
+import type { LLMSelection, StreamEvent } from "@/lib/unified-ws";
export interface SessionMessage {
id: number;
@@ -38,6 +39,8 @@ export interface SessionSummary {
| "cancelled"
| "rejected";
active_turn_id?: string;
+ /** Originating surface — see ``SurfaceKind`` in lib/session-surfaces. */
+ kind?: SurfaceKind;
preferences?: {
capability?: string;
tools?: string[];
@@ -114,13 +117,21 @@ async function expectJson<T>(response: Response): Promise<T> {
export async function listSessions(
limit = 50,
offset = 0,
- options?: { force?: boolean },
+ options?: { force?: boolean; kind?: SurfaceKind | null },
): Promise<SessionSummary[]> {
+ const kindKey = options?.kind ?? "all";
+ const qs = new URLSearchParams({
+ limit: String(limit),
+ offset: String(offset),
+ });
+ if (options?.kind) {
+ qs.set("kind", options.kind);
+ }
return withClientCache<SessionSummary[]>(
- `sessions:${limit}:${offset}`,
+ `sessions:${kindKey}:${limit}:${offset}`,
async () => {
const response = await fetch(
- apiUrl(`/api/v1/sessions?limit=${limit}&offset=${offset}`),
+ apiUrl(`/api/v1/sessions?${qs.toString()}`),
{
cache: "no-store",
credentials: "include",
diff --git a/web/lib/session-surfaces.ts b/web/lib/session-surfaces.ts
new file mode 100644
index 000000000..5ea33657d
--- /dev/null
+++ b/web/lib/session-surfaces.ts
@@ -0,0 +1,55 @@
+/**
+ * Single source of truth for "what surface am I on?"
+ *
+ * The product has two top-level surfaces whose chat history must stay
+ * isolated:
+ *
+ * • ``chat`` — manual capability picker (``/chat``, ``/space/chat-history``)
+ * • ``co_learn`` — auto router (``/co-learn``, ``/space/co-learn-history``)
+ *
+ * The backend tags each session row with the surface that created it;
+ * the frontend filters by surface in every sidebar and history page.
+ * If a third surface is ever added, edit this file ONLY — every sidebar
+ * derives from ``surfaceForPath``.
+ */
+
+export type SurfaceKind = "chat" | "co_learn";
+
+export interface Surface {
+ readonly kind: SurfaceKind;
+ /** Route prefix used to build session URLs and "new chat" buttons. */
+ readonly basePath: "/chat" | "/co-learn";
+}
+
+const CHAT: Surface = { kind: "chat", basePath: "/chat" };
+const CO_LEARN: Surface = { kind: "co_learn", basePath: "/co-learn" };
+
+// Path *prefixes* (exact match OR followed by ``/``) that map to each
+// surface. ``startsWith(prefix)`` alone would over-match (e.g. ``/co-learn``
+// would swallow a hypothetical ``/co-learn-archive``), so we enforce a
+// path-segment boundary instead.
+const PREFIXES: ReadonlyArray<readonly [Surface, readonly string[]]> = [
+ [CO_LEARN, ["/co-learn", "/space/co-learn-history"]],
+ [CHAT, ["/chat", "/space/chat-history"]],
+];
+
+function pathMatches(pathname: string, prefix: string): boolean {
+ return pathname === prefix || pathname.startsWith(`${prefix}/`);
+}
+
+/**
+ * Return the surface owning ``pathname``. Falls back to ``chat`` for any
+ * route that doesn't explicitly belong elsewhere (knowledge, settings, …) —
+ * the chat surface is the safe default since it's the legacy/manual mode.
+ */
+export function surfaceForPath(
+ pathname: string | null | undefined,
+): Surface {
+ if (!pathname) return CHAT;
+ for (const [surface, prefixes] of PREFIXES) {
+ if (prefixes.some((p) => pathMatches(pathname, p))) return surface;
+ }
+ return CHAT;
+}
+
+export const SURFACES = { chat: CHAT, co_learn: CO_LEARN } as const;
diff --git a/web/lib/space-items.ts b/web/lib/space-items.ts
index af43957d9..fc0297329 100644
--- a/web/lib/space-items.ts
+++ b/web/lib/space-items.ts
@@ -5,12 +5,14 @@ import {
ClipboardList,
History,
NotebookPen,
+ Sparkles,
Wand2,
type LucideIcon,
} from "lucide-react";
export type SpaceItemKey =
| "chat_history"
+ | "co_learn_history"
| "notebooks"
| "question_bank"
| "skills"
@@ -34,6 +36,13 @@ export const SPACE_ITEMS: SpaceItem[] = [
description: "Review and reopen previous conversations.",
icon: History,
},
+ {
+ key: "co_learn_history",
+ href: "/space/co-learn-history",
+ label: "Co-Learn History",
+ description: "Browse past auto-routed Co-Learn sessions.",
+ icon: Sparkles,
+ },
{
key: "notebooks",
href: "/space/notebooks",
diff --git a/web/lib/unified-ws.ts b/web/lib/unified-ws.ts
index 8c2c4d28e..3be8bd4b9 100644
--- a/web/lib/unified-ws.ts
+++ b/web/lib/unified-ws.ts
@@ -11,6 +11,7 @@
*/
import { wsUrl } from "./api";
+import type { SurfaceKind } from "./session-surfaces";
// ---- StreamEvent types (mirror Python StreamEventType) ----
@@ -48,6 +49,14 @@ export interface LLMSelection {
// ---- Client message ----
+/**
+ * Surface that originated the turn. Alias of ``SurfaceKind`` from
+ * ``lib/session-surfaces`` so the two values never drift. The backend tags
+ * the underlying session with this value so the /chat and /co-learn surfaces
+ * never list each other's history. Defaults to ``"chat"`` when omitted.
+ */
+export type SessionKind = SurfaceKind;
+
export interface StartTurnMessage {
type: "message" | "start_turn";
content: string;
@@ -55,6 +64,7 @@ export interface StartTurnMessage {
capability?: string | null;
knowledge_bases?: string[];
session_id?: string | null;
+ kind?: SessionKind;
attachments?: {
type: string;
url?: string;
@@ -182,6 +192,13 @@ export class UnifiedWSClient {
this.lastReceivedAt = Date.now();
try {
const event: StreamEvent = JSON.parse(ev.data);
+ // Heartbeat frames (client-sent ``ping`` echoed by some legacy
+ // backends, or ``pong`` from the modern handler) keep the socket
+ // alive but are not user-visible chat events. They MUST be dropped
+ // here — otherwise the message list renders them as "Unknown type"
+ // error rows, especially during long-running turns.
+ const type = (event as { type?: string }).type;
+ if (type === "ping" || type === "pong") return;
if (event.turn_id) this.activeTurnId = event.turn_id;
if (event.seq != null) this.lastSeq = Math.max(this.lastSeq, event.seq);
this.onEvent(event);
diff --git a/web/lib/version.ts b/web/lib/version.ts
index 17b657b2b..8fce7bbd5 100644
--- a/web/lib/version.ts
+++ b/web/lib/version.ts
@@ -1,93 +1,16 @@
-export type VersionSource = "git" | "env" | "unknown";
-
-export interface ParsedBuild {
- /** Clean base tag if the version can be traced to a semver tag. */
- tag: string | null;
- /** True when commits exist after the tag, the tree is dirty, or no tag exists. */
- isDev: boolean;
- /** True when git reported a dirty worktree. */
- isDirty: boolean;
- /** Human-readable display, e.g. "v1.2.3" or "v1.2.3+5". */
- display: string;
- /** Original version string before parsing. */
- raw: string;
- /** Number of commits after the base tag, when available. */
- commitsAhead: number | null;
- /** Short git commit hash, when available. */
- commit: string | null;
-}
-
-const SEMVER_TAG = String.raw`(\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?)`;
-const DIRTY_SUFFIX = "-dev";
-const DIRTY_DISPLAY = "\u00b7dev";
-
-export function parseBuild(
- rawValue: string | null | undefined,
-): ParsedBuild | null {
- const raw = rawValue?.trim() ?? "";
- if (!raw) return null;
-
- const isDirty = raw.endsWith(DIRTY_SUFFIX);
- const stripped = isDirty ? raw.slice(0, -DIRTY_SUFFIX.length) : raw;
-
- const ahead = stripped.match(
- new RegExp(`^v?${SEMVER_TAG}-(\\d+)-g([0-9a-f]+)$`),
- );
- if (ahead) {
- const tag = `v${ahead[1]}`;
- const commitsAhead = Number.parseInt(ahead[2], 10);
- const commit = ahead[3];
- return {
- tag,
- isDev: true,
- isDirty,
- display: `${tag}+${commitsAhead}${isDirty ? DIRTY_DISPLAY : ""}`,
- raw,
- commitsAhead,
- commit,
- };
- }
-
- const cleanTag = stripped.match(new RegExp(`^v?${SEMVER_TAG}$`));
- if (cleanTag) {
- const tag = `v${cleanTag[1]}`;
- return {
- tag,
- isDev: isDirty,
- isDirty,
- display: isDirty ? `${tag}${DIRTY_DISPLAY}` : tag,
- raw,
- commitsAhead: null,
- commit: null,
- };
- }
-
- return {
- tag: null,
- isDev: true,
- isDirty,
- display: "dev",
- raw,
- commitsAhead: null,
- commit: null,
- };
-}
-
+/** Normalize a version string into a ``vMAJOR.MINOR.PATCH`` tag form.
+ *
+ * Accepts PEP 440 / semver forms used in ``deeptutor/__version__.py`` and
+ * GitHub release tags (``1.4.0``, ``v1.4.0``, ``1.4.0rc1``, ``v1.0.0-beta.4``)
+ * while rejecting git-describe output like ``v1.2.3-5-gabc1234``.
+ */
export function normalizeVersionTag(
raw: string | null | undefined,
): string | null {
- const parsed = parseBuild(raw);
- return parsed && !parsed.isDev ? parsed.tag : null;
-}
-
-export function unknownBuild(raw = ""): ParsedBuild {
- return {
- tag: null,
- isDev: true,
- isDirty: false,
- display: raw.trim() || "unknown",
- raw: raw.trim(),
- commitsAhead: null,
- commit: null,
- };
+ const value = raw?.trim();
+ if (!value) return null;
+ const match = value.match(
+ /^v?(\d+\.\d+\.\d+(?:(?:rc|a|b)\d+|\.dev\d+|\.post\d+|-[A-Za-z][0-9A-Za-z.-]*)?)$/,
+ );
+ return match ? `v${match[1]}` : null;
}
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 1c3693720..2873eb370 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -1603,5 +1603,14 @@
"Co-Writer tooltip": "AI-powered document editor.",
"Book tooltip": "Create AI-powered books.",
"Knowledge tooltip": "Manage learning personas.",
- "Space tooltip": "Your personal learning library."
+ "Space tooltip": "Your personal learning library.",
+ "Quiz settings": "Quiz settings",
+ "Animator settings": "Animator settings",
+ "Visualize settings": "Visualize settings",
+ "Research settings": "Research settings",
+ "Confirm": "Confirm",
+ "Confirmed": "Confirmed",
+ "Edit any field to update settings.": "Edit any field to update settings.",
+ "Confirm settings to enable sending.": "Confirm settings to enable sending.",
+ "Confirm settings on the right to send.": "Confirm settings on the right to send."
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 7a1466cfd..3a2d61984 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -1603,5 +1603,14 @@
"Co-Writer tooltip": "AI 驱动的协作文档编辑器。",
"Book tooltip": "生成交互式 AI 书籍。",
"Knowledge tooltip": "管理文档与教学人设。",
- "Space tooltip": "你的个人学习空间。"
+ "Space tooltip": "你的个人学习空间。",
+ "Quiz settings": "测验设置",
+ "Animator settings": "动画设置",
+ "Visualize settings": "可视化设置",
+ "Research settings": "研究设置",
+ "Confirm": "确定",
+ "Confirmed": "已确认",
+ "Edit any field to update settings.": "修改任意字段即可更新设置。",
+ "Confirm settings to enable sending.": "确认设置后即可发送。",
+ "Confirm settings on the right to send.": "请先在右侧确认设置后再发送。"
}
diff --git a/web/next.config.js b/web/next.config.js
index 639d01b14..503087946 100644
--- a/web/next.config.js
+++ b/web/next.config.js
@@ -60,23 +60,19 @@ const NEXT_PUBLIC_AUTH_ENABLED = normalizeBoolean(
process.env.NEXT_PUBLIC_API_BASE = NEXT_PUBLIC_API_BASE;
process.env.NEXT_PUBLIC_AUTH_ENABLED = NEXT_PUBLIC_AUTH_ENABLED;
-// Resolve the build-time application version. Priority:
-// 1. Explicit APP_VERSION env (set by CI from the release tag)
-// 2. `git describe --tags` when building from a checkout (local dev)
-// 3. Empty string → frontend treats it as "unknown" and shows the
-// latest GitHub release as a neutral fallback.
+// Resolve the build-time application version from the single source of
+// truth at ``deeptutor/__version__.py``. The Python file is parsed with a
+// small regex so the JS build does not need to execute Python.
const APP_VERSION = (() => {
- if (process.env.APP_VERSION) return process.env.APP_VERSION;
try {
- const { execSync } = require("child_process");
- return execSync("git describe --tags --always --dirty=-dev", {
- stdio: ["ignore", "pipe", "ignore"],
- })
- .toString()
- .trim();
- } catch {
- return "";
- }
+ const text = fs.readFileSync(
+ path.resolve(__dirname, "..", "deeptutor", "__version__.py"),
+ "utf8",
+ );
+ const match = text.match(/__version__\s*=\s*["']([^"']+)["']/);
+ if (match) return match[1];
+ } catch {}
+ return "";
})();
const nextConfig = {
diff --git a/web/tests/version.test.ts b/web/tests/version.test.ts
index f85bb7894..30a0aa40d 100644
--- a/web/tests/version.test.ts
+++ b/web/tests/version.test.ts
@@ -1,65 +1,23 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { normalizeVersionTag, parseBuild, unknownBuild } from "../lib/version";
+import { normalizeVersionTag } from "../lib/version";
-test("parseBuild normalizes clean release tags", () => {
- assert.deepEqual(parseBuild("1.2.3"), {
- tag: "v1.2.3",
- isDev: false,
- isDirty: false,
- display: "v1.2.3",
- raw: "1.2.3",
- commitsAhead: null,
- commit: null,
- });
+test("normalizeVersionTag accepts bare semver", () => {
+ assert.equal(normalizeVersionTag("1.4.0"), "v1.4.0");
});
-test("parseBuild handles commits ahead of a release tag", () => {
- assert.deepEqual(parseBuild("v1.2.3-5-gabc1234"), {
- tag: "v1.2.3",
- isDev: true,
- isDirty: false,
- display: "v1.2.3+5",
- raw: "v1.2.3-5-gabc1234",
- commitsAhead: 5,
- commit: "abc1234",
- });
+test("normalizeVersionTag keeps the v prefix", () => {
+ assert.equal(normalizeVersionTag("v1.4.0"), "v1.4.0");
});
-test("parseBuild preserves dirty worktree state", () => {
- assert.deepEqual(parseBuild("v1.2.3-5-gabc1234-dev"), {
- tag: "v1.2.3",
- isDev: true,
- isDirty: true,
- display: "v1.2.3+5\u00b7dev",
- raw: "v1.2.3-5-gabc1234-dev",
- commitsAhead: 5,
- commit: "abc1234",
- });
+test("normalizeVersionTag supports PEP 440-style pre-releases", () => {
+ assert.equal(normalizeVersionTag("v1.0.0-beta.4"), "v1.0.0-beta.4");
+ assert.equal(normalizeVersionTag("1.0.0rc1"), "v1.0.0rc1");
});
-test("parseBuild supports prerelease tags", () => {
- assert.equal(parseBuild("v1.0.0-beta.4")?.tag, "v1.0.0-beta.4");
- assert.equal(
- parseBuild("v1.0.0-beta.4-2-gabc1234")?.display,
- "v1.0.0-beta.4+2",
- );
-});
-
-test("normalizeVersionTag only returns exact version tags", () => {
- assert.equal(normalizeVersionTag("1.2.3"), "v1.2.3");
- assert.equal(normalizeVersionTag("v1.2.3-dev"), null);
+test("normalizeVersionTag rejects unparseable inputs", () => {
+ assert.equal(normalizeVersionTag(""), null);
+ assert.equal(normalizeVersionTag(undefined), null);
+ assert.equal(normalizeVersionTag("abc1234"), null);
assert.equal(normalizeVersionTag("v1.2.3-5-gabc1234"), null);
});
-
-test("unknownBuild keeps an unknown raw version visible", () => {
- assert.deepEqual(unknownBuild("abc1234"), {
- tag: null,
- isDev: true,
- isDirty: false,
- display: "abc1234",
- raw: "abc1234",
- commitsAhead: null,
- commit: null,
- });
-});